diff --git a/.github/workflows/deploy-images-on-release.yml b/.github/workflows/deploy-images-on-release.yml index cf06f7840..a9b2dfdb8 100644 --- a/.github/workflows/deploy-images-on-release.yml +++ b/.github/workflows/deploy-images-on-release.yml @@ -79,18 +79,6 @@ jobs: run: | docker push ghcr.io/bluewave-labs/checkmate-mongo:${{ steps.extract_tag.outputs.version }} - - name: Build Redis Docker image - run: | - docker build \ - -t ghcr.io/bluewave-labs/checkmate-redis:${{ steps.extract_tag.outputs.version }} \ - -f ./docker/dist/redis.Dockerfile \ - --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \ - . - - - name: Push Redis Docker image - run: | - docker push ghcr.io/bluewave-labs/checkmate-redis:${{ steps.extract_tag.outputs.version }} - docker-build-and-push-server-mono-multiarch: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/deploy-images.yml b/.github/workflows/deploy-images.yml index fa39fed85..53d7ab368 100644 --- a/.github/workflows/deploy-images.yml +++ b/.github/workflows/deploy-images.yml @@ -74,18 +74,6 @@ jobs: run: | docker push ghcr.io/bluewave-labs/checkmate-mongo:latest - - name: Build Redis Docker image - run: | - docker build \ - -t ghcr.io/bluewave-labs/checkmate-redis:latest \ - -f ./docker/dist/redis.Dockerfile \ - --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \ - . - - - name: Push Redis Docker image - run: | - docker push ghcr.io/bluewave-labs/checkmate-redis:latest - docker-build-and-push-server-mono-multiarch: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/production-deploy.yml b/.github/workflows/production-deploy.yml index 7764c488b..532197710 100644 --- a/.github/workflows/production-deploy.yml +++ b/.github/workflows/production-deploy.yml @@ -71,17 +71,6 @@ jobs: - name: Push MongoDB Docker image run: docker push ghcr.io/bluewave-labs/checkmate:mongo-demo - - name: Build Redis Docker image - run: | - docker build \ - -t ghcr.io/bluewave-labs/checkmate:redis-demo \ - -f ./docker/prod/redis.Dockerfile \ - --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \ - . - - - name: Push Redis Docker image - run: docker push ghcr.io/bluewave-labs/checkmate:redis-demo - deploy-to-demo: needs: docker-build-and-push-server runs-on: ubuntu-latest diff --git a/.github/workflows/staging-deploy.yml b/.github/workflows/staging-deploy.yml index ea5477815..27b7e8690 100644 --- a/.github/workflows/staging-deploy.yml +++ b/.github/workflows/staging-deploy.yml @@ -71,17 +71,6 @@ jobs: - name: Push MongoDB Docker image run: docker push ghcr.io/bluewave-labs/checkmate:mongo-staging - - name: Build Redis Docker image - run: | - docker build \ - -t ghcr.io/bluewave-labs/checkmate:redis-staging \ - -f ./docker/staging/redis.Dockerfile \ - --label org.opencontainers.image.source=https://github.com/bluewave-labs/checkmate \ - . - - - name: Push Redis Docker image - run: docker push ghcr.io/bluewave-labs/checkmate:redis-staging - deploy-to-staging: needs: docker-build-and-push-server runs-on: ubuntu-latest diff --git a/README.md b/README.md index cc1b10e0e..048cf0706 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ This repository contains both the frontend and the backend of Checkmate, an open-source, self-hosted monitoring tool for tracking server hardware, uptime, response times, and incidents in real-time with beautiful visualizations. Checkmate regularly checks whether a server/website is accessible and performs optimally, providing real-time alerts and reports on the monitored services' availability, downtime, and response time. -Checkmate also has an agent, called [Capture](https://github.com/bluewave-labs/capture), to retrieve data from remote servers. While Capture is not required to run Checkmate, it provides additional insights about your servers' CPU, RAM, disk, and temperature status. +Checkmate also has an agent, called [Capture](https://github.com/bluewave-labs/capture), to retrieve data from remote servers. While Capture is not required to run Checkmate, it provides additional insights about your servers' CPU, RAM, disk, and temperature status. Capture can run on Linux, Windows, Mac, Raspberry Pi, or any device that can run Go. Checkmate has been stress-tested with 1000+ active monitors without any particular issues or performance bottlenecks. @@ -54,6 +54,12 @@ See installation instructions in [Checkmate documentation portal](https://docs.c Alternatively, you can also use [Coolify](https://coolify.io/), [Elestio](https://elest.io/open-source/checkmate), [K8s](./charts/helm/checkmate/INSTALLATION.md) or [Pikapods](https://www.pikapods.com/) to quickly spin off a Checkmate instance. If you would like to monitor your server infrastructure, you'll need [Capture agent](https://github.com/bluewave-labs/capture). Capture repository also contains the installation instructions. +### Using a Custom CA + +If you need to monitor internal HTTPS endpoints with certificates from private Certificate Authorities (like Smallstep), see our [Custom CA Trust Guide](./docs/custom-ca-trust.md) for Docker configuration options. + +For more documentation, see the [docs directory](./docs/). + ## Translations @@ -84,20 +90,22 @@ Feel free to ask questions or share your ideas - we'd love to hear from you! - Completely open source, deployable on your servers or home devices (e.g Raspberry Pi 4 or 5) - Website monitoring - Page speed monitoring -- Infrastructure monitoring (memory, disk usage, CPU performance etc) - requires [Capture](https://github.com/bluewave-labs/capture) agent +- Infrastructure monitoring (memory, disk usage, CPU performance, network etc) - requires [Capture](https://github.com/bluewave-labs/capture) agent - Docker monitoring - Ping monitoring - SSL monitoring - Port monitoring +- Game server monitoring (3.0) - Incidents at a glance - Status pages -- E-mail, Webhooks, Discord, Telegram, Slack notifications +- E-mail, Webhooks, Discord and Slack notifications - Scheduled maintenance - JSON query monitoring - Multi-language support for English, German, Japanese, Portuguese (Brazil), Russian, Turkish, Ukrainian, Vietnamese, Chinese (Traditional, Taiwan) **Short term roadmap:** +- Plugins that will help Checkmate get any information from a remote service (e.g database, etc) - Better notifications - Network monitoring - ..and a few more features @@ -139,7 +147,7 @@ If you would like to sponsor an additional feature, [see this page](https://chec ## Contributing -We are [Alex](http://github.com/ajhollid) (team lead), [Mohadeseh](http://github.com/mohicody), [Gorkem](http://github.com/gorkem-bwl/), [Owaise](http://github.com/Owaiseimdad), [Aryaman](https://github.com/Br0wnHammer), [Mert](https://github.com/mertssmnoglu) and [Karen](https://github.com/karenvicent) helping individuals and businesses monitor their infra and servers. +We are [Alex](http://github.com/ajhollid) (team lead), [Gorkem](http://github.com/gorkem-bwl/), [Owaise](http://github.com/Owaiseimdad), [Aryaman](https://github.com/Br0wnHammer), [Mert](https://github.com/mertssmnoglu) and [Karen](https://github.com/karenvicent) helping individuals and businesses monitor their infra and servers. We pride ourselves on building strong connections with contributors at every level. Despite being a young project, Checkmate has already earned 7000+ stars and attracted 90+ contributors from around the globe. diff --git a/client/src/Components/Charts/Utils/chartUtils.jsx b/client/src/Components/Charts/Utils/chartUtils.jsx index 414e1ff9c..e24881c1c 100644 --- a/client/src/Components/Charts/Utils/chartUtils.jsx +++ b/client/src/Components/Charts/Utils/chartUtils.jsx @@ -88,7 +88,51 @@ PercentTick.propTypes = { */ const getFormattedPercentage = (value) => { if (typeof value !== "number") return value; - return `${(value * 100).toFixed(2)}.%`; + return `${(value * 100).toFixed(2)}%`; +}; + +/** + * Custom tick component for rendering network bytes per second. + * + * @param {Object} props - The properties object. + * @param {number} props.x - The x-coordinate for the tick. + * @param {number} props.y - The y-coordinate for the tick. + * @param {Object} props.payload - The payload object containing tick data. + * @param {number} props.index - The index of the tick. + * @returns {JSX.Element|null} The rendered tick component or null for the first tick. + */ +export const NetworkTick = ({ x, y, payload, index, formatter }) => { + const theme = useTheme(); + if (index === 0) return null; + + if (formatter === undefined) { + formatter = (value, space = false) => { + if (typeof value !== "number") return value; + // need to add space between value and unit + return `${(value / 1024).toFixed(1)}${space ? " " : ""}Kbps`; + }; + } + + return ( + + {formatter(payload?.value, true)} + + ); +}; + +NetworkTick.propTypes = { + x: PropTypes.number, + y: PropTypes.number, + payload: PropTypes.object, + index: PropTypes.number, + formatter: PropTypes.func, }; /** @@ -112,6 +156,7 @@ export const InfrastructureTooltip = ({ yLabel, dotColor, dateRange, + formatter = getFormattedPercentage, }) => { const uiTimezone = useSelector((state) => state.ui.timezone); const theme = useTheme(); @@ -166,8 +211,8 @@ export const InfrastructureTooltip = ({ sx={{ opacity: 0.8 }} > {yIdx >= 0 - ? `${yLabel} ${getFormattedPercentage(payload[0].payload[hardwareType][yIdx][metric])}` - : `${yLabel} ${getFormattedPercentage(payload[0].payload[yKey])}`} + ? `${yLabel} ${formatter(payload[0].payload[hardwareType][yIdx][metric])}` + : `${yLabel} ${formatter(payload[0].payload[yKey])}`} diff --git a/client/src/Pages/Infrastructure/Details/Components/NetworkStats/NetworkCharts.jsx b/client/src/Pages/Infrastructure/Details/Components/NetworkStats/NetworkCharts.jsx new file mode 100644 index 000000000..9157a3432 --- /dev/null +++ b/client/src/Pages/Infrastructure/Details/Components/NetworkStats/NetworkCharts.jsx @@ -0,0 +1,132 @@ +import PropTypes from "prop-types"; +import { Stack, Typography } from "@mui/material"; +import InfraAreaChart from "../../../../../Pages/Infrastructure/Details/Components/AreaChartBoxes/InfraAreaChart"; + +import { + TzTick, + InfrastructureTooltip, + NetworkTick, +} from "../../../../../Components/Charts/Utils/chartUtils"; +import { useTheme } from "@emotion/react"; +import { useTranslation } from "react-i18next"; +import { useHardwareUtils } from "../../Hooks/useHardwareUtils"; + +const NetworkCharts = ({ ethernetData, dateRange }) => { + const theme = useTheme(); + const { t } = useTranslation(); + + const { formatBytesPerSecondString, formatPacketsPerSecondString } = useHardwareUtils(); + + if (!ethernetData?.length) { + return {t("noNetworkStatsAvailable")}; + } + + const configs = [ + { + type: "network-bytes", + data: ethernetData, + dataKeys: ["bytesPerSec"], + heading: t("dataReceived"), + strokeColor: theme.palette.info.main, + gradientStartColor: theme.palette.info.main, + yLabel: t("rate"), + xTick: , + yTick: , + toolTip: ( + + ), + }, + { + type: "network-packets", + data: ethernetData, + dataKeys: ["packetsPerSec"], + heading: t("packetsReceivedRate"), + strokeColor: theme.palette.success.main, + gradientStartColor: theme.palette.success.main, + yLabel: t("rate"), + xTick: , + yTick: , + toolTip: ( + + ), + }, + { + type: "network-errors", + data: ethernetData, + dataKeys: ["errors"], + heading: t("networkErrors"), + strokeColor: theme.palette.error.main, + gradientStartColor: theme.palette.error.main, + yLabel: t("errors"), + xTick: , + toolTip: ( + Math.round(value).toLocaleString()} + /> + ), + }, + { + type: "network-drops", + data: ethernetData, + dataKeys: ["drops"], + heading: t("networkDrops"), + strokeColor: theme.palette.warning.main, + gradientStartColor: theme.palette.warning.main, + yLabel: t("drops"), + xTick: , + toolTip: ( + Math.round(value).toLocaleString()} + /> + ), + }, + ]; + + return ( + *": { + flexBasis: `calc(50% - ${theme.spacing(8)})`, + maxWidth: `calc(50% - ${theme.spacing(8)})`, + }, + }} + > + {configs.map((config) => ( + + ))} + + ); +}; + +NetworkCharts.propTypes = { + ethernetData: PropTypes.array.isRequired, + dateRange: PropTypes.string.isRequired, +}; + +export default NetworkCharts; diff --git a/client/src/Pages/Infrastructure/Details/Components/NetworkStats/NetworkStatBoxes.jsx b/client/src/Pages/Infrastructure/Details/Components/NetworkStats/NetworkStatBoxes.jsx new file mode 100644 index 000000000..98ba90dae --- /dev/null +++ b/client/src/Pages/Infrastructure/Details/Components/NetworkStats/NetworkStatBoxes.jsx @@ -0,0 +1,81 @@ +import PropTypes from "prop-types"; +import StatusBoxes from "../../../../../Components/StatusBoxes"; +import StatBox from "../../../../../Components/StatBox"; +import { Typography } from "@mui/material"; +import { useTranslation } from "react-i18next"; +import { useHardwareUtils } from "../../Hooks/useHardwareUtils"; + +function formatNumber(num) { + return num != null ? num.toLocaleString() : "0"; +} + +const NetworkStatBoxes = ({ shouldRender, net, ifaceName }) => { + const { t } = useTranslation(); + const { formatBytes } = useHardwareUtils(); + + const filtered = net?.filter((iface) => iface.name === ifaceName) || []; + + if (!net?.length) { + return {t("noNetworkStatsAvailable")}; + } + + return ( + + {filtered + .map((iface) => [ + , + , + , + , + , + , + ]) + .flat()} + + ); +}; + +NetworkStatBoxes.propTypes = { + shouldRender: PropTypes.bool.isRequired, + net: PropTypes.arrayOf( + PropTypes.shape({ + name: PropTypes.string.isRequired, + bytes_sent: PropTypes.number, + bytes_recv: PropTypes.number, + packets_sent: PropTypes.number, + packets_recv: PropTypes.number, + err_in: PropTypes.number, + err_out: PropTypes.number, + }) + ), + ifaceName: PropTypes.string.isRequired, +}; + +export default NetworkStatBoxes; diff --git a/client/src/Pages/Infrastructure/Details/Components/NetworkStats/index.jsx b/client/src/Pages/Infrastructure/Details/Components/NetworkStats/index.jsx new file mode 100644 index 000000000..41d2b0a87 --- /dev/null +++ b/client/src/Pages/Infrastructure/Details/Components/NetworkStats/index.jsx @@ -0,0 +1,101 @@ +import PropTypes from "prop-types"; +import { useState, useEffect } from "react"; +import { Box } from "@mui/material"; +import { useTranslation } from "react-i18next"; +import { useTheme } from "@emotion/react"; +import Select from "../../../../../Components/Inputs/Select"; +import NetworkStatBoxes from "./NetworkStatBoxes"; +import NetworkCharts from "./NetworkCharts"; +import MonitorTimeFrameHeader from "../../../../../Components/MonitorTimeFrameHeader"; + +const getAvailableInterfaces = (net) => { + return (net || []).map((iface) => iface.name).filter(Boolean); +}; + +const getNetworkInterfaceData = (checks, ifaceName) => { + if (!ifaceName) return []; + + // Transform backend data structure for the selected interface + // Backend already calculates deltas, we just reshape the data + return (checks || []) + .map((check) => { + const networkInterface = (check.net || []).find( + (iface) => iface.name === ifaceName + ); + if (!networkInterface) return null; + return { + _id: check._id, + bytesPerSec: networkInterface.deltaBytesRecv, + packetsPerSec: networkInterface.deltaPacketsRecv, + errors: networkInterface.deltaErrOut ?? 0, + drops: networkInterface.deltaDropOut ?? 0, + }; + }) + .filter(Boolean); +}; + +const Network = ({ net, checks, isLoading, dateRange, setDateRange }) => { + const { t } = useTranslation(); + const theme = useTheme(); + + const availableInterfaces = getAvailableInterfaces(net); + const [selectedInterface, setSelectedInterface] = useState(""); + + // Set default interface when data loads + useEffect(() => { + if (availableInterfaces.length > 0 && !selectedInterface) { + setSelectedInterface(availableInterfaces[0]); + } + }, [availableInterfaces, selectedInterface]); + + const ethernetData = getNetworkInterfaceData(checks, selectedInterface); + + return ( + <> + + + {availableInterfaces.length > 0 && ( + { return ( - {t("queuePage.metricsTable.title")} - { const theme = useTheme(); // Local state - const [value, setValue] = useState(2); + const [value, setValue] = useState(0); // Handlers const handleChange = (event, newValue) => { @@ -29,6 +29,12 @@ const Logs = () => { diff --git a/client/src/Pages/PageSpeed/Create/index.jsx b/client/src/Pages/PageSpeed/Create/index.jsx index 78709093a..46bc7f977 100644 --- a/client/src/Pages/PageSpeed/Create/index.jsx +++ b/client/src/Pages/PageSpeed/Create/index.jsx @@ -152,7 +152,7 @@ const PageSpeedSetup = () => { }); const { error } = monitorValidation.validate( - { [name]: value }, + { [name]: value, type: monitor.type }, { abortEarly: false } ); setErrors((prev) => ({ diff --git a/client/src/Utils/Theme/globalTheme.js b/client/src/Utils/Theme/globalTheme.js index ce58153ec..bda415c90 100644 --- a/client/src/Utils/Theme/globalTheme.js +++ b/client/src/Utils/Theme/globalTheme.js @@ -564,6 +564,10 @@ const baseTheme = (palette) => ({ "& .MuiSelect-icon": { color: theme.palette.primary.contrastTextSecondary, // Dropdown + color }, + "& .MuiSelect-select": { + display: "flex", + alignItems: "center", + }, "&:hover": { backgroundColor: theme.palette.primary.main, // Background on hover }, diff --git a/client/src/locales/en.json b/client/src/locales/en.json index ecb080357..857825c9f 100644 --- a/client/src/locales/en.json +++ b/client/src/locales/en.json @@ -202,6 +202,13 @@ "avgCpuTemperature": "Average CPU Temperature", "bar": "Bar", "basicInformation": "Basic Information", + "bytesPerSecond": "Bytes per second", + "bytesReceived": "Bytes Received", + "bytesSent": "Bytes Sent", + "dataReceived": "Data Received", + "dataSent": "Data Sent", + "dataRate": "Data Rate", + "rate": "Rate", "bulkImport": { "fallbackPage": "Import a file to upload a list of servers in bulk", "invalidFileType": "Invalid file type", @@ -334,6 +341,15 @@ }, "disk": "Disk", "diskUsage": "Disk Usage", + "drops": "Drops", + "errors": "Errors", + "errorsIn": "Errors In", + "errorsOut": "Errors Out", + "networkErrors": "Network Errors", + "networkDrops": "Network Drops", + "networkInterface": "Network Interface", + "selectInterface": "Select Interface", + "details": "Details", "displayName": "Display name", "distributedRightCategoryTitle": "Monitor", "distributedStatusHeaderText": "Real-time, real-device coverage", @@ -639,7 +655,9 @@ }, "ms": "ms", "navControls": "Controls", + "network": "Network", "nextWindow": "Next window", + "noNetworkStatsAvailable": "No network stats available.", "notFoundButton": "Go to the main dashboard", "notificationConfig": { "description": "Select the notifications channels you want to use", @@ -751,6 +769,10 @@ "passwordRequirements": "New password must contain at least 8 characters and must have at least one uppercase letter, one lowercase letter, one number and one special character.", "saving": "Saving..." }, + "packetsPerSecond": "Packets per second", + "packetsReceived": "Packets Received", + "packetsReceivedRate": "Packets Received Rate", + "packetsSent": "Packets Sent", "pause": "Pause", "pingMonitoring": "Ping monitoring", "pingMonitoringDescription": "Check whether your server is available or not.", diff --git a/client/vite.config.js b/client/vite.config.js index 44a5905c5..df686d751 100644 --- a/client/vite.config.js +++ b/client/vite.config.js @@ -5,7 +5,7 @@ import { execSync } from "child_process"; export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd(), ""); - let version = 2.3; + let version = "3.0-beta"; return { base: "/", diff --git a/docker/.gitignore b/docker/.gitignore index 9a6df883a..76567d514 100755 --- a/docker/.gitignore +++ b/docker/.gitignore @@ -12,3 +12,13 @@ dist/docker-compose-test.yaml /dist-mono/redis/data/* /dist-arm/mongo/data/* *.env + +# Custom CA certificates and keys (should not be committed) +dev/certs/* +!dev/certs/.gitkeep + +# Certificate artifacts +*.key +*.csr +*.srl +*.log diff --git a/docker/dev/certs/.gitkeep b/docker/dev/certs/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/docker/dev/docker-compose.custom-ca-example.yaml b/docker/dev/docker-compose.custom-ca-example.yaml new file mode 100644 index 000000000..a5d7e2f43 --- /dev/null +++ b/docker/dev/docker-compose.custom-ca-example.yaml @@ -0,0 +1,30 @@ +# Dev/Test only: Not required in production +# Example Docker Compose configuration for custom CA trust +# This file demonstrates how to configure Checkmate to trust custom CAs +# +# Usage: docker-compose -f docker-compose.yaml -f docker-compose.custom-ca-example.yaml up + +services: + server: + image: uptime_server:latest + restart: always + ports: + - "52345:52345" + env_file: + - server.env + environment: + # Mount your custom CA certificate + NODE_EXTRA_CA_CERTS: /certs/custom-ca.pem + volumes: + # Mount the certs directory (read-only for security) + - ./certs:/certs:ro + depends_on: + - redis + - mongodb + # Optional: Add healthcheck to ensure the server starts properly + healthcheck: + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:52345/api/v1/health"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 40s diff --git a/docker/dev/docker-compose.yaml b/docker/dev/docker-compose.yaml index f0b193b2d..a2c66c027 100755 --- a/docker/dev/docker-compose.yaml +++ b/docker/dev/docker-compose.yaml @@ -19,29 +19,17 @@ services: env_file: - server.env depends_on: - - redis - mongodb - redis: - image: uptime_redis:latest - restart: always - volumes: - - ./redis/data:/data - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 30s - timeout: 10s - retries: 5 - start_period: 5s mongodb: image: uptime_mongo:latest restart: always - command: ["mongod", "--quiet", "--replSet", "rs0", "--bind_ip_all"] + command: ["mongod", "--quiet", "--bind_ip_all"] volumes: - ./mongo/data:/data/db healthcheck: - test: echo "try { rs.status() } catch (err) { rs.initiate({_id:'rs0',members:[{_id:0,host:'mongodb:27017'}]}) }" | mongosh --port 27017 --quiet + test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')", "--quiet"] interval: 5s timeout: 30s start_period: 0s start_interval: 1s - retries: 30 \ No newline at end of file + retries: 30 diff --git a/docker/dev/nginx-test/docker-compose.nginx-test.yaml b/docker/dev/nginx-test/docker-compose.nginx-test.yaml new file mode 100644 index 000000000..766e839bd --- /dev/null +++ b/docker/dev/nginx-test/docker-compose.nginx-test.yaml @@ -0,0 +1,13 @@ +# Dev/Test only: Not required in production +# Docker Compose configuration for nginx test service + +services: + nginx-test: + image: nginx:alpine + ports: + - "8443:443" + volumes: + - ../certs/host-int-cert.pem:/etc/nginx/certs/server.crt:ro + - ../certs/host-int-key.pem:/etc/nginx/certs/server.key:ro + - ./nginx.conf:/etc/nginx/nginx.conf:ro + restart: unless-stopped diff --git a/docker/dev/nginx-test/nginx.conf b/docker/dev/nginx-test/nginx.conf new file mode 100644 index 000000000..81c4c9240 --- /dev/null +++ b/docker/dev/nginx-test/nginx.conf @@ -0,0 +1,14 @@ +# Dev/Test only: Not required in production +# Nginx configuration for testing custom CA trust functionality + +events {} +http { + server { + listen 443 ssl; + ssl_certificate /etc/nginx/certs/server.crt; + ssl_certificate_key /etc/nginx/certs/server.key; + location / { + return 200 "hello from tls\n"; + } + } +} diff --git a/docker/dev/redis.Dockerfile b/docker/dev/redis.Dockerfile deleted file mode 100755 index af68ec61e..000000000 --- a/docker/dev/redis.Dockerfile +++ /dev/null @@ -1,2 +0,0 @@ -FROM redis -EXPOSE 6379 \ No newline at end of file diff --git a/docker/dist-arm/docker-compose.yaml b/docker/dist-arm/docker-compose.yaml index 921d3b8c1..96bbf8f3f 100644 --- a/docker/dist-arm/docker-compose.yaml +++ b/docker/dist-arm/docker-compose.yaml @@ -7,7 +7,7 @@ services: environment: - UPTIME_APP_API_BASE_URL=http://localhost:52345/api/v1 - UPTIME_APP_CLIENT_HOST=http://localhost - - DB_CONNECTION_STRING=mongodb://mongodb:27017/uptime_db?replicaSet=rs0 + - DB_CONNECTION_STRING=mongodb://mongodb:27017/uptime_db - REDIS_URL=redis://redis:6379 - CLIENT_HOST=http://localhost - JWT_SECRET=my_secret @@ -22,22 +22,10 @@ services: - "27017:27017" volumes: - ./mongo/data:/data/db - - mongo-init: - image: mongo:4.4.18 - depends_on: - - mongodb - entrypoint: > - bash -c " - echo 'Waiting for MongoDB to be ready...' && - until mongo --host mongodb --eval 'db.adminCommand(\"ping\")' > /dev/null 2>&1; do - sleep 2 - done && - echo 'MongoDB is up. Initiating replica set...' && - mongo --host mongodb --eval ' - rs.initiate({ - _id: \"rs0\", - members: [{ _id: 0, host: \"mongodb:27017\" }] - }) - ' || echo 'Replica set may already be initialized.' - " + healthcheck: + test: ["CMD", "mongo", "--eval", "db.runCommand({ ping: 1 })", "--quiet"] + interval: 5s + timeout: 30s + start_period: 0s + start_interval: 1s + retries: 30 diff --git a/docker/dist-mono/build_images.sh b/docker/dist-mono/build_images.sh index b56b9052c..e3a0233d4 100755 --- a/docker/dist-mono/build_images.sh +++ b/docker/dist-mono/build_images.sh @@ -5,10 +5,9 @@ cd "$(dirname "$0")" cd ../.. # Define service names and their corresponding Dockerfiles in parallel arrays -services=("mono_mongo" "mono_redis" "mono_server") +services=("mono_mongo" "mono_server") dockerfiles=( "./docker/dist-mono/mongoDB.Dockerfile" - "./docker/dist-mono/redis.Dockerfile" "./docker/dist-mono/server.Dockerfile" ) diff --git a/docker/dist-mono/docker-compose.yaml b/docker/dist-mono/docker-compose.yaml index 0dd97aafb..0e0b49445 100755 --- a/docker/dist-mono/docker-compose.yaml +++ b/docker/dist-mono/docker-compose.yaml @@ -7,8 +7,7 @@ services: environment: - UPTIME_APP_API_BASE_URL=http://localhost:52345/api/v1 - UPTIME_APP_CLIENT_HOST=http://localhost - - DB_CONNECTION_STRING=mongodb://mongodb:27017/uptime_db?replicaSet=rs0 - - REDIS_URL=redis://redis:6379 + - DB_CONNECTION_STRING=mongodb://mongodb:27017/uptime_db - CLIENT_HOST=http://localhost - JWT_SECRET=my_secret depends_on: @@ -16,11 +15,11 @@ services: mongodb: image: ghcr.io/bluewave-labs/checkmate-mongo:latest restart: always - command: ["mongod", "--quiet", "--replSet", "rs0", "--bind_ip_all"] + command: ["mongod", "--quiet", "--bind_ip_all"] volumes: - ./mongo/data:/data/db healthcheck: - test: echo "try { rs.status() } catch (err) { rs.initiate({_id:'rs0',members:[{_id:0,host:'mongodb:27017'}]}) }" | mongosh --port 27017 --quiet + test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')", "--quiet"] interval: 5s timeout: 30s start_period: 0s diff --git a/docker/dist-mono/redis.Dockerfile b/docker/dist-mono/redis.Dockerfile deleted file mode 100755 index af68ec61e..000000000 --- a/docker/dist-mono/redis.Dockerfile +++ /dev/null @@ -1,2 +0,0 @@ -FROM redis -EXPOSE 6379 \ No newline at end of file diff --git a/docker/dist/build_images.sh b/docker/dist/build_images.sh index 953682175..84fbb7d5a 100755 --- a/docker/dist/build_images.sh +++ b/docker/dist/build_images.sh @@ -7,7 +7,6 @@ cd ../../ declare -A services=( ["bluewaveuptime/uptime_client"]="./docker/dist/client.Dockerfile" ["bluewaveuptime/uptime_database_mongo"]="./docker/dist/mongoDB.Dockerfile" - ["bluewaveuptime/uptime_redis"]="./docker/dist/redis.Dockerfile" ["bluewaveuptime/uptime_server"]="./docker/dist/server.Dockerfile" ) diff --git a/docker/dist/docker-compose.yaml b/docker/dist/docker-compose.yaml index ff2f1b7ea..2e845daab 100755 --- a/docker/dist/docker-compose.yaml +++ b/docker/dist/docker-compose.yaml @@ -18,8 +18,7 @@ services: depends_on: - mongodb environment: - - DB_CONNECTION_STRING=mongodb://mongodb:27017/uptime_db?replicaSet=rs0 - - REDIS_URL=redis://redis:6379 + - DB_CONNECTION_STRING=mongodb://mongodb:27017/uptime_db - CLIENT_HOST=http://localhost - JWT_SECRET=my_secret # volumes: @@ -29,9 +28,9 @@ services: restart: always volumes: - ./mongo/data:/data/db - command: ["mongod", "--quiet", "--replSet", "rs0", "--bind_ip_all"] + command: ["mongod", "--quiet", "--bind_ip_all"] healthcheck: - test: echo "try { rs.status() } catch (err) { rs.initiate({_id:'rs0',members:[{_id:0,host:'mongodb:27017'}]}) }" | mongosh --port 27017 --quiet + test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')", "--quiet"] interval: 5s timeout: 30s start_period: 0s diff --git a/docker/dist/redis.Dockerfile b/docker/dist/redis.Dockerfile deleted file mode 100755 index af68ec61e..000000000 --- a/docker/dist/redis.Dockerfile +++ /dev/null @@ -1,2 +0,0 @@ -FROM redis -EXPOSE 6379 \ No newline at end of file diff --git a/docker/prod/build_images.sh b/docker/prod/build_images.sh index 23e91355c..49f8c7841 100755 --- a/docker/prod/build_images.sh +++ b/docker/prod/build_images.sh @@ -8,7 +8,6 @@ cd ../../ declare -A services=( ["uptime_client"]="./docker/prod/client.Dockerfile" ["uptime_database_mongo"]="./docker/prod/mongoDB.Dockerfile" - ["uptime_redis"]="./docker/prod/redis.Dockerfile" ["uptime_server"]="./docker/prod/server.Dockerfile" ) diff --git a/docker/prod/docker-compose.yaml b/docker/prod/docker-compose.yaml index 980a0e2f5..6e29fd90a 100755 --- a/docker/prod/docker-compose.yaml +++ b/docker/prod/docker-compose.yaml @@ -37,16 +37,26 @@ services: mongodb: image: ghcr.io/bluewave-labs/checkmate:mongo-demo restart: always - command: ["mongod", "--quiet", "--replSet", "rs0", "--bind_ip_all"] + command: ["mongod", "--quiet", "--bind_ip_all"] volumes: - ./mongo/data:/data/db - # - ./mongo/init/init.js:/docker-entrypoint-initdb.d/init.js // No longer needed env_file: - mongo.env healthcheck: - test: echo "try { rs.status() } catch (err) { rs.initiate({_id:'rs0',members:[{_id:0,host:'mongodb:27017'}]}) }" | mongosh --port 27017 --quiet + test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')", "--quiet"] interval: 5s timeout: 30s start_period: 0s start_interval: 1s retries: 30 + capture: + image: ghcr.io/bluewave-labs/capture:latest + container_name: capture + restart: unless-stopped + ports: + - "59232:59232" + environment: + - API_SECRET=my_secret + - GIN_MODE=release + volumes: + - /etc/os-release:/etc/os-release:ro diff --git a/docker/prod/redis.Dockerfile b/docker/prod/redis.Dockerfile deleted file mode 100755 index af68ec61e..000000000 --- a/docker/prod/redis.Dockerfile +++ /dev/null @@ -1,2 +0,0 @@ -FROM redis -EXPOSE 6379 \ No newline at end of file diff --git a/docker/staging/build_images.sh b/docker/staging/build_images.sh index ccfd451ba..a11aebf7c 100755 --- a/docker/staging/build_images.sh +++ b/docker/staging/build_images.sh @@ -8,7 +8,6 @@ cd ../../ declare -A services=( ["uptime_client"]="./docker/staging/client.Dockerfile" ["uptime_database_mongo"]="./docker/staging/mongoDB.Dockerfile" - ["uptime_redis"]="./docker/staging/redis.Dockerfile" ["uptime_server"]="./docker/staging/server.Dockerfile" ) diff --git a/docker/staging/docker-compose.yaml b/docker/staging/docker-compose.yaml index b9ca52b6e..f4ed5ce6f 100755 --- a/docker/staging/docker-compose.yaml +++ b/docker/staging/docker-compose.yaml @@ -31,36 +31,32 @@ services: env_file: - server.env depends_on: - - redis - mongodb - redis: - image: ghcr.io/bluewave-labs/checkmate:redis-staging - restart: always - ports: - - "6379:6379" - volumes: - - ./redis/data:/data - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 30s - timeout: 10s - retries: 5 - start_period: 5s mongodb: image: ghcr.io/bluewave-labs/checkmate:mongo-staging restart: always - command: ["mongod", "--quiet", "--replSet", "rs0", "--bind_ip_all"] + command: ["mongod", "--quiet", "--bind_ip_all"] ports: - "27017:27017" volumes: - ./mongo/data:/data/db - # - ./mongo/init/02_create_users.js:/docker-entrypoint-initdb.d/02_create_users.js // No longer needed env_file: - mongo.env healthcheck: - test: echo "try { rs.status() } catch (err) { rs.initiate({_id:'rs0',members:[{_id:0,host:'mongodb:27017'}]}) }" | mongosh --port 27017 --quiet + test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')", "--quiet"] interval: 5s timeout: 30s start_period: 0s start_interval: 1s retries: 30 + capture: + image: ghcr.io/bluewave-labs/capture:latest + container_name: capture + restart: unless-stopped + ports: + - "59232:59232" + environment: + - API_SECRET=my_secret + - GIN_MODE=release + volumes: + - /etc/os-release:/etc/os-release:ro diff --git a/docker/staging/redis.Dockerfile b/docker/staging/redis.Dockerfile deleted file mode 100755 index af68ec61e..000000000 --- a/docker/staging/redis.Dockerfile +++ /dev/null @@ -1,2 +0,0 @@ -FROM redis -EXPOSE 6379 \ No newline at end of file diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..dc245e21e --- /dev/null +++ b/docs/README.md @@ -0,0 +1,38 @@ +# Checkmate Documentation + +Welcome to the Checkmate documentation. This directory contains guides and references for various aspects of Checkmate deployment and configuration. + +## Available Documentation + +### Deployment & Configuration +- **[Custom CA Trust Guide](./custom-ca-trust.md)** - Configure Checkmate to trust custom Certificate Authorities +- **[Custom CA Quick Reference](./custom-ca-quick-reference.md)** - Quick setup guide for custom CA trust + +## Docker Configuration + +### Custom CA Trust +If you need to monitor internal HTTPS endpoints with certificates from private Certificate Authorities (like Smallstep), see our custom CA trust documentation: + +- **Full Guide**: [Custom CA Trust Guide](./custom-ca-trust.md) +- **Quick Reference**: [Custom CA Quick Reference](./custom-ca-quick-reference.md) + +### Example Configurations +The `docker/dev/` directory contains example configurations: +- `docker-compose.custom-ca-example.yaml` - Example Docker Compose with custom CA +- `server-custom-ca.Dockerfile` - Example Dockerfile for OS-level CA trust +- `export-smallstep-ca.sh` - Helper script for Smallstep CA export + +## Contributing to Documentation + +If you find issues or want to improve the documentation: + +1. Check existing issues and discussions +2. Submit a pull request with your changes +3. Follow the same markdown formatting style +4. Include practical examples and code snippets + +## Getting Help + +- [GitHub Discussions](https://github.com/bluewave-labs/checkmate/discussions) +- [Discord Channel](https://discord.gg/NAb6H3UTjK) +- [Documentation Portal](https://docs.checkmate.so/) diff --git a/docs/custom-ca-quick-reference.md b/docs/custom-ca-quick-reference.md new file mode 100644 index 000000000..71ea3b954 --- /dev/null +++ b/docs/custom-ca-quick-reference.md @@ -0,0 +1,60 @@ +# Custom CA Trust - Quick Reference + +## Fast Setup (Node-level) + +1. **Export your CA certificate:** + ```bash + # For Smallstep + step certificate inspect --format pem step-ca/root_ca.crt > docker/dev/certs/custom-ca.pem + ``` + +2. **Use the provided example override:** + ```bash + docker-compose -f docker-compose.yaml -f docker-compose.custom-ca-example.yaml up -d + ``` + +3. **Or manually update docker-compose.yaml:** + ```yaml + services: + server: + environment: + NODE_EXTRA_CA_CERTS: /certs/custom-ca.pem + volumes: + - ./certs:/certs:ro + ``` + +## Alternative Setup (OS-level) + +1. **Use custom Dockerfile:** + ```bash + docker-compose -f docker-compose.yaml -f docker-compose.custom-ca.yaml up + ``` + +## File Structure +``` +docker/dev/ +├── docker-compose.yaml +├── docker-compose.custom-ca-example.yaml # Example config +├── certs/ +│ ├── README.md +│ └── custom-ca.pem # Your CA certificate +└── export-smallstep-ca.sh # Helper script +``` + +## Environment Variables +- `NODE_EXTRA_CA_CERTS=/certs/custom-ca.pem` - Node.js trust +- Mount `./certs:/certs:ro` - Volume mount + +## Security +- ✅ Only trust CAs you control +- ✅ Use read-only volume mounts +- ✅ Keep certificates out of version control +- ❌ Never trust untrusted CAs + +## Troubleshooting +- Check container logs: `docker-compose logs server` +- Verify certificate: `docker exec -it ls -la /certs/` +- Test connection: `docker exec -it wget --ca-certificate=/certs/custom-ca.pem https://your-internal-site.com` + +## Full Documentation +See [Custom CA Trust Guide](./custom-ca-trust.md) for detailed instructions. diff --git a/docs/custom-ca-trust.md b/docs/custom-ca-trust.md new file mode 100644 index 000000000..b3a19831f --- /dev/null +++ b/docs/custom-ca-trust.md @@ -0,0 +1,234 @@ +# Custom Certificate Authority Trust + +This guide explains how to configure Checkmate to trust custom Certificate Authorities (CAs) when running in Docker, particularly useful for internal/private CAs like Smallstep. + +## Understanding Certificate Authorities + +Certificate Authorities (CAs) are entities that issue and manage digital certificates. While public CAs (like Let's Encrypt, DigiCert) are trusted by default in most systems, private or internal CAs (like those issued by Smallstep, internal PKI systems) require explicit trust configuration. + +When Checkmate monitors HTTPS endpoints with certificates from private CAs, it may show them as "DOWN" due to certificate validation failures, even if the service is actually accessible. + +## Node-level Trust Approach + +The simplest approach is to mount your custom CA certificate and configure Node.js to trust it using the `NODE_EXTRA_CA_CERTS` environment variable. + +### Docker Compose Configuration + +Add a volume mount for your CA certificate and set the environment variable: + +```yaml +services: + server: + image: uptime_server:latest + restart: always + ports: + - "52345:52345" + env_file: + - server.env + environment: + NODE_EXTRA_CA_CERTS: /certs/custom-ca.pem + volumes: + - ./certs:/certs:ro + depends_on: + - redis + - mongodb +``` + +### Directory Structure + +Create a `certs` directory in your Docker Compose project root: + +``` +docker/dev/ +├── docker-compose.yaml +├── certs/ +│ └── custom-ca.pem +└── ... +``` + +## OS-level Trust Approach (Debian-based) + +For more comprehensive trust configuration, you can create a derived Dockerfile that installs your CA at the OS level. + +### Custom Dockerfile + +Create `docker/dev/server-custom-ca.Dockerfile`: + +```dockerfile +FROM node:20-alpine + +# Install ca-certificates for Alpine +RUN apk add --no-cache ca-certificates + +WORKDIR /app + +COPY ./server/package*.json ./ + +RUN npm install + +COPY ./server/ ./ + +# Copy your custom CA certificate +COPY ./certs/custom-ca.crt /usr/local/share/ca-certificates/ + +# Update CA certificates +RUN update-ca-certificates + +EXPOSE 52345 + +CMD ["node", "src/index.js"] +``` + +### Docker Compose Override + +Create `docker/dev/docker-compose.custom-ca.yaml`: + +```yaml +services: + server: + build: + context: . + dockerfile: server-custom-ca.Dockerfile + restart: always + ports: + - "52345:52345" + env_file: + - server.env + depends_on: + - redis + - mongodb +``` + +Run with: `docker-compose -f docker-compose.yaml -f docker-compose.custom-ca.yaml up` + +## Alpine Linux Considerations + +Since Checkmate uses Alpine Linux as the base image, you need to install the `ca-certificates` package: + +```dockerfile +# Install ca-certificates for Alpine +RUN apk add --no-cache ca-certificates + +# Copy and update CA certificates +COPY ./certs/custom-ca.crt /usr/local/share/ca-certificates/ +RUN update-ca-certificates +``` + +## Smallstep CA Configuration + +If you're using Smallstep as your internal CA, you can export the root CA certificate: + +### Export Smallstep Root CA + +```bash +# Export the root CA certificate +step certificate inspect --format pem step-ca/root_ca.crt > custom-ca.pem + +# Or if you have the CA URL configured +step certificate inspect --format pem $(step path)/certs/root_ca.crt > custom-ca.pem +``` + +### Using the Exported Certificate + +1. Copy the exported `custom-ca.pem` to your `docker/dev/certs/` directory +2. Use either the Node-level or OS-level approach above +3. Restart your Checkmate server container + +## Security Considerations + +⚠️ **Important Security Warning**: Only trust CAs that you control or explicitly trust. Adding untrusted CAs can compromise the security of your monitoring system. + +- **Private CAs**: Only trust CAs from your organization's PKI infrastructure +- **Self-signed certificates**: Consider using proper CA infrastructure instead +- **Certificate validation**: Ensure your CA certificates are valid and not expired +- **Access control**: Limit access to the CA certificate files in production + +## Troubleshooting + +### Verify CA Trust + +Test if your CA is trusted by the container: + +```bash +# Enter the running container +docker exec -it sh + +# Check if the CA is in the trust store +ls -la /usr/local/share/ca-certificates/ +cat /etc/ssl/certs/ca-certificates.crt | grep -A 5 -B 5 "YOUR_CA_NAME" +``` + +### Common Issues + +1. **Permission denied**: Ensure the CA certificate file has proper read permissions +2. **Certificate format**: Use PEM format (.pem, .crt) for best compatibility +3. **Container restart**: Always restart the container after adding new CA certificates +4. **Path issues**: Verify the certificate path in your volume mounts + +## Example: Complete Working Setup + +Here's a complete example for a Smallstep CA setup. This demonstrates both the baseline failure (expected) and the custom CA success: + +### Baseline Test (Should Fail) +1. **Start Checkmate without custom CA trust:** + ```bash + cd docker/dev + docker-compose up -d + ``` + +2. **Test connection to internal HTTPS endpoint:** + ```bash + # This should fail with TLS error (unknown CA) + docker-compose exec server node -e " + const https = require('https'); + https.get('https://your-internal-site.com', res => { + console.log('STATUS:', res.statusCode); + }).on('error', e => { + console.error('ERR:', e.message); + }); + " + ``` + **Expected result**: TLS error due to unknown CA + +### Custom CA Test (Should Succeed) +1. **Export Smallstep Root CA:** + ```bash + step certificate inspect --format pem step-ca/root_ca.crt > docker/dev/certs/smallstep-root-ca.pem + ``` + +2. **Update docker-compose.yaml with custom CA trust:** + ```yaml + services: + server: + environment: + NODE_EXTRA_CA_CERTS: /certs/smallstep-root-ca.pem + volumes: + - ./certs:/certs:ro + ``` + +3. **Restart with custom CA:** + ```bash + docker-compose down + docker-compose -f docker-compose.yaml -f docker-compose.custom-ca-example.yaml up -d + ``` + +4. **Test the same connection:** + ```bash + # This should now succeed + docker-compose exec server node -e " + const https = require('https'); + https.get('https://your-internal-site.com', res => { + console.log('STATUS:', res.statusCode); + }).on('error', e => { + console.error('ERR:', e.message); + }); + " + ``` + **Expected result**: HTTP 200 OK + +### Verification +- **Baseline**: TLS failure proves default behavior (unknown CA) +- **Custom CA**: TLS success proves custom CA trust is working +- **Both tests must pass** to confirm the feature works correctly + +Your Checkmate server should now trust certificates issued by your Smallstep CA, allowing you to monitor internal HTTPS endpoints without disabling SSL validation. diff --git a/scripts/dev/setup-custom-ca.sh b/scripts/dev/setup-custom-ca.sh new file mode 100755 index 000000000..699f70bbd --- /dev/null +++ b/scripts/dev/setup-custom-ca.sh @@ -0,0 +1,143 @@ +#!/usr/bin/env bash + +# Dev/Test only: Not required in production +# This script generates test certificates for development and testing purposes + +set -euo pipefail + +# Colors for output +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Configuration +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +CERTS_DIR="$REPO_ROOT/docker/dev/certs" + +# Function to print colored output +print_status() { + local status=$1 + local message=$2 + case $status in + "PASS") + echo -e "${GREEN}[PASS]${NC} $message" + ;; + "INFO") + echo -e "${BLUE}[INFO]${NC} $message" + ;; + "WARN") + echo -e "${YELLOW}[WARN]${NC} $message" + ;; + esac +} + +# Function to check if a command exists +command_exists() { + command -v "$1" >/dev/null 2>&1 +} + +# Function to generate certificates using mkcert +generate_certs_mkcert() { + print_status "INFO" "Generating certificates using mkcert..." + + # Install mkcert CA (ignore if already done) + mkcert -install 2>/dev/null || true + + # Copy root CA + local ca_root + ca_root=$(mkcert -CAROOT) + cp "$ca_root/rootCA.pem" "$CERTS_DIR/custom-ca.pem" + + # Generate server certificate + mkcert -key-file "$CERTS_DIR/host-int-key.pem" \ + -cert-file "$CERTS_DIR/host-int-cert.pem" \ + host.docker.internal + + print_status "PASS" "Certificates generated using mkcert" +} + +# Function to generate certificates using OpenSSL +generate_certs_openssl() { + print_status "INFO" "Generating certificates using OpenSSL..." + + # Create CA private key + openssl genrsa -out "$CERTS_DIR/ca.key" 2048 + + # Create CA certificate + openssl req -new -x509 -days 365 -key "$CERTS_DIR/ca.key" \ + -out "$CERTS_DIR/custom-ca.pem" \ + -subj "/C=US/ST=Test/L=Test/O=Test CA/CN=Test Root CA" + + # Create server private key + openssl genrsa -out "$CERTS_DIR/host-int-key.pem" 2048 + + # Create server certificate signing request + openssl req -new -key "$CERTS_DIR/host-int-key.pem" \ + -out "$CERTS_DIR/host-int-cert.csr" \ + -subj "/C=US/ST=Test/L=Test/O=Test/CN=host.docker.internal" + + # Create extfile for SAN + cat > "$CERTS_DIR/san.ext" << EOF +subjectAltName=DNS:host.docker.internal,IP:127.0.0.1 +EOF + + # Sign server certificate with CA + openssl x509 -req -days 365 \ + -in "$CERTS_DIR/host-int-cert.csr" \ + -CA "$CERTS_DIR/custom-ca.pem" \ + -CAkey "$CERTS_DIR/ca.key" \ + -CAcreateserial \ + -out "$CERTS_DIR/host-int-cert.pem" \ + -extfile "$CERTS_DIR/san.ext" + + # Clean up temporary files + rm -f "$CERTS_DIR/ca.key" "$CERTS_DIR/host-int-cert.csr" "$CERTS_DIR/san.ext" "$CERTS_DIR/.srl" + + print_status "PASS" "Certificates generated using OpenSSL" +} + +# Main function +main() { + print_status "INFO" "Setting up custom CA certificates for Checkmate testing" + echo "================================================================" + + # Create certs directory if missing + print_status "INFO" "Creating certificates directory..." + mkdir -p "$CERTS_DIR" + + # Generate certificates + if command_exists mkcert; then + generate_certs_mkcert + else + print_status "WARN" "mkcert not found, falling back to OpenSSL" + generate_certs_openssl + fi + + # Create duplicate for compatibility with existing overrides + print_status "INFO" "Creating duplicate CA file for compatibility..." + cp "$CERTS_DIR/custom-ca.pem" "$CERTS_DIR/smallstep-root-ca.pem" + + # Verify certificates exist + if [ ! -f "$CERTS_DIR/custom-ca.pem" ] || [ ! -f "$CERTS_DIR/host-int-cert.pem" ] || [ ! -f "$CERTS_DIR/host-int-key.pem" ]; then + echo "Error: Failed to generate required certificates" + exit 1 + fi + + # Print summary + echo "" + print_status "PASS" "All required certificates generated successfully" + echo "" + echo "Certificate summary:" + echo "====================" + ls -l "$CERTS_DIR" + echo "" + echo "CA certificate preview:" + echo "======================" + head -3 "$CERTS_DIR/custom-ca.pem" + echo "" + print_status "INFO" "Certificates are ready for use with Checkmate custom CA trust" +} + +# Run main function +main "$@" diff --git a/scripts/test-custom-ca.sh b/scripts/test-custom-ca.sh new file mode 100755 index 000000000..bdf5b62c7 --- /dev/null +++ b/scripts/test-custom-ca.sh @@ -0,0 +1,454 @@ +#!/usr/bin/env bash + +# Dev/Test only: Not required in production +# This script tests the custom CA trust functionality in development environment + +set -euo pipefail + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Configuration +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +DEV_DIR="${ROOT_DIR}/docker/dev" +CERT_DIR="${DEV_DIR}/certs" +NGINX_DIR="${DEV_DIR}/nginx-test" +COMPOSE_BASELINE="${DEV_DIR}/docker-compose.yaml" +COMPOSE_CUSTOM_CA="${DEV_DIR}/docker-compose.custom-ca-example.yaml" +COMPOSE_NGINX_TEST="${NGINX_DIR}/docker-compose.nginx-test.yaml" + +# Test configuration +NGINX_PORT=8443 +CHECKMATE_PORT=52345 +HEALTH_ENDPOINT="http://localhost:$CHECKMATE_PORT/api/v1/health" +TEST_URL="https://host.docker.internal:$NGINX_PORT" +MAX_WAIT=60 +WAIT_INTERVAL=2 + +# Global flag for cleanup behavior +CLEAN_CERTS=false + +# Function to print colored output +print_status() { + local status=$1 + local message=$2 + case $status in + "PASS") + echo -e "${GREEN}[PASS]${NC} $message" + ;; + "FAIL") + echo -e "${RED}[FAIL]${NC} $message" + ;; + "INFO") + echo -e "${BLUE}[INFO]${NC} $message" + ;; + "WARN") + echo -e "${YELLOW}[WARN]${NC} $message" + ;; + esac +} + +# Function to check if a command exists +command_exists() { + command -v "$1" >/dev/null 2>&1 +} + +# Function to check if certificates exist and are valid +check_certificates() { + local ca_file="${CERT_DIR}/custom-ca.pem" + local cert_file="${CERT_DIR}/host-int-cert.pem" + local key_file="${CERT_DIR}/host-int-key.pem" + + if [ ! -f "$ca_file" ] || [ ! -f "$cert_file" ] || [ ! -f "$key_file" ]; then + return 1 + fi + + # Check if files are not empty + if [ ! -s "$ca_file" ] || [ ! -s "$cert_file" ] || [ ! -s "$key_file" ]; then + return 1 + fi + + # Check if CA file starts with BEGIN CERTIFICATE + if ! head -1 "$ca_file" | grep -q "BEGIN CERTIFICATE"; then + return 1 + fi + + return 0 +} + +# Function to wait for service to be ready +wait_for_service() { + local url=$1 + local service_name=$2 + local elapsed=0 + + print_status "INFO" "Waiting for $service_name to be ready..." + + while [ $elapsed -lt $MAX_WAIT ]; do + if curl -s -f "$url" >/dev/null 2>&1; then + print_status "PASS" "$service_name is ready after ${elapsed}s" + return 0 + fi + + sleep $WAIT_INTERVAL + elapsed=$((elapsed + WAIT_INTERVAL)) + echo -n "." + done + + print_status "FAIL" "$service_name failed to start within ${MAX_WAIT}s" + return 1 +} + +# Function to get container name by image +get_container_name() { + local image_name=$1 + docker ps --filter "ancestor=$image_name" --format "{{.Names}}" | head -n1 +} + +# Function to run Node.js probe test +run_probe_test() { + local container_name=$1 + local test_name=$2 + local expected_exit_code=$3 + + print_status "INFO" "Running $test_name probe test..." + + local probe_script=" +const https = require('https'); +https.get('https://host.docker.internal:8443', res => { + console.log('STATUS', res.statusCode); + process.exit(res.statusCode===200?0:1); +}).on('error', e => { + console.error('ERR', e.code||e.message); + process.exit(1); +}); +" + + local exit_code + if docker exec -i "$container_name" node -e "$probe_script" 2>/dev/null; then + exit_code=$? + else + exit_code=$? + fi + + if [ $exit_code -eq $expected_exit_code ]; then + print_status "PASS" "$test_name probe test completed with expected exit code $expected_exit_code" + return 0 + else + print_status "FAIL" "$test_name probe test failed with exit code $exit_code (expected $expected_exit_code)" + return 1 + fi +} + +# Function to setup certificates if needed +setup_certificates_if_needed() { + if check_certificates; then + print_status "INFO" "Certificates already exist and are valid, skipping generation" + return 0 + fi + + print_status "INFO" "Certificates missing or invalid, generating new ones..." + if [ -x "${ROOT_DIR}/scripts/dev/setup-custom-ca.sh" ]; then + "${ROOT_DIR}/scripts/dev/setup-custom-ca.sh" + else + print_status "FAIL" "Certificate setup script not found at scripts/dev/setup-custom-ca.sh" + return 1 + fi +} + +# Function to create nginx test configuration +create_nginx_test_config() { + print_status "INFO" "Setting up nginx test configuration..." + + mkdir -p "$NGINX_DIR" + + # Create nginx.conf if it doesn't exist + if [ ! -f "${NGINX_DIR}/nginx.conf" ]; then + cat > "${NGINX_DIR}/nginx.conf" << 'EOF' +events {} +http { + server { + listen 443 ssl; + ssl_certificate /etc/nginx/certs/server.crt; + ssl_certificate_key /etc/nginx/certs/server.key; + location / { + return 200 "hello from tls\n"; + } + } +} +EOF + fi + + # Create docker-compose.nginx-test.yaml if it doesn't exist + if [ ! -f "$COMPOSE_NGINX_TEST" ]; then + cat > "$COMPOSE_NGINX_TEST" << EOF +services: + nginx-test: + image: nginx:alpine + ports: + - "$NGINX_PORT:443" + volumes: + - ../certs/host-int-cert.pem:/etc/nginx/certs/server.crt:ro + - ../certs/host-int-key.pem:/etc/nginx/certs/server.key:ro + - ./nginx.conf:/etc/nginx/nginx.conf:ro + restart: unless-stopped +EOF + fi + + print_status "PASS" "Nginx test configuration created" +} + +# Function to start nginx test service +start_nginx_test() { + print_status "INFO" "Starting nginx test service..." + + cd "$NGINX_DIR" + docker-compose -f docker-compose.nginx-test.yaml up -d + + # Wait for nginx to be ready + local elapsed=0 + while [ $elapsed -lt $MAX_WAIT ]; do + if curl -s -f -k "https://localhost:$NGINX_PORT" >/dev/null 2>&1; then + print_status "PASS" "Nginx test service is ready" + cd "$ROOT_DIR" + return 0 + fi + + sleep $WAIT_INTERVAL + elapsed=$((elapsed + WAIT_INTERVAL)) + echo -n "." + done + + print_status "FAIL" "Nginx test service failed to start" + cd "$ROOT_DIR" + return 1 +} + +# Function to stop nginx test service +stop_nginx_test() { + print_status "INFO" "Stopping nginx test service..." + cd "$NGINX_DIR" + docker-compose -f docker-compose.nginx-test.yaml down 2>/dev/null || true + cd "$ROOT_DIR" +} + +# Function to run baseline test +run_baseline_test() { + print_status "INFO" "Running baseline test (should fail due to unknown CA)..." + + # Start baseline Checkmate + cd "$DEV_DIR" + docker-compose -f docker-compose.yaml up -d --build + + # Wait for Checkmate to be ready + if ! wait_for_service "$HEALTH_ENDPOINT" "Checkmate baseline"; then + cd "$ROOT_DIR" + return 1 + fi + + # Get container name + local container_name + container_name=$(get_container_name "uptime_server") + if [ -z "$container_name" ]; then + print_status "FAIL" "Could not find Checkmate server container" + cd "$ROOT_DIR" + return 1 + fi + + # Run probe test (should fail) + if run_probe_test "$container_name" "baseline" 1; then + print_status "PASS" "Baseline test completed - TLS failure as expected" + cd "$ROOT_DIR" + return 0 + else + print_status "FAIL" "Baseline test failed - unexpected behavior" + cd "$ROOT_DIR" + return 1 + fi +} + +# Function to run custom CA test +run_custom_ca_test() { + print_status "INFO" "Running custom CA test (should succeed)..." + + # Stop baseline Checkmate + cd "$DEV_DIR" + docker-compose -f docker-compose.yaml down + + # Start Checkmate with custom CA + docker-compose -f docker-compose.yaml -f docker-compose.custom-ca-example.yaml up -d --build + + # Wait for Checkmate to be ready + if ! wait_for_service "$HEALTH_ENDPOINT" "Checkmate custom CA"; then + cd "$ROOT_DIR" + return 1 + fi + + # Get container name + local container_name + container_name=$(get_container_name "uptime_server") + if [ -z "$container_name" ]; then + print_status "FAIL" "Could not find Checkmate server container" + cd "$ROOT_DIR" + return 1 + fi + + # Run probe test (should succeed) + if run_probe_test "$container_name" "custom CA" 0; then + print_status "PASS" "Custom CA test completed - TLS success as expected" + cd "$ROOT_DIR" + return 0 + else + print_status "FAIL" "Custom CA test failed - unexpected behavior" + cd "$ROOT_DIR" + return 1 + fi +} + +# Function to cleanup everything +cleanup() { + print_status "INFO" "Cleaning up test environment..." + + # Stop all services + cd "$DEV_DIR" + docker-compose -f docker-compose.yaml down 2>/dev/null || true + docker-compose -f docker-compose.yaml -f docker-compose.custom-ca-example.yaml down 2>/dev/null || true + + stop_nginx_test + + # Only remove certificates if --clean was specified + if [ "$CLEAN_CERTS" = true ]; then + print_status "INFO" "Removing certificates as requested with --clean" + rm -rf "${CERT_DIR:?}"/* + else + print_status "INFO" "Preserving certificates for future test runs" + fi + + cd "$ROOT_DIR" + print_status "PASS" "Cleanup completed" +} + +# Function to show usage +show_usage() { + echo "Usage: $0 [OPTIONS]" + echo "" + echo "Options:" + echo " --clean Clean up all test containers and certificates" + echo " --help Show this help message" + echo "" + echo "This script tests the custom CA trust functionality in Checkmate." +} + +# Main function +main() { + local clean_only=false + + # Parse command line arguments + while [[ $# -gt 0 ]]; do + case $1 in + --clean) + clean_only=true + CLEAN_CERTS=true + shift + ;; + --help) + show_usage + exit 0 + ;; + *) + echo "Unknown option: $1" + show_usage + exit 1 + ;; + esac + done + + print_status "INFO" "Starting Checkmate Custom CA Trust Test" + echo "==================================================" + + if [ "$clean_only" = true ]; then + cleanup + exit 0 + fi + + # Check prerequisites + if ! command_exists docker; then + print_status "FAIL" "Docker is not installed or not in PATH" + exit 1 + fi + + if ! command_exists docker-compose; then + print_status "FAIL" "docker-compose is not installed or not in PATH" + exit 1 + fi + + # Check if required files exist + if [ ! -f "$COMPOSE_BASELINE" ]; then + print_status "FAIL" "Baseline docker-compose.yaml not found at $COMPOSE_BASELINE" + exit 1 + fi + + if [ ! -f "$COMPOSE_CUSTOM_CA" ]; then + print_status "FAIL" "Custom CA docker-compose override not found at $COMPOSE_CUSTOM_CA" + exit 1 + fi + + # Setup test environment + setup_certificates_if_needed + create_nginx_test_config + start_nginx_test + + # Run tests + local baseline_result=false + local custom_ca_result=false + + if run_baseline_test; then + baseline_result=true + fi + + if run_custom_ca_test; then + custom_ca_result=true + fi + + # Print summary + echo "" + echo "==================================================" + print_status "INFO" "Test Summary" + echo "==================================================" + + if [ "$baseline_result" = true ]; then + print_status "PASS" "Baseline: TLS failure as expected" + else + print_status "FAIL" "Baseline: Unexpected behavior" + fi + + if [ "$custom_ca_result" = true ]; then + print_status "PASS" "Custom CA: TLS success (STATUS 200)" + else + print_status "FAIL" "Custom CA: Unexpected behavior" + fi + + if [ "$baseline_result" = true ] && [ "$custom_ca_result" = true ]; then + echo "" + print_status "PASS" "All tests passed! Custom CA trust is working correctly." + echo "" + print_status "INFO" "To clean up, run: $0 --clean" + exit 0 + else + echo "" + print_status "FAIL" "Some tests failed. Custom CA trust may not be working correctly." + echo "" + print_status "INFO" "To clean up, run: $0 --clean" + exit 1 + fi +} + +# Trap cleanup on script exit +trap cleanup EXIT + +# Run main function +main "$@" diff --git a/server/src/db/mongo/modules/monitorModule.js b/server/src/db/mongo/modules/monitorModule.js index c4a896030..0e301cdcf 100755 --- a/server/src/db/mongo/modules/monitorModule.js +++ b/server/src/db/mongo/modules/monitorModule.js @@ -330,6 +330,7 @@ class MonitorModule { try { const monitor = await this.Monitor.findById(monitorId); const dates = this.getDateRange(dateRange); + const formatLookup = { recent: "%Y-%m-%dT%H:%M:00Z", day: "%Y-%m-%dT%H:00:00Z", @@ -337,13 +338,15 @@ class MonitorModule { month: "%Y-%m-%dT00:00:00Z", }; const dateString = formatLookup[dateRange]; + const hardwareStats = await this.HardwareCheck.aggregate(buildHardwareDetailsPipeline(monitor, dates, dateString)); - const monitorStats = { + const stats = hardwareStats[0]; + + return { ...monitor.toObject(), - stats: hardwareStats[0], + stats, }; - return monitorStats; } catch (error) { error.service = SERVICE_NAME; error.method = "getHardwareDetailsById"; diff --git a/server/src/db/mongo/modules/monitorModuleQueries.js b/server/src/db/mongo/modules/monitorModuleQueries.js index a5a56ff9b..f6d20d855 100755 --- a/server/src/db/mongo/modules/monitorModuleQueries.js +++ b/server/src/db/mongo/modules/monitorModuleQueries.js @@ -218,9 +218,9 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => { { $project: { diskCount: { - $size: "$disk", + $size: { $ifNull: ["$disk", []] }, }, - netCount: { $size: "$net" }, + netCount: { $size: { $ifNull: ["$net", []] } }, }, }, { @@ -263,6 +263,9 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => { net: { $push: "$net", }, + updatedAts: { + $push: "$updatedAt", + }, }, }, { @@ -378,90 +381,399 @@ const buildHardwareDetailsPipeline = (monitor, dates, dateString) => { }, net: { $map: { - input: { $range: [0, "$$netCount"] }, + input: { $range: [0, { $size: { $ifNull: [{ $arrayElemAt: ["$net", 0] }, []] } }] }, as: "netIndex", in: { name: { $arrayElemAt: [ { $map: { - input: "$net", - as: "netArray", - in: { $arrayElemAt: ["$$netArray.name", "$$netIndex"] }, + input: { $arrayElemAt: ["$net", 0] }, + as: "iface", + in: "$$iface.name", }, }, - 0, + "$$netIndex", ], }, - avgBytesSent: { - $avg: { - $map: { - input: "$net", - as: "netArray", - in: { - $arrayElemAt: ["$$netArray.bytes_sent", "$$netIndex"], + bytesSentPerSecond: { + $let: { + vars: { + first: { + $arrayElemAt: [ + { $map: { input: { $arrayElemAt: ["$net", 0] }, as: "iface", in: "$$iface.bytes_sent" } }, + "$$netIndex", + ], }, + last: { + $arrayElemAt: [ + { + $map: { + input: { + $arrayElemAt: [{ $ifNull: ["$net", []] }, { $subtract: [{ $size: { $ifNull: ["$net", []] } }, 1] }], + }, + as: "iface", + in: "$$iface.bytes_sent", + }, + }, + "$$netIndex", + ], + }, + tFirst: { $arrayElemAt: ["$updatedAts", 0] }, + tLast: { + $arrayElemAt: [{ $ifNull: ["$updatedAts", []] }, { $subtract: [{ $size: { $ifNull: ["$updatedAts", []] } }, 1] }], + }, + }, + in: { + $cond: [ + { $gt: [{ $subtract: ["$$tLast", "$$tFirst"] }, 0] }, + { + $divide: [{ $subtract: ["$$last", "$$first"] }, { $divide: [{ $subtract: ["$$tLast", "$$tFirst"] }, 1000] }], + }, + 0, + ], }, }, }, - avgBytesRecv: { - $avg: { - $map: { - input: "$net", - as: "netArray", - in: { - $arrayElemAt: ["$$netArray.bytes_recv", "$$netIndex"], + deltaBytesRecv: { + $let: { + vars: { + first: { + $arrayElemAt: [ + { $map: { input: { $arrayElemAt: ["$net", 0] }, as: "iface", in: "$$iface.bytes_recv" } }, + "$$netIndex", + ], }, + last: { + $arrayElemAt: [ + { + $map: { + input: { + $arrayElemAt: [{ $ifNull: ["$net", []] }, { $subtract: [{ $size: { $ifNull: ["$net", []] } }, 1] }], + }, + as: "iface", + in: "$$iface.bytes_recv", + }, + }, + "$$netIndex", + ], + }, + tFirst: { $arrayElemAt: ["$updatedAts", 0] }, + tLast: { + $arrayElemAt: [{ $ifNull: ["$updatedAts", []] }, { $subtract: [{ $size: { $ifNull: ["$updatedAts", []] } }, 1] }], + }, + }, + in: { + $cond: [ + { $gt: [{ $subtract: ["$$tLast", "$$tFirst"] }, 0] }, + { + $divide: [{ $subtract: ["$$last", "$$first"] }, { $divide: [{ $subtract: ["$$tLast", "$$tFirst"] }, 1000] }], + }, + 0, + ], }, }, }, - avgPacketsSent: { - $avg: { - $map: { - input: "$net", - as: "netArray", - in: { - $arrayElemAt: ["$$netArray.packets_sent", "$$netIndex"], + deltaPacketsSent: { + $let: { + vars: { + first: { + $arrayElemAt: [ + { $map: { input: { $arrayElemAt: ["$net", 0] }, as: "iface", in: "$$iface.packets_sent" } }, + "$$netIndex", + ], }, + last: { + $arrayElemAt: [ + { + $map: { + input: { + $arrayElemAt: [{ $ifNull: ["$net", []] }, { $subtract: [{ $size: { $ifNull: ["$net", []] } }, 1] }], + }, + as: "iface", + in: "$$iface.packets_sent", + }, + }, + "$$netIndex", + ], + }, + tFirst: { $arrayElemAt: ["$updatedAts", 0] }, + tLast: { + $arrayElemAt: [{ $ifNull: ["$updatedAts", []] }, { $subtract: [{ $size: { $ifNull: ["$updatedAts", []] } }, 1] }], + }, + }, + in: { + $cond: [ + { $gt: [{ $subtract: ["$$tLast", "$$tFirst"] }, 0] }, + { + $divide: [{ $subtract: ["$$last", "$$first"] }, { $divide: [{ $subtract: ["$$tLast", "$$tFirst"] }, 1000] }], + }, + 0, + ], }, }, }, - avgPacketsRecv: { - $avg: { - $map: { - input: "$net", - as: "netArray", - in: { - $arrayElemAt: ["$$netArray.packets_recv", "$$netIndex"], + deltaPacketsRecv: { + $let: { + vars: { + first: { + $arrayElemAt: [ + { + $map: { + input: { $arrayElemAt: ["$net", 0] }, + as: "iface", + in: "$$iface.packets_recv", + }, + }, + "$$netIndex", + ], }, + last: { + $arrayElemAt: [ + { + $map: { + input: { + $arrayElemAt: [ + { $ifNull: ["$net", []] }, + { + $subtract: [{ $size: { $ifNull: ["$net", []] } }, 1], + }, + ], + }, + as: "iface", + in: "$$iface.packets_recv", + }, + }, + "$$netIndex", + ], + }, + tFirst: { $arrayElemAt: ["$updatedAts", 0] }, + tLast: { + $arrayElemAt: [ + { $ifNull: ["$updatedAts", []] }, + { + $subtract: [{ $size: { $ifNull: ["$updatedAts", []] } }, 1], + }, + ], + }, + }, + in: { + $cond: [ + { $gt: [{ $subtract: ["$$tLast", "$$tFirst"] }, 0] }, + { + $divide: [{ $subtract: ["$$last", "$$first"] }, { $divide: [{ $subtract: ["$$tLast", "$$tFirst"] }, 1000] }], + }, + 0, + ], }, }, }, - avgErrIn: { - $avg: { - $map: { - input: "$net", - as: "netArray", - in: { - $arrayElemAt: ["$$netArray.err_in", "$$netIndex"], + deltaErrIn: { + $let: { + vars: { + first: { + $arrayElemAt: [{ $map: { input: { $arrayElemAt: ["$net", 0] }, as: "iface", in: "$$iface.err_in" } }, "$$netIndex"], }, + last: { + $arrayElemAt: [ + { + $map: { + input: { + $arrayElemAt: [{ $ifNull: ["$net", []] }, { $subtract: [{ $size: { $ifNull: ["$net", []] } }, 1] }], + }, + as: "iface", + in: "$$iface.err_in", + }, + }, + "$$netIndex", + ], + }, + tFirst: { $arrayElemAt: ["$updatedAts", 0] }, + tLast: { + $arrayElemAt: [{ $ifNull: ["$updatedAts", []] }, { $subtract: [{ $size: { $ifNull: ["$updatedAts", []] } }, 1] }], + }, + }, + in: { + $cond: [ + { $gt: [{ $subtract: ["$$tLast", "$$tFirst"] }, 0] }, + { + $divide: [{ $subtract: ["$$last", "$$first"] }, { $divide: [{ $subtract: ["$$tLast", "$$tFirst"] }, 1000] }], + }, + 0, + ], }, }, }, - avgErrOut: { - $avg: { - $map: { - input: "$net", - as: "netArray", - in: { - $arrayElemAt: ["$$netArray.err_out", "$$netIndex"], + deltaErrOut: { + $let: { + vars: { + first: { + $arrayElemAt: [ + { + $map: { + input: { $arrayElemAt: ["$net", 0] }, + as: "iface", + in: "$$iface.err_out", + }, + }, + "$$netIndex", + ], }, + last: { + $arrayElemAt: [ + { + $map: { + input: { + $arrayElemAt: [ + { $ifNull: ["$net", []] }, + { + $subtract: [{ $size: { $ifNull: ["$net", []] } }, 1], + }, + ], + }, + as: "iface", + in: "$$iface.err_out", + }, + }, + "$$netIndex", + ], + }, + tFirst: { $arrayElemAt: ["$updatedAts", 0] }, + tLast: { + $arrayElemAt: [ + { $ifNull: ["$updatedAts", []] }, + { + $subtract: [{ $size: { $ifNull: ["$updatedAts", []] } }, 1], + }, + ], + }, + }, + in: { + $cond: [ + { $gt: [{ $subtract: ["$$tLast", "$$tFirst"] }, 0] }, + { + $divide: [{ $subtract: ["$$last", "$$first"] }, { $divide: [{ $subtract: ["$$tLast", "$$tFirst"] }, 1000] }], + }, + 0, + ], + }, + }, + }, + deltaDropIn: { + $let: { + vars: { + first: { + $arrayElemAt: [ + { + $map: { + input: { $arrayElemAt: ["$net", 0] }, + as: "iface", + in: "$$iface.drop_in", + }, + }, + "$$netIndex", + ], + }, + last: { + $arrayElemAt: [ + { + $map: { + input: { + $arrayElemAt: [ + { $ifNull: ["$net", []] }, + { + $subtract: [{ $size: { $ifNull: ["$net", []] } }, 1], + }, + ], + }, + as: "iface", + in: "$$iface.drop_in", + }, + }, + "$$netIndex", + ], + }, + tFirst: { $arrayElemAt: ["$updatedAts", 0] }, + tLast: { + $arrayElemAt: [ + { $ifNull: ["$updatedAts", []] }, + { + $subtract: [{ $size: { $ifNull: ["$updatedAts", []] } }, 1], + }, + ], + }, + }, + in: { + $cond: [ + { $gt: [{ $subtract: ["$$tLast", "$$tFirst"] }, 0] }, + { + $divide: [{ $subtract: ["$$last", "$$first"] }, { $divide: [{ $subtract: ["$$tLast", "$$tFirst"] }, 1000] }], + }, + 0, + ], + }, + }, + }, + deltaDropOut: { + $let: { + vars: { + first: { + $arrayElemAt: [ + { + $map: { + input: { $arrayElemAt: ["$net", 0] }, + as: "iface", + in: "$$iface.drop_out", + }, + }, + "$$netIndex", + ], + }, + last: { + $arrayElemAt: [ + { + $map: { + input: { + $arrayElemAt: [ + { $ifNull: ["$net", []] }, + { + $subtract: [{ $size: { $ifNull: ["$net", []] } }, 1], + }, + ], + }, + as: "iface", + in: "$$iface.drop_out", + }, + }, + "$$netIndex", + ], + }, + tFirst: { $arrayElemAt: ["$updatedAts", 0] }, + tLast: { + $arrayElemAt: [ + { $ifNull: ["$updatedAts", []] }, + { + $subtract: [{ $size: { $ifNull: ["$updatedAts", []] } }, 1], + }, + ], + }, + }, + in: { + $cond: [ + { $gt: [{ $subtract: ["$$tLast", "$$tFirst"] }, 0] }, + { + $divide: [{ $subtract: ["$$last", "$$first"] }, { $divide: [{ $subtract: ["$$tLast", "$$tFirst"] }, 1000] }], + }, + 0, + ], }, }, }, }, }, }, + firstUpdatedAt: 1, + lastUpdatedAt: 1, }, }, ], diff --git a/server/src/index.js b/server/src/index.js index 6b12eb25d..d1ff649eb 100755 --- a/server/src/index.js +++ b/server/src/index.js @@ -18,7 +18,7 @@ const startApp = async () => { const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const openApiSpec = JSON.parse(fs.readFileSync(path.join(__dirname, "../openapi.json"), "utf8")); - const frontendPath = path.join(__dirname, "public"); + const frontendPath = path.join(__dirname, "..", "public"); // Create services const settingsService = new SettingsService(AppSettings);