diff --git a/.github/scripts/smoke_nifi_login.sh b/.github/scripts/smoke_nifi_login.sh new file mode 100644 index 00000000..4ea4f303 --- /dev/null +++ b/.github/scripts/smoke_nifi_login.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail + +api="${1%/}/nifi-api" +request=(curl -fsS --noproxy '*' --cacert "$SECURITY_DIR/certificates/root/root-ca.pem" --max-time 10) +token=$("${request[@]}" --retry 30 --retry-all-errors --retry-delay 10 --retry-max-time 300 \ + --data-urlencode "username=$SINGLE_USER_CREDENTIALS_USERNAME" \ + --data-urlencode "password=$SINGLE_USER_CREDENTIALS_PASSWORD" "$api/access/token") +[[ -n "$token" ]] +"${request[@]}" --header "Authorization: Bearer $token" "$api/flow/current-user" | + jq -e --arg user "$SINGLE_USER_CREDENTIALS_USERNAME" '.identity == $user and .anonymous == false' diff --git a/.github/workflows/build_helm_charts.yml b/.github/workflows/build_helm_charts.yml index 2b515fb9..f165e5e5 100644 --- a/.github/workflows/build_helm_charts.yml +++ b/.github/workflows/build_helm_charts.yml @@ -21,10 +21,12 @@ on: - "helm-charts/*-v*.*.*" # e.g., helm-charts/medcat-trainer-helm-v0.1.2 paths: - "deployment/charts/**" + - "apps/opensearch/config/opensearch.yml" - ".github/workflows/build_helm_charts.yml" pull_request: paths: - "deployment/charts/**" + - "apps/opensearch/config/opensearch.yml" - ".github/workflows/build_helm_charts.yml" defaults: diff --git a/.github/workflows/docker_smoke_nifi.yml b/.github/workflows/docker_smoke_nifi.yml new file mode 100644 index 00000000..e4ec7f09 --- /dev/null +++ b/.github/workflows/docker_smoke_nifi.yml @@ -0,0 +1,89 @@ +name: docker_smoke_nifi + +on: + push: + branches: ['**'] + paths: &paths + - 'apps/nifi/**' + - 'apps/nginx/**' + - 'deployment/Makefile' + - 'deployment/make/**' + - 'deployment/scripts/security/**' + - 'deployment/security/templates/**' + - '.github/scripts/smoke_nifi_login.sh' + - '.github/workflows/docker_smoke_nifi.yml' + - '!**/*.md' + - '!**/README*' + pull_request: + paths: *paths + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +defaults: + run: + shell: bash + working-directory: apps/nifi/docker + +jobs: + smoke: + name: Smoke-test NiFi services + runs-on: ubuntu-24.04 + timeout-minutes: 45 + env: + COMPOSE_PROJECT_NAME: nifi-smoke-${{ github.run_id }}-${{ github.run_attempt }} + COGSTACK_GENERAL_ENV_FILE: /dev/null + COGSTACK_NIFI_ENV_FILE: /dev/null + NIFI_DOCKER_CPU_MIN: '1' + NIFI_DOCKER_CPU_MAX: '2' + NIFI_DOCKER_RAM: 4g + SINGLE_USER_CREDENTIALS_USERNAME: smoke + + steps: + - uses: actions/checkout@v7 + + - name: Set up Java + uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: '21' + + - name: Start NiFi and verify login + run: | + SECURITY_DIR=$(mktemp -d "$RUNNER_TEMP/nifi-smoke.XXXXXX") + printf 'SECURITY_DIR=%s\n' "$SECURITY_DIR" >> "$GITHUB_ENV" + password="$(openssl rand -hex 16)" + NIFI_SENSITIVE_PROPS_KEY=$(openssl rand -hex 16) + export SECURITY_DIR NIFI_SENSITIVE_PROPS_KEY + export KEYSTORE_PASSWORD="$password" TRUSTSTORE_PASSWORD="$password" SINGLE_USER_CREDENTIALS_PASSWORD="$password" + ROOT_CERTIFICATE_KEYSTORE_PASSWORD="$password" make -C ../../../deployment -j1 certs-root certs-nifi certs-nginx + # The published containers run as UID/GID 1000. + sudo chown 1000:1000 "$SECURITY_DIR"/certificates/{nifi/nifi-keystore.jks,nginx/tls.key} + + docker compose -f docker-compose.yml -f - up -d <<'YAML' + services: + nifi: + environment: + NIFI_HEALTHCHECK_HOST: nifi + NIFI_WEB_PROXY_HOST: 127.0.0.1:8443 + NIFI_SENSITIVE_PROPS_KEY: ${NIFI_SENSITIVE_PROPS_KEY} + YAML + bash ../../../.github/scripts/smoke_nifi_login.sh https://127.0.0.1:8443 + + - name: Dump container logs + if: failure() + run: | + [[ -n "${SECURITY_DIR:-}" ]] || exit 0 + docker compose ps + docker compose logs --no-color nifi nifi-nginx + + - name: Shutdown stack + if: always() + run: | + [[ -n "${SECURITY_DIR:-}" ]] || exit 0 + docker compose down -v diff --git a/.github/workflows/docker_smoke_opensearch.yml b/.github/workflows/docker_smoke_opensearch.yml new file mode 100644 index 00000000..63e03533 --- /dev/null +++ b/.github/workflows/docker_smoke_opensearch.yml @@ -0,0 +1,82 @@ +name: docker_smoke_opensearch + +on: + push: + branches: ['**'] + paths: &paths + - 'apps/opensearch/**' + - 'apps/opensearch-dashboards/**' + - 'deployment/Makefile' + - 'deployment/make/**' + - 'deployment/scripts/security/**' + - 'deployment/security/templates/**' + - '.github/workflows/docker_smoke_opensearch.yml' + pull_request: + paths: *paths + workflow_dispatch: + +permissions: + contents: read + +jobs: + smoke: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + env: + SMOKE_PROJECT_SUFFIX: smoke-${{ github.run_id }}-${{ github.run_attempt }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: '21' + + - name: Start the default stack and verify access + shell: bash + run: | + SECURITY_DIR=$(mktemp -d "$RUNNER_TEMP/opensearch-smoke.XXXXXX") + KIBANA_PASSWORD=$(openssl rand -hex 16) + OS_NIFI_PASSWORD=$(openssl rand -hex 16) + OS_ANALYST_PASSWORD=$(openssl rand -hex 16) + export SECURITY_DIR KIBANA_PASSWORD OS_NIFI_PASSWORD OS_ANALYST_PASSWORD + printf '::add-mask::%s\n' "$KIBANA_PASSWORD" + printf 'SECURITY_DIR=%s\nKIBANA_PASSWORD=%s\n' "$SECURITY_DIR" "$KIBANA_PASSWORD" >> "$GITHUB_ENV" + password=$(openssl rand -hex 16) + export ROOT_CERTIFICATE_KEYSTORE_PASSWORD="$password" OS_CERTIFICATE_PASSWORD="$password" + make -C deployment certs-root certs-opensearch + OPENSEARCH_DASHBOARDS_DNS_NAMES=localhost ./deployment/scripts/security/create_opensearch_client_admin_certs.sh --dashboards-only + certs="$SECURITY_DIR/certificates/opensearch" + sudo chown 1000:1000 "$certs"/{opensearch-shared.key,es_kibana_client.key} + request=(curl -sS --noproxy '*' --cacert "$SECURITY_DIR/certificates/root/root-ca.pem" --max-time 10) + + search=(docker compose -p "opensearch-$SMOKE_PROJECT_SUFFIX" -f apps/opensearch/docker/docker-compose.yml) + "${search[@]}" up -d + bash apps/opensearch/security/bootstrap.sh "${search[@]}" exec -T opensearch + + printf '%s\n' '{"index":{"_id":"smoke"}}' '{"ok":true}' | + "${request[@]}" -f -u "nifi:$OS_NIFI_PASSWORD" -H 'Content-Type: application/x-ndjson' \ + --data-binary @- https://localhost:9200/nifi_smoke/_bulk | jq -e '.errors == false' + "${request[@]}" -f -u "cogstack_user:$OS_ANALYST_PASSWORD" \ + https://localhost:9200/nifi_smoke/_doc/smoke | jq -e '._source.ok == true' + status=$("${request[@]}" -u "cogstack_user:$OS_ANALYST_PASSWORD" -o /dev/null -w '%{http_code}' \ + -X PUT --json '{"ok":false}' https://localhost:9200/nifi_smoke/_doc/smoke) + [[ "$status" == 403 ]] + + docker compose -p "opensearch-dashboards-$SMOKE_PROJECT_SUFFIX" -f apps/opensearch-dashboards/docker/docker-compose.yml up -d + "${request[@]}" -f --retry 30 --retry-all-errors --retry-delay 3 -H 'osd-xsrf: smoke' \ + --json "{\"username\":\"cogstack_user\",\"password\":\"$OS_ANALYST_PASSWORD\"}" \ + https://localhost:5601/auth/login | jq -e '.username == "cogstack_user"' + + - name: Cleanup + if: always() + env: + SMOKE_JOB_STATUS: ${{ job.status }} + run: | + [[ -n "${SECURITY_DIR:-}" ]] || exit 0 + for app in opensearch-dashboards opensearch; do + compose=(docker compose -p "$app-$SMOKE_PROJECT_SUFFIX" -f "apps/$app/docker/docker-compose.yml") + if [[ "$SMOKE_JOB_STATUS" == failure ]]; then + "${compose[@]}" logs --tail 50 || true + fi + "${compose[@]}" down -v + done diff --git a/.github/workflows/helm_smoke_logins.yml b/.github/workflows/helm_smoke_logins.yml new file mode 100644 index 00000000..f443cad4 --- /dev/null +++ b/.github/workflows/helm_smoke_logins.yml @@ -0,0 +1,132 @@ +name: helm_smoke_logins + +on: + push: + branches: ['**'] + paths: &paths + - 'deployment/charts/nifi/**' + - 'deployment/charts/nginx/**' + - 'deployment/charts/opensearch/**' + - 'deployment/charts/opensearch-dashboards/**' + - 'deployment/Makefile' + - 'deployment/make/**' + - 'deployment/env/authentication.env' + - 'deployment/env/certificates.env' + - 'deployment/env/general.env' + - 'deployment/scripts/security/**' + - 'deployment/security/templates/**' + - 'apps/opensearch/**' + - '.github/workflows/helm_smoke_logins.yml' + pull_request: + paths: *paths + workflow_dispatch: + workflow_call: + inputs: + stacks: + type: string + required: true + +permissions: + contents: read + +defaults: + run: + shell: bash + +jobs: + smoke: + name: Helm smoke (${{ matrix.stack }}) + runs-on: ubuntu-24.04 + timeout-minutes: 35 + strategy: + fail-fast: false + matrix: + stack: ${{ fromJSON(inputs.stacks || '["nifi","opensearch"]') }} + env: + SINGLE_USER_CREDENTIALS_USERNAME: smoke + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: '21' + - uses: azure/setup-helm@v5.1.0 + with: + version: v3.17.0 + - uses: helm/kind-action@v1.15.2 + + - name: Generate and load certificates + env: + STACK: ${{ matrix.stack }} + run: | + source deployment/env/general.env + SECURITY_DIR=$(mktemp -d "$RUNNER_TEMP/helm-smoke.XXXXXX") + password=$(openssl rand -hex 16) + printf '::add-mask::%s\n' "$password" + printf 'SECURITY_DIR=%s\nSMOKE_PASSWORD=%s\n' "$SECURITY_DIR" "$password" >> "$GITHUB_ENV" + export SECURITY_DIR ROOT_CERTIFICATE_KEYSTORE_PASSWORD="$password" OS_CERTIFICATE_PASSWORD="$password" + make -C deployment -j1 setup-k3s-namespace certs-root certs-nginx k3s-load-certs-nginx + if [[ "$STACK" == opensearch ]]; then + make -C deployment -j1 certs-opensearch-nodes k3s-load-certs-opensearch NODES=opensearch-shared + fi + kubectl config set-context --current --namespace="$KUBE_NAMESPACE" + + - name: Install NiFi + if: matrix.stack == 'nifi' || matrix.stack == 'nginx' + run: | + NIFI_SINGLE_USER_CREDENTIALS_USERNAME="$SINGLE_USER_CREDENTIALS_USERNAME" \ + NIFI_SINGLE_USER_CREDENTIALS_PASSWORD="$SMOKE_PASSWORD" \ + NIFI_SENSITIVE_PROPS_KEY="$(openssl rand -hex 16)" \ + make -C deployment k3s-load-auth-nifi + make -C deployment helm-install-nifi HELM_TIMEOUT=15m + + - name: Install OpenSearch and Dashboards + if: matrix.stack == 'opensearch' + run: | + command -v htpasswd >/dev/null || sudo apt-get install -y apache2-utils + sudo sysctl -w vm.max_map_count=262144 + OPENSEARCH_KIBANA_PASSWORD="$SMOKE_PASSWORD" OPENSEARCH_ANALYST_PASSWORD="$SMOKE_PASSWORD" \ + make -C deployment helm-install-opensearch-stack + + - name: Install NGINX + run: | + make -C deployment helm-install-nginx HELM_VALUES=- HELM_TIMEOUT=5m <<'YAML' + service: + type: ClusterIP + YAML + + - name: NGINX Helm proxy login + if: matrix.stack == 'nifi' || matrix.stack == 'nginx' + run: | + kubectl port-forward svc/cogstack-nginx 8443:443 & + trap 'kill "$!"' EXIT + request=(curl -sS --noproxy '*' --cacert "$SECURITY_DIR/certificates/root/root-ca.pem" + --retry 12 --retry-all-errors --retry-delay 2 --max-time 10) + api=https://127.0.0.1:8443/nifi-api/flow/current-user + [[ $("${request[@]}" -o /dev/null -w '%{http_code}' "$api") == 401 ]] + "${request[@]}" -f -u "$SINGLE_USER_CREDENTIALS_USERNAME:$SMOKE_PASSWORD" "$api" | + jq -e '.anonymous == true' + + - name: OpenSearch and Dashboards through NGINX + if: matrix.stack == 'opensearch' + run: | + kubectl port-forward svc/cogstack-nginx 8443:443 & + trap 'kill "$!"' EXIT + request=(curl -sS --noproxy '*' --cacert "$SECURITY_DIR/certificates/root/root-ca.pem" + --retry 30 --retry-all-errors --retry-delay 3 --max-time 10) + "${request[@]}" -f -u "cogstack_user:$SMOKE_PASSWORD" \ + https://127.0.0.1:8443/opensearch/_plugins/_security/authinfo | + jq -e '.user_name == "cogstack_user"' + headers=$(mktemp) + "${request[@]}" -f -D "$headers" -H 'osd-xsrf: smoke' \ + --json "{\"username\":\"cogstack_user\",\"password\":\"$SMOKE_PASSWORD\"}" \ + https://127.0.0.1:8443/dashboards/auth/login | jq -e '.username == "cogstack_user"' + grep -qi '^set-cookie: .*; secure' "$headers" + + - name: Show pod logs on failure + if: failure() + run: | + kubectl get pods,svc,pvc + for pod in $(kubectl get pods -o name); do + kubectl logs "$pod" --all-containers --tail=100 || true + done diff --git a/.github/workflows/helm_smoke_nginx.yml b/.github/workflows/helm_smoke_nginx.yml new file mode 100644 index 00000000..39fd5f69 --- /dev/null +++ b/.github/workflows/helm_smoke_nginx.yml @@ -0,0 +1,12 @@ +name: helm_smoke_nginx + +on: workflow_dispatch + +permissions: + contents: read + +jobs: + smoke: + uses: ./.github/workflows/helm_smoke_logins.yml + with: + stacks: '["nginx"]' diff --git a/.github/workflows/helm_smoke_opensearch.yml b/.github/workflows/helm_smoke_opensearch.yml new file mode 100644 index 00000000..93e28f87 --- /dev/null +++ b/.github/workflows/helm_smoke_opensearch.yml @@ -0,0 +1,12 @@ +name: helm_smoke_opensearch + +on: workflow_dispatch + +permissions: + contents: read + +jobs: + smoke: + uses: ./.github/workflows/helm_smoke_logins.yml + with: + stacks: '["opensearch"]' diff --git a/.github/workflows/smoke_nifi_services.yml b/.github/workflows/smoke_nifi_services.yml deleted file mode 100644 index 8271642a..00000000 --- a/.github/workflows/smoke_nifi_services.yml +++ /dev/null @@ -1,163 +0,0 @@ -name: smoke-nifi-services - -on: - push: - branches: ['**'] - paths: &paths - - 'apps/nifi/**' - - 'apps/nginx/**' - - '.github/workflows/smoke_nifi_services.yml' - - '!**/*.md' - - '!**/README*' - pull_request: - paths: *paths - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -permissions: - contents: read - -defaults: - run: - shell: bash - working-directory: apps/nifi/docker - -jobs: - smoke: - name: Build and smoke-test NiFi services - runs-on: ubuntu-24.04 - timeout-minutes: 45 - env: - COMPOSE_FILE: docker-compose.base.yml:docker-compose.dev.yml - COMPOSE_PROJECT_NAME: nifi-smoke - CERT_DIR: ../../../deployment/security/certificates - - steps: - - uses: actions/checkout@v7 - - - name: Set up Java - uses: actions/setup-java@v6 - with: - distribution: temurin - java-version: '21' - - - name: Generate smoke fixtures - run: | - scratch_dir="$(mktemp -d)" - trap 'rm -rf "$scratch_dir"' EXIT - mkdir -p "$CERT_DIR"/{root,nifi,nginx} ../env - ca_cert="$CERT_DIR/root/root-ca.pem" - password="$(openssl rand -hex 16)" - - openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj '/CN=NiFi smoke CA' \ - -addext 'basicConstraints=critical,CA:TRUE' \ - -addext 'keyUsage=critical,keyCertSign,cRLSign' \ - -keyout "$scratch_dir/ca.key" -out "$ca_cert" - - issue_cert() { - local subject="$1" san="$2" key="$3" cert="$4" - openssl req -new -newkey rsa:2048 -nodes -subj "/CN=$subject" \ - -keyout "$key" -out "$scratch_dir/leaf.csr" - openssl x509 -req -days 1 -in "$scratch_dir/leaf.csr" \ - -CA "$ca_cert" -CAkey "$scratch_dir/ca.key" \ - -CAserial "$scratch_dir/ca.srl" -CAcreateserial \ - -extfile <(printf 'subjectAltName=%s\nextendedKeyUsage=serverAuth\n' "$san") -out "$cert" - } - issue_cert nifi DNS:nifi "$scratch_dir/nifi.key" "$scratch_dir/nifi.pem" - issue_cert 127.0.0.1 IP:127.0.0.1 "$CERT_DIR/nginx/tls.key" "$CERT_DIR/nginx/tls.crt" - - openssl pkcs12 -export -name nifi -inkey "$scratch_dir/nifi.key" \ - -in "$scratch_dir/nifi.pem" -certfile "$ca_cert" \ - -out "$scratch_dir/nifi.p12" -passout "pass:$password" - keytool -importkeystore -noprompt \ - -srckeystore "$scratch_dir/nifi.p12" -srcstoretype PKCS12 -srcstorepass "$password" \ - -destkeystore "$CERT_DIR/nifi/nifi-keystore.jks" -deststoretype JKS -deststorepass "$password" - keytool -importcert -noprompt -alias root-ca -file "$ca_cert" \ - -keystore "$CERT_DIR/nifi/nifi-truststore.jks" -storetype JKS -storepass "$password" - - touch ../env/general.env - cat > ../env/nifi.env <&2; exit 1 ;; - esac - done - - for service in nifi nifi-nginx; do - docker compose exec -T "$service" sh -ec 'test "$(id -u)" -ne 0' - done - docker compose exec -T nifi /opt/nifi/scripts/cogstack-healthcheck.sh live - docker compose exec -T nifi /opt/nifi/scripts/cogstack-healthcheck.sh ready - for probe in live ready; do - docker compose exec -T nifi-nginx curl -fsS --output /dev/null "http://127.0.0.1:8080/healthz/$probe" - done - - response="$("${request[@]}" --data-urlencode "username=$SINGLE_USER_CREDENTIALS_USERNAME" \ - --data-urlencode "password=$SINGLE_USER_CREDENTIALS_PASSWORD" \ - --write-out $'\n%{http_code}' "$url/nifi-api/access/token")" - code="${response##*$'\n'}" - token="${response%$'\n'*}" - if [[ "$code" != 201 || -z "$token" ]]; then - echo "NiFi token request returned HTTP $code or an empty token" >&2 - exit 1 - fi - - code="$("${request[@]}" --header "Authorization: Bearer $token" --output /dev/null \ - --write-out '%{http_code}' "$url/nifi-api/flow/about")" - if [[ "$code" != 200 ]]; then - echo "Authenticated NiFi API returned HTTP $code" >&2 - exit 1 - fi - echo 'OK: authenticated NiFi API returned HTTP 200' - - - name: Dump container logs - if: failure() - run: | - [[ -f ../env/nifi.env ]] || exit 0 - source ./export_env_vars.sh - docker compose ps - docker compose logs --no-color nifi nifi-nginx - - - name: Shutdown stack - if: always() - run: | - [[ -f ../env/nifi.env ]] || exit 0 - source ./export_env_vars.sh - docker compose down -v - docker compose -p nifi-smoke-published -f docker-compose.yml down diff --git a/apps/nifi/README.md b/apps/nifi/README.md index a84f9d3a..36f90aa5 100644 --- a/apps/nifi/README.md +++ b/apps/nifi/README.md @@ -13,56 +13,40 @@ production configurations use `cogstacksystems/nifi` and `cogstacksystems/nginx` From the repository root, create `apps/nifi/env/` and add `general.env` and `nifi.env`. Both files are Git-ignored. `general.env` can be empty if you have -no shared settings. Use the following as a starting point for `nifi.env` and -replace the example credentials and passwords before starting NiFi. +no shared settings. Use the following as a starting point for `nifi.env`. ```dotenv NIFI_DOCKER_CPU_MIN=1 NIFI_DOCKER_CPU_MAX=2 NIFI_DOCKER_RAM=4g -SINGLE_USER_CREDENTIALS_USERNAME=admin -SINGLE_USER_CREDENTIALS_PASSWORD='replace-with-a-unique-password' -NIFI_SENSITIVE_PROPS_KEY='replace-with-a-stable-encryption-key' - -KEYSTORE_PATH=/security/certificates/nifi/nifi-keystore.jks -KEYSTORE_TYPE=JKS -KEYSTORE_PASSWORD='replace-with-the-keystore-password' -TRUSTSTORE_PATH=/security/certificates/nifi/nifi-truststore.jks -TRUSTSTORE_TYPE=JKS -TRUSTSTORE_PASSWORD='replace-with-the-truststore-password' - NIFI_WEB_PROXY_HOST=localhost:8443 NIFI_HEALTHCHECK_HOST=nifi ``` -Use at least 12 characters for the single-user password. Preserve -`NIFI_SENSITIVE_PROPS_KEY` with the flow configuration so NiFi can decrypt -saved sensitive properties. For a non-local deployment, set `NIFI_WEB_PROXY_HOST` -to the browser-facing host and port. If you change `NIFI_EXTERNAL_PORT_NGINX`, -update that allowlist entry as well. See [Apache's startup script](https://github.com/apache/nifi/blob/rel/nifi-2.12.0/nifi-docker/dockerhub/sh/start.sh) +Set `KEYSTORE_PASSWORD` and `TRUSTSTORE_PASSWORD` to match the mounted stores. +Set `SINGLE_USER_CREDENTIALS_USERNAME` and `SINGLE_USER_CREDENTIALS_PASSWORD` +for the NiFi login. Use at least 12 characters for the single-user password. +Use `COGSTACK_NIFI_ENV_FILE` to select another deployment's `nifi.env`. + +The dev Make targets take their sample store passwords and login from +[`certificates.env`](../../deployment/env/certificates.env) and +[`authentication.env`](../../deployment/env/authentication.env). +Set your own values in `nifi.env` to override the samples. + +Preserve `NIFI_SENSITIVE_PROPS_KEY` with the flow configuration so NiFi can +decrypt saved sensitive properties. For a non-local deployment, set +`NIFI_WEB_PROXY_HOST` to the browser-facing host and port. If you change +`NIFI_EXTERNAL_PORT_NGINX`, update that allowlist entry as well. See +[Apache's startup script](https://github.com/apache/nifi/blob/rel/nifi-2.12.0/nifi-docker/dockerhub/sh/start.sh) and [Docker setup guide](https://github.com/apache/nifi/blob/rel/nifi-2.12.0/nifi-docker/dockerhub/README.md) for additional settings. ### TLS certificates -For local development, keep TLS and demo login settings in -`deployment/env/cert_auth_settings_dev.env`. Set an absolute `SECURITY_DIR`, -`ROOT_CERTIFICATE_KEYSTORE_PASSWORD`, `KEYSTORE_PASSWORD`, `TRUSTSTORE_PASSWORD`, -`SINGLE_USER_CREDENTIALS_USERNAME`, and `SINGLE_USER_CREDENTIALS_PASSWORD`. -Prepare or reuse the TLS bundle from the repository root. - -```bash -make -C apps/nifi/docker setup-nifi-dev-tls -``` - -Keep this Git-ignored file at mode `0600`. It can also hold store paths, types, -and TLS names. `start-nifi-dev` and `start-nifi-dev-build` load it automatically -when present and mount the bundle's runtime TLS files. The CA signing key and -its store password stay on the host. - -To supply certificates manually, place the following under -`deployment/security/certificates/`. +Use the existing certificate generators or supply a TLS bundle. Place the files +under `deployment/security/certificates/`, or set `SECURITY_DIR` in `nifi.env` +to the parent of your deployment’s `certificates/` directory. | Files | Purpose | | --- | --- | @@ -72,10 +56,9 @@ To supply certificates manually, place the following under Compose mounts the service certificate directories and `root/root-ca.pem` read-only. The CA signing key and private bundles stay on the host. Make the mounted files -readable by their container users. The start targets run `make check-tls`, which -checks for readable, nonempty regular files. If `root-ca.pem` is a directory from an -earlier bind mount, replace it with the actual PEM file. Certificate validation -occurs when the services connect over TLS. +readable by their container users. The start targets check for readable, +nonempty files before launching. Certificate validation occurs when the services +connect over TLS. ### Start and verify @@ -85,6 +68,7 @@ Run these commands from `apps/nifi/docker/`: | --- | --- | | `make check-config` | Resolve and validate all three Compose configurations using the env files. | | `make start-nifi` | Use `docker-compose.yml` to start published images with a Compose-managed `cogstack-net`. | +| `make start-nifi-dev` | Start NiFi and NGINX with the dev settings. | | `make start-nifi-dev-build` | Apply `docker-compose.dev.yml` over the base, build both images locally, mount editable NiFi resources and dev data, and use `nifi-dev-net`. | | `make start-nifi-prod` | Apply `docker-compose.prod.yml` over the base and start published images on an existing `cogstack-net`. | diff --git a/apps/nifi/docker/Makefile b/apps/nifi/docker/Makefile index 037f080b..b347f961 100644 --- a/apps/nifi/docker/Makefile +++ b/apps/nifi/docker/Makefile @@ -3,36 +3,27 @@ SHELL := /usr/bin/env bash DC_START_CMD := up -d DC_STOP_CMD := stop -COMPOSE_DEV := docker compose -f docker-compose.base.yml -f docker-compose.dev.yml +COMPOSE_DEV := docker compose --env-file ../../../deployment/env/certificates.env \ + --env-file ../../../deployment/env/authentication.env \ + $(if $(wildcard .env),--env-file .env) \ + -f docker-compose.base.yml -f docker-compose.dev.yml COMPOSE_PROD := docker compose -f docker-compose.base.yml -f docker-compose.prod.yml -DEV_CERT_ENV := $(abspath ../../../deployment/env/cert_auth_settings_dev.env) define WITH_ENV source ./export_env_vars.sh || exit $$?; endef -define WITH_DEV_CERTS -$(WITH_ENV) \ -cert_dir=../../../deployment/security/certificates; \ -dev_certs=(); \ -if [[ -f "$(DEV_CERT_ENV)" ]]; then \ - set -a; source "$(DEV_CERT_ENV)" || exit $$?; set +a; \ - : "$${SECURITY_DIR:?Set SECURITY_DIR in the dev settings file}"; \ - : "$${KEYSTORE_PASSWORD:?Set KEYSTORE_PASSWORD in the dev settings file}" "$${TRUSTSTORE_PASSWORD:?Set TRUSTSTORE_PASSWORD in the dev settings file}"; \ - cert_dir="$$SECURITY_DIR/certificates"; \ - dev_certs=(-f docker-compose.dev-tls.yml); \ -fi; -endef - define CHECK_TLS_FILES -for cert in root/root-ca.pem nifi/nifi-keystore.jks nifi/nifi-truststore.jks nginx/tls.crt nginx/tls.key; do \ - file="$$cert_dir/$$cert"; \ +for cert in root/root-ca.pem nifi/nifi-{keystore,truststore}.jks nginx/tls.{crt,key}; do \ + file="$${SECURITY_DIR:-../../../deployment/security}/certificates/$$cert"; \ if [ ! -f "$$file" ] || [ ! -r "$$file" ] || [ ! -s "$$file" ]; then \ printf 'TLS file missing, empty, or unreadable: %s\n' "$$file" >&2; exit 1; \ fi; \ done; endef +WITH_START = $(WITH_ENV) $(CHECK_TLS_FILES) + help: ## List available targets with descriptions @echo "Available targets:" @awk '\ @@ -73,26 +64,22 @@ show-env: ## Print sorted environment variables after loading export_env_vars.sh ${WITH_ENV} >/dev/null 2>&1; printenv | sort check-config: ## Validate the default, dev and prod Compose configurations - @$(WITH_ENV) docker compose config --quiet && $(COMPOSE_PROD) config --quiet - @$(WITH_DEV_CERTS) $(COMPOSE_DEV) "$${dev_certs[@]}" config --quiet + @$(WITH_ENV) docker compose config --quiet && $(COMPOSE_DEV) config --quiet && $(COMPOSE_PROD) config --quiet check-tls: ## Check the TLS files required by NiFi and NGINX - @cert_dir=../../../deployment/security/certificates; $(CHECK_TLS_FILES) - -start-nifi: check-tls ## Start the default NiFi and NGINX stack - $(WITH_ENV) docker compose $(DC_START_CMD) + @$(WITH_ENV) $(CHECK_TLS_FILES) -setup-nifi-dev-tls: ## Generate or validate the local dev certificates using cert_auth_settings_dev.env - @./setup_dev_tls.sh "$(DEV_CERT_ENV)" +start-nifi: ## Start the default NiFi and NGINX stack + $(WITH_START) docker compose $(DC_START_CMD) start-nifi-dev: ## Start NiFi and NGINX with local builds - $(WITH_DEV_CERTS) $(CHECK_TLS_FILES) $(COMPOSE_DEV) "$${dev_certs[@]}" $(DC_START_CMD) nifi nifi-nginx + $(WITH_START) $(COMPOSE_DEV) $(DC_START_CMD) nifi nifi-nginx start-nifi-dev-build: ## Build and start NiFi dev services - $(WITH_DEV_CERTS) $(CHECK_TLS_FILES) $(COMPOSE_DEV) "$${dev_certs[@]}" up -d --build nifi nifi-nginx + $(WITH_START) $(COMPOSE_DEV) up -d --build nifi nifi-nginx -start-nifi-prod: check-tls ## Start the published NiFi and NGINX images on cogstack-net - $(WITH_ENV) $(COMPOSE_PROD) $(DC_START_CMD) +start-nifi-prod: ## Start the published NiFi and NGINX images on cogstack-net + $(WITH_START) $(COMPOSE_PROD) $(DC_START_CMD) build-nifi-image: ## Build the local NiFi image without starting services $(WITH_ENV) docker build \ @@ -128,4 +115,4 @@ delete-nifi-dev-images: ## Delete the NiFi dev images echo "No NiFi dev images found."; \ fi -.PHONY: help load-env show-env check-config check-tls start-nifi setup-nifi-dev-tls start-nifi-dev start-nifi-dev-build start-nifi-prod build-nifi-image stop-nifi-dev stop-nifi-prod delete-nifi delete-nifi-dev-containers delete-nifi-dev-volumes delete-nifi-dev-images +.PHONY: help load-env show-env check-config check-tls start-nifi start-nifi-dev start-nifi-dev-build start-nifi-prod build-nifi-image stop-nifi-dev stop-nifi-prod delete-nifi delete-nifi-dev-containers delete-nifi-dev-volumes delete-nifi-dev-images diff --git a/apps/nifi/docker/docker-compose.base.yml b/apps/nifi/docker/docker-compose.base.yml index 55763034..f1f1890c 100644 --- a/apps/nifi/docker/docker-compose.base.yml +++ b/apps/nifi/docker/docker-compose.base.yml @@ -19,14 +19,14 @@ x-env: AUTH: ${AUTH:-tls} NIFI_SECURITY_USER_AUTHORIZER: ${NIFI_SECURITY_USER_AUTHORIZER:-single-user-authorizer} NIFI_SECURITY_USER_LOGIN_IDENTITY_PROVIDER: ${NIFI_SECURITY_USER_LOGIN_IDENTITY_PROVIDER:-single-user-provider} - SINGLE_USER_CREDENTIALS_USERNAME: ${SINGLE_USER_CREDENTIALS_USERNAME:-${NIFI_SINGLE_USER_CREDENTIALS_USERNAME}} - SINGLE_USER_CREDENTIALS_PASSWORD: ${SINGLE_USER_CREDENTIALS_PASSWORD:-${NIFI_SINGLE_USER_CREDENTIALS_PASSWORD}} - KEYSTORE_PATH: ${KEYSTORE_PATH:-${NIFI_KEYSTORE_PATH}} - KEYSTORE_TYPE: ${KEYSTORE_TYPE:-${NIFI_KEYSTORE_TYPE}} - KEYSTORE_PASSWORD: ${KEYSTORE_PASSWORD:-${NIFI_KEYSTORE_PASSWORD}} - TRUSTSTORE_PATH: ${TRUSTSTORE_PATH:-${NIFI_TRUSTSTORE_PATH}} - TRUSTSTORE_TYPE: ${TRUSTSTORE_TYPE:-${NIFI_TRUSTSTORE_TYPE}} - TRUSTSTORE_PASSWORD: ${TRUSTSTORE_PASSWORD:-${NIFI_TRUSTSTORE_PASSWORD}} + SINGLE_USER_CREDENTIALS_USERNAME: ${SINGLE_USER_CREDENTIALS_USERNAME:-${NIFI_SINGLE_USER_CREDENTIALS_USERNAME:-}} + SINGLE_USER_CREDENTIALS_PASSWORD: ${SINGLE_USER_CREDENTIALS_PASSWORD:-${NIFI_SINGLE_USER_CREDENTIALS_PASSWORD:-}} + KEYSTORE_PATH: ${KEYSTORE_PATH:-${NIFI_KEYSTORE_PATH:-/security/certificates/nifi/nifi-keystore.jks}} + KEYSTORE_TYPE: ${KEYSTORE_TYPE:-${NIFI_KEYSTORE_TYPE:-JKS}} + KEYSTORE_PASSWORD: ${KEYSTORE_PASSWORD:-${NIFI_KEYSTORE_PASSWORD:-}} + TRUSTSTORE_PATH: ${TRUSTSTORE_PATH:-${NIFI_TRUSTSTORE_PATH:-/security/certificates/nifi/nifi-truststore.jks}} + TRUSTSTORE_TYPE: ${TRUSTSTORE_TYPE:-${NIFI_TRUSTSTORE_TYPE:-JKS}} + TRUSTSTORE_PASSWORD: ${TRUSTSTORE_PASSWORD:-${NIFI_TRUSTSTORE_PASSWORD:-}} NIFI_WEB_HTTPS_PORT: ${NIFI_WEB_HTTPS_PORT:-${NIFI_INTERNAL_PORT:-8443}} NIFI_REMOTE_INPUT_SOCKET_PORT: ${NIFI_REMOTE_INPUT_SOCKET_PORT:-${NIFI_INPUT_SOCKET_PORT:-10000}} PYTHONPATH: ${NIFI_PYTHONPATH:-/opt/nifi/nifi-current/python/framework} @@ -45,9 +45,9 @@ x-env: x-mounts: nifi: &nifi-volumes # Security certificates - - ../../../deployment/security/certificates/nifi:/security/certificates/nifi:ro + - ${SECURITY_DIR:-../../../deployment/security}/certificates/nifi:/security/certificates/nifi:ro - type: bind - source: ../../../deployment/security/certificates/root/root-ca.pem + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/root/root-ca.pem target: /security/certificates/root/root-ca.pem read_only: true bind: @@ -67,9 +67,9 @@ x-mounts: - /tmp:mode=1777 nifi-nginx: &nifi-nginx-volumes - - ../../../deployment/security/certificates/nginx:/certificates/nginx:ro + - ${SECURITY_DIR:-../../../deployment/security}/certificates/nginx:/certificates/nginx:ro - type: bind - source: ../../../deployment/security/certificates/root/root-ca.pem + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/root/root-ca.pem target: /certificates/root/root-ca.pem read_only: true bind: diff --git a/apps/openbao/.gitignore b/apps/openbao/.gitignore new file mode 100644 index 00000000..1a56d0d2 --- /dev/null +++ b/apps/openbao/.gitignore @@ -0,0 +1,3 @@ +!/env/ +/env/* +!/env/openbao.env diff --git a/apps/openbao/Makefile b/apps/openbao/Makefile new file mode 100644 index 00000000..1ba58979 --- /dev/null +++ b/apps/openbao/Makefile @@ -0,0 +1,12 @@ +OPENBAO_HOST_PORT ?= 8201 +OPENBAO_TLS_DIR ?= $(CURDIR)/local-server/tls + +.PHONY: start-openbao start-openbao-dev + +start-openbao: ## Start the persistent OpenBao server + OPENBAO_HOST_PORT="$(OPENBAO_HOST_PORT)" OPENBAO_TLS_DIR="$(OPENBAO_TLS_DIR)" \ + docker compose --project-name openbao-server --env-file env/openbao.env \ + -f docker/docker-compose.base.yml -f docker/docker-compose.server.yml up -d + +start-openbao-dev: ## Start the in-memory OpenBao server + docker compose -f docker/docker-compose.yml up -d diff --git a/apps/openbao/docker/docker-compose.base.yml b/apps/openbao/docker/docker-compose.base.yml new file mode 100644 index 00000000..bfc36c4a --- /dev/null +++ b/apps/openbao/docker/docker-compose.base.yml @@ -0,0 +1,3 @@ +services: + openbao: + image: ${OPENBAO_DOCKER_IMAGE:?Set OPENBAO_DOCKER_IMAGE} diff --git a/apps/openbao/docker/docker-compose.dev.yml b/apps/openbao/docker/docker-compose.dev.yml new file mode 100644 index 00000000..59688003 --- /dev/null +++ b/apps/openbao/docker/docker-compose.dev.yml @@ -0,0 +1,8 @@ +services: + openbao: + # The upstream image starts an in-memory dev server by default. + environment: + BAO_ADDR: ${OPENBAO_ADDR:?Set OPENBAO_ADDR} + BAO_DEV_ROOT_TOKEN_ID: + ports: + - "127.0.0.1:${OPENBAO_HOST_PORT:?Set OPENBAO_HOST_PORT}:8200" diff --git a/apps/openbao/docker/docker-compose.server.yml b/apps/openbao/docker/docker-compose.server.yml new file mode 100644 index 00000000..324cb785 --- /dev/null +++ b/apps/openbao/docker/docker-compose.server.yml @@ -0,0 +1,21 @@ +name: openbao-server + +services: + openbao: + command: [server] + environment: + BAO_API_ADDR: ${OPENBAO_API_ADDR:-https://127.0.0.1:${OPENBAO_HOST_PORT}} + ports: + - "127.0.0.1:${OPENBAO_HOST_PORT}:8200" + volumes: + - openbao-data:/openbao/file + - ./openbao.hcl:/openbao/config/openbao.hcl:ro + - type: bind + source: ${OPENBAO_TLS_DIR:?Set OPENBAO_TLS_DIR} + target: /openbao/tls + read_only: true + bind: + create_host_path: false + +volumes: + openbao-data: diff --git a/apps/openbao/docker/docker-compose.yml b/apps/openbao/docker/docker-compose.yml new file mode 100644 index 00000000..f54551f7 --- /dev/null +++ b/apps/openbao/docker/docker-compose.yml @@ -0,0 +1,7 @@ +name: openbao + +include: + - path: + - docker-compose.base.yml + - docker-compose.dev.yml + env_file: ../env/openbao.env diff --git a/apps/openbao/docker/openbao.hcl b/apps/openbao/docker/openbao.hcl new file mode 100644 index 00000000..44b6fac1 --- /dev/null +++ b/apps/openbao/docker/openbao.hcl @@ -0,0 +1,12 @@ +ui = true +cluster_addr = "https://openbao:8201" + +storage "raft" { + path = "/openbao/file" +} + +listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/openbao/tls/tls.crt" + tls_key_file = "/openbao/tls/tls.key" +} diff --git a/apps/openbao/env/openbao.env b/apps/openbao/env/openbao.env new file mode 100644 index 00000000..d98b1de1 --- /dev/null +++ b/apps/openbao/env/openbao.env @@ -0,0 +1,7 @@ +OPENBAO_DOCKER_IMAGE=openbao/openbao:2.7.3 +OPENBAO_HOST_PORT=8200 + +# Address for the bao CLI inside the container. +OPENBAO_ADDR=http://127.0.0.1:8200 + +# Export BAO_DEV_ROOT_TOKEN_ID in your shell if a demo script needs a known token. diff --git a/apps/opensearch-dashboards/.gitignore b/apps/opensearch-dashboards/.gitignore new file mode 100644 index 00000000..a05566ac --- /dev/null +++ b/apps/opensearch-dashboards/.gitignore @@ -0,0 +1,3 @@ +!/env/ +/env/* +!/env/opensearch-dashboards.env diff --git a/apps/opensearch-dashboards/config/opensearch.yml b/apps/opensearch-dashboards/config/opensearch.yml new file mode 100644 index 00000000..a24ca360 --- /dev/null +++ b/apps/opensearch-dashboards/config/opensearch.yml @@ -0,0 +1,151 @@ +# OpenSearch Dashboards is served by a back end server. This setting specifies the port to use. +server.port: 5601 + +# Specifies the address to which the OpenSearch Dashboards server will bind. IP addresses and host names are both valid values. +# The default is 'localhost', which usually means remote machines will not be able to connect. +# To allow connections from remote users, set this parameter to a non-loopback address. +server.host: "0.0.0.0" + +# Enables you to specify a path to mount OpenSearch Dashboards at if you are running behind a proxy. +# Use the `server.rewriteBasePath` setting to tell OpenSearch Dashboards if it should remove the basePath +# from requests it receives, and to prevent a deprecation warning at startup. +# This setting cannot end in a slash. +#server.basePath: "" + +# Specifies whether OpenSearch Dashboards should rewrite requests that are prefixed with +# `server.basePath` or require that they are rewritten by your reverse proxy. +#server.rewriteBasePath: false + +# The maximum payload size in bytes for incoming server requests. +#server.maxPayloadBytes: 1048576 + +# The OpenSearch Dashboards server's name. This is used for display purposes. +server.name: ${OPENSEARCH_DASHBOARDS_SERVER_NAME} + +# The URLs of the OpenSearch instances to use for all your queries. +opensearch.hosts: ${OPENSEARCH_HOSTS} + +opensearch_security.multitenancy.enabled: true +opensearch_security.multitenancy.tenants.enable_global: true +opensearch_security.multitenancy.tenants.enable_private: true +opensearch_security.multitenancy.tenants.preferred: ["Global"] +opensearch_security.readonly_mode.roles: ["kibana_read_only"] +opensearch_security.multitenancy.enable_filter: true +opensearch_security.cookie.secure: true + +# OpenSearch Dashboards uses an index in OpenSearch to store saved searches, visualizations and +# dashboards. OpenSearch Dashboards creates a new index if the index doesn't already exist. + +# We changed this from .opensearch_dashboards to .kibana because of a permission bug in OpenSearch Dashboards 2.19.x and 3.0.0 +# report: https://github.com/opensearch-project/security/issues/5360 +opensearchDashboards.index: ".opensearch_dashboards" + +# The default application to load. +#opensearchDashboards.defaultAppId: "home" + +# Setting for an optimized healthcheck that only uses the local OpenSearch node to do Dashboards healthcheck. +# This settings should be used for large clusters or for clusters with ingest heavy nodes. +# It allows Dashboards to only healthcheck using the local OpenSearch node rather than fan out requests across all nodes. +# +# It requires the user to create an OpenSearch node attribute with the same name as the value used in the setting +# This node attribute should assign all nodes of the same cluster an integer value that increments with each new cluster that is spun up +# e.g. in opensearch.yml file you would set the value to a setting using node.attr.cluster_id: +# Should only be enabled if there is a corresponding node attribute created in your OpenSearch config that matches the value here +#opensearch.optimizedHealthcheckId: "cluster_id" + +# If your OpenSearch is protected with basic authentication, these settings provide +# the username and password that the OpenSearch Dashboards server uses to perform maintenance on the OpenSearch Dashboards +# index at startup. Your OpenSearch Dashboards users still need to authenticate with OpenSearch, which +# is proxied through the OpenSearch Dashboards server. +opensearch.username: ${KIBANA_USER} +opensearch.password: ${KIBANA_PASSWORD} + +# Enables SSL and paths to the PEM-format SSL certificate and SSL key files, respectively. +# These settings enable SSL for outgoing requests from the OpenSearch Dashboards server to the browser. +server.ssl.enabled: true +server.ssl.certificate: "/certificates/elastic/opensearch/es_kibana_client.pem" +server.ssl.key: "/certificates/elastic/opensearch/es_kibana_client.key" + +# Outgoing requests use KIBANA_USER/KIBANA_PASSWORD and verify the server CA. +# Do not send an admin client certificate: that would bypass the service account. + +# Optional setting that enables you to specify a path to the PEM file for the certificate +# authority for your OpenSearch instance. +opensearch.ssl.certificateAuthorities: ["/certificates/elastic/opensearch/elastic-stack-ca.crt.pem"] + +# To disregard the validity of SSL certificates, change this setting's value to 'none'. +opensearch.ssl.verificationMode: full + +# Time in milliseconds to wait for OpenSearch to respond to pings. Defaults to the value of +# the opensearch.requestTimeout setting. +opensearch.pingTimeout: 10000 + +# Time in milliseconds to wait for responses from the back end or OpenSearch. This value +# must be a positive integer. +opensearch.requestTimeout: 420000 + +# List of OpenSearch Dashboards client-side headers to send to OpenSearch. To send *no* client-side +# headers, set this value to [] (an empty list). +opensearch.requestHeadersAllowlist: ["securitytenant", "Authorization"] + +# Header names and values that are sent to OpenSearch. Any custom headers cannot be overwritten +# by client-side headers, regardless of the opensearch.requestHeadersAllowlist configuration. +# opensearch.customHeaders: {} + +# Time in milliseconds for OpenSearch to wait for responses from shards. Set to 0 to disable. +# opensearch.shardTimeout: 30000 + +# Logs queries sent to OpenSearch. Requires logging.verbose set to true. +# opensearch.logQueries: false + +# Specifies the path where OpenSearch Dashboards creates the process ID file. +# pid.file: /var/run/opensearchDashboards.pid + +# Enables you to specify a file where OpenSearch Dashboards stores log output. +# logging.dest: stdout + +# Set the value of this setting to true to suppress all logging output. +# logging.silent: false + +# Set the value of this setting to true to suppress all logging output other than error messages. +# logging.quiet: false + +# Set the value of this setting to true to log all events, including system usage information +# and all requests. +# logging.verbose: false + +# Set the interval in milliseconds to sample system and process performance +# metrics. Minimum is 100ms. Defaults to 5000. +# ops.interval: 5000 + +# Specifies locale to be used for all localizable strings, dates and number formats. +# Supported languages are the following: English - en , by default , Chinese - zh-CN . +# i18n.locale: "en" + +# Set the allowlist to check input graphite Url. Allowlist is the default check list. +#vis_type_timeline.graphiteAllowedUrls: ['https://www.hostedgraphite.com/UID/ACCESS_KEY/graphite'] + +# Set the value of this setting to true to capture region blocked warnings and errors +# for your map rendering services. +# map.showRegionBlockedWarning: false + +# Enable ML Commons model monitoring and management. Model registration and +# deployment are performed through the REST API or the Dashboards Dev Tools UI. +ml_commons_dashboards.enabled: true +assistant.chat.enabled: true +assistant.incontextInsight.enabled: true +assistant.next.enabled: true +assistant.text2viz.enabled: true +observability.query_assist.enabled: true + +savedObjects.permission.enabled: true + +# Set the value to true to enable multiple data source feature +data_source.enabled: false +# Set the value to true to enable workspace feature +workspace.enabled: true +# Set the value to true to enable explore feature +explore.enabled: true + +opensearchDashboards.dashboardAdmin.users: ["admin"] +opensearchDashboards.dashboardAdmin.groups: ["admin","all_access"] diff --git a/apps/opensearch-dashboards/docker/docker-compose.base.yml b/apps/opensearch-dashboards/docker/docker-compose.base.yml new file mode 100644 index 00000000..3118484a --- /dev/null +++ b/apps/opensearch-dashboards/docker/docker-compose.base.yml @@ -0,0 +1,34 @@ +services: + opensearch-dashboards: + image: ${OPENSEARCH_DASHBOARDS_DOCKER_IMAGE:?Load ../env/opensearch-dashboards.env} + restart: unless-stopped + mem_limit: ${OPENSEARCH_DASHBOARDS_DOCKER_RAM:-1g} + environment: + OPENSEARCH_DASHBOARDS_SERVER_NAME: ${OPENSEARCH_DASHBOARDS_SERVER_NAME:-cogstack-opensearch-dashboards} + OPENSEARCH_HOSTS: '${OPENSEARCH_HOSTS:-["https://opensearch-shared:9200"]}' + OPENSEARCHDASHBOARDS_INDEX: ${OPENSEARCHDASHBOARDS_INDEX:-.kibana} + KIBANA_USER: ${KIBANA_USER:-kibanaserver} + ports: + - '127.0.0.1:${OPENSEARCH_DASHBOARDS_SERVER_OUTPUT_PORT:-5601}:5601' + volumes: + - &bind + type: bind + source: ../config/opensearch.yml + target: /usr/share/opensearch-dashboards/config/opensearch_dashboards.yml + read_only: true + bind: + create_host_path: false + - <<: *bind + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/opensearch/es_kibana_client.pem + target: /certificates/elastic/opensearch/es_kibana_client.pem + - <<: *bind + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/opensearch/es_kibana_client.key + target: /certificates/elastic/opensearch/es_kibana_client.key + - <<: *bind + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/root/root-ca.pem + target: /certificates/elastic/opensearch/elastic-stack-ca.crt.pem + networks: [cognet] + +networks: + cognet: + external: true diff --git a/apps/opensearch-dashboards/docker/docker-compose.dev.yml b/apps/opensearch-dashboards/docker/docker-compose.dev.yml new file mode 100644 index 00000000..90ccfb30 --- /dev/null +++ b/apps/opensearch-dashboards/docker/docker-compose.dev.yml @@ -0,0 +1,10 @@ +name: opensearch-dashboards-dev + +services: + opensearch-dashboards: + environment: + KIBANA_PASSWORD: ${KIBANA_PASSWORD:-kibanaserver} + +networks: + cognet: + name: opensearch-dev-net diff --git a/apps/opensearch-dashboards/docker/docker-compose.prod.yml b/apps/opensearch-dashboards/docker/docker-compose.prod.yml new file mode 100644 index 00000000..07c83e34 --- /dev/null +++ b/apps/opensearch-dashboards/docker/docker-compose.prod.yml @@ -0,0 +1,10 @@ +name: opensearch-dashboards + +services: + opensearch-dashboards: + environment: + KIBANA_PASSWORD: ${KIBANA_PASSWORD:?Set the Dashboards service account password} + +networks: + cognet: + name: cogstack-net diff --git a/apps/opensearch-dashboards/docker/docker-compose.yml b/apps/opensearch-dashboards/docker/docker-compose.yml new file mode 100644 index 00000000..4af24138 --- /dev/null +++ b/apps/opensearch-dashboards/docker/docker-compose.yml @@ -0,0 +1,5 @@ +name: opensearch-dashboards + +include: + - path: [docker-compose.base.yml, docker-compose.prod.yml] + env_file: ../env/opensearch-dashboards.env diff --git a/apps/opensearch-dashboards/env/opensearch-dashboards.env b/apps/opensearch-dashboards/env/opensearch-dashboards.env new file mode 100644 index 00000000..03d23fee --- /dev/null +++ b/apps/opensearch-dashboards/env/opensearch-dashboards.env @@ -0,0 +1,20 @@ +########################################################################## OpenSearch Dashboards Env vars ########################################################################### + +OPENSEARCH_DASHBOARDS_HOST="https://kibana:5601" + +# possible values: +# - opensearch : opensearchproject/opensearch-dashboards:3.9.0 +# the custom cogstack image is always based on the last image of ES native + +OPENSEARCH_DASHBOARDS_DOCKER_IMAGE=opensearchproject/opensearch-dashboards:3.9.0@sha256:256d4cea5928868ac09bca642a0ac8285a2b7e4b7fdd45c4ec06e75a5cf3184c + +OPENSEARCH_DASHBOARDS_SERVER_NAME="cogstack-opensearch-dashboards" +OPENSEARCH_DASHBOARDS_PUBLIC_BASE_URL="https://elasticsearch-1:5601" + +OPENSEARCH_DASHBOARDS_SERVER_HOST="0.0.0.0" +OPENSEARCH_DASHBOARDS_SERVER_OUTPUT_PORT=5601 + +OPENSEARCH_DASHBOARDS_DOCKER_SHM_SIZE=512m +OPENSEARCH_DASHBOARDS_DOCKER_CPU_MIN=1 +OPENSEARCH_DASHBOARDS_DOCKER_CPU_MAX=1 +OPENSEARCH_DASHBOARDS_DOCKER_RAM=1g diff --git a/apps/opensearch/.gitignore b/apps/opensearch/.gitignore new file mode 100644 index 00000000..641f226a --- /dev/null +++ b/apps/opensearch/.gitignore @@ -0,0 +1,3 @@ +!/env/ +/env/* +!/env/opensearch.env diff --git a/apps/opensearch/README.md b/apps/opensearch/README.md new file mode 100644 index 00000000..9bd40f4c --- /dev/null +++ b/apps/opensearch/README.md @@ -0,0 +1,47 @@ +# OpenSearch and Dashboards in Docker + +From the repository root, run the commands for any missing TLS files. + +```bash +make -C deployment certs-root +make -C deployment certs-opensearch +OPENSEARCH_DASHBOARDS_DNS_NAMES=localhost \ + ./deployment/scripts/security/create_opensearch_client_admin_certs.sh --dashboards-only +``` + +Set an absolute `SECURITY_DIR` to use a different certificate bundle. Each +container runs as UID 1000 and needs read access to its own private key. The +Dashboards certificate must cover the browser hostname. + +Export `KIBANA_PASSWORD` from your deployment secrets for the `kibanaserver` +account. Set `OS_NIFI_PASSWORD`, `OS_PIPELINE_PASSWORD`, or `OS_ANALYST_PASSWORD` +to create `nifi`, `cogstack_pipeline`, or `cogstack_user`, respectively. +Run from the repository root on a fresh deployment. + +```bash +docker compose -f apps/opensearch/docker/docker-compose.yml up -d +bash apps/opensearch/security/bootstrap.sh \ + docker compose -f apps/opensearch/docker/docker-compose.yml exec -T opensearch +docker compose -f apps/opensearch-dashboards/docker/docker-compose.yml up -d +``` + +The bootstrap hashes the supplied passwords and applies the shared policy in +[`security/`](security/). Apply changes to existing clusters through the +[Security REST API](https://docs.opensearch.org/latest/security/api/roles/). +Dashboards listens at `https://localhost:5601`. + +Compose uses `.kibana` for saved objects to match the bundled Security role. +Set `OPENSEARCHDASHBOARDS_INDEX` when your Security configuration uses another index. + +For dev, run this from each app's `docker/` directory, starting with OpenSearch. +Use `opensearch-dashboards.env` for Dashboards. + +```bash +docker compose --env-file ../env/opensearch.env \ + -f docker-compose.base.yml -f docker-compose.dev.yml up -d +``` + +Dev uses the bundled Security users and a separate network. The corresponding +`docker-compose.prod.yml` overlay joins an existing `cogstack-net`. OpenSearch +stores indexes and Security state in `opensearch_data` or `opensearch-dev_data`, +which survive `docker compose down`. diff --git a/apps/opensearch/config/opensearch.yml b/apps/opensearch/config/opensearch.yml new file mode 100644 index 00000000..1966adbd --- /dev/null +++ b/apps/opensearch/config/opensearch.yml @@ -0,0 +1,222 @@ +network.host: '${OPENSEARCH_NETWORK_HOST:0.0.0.0}' +network.publish_host: '${OPENSEARCH_NETWORK_PUBLISH_HOST:}' +logger.level: '${OPENSEARCH_LOG_LEVEL:INFO}' + +###### CLUSTER CONFIGURATION ###### + +bootstrap.system_call_filter: '${OPENSEARCH_SYSTEM_CALL_FILTER:true}' + +# Docker supplies these settings through its environment. Helm supplies the +# Kubernetes discovery settings through the StatefulSet. +discovery.seed_hosts: '${OPENSEARCH_SEED_HOSTS:}' +cluster.initial_cluster_manager_nodes: '${OPENSEARCH_INITIAL_CLUSTER_MANAGER_NODES:}' +discovery.type: zen + +plugins.security.ssl.transport.pemcert_filepath: tls/node.crt +plugins.security.ssl.transport.pemkey_filepath: tls/node.key +plugins.security.ssl.transport.pemtrustedcas_filepath: tls/ca.crt +transport.ssl.enforce_hostname_verification: false +plugins.security.ssl.http.enabled: true +plugins.security.ssl.transport.enabled: true +plugins.security.ssl.http.pemcert_filepath: tls/node.crt +plugins.security.ssl.http.pemkey_filepath: tls/node.key +plugins.security.ssl.http.pemtrustedcas_filepath: tls/ca.crt +plugins.security.allow_unsafe_democertificates: false +plugins.security.allow_default_init_securityindex: '${OPENSEARCH_ALLOW_DEFAULT_INIT_SECURITYINDEX:false}' + +plugins.security.authcz.admin_dn: + - "CN=admin,OU=cogstack,O=cogstack,L=UK,ST=London,C=UK" + +plugins.security.nodes_dn: + - "CN=opensearch-shared,OU=cogstack,O=cogstack,L=UK,ST=London,C=UK" + +plugins.security.enable_snapshot_restore_privilege: true +plugins.security.check_snapshot_restore_write_privileges: true +cluster.routing.allocation.disk.threshold_enabled: true + +plugins.security.ssl.http.clientauth_mode : OPTIONAL + +plugins.security.roles_mapping_resolution: MAPPING_ONLY + +# Supply deployment-specific values on every node when using these features. +plugins.security.compliance.salt: '${OPENSEARCH_COMPLIANCE_SALT:}' +plugins.query.datasources.encryption.masterkey: '${OPENSEARCH_DATASOURCE_MASTER_KEY:}' + +############## REST Management API configuration settings ############## +# Enable or disable role based access to the REST management API +# Default is that no role is allowed to access the REST management API. +plugins.security.restapi.roles_enabled: ["all_access", "security_rest_api_access"] + +# Disable particular endpoints and their HTTP methods for roles. +# By default all endpoints/methods are allowed. +#plugins.security.restapi.endpoints_disabled..: +# Example: +#plugins.security.restapi.endpoints_disabled.all_access.ACTIONGROUPS: ["PUT","POST","DELETE"] +#plugins.security.restapi.endpoints_disabled.xyz_role.LICENSE: ["DELETE"] + +# The following endpoints exist: +# ACTIONGROUPS +# CACHE +# CONFIG +# ROLES +# ROLESMAPPING +# INTERNALUSERS +# SYSTEMINFO +# PERMISSIONSINFO + +############## Auditlog configuration settings ############## + +# Destination of the auditlog events +plugins.security.audit.type: internal_opensearch +plugins.security.audit.config.http_endpoints: '${OPENSEARCH_HOSTS:}' +plugins.security.audit.config.enable_ssl_client_auth: true + +#plugins.security.audit.enable_rest: false +#plugins.security.audit.enable_transport: false +#plugins.security.audit.config.disabled_rest_categories: NONE +#plugins.security.audit.config.disabled_transport_categories: NONE +#plugins.security.audit.config.index: auditlog6 # make sure you secure this index properly +#plugins.security.audit.config.index: "'auditlog6-'YYYY.MM.dd" #rotates index daily - make sure you secure this index properly +#plugins.security.audit.config.type: auditlog +#plugins.security.audit.config.username: auditloguser +#plugins.security.audit.config.password: auditlogpassword +#plugins.security.audit.config.enable_ssl: false +#plugins.security.audit.config.verify_hostnames: false +#plugins.security.audit.config.cert_alias: mycert +#plugins.security.audit.config.pemkey_filepath: key.pem +#plugins.security.audit.config.pemkey_content: <...pem base 64 content> +#plugins.security.audit.config.pemkey_password: secret +#plugins.security.audit.config.pemcert_filepath: cert.pem +#plugins.security.audit.config.pemcert_content: <...pem base 64 content> +#plugins.security.audit.config.pemtrustedcas_filepath: ca.pem +#plugins.security.audit.config.pemtrustedcas_content: <...pem base 64 content> + +# webhook settings +#plugins.security.audit.config.webhook.url: "http://mywebhook/endpoint" +# One of URL_PARAMETER_GET,URL_PARAMETER_POST,TEXT,JSON,SLACK +#plugins.security.audit.config.webhook.format: JSON +#plugins.security.audit.config.webhook.ssl.verify: false +#plugins.security.audit.config.webhook.ssl.pemtrustedcas_filepath: ca.pem +#plugins.security.audit.config.webhook.ssl.pemtrustedcas_content: <...pem base 64 content> + +# log4j settings +#plugins.security.audit.config.log4j.logger_name: auditlogger +#plugins.security.audit.config.log4j.level: INFO + +############## Kerberos configuration settings ############## +# If Kerberos authentication should be used you have to configure: + +# The Path to the krb5.conf file +# Can be absolute or relative to the OpenSearch config directory +#plugins.security.kerberos.krb5_filepath: '/etc/krb5.conf' + +# The Path to the keytab where the acceptor_principal credentials are stored. +# Must be relative to the OpenSearch config directory +#plugins.security.kerberos.acceptor_keytab_filepath: 'eskeytab.tab' + +# Acceptor (Server) Principal name, must be present in acceptor_keytab_path file +#plugins.security.kerberos.acceptor_principal: 'HTTP/localhost' + + +############## Expert settings ############## +# WARNING: Expert settings, do only use if you know what you are doing +# If you set wrong values here this this could be a security risk +# or make OpenSearch Security stop working + +# Name of the index where .opendistro_security stores its configuration. + +#plugins.security.config_index_name: .opendistro_security + +# This defines the OID of server node certificates +#plugins.security.cert.oid: '1.2.3.4.5.5' + +# This specifies the implementation of org.opensearch.security.transport.InterClusterRequestEvaluator +# that is used to determine inter-cluster request. +# Instances of org.opensearch.security.transport.InterClusterRequestEvaluator must implement a single argument +# constructor that takes an org.opensearch.common.settings.Settings +#plugins.security.cert.intercluster_request_evaluator_class: org.opensearch.security.transport.DefaultInterClusterRequestEvaluator + +# By default, normal users can restore snapshots if they have the priviliges 'cluster:admin/snapshot/restore', +# 'indices:admin/create', and 'indices:data/write/index' for the indices to be restored. +# To disable snapshot restore for normal users set 'plugins.security.enable_snapshot_restore_privilege: false'. +# This makes it so that only snapshot restore requests signed by an admin TLS certificate are accepted. +# A snapshot can only be restored when it does not contain global state and does not restore the '.opendistro_security' index +# If 'plugins.security.check_snapshot_restore_write_privileges: false' is set then the additional indices checks are omitted. +#plugins.security.enable_snapshot_restore_privilege: true +#plugins.security.check_snapshot_restore_write_privileges: true + +# Authentication cache timeout in minutes (A value of 0 disables caching, default is 60) +#plugins.security.cache.ttl_minutes: 60 + +# Disable OpenSearch Security +# WARNING: This can expose your configuration (including passwords) to the public. +#plugins.security.disabled: false + +# Protected indices are even more secure than normal indices. These indices require a role to access like any other index, but they require an additional role +# to be visible, listed in the plugins.security.protected_indices.roles setting. +# Enable protected indices +# plugins.security.protected_indices.enabled: true +# Specify a list of roles a user must be member of to touch any protected index. +# plugins.security.protected_indices.roles: ['all_access'] + +# Bundled plugins register their system indices with OpenSearch. Protect those +# registered indices without the deprecated plugins.security.system_indices.indices list. +# Allow explicit system:admin/system_index role permissions as well as super-admin access. +plugins.security.system_indices.enabled: true +plugins.security.system_indices.permission.enabled: true + +# ================= ML Commons ================= + +plugins.ml_commons.local_model.enabled: true +plugins.ml_commons.remote_inference.enabled: true +plugins.ml_commons.only_run_on_ml_node: false +plugins.ml_commons.allow_registering_model_via_url: true +plugins.ml_commons.allow_registering_model_via_local_file: true +# Permit HTTPS model repositories and only the dedicated read-only local model +# directory; do not allow arbitrary HTTP, FTP, or file-system paths. +plugins.ml_commons.trusted_url_regex: '^https://.*$|^file:///usr/share/opensearch/models/[^?#]+\.zip$' +# Permit ML Commons connectors to call only the Ollama service on the private +# CogStack Docker network. Docker resolves this stable service name to a +# private container IP, so both the general and private endpoint allowlists +# are required by OpenSearch 3.7 and later. +plugins.ml_commons.connector.private_ip_enabled: true +plugins.ml_commons.trusted_connector_endpoints_regex: + - '^http://ollama:11434/.*$' + - '^http://ollama-openai-proxy:11435/.*$' +plugins.ml_commons.trusted_connector_private_endpoints_regex: + - '^http://ollama:11434/.*$' + - '^http://ollama-openai-proxy:11435/.*$' +plugins.ml_commons.model_access_control_enabled: true +plugins.ml_commons.connector_access_control_enabled: true +plugins.ml_commons.safe_delete_model: true +plugins.ml_commons.agent_framework_enabled: true +plugins.ml_commons.rag_pipeline_feature_enabled: true +# Upper bound for asynchronous ML Commons tasks. Remote connector connection +# and response timeouts are configured per connector by opensearch-ai-init.sh. +plugins.ml_commons.ml_task_timeout_in_seconds: 600 + +# This cluster has no dedicated ML nodes, so allow both local and remote models +# to execute on data nodes. +plugins.ml_commons.task_dispatcher.eligible_node_role.local_model: + - data +plugins.ml_commons.task_dispatcher.eligible_node_role.remote_model: + - data + + +# Enable SQL-like queries, allows you to join across indices etc. +plugins.sql.enabled: true +plugins.ppl.enabled: true + +# Calcite (SQL v3 engine) +plugins.calcite.enabled: true +# WARNING: exists only in OpenSearch > 3.4, please DISABLE if you are not on this version as this setting doesn't exist. +plugins.calcite.all_join_types.allowed: true + +# coordinator-level kill switch for searches +search.cancel_after_time_interval: 5m + +# shard-level default timeout (can be overridden per request via "timeout") +search.default_search_timeout: 5m + +# relevant if SQL is paging via PIT +search.default_keep_alive: 10m diff --git a/apps/opensearch/docker/docker-compose.base.yml b/apps/opensearch/docker/docker-compose.base.yml new file mode 100644 index 00000000..515c2dc8 --- /dev/null +++ b/apps/opensearch/docker/docker-compose.base.yml @@ -0,0 +1,40 @@ +services: + opensearch: + image: ${OPENSEARCH_DOCKER_IMAGE:?Load ../env/opensearch.env} + restart: unless-stopped + mem_limit: ${OPENSEARCH_DOCKER_RAM:-2g} + shm_size: ${OPENSEARCH_DOCKER_SHM_SIZE:-512m} + environment: + discovery.type: single-node + DISABLE_INSTALL_DEMO_CONFIG: 'true' + OPENSEARCH_JAVA_OPTS: ${OPENSEARCH_JAVA_OPTS:--Xms512m -Xmx512m} + ports: + - '127.0.0.1:${OPENSEARCH_NODE_1_OUTPUT_PORT:-9200}:9200' + volumes: + - data:/usr/share/opensearch/data + - &bind + type: bind + source: ../config/opensearch.yml + target: /usr/share/opensearch/config/opensearch.yml + read_only: true + bind: + create_host_path: false + - <<: *bind + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/opensearch/opensearch-shared.crt + target: /usr/share/opensearch/config/tls/node.crt + - <<: *bind + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/opensearch/opensearch-shared.key + target: /usr/share/opensearch/config/tls/node.key + - <<: *bind + source: ${SECURITY_DIR:-../../../deployment/security}/certificates/root/root-ca.pem + target: /usr/share/opensearch/config/tls/ca.crt + networks: + cognet: + aliases: [opensearch-shared] + +volumes: + data: + +networks: + cognet: + name: cogstack-net diff --git a/apps/opensearch/docker/docker-compose.dev.yml b/apps/opensearch/docker/docker-compose.dev.yml new file mode 100644 index 00000000..412878fd --- /dev/null +++ b/apps/opensearch/docker/docker-compose.dev.yml @@ -0,0 +1,10 @@ +name: opensearch-dev + +services: + opensearch: + environment: + OPENSEARCH_ALLOW_DEFAULT_INIT_SECURITYINDEX: 'true' + +networks: + cognet: + name: opensearch-dev-net diff --git a/apps/opensearch/docker/docker-compose.prod.yml b/apps/opensearch/docker/docker-compose.prod.yml new file mode 100644 index 00000000..ac008b13 --- /dev/null +++ b/apps/opensearch/docker/docker-compose.prod.yml @@ -0,0 +1,5 @@ +name: opensearch + +networks: + cognet: + external: true diff --git a/apps/opensearch/docker/docker-compose.yml b/apps/opensearch/docker/docker-compose.yml new file mode 100644 index 00000000..30218390 --- /dev/null +++ b/apps/opensearch/docker/docker-compose.yml @@ -0,0 +1,5 @@ +name: opensearch + +include: + - path: docker-compose.base.yml + env_file: ../env/opensearch.env diff --git a/apps/opensearch/env/opensearch.env b/apps/opensearch/env/opensearch.env new file mode 100644 index 00000000..a348afe0 --- /dev/null +++ b/apps/opensearch/env/opensearch.env @@ -0,0 +1,206 @@ +# Based on CogStack-NiFi deploy/elasticsearch.env. +# Supply credentials and encryption keys through your private deployment settings. +####################################################################### OpenSearch Env vars ####################################################################### + +# possible values : +# - elasticsearch : docker.elastic.co/elasticsearch/elasticsearch:9.5.2 +# - elasticsearch (custom cogstack image) : cogstacksystems/cogstack-elasticsearch:latest +# - opensearch : opensearchproject/opensearch:3.9.0 +# the custom cogstack image is always based on the last image of ES native + +OPENSEARCH_DOCKER_IMAGE=opensearchproject/opensearch:3.9.0@sha256:3b55f6b6249cfdb92b52ee59adc8a266203ba9ef9f5d82544fad6f1af2f3609e + +# Each K3s replica runs on a separate Kubernetes node. +OPENSEARCH_K3S_REPLICA_COUNT=1 +# Comma-separated Kubernetes node names to exclude. +OPENSEARCH_K3S_BLACKLIST= + +OPENSEARCH_LOG_LEVEL=INFO + +OPENSEARCH_SEED_HOSTS=localhost,elasticsearch-2,elasticsearch-1 +OPENSEARCH_INITIAL_CLUSTER_MANAGER_NODES=es01 + + +OPENSEARCH_NETWORK_HOST="0.0.0.0" +OPENSEARCH_NETWORK_PUBLISH_HOST="0.0.0.0" + +OPENSEARCH_NODE_1_OUTPUT_PORT=9200 +OPENSEARCH_NODE_2_OUTPUT_PORT=9201 +OPENSEARCH_NODE_3_OUTPUT_PORT=9202 + +# cluster communication port +OPENSEARCH_NODE_1_COMM_OUTPUT_PORT=9300 +OPENSEARCH_NODE_2_COMM_OUTPUT_PORT=9301 +OPENSEARCH_NODE_3_COMM_OUTPUT_PORT=9302 + +# cluster analyzer port +OPENSEARCH_NODE_1_ANALYZER_OUTPUT_PORT=9600 +OPENSEARCH_NODE_2_ANALYZER_OUTPUT_PORT=9601 +OPENSEARCH_NODE_3_ANALYZER_OUTPUT_PORT=9602 + +# do not change these values unless you want to create new volumes manually in services.yml +# or you have a special case where you need to switch volumes +OPENSEARCH_NODE_1_DATA_VOL_NAME=elasticsearch-vol-1 +OPENSEARCH_NODE_2_DATA_VOL_NAME=elasticsearch-vol-2 +OPENSEARCH_NODE_3_DATA_VOL_NAME=elasticsearch-vol-3 + +# log volumes shared between filebeat and elasticsearch +OPENSEARCH_NODE_1_LOG_VOL_NAME=elasticsearch-vol-log-1 +OPENSEARCH_NODE_2_LOG_VOL_NAME=elasticsearch-vol-log-2 +OPENSEARCH_NODE_3_LOG_VOL_NAME=elasticsearch-vol-log-3 + +# Performance Analyzer volumes (OpenSearch) +OPENSEARCH_NODE_1_PA_VOL_NAME=elasticsearch-vol-performance-analyzer-1 +OPENSEARCH_NODE_2_PA_VOL_NAME=elasticsearch-vol-performance-analyzer-2 +OPENSEARCH_NODE_3_PA_VOL_NAME=elasticsearch-vol-performance-analyzer-3 + +# this is for native ES +# possible values: +# - trial # 30 day trial +# - basic + +OPENSEARCH_LICENSE_TYPE="trial" + +OPENSEARCH_SSL_ENABLED=true +OPENSEARCH_ALLOW_DEFAULT_INIT_SECURITYINDEX=true + +OPENSEARCH_CLUSTER_NAME="elasticsearch-cogstack-cluster" + +# Match the node names to the hostnames passed to the certificate generator. +OPENSEARCH_NODE_1_NAME=es01 +OPENSEARCH_NODE_2_NAME=es02 +OPENSEARCH_NODE_3_NAME=es03 + +# corresponds to "node.attr.rack=" +OPENSEARCH_NODE_ATTR="elastic" + +OPENSEARCH_CORS_ENABLED="true" + +OPENSEARCH_HTTP_PORT=9200 + +# this setting represents the number of CPUS allocated to each cluster. +OPENSEARCH_NODE_PROCESSORS="2" + +OPENSEARCH_BACKUPS_PATH_REPO=["/mnt/es_data_backups","/mnt/es_config_backups"] + +# used for full snapshot backup +# this is the path on the physical drive, not inside the container +OPENSEARCH_BACKUP_PARTITION_FULL=/data/es_snapshot_backups/full_backup + +# this is the path on the physical drive, not inside the container +# used for snapshot backups of configs +OPENSEARCH_BACKUP_PARTITION_CONFIG=/data/es_snapshot_backups/config_backup + +# Security certificates +OPENSEARCH_SECURITY_DIR=../security/certificates/elastic/ + +# MEMORY CONFIG +OPENSEARCH_JAVA_OPTS="-Xms512m -Xmx512m -Des.failure_store_feature_flag_enabled=true --enable-native-access=ALL-UNNAMED" +OS_JAVA_OPTS=$OPENSEARCH_JAVA_OPTS + +OPENSEARCH_DOCKER_CPU_MIN=1 +OPENSEARCH_DOCKER_CPU_MAX=1 +# Leave room beyond the Java heap for direct buffers, native code, and plugins. +# OpenSearch 3.9 exceeds a 1 GiB container limit during plugin initialization. +OPENSEARCH_DOCKER_RAM=2g + +OPENSEARCH_DOCKER_SHM_SIZE=512m + +OPENSEARCH_DOCKER_LOG_SIZE_PER_FILE="1000m" +OPENSEARCH_DOCKER_LOG_NUM_FILES=10 + +# OpenSearch ML Commons bootstrap settings. Connector timeouts are seconds; +# the Dashboards opensearch.requestTimeout setting is milliseconds. +OPENSEARCH_AI_OPENSEARCH_CONTAINER=elasticsearch-1 +# Local development credentials; update these when the OpenSearch admin login +# is rotated or override them when invoking the bootstrap script. +OPENSEARCH_AI_OPENSEARCH_USER=admin +# OPENSEARCH_AI_OPENSEARCH_PASSWORD= +OPENSEARCH_AI_CONNECTION_TIMEOUT_SECONDS=720 +OPENSEARCH_AI_READ_TIMEOUT_SECONDS=1440 +OPENSEARCH_AI_DEPLOY_TIMEOUT_SECONDS=360 +OPENSEARCH_AI_MAX_TOKENS=16384 +OPENSEARCH_AI_UTILITY_MAX_TOKENS=16384 +OPENSEARCH_AI_REASONING_EFFORT=none +# Leave room for discovery, one bounded retry, and result summarization. +OPENSEARCH_AI_CHAT_MAX_ITERATIONS=8 +# Hard cap on rows returned by the chat assistant's executing PPL tool. +OPENSEARCH_AI_PPL_RESULT_LIMIT=100 + +# Stable resource names let scripts/opensearch-ai-init.sh safely find and +# update resources instead of creating duplicates on every run. +OPENSEARCH_AI_CHAT_CONNECTOR_NAME="Ollama Qwen Agent Connector" +OPENSEARCH_AI_CHAT_MODEL_NAME="Qwen 3.5 Ollama Agent Model" +OPENSEARCH_AI_CHAT_AGENT_NAME="Qwen 3.5 Conversational Agent v2" +OPENSEARCH_AI_ROOT_AGENT_NAME="Qwen Dashboards Root Agent" +OPENSEARCH_AI_PPL_CONNECTOR_NAME="Ollama Qwen PPL Connector" +OPENSEARCH_AI_PPL_MODEL_NAME="Qwen 3.5 Ollama PPL Model" +OPENSEARCH_AI_PPL_AGENT_NAME="Qwen PPL Query Assist Agent" +OPENSEARCH_AI_TIME_RANGE_CONNECTOR_NAME="Ollama Qwen Time Range Connector" +OPENSEARCH_AI_TIME_RANGE_MODEL_NAME="Qwen 3.5 Ollama Time Range Model" +OPENSEARCH_AI_TIME_RANGE_AGENT_NAME="Qwen Query Time Range Parser Agent" +OPENSEARCH_AI_UTILITY_CONNECTOR_NAME="Ollama Qwen Dashboards Utility Connector" +OPENSEARCH_AI_UTILITY_MODEL_NAME="Qwen 3.5 Dashboards Utility Model" +OPENSEARCH_AI_AD_CONNECTOR_NAME="Ollama Qwen Anomaly Suggestion Connector" +OPENSEARCH_AI_AD_MODEL_NAME="Qwen 3.5 Anomaly Suggestion Model" +OPENSEARCH_AI_VISUAL_CONNECTOR_NAME="Ollama Qwen Visualization Connector" +OPENSEARCH_AI_VISUAL_MODEL_NAME="Qwen 3.5 Visualization Model" + +# disables swapping, imporving r/w performance (at the expense of RAM) +OPENSEARCH_BOOTSTRAP_MEMORY_LOCK=true + +# system_call_filter | https://en.wikipedia.org/wiki/Seccomp +OPENSEARCH_SYSTEM_CALL_FILTER=false + +####### OpenID Connect (OpenSearch Security) ####### +# Values used by: security/es_roles/opensearch/config.yml (openid_auth_domain) +OPENSEARCH_OPENID_CONNECT_URL="https://keycloak.example.com:8080/auth/realms/master/.well-known/openid-configuration" +OPENSEARCH_OPENID_REQUIRED_AUDIENCE="your-openid-client-id" +OPENSEARCH_OPENID_SUBJECT_KEY="preferred_username" +OPENSEARCH_OPENID_ROLES_KEY="roles" + +####### This section is for AD user authentication ####### + +# example: network.xyz.uk +OPENSEARCH_AD_DOMAIN_NAME="network.xyz.uk" + +# example: "ldap://server1.xyz.uk:389,ldap://server2.xyz.uk:389" +OPENSEARCH_AD_URL="ldap://server1.xyz.uk:389,ldap://server2.xyz.uk:389" + +OPENSEARCH_AD_UNMAPPED_GROUPS_AS_ROLES=true +OPENSEARCH_AD_FOLLOW_REFERRALS=false + +OPENSEARCH_AD_TIMEOUT=60s + + +####### SMTP EMAIL section + +# example Watcher_Email +OPENSEARCH_EMAIL_ACCOUNT_PROFILE="Watcher_Email" + +OPENSEARCH_EMAIL_ACCOUNT_EMAIL_DEFAULTS=info@notifications.cogstack.net + +# example: smtpserver.xyz.uk +OPENSEARCH_EMAIL_SMTP_HOST="smtpserver.xyz.uk" +OPENSEARCH_EMAIL_SMTP_PORT=25 + + +# Other elasticsearch settings, important for indexing etc +OPENSEARCH_QUERY_BOOL_MAX_CLAUSE_COUNT=4096 +OPENSEARCH_INDICES_MEMORY_INDEX_BUFFER_SIZE="25%" + + +########################################################## + +############################################################ Shared Env vars for MetricBeats/Kibana etc ############################################################## + +# please respect the double quotes "" on each address or you may get type errors from Kibana +OPENSEARCH_HOSTS='["https://elasticsearch-1:9200","https://elasticsearch-2:9200"]' + +# You can generate values for the below strings by using openssl rand +# example, in bash: openssl rand -base64 32 +# the keys must be at least 32 characters long + +# xpack.security.encryptionKey: "something_at_least_32_characters" +# OPENSEARCH_XPACK_SECURITY_ENCRYPTION_KEY= + diff --git a/apps/opensearch/security/bootstrap.sh b/apps/opensearch/security/bootstrap.sh new file mode 100644 index 00000000..9eb75d26 --- /dev/null +++ b/apps/opensearch/security/bootstrap.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +set -euo pipefail +umask 077 + +if (( $# == 0 )); then + printf 'Usage: bash %s \n' "$0" >&2 + exit 2 +fi +OPENSEARCH_KIBANA_PASSWORD=${OPENSEARCH_KIBANA_PASSWORD:-${KIBANA_PASSWORD:-}} +: "${OPENSEARCH_KIBANA_PASSWORD:?Set the Dashboards service account password}" + +policy_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) +certs=$(cd -- "${SECURITY_DIR:-$policy_dir/../../../deployment/security}/certificates/opensearch" && pwd -P) +scratch=$(mktemp -d) +trap 'rm -rf -- "$scratch"' EXIT +printf '%s\0' kibanaserver "$OPENSEARCH_KIBANA_PASSWORD" \ + nifi "${OPENSEARCH_NIFI_PASSWORD:-${OS_NIFI_PASSWORD:-}}" \ + cogstack_pipeline "${OPENSEARCH_PIPELINE_PASSWORD:-${OS_PIPELINE_PASSWORD:-}}" \ + cogstack_user "${OPENSEARCH_ANALYST_PASSWORD:-${OS_ANALYST_PASSWORD:-}}" > "$scratch/passwords" + +bootstrap=$(cat <<'BASH' +set -euo pipefail +umask 077 +work=$(mktemp -d) +trap 'rm -rf -- "$work"' EXIT +tar -xf - -C "$work" + +opensearch_home=${OPENSEARCH_HOME:-/usr/share/opensearch} +tools="$opensearch_home/plugins/opensearch-security/tools" +ca="$opensearch_home/config/tls/ca.crt" +status=$(curl -sS --noproxy '*' --retry 30 --retry-all-errors --retry-delay 3 --max-time 10 \ + --cacert "$ca" --cert "$work/admin.crt" --key "$work/admin.key.pem" \ + --head --output /dev/null --write-out '%{http_code}' https://localhost:9200/.opendistro_security) +if [[ "$status" != 404 ]]; then + printf 'Bootstrap requires an empty Security index (index check returned HTTP %s).\n' "$status" >&2 + exit 1 +fi + +cp "$opensearch_home/config/opensearch-security"/{action_groups,allowlist,audit,config,nodes_dn}.yml "$work/" +{ + printf '_meta:\n type: internalusers\n config_version: 2\n' + while IFS= read -r -d '' user && IFS= read -r -d '' password; do + [[ -n "$password" ]] || continue + hash=$("$tools/hash.sh" -p "$password") + printf '%s:\n hash: "%s"\n' "$user" "$hash" + done < "$work/passwords" +} > "$work/internal_users.yml" +rm -- "$work/passwords" + +"$tools/securityadmin.sh" -icl -cd "$work" -cacert "$ca" \ + -cert "$work/admin.crt" -key "$work/admin.key.pem" +BASH +) + +tar -cf - -C "$scratch" passwords -C "$certs" admin.crt admin.key.pem \ + -C "$policy_dir" roles.yml roles_mapping.yml tenants.yml | + "$@" bash -c "$bootstrap" diff --git a/apps/opensearch/security/roles.yml b/apps/opensearch/security/roles.yml new file mode 100644 index 00000000..eb1eb737 --- /dev/null +++ b/apps/opensearch/security/roles.yml @@ -0,0 +1,18 @@ +_meta: + type: roles + config_version: 2 + +cogstack_ingest: + cluster_permissions: ['indices:data/write/bulk'] + index_permissions: + - index_patterns: ['nifi_*', 'cogstack_*'] + allowed_actions: [create_index, index] + +cogstack_access: + cluster_permissions: [cluster_composite_ops_ro] + index_permissions: + - index_patterns: ['nifi_*', 'cogstack_*'] + allowed_actions: [read] + tenant_permissions: + - tenant_patterns: [cogstack_tenant] + allowed_actions: [kibana_all_read] diff --git a/apps/opensearch/security/roles_mapping.yml b/apps/opensearch/security/roles_mapping.yml new file mode 100644 index 00000000..9eb7b9c0 --- /dev/null +++ b/apps/opensearch/security/roles_mapping.yml @@ -0,0 +1,19 @@ +_meta: + type: rolesmapping + config_version: 2 + +cogstack_ingest: + backend_roles: [cogstack_ingest] + users: [nifi, cogstack_pipeline] + +cogstack_access: + backend_roles: [cogstack_access] + users: [cogstack_user] + +kibana_user: + backend_roles: [cogstack_access] + users: [cogstack_user] + +kibana_server: + reserved: true + users: [kibanaserver] diff --git a/apps/opensearch/security/tenants.yml b/apps/opensearch/security/tenants.yml new file mode 100644 index 00000000..b538c77a --- /dev/null +++ b/apps/opensearch/security/tenants.yml @@ -0,0 +1,6 @@ +_meta: + type: tenants + config_version: 2 + +cogstack_tenant: + description: CogStack dashboards diff --git a/deployment/.gitignore b/deployment/.gitignore index 45a9af48..241c1ce0 100644 --- a/deployment/.gitignore +++ b/deployment/.gitignore @@ -2,7 +2,10 @@ !/env/ /env/* !/env/certificates.env +!/env/authentication.env !/env/cohorter.env !/env/jupyter.env +!/env/opensearch.env +!/env/opensearch-dashboards.env !/env/ocr_service.env !/env/ocr_service_text_only.env diff --git a/deployment/Makefile b/deployment/Makefile index 26b16018..2f0ca14d 100644 --- a/deployment/Makefile +++ b/deployment/Makefile @@ -1,18 +1,25 @@ SHELL := /usr/bin/env bash .SHELLFLAGS := -o pipefail -c +.DEFAULT_GOAL := setup-install-pre-requisites -.PHONY: setup-install-pre-requisites setup-k3s-cluster-init setup-verify setup-k3s-cluster-remote +include $(addprefix $(dir $(lastword $(MAKEFILE_LIST)))make/,setup.mk certs.mk k3s.mk helm.mk) -setup-install-pre-requisites: - bash scripts/installation_utils/install_os_tools_and_software.sh - -setup-k3s-cluster-init: - bash scripts/installation_utils/setup_kubernetes_cluster.sh k3s server --cluster-init - -setup-k3s-cluster-remote: - bash scripts/installation_utils/setup_k3s_cluster.sh $(NODES) - -setup-verify: - bash scripts/installation_utils/verify_docker.sh - bash scripts/installation_utils/verify_k3s.sh +.PHONY: help +# Use the first comment in each included file as its help section heading. +help: ## Show deployment commands + @printf '%s\n' 'Deployment commands' + @awk -F ':.*## ' ' \ + FNR == 1 && /^# / { labels[++count] = substr($$0, 3); next } \ + NF == 2 && $$1 ~ /^[[:alnum:]_-]+$$/ { \ + labels[++count] = $$1; descriptions[count] = $$2; \ + if (length($$1) > width) width = length($$1); \ + } \ + END { \ + for (i = 1; i <= count; i++) { \ + if (i in descriptions) printf " %-*s %s\n", width, labels[i], descriptions[i]; \ + else printf "\n%s\n", labels[i]; \ + } \ + }' $(MAKEFILE_LIST) + @printf '\n%s\n %s\n' 'Remote setup example' \ + 'make setup-k3s-cluster-remote NODES="admin@server1 admin@server2 admin@server3"' diff --git a/deployment/README.md b/deployment/README.md new file mode 100644 index 00000000..dd6f0285 --- /dev/null +++ b/deployment/README.md @@ -0,0 +1,94 @@ +# CogStack deployment + +Run the Makefile commands below from the `deployment/` directory. [Deployment Makefile](Makefile) + +## Quickstart after setup + +After `make setup-all` succeeds, set `NGINX_TLS_NAMES` in `env/certificates.env` +to the hostname or IP clients will use for NGINX. Set the certificate store +passwords, provide deployment credentials, and create `../apps/nifi/env/nifi.env` +if it’s missing. [Environment settings](#environment-settings) + +```bash +make certs-all +make k3s-prepare-all +``` + +`certs-all` generates the certificate bundle. `k3s-prepare-all` renders Helm +values and loads the TLS Secrets, runtime ConfigMaps, and authentication Secrets. + +To deploy all four services, run `make certs-all` followed by +`make helm-install-all`, which runs preparation automatically. +[Install options](#install-the-applications) + +## On-premises setup + +Use a Debian, Ubuntu, or RHEL server with a full repository checkout, systemd, +network access, Bash, GNU Make, and `sudo`. + +`setup-all` runs `setup-install-pre-requisites`, `setup-k3s-cluster-init`, +`setup-k3s-namespace`, and `setup-verify` in order. It installs the host tools, +Docker, K3s, and Helm, then creates the namespace from `env/general.env`. + +- For an existing cluster, point `KUBECONFIG` at it and run + `make setup-k3s-namespace`. The cluster needs NetworkPolicy enforcement and a + StorageClass for NiFi and OpenSearch. [Kubeconfig setup](scripts/README.md#kubectl-access) +- If Docker verification reports a group permission error, sign in again, set + `KUBECONFIG`, and run `make setup-verify`. For multiple servers, use the + [SSH cluster setup guide](scripts/README.md#set-up-a-cluster-over-ssh). + +### Generate certificates + +Use `make certs-k3s` to generate the CA, NGINX HTTPS certificate, and OpenSearch +transport certificate for K3s. If you already have a bundle, set +`SECURITY_DIR` to the directory containing `certificates/` and start with +`make k3s-prepare-all`. The default directory is `deployment/security`. +[Certificate targets](scripts/README.md#certificates) + +## Environment settings + +| File | Settings used by the deployment | +| --- | --- | +| `env/general.env` | `KUBE_NAMESPACE` (default `cogstack`) and `CLUSTER_DOMAIN`. | +| `env/certificates.env` | `SECURITY_DIR`, `NGINX_TLS_NAMES`, and certificate store passwords. | +| `env/authentication.env` | NiFi login and OpenSearch account passwords. | +| `env/nifi.env` | `NIFI_UID`, `NIFI_GID`, `NIFI_DOCKER_*` resources, `NIFI_K3S_WHITELIST`, and `NIFI_INTERNAL_PORT_NGINX`. | +| `env/nginx.env` (optional) | `NGINX_DOCKER_*` resource overrides and `NGINX_NIFI_SERVER_NAME`. | +| `env/opensearch.env` | `OPENSEARCH_K3S_REPLICA_COUNT`, `OPENSEARCH_K3S_BLACKLIST`, `OPENSEARCH_DOCKER_*` resources, and `OPENSEARCH_LOG_LEVEL`. | +| `env/opensearch-dashboards.env` | `OPENSEARCH_DASHBOARDS_DOCKER_*` resources. | + +`k3s-prepare-all` reads login credentials from `env/authentication.env` by +default. To use a private copy, export its absolute path as `NIFI_AUTH_FILE` +and `OPENSEARCH_AUTH_FILE`. Set +`NIFI_SINGLE_USER_CREDENTIALS_USERNAME` and `NIFI_SINGLE_USER_CREDENTIALS_PASSWORD` +for NiFi, `OPENSEARCH_KIBANA_PASSWORD` for the Dashboards service account, and +`OPENSEARCH_ANALYST_PASSWORD` to sign in to Dashboards as `cogstack_user`. +The NiFi loader prompts if its password is empty or still uses the checked-in +Compose sample. + +## Install the applications + +After `make k3s-prepare-all`, choose a stack or install the charts individually. + +| Makefile command | What it installs or upgrades | +| --- | --- | +| `make helm-install-nifi-stack` | NiFi, then NGINX for the HTTPS UI and API. | +| `make helm-install-opensearch-stack` | OpenSearch, then Dashboards using the prepared authentication Secrets. | +| `make helm-install-nifi` | The NiFi StatefulSet. Use NGINX for HTTPS access. | +| `make helm-install-nginx` | The HTTPS gateway for the backends you deploy. | +| `make helm-install-opensearch` | The OpenSearch cluster and its REST API. | +| `make helm-install-opensearch-dashboards` | Dashboards. Install OpenSearch first. | + +## Verify and access the applications + +Replace `cogstack` with your `KUBE_NAMESPACE` if you changed it. + +```bash +helm list -n cogstack +kubectl -n cogstack get pods,pvc,svc +``` + +Check that your selected releases are deployed, their pods are ready, and their +PVCs are bound. Point your DNS name at the external address of `cogstack-nginx` +and trust `deployment/security/certificates/root/root-ca.pem` on client machines. +Use HTTPS at `/nifi/`, `/opensearch/`, or `/dashboards/`. diff --git a/deployment/charts/README.md b/deployment/charts/README.md index 2d87edec..fe1bc74e 100644 --- a/deployment/charts/README.md +++ b/deployment/charts/README.md @@ -4,19 +4,46 @@ Reusable deployment charts for CogStack. Each chart sits directly under this directory and declares its package name in `Chart.yaml`. Folder names use component names, such as `medcat-service` and `jupyter-hub`. -## NiFi charts +## Kubernetes HTTPS entry point -These charts were migrated from `cogstack_nifi/deploy/kubernetes/charts/`: +Deploy the four standalone charts in the same namespace. NGINX serves HTTPS +for the stack and forwards requests to the application Services over HTTP. -| Chart | Purpose | -| --- | --- | -| [`nifi/`](nifi/README.md) | NiFi StatefulSet, Services, TLS settings and persistent storage. | -| [`nginx/`](nginx/README.md) | TLS reverse proxy for the NiFi web Service, with optional Ingress. | +- **NiFi (`nifi/`)** runs Apache NiFi as a StatefulSet with persistent storage + for flow configuration and repositories. A NetworkPolicy restricts its + internal HTTP port `8080` to NGINX pods. Users reach the UI at `/nifi/` and the + API at `/nifi-api/`. [NiFi chart](nifi/README.md) +- **NGINX (`nginx/`)** exposes a `LoadBalancer` Service on port `443` and + terminates TLS with the `nginx-tls` Secret. It handles NiFi Basic Auth using + credentials from `nifi-auth`. [NGINX chart](nginx/README.md) +- **OpenSearch (`opensearch/`)** runs a StatefulSet with persistent storage. + OpenSearch Security controls access to the HTTP REST API on port `9200`, which + NGINX exposes at `/opensearch/`. The `opensearch-node-tls` Secret secures node + transport on port `9300`. [OpenSearch chart](opensearch/README.md) +- **OpenSearch Dashboards (`opensearch-dashboards/`)** serves the UI over HTTP + on port `5601` behind NGINX at `/dashboards/`. It connects to OpenSearch using + the `dashboards-auth` service account Secret. Users sign in with their + OpenSearch accounts. [OpenSearch Dashboards chart](opensearch-dashboards/README.md) -The `nifi/` directory declares `name: nifi` in `Chart.yaml`, so Helm -packages it as `nifi-.tgz`. +### Install the standalone charts -Run from the repository root: +For a new deployment, set `NGINX_TLS_NAMES` to the hostname or IP clients will +use. Supply your deployment credentials. The OpenSearch loader uses `htpasswd` +(`apache2-utils` on Debian/Ubuntu or `httpd-tools` on RHEL). Follow the host +prerequisites, then run these commands from the repository root. +[On-premises deployment guide](../README.md) + +```bash +make -C deployment setup-k3s-namespace +make -C deployment certs-k3s +make -C deployment helm-install-all +``` + +Existing deployments must reload `nifi-auth` for NGINX before upgrading. +OpenSearch upgrades also require the bootstrap Secret and preparation of +administrative access when using an admin certificate. [OpenSearch upgrade details](opensearch/README.md#install) + +## Chart development ```bash helm lint deployment/charts/nifi deployment/charts/nginx @@ -25,8 +52,11 @@ helm template cogstack-nginx deployment/charts/nginx --namespace cogstack ``` See each chart's README for the ConfigMaps, Secrets and storage needed before -installation. `values.env.yaml` files are optional `envsubst` inputs; render -their environment placeholders before supplying them to Helm. +installation. Run `make -C deployment helm-values-` for NiFi, NGINX, +OpenSearch, or OpenSearch Dashboards to render `values.env.yaml` into +`values.yaml` using `deployment/env/.env`. NGINX reads `nifi.env` for +its listener port and applies `nginx.env` when present. Docker memory sizes such +as `2g` render as `2Gi`. ## Validation and releases diff --git a/deployment/charts/ce/values.yaml b/deployment/charts/ce/values.yaml index 785d77e4..c05c860b 100644 --- a/deployment/charts/ce/values.yaml +++ b/deployment/charts/ce/values.yaml @@ -47,7 +47,7 @@ ocr-service: # -- OCR service image repository. # repository: cogstacksystems/ocr-service # -- OCR service image tag. - # tag: "1.1.1" + # tag: "latest" medcat-trainer: # -- Enable MedCAT Trainer deployment. diff --git a/deployment/charts/nginx/Chart.yaml b/deployment/charts/nginx/Chart.yaml index c47eff23..02dd4e50 100644 --- a/deployment/charts/nginx/Chart.yaml +++ b/deployment/charts/nginx/Chart.yaml @@ -1,6 +1,6 @@ apiVersion: v2 name: nginx -description: TLS reverse proxy for CogStack Apache NiFi +description: TLS reverse proxy for CogStack Kubernetes services # A chart can be either an 'application' or a 'library' chart. # diff --git a/deployment/charts/nginx/README.md b/deployment/charts/nginx/README.md index 3f9b9e2e..9d9472d6 100644 --- a/deployment/charts/nginx/README.md +++ b/deployment/charts/nginx/README.md @@ -1,75 +1,40 @@ -# NiFi NGINX Helm chart +# CogStack NGINX Helm chart -Deploys `cogstacksystems/nifi-nginx` as the TLS reverse proxy for the NiFi web -Service. It creates a Deployment, a Service, an upstream-settings ConfigMap and -an optional Ingress. +This chart exposes NGINX over HTTPS on port `443` through a `LoadBalancer` +Service. NGINX forwards requests to the cluster-internal HTTP Services in the +release namespace. -## Prerequisites - -Prepare these resources in the release namespace before installing: - -| Resource | Default name | Required contents | +| HTTPS path | Backend | Client authentication | | --- | --- | --- | -| ConfigMap | `nginx-env` | Deployment-specific NGINX environment settings. | -| ConfigMap | `nifi-env` | Shared NiFi environment settings. | -| Secret | `cogstack-root-ca` | `ca.crt`, the public CA for upstream TLS verification. | -| TLS Secret | `nginx-tls` | `tls.crt` and `tls.key` for the proxy certificate. | +| `/nifi/`, `/nifi-api/` | NiFi on `8080` | NGINX Basic Auth | +| `/opensearch/` | OpenSearch on `9200` | OpenSearch Security | +| `/dashboards/` | OpenSearch Dashboards on `5601` | Dashboards login | -The environment ConfigMap names are currently fixed in the template. Override -certificate Secret names with `tls.rootCASecret` and `tls.existingSecret`. -The chart references these inputs rather than creating them from host files. +Load `nginx-tls` with `make -C deployment k3s-load-certs-nginx`, or provide a +TLS Secret and set `tls.existingSecret`. The certificate must cover the hostname +or IP that clients use. `NGINX_TLS_NAMES` controls the names when generating a +certificate with `make -C deployment certs-nginx`. -By default, the proxy connects to -`cogstack-nifi-web..svc.cluster.local:8443`, which matches the -Service from `deployment/charts/nifi`. Set `nifi.host` and `nifi.port` -for another upstream. `nifi.tlsName` must match the upstream certificate's TLS -name; it defaults to `nifi`. +For NiFi, run `make -C deployment k3s-load-auth-nifi` to load the password hash +into `nifi-auth`. NGINX needs the `htpasswd` key in this Secret to grant access +to NiFi. -## Render and install - -Run from the platform repository root: +On K3s using ServiceLB, disable the bundled Traefik controller on all servers +with `--disable=traefik` to free port `443` for NGINX. ```bash -helm lint ./deployment/charts/nginx -helm template cogstack-nginx ./deployment/charts/nginx --namespace cogstack -helm upgrade --install cogstack-nginx ./deployment/charts/nginx \ - --namespace cogstack --create-namespace +make -C deployment helm-install-nginx ``` -Pass deployment overrides with `-f /path/to/nginx-values.yaml`. Set `image.tag` -to the image release required by the deployment. - -## Optional Ingress +For local access, set `service.type: ClusterIP` and forward the NGINX Service. -Ingress is disabled by default. Example deployment values: - -```yaml -ingress: - enabled: true - className: nginx - annotations: - nginx.ingress.kubernetes.io/backend-protocol: HTTPS - hosts: - - host: nifi.example.org - paths: - - path: / - pathType: Prefix - tls: - - secretName: nifi-ingress-tls - hosts: - - nifi.example.org +```bash +kubectl -n cogstack port-forward svc/cogstack-nginx 8443:443 ``` -Configure annotations for the selected Ingress controller and provide any -referenced TLS Secret in the namespace. The chart's Service uses HTTPS on -`nginx.internalPort`, which defaults to `8443`. - -## Environment-based values - -`values.yaml` contains reusable defaults. `values.env.yaml` is an optional -`envsubst` input for deployment ports, upstream TLS name and resource limits. -Populate all referenced variables and render it to a separate values file before -passing it to Helm; Helm does not expand `${VARIABLE}` placeholders. +Use `https://localhost:8443` with the trusted CA for the certificate. -The chart currently uses fixed `cogstack-nginx` resource names. Use separate -namespaces for independent deployments. +Override `clusterDomain` if needed, or set `nifi.host`, `opensearch.host`, +`dashboards.host` and their corresponding `port` values to use other upstreams. +The optional `nginx-env` ConfigMap, loaded by `helm-install-nginx`, provides +`NGINX_NIFI_SERVER_NAME` from `deployment/env/nginx.env`. diff --git a/deployment/charts/nginx/ci/ci-values.yaml b/deployment/charts/nginx/ci/ci-values.yaml index bcd196df..bca9dab2 100644 --- a/deployment/charts/nginx/ci/ci-values.yaml +++ b/deployment/charts/nginx/ci/ci-values.yaml @@ -1,3 +1,5 @@ # CI validates resource installation without deployment-owned ConfigMaps and Secrets. # Runtime startup requires those inputs and a separate application smoke test. replicaCount: 0 +service: + type: ClusterIP diff --git a/deployment/charts/nginx/nginx.conf.template b/deployment/charts/nginx/nginx.conf.template new file mode 100644 index 00000000..6f345f42 --- /dev/null +++ b/deployment/charts/nginx/nginx.conf.template @@ -0,0 +1,62 @@ +{{- $domain := printf "%s.svc.%s" .Release.Namespace .Values.clusterDomain -}} +resolver ${NGINX_LOCAL_RESOLVERS} valid=10s; +resolver_timeout 3s; + +upstream nifi { + zone nifi 64k; + server {{ .Values.nifi.host | default (printf "cogstack-nifi.%s" $domain) }}:{{ .Values.nifi.port }} resolve; +} +upstream opensearch { + zone opensearch 64k; + server {{ .Values.opensearch.host | default (printf "opensearch-cluster-master.%s" $domain) }}:{{ .Values.opensearch.port }} resolve; +} +upstream dashboards { + zone dashboards 64k; + server {{ .Values.dashboards.host | default (printf "opensearch-dashboards.%s" $domain) }}:{{ .Values.dashboards.port }} resolve; +} + +map $request_port $nifi_public_port { + "" 443; + default $request_port; +} + +server { + listen {{ .Values.nginx.internalPort }} ssl; + server_name ${NGINX_NIFI_SERVER_NAME}; + ssl_certificate /certificates/tls.crt; + ssl_certificate_key /certificates/tls.key; + ssl_protocols TLSv1.2 TLSv1.3; + absolute_redirect off; + + proxy_set_header Host $http_host; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-For $remote_addr; + + location = / { return 302 /nifi/; } + location = /nifi { return 308 /nifi/; } + + location /opensearch/ { + client_max_body_size 100m; + proxy_pass http://opensearch/; + } + + location /dashboards/ { + proxy_pass http://dashboards; + } + + location / { + auth_basic "NiFi"; + auth_basic_user_file /etc/nginx/nifi-auth/htpasswd; + proxy_set_header Authorization ""; + proxy_set_header Host $http_host; + proxy_set_header X-ProxyHost $host; + proxy_set_header X-ProxyPort $nifi_public_port; + proxy_set_header X-ProxyScheme $scheme; + proxy_set_header X-ProxyContextPath ""; + proxy_set_header X-Forwarded-Context ""; + proxy_set_header X-Forwarded-Prefix ""; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_redirect http://$http_host/ /; + proxy_pass http://nifi; + } +} diff --git a/deployment/charts/nginx/templates/configmap.yaml b/deployment/charts/nginx/templates/configmap.yaml index eeddd90f..3fb8f621 100644 --- a/deployment/charts/nginx/templates/configmap.yaml +++ b/deployment/charts/nginx/templates/configmap.yaml @@ -1,10 +1,7 @@ apiVersion: v1 kind: ConfigMap metadata: - name: cogstack-nginx-env + name: cogstack-nginx-config data: - NIFI_UPSTREAM_HOST: {{ default (printf "cogstack-nifi-web.%s.svc.cluster.local" .Release.Namespace) .Values.nifi.host | quote }} - NIFI_UPSTREAM_PORT: {{ .Values.nifi.port | quote }} - NIFI_UPSTREAM_TLS_NAME: {{ .Values.nifi.tlsName | quote }} - NIFI_INTERNAL_PORT_NGINX: {{ .Values.nginx.internalPort | quote }} - NIFI_WEB_PROXY_PORT: {{ .Values.nginx.internalPort | quote }} + nginx.conf.template: | + {{- tpl (.Files.Get "nginx.conf.template") . | nindent 4 }} diff --git a/deployment/charts/nginx/templates/deployment.yaml b/deployment/charts/nginx/templates/deployment.yaml index c69833c9..26961b2f 100644 --- a/deployment/charts/nginx/templates/deployment.yaml +++ b/deployment/charts/nginx/templates/deployment.yaml @@ -23,42 +23,43 @@ spec: imagePullPolicy: {{ .Values.image.pullPolicy }} ports: - - containerPort: {{ .Values.nginx.internalPort }} + - name: https + containerPort: {{ .Values.nginx.internalPort }} envFrom: - configMapRef: name: nginx-env - - configMapRef: - name: nifi-env - - configMapRef: - name: cogstack-nginx-env + optional: true volumeMounts: + - name: config + mountPath: /etc/nginx/templates/nifi + readOnly: true - name: tls mountPath: /certificates readOnly: true + - name: nifi-auth + mountPath: /etc/nginx/nifi-auth + readOnly: true readinessProbe: - exec: - command: ["/usr/local/bin/cogstack-nginx-healthcheck.sh", "ready"] - timeoutSeconds: 10 + tcpSocket: + port: https resources: {{- toYaml .Values.resources | nindent 12 }} volumes: + - name: config + configMap: + name: cogstack-nginx-config - name: tls - projected: - sources: - - secret: - name: {{ .Values.tls.rootCASecret }} - items: - - key: ca.crt - path: root/root-ca.pem - - secret: - name: {{ .Values.tls.existingSecret }} - items: - - key: tls.crt - path: nifi/nifi.pem - - key: tls.key - path: nifi/nifi.key + secret: + secretName: {{ .Values.tls.existingSecret }} + - name: nifi-auth + secret: + secretName: nifi-auth + optional: true + items: + - key: htpasswd + path: htpasswd diff --git a/deployment/charts/nginx/templates/ingress.yaml b/deployment/charts/nginx/templates/ingress.yaml deleted file mode 100644 index e18130c2..00000000 --- a/deployment/charts/nginx/templates/ingress.yaml +++ /dev/null @@ -1,41 +0,0 @@ -{{- if .Values.ingress.enabled -}} -apiVersion: networking.k8s.io/v1 -kind: Ingress -metadata: - name: cogstack-nginx - labels: - app: cogstack-nginx - {{- with .Values.ingress.annotations }} - annotations: - {{- toYaml . | nindent 4 }} - {{- end }} -spec: - {{- with .Values.ingress.className }} - ingressClassName: {{ . }} - {{- end }} - {{- if .Values.ingress.tls }} - tls: - {{- range .Values.ingress.tls }} - - hosts: - {{- range .hosts }} - - {{ . | quote }} - {{- end }} - secretName: {{ .secretName }} - {{- end }} - {{- end }} - rules: - {{- range .Values.ingress.hosts }} - - host: {{ .host | quote }} - http: - paths: - {{- range .paths }} - - path: {{ .path }} - pathType: {{ .pathType | default "Prefix" }} - backend: - service: - name: cogstack-nginx - port: - number: {{ $.Values.nginx.internalPort }} - {{- end }} - {{- end }} -{{- end }} diff --git a/deployment/charts/nginx/templates/service.yaml b/deployment/charts/nginx/templates/service.yaml index 1c01190d..30e9d572 100644 --- a/deployment/charts/nginx/templates/service.yaml +++ b/deployment/charts/nginx/templates/service.yaml @@ -8,6 +8,6 @@ spec: app: cogstack-nginx ports: - name: https - port: {{ .Values.nginx.internalPort }} - targetPort: {{ .Values.nginx.internalPort }} + port: {{ .Values.service.port }} + targetPort: https protocol: TCP diff --git a/deployment/charts/nginx/values.env.yaml b/deployment/charts/nginx/values.env.yaml index 7b1227fa..efcb1dbb 100644 --- a/deployment/charts/nginx/values.env.yaml +++ b/deployment/charts/nginx/values.env.yaml @@ -1,29 +1,31 @@ replicaCount: 1 image: - repository: cogstacksystems/nifi-nginx + repository: cogstacksystems/nginx tag: "latest" pullPolicy: Always nginx: internalPort: ${NIFI_INTERNAL_PORT_NGINX} +clusterDomain: cluster.local + nifi: - # Empty uses cogstack-nifi-web..svc.cluster.local; override with a full DNS name. host: "" - port: ${NIFI_INTERNAL_PORT} - tlsName: ${NIFI_UPSTREAM_TLS_NAME} + port: 8080 +opensearch: + host: "" + port: 9200 +dashboards: + host: "" + port: 5601 tls: - rootCASecret: cogstack-root-ca - # NGINX's own tls.crt/tls.key retain the image's existing /certificates/nifi paths. existingSecret: nginx-tls service: - type: ClusterIP - -ingress: - enabled: false + type: LoadBalancer + port: 443 resources: requests: diff --git a/deployment/charts/nginx/values.yaml b/deployment/charts/nginx/values.yaml index 7fc8e7df..3fd8f548 100644 --- a/deployment/charts/nginx/values.yaml +++ b/deployment/charts/nginx/values.yaml @@ -1,29 +1,31 @@ replicaCount: 1 image: - repository: cogstacksystems/nifi-nginx + repository: cogstacksystems/nginx tag: "latest" pullPolicy: Always nginx: internalPort: 8443 +clusterDomain: cluster.local + nifi: - # Empty uses cogstack-nifi-web..svc.cluster.local; override with a full DNS name. host: "" - port: 8443 - tlsName: nifi + port: 8080 +opensearch: + host: "" + port: 9200 +dashboards: + host: "" + port: 5601 tls: - rootCASecret: cogstack-root-ca - # NGINX's own tls.crt/tls.key retain the image's existing /certificates/nifi paths. existingSecret: nginx-tls service: - type: ClusterIP - -ingress: - enabled: false + type: LoadBalancer + port: 443 resources: requests: diff --git a/deployment/charts/nifi/README.md b/deployment/charts/nifi/README.md index ba4c074e..52a35b4f 100644 --- a/deployment/charts/nifi/README.md +++ b/deployment/charts/nifi/README.md @@ -1,29 +1,22 @@ # CogStack NiFi Helm chart -Deploys the CogStack Apache NiFi image with a StatefulSet, headless and web -Services, a TLS configuration ConfigMap, and persistent storage for configuration -and NiFi repositories. Application sources and the Dockerfile live in -`apps/nifi/`. +Deploys the CogStack Apache NiFi image with a StatefulSet, cluster-internal HTTP +Services, and persistent storage for configuration and NiFi repositories. +NGINX handles HTTPS and login for the UI and API. [NGINX chart](../nginx/README.md) ## Prerequisites -Prepare these resources in the release namespace before installing: +Run `make -C deployment k3s-load-auth-nifi` to create or update `nifi-auth` with +the NiFi flow encryption key and the NGINX `htpasswd` entry. Set +`NIFI_SINGLE_USER_CREDENTIALS_USERNAME` and `NIFI_SINGLE_USER_CREDENTIALS_PASSWORD` +in the environment or `deployment/env/authentication.env`. The loader uses +OpenSSL and prompts for a deployment password if needed. It preserves the +existing `NIFI_SENSITIVE_PROPS_KEY` when upgrading. -| Resource | Default name | Required contents | -| --- | --- | --- | -| ConfigMap | `nifi-env` | NiFi runtime environment settings for the deployment. | -| Secret | `nifi-auth` | Apache startup environment variables for login credentials, TLS passwords, the sensitive-properties key and the matching initial admin identity. | -| Secret | `cogstack-root-ca` | `ca.crt` and `truststore.jks`; the public CA and shared truststore. | -| Secret | `nifi-tls` | `nifi-keystore.jks`; the NiFi node certificate and private key. | - -Set `certificates.rootCASecret` and `certificates.existingSecret` to use different -certificate Secret names. The environment ConfigMap and authentication Secret -names are currently fixed in the workload template. - -The chart references these resources; it does not read host environment files or -create authentication or certificate Secrets. Keep private CA signing material -outside the pod. The namespace also needs a StorageClass or suitable -pre-provisioned persistent volumes for the six per-replica claims. +The namespace needs a StorageClass or persistent volumes for the six claims per +replica. NiFi grants full access in HTTP mode. Use a cluster that enforces +NetworkPolicy so the chart can restrict access to the NGINX pods in the same +namespace. ## Render and install @@ -40,14 +33,7 @@ Pass deployment overrides with `-f /path/to/nifi-values.yaml`. The default image is `cogstacksystems/nifi:latest`; set `image.tag` to the image release required by the deployment. -For local access: - -```bash -kubectl -n cogstack port-forward svc/cogstack-nifi-web 8443:8443 -``` - -Open `https://localhost:8443/nifi/` using the deployment's trusted CA and -credentials. +Use the NGINX `/nifi/` and `/nifi-api/` routes with HTTP Basic authentication. ## Persistent configuration and data @@ -74,19 +60,21 @@ StorageClass and access modes. Existing StatefulSet claim templates have Kubernetes immutability constraints; plan storage changes and backups separately. Drivers, schemas and Python processors are bundled by the NiFi image. Startup -and readiness probes call its `/opt/nifi/scripts/cogstack-healthcheck.sh` -with the projected public CA. +and readiness probes use NiFi's loopback HTTP endpoint. ## Environment-based values -`values.yaml` contains reusable defaults. `values.env.yaml` is an optional -`envsubst` input for deployment-specific UID/GID, ports and resource limits. -Populate all referenced variables and render it to a separate values file before -passing it to Helm; Helm does not expand `${VARIABLE}` placeholders. +Run `make -C deployment helm-values-nifi` to render `values.env.yaml` using +`deployment/env/nifi.env`. Set `NIFI_K3S_WHITELIST` to comma-separated names +from `kubectl get nodes` to populate `allowedNodes`. An empty list allows any +otherwise eligible node. ## Resource names -The chart currently uses fixed `cogstack-nifi` workload and headless Service names -and a `cogstack-nifi-web` web Service. Use separate namespaces for independent -deployments. Increasing `replicaCount` also requires appropriate NiFi cluster -configuration, node identities and certificates in the supplied runtime inputs. +The `cogstack-nifi` StatefulSet uses `cogstack-nifi-headless` for pod DNS. NGINX +connects to the `cogstack-nifi` ClusterIP Service on port `8080`. Use separate +namespaces for independent deployments. + +Upgrades from the previous Service names require recreating the StatefulSet and +the old `cogstack-nifi` headless Service. Keep the existing PVCs for the recreated +StatefulSet. diff --git a/deployment/charts/nifi/templates/networkpolicy.yaml b/deployment/charts/nifi/templates/networkpolicy.yaml new file mode 100644 index 00000000..cc178c64 --- /dev/null +++ b/deployment/charts/nifi/templates/networkpolicy.yaml @@ -0,0 +1,17 @@ +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: cogstack-nifi +spec: + podSelector: + matchLabels: + app: cogstack-nifi + policyTypes: [Ingress] + ingress: + - from: + - podSelector: + matchLabels: + app: cogstack-nginx + ports: + - protocol: TCP + port: {{ .Values.nifi.internalPort }} diff --git a/deployment/charts/nifi/templates/service.yaml b/deployment/charts/nifi/templates/service.yaml index 387a45db..4065f680 100644 --- a/deployment/charts/nifi/templates/service.yaml +++ b/deployment/charts/nifi/templates/service.yaml @@ -1,24 +1,25 @@ apiVersion: v1 kind: Service metadata: - name: cogstack-nifi + name: cogstack-nifi-headless spec: + type: ClusterIP clusterIP: None selector: app: cogstack-nifi ports: - - name: https + - name: http port: {{ .Values.nifi.internalPort }} --- apiVersion: v1 kind: Service metadata: - name: cogstack-nifi-web + name: cogstack-nifi spec: type: ClusterIP selector: app: cogstack-nifi ports: - - name: https + - name: http port: {{ .Values.nifi.internalPort }} - targetPort: {{ .Values.nifi.internalPort }} + targetPort: http diff --git a/deployment/charts/nifi/templates/statefulset.yaml b/deployment/charts/nifi/templates/statefulset.yaml index 815c814d..4cbb1a48 100644 --- a/deployment/charts/nifi/templates/statefulset.yaml +++ b/deployment/charts/nifi/templates/statefulset.yaml @@ -5,7 +5,7 @@ metadata: name: cogstack-nifi spec: - serviceName: cogstack-nifi + serviceName: cogstack-nifi-headless replicas: {{ .Values.replicaCount }} persistentVolumeClaimRetentionPolicy: whenDeleted: Retain @@ -17,9 +17,19 @@ spec: metadata: labels: app: cogstack-nifi - annotations: - checksum/tls-config: {{ include (print $.Template.BasePath "/tls-configmap.yaml") . | sha256sum }} spec: + {{- with .Values.allowedNodes }} + affinity: + nodeAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + nodeSelectorTerms: + {{- range . }} + - matchFields: + - key: metadata.name + operator: In + values: [{{ . | quote }}] + {{- end }} + {{- end }} securityContext: {{- toYaml .Values.podSecurityContext | nindent 8 }} terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }} @@ -69,19 +79,32 @@ spec: - name: nifi securityContext: {{- toYaml .Values.securityContext | nindent 12 }} - envFrom: - - configMapRef: - name: nifi-env - - configMapRef: - name: cogstack-nifi-tls-env - # Login/password variables and matching INITIAL_ADMIN_IDENTITY only; no certificate files. - - secretRef: - name: nifi-auth + env: + - name: NIFI_SENSITIVE_PROPS_KEY + valueFrom: + secretKeyRef: + name: nifi-auth + key: NIFI_SENSITIVE_PROPS_KEY + command: ["/bin/sh", "-ec"] + args: + - | + # The upstream container entrypoint always configures HTTPS. + . /opt/nifi/scripts/common.sh + prop_replace 'nifi.web.http.host' '0.0.0.0' + prop_replace 'nifi.web.http.port' '{{ .Values.nifi.internalPort | int }}' + prop_replace 'nifi.remote.input.secure' 'false' + prop_replace 'nifi.security.autoreload.enabled' 'false' + sed -i -E \ + -e 's/^(nifi\.web\.https\.(host|port))=.*/\1=/' \ + -e 's/^(nifi\.security\.(keystore[^=]*|truststore[^=]*|keyPasswd))=.*/\1=/' \ + -e 's/^(nifi\.security\.user\.(authorizer|login\.identity\.provider))=.*/\1=/' "$nifi_props_file" + prop_replace 'nifi.sensitive.props.key' "$NIFI_SENSITIVE_PROPS_KEY" + uncomment 'nifi.python.command' "$nifi_props_file" + prop_replace 'nifi.python.extensions.source.directory.default' "$NIFI_HOME/python_extensions" + prop_replace 'nifi.nar.library.autoload.directory' "$NIFI_HOME/nar_extensions" + exec "$NIFI_HOME/bin/nifi.sh" run volumeMounts: - - name: tls - mountPath: /certificates - readOnly: true {{- range $directory := $directories }} - name: {{ $directory | replace "_" "-" }} mountPath: /opt/nifi/nifi-current/{{ $directory }} @@ -90,36 +113,19 @@ spec: image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" imagePullPolicy: {{ .Values.image.pullPolicy }} ports: - - containerPort: {{ .Values.nifi.internalPort | int }} + - name: http + containerPort: {{ .Values.nifi.internalPort | int }} startupProbe: - exec: - command: ["/opt/nifi/scripts/cogstack-healthcheck.sh", "startup"] + exec: &healthcheck + command: ["curl", "-fsS", "--noproxy", "*", "-o", "/dev/null", "http://127.0.0.1:{{ .Values.nifi.internalPort }}/nifi-api/authentication/configuration"] timeoutSeconds: 10 failureThreshold: 30 readinessProbe: - exec: - command: ["/opt/nifi/scripts/cogstack-healthcheck.sh", "ready"] + exec: *healthcheck timeoutSeconds: 10 - resources: + resources: {{- toYaml .Values.resources | nindent 12 }} - volumes: - - name: tls - projected: - sources: - - secret: - name: {{ .Values.certificates.rootCASecret }} - items: - - key: ca.crt - path: root/root-ca.pem - - key: truststore.jks - path: nifi/nifi-truststore.jks - - secret: - name: {{ .Values.certificates.existingSecret }} - items: - - key: nifi-keystore.jks - path: nifi/nifi-keystore.jks - volumeClaimTemplates: {{- range $directory := $directories }} {{- $claim := required (printf "persistence.volumes.%s is required" $directory) (index $.Values.persistence.volumes $directory) }} diff --git a/deployment/charts/nifi/templates/tls-configmap.yaml b/deployment/charts/nifi/templates/tls-configmap.yaml deleted file mode 100644 index 89669cff..00000000 --- a/deployment/charts/nifi/templates/tls-configmap.yaml +++ /dev/null @@ -1,17 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - name: cogstack-nifi-tls-env -data: - AUTH: tls - NIFI_SECURITY_USER_AUTHORIZER: managed-authorizer - NIFI_SECURITY_USER_LOGIN_IDENTITY_PROVIDER: single-user-provider - NIFI_WEB_HTTPS_PORT: {{ .Values.nifi.internalPort | quote }} - # Kubernetes uses /certificates; Compose retains /security/certificates. - NIFI_KEYSTORE_PATH: /certificates/nifi/nifi-keystore.jks - NIFI_TRUSTSTORE_PATH: /certificates/nifi/nifi-truststore.jks - NIFI_HEALTHCHECK_CA_FILE: /certificates/root/root-ca.pem - KEYSTORE_PATH: /certificates/nifi/nifi-keystore.jks - TRUSTSTORE_PATH: /certificates/nifi/nifi-truststore.jks - KEYSTORE_TYPE: JKS - TRUSTSTORE_TYPE: JKS diff --git a/deployment/charts/nifi/values.env.yaml b/deployment/charts/nifi/values.env.yaml index cf3b53f5..05d4c419 100644 --- a/deployment/charts/nifi/values.env.yaml +++ b/deployment/charts/nifi/values.env.yaml @@ -2,6 +2,7 @@ nameOverride: "" fullnameOverride: "" replicaCount: 1 +allowedNodes: ${NIFI_K3S_ALLOWED_NODES} image: repository: cogstacksystems/nifi @@ -23,14 +24,7 @@ podSecurityContext: fsGroupChangePolicy: OnRootMismatch nifi: - internalPort: ${NIFI_INTERNAL_PORT} - outputPort: ${NIFI_OUTPUT_PORT} - -certificates: - # Shared CA only: ca.crt and truststore.jks; never the root private-key keystore. - rootCASecret: cogstack-root-ca - # NiFi's JKS contains its certificate and private key; the CA truststore is shared. - existingSecret: nifi-tls + internalPort: 8080 persistence: # null uses the cluster default; "" selects no StorageClass (pre-provisioned PVs). diff --git a/deployment/charts/nifi/values.yaml b/deployment/charts/nifi/values.yaml index 9afa52be..63ebf65e 100644 --- a/deployment/charts/nifi/values.yaml +++ b/deployment/charts/nifi/values.yaml @@ -2,6 +2,7 @@ nameOverride: "" fullnameOverride: "" replicaCount: 1 +allowedNodes: [] image: repository: cogstacksystems/nifi @@ -23,14 +24,7 @@ podSecurityContext: fsGroupChangePolicy: OnRootMismatch nifi: - internalPort: 8443 - outputPort: 8082 - -certificates: - # Shared CA only: ca.crt and truststore.jks; never the root private-key keystore. - rootCASecret: cogstack-root-ca - # NiFi's JKS contains its certificate and private key; the CA truststore is shared. - existingSecret: nifi-tls + internalPort: 8080 persistence: # null uses the cluster default; "" selects no StorageClass (pre-provisioned PVs). diff --git a/deployment/charts/ocr-service/Chart.yaml b/deployment/charts/ocr-service/Chart.yaml index fbcd1e41..58d1d315 100644 --- a/deployment/charts/ocr-service/Chart.yaml +++ b/deployment/charts/ocr-service/Chart.yaml @@ -21,7 +21,7 @@ version: 0.1.0 # incremented each time you make changes to the application. Versions are not expected to # follow Semantic Versioning. They should reflect the version the application is using. # It is recommended to use it with quotes. -appVersion: "1.1.1" +appVersion: "latest" keywords: - cogstack diff --git a/deployment/charts/opensearch-dashboards/.gitignore b/deployment/charts/opensearch-dashboards/.gitignore new file mode 100644 index 00000000..0ad51707 --- /dev/null +++ b/deployment/charts/opensearch-dashboards/.gitignore @@ -0,0 +1 @@ +/charts/*.tgz diff --git a/deployment/charts/opensearch-dashboards/Chart.lock b/deployment/charts/opensearch-dashboards/Chart.lock new file mode 100644 index 00000000..818c76c0 --- /dev/null +++ b/deployment/charts/opensearch-dashboards/Chart.lock @@ -0,0 +1,6 @@ +dependencies: +- name: opensearch-dashboards + repository: https://opensearch-project.github.io/helm-charts/ + version: 3.9.0 +digest: sha256:d2da97a34837a14000abebae3ec47668d475081d9d8d0ac1ef6f8bbd4cdff9cf +generated: "2026-11-24T22:01:58.231528Z" diff --git a/deployment/charts/opensearch-dashboards/Chart.yaml b/deployment/charts/opensearch-dashboards/Chart.yaml new file mode 100644 index 00000000..8a1baf3e --- /dev/null +++ b/deployment/charts/opensearch-dashboards/Chart.yaml @@ -0,0 +1,13 @@ +apiVersion: v2 +name: opensearch-dashboards +description: Standalone OpenSearch Dashboards Helm chart +type: application +version: 0.1.0 + +maintainers: + - name: CogStack + +dependencies: + - name: opensearch-dashboards + version: "3.9.0" + repository: https://opensearch-project.github.io/helm-charts/ diff --git a/deployment/charts/opensearch-dashboards/README.md b/deployment/charts/opensearch-dashboards/README.md new file mode 100644 index 00000000..6e96fb3b --- /dev/null +++ b/deployment/charts/opensearch-dashboards/README.md @@ -0,0 +1,43 @@ +# Standalone OpenSearch Dashboards + +Deploy Dashboards in the same namespace as OpenSearch and NGINX. Dashboards +serves HTTP on its ClusterIP Service and connects to OpenSearch over HTTP. +Clients use `/dashboards/` over HTTPS through NGINX. The session cookie is Secure. + +From the repository root, load the `dashboards-auth` Secret in the namespace set +in `deployment/env/general.env`. The target uses `OPENSEARCH_KIBANA_PASSWORD` from the +environment, `deployment/env/authentication.env`, or the existing Secret, and +prompts if it needs a password. It generates a cookie key on first use and +reuses it on subsequent runs. Load this Secret before the OpenSearch bootstrap +to share the `kibanaserver` password. If OpenSearch is already initialized, use +its current `kibanaserver` password. + +```bash +make -C deployment k3s-load-auth-opensearch-dashboards +make -C deployment helm-install-opensearch-dashboards +``` + +The default values use `dashboards-auth` and `.kibana`, which matches the +built-in `kibana_server` role. Keep any existing saved-object index override +when upgrading. If you supply a custom `opensearch_dashboards.yml`, set +`server.ssl.enabled: false`, `server.basePath: /dashboards`, +`server.rewriteBasePath: true` and `opensearch_security.cookie.secure: true`. +Use `opensearch_security.cookie.password: ${COOKIE_PASS}` for the cookie key +from the Secret. + +```bash +helm repo add opensearch https://opensearch-project.github.io/helm-charts/ +helm dependency build deployment/charts/opensearch-dashboards +helm upgrade --install opensearch-dashboards deployment/charts/opensearch-dashboards -n cogstack +``` + +Set overrides under `opensearch-dashboards:` in your values file. Use +`--set-file` to supply a complete Kubernetes configuration. + +```bash +helm upgrade --install opensearch-dashboards deployment/charts/opensearch-dashboards -n cogstack \ + --set-file 'opensearch-dashboards.config.opensearch_dashboards\.yml=/path/to/kubernetes/opensearch_dashboards.yml' +``` + +Dashboards inherits its Kubernetes templates from the upstream chart. +[Upstream values](https://github.com/opensearch-project/helm-charts/blob/main/charts/opensearch-dashboards/values.yaml) diff --git a/deployment/charts/opensearch-dashboards/ci/ci-values.yaml b/deployment/charts/opensearch-dashboards/ci/ci-values.yaml new file mode 100644 index 00000000..b7e22efb --- /dev/null +++ b/deployment/charts/opensearch-dashboards/ci/ci-values.yaml @@ -0,0 +1,3 @@ +# The login smoke test provides the Secret and OpenSearch service. +opensearch-dashboards: + replicaCount: 0 diff --git a/deployment/charts/opensearch-dashboards/values.env.yaml b/deployment/charts/opensearch-dashboards/values.env.yaml new file mode 100644 index 00000000..d26c6d81 --- /dev/null +++ b/deployment/charts/opensearch-dashboards/values.env.yaml @@ -0,0 +1,20 @@ +opensearch-dashboards: + opensearchHosts: http://opensearch-cluster-master:9200 + opensearchAccount: + secret: dashboards-auth + config: + opensearch_dashboards.yml: + server.ssl.enabled: false + server.basePath: /dashboards + server.rewriteBasePath: true + opensearchDashboards.index: .kibana + opensearch.requestHeadersAllowlist: [authorization, securitytenant] + opensearch_security.cookie.secure: true + opensearch_security.cookie.password: '{{ "$" }}{COOKIE_PASS}' + resources: + requests: + cpu: "${OPENSEARCH_DASHBOARDS_DOCKER_CPU_MIN}" + memory: "${OPENSEARCH_DASHBOARDS_DOCKER_RAM}" + limits: + cpu: "${OPENSEARCH_DASHBOARDS_DOCKER_CPU_MAX}" + memory: "${OPENSEARCH_DASHBOARDS_DOCKER_RAM}" diff --git a/deployment/charts/opensearch-dashboards/values.yaml b/deployment/charts/opensearch-dashboards/values.yaml new file mode 100644 index 00000000..84c17a08 --- /dev/null +++ b/deployment/charts/opensearch-dashboards/values.yaml @@ -0,0 +1,20 @@ +opensearch-dashboards: + opensearchHosts: http://opensearch-cluster-master:9200 + opensearchAccount: + secret: dashboards-auth + config: + opensearch_dashboards.yml: + server.ssl.enabled: false + server.basePath: /dashboards + server.rewriteBasePath: true + opensearchDashboards.index: .kibana + opensearch.requestHeadersAllowlist: [authorization, securitytenant] + opensearch_security.cookie.secure: true + opensearch_security.cookie.password: '{{ "$" }}{COOKIE_PASS}' + resources: + requests: + cpu: "1" + memory: "1Gi" + limits: + cpu: "1" + memory: "1Gi" diff --git a/deployment/charts/opensearch/.gitignore b/deployment/charts/opensearch/.gitignore new file mode 100644 index 00000000..0ad51707 --- /dev/null +++ b/deployment/charts/opensearch/.gitignore @@ -0,0 +1 @@ +/charts/*.tgz diff --git a/deployment/charts/opensearch/Chart.lock b/deployment/charts/opensearch/Chart.lock new file mode 100644 index 00000000..ad9ec22a --- /dev/null +++ b/deployment/charts/opensearch/Chart.lock @@ -0,0 +1,6 @@ +dependencies: +- name: opensearch + repository: https://opensearch-project.github.io/helm-charts/ + version: 3.9.0 +digest: sha256:5df49c2ae6f2d24003102623e6b74d44f67c74a5846d9ffe53d12361da52deed +generated: "2026-11-24T22:01:57.799564Z" diff --git a/deployment/charts/opensearch/Chart.yaml b/deployment/charts/opensearch/Chart.yaml new file mode 100644 index 00000000..a56ad989 --- /dev/null +++ b/deployment/charts/opensearch/Chart.yaml @@ -0,0 +1,13 @@ +apiVersion: v2 +name: opensearch +description: Standalone OpenSearch Helm chart +type: application +version: 0.1.0 + +maintainers: + - name: CogStack + +dependencies: + - name: opensearch + version: "3.9.0" + repository: https://opensearch-project.github.io/helm-charts/ diff --git a/deployment/charts/opensearch/README.md b/deployment/charts/opensearch/README.md new file mode 100644 index 00000000..42d2a180 --- /dev/null +++ b/deployment/charts/opensearch/README.md @@ -0,0 +1,101 @@ +# Standalone OpenSearch + +This chart installs the upstream OpenSearch StatefulSet as its own Helm release. +The upstream chart supplies the Kubernetes templates. Set overrides under +`opensearch:` in your values file. + +## Install + +OpenSearch serves HTTP on the internal `opensearch-cluster-master` Service. +OpenSearch Security requires TLS on its node transport. Generate the shared +node certificate with an existing CA and load it into the release namespace. +Use an absolute `SECURITY_DIR` for a custom certificate directory. +[Cluster prerequisites](https://docs.opensearch.org/latest/opensearch/install/helm/#prerequisites) + +```bash +make -C deployment -j1 certs-opensearch-nodes k3s-load-certs-opensearch NODES=opensearch-shared +make -C deployment helm-install-opensearch-stack +``` + +The stack target prepares the authentication Secrets, then installs OpenSearch +and Dashboards. It uses `KUBE_NAMESPACE` from `deployment/env/general.env`. + +To install OpenSearch on its own, prepare the bootstrap Secret before installing. + +```bash +make -C deployment k3s-load-auth-opensearch +make -C deployment helm-install-opensearch +``` + +The loader requires `htpasswd`. Set `OPENSEARCH_KIBANA_PASSWORD` for +`kibanaserver` in the environment or `deployment/env/authentication.env`. It +also accepts the password from a preexisting `dashboards-auth` Secret. Set +`OPENSEARCH_NIFI_PASSWORD`, `OPENSEARCH_PIPELINE_PASSWORD`, or +`OPENSEARCH_ANALYST_PASSWORD` to create `nifi`, `cogstack_pipeline`, or +`cogstack_user`. Set `OPENSEARCH_ADMIN_PASSWORD` to create a password-based +`admin` with the `all_access` role. Use `OPENSEARCH_AUTH_FILE` to select another +credentials file. + +OpenSearch uses `opensearch-security-bootstrap` to initialize an empty Security +index. For an existing cluster that uses an admin certificate, create a +password-authenticated administrator in the existing Security index before +switching to HTTP. Use the current `kibanaserver` password when loading the +Dashboards Secret. + +Clients in the release namespace can use `http://opensearch-cluster-master:9200`. +External clients use the NGINX `/opensearch/` route over HTTPS. + +## Replicas + +Set `OPENSEARCH_K3S_REPLICA_COUNT` in `deployment/env/opensearch.env` +and run `make -C deployment helm-values-opensearch` before installing or +scaling up with Helm. The default is one replica. Required pod anti-affinity +places each replica on a separate Kubernetes node, so two replicas require +two schedulable nodes. + +To exclude nodes, set `OPENSEARCH_K3S_BLACKLIST` in the same env file to +comma-separated names from `kubectl get nodes`, such as `worker-1,worker-2`. +An empty list allows all otherwise eligible nodes. Rerender the values and +upgrade the release after editing the list. A replica with a PVC tied to an +excluded node can stay Pending. + +Both members of a two-node cluster are needed for quorum. Use three replicas +on three nodes to tolerate one node failure. +[OpenSearch quorum rules](https://docs.opensearch.org/3.9/tuning-your-cluster/discovery-cluster-formation/voting-quorums/) + +## Storage + +The StatefulSet creates one 8 GiB PVC per pod and mounts it at +`/usr/share/opensearch/data`. Set `opensearch.persistence.size` and +`opensearch.persistence.storageClass` before installing. The first command +shows the claim template. The second lists claims after installation. + +```bash +helm template opensearch deployment/charts/opensearch -n cogstack \ + --show-only charts/opensearch/templates/statefulset.yaml +kubectl -n cogstack get pvc +``` + +## Configuration + +`helm-install-opensearch` loads the bundled configuration with `--set-file` and +applies `OPENSEARCH_LOG_LEVEL` from `deployment/env/opensearch.env`. The chart +sets `plugins.security.ssl.http.enabled=false` and enables Security bootstrap +from the mounted policy through the OpenSearch container's settings environment. + +### Custom values + +For direct Helm installs, build the dependency and load a config file. The +release also requires the `opensearch-security-bootstrap` and +`opensearch-node-tls` Secrets in the same namespace. + +```bash +chart=deployment/charts/opensearch +helm repo add opensearch https://opensearch-project.github.io/helm-charts/ +helm dependency build "$chart" +helm upgrade --install opensearch "$chart" -n cogstack \ + --set-file "opensearch.config.opensearch\.yml=$chart/config/opensearch.yml" +``` + +For a packaged chart, set `chart=./opensearch` after extracting it. The archive +includes the chart dependency, OpenSearch configuration, and Security policy. diff --git a/deployment/charts/opensearch/ci/ci-values.yaml b/deployment/charts/opensearch/ci/ci-values.yaml new file mode 100644 index 00000000..933112e8 --- /dev/null +++ b/deployment/charts/opensearch/ci/ci-values.yaml @@ -0,0 +1,13 @@ +opensearch: + replicas: 1 + secretMounts: [] + securityConfig: + internalUsersSecret: "" + rolesSecret: "" + rolesMappingSecret: "" + tenantsSecret: "" + extraEnvs: + - name: OPENSEARCH_INITIAL_ADMIN_PASSWORD + value: "CogStack-Chart-Test9!" + - name: plugins.security.ssl.http.enabled + value: "false" diff --git a/deployment/charts/opensearch/config/opensearch.yml b/deployment/charts/opensearch/config/opensearch.yml new file mode 120000 index 00000000..cc4c4ad4 --- /dev/null +++ b/deployment/charts/opensearch/config/opensearch.yml @@ -0,0 +1 @@ +../../../../apps/opensearch/config/opensearch.yml \ No newline at end of file diff --git a/deployment/charts/opensearch/security b/deployment/charts/opensearch/security new file mode 120000 index 00000000..b8f68618 --- /dev/null +++ b/deployment/charts/opensearch/security @@ -0,0 +1 @@ +../../../apps/opensearch/security \ No newline at end of file diff --git a/deployment/charts/opensearch/values.env.yaml b/deployment/charts/opensearch/values.env.yaml new file mode 100644 index 00000000..8ee04943 --- /dev/null +++ b/deployment/charts/opensearch/values.env.yaml @@ -0,0 +1,38 @@ +opensearch: + replicas: ${OPENSEARCH_K3S_REPLICA_COUNT} + protocol: http + antiAffinity: hard + nodeAffinity: ${OPENSEARCH_K3S_NODE_AFFINITY} + # Each StatefulSet pod gets its own claim from the cluster's default StorageClass. + persistence: + enabled: true + size: 8Gi + # Supply opensearch.yml with --set-file as shown in the README. + extraEnvs: + - name: DISABLE_INSTALL_DEMO_CONFIG + value: "true" + - name: plugins.security.ssl.http.enabled + value: "false" + - name: plugins.security.allow_default_init_securityindex + value: "true" + envFrom: + - configMapRef: + name: opensearch-env + optional: true + secretMounts: + - name: node-tls + secretName: opensearch-node-tls + path: /usr/share/opensearch/config/tls + defaultMode: 0440 + securityConfig: + internalUsersSecret: opensearch-security-bootstrap + rolesSecret: opensearch-security-bootstrap + rolesMappingSecret: opensearch-security-bootstrap + tenantsSecret: opensearch-security-bootstrap + resources: + requests: + cpu: "${OPENSEARCH_DOCKER_CPU_MIN}" + memory: "${OPENSEARCH_DOCKER_RAM}" + limits: + cpu: "${OPENSEARCH_DOCKER_CPU_MAX}" + memory: "${OPENSEARCH_DOCKER_RAM}" diff --git a/deployment/charts/opensearch/values.yaml b/deployment/charts/opensearch/values.yaml new file mode 100644 index 00000000..3f8e9a52 --- /dev/null +++ b/deployment/charts/opensearch/values.yaml @@ -0,0 +1,38 @@ +opensearch: + replicas: 1 + protocol: http + antiAffinity: hard + nodeAffinity: {} + # Each StatefulSet pod gets its own claim from the cluster's default StorageClass. + persistence: + enabled: true + size: 8Gi + # Supply opensearch.yml with --set-file as shown in the README. + extraEnvs: + - name: DISABLE_INSTALL_DEMO_CONFIG + value: "true" + - name: plugins.security.ssl.http.enabled + value: "false" + - name: plugins.security.allow_default_init_securityindex + value: "true" + envFrom: + - configMapRef: + name: opensearch-env + optional: true + secretMounts: + - name: node-tls + secretName: opensearch-node-tls + path: /usr/share/opensearch/config/tls + defaultMode: 0440 + securityConfig: + internalUsersSecret: opensearch-security-bootstrap + rolesSecret: opensearch-security-bootstrap + rolesMappingSecret: opensearch-security-bootstrap + tenantsSecret: opensearch-security-bootstrap + resources: + requests: + cpu: "1" + memory: "2Gi" + limits: + cpu: "1" + memory: "2Gi" diff --git a/deployment/env/authentication.env b/deployment/env/authentication.env new file mode 100644 index 00000000..e2732a06 --- /dev/null +++ b/deployment/env/authentication.env @@ -0,0 +1,17 @@ +# NiFi sample credentials for Docker development and k3s-load-auth-nifi. +# Environment values override these defaults. +NIFI_SINGLE_USER_CREDENTIALS_USERNAME="${NIFI_SINGLE_USER_CREDENTIALS_USERNAME:-admin}" +NIFI_SINGLE_USER_CREDENTIALS_PASSWORD="${NIFI_SINGLE_USER_CREDENTIALS_PASSWORD:-cogstackNiFi}" + +# Store passwords are configured in certificates.env. +NIFI_INITIAL_ADMIN_IDENTITY=${NIFI_INITIAL_ADMIN_IDENTITY:-$NIFI_SINGLE_USER_CREDENTIALS_USERNAME} +NIFI_SENSITIVE_PROPS_KEY=${NIFI_SENSITIVE_PROPS_KEY:-c6063c770f5a281732877e7a9f7de2bc} + +# Set the admin password to create an admin user with all_access during initial bootstrap. +OPENSEARCH_ADMIN_PASSWORD=${OPENSEARCH_ADMIN_PASSWORD:-demo} + +# OpenSearch passwords for kibanaserver, nifi, cogstack_pipeline and cogstack_user. +OPENSEARCH_KIBANA_PASSWORD=${OPENSEARCH_KIBANA_PASSWORD:-demo} +OPENSEARCH_NIFI_PASSWORD=${OPENSEARCH_NIFI_PASSWORD:-demo} +OPENSEARCH_PIPELINE_PASSWORD=${OPENSEARCH_PIPELINE_PASSWORD:-demo} +OPENSEARCH_ANALYST_PASSWORD=${OPENSEARCH_ANALYST_PASSWORD:-demo} diff --git a/deployment/env/certificates.env b/deployment/env/certificates.env index bf9fee25..2cb9665c 100644 --- a/deployment/env/certificates.env +++ b/deployment/env/certificates.env @@ -1,28 +1,31 @@ -# Non-secret settings for the certificate generators. Leave blank to use the -# script defaults. Supply store passwords separately and use --days DAYS to -# set validity when running a generator. +# Certificate generator settings with development store passwords. +# Blank settings use the script defaults. Use --days DAYS to set validity. # -# Load from the repository root before running a generator. +# The certificate Make targets load this file automatically. +# For a direct generator invocation, load it from the repository root. # set -a +# source deployment/env/general.env # source deployment/env/certificates.env # set +a # Blank uses deployment/security/ for certificate inputs and outputs. -SECURITY_DIR= +SECURITY_DIR="${SECURITY_DIR:-}" # Optional names to add to the NiFi certificate. Match the names NGINX and the # health check verify in the deployment. -NIFI_UPSTREAM_TLS_NAME= -NIFI_HEALTHCHECK_HOST= - -# Set the namespace to include the NiFi web Service's full Kubernetes DNS name. -KUBE_NAMESPACE= -CLUSTER_DOMAIN=cluster.local +NIFI_UPSTREAM_TLS_NAME="${NIFI_UPSTREAM_TLS_NAME:-}" +NIFI_HEALTHCHECK_HOST="${NIFI_HEALTHCHECK_HOST:-}" # Browser-facing NGINX DNS names or IP addresses, comma-separated. # Blank uses localhost,127.0.0.1. -NGINX_TLS_NAMES= +NGINX_TLS_NAMES="${NGINX_TLS_NAMES:-}" # Optional comma-separated DNS aliases for each OpenSearch node and for Dashboards. -OPENSEARCH_NODE_DNS_NAMES= -OPENSEARCH_DASHBOARDS_DNS_NAMES= +OPENSEARCH_NODE_DNS_NAMES="${OPENSEARCH_NODE_DNS_NAMES:-}" +OPENSEARCH_DASHBOARDS_DNS_NAMES="${OPENSEARCH_DASHBOARDS_DNS_NAMES:-}" + +# Development store passwords. Environment values override these defaults. +NIFI_KEYSTORE_PASSWORD=${NIFI_KEYSTORE_PASSWORD:-cogstack} +NIFI_TRUSTSTORE_PASSWORD=${NIFI_TRUSTSTORE_PASSWORD:-cogstack} +OPENSEARCH_CERTIFICATE_PASSWORD=${OPENSEARCH_CERTIFICATE_PASSWORD:-${OS_CERTIFICATE_PASSWORD:-cogstack}} +ROOT_CERTIFICATE_KEYSTORE_PASSWORD="${ROOT_CERTIFICATE_KEYSTORE_PASSWORD:-cogstackNiFi}" diff --git a/deployment/env/general.env b/deployment/env/general.env new file mode 100644 index 00000000..5c8a2e08 --- /dev/null +++ b/deployment/env/general.env @@ -0,0 +1,28 @@ +# any other variables that you may want to use go here + +# Kubernetes namespace and DNS domain. +KUBE_NAMESPACE=cogstack +CLUSTER_DOMAIN=cluster.local + +# This is used to explicitly inform systems that run on Apple silicon to emulate this architecture +# set only CPU_ARCHITECTURE to amd/arm64 +# remove if this causes issues on any other platform +# possible values: amd64, arm64 +CPU_ARCHITECTURE=arm64 +DOCKER_DEFAULT_PLATFORM=linux/${CPU_ARCHITECTURE:-amd64} +COMPOSE_BAKE=True + +COGSTACK_ADMIN_EMAIL=admin@cogstack.net + +# used in NiFi for the timezone +TZ="Europe/London" + +# IMPORTANT: this is used to prefix all volumes created by docker-compose for ALL services, this includes SUBMODULES +# this has been added for backward compatibility with existing deployments +VOLUME_PREFIX=deploy_ + + +# this is the default, for containers which dont rely on individual settings +DOCKER_SHM_SIZE=512m +DOCKER_LOG_SIZE_PER_FILE="100m" +DOCKER_LOG_NUM_FILES=10 diff --git a/deployment/env/network_settings.env b/deployment/env/network_settings.env new file mode 100644 index 00000000..5ae69fcb --- /dev/null +++ b/deployment/env/network_settings.env @@ -0,0 +1,20 @@ +# use this file to set EXTRA_HOSTS in docker-compose +# useful if you have the services on separate machines/servers +# and you have generated SSL certificates using the container names rather than IP addresses +# this is the equivalent of /etc/hosts file, read this: https://tldp.org/LDP/solrhe/Securing-Optimizing-Linux-RH-Edition-v1.3/chap9sec95.html + + +# example ELASTICSEARCH_1_HOST_NAME="elasticsearch-1:0.0.0.0" +ELASTICSEARCH_1_HOST_NAME="test-1:0.0.0.0" +ELASTICSEARCH_2_HOST_NAME="test-2:0.0.0.0" +ELASTICSEARCH_3_HOST_NAME="test-3:0.0.0.0" +KIBANA_HOST_NAME="test-4:0.0.0.0" +NIFI_HOST_NAME="test-5:0.0.0.0" + +# general network settings +HTTPS_PROXY="" +HTTP_PROXY="" +NO_PROXY="" +no_proxy="" +http_proxy="" +https_proxy="" diff --git a/deployment/env/nifi.env b/deployment/env/nifi.env new file mode 120000 index 00000000..29e37aa8 --- /dev/null +++ b/deployment/env/nifi.env @@ -0,0 +1 @@ +../../apps/nifi/env/nifi.env \ No newline at end of file diff --git a/deployment/env/opensearch-dashboards.env b/deployment/env/opensearch-dashboards.env new file mode 120000 index 00000000..fbe3d735 --- /dev/null +++ b/deployment/env/opensearch-dashboards.env @@ -0,0 +1 @@ +../../apps/opensearch-dashboards/env/opensearch-dashboards.env \ No newline at end of file diff --git a/deployment/env/opensearch.env b/deployment/env/opensearch.env new file mode 120000 index 00000000..3ddb229e --- /dev/null +++ b/deployment/env/opensearch.env @@ -0,0 +1 @@ +../../apps/opensearch/env/opensearch.env \ No newline at end of file diff --git a/deployment/make/certs.mk b/deployment/make/certs.mk new file mode 100644 index 00000000..39c93c18 --- /dev/null +++ b/deployment/make/certs.mk @@ -0,0 +1,87 @@ +# Certificates + +.PHONY: certs-all certs-k3s certs-root certs-nifi certs-nginx certs-opensearch certs-opensearch-shared certs-opensearch-nodes delete-certs-all + +load_certificates_env = set -e; set -a; if [ -f ./env/certificates.env ]; then . ./env/certificates.env; fi; set +a +load_certificates_cluster_env = set -e; . ./env/general.env; export CLUSTER_DOMAIN; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}" + +certs-k3s: certs-root ## Generate the CA, NGINX HTTPS certificate, and OpenSearch transport certificate + $(MAKE) certs-nginx + @$(load_certificates_cluster_env); \ + $(MAKE) certs-opensearch-shared KUBE_NAMESPACE="$$namespace" + +certs-all: certs-k3s ## Generate the K3s and Docker certificate bundles + @$(load_certificates_cluster_env); \ + $(MAKE) certs-nifi KUBE_NAMESPACE="$$namespace" + @$(load_certificates_env); \ + OPENSEARCH_DASHBOARDS_DNS_NAMES="$${OPENSEARCH_DASHBOARDS_DNS_NAMES:-localhost}" \ + bash scripts/security/create_opensearch_client_admin_certs.sh + +certs-root: ## Generate the root CA bundle + @$(load_certificates_env); \ + bash scripts/security/create_root_ca_cert.sh + +certs-nifi: ## Generate the NiFi certificate and stores with the existing CA + bash scripts/security/create_nifi_certs.sh + +certs-nginx: ## Generate the NGINX certificate with the existing CA + @$(load_certificates_env); \ + bash scripts/security/create_nginx_certs.sh + +certs-opensearch: certs-opensearch-shared ## Generate the shared OpenSearch node and admin client certificates + @$(load_certificates_env); \ + bash scripts/security/create_opensearch_client_admin_certs.sh --admin-only + +certs-opensearch-shared: + @$(load_certificates_env); \ + service=opensearch-cluster-master; \ + service_dns="$$service.$${KUBE_NAMESPACE:-search}.svc"; \ + $(MAKE) certs-opensearch-nodes NODES=opensearch-shared \ + OPENSEARCH_NODE_DNS_NAMES="$${OPENSEARCH_NODE_DNS_NAMES:-localhost,$$service,$$service_dns,$$service_dns.$${CLUSTER_DOMAIN:-cluster.local}}" + +certs-opensearch-nodes: ## Generate OpenSearch node certificates for NODES="node1 node2 ..." + @$(load_certificates_env); \ + read -r -a nodes <<< "$$NODES"; \ + bash scripts/security/create_opensearch_node_cert.sh "$${nodes[@]}" + +delete-certs-all: ## Delete generated local TLS certificates, keys, and stores + @set -e; \ + certs="$${SECURITY_DIR:-security}/certificates"; \ + if [ -L "$$certs" ]; then printf 'Certificate directory is a symlink: %s\n' "$$certs" >&2; exit 1; fi; \ + [ -d "$$certs" ] || exit 0; \ + CDPATH= cd -- "$$certs"; \ + find -P . -maxdepth 2 \( -type f -o -type l \) \ + \( -path './root/*' -o -path './nifi/*' -o -path './nginx/*' -o -path './opensearch/*' \) \ + \( -name '*.crt' -o -name '*.pem' -o -name '*.key' -o -name '*.csr' -o -name '*.p12' -o -name '*.jks' \) -delete + +.PHONY: k3s-load-certs k3s-load-certs-all k3s-load-certs-nginx k3s-load-certs-opensearch + +k3s-load-certs: k3s-load-certs-all +k3s-load-certs-all: ## Load the NGINX HTTPS and OpenSearch transport TLS Secrets +k3s-load-certs-nginx: ## Load the NGINX certificate and key into nginx-tls +k3s-load-certs-opensearch: ## Load the shared node certificate into opensearch-node-tls + +k3s-load-certs-all k3s-load-certs-nginx k3s-load-certs-opensearch: + @set -eo pipefail; \ + . ./env/general.env; \ + if [ -f ./env/certificates.env ]; then . ./env/certificates.env; fi; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}"; \ + certs="$${SECURITY_DIR:-security}/certificates"; \ + services=$(@:k3s-load-certs-%=%); \ + if [ "$$services" = all ]; then services="nginx opensearch"; fi; \ + manifests=(); \ + for service in $$services; do \ + case "$$service" in \ + nginx) secret=(tls nginx-tls \ + --cert="$$certs/nginx/tls.crt" --key="$$certs/nginx/tls.key");; \ + opensearch) secret=(generic opensearch-node-tls \ + --from-file="node.crt=$$certs/opensearch/opensearch-shared.crt" \ + --from-file="node.key=$$certs/opensearch/opensearch-shared.key" \ + --from-file="ca.crt=$$certs/opensearch/elastic-stack-ca.crt.pem");; \ + esac; \ + manifest=$$(kubectl -n "$$namespace" create secret "$${secret[@]}" --dry-run=client -o yaml); \ + manifests+=("$$manifest"); \ + done; \ + printf -- '---\n%s\n' "$${manifests[@]}" | \ + kubectl -n "$$namespace" apply --server-side --field-manager=cogstack-certificates -f - diff --git a/deployment/make/helm.mk b/deployment/make/helm.mk new file mode 100644 index 00000000..74dfdd96 --- /dev/null +++ b/deployment/make/helm.mk @@ -0,0 +1,153 @@ +# Helm values and releases + +.PHONY: helm-values-all helm-values-nifi helm-values-nginx helm-values-opensearch helm-values-opensearch-dashboards + +helm-values-all: helm-values-nifi helm-values-nginx helm-values-opensearch helm-values-opensearch-dashboards ## Render all four charts' environment-based values +helm-values-nifi: ## Render NiFi values.yaml from env/nifi.env +helm-values-nginx: ## Render NGINX values.yaml from env/nifi.env and optional env/nginx.env +helm-values-opensearch: ## Render OpenSearch values.yaml from env/opensearch.env +helm-values-opensearch-dashboards: ## Render OpenSearch Dashboards values.yaml from env/opensearch-dashboards.env + +helm-values-nifi helm-values-nginx helm-values-opensearch helm-values-opensearch-dashboards: + @set -e; \ + service=$(@:helm-values-%=%); \ + env_file="./env/$$service.env"; \ + set -a; \ + if [ "$$service" = nginx ]; then \ + : "$${NGINX_DOCKER_CPU_MIN:=1}" "$${NGINX_DOCKER_CPU_MAX:=1}" "$${NGINX_DOCKER_RAM:=512M}"; \ + if [ -f "$$env_file" ] && [ -f ./env/nifi.env ]; then . ./env/nifi.env; fi; \ + [ -f "$$env_file" ] || env_file=./env/nifi.env; \ + fi; \ + . "$$env_file"; \ + set +a; \ + case "$$service" in \ + nifi) node_setting=NIFI_K3S_WHITELIST; export NIFI_K3S_ALLOWED_NODES='[]';; \ + opensearch) node_setting=OPENSEARCH_K3S_BLACKLIST; export OPENSEARCH_K3S_NODE_AFFINITY='{}';; \ + *) node_setting=;; \ + esac; \ + if [ -n "$$node_setting" ]; then \ + node_list="$${!node_setting}"; \ + IFS=$$' ,\t' read -r -a nodes <<< "$${node_list//$$'\n'/ }"; \ + if (( $${#nodes[@]} )); then \ + node_label='[a-z0-9]([a-z0-9-]*[a-z0-9])?'; \ + for node in "$${nodes[@]}"; do \ + if [[ $${#node} -gt 253 || ! "$$node" =~ ^$$node_label([.]$$node_label)*$$ ]]; then \ + printf 'Invalid Kubernetes node name in %s: %s\n' "$$node_setting" "$$node" >&2; \ + exit 1; \ + fi; \ + done; \ + if [ "$$service" = nifi ]; then \ + printf -v names '"%s",' "$${nodes[@]}"; \ + NIFI_K3S_ALLOWED_NODES="[$${names%,}]"; \ + else \ + printf -v fields '{key: metadata.name, operator: NotIn, values: ["%s"]},' "$${nodes[@]}"; \ + OPENSEARCH_K3S_NODE_AFFINITY="{requiredDuringSchedulingIgnoredDuringExecution: {nodeSelectorTerms: [{matchFields: [$${fields%,}]}]}}"; \ + fi; \ + fi; \ + fi; \ + chart="charts/$$service"; \ + template="$$chart/values.env.yaml"; \ + variables=$$(envsubst --variables "$$(cat "$$template")"); \ + for name in $$variables; do \ + value="$${!name:?Set $$name in $$env_file before rendering}"; \ + if [[ "$$name" == *_DOCKER_RAM && "$$value" =~ ^([0-9]+([.][0-9]+)?)([kmgtp])[bB]?$$ ]]; then \ + unit=$$(printf '%s' "$${BASH_REMATCH[3]}" | tr kmgtp KMGTP); \ + export "$$name=$${BASH_REMATCH[1]}$${unit}i"; \ + fi; \ + done; \ + tmp=$$(mktemp -d "$$chart/.values.XXXXXX"); \ + trap 'rm -rf -- "$$tmp"' EXIT; \ + envsubst < "$$template" > "$$tmp/values.yaml"; \ + mv -- "$$tmp/values.yaml" "$$chart/values.yaml" + +.PHONY: helm-install helm-install-all helm-install-nifi helm-install-nginx helm-install-nifi-stack +.PHONY: helm-install-opensearch helm-install-opensearch-dashboards helm-install-opensearch-stack + +# Set KUBE_NAMESPACE in deployment/env/general.env and create the namespace +# and required Secrets and ConfigMaps. Run these from the repository root. +# make -C deployment helm-install-nifi HELM_TIMEOUT=15m +# make -C deployment helm-install-nginx +# make -C deployment helm-install-nifi-stack +# Load dashboards-auth first to share its service account password with bootstrap. +# make -C deployment k3s-load-auth-opensearch-dashboards +# make -C deployment k3s-load-auth-opensearch +# make -C deployment helm-install-opensearch +# make -C deployment helm-install-opensearch-dashboards HELM_VALUES=/path/to/dashboards-values.yaml +# Set BOOTSTRAP_OPENSEARCH_SECURITY=0 to use existing auth Secrets. +# make -C deployment helm-install-opensearch-stack HELM_VALUES=/path/to/dashboards-values.yaml +# The stack target uses HELM_VALUES for Dashboards. +# HELM_VALUES accepts an absolute path, a path relative to deployment/, or - for stdin. +# HELM_TIMEOUT defaults to 10m. +helm-install: ## Install or upgrade CHART with optional HELM_VALUES and HELM_TIMEOUT + @set -e; \ + . ./env/general.env; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}"; \ + chart="charts/$${CHART:?Set CHART to a directory under deployment/charts}"; \ + release="$$CHART"; \ + args=(); \ + case "$$CHART" in \ + nifi|nginx) release="cogstack-$$CHART";; \ + opensearch|opensearch-dashboards) \ + helm repo add opensearch https://opensearch-project.github.io/helm-charts/; \ + helm dependency build "$$chart";; \ + esac; \ + if [ "$$CHART" = opensearch ]; then \ + args+=(--set-file "opensearch.config.opensearch\\.yml=$$chart/config/opensearch.yml"); \ + fi; \ + if [ -n "$${HELM_VALUES:-}" ]; then args+=(-f "$$HELM_VALUES"); fi; \ + helm upgrade --install "$$release" "$$chart" -n "$$namespace" \ + --wait --timeout "$${HELM_TIMEOUT:-10m}" "$${args[@]}" + +helm-install-all: k3s-prepare-all ## Prepare and install or upgrade both application stacks + $(MAKE) helm-install-nifi-stack + $(MAKE) helm-install-opensearch-stack BOOTSTRAP_OPENSEARCH_SECURITY=0 + +helm-install-nifi: ## Install or upgrade NiFi +helm-install-nginx: k3s-load-env-nginx ## Load the NGINX environment, then install or upgrade NGINX +helm-install-opensearch: k3s-load-env-opensearch ## Load the OpenSearch environment, then install or upgrade OpenSearch +helm-install-opensearch-dashboards: ## Install or upgrade OpenSearch Dashboards + +helm-install-nifi helm-install-nginx helm-install-opensearch helm-install-opensearch-dashboards: + $(MAKE) helm-install CHART=$(@:helm-install-%=%) + +helm-install-nifi-stack: helm-install-nifi ## Load the runtime environment and install or upgrade NiFi and NGINX + $(MAKE) helm-install-nginx + +helm-install-opensearch-stack: ## Install OpenSearch and then Dashboards + @if [ "$${BOOTSTRAP_OPENSEARCH_SECURITY:-1}" = 1 ]; then \ + $(MAKE) k3s-load-auth-opensearch-dashboards && $(MAKE) k3s-bootstrap-opensearch; \ + fi + $(MAKE) helm-install-opensearch HELM_VALUES= + $(MAKE) helm-install-opensearch-dashboards + +.PHONY: helm-uninstall-nifi helm-uninstall-nginx helm-uninstall-nifi-stack +.PHONY: helm-uninstall-opensearch helm-uninstall-opensearch-dashboards helm-uninstall-opensearch-stack +.PHONY: helm-delete-opensearch-volumes + +# Reinstall in the same namespace with the same StatefulSet names to reuse the retained PVCs. +helm-uninstall-nifi: ## Uninstall NiFi and retain its PVCs +helm-uninstall-nginx: ## Uninstall NGINX +helm-uninstall-opensearch: ## Uninstall OpenSearch and retain its PVCs +helm-uninstall-opensearch-dashboards: ## Uninstall OpenSearch Dashboards + +helm-uninstall-nifi helm-uninstall-nginx helm-uninstall-opensearch helm-uninstall-opensearch-dashboards: + @set -e; \ + . ./env/general.env; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}"; \ + release=$(@:helm-uninstall-%=%); \ + case "$$release" in nifi|nginx) release="cogstack-$$release";; esac; \ + helm uninstall "$$release" -n "$$namespace" --ignore-not-found \ + --cascade foreground --wait --timeout "$${HELM_TIMEOUT:-10m}" + +helm-uninstall-nifi-stack: helm-uninstall-nginx ## Uninstall NGINX, then NiFi, and retain PVCs + $(MAKE) helm-uninstall-nifi + +helm-uninstall-opensearch-stack: helm-uninstall-opensearch-dashboards ## Uninstall Dashboards, then OpenSearch, and retain PVCs + $(MAKE) helm-uninstall-opensearch + +helm-delete-opensearch-volumes: ## Delete OpenSearch data PVCs after uninstalling + @set -e; \ + . ./env/general.env; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}"; \ + kubectl -n "$$namespace" delete pvc --ignore-not-found \ + -l 'app.kubernetes.io/instance=opensearch,app.kubernetes.io/name=opensearch' diff --git a/deployment/make/k3s.mk b/deployment/make/k3s.mk new file mode 100644 index 00000000..fa773e89 --- /dev/null +++ b/deployment/make/k3s.mk @@ -0,0 +1,68 @@ +# Kubernetes configuration + +.PHONY: k3s-load-auth-all k3s-load-auth-nifi k3s-load-auth-opensearch k3s-load-auth-opensearch-dashboards + +k3s-load-auth-all: ## Load the NiFi, Dashboards, and OpenSearch auth Secrets + $(MAKE) k3s-load-auth-nifi + $(MAKE) k3s-load-auth-opensearch-dashboards + $(MAKE) k3s-load-auth-opensearch + +# Uses env/authentication.env. Set NIFI_AUTH_FILE to choose another auth file. +k3s-load-auth-nifi: ## Load the NiFi flow encryption key and NGINX login Secret + @bash scripts/security/load_nifi_auth.sh + +# Both targets use env/authentication.env unless OPENSEARCH_AUTH_FILE is set. +k3s-load-auth-opensearch: ## Load the bootstrap policy and users before installing OpenSearch +k3s-load-auth-opensearch-dashboards: ## Load the OpenSearch Dashboards auth Secret + +k3s-load-auth-opensearch k3s-load-auth-opensearch-dashboards: + @bash scripts/security/load_opensearch_auth.sh $(@:k3s-load-auth-%=%) + +.PHONY: k3s-delete-auth-all k3s-delete-auth-nifi k3s-delete-auth-opensearch k3s-delete-auth-opensearch-dashboards + +k3s-delete-auth-all: k3s-delete-auth-nifi k3s-delete-auth-opensearch k3s-delete-auth-opensearch-dashboards ## Delete the NiFi, OpenSearch, and Dashboards auth Secrets +k3s-delete-auth-nifi: ## Delete the NiFi login and flow encryption key Secret +k3s-delete-auth-opensearch: ## Delete the OpenSearch security bootstrap Secret +k3s-delete-auth-opensearch-dashboards: ## Delete the OpenSearch Dashboards auth Secret + +k3s-delete-auth-nifi k3s-delete-auth-opensearch k3s-delete-auth-opensearch-dashboards: + @set -e; \ + . ./env/general.env; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}"; \ + case "$(@:k3s-delete-auth-%=%)" in \ + nifi) secret=nifi-auth;; \ + opensearch) secret=opensearch-security-bootstrap;; \ + opensearch-dashboards) secret=dashboards-auth;; \ + esac; \ + kubectl -n "$$namespace" delete secret "$$secret" --ignore-not-found + +.PHONY: k3s-load-env-all k3s-load-env-nginx k3s-load-env-opensearch + +k3s-load-env-all: k3s-load-env-nginx k3s-load-env-opensearch ## Load all runtime environment ConfigMaps +k3s-load-env-nginx: ## Load the NGINX runtime settings into the nginx-env ConfigMap +k3s-load-env-opensearch: ## Load the OpenSearch log level into the opensearch-env ConfigMap + +k3s-load-env-nginx k3s-load-env-opensearch: + @set -eo pipefail; \ + . ./env/general.env; \ + namespace="$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}"; \ + service=$(@:k3s-load-env-%=%); \ + env_file="./env/$$service.env"; \ + if [[ "$$service" == opensearch || -f "$$env_file" ]]; then . "$$env_file"; fi; \ + args=(); \ + case "$$service" in \ + nginx) args+=("--from-literal=NGINX_NIFI_SERVER_NAME=$${NGINX_NIFI_SERVER_NAME:-_}");; \ + opensearch) args+=("--from-literal=OPENSEARCH_LOG_LEVEL=$${OPENSEARCH_LOG_LEVEL:-INFO}");; \ + esac; \ + kubectl -n "$$namespace" create configmap "$$service-env" "$${args[@]}" --dry-run=client -o yaml | \ + kubectl -n "$$namespace" apply --server-side --field-manager=cogstack-env -f - + +.PHONY: k3s-bootstrap-opensearch k3s-prepare-all + +k3s-bootstrap-opensearch: k3s-load-auth-opensearch ## Alias for k3s-load-auth-opensearch + +k3s-prepare-all: ## Render Helm values and load TLS, runtime, and auth resources + $(MAKE) helm-values-all + $(MAKE) k3s-load-certs-all + $(MAKE) k3s-load-env-all + $(MAKE) k3s-load-auth-all diff --git a/deployment/make/setup.mk b/deployment/make/setup.mk new file mode 100644 index 00000000..778deb87 --- /dev/null +++ b/deployment/make/setup.mk @@ -0,0 +1,28 @@ +# Cluster setup + +.PHONY: setup-all setup-install-pre-requisites setup-k3s-cluster-init setup-verify setup-k3s-cluster-remote setup-k3s-namespace + +setup-install-pre-requisites: ## Install host tools, Docker, K3s, and Helm locally by default + bash scripts/installation_utils/install_os_tools_and_software.sh + +setup-k3s-cluster-init: ## Initialize the first K3s server on this machine + bash scripts/installation_utils/setup_kubernetes_cluster.sh k3s server --cluster-init + +setup-k3s-cluster-remote: ## Install prerequisites, initialize the first server, and join the rest over SSH + bash scripts/installation_utils/setup_k3s_cluster.sh $(NODES) + +setup-k3s-namespace: ## Create the namespace configured in env/general.env + @set -eo pipefail; \ + . ./env/general.env; \ + kubectl create namespace "$${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}" --dry-run=client -o yaml | \ + kubectl apply --server-side --field-manager=cogstack-namespace -f - + +setup-verify: ## Check local Docker, Docker Compose, and K3s access without sudo + bash scripts/installation_utils/verify_docker.sh + bash scripts/installation_utils/verify_k3s.sh + +setup-all: ## Install prerequisites, initialize K3s, create the namespace, and verify + $(MAKE) setup-install-pre-requisites + $(MAKE) setup-k3s-cluster-init + $(MAKE) setup-k3s-namespace + $(MAKE) setup-verify diff --git a/deployment/scripts/README.md b/deployment/scripts/README.md index e432fe85..c848e9ec 100644 --- a/deployment/scripts/README.md +++ b/deployment/scripts/README.md @@ -11,8 +11,28 @@ is 1,460 days for the root CA and OpenSearch certificates and 397 days for NiFi and NGINX. The root CA, NiFi and OpenSearch node generators also use Java's `keytool`. `SECURITY_DIR` defaults to `deployment/security/`. -If you need a root CA, export `ROOT_CERTIFICATE_KEYSTORE_PASSWORD` and run this -from the repository root. +The generators prompt for missing passwords with hidden input in a terminal. +For non-interactive runs, provide the required passwords through the environment +or the generator's configuration. + +The Makefile loads `deployment/env/certificates.env` for certificate generation +and loading. Choose a bundle when generating fresh certificates. + +| Target | Certificates | +| --- | --- | +| `certs-k3s` | CA, NGINX HTTPS, and OpenSearch transport | +| `certs-all` | K3s bundle plus the NiFi, OpenSearch admin, and Dashboards certificates for Docker | + +For a direct invocation of the root CA generator, load the file to use its +sample store password. + +```bash +set -a +source deployment/env/certificates.env +set +a +``` + +The root CA generator uses `ROOT_CERTIFICATE_KEYSTORE_PASSWORD`. ```bash ./deployment/scripts/security/create_root_ca_cert.sh @@ -20,12 +40,12 @@ from the repository root. ### NiFi -Export the `KEYSTORE_PASSWORD` and `TRUSTSTORE_PASSWORD` that NiFi will use. -The legacy `NIFI_KEYSTORE_PASSWORD` and `NIFI_TRUSTSTORE_PASSWORD` names are -also accepted. +The NiFi generator reads `NIFI_KEYSTORE_PASSWORD` and `NIFI_TRUSTSTORE_PASSWORD` from +`deployment/env/certificates.env`. `KEYSTORE_PASSWORD` and +`TRUSTSTORE_PASSWORD` take precedence when set. Choose the command for your deployment. The default NiFi certificate covers -`nifi`, `localhost`, `cogstack-nifi`, `cogstack-nifi-web`, and `127.0.0.1`. +`nifi`, `localhost`, `cogstack-nifi`, `cogstack-nifi-headless`, and `127.0.0.1`. ```bash ./deployment/scripts/security/create_nifi_certs.sh @@ -38,14 +58,6 @@ verify. `NIFI_HEALTHCHECK_HOST` also adds a name when supplied. NIFI_UPSTREAM_TLS_NAME=nifi.internal.example ./deployment/scripts/security/create_nifi_certs.sh ``` -For Kubernetes, set `KUBE_NAMESPACE` to include the web Service's full name. -For example, `cogstack` adds `cogstack-nifi-web.cogstack.svc.cluster.local`. -Set `CLUSTER_DOMAIN` if your cluster uses a domain other than `cluster.local`. - -```bash -KUBE_NAMESPACE=cogstack ./deployment/scripts/security/create_nifi_certs.sh -``` - Each invocation writes `nifi.key`, `nifi.csr`, `nifi.pem`, `nifi.crt` (DER), `nifi.p12`, `nifi-keystore.jks`, and `nifi-truststore.jks` under `$SECURITY_DIR/certificates/nifi/`. @@ -67,7 +79,7 @@ It runs without a store password or `keytool`. ### OpenSearch -Export `ES_CERTIFICATE_PASSWORD` for the Java and PKCS#12 stores. Pass the node +Use `OPENSEARCH_CERTIFICATE_PASSWORD` for the Java and PKCS#12 stores. Pass the node hostnames when generating the node certificates. Generate the Dashboards and admin certificates with the second command. @@ -83,6 +95,9 @@ a Kubernetes Service FQDN. Outputs are under prefix. Use the issued node and admin subjects in the corresponding OpenSearch DN settings. +Kubernetes uses the NGINX certificate and the OpenSearch transport certificate. +Load them with `make -C deployment k3s-load-certs-all`. + ## Install, initialize and verify Install on every machine before creating or joining a cluster: diff --git a/deployment/scripts/installation_utils/install_host_utils.sh b/deployment/scripts/installation_utils/install_host_utils.sh index d3a1ec73..41a37dc3 100755 --- a/deployment/scripts/installation_utils/install_host_utils.sh +++ b/deployment/scripts/installation_utils/install_host_utils.sh @@ -11,7 +11,7 @@ if [ "$os_distribution" == "debian" ] || [ "$os_distribution" == "ubuntu" ]; then install_missing_packages "$os_distribution" \ samba cifs-utils nfs-common nfs-kernel-server archivemount \ - htop iotop sysstat \ + htop iotop sysstat default-jdk \ jq gettext-base wget curl gnupg gnupg-agent git ca-certificates apt-transport-https python3 python3-pip python3-full openssl libssl-dev zip unzip tar nano gcc make python3-dev build-essential software-properties-common if command -v az >/dev/null 2>&1 || package_is_installed "$os_distribution" azure-cli; then @@ -27,7 +27,7 @@ elif [ "$os_distribution" == "redhat" ]; then install_missing_packages "$os_distribution" \ samba samba-client cifs-utils nfs-utils rpcbind archivemount \ - htop iotop sysstat \ + htop iotop sysstat java-21-openjdk-devel \ jq gettext yum-utils wget curl git device-mapper-persistent-data lvm2 python3 python3-pip libffi-devel openssl openssl-devel zip unzip tar nano gcc gcc-c++ make python3-devel libevent-devel if command -v az >/dev/null 2>&1 || package_is_installed "$os_distribution" azure-cli; then diff --git a/deployment/scripts/installation_utils/install_os_tools_and_software.sh b/deployment/scripts/installation_utils/install_os_tools_and_software.sh index 54c3076a..e95cfd95 100755 --- a/deployment/scripts/installation_utils/install_os_tools_and_software.sh +++ b/deployment/scripts/installation_utils/install_os_tools_and_software.sh @@ -22,6 +22,12 @@ os_distribution="$(bash "${script_dir}/detect_os.sh")" echo "Found distribution: $os_distribution " bash "${script_dir}/install_host_utils.sh" + +if ! keytool -help >/dev/null 2>&1; then + echo "Java keytool could not run after JDK installation." >&2 + exit 1 +fi + bash "${script_dir}/install_docker.sh" if [ "$install_k3s" = "true" ]; then diff --git a/deployment/scripts/security/create_nifi_certs.sh b/deployment/scripts/security/create_nifi_certs.sh index 3019c430..f4ca0135 100755 --- a/deployment/scripts/security/create_nifi_certs.sh +++ b/deployment/scripts/security/create_nifi_certs.sh @@ -9,7 +9,8 @@ # # Requires: # - Bash, OpenSSL and Java keytool -# - KEYSTORE_PASSWORD and TRUSTSTORE_PASSWORD in the environment +# - NiFi store passwords from the environment or deployment/env/certificates.env +# (prompted when missing) # - root-ca.pem and root-ca.key under certificates/root/ in SECURITY_DIR # # Optional environment variables: @@ -40,16 +41,16 @@ if (( $# > 0 )); then fi script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +if [[ -f "$script_dir/../../env/certificates.env" ]]; then + # shellcheck source=../../env/certificates.env + source "$script_dir/../../env/certificates.env" +fi security_dir=${SECURITY_DIR:-"$script_dir/../../security"} profile="$script_dir/../../security/templates/ssl-extensions-x509.cnf" ca_cert="$security_dir/certificates/root/root-ca.pem" ca_key="$security_dir/certificates/root/root-ca.key" output_dir="$security_dir/certificates/nifi" -export KEYSTORE_PASSWORD="${KEYSTORE_PASSWORD:-${NIFI_KEYSTORE_PASSWORD:-}}" -export TRUSTSTORE_PASSWORD="${TRUSTSTORE_PASSWORD:-${NIFI_TRUSTSTORE_PASSWORD:-}}" -: "${KEYSTORE_PASSWORD:?Set KEYSTORE_PASSWORD}" "${TRUSTSTORE_PASSWORD:?Set TRUSTSTORE_PASSWORD}" - for input in "$ca_cert" "$ca_key"; do if [[ ! -f "$input" || ! -r "$input" || ! -s "$input" ]]; then printf 'Missing or unreadable CA file %s. Run create_root_ca_cert.sh first.\n' "$input" >&2 @@ -65,6 +66,13 @@ for file in "${files[@]}"; do fi done +KEYSTORE_PASSWORD=${KEYSTORE_PASSWORD:-${NIFI_KEYSTORE_PASSWORD:-}} +TRUSTSTORE_PASSWORD=${TRUSTSTORE_PASSWORD:-${NIFI_TRUSTSTORE_PASSWORD:-}} +# shellcheck source=password_prompt.sh +source "$script_dir/password_prompt.sh" +require_password KEYSTORE_PASSWORD +require_password TRUSTSTORE_PASSWORD + # Build the whole bundle before publishing it. Clean up files written by this # run if any of the final writes fail. scratch_dir=$(mktemp -d) @@ -82,7 +90,7 @@ trap 'exit 143' TERM # === Add deployment-specific SANs to the template defaults names=("${NIFI_UPSTREAM_TLS_NAME:-}" "${NIFI_HEALTHCHECK_HOST:-}") if [[ -n "${KUBE_NAMESPACE:-}" ]]; then - names+=("cogstack-nifi-web.${KUBE_NAMESPACE}.svc.${CLUSTER_DOMAIN:-cluster.local}") + names+=("cogstack-nifi.${KUBE_NAMESPACE}.svc.${CLUSTER_DOMAIN:-cluster.local}") fi { diff --git a/deployment/scripts/security/create_opensearch_client_admin_certs.sh b/deployment/scripts/security/create_opensearch_client_admin_certs.sh index 8870836a..eaf36127 100755 --- a/deployment/scripts/security/create_opensearch_client_admin_certs.sh +++ b/deployment/scripts/security/create_opensearch_client_admin_certs.sh @@ -4,12 +4,14 @@ # 🔐 Create the OpenSearch Dashboards and admin certificates and keys # # Usage: -# ./create_opensearch_client_admin_certs.sh [--days DAYS] +# ./create_opensearch_client_admin_certs.sh [--admin-only|--dashboards-only] [--days DAYS] +# --admin-only skips the Dashboards certificate and PKCS#12 bundle. +# --dashboards-only skips the admin client certificate. # DAYS is a positive integer. The default validity is 1,460 days. # # Requires: # - Bash and OpenSSL -# - ES_CERTIFICATE_PASSWORD for the encrypted Dashboards PKCS#12 bundle +# - OPENSEARCH_CERTIFICATE_PASSWORD for the encrypted Dashboards PKCS#12 bundle # - root-ca.pem and root-ca.key under certificates/root/ in SECURITY_DIR # # Optional environment variables: @@ -31,17 +33,18 @@ set -euo pipefail umask 077 days=1460 +mode= +case ${1:-} in + --admin-only|--dashboards-only) mode=$1; shift ;; +esac if (( $# > 0 )); then if [[ $# -ne 2 || "$1" != --days || ! "$2" =~ ^[1-9][0-9]*$ ]]; then - printf 'Usage: %s [--days DAYS] (DAYS must be a positive integer)\n' "$0" >&2 + printf 'Usage: %s [--admin-only|--dashboards-only] [--days DAYS] (DAYS must be a positive integer)\n' "$0" >&2 exit 2 fi days=$2 fi -: "${ES_CERTIFICATE_PASSWORD:?Set ES_CERTIFICATE_PASSWORD}" -export ES_CERTIFICATE_PASSWORD - script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) security_dir=${SECURITY_DIR:-"$script_dir/../../security"} ca_cert="$security_dir/certificates/root/root-ca.pem" @@ -55,18 +58,32 @@ for input in "$ca_cert" "$ca_key"; do fi done -sans=DNS:opensearch-dashboards,DNS:kibana -if [[ -n "${OPENSEARCH_DASHBOARDS_DNS_NAMES:-}" ]]; then - dns_label='[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?' - dns_name="$dns_label(\.$dns_label)*" - if [[ ! "$OPENSEARCH_DASHBOARDS_DNS_NAMES" =~ ^$dns_name(,$dns_name)*$ ]]; then - printf 'OPENSEARCH_DASHBOARDS_DNS_NAMES must contain comma-separated DNS names.\n' >&2 - exit 2 +roles=() +files=() +if [[ "$mode" != --admin-only ]]; then + # shellcheck source=password_prompt.sh + source "$script_dir/password_prompt.sh" + OPENSEARCH_CERTIFICATE_PASSWORD=${OPENSEARCH_CERTIFICATE_PASSWORD:-${OS_CERTIFICATE_PASSWORD:-}} + require_password OPENSEARCH_CERTIFICATE_PASSWORD + roles=(client) + files=(es_kibana_client.pem es_kibana_client.key es_kibana_client.csr es_kibana_client.p12) + + sans=DNS:opensearch-dashboards,DNS:kibana + if [[ -n "${OPENSEARCH_DASHBOARDS_DNS_NAMES:-}" ]]; then + dns_label='[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?' + dns_name="$dns_label(\.$dns_label)*" + if [[ ! "$OPENSEARCH_DASHBOARDS_DNS_NAMES" =~ ^$dns_name(,$dns_name)*$ ]]; then + printf 'OPENSEARCH_DASHBOARDS_DNS_NAMES must contain comma-separated DNS names.\n' >&2 + exit 2 + fi + sans+=",DNS:${OPENSEARCH_DASHBOARDS_DNS_NAMES//,/,DNS:}" fi - sans+=",DNS:${OPENSEARCH_DASHBOARDS_DNS_NAMES//,/,DNS:}" +fi +if [[ "$mode" != --dashboards-only ]]; then + roles+=(admin) + files+=(admin.crt admin.key.pem admin.csr) fi -files=(es_kibana_client.pem es_kibana_client.key es_kibana_client.csr es_kibana_client.p12 admin.crt admin.key.pem admin.csr) for file in "${files[@]}"; do if [[ -e "$output_dir/$file" || -L "$output_dir/$file" ]]; then printf 'Output already exists: %s\n' "$output_dir/$file" >&2 @@ -88,7 +105,7 @@ trap 'exit 130' INT trap 'exit 143' TERM subject='/C=UK/ST=London/L=UK/O=cogstack/OU=cogstack' -for role in client admin; do +for role in "${roles[@]}"; do if [[ "$role" == client ]]; then key=es_kibana_client.key csr=es_kibana_client.csr @@ -111,9 +128,11 @@ for role in client admin; do openssl verify -CAfile "$ca_cert" "$scratch_dir/$cert" >/dev/null done -openssl pkcs12 -export -name es_kibana_client -inkey "$scratch_dir/es_kibana_client.key" \ - -in "$scratch_dir/es_kibana_client.pem" -certfile "$ca_cert" -out "$scratch_dir/es_kibana_client.p12" \ - -keypbe AES-256-CBC -certpbe AES-256-CBC -passout env:ES_CERTIFICATE_PASSWORD +if [[ "$mode" != --admin-only ]]; then + openssl pkcs12 -export -name es_kibana_client -inkey "$scratch_dir/es_kibana_client.key" \ + -in "$scratch_dir/es_kibana_client.pem" -certfile "$ca_cert" -out "$scratch_dir/es_kibana_client.p12" \ + -keypbe AES-256-CBC -certpbe AES-256-CBC -passout env:OPENSEARCH_CERTIFICATE_PASSWORD +fi (umask 022; mkdir -p -- "$output_dir") set -o noclobber @@ -122,6 +141,8 @@ for file in "${files[@]}"; do published+=("$output_dir/$file") cat -- "$scratch_dir/$file" } > "$output_dir/$file" + case "$file" in + *.crt|*.csr|es_kibana_client.pem) chmod 644 "$output_dir/$file" ;; + esac done -chmod 644 "$output_dir"/es_kibana_client.{pem,csr} "$output_dir"/admin.{crt,csr} -printf 'Created OpenSearch Dashboards and admin certificates under %s\n' "$output_dir" +printf 'Created OpenSearch client certificates under %s\n' "$output_dir" diff --git a/deployment/scripts/security/create_opensearch_node_cert.sh b/deployment/scripts/security/create_opensearch_node_cert.sh index d416bbeb..3dab08b7 100755 --- a/deployment/scripts/security/create_opensearch_node_cert.sh +++ b/deployment/scripts/security/create_opensearch_node_cert.sh @@ -8,7 +8,7 @@ # # Requires: # - Bash, OpenSSL and Java keytool -# - ES_CERTIFICATE_PASSWORD for the PKCS#12 bundle and Java stores +# - OPENSEARCH_CERTIFICATE_PASSWORD for the PKCS#12 bundle and Java stores # - root-ca.pem and root-ca.key under certificates/root/ in SECURITY_DIR # # Optional settings: @@ -92,8 +92,6 @@ for node in "$@"; do done done -: "${ES_CERTIFICATE_PASSWORD:?Set ES_CERTIFICATE_PASSWORD}" -export ES_CERTIFICATE_PASSWORD for input in "$ca_cert" "$ca_key"; do if [[ ! -f "$input" || ! -r "$input" || ! -s "$input" ]]; then printf 'Missing or unreadable CA file %s. Run create_root_ca_cert.sh first.\n' "$input" >&2 @@ -110,6 +108,11 @@ if [[ -e "$ca_alias" || -L "$ca_alias" ]]; then write_ca_alias=false fi +# shellcheck source=password_prompt.sh +source "$script_dir/password_prompt.sh" +OPENSEARCH_CERTIFICATE_PASSWORD=${OPENSEARCH_CERTIFICATE_PASSWORD:-${OS_CERTIFICATE_PASSWORD:-}} +require_password OPENSEARCH_CERTIFICATE_PASSWORD + # Stage all node bundles before writing deployment files. Roll back writes on failure. scratch_dir=$(mktemp -d) published=() @@ -150,15 +153,15 @@ for node in "$@"; do # Preserve OpenSearch's original aliases and the separate leaf-pinning truststore. openssl pkcs12 -export -name "$node" -inkey "$stage.key" -in "$stage.crt" \ -certfile "$ca_cert" -out "$stage.p12" -keypbe AES-256-CBC -certpbe AES-256-CBC \ - -passout env:ES_CERTIFICATE_PASSWORD + -passout env:OPENSEARCH_CERTIFICATE_PASSWORD keytool -importkeystore -noprompt -alias "$node" \ - -srckeystore "$stage.p12" -srcstoretype PKCS12 -srcstorepass:env ES_CERTIFICATE_PASSWORD \ + -srckeystore "$stage.p12" -srcstoretype PKCS12 -srcstorepass:env OPENSEARCH_CERTIFICATE_PASSWORD \ -destkeystore "$stage-keystore.jks" -deststoretype JKS \ - -deststorepass:env ES_CERTIFICATE_PASSWORD -destkeypass:env ES_CERTIFICATE_PASSWORD + -deststorepass:env OPENSEARCH_CERTIFICATE_PASSWORD -destkeypass:env OPENSEARCH_CERTIFICATE_PASSWORD keytool -importcert -noprompt -alias root-ca -file "$ca_cert" \ - -keystore "$stage-keystore.jks" -storetype JKS -storepass:env ES_CERTIFICATE_PASSWORD + -keystore "$stage-keystore.jks" -storetype JKS -storepass:env OPENSEARCH_CERTIFICATE_PASSWORD keytool -importcert -noprompt -alias "$node" -file "$stage.crt" \ - -keystore "$stage-truststore.key" -storetype JKS -storepass:env ES_CERTIFICATE_PASSWORD + -keystore "$stage-truststore.key" -storetype JKS -storepass:env OPENSEARCH_CERTIFICATE_PASSWORD done # Private files inherit mode 0600, and noclobber protects concurrent writes. diff --git a/deployment/scripts/security/create_root_ca_cert.sh b/deployment/scripts/security/create_root_ca_cert.sh index 7730d6a6..baae3e01 100755 --- a/deployment/scripts/security/create_root_ca_cert.sh +++ b/deployment/scripts/security/create_root_ca_cert.sh @@ -10,7 +10,7 @@ # # Requires: # - Bash, OpenSSL and Java keytool -# - ROOT_CERTIFICATE_KEYSTORE_PASSWORD in the environment +# - ROOT_CERTIFICATE_KEYSTORE_PASSWORD (prompted when unset) # - ../../security/templates/ssl-extensions-x509.cnf relative to this script # # Output: @@ -53,10 +53,6 @@ CRT_FILE="$ROOT_DIR/$CA_NAME.crt" CSR_FILE="$ROOT_DIR/$CA_NAME.csr" TRUSTSTORE_FILE="$ROOT_DIR/$CA_NAME-truststore.jks" -# OpenSSL and keytool read the store password from the environment. -: "${ROOT_CERTIFICATE_KEYSTORE_PASSWORD:?Set ROOT_CERTIFICATE_KEYSTORE_PASSWORD}" -export ROOT_CERTIFICATE_KEYSTORE_PASSWORD - # === Protect existing CA material # Replacing a CA invalidates trust for certificates issued under the old key. for output in "$KEY_FILE" "$PEM_FILE" "$CRT_FILE" "$CSR_FILE" "$P12_FILE" "$JKS_FILE" "$TRUSTSTORE_FILE"; do @@ -66,6 +62,10 @@ for output in "$KEY_FILE" "$PEM_FILE" "$CRT_FILE" "$CSR_FILE" "$P12_FILE" "$JKS_ fi done +# shellcheck source=password_prompt.sh +source "$SCRIPT_DIR/password_prompt.sh" +require_password ROOT_CERTIFICATE_KEYSTORE_PASSWORD + # Build the entire bundle in a private temporary directory. If publication fails, # remove the files written by this run and clean up the temporary directory. scratch_dir=$(mktemp -d) diff --git a/deployment/scripts/security/load_nifi_auth.sh b/deployment/scripts/security/load_nifi_auth.sh new file mode 100644 index 00000000..4a0cc38f --- /dev/null +++ b/deployment/scripts/security/load_nifi_auth.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../../env/general.env +source "$script_dir/../../env/general.env" +namespace="${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}" +auth_file="${NIFI_AUTH_FILE:-$script_dir/../../env/authentication.env}" +# shellcheck disable=SC1090 # Optional deployment credentials. +if [[ -f "$auth_file" || -n ${NIFI_AUTH_FILE:-} ]]; then source "$auth_file"; fi +# shellcheck source=password_prompt.sh +source "$script_dir/password_prompt.sh" + +if [[ -z ${NIFI_SINGLE_USER_CREDENTIALS_USERNAME:-} && -t 0 ]]; then + IFS= read -r -p 'NiFi username: ' NIFI_SINGLE_USER_CREDENTIALS_USERNAME +fi +: "${NIFI_SINGLE_USER_CREDENTIALS_USERNAME:?Set NIFI_SINGLE_USER_CREDENTIALS_USERNAME or run in a terminal}" +# Reserve the checked-in password for Compose development. +if [[ ${NIFI_SINGLE_USER_CREDENTIALS_PASSWORD:-} == cogstackNiFi ]]; then + unset NIFI_SINGLE_USER_CREDENTIALS_PASSWORD +fi +require_password NIFI_SINGLE_USER_CREDENTIALS_PASSWORD +password=$NIFI_SINGLE_USER_CREDENTIALS_PASSWORD +if [[ "$password" == *[$'\r\n']* || ${#password} -lt 12 ]] || + (LC_ALL=C; (( ${#password} > 72 ))); then + printf 'NiFi login password must be one line, at least 12 characters and at most 72 bytes.\n' >&2 + exit 1 +fi +if [[ "$NIFI_SINGLE_USER_CREDENTIALS_USERNAME" == *[[:cntrl:]:]* || "$NIFI_SINGLE_USER_CREDENTIALS_USERNAME" == \#* ]]; then + printf 'NiFi username cannot contain colons or control characters, or start with #.\n' >&2 + exit 1 +fi +salt=$(openssl rand -hex 8) +hash=$(openssl passwd -6 -salt "rounds=100000\$$salt" -stdin <<< "$password") +NIFI_HTPASSWD="$NIFI_SINGLE_USER_CREDENTIALS_USERNAME:$hash" + +existing=$(kubectl -n "$namespace" get secret nifi-auth --ignore-not-found -o json) +version=$(jq -r '.metadata.resourceVersion' <<< "$existing") +key=$(jq -r '.data.NIFI_SENSITIVE_PROPS_KEY // "" | @base64d' <<< "$existing") +NIFI_SENSITIVE_PROPS_KEY=${key:-${NIFI_SENSITIVE_PROPS_KEY:-$(openssl rand -hex 16)}} +export NIFI_SENSITIVE_PROPS_KEY NIFI_HTPASSWD + +manifest=$(jq -n --arg version "$version" '{ + apiVersion: "v1", kind: "Secret", + metadata: {name: "nifi-auth", resourceVersion: (if $version == "" then null else $version end)}, + stringData: { + htpasswd: env.NIFI_HTPASSWD, + NIFI_SENSITIVE_PROPS_KEY: env.NIFI_SENSITIVE_PROPS_KEY + } +}') +if [[ -z "$version" ]]; then + kubectl -n "$namespace" create -f - <<< "$manifest" +else + kubectl -n "$namespace" replace -f - <<< "$manifest" +fi diff --git a/deployment/scripts/security/load_opensearch_auth.sh b/deployment/scripts/security/load_opensearch_auth.sh new file mode 100644 index 00000000..6b272ead --- /dev/null +++ b/deployment/scripts/security/load_opensearch_auth.sh @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +set -euo pipefail + +service=${1:-} +case "$service" in + opensearch|opensearch-dashboards) ;; + *) printf '%s\n' 'Specify opensearch or opensearch-dashboards.' >&2; exit 2 ;; +esac + +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +# shellcheck source=../../env/general.env +source "$script_dir/../../env/general.env" +namespace="${KUBE_NAMESPACE:?Set KUBE_NAMESPACE in env/general.env}" +if [[ "$service" == opensearch ]]; then + bootstrap=$(kubectl -n "$namespace" get secret opensearch-security-bootstrap --ignore-not-found -o name) + if [[ -n "$bootstrap" ]]; then + printf '%s\n' "$bootstrap already exists." + exit 0 + fi +fi + +auth_file=${OPENSEARCH_AUTH_FILE:-$script_dir/../../env/authentication.env} +# shellcheck disable=SC1090 # Optional deployment credentials. +if [[ -f "$auth_file" || -n ${OPENSEARCH_AUTH_FILE:-} ]]; then source "$auth_file"; fi +# shellcheck source=password_prompt.sh +source "$script_dir/password_prompt.sh" + +OPENSEARCH_KIBANA_PASSWORD=${OPENSEARCH_KIBANA_PASSWORD:-${KIBANA_PASSWORD:-}} +existing= +if [[ "$service" == opensearch-dashboards || -z "$OPENSEARCH_KIBANA_PASSWORD" ]]; then + existing=$(kubectl -n "$namespace" get secret dashboards-auth --ignore-not-found -o json) +fi +if [[ -z "$OPENSEARCH_KIBANA_PASSWORD" && -n "$existing" ]]; then + # Append a character so command substitution preserves trailing newlines. + stored_password=$(jq -j '(.data.password // "" | @base64d) + "."' <<< "$existing") + OPENSEARCH_KIBANA_PASSWORD=${stored_password%.} +fi +require_password OPENSEARCH_KIBANA_PASSWORD + +if [[ "$service" == opensearch ]]; then + policy="$script_dir/../../charts/opensearch/security" + internal_users=$( + printf '_meta:\n type: internalusers\n config_version: 2\n' + users=(kibanaserver nifi cogstack_pipeline cogstack_user admin) + passwords=("$OPENSEARCH_KIBANA_PASSWORD" "${OPENSEARCH_NIFI_PASSWORD:-${OS_NIFI_PASSWORD:-}}" + "${OPENSEARCH_PIPELINE_PASSWORD:-${OS_PIPELINE_PASSWORD:-}}" + "${OPENSEARCH_ANALYST_PASSWORD:-${OS_ANALYST_PASSWORD:-}}" "${OPENSEARCH_ADMIN_PASSWORD:-}") + for i in "${!users[@]}"; do + [[ -n "${passwords[i]}" ]] || continue + entry=$(bcrypt_entry "${users[i]}" "${passwords[i]}") || exit 1 + printf '%s:\n hash: "%s"\n' "${users[i]}" "${entry#*:}" + done + ) + roles_mapping=$(cat "$policy/roles_mapping.yml") + if [[ -n ${OPENSEARCH_ADMIN_PASSWORD:-} ]]; then + roles_mapping+=$'\n\nall_access:\n users: [admin]\n' + fi + kubectl -n "$namespace" create secret generic opensearch-security-bootstrap \ + --from-literal="internal_users.yml=$internal_users" \ + --from-file="roles.yml=$policy/roles.yml" \ + --from-literal="roles_mapping.yml=$roles_mapping" \ + --from-file="tenants.yml=$policy/tenants.yml" + exit +fi + +DASHBOARDS_COOKIE_DATA=$(jq -r '.data.cookie // ""' <<< "$existing") +if [[ -z "$DASHBOARDS_COOKIE_DATA" ]]; then + cookie=$(openssl rand -hex 16) + DASHBOARDS_COOKIE_DATA=$(printf '%s' "$cookie" | openssl base64 -A) +fi +export DASHBOARDS_COOKIE_DATA + +manifest=$(jq -s '.[0] | { + apiVersion: "v1", kind: "Secret", type: "Opaque", + metadata: {name: "dashboards-auth", resourceVersion: .metadata.resourceVersion}, + data: { + username: ("kibanaserver" | @base64), + password: (env.OPENSEARCH_KIBANA_PASSWORD | @base64), + cookie: env.DASHBOARDS_COOKIE_DATA + } +}' <<< "$existing") +if [[ -z "$existing" ]]; then + kubectl -n "$namespace" create -f - <<< "$manifest" +else + kubectl -n "$namespace" patch secret dashboards-auth --type=merge --patch-file=/dev/stdin <<< "$manifest" +fi diff --git a/deployment/scripts/security/password_prompt.sh b/deployment/scripts/security/password_prompt.sh new file mode 100644 index 00000000..c18e0436 --- /dev/null +++ b/deployment/scripts/security/password_prompt.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash + +require_password() { + local name=$1 password + + if [[ -n ${!name:-} ]]; then + export "${name?}" + return + fi + + if [[ ! -t 0 ]]; then + printf 'Set %s in the environment or run this command in a terminal.\n' "$name" >&2 + return 1 + fi + + if ! IFS= read -r -s -p "Enter $name: " password || [[ -z "$password" ]]; then + printf '\nSet %s to a nonempty password.\n' "$name" >&2 + return 1 + fi + + printf '\n' >&2 + export "$name=$password" +} + +bcrypt_entry() { + local user=$1 password=$2 LC_ALL=C + if [[ "$password" == *[$'\r\n']* || ${#password} -gt 72 ]]; then + printf 'The password for %s must fit on one line and be at most 72 bytes.\n' "$user" >&2 + return 1 + fi + printf '%s\n' "$password" | htpasswd -nBi -C 10 -- "$user" +} diff --git a/deployment/security/templates/ssl-extensions-x509.cnf b/deployment/security/templates/ssl-extensions-x509.cnf index a58badde..1b626038 100755 --- a/deployment/security/templates/ssl-extensions-x509.cnf +++ b/deployment/security/templates/ssl-extensions-x509.cnf @@ -23,7 +23,7 @@ authorityKeyIdentifier = keyid,issuer DNS.1 = nifi DNS.2 = localhost DNS.3 = cogstack-nifi -DNS.4 = cogstack-nifi-web +DNS.4 = cogstack-nifi-headless IP.1 = 127.0.0.1 [req]