diff --git a/.github/workflows/release-standalone-docker-img-postgres-offical.yml b/.github/workflows/release-standalone-docker-img-postgres-offical.yml index 5d9f384f7..f3265f3e9 100644 --- a/.github/workflows/release-standalone-docker-img-postgres-offical.yml +++ b/.github/workflows/release-standalone-docker-img-postgres-offical.yml @@ -135,10 +135,10 @@ jobs: TAG_NAME="${{ github.ref_name }}" echo "Checking for tag: $TAG_NAME" - EXACT_MATCH=$(gh api repos/Infisical/infisical-omnibus/git/refs/tags/$TAG_NAME | jq -r 'if type == "array" then .[].ref else .ref end' | grep -x "refs/tags/$TAG_NAME") + EXACT_MATCH=$(gh api repos/Infisical/infisical-omnibus/git/refs/tags/$TAG_NAME 2>/dev/null | jq -r 'if type == "array" then .[].ref else .ref end' | grep -x "refs/tags/$TAG_NAME" || true) if [ "$EXACT_MATCH" == "refs/tags/$TAG_NAME" ]; then - echo "Tag $TAG_NAME already exists, skipping..." + echo "Tag $TAG_NAME already exists, skipping..." else echo "Creating tag in Infisical/infisical-omnibus: $TAG_NAME" LATEST_SHA=$(gh api repos/Infisical/infisical-omnibus/git/refs/heads/main --jq '.object.sha') diff --git a/.github/workflows/release_helm_gateway.yaml b/.github/workflows/release_helm_gateway.yaml index 7fd0eb03a..cfd29a56e 100644 --- a/.github/workflows/release_helm_gateway.yaml +++ b/.github/workflows/release_helm_gateway.yaml @@ -24,6 +24,8 @@ jobs: - name: Set up chart-testing uses: helm/chart-testing-action@v2.7.0 + with: + yamale_version: "6.0.0" - name: Run chart-testing (lint) run: ct lint --config ct.yaml --charts helm-charts/infisical-gateway diff --git a/.github/workflows/run-helm-chart-tests-infisical-gateway.yml b/.github/workflows/run-helm-chart-tests-infisical-gateway.yml index eff42506e..b382669e3 100644 --- a/.github/workflows/run-helm-chart-tests-infisical-gateway.yml +++ b/.github/workflows/run-helm-chart-tests-infisical-gateway.yml @@ -27,6 +27,8 @@ jobs: - name: Set up chart-testing uses: helm/chart-testing-action@v2.7.0 + with: + yamale_version: "6.0.0" - name: Run chart-testing (lint) run: ct lint --config ct.yaml --charts helm-charts/infisical-gateway diff --git a/backend/package-lock.json b/backend/package-lock.json index adda83043..a6cef3888 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -150,7 +150,7 @@ "@types/jsrp": "^0.2.6", "@types/libsodium-wrappers": "^0.7.13", "@types/lodash.isequal": "^4.5.8", - "@types/node": "^20.17.30", + "@types/node": "^20.19.0", "@types/nodemailer": "^6.4.14", "@types/passport-google-oauth20": "^2.0.14", "@types/pg": "^8.10.9", @@ -182,10 +182,10 @@ "ts-node": "^10.9.2", "tsc-alias": "^1.8.8", "tsconfig-paths": "^4.2.0", - "tsup": "^8.0.1", + "tsup": "^8.5.0", "tsx": "^4.4.0", "typescript": "^5.3.2", - "vitest": "^1.2.2" + "vitest": "^3.0.6" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -7451,9 +7451,9 @@ } }, "node_modules/@esbuild/aix-ppc64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", - "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.11.tgz", + "integrity": "sha512-Xt1dOL13m8u0WE8iplx9Ibbm+hFAO0GsU2P34UNoDGvZYkY8ifSiy6Zuc1lYxfG7svWE2fzqCUmFp5HCn51gJg==", "cpu": [ "ppc64" ], @@ -7464,269 +7464,285 @@ "aix" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/android-arm": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.18.20.tgz", - "integrity": "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.11.tgz", + "integrity": "sha512-uoa7dU+Dt3HYsethkJ1k6Z9YdcHjTrSb5NUy66ZfZaSV8hEYGD5ZHbEMXnqLFlbBflLsl89Zke7CAdDJ4JI+Gg==", "cpu": [ "arm" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "android" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/android-arm64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.18.20.tgz", - "integrity": "sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.11.tgz", + "integrity": "sha512-9slpyFBc4FPPz48+f6jyiXOx/Y4v34TUeDDXJpZqAWQn/08lKGeD8aDp9TMn9jDz2CiEuHwfhRmGBvpnd/PWIQ==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "android" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/android-x64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.18.20.tgz", - "integrity": "sha512-8GDdlePJA8D6zlZYJV/jnrRAi6rOiNaCC/JclcXpB+KIuvfBN4owLtgzY2bsxnx666XjJx2kDPUmnTtR8qKQUg==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.11.tgz", + "integrity": "sha512-Sgiab4xBjPU1QoPEIqS3Xx+R2lezu0LKIEcYe6pftr56PqPygbB7+szVnzoShbx64MUupqoE0KyRlN7gezbl8g==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "android" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.18.20.tgz", - "integrity": "sha512-bxRHW5kHU38zS2lPTPOyuyTm+S+eobPUnTNkdJEfAddYgEcll4xkT8DB9d2008DtTbl7uJag2HuE5NZAZgnNEA==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.11.tgz", + "integrity": "sha512-VekY0PBCukppoQrycFxUqkCojnTQhdec0vevUL/EDOCnXd9LKWqD/bHwMPzigIJXPhC59Vd1WFIL57SKs2mg4w==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.18.20.tgz", - "integrity": "sha512-pc5gxlMDxzm513qPGbCbDukOdsGtKhfxD1zJKXjCCcU7ju50O7MeAZ8c4krSJcOIJGFR+qx21yMMVYwiQvyTyQ==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.11.tgz", + "integrity": "sha512-+hfp3yfBalNEpTGp9loYgbknjR695HkqtY3d3/JjSRUyPg/xd6q+mQqIb5qdywnDxRZykIHs3axEqU6l1+oWEQ==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.18.20.tgz", - "integrity": "sha512-yqDQHy4QHevpMAaxhhIwYPMv1NECwOvIpGCZkECn8w2WFHXjEwrBn3CeNIYsibZ/iZEUemj++M26W3cNR5h+Tw==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.11.tgz", + "integrity": "sha512-CmKjrnayyTJF2eVuO//uSjl/K3KsMIeYeyN7FyDBjsR3lnSJHaXlVoAK8DZa7lXWChbuOk7NjAc7ygAwrnPBhA==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "freebsd" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.18.20.tgz", - "integrity": "sha512-tgWRPPuQsd3RmBZwarGVHZQvtzfEBOreNuxEMKFcd5DaDn2PbBxfwLcj4+aenoh7ctXcbXmOQIn8HI6mCSw5MQ==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.11.tgz", + "integrity": "sha512-Dyq+5oscTJvMaYPvW3x3FLpi2+gSZTCE/1ffdwuM6G1ARang/mb3jvjxs0mw6n3Lsw84ocfo9CrNMqc5lTfGOw==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "freebsd" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-arm": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.18.20.tgz", - "integrity": "sha512-/5bHkMWnq1EgKr1V+Ybz3s1hWXok7mDFUMQ4cG10AfW3wL02PSZi5kFpYKrptDsgb2WAJIvRcDm+qIvXf/apvg==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.11.tgz", + "integrity": "sha512-TBMv6B4kCfrGJ8cUPo7vd6NECZH/8hPpBHHlYI3qzoYFvWu2AdTvZNuU/7hsbKWqu/COU7NIK12dHAAqBLLXgw==", "cpu": [ "arm" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.18.20.tgz", - "integrity": "sha512-2YbscF+UL7SQAVIpnWvYwM+3LskyDmPhe31pE7/aoTMFKKzIc9lLbyGUpmmb8a8AixOL61sQ/mFh3jEjHYFvdA==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.11.tgz", + "integrity": "sha512-Qr8AzcplUhGvdyUF08A1kHU3Vr2O88xxP0Tm8GcdVOUm25XYcMPp2YqSVHbLuXzYQMf9Bh/iKx7YPqECs6ffLA==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.18.20.tgz", - "integrity": "sha512-P4etWwq6IsReT0E1KHU40bOnzMHoH73aXp96Fs8TIT6z9Hu8G6+0SHSw9i2isWrD2nbx2qo5yUqACgdfVGx7TA==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.11.tgz", + "integrity": "sha512-TmnJg8BMGPehs5JKrCLqyWTVAvielc615jbkOirATQvWWB1NMXY77oLMzsUjRLa0+ngecEmDGqt5jiDC6bfvOw==", "cpu": [ "ia32" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.18.20.tgz", - "integrity": "sha512-nXW8nqBTrOpDLPgPY9uV+/1DjxoQ7DoB2N8eocyq8I9XuqJ7BiAMDMf9n1xZM9TgW0J8zrquIb/A7s3BJv7rjg==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.11.tgz", + "integrity": "sha512-DIGXL2+gvDaXlaq8xruNXUJdT5tF+SBbJQKbWy/0J7OhU8gOHOzKmGIlfTTl6nHaCOoipxQbuJi7O++ldrxgMw==", "cpu": [ "loong64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.18.20.tgz", - "integrity": "sha512-d5NeaXZcHp8PzYy5VnXV3VSd2D328Zb+9dEq5HE6bw6+N86JVPExrA6O68OPwobntbNJ0pzCpUFZTo3w0GyetQ==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.11.tgz", + "integrity": "sha512-Osx1nALUJu4pU43o9OyjSCXokFkFbyzjXb6VhGIJZQ5JZi8ylCQ9/LFagolPsHtgw6himDSyb5ETSfmp4rpiKQ==", "cpu": [ "mips64el" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.18.20.tgz", - "integrity": "sha512-WHPyeScRNcmANnLQkq6AfyXRFr5D6N2sKgkFo2FqguP44Nw2eyDlbTdZwd9GYk98DZG9QItIiTlFLHJHjxP3FA==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.11.tgz", + "integrity": "sha512-nbLFgsQQEsBa8XSgSTSlrnBSrpoWh7ioFDUmwo158gIm5NNP+17IYmNWzaIzWmgCxq56vfr34xGkOcZ7jX6CPw==", "cpu": [ "ppc64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.18.20.tgz", - "integrity": "sha512-WSxo6h5ecI5XH34KC7w5veNnKkju3zBRLEQNY7mv5mtBmrP/MjNBCAlsM2u5hDBlS3NGcTQpoBvRzqBcRtpq1A==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.11.tgz", + "integrity": "sha512-HfyAmqZi9uBAbgKYP1yGuI7tSREXwIb438q0nqvlpxAOs3XnZ8RsisRfmVsgV486NdjD7Mw2UrFSw51lzUk1ww==", "cpu": [ "riscv64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.18.20.tgz", - "integrity": "sha512-+8231GMs3mAEth6Ja1iK0a1sQ3ohfcpzpRLH8uuc5/KVDFneH6jtAJLFGafpzpMRO6DzJ6AvXKze9LfFMrIHVQ==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.11.tgz", + "integrity": "sha512-HjLqVgSSYnVXRisyfmzsH6mXqyvj0SA7pG5g+9W7ESgwA70AXYNpfKBqh1KbTxmQVaYxpzA/SvlB9oclGPbApw==", "cpu": [ "s390x" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-x64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.18.20.tgz", - "integrity": "sha512-UYqiqemphJcNsFEskc73jQ7B9jgwjWrSayxawS6UVFZGWrAAtkzjxSqnoclCXxWtfwLdzU+vTpcNYhpn43uP1w==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.11.tgz", + "integrity": "sha512-HSFAT4+WYjIhrHxKBwGmOOSpphjYkcswF449j6EjsjbinTZbp8PJtjsVK1XFJStdzXdy/jaddAep2FGY+wyFAQ==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/netbsd-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.0.tgz", - "integrity": "sha512-RuG4PSMPFfrkH6UwCAqBzauBWTygTvb1nxWasEJooGSJ/NwRw7b2HOwyRTQIU97Hq37l3npXoZGYMy3b3xYvPw==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.11.tgz", + "integrity": "sha512-hr9Oxj1Fa4r04dNpWr3P8QKVVsjQhqrMSUzZzf+LZcYjZNqhA3IAfPQdEh1FLVUJSiu6sgAwp3OmwBfbFgG2Xg==", "cpu": [ "arm64" ], @@ -7741,25 +7757,26 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.18.20.tgz", - "integrity": "sha512-iO1c++VP6xUBUmltHZoMtCUdPlnPGdBom6IrO4gyKPFFVBKioIImVooR5I83nTew5UOYrk3gIJhbZh8X44y06A==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.11.tgz", + "integrity": "sha512-u7tKA+qbzBydyj0vgpu+5h5AeudxOAGncb8N6C9Kh1N4n7wU1Xw1JDApsRjpShRpXRQlJLb9wY28ELpwdPcZ7A==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "netbsd" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/openbsd-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.0.tgz", - "integrity": "sha512-21sUNbq2r84YE+SJDfaQRvdgznTD8Xc0oc3p3iW/a1EVWeNj/SdUCbm5U0itZPQYRuRTW20fPMWMpcrciH2EJw==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.11.tgz", + "integrity": "sha512-Qq6YHhayieor3DxFOoYM1q0q1uMFYb7cSpLD2qzDSvK1NAvqFi8Xgivv0cFC6J+hWVw2teCYltyy9/m/14ryHg==", "cpu": [ "arm64" ], @@ -7774,19 +7791,20 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.18.20.tgz", - "integrity": "sha512-e5e4YSsuQfX4cxcygw/UCPIEP6wbIL+se3sxPdCiMbFLBWu0eiZOJ7WoD+ptCLrmjZBK1Wk7I6D/I3NglUGOxg==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.11.tgz", + "integrity": "sha512-CN+7c++kkbrckTOz5hrehxWN7uIhFFlmS/hqziSFVWpAzpWrQoAG4chH+nN3Be+Kzv/uuo7zhX716x3Sn2Jduw==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "openbsd" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/openharmony-arm64": { @@ -7807,67 +7825,71 @@ } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.18.20.tgz", - "integrity": "sha512-kDbFRFp0YpTQVVrqUd5FTYmWo45zGaXe0X8E1G/LKFC0v8x0vWrhOWSLITcCn63lmZIxfOMXtCfti/RxN/0wnQ==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.11.tgz", + "integrity": "sha512-nq2xdYaWxyg9DcIyXkZhcYulC6pQ2FuCgem3LI92IwMgIZ69KHeY8T4Y88pcwoLIjbed8n36CyKoYRDygNSGhA==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "sunos" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.18.20.tgz", - "integrity": "sha512-ddYFR6ItYgoaq4v4JmQQaAI5s7npztfV4Ag6NrhiaW0RrnOXqBkgwZLofVTlq1daVTQNhtI5oieTvkRPfZrePg==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.11.tgz", + "integrity": "sha512-3XxECOWJq1qMZ3MN8srCJ/QfoLpL+VaxD/WfNRm1O3B4+AZ/BnLVgFbUV3eiRYDMXetciH16dwPbbHqwe1uU0Q==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.18.20.tgz", - "integrity": "sha512-Wv7QBi3ID/rROT08SABTS7eV4hX26sVduqDOTe1MvGMjNd3EjOz4b7zeexIR62GTIEKrfJXKL9LFxTYgkyeu7g==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.11.tgz", + "integrity": "sha512-3ukss6gb9XZ8TlRyJlgLn17ecsK4NSQTmdIXRASVsiS2sQ6zPPZklNJT5GR5tE/MUarymmy8kCEf5xPCNCqVOA==", "cpu": [ "ia32" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/win32-x64": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.18.20.tgz", - "integrity": "sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.11.tgz", + "integrity": "sha512-D7Hpz6A2L4hzsRpPaCYkQnGOotdUpDzSGRIv9I+1ITdHROSFUWW95ZPZWQmGka1Fg7W3zFJowyn9WGwMJ0+KPA==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@eslint-community/eslint-utils": { @@ -9280,18 +9302,6 @@ "node": ">=12" } }, - "node_modules/@jest/schemas": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", - "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", - "dev": true, - "dependencies": { - "@sinclair/typebox": "^0.27.8" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -13245,9 +13255,9 @@ } }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.24.0.tgz", - "integrity": "sha512-Q6HJd7Y6xdB48x8ZNVDOqsbh2uByBhgK8PiQgPhwkIw/HC/YX5Ghq2mQY5sRMZWHb3VsFkWooUVOZHKr7DmDIA==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.52.5.tgz", + "integrity": "sha512-8c1vW4ocv3UOMp9K+gToY5zL2XiiVw3k7f1ksf4yO1FlDFQ1C2u72iACFnSOceJFsWskc2WZNqeRhFRPzv+wtQ==", "cpu": [ "arm" ], @@ -13259,9 +13269,9 @@ ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.24.0.tgz", - "integrity": "sha512-ijLnS1qFId8xhKjT81uBHuuJp2lU4x2yxa4ctFPtG+MqEE6+C5f/+X/bStmxapgmwLwiL3ih122xv8kVARNAZA==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.52.5.tgz", + "integrity": "sha512-mQGfsIEFcu21mvqkEKKu2dYmtuSZOBMmAl5CFlPGLY94Vlcm+zWApK7F/eocsNzp8tKmbeBP8yXyAbx0XHsFNA==", "cpu": [ "arm64" ], @@ -13273,9 +13283,9 @@ ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.24.0.tgz", - "integrity": "sha512-bIv+X9xeSs1XCk6DVvkO+S/z8/2AMt/2lMqdQbMrmVpgFvXlmde9mLcbQpztXm1tajC3raFDqegsH18HQPMYtA==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.52.5.tgz", + "integrity": "sha512-takF3CR71mCAGA+v794QUZ0b6ZSrgJkArC+gUiG6LB6TQty9T0Mqh3m2ImRBOxS2IeYBo4lKWIieSvnEk2OQWA==", "cpu": [ "arm64" ], @@ -13287,9 +13297,9 @@ ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.24.0.tgz", - "integrity": "sha512-X6/nOwoFN7RT2svEQWUsW/5C/fYMBe4fnLK9DQk4SX4mgVBiTA9h64kjUYPvGQ0F/9xwJ5U5UfTbl6BEjaQdBQ==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.52.5.tgz", + "integrity": "sha512-W901Pla8Ya95WpxDn//VF9K9u2JbocwV/v75TE0YIHNTbhqUTv9w4VuQ9MaWlNOkkEfFwkdNhXgcLqPSmHy0fA==", "cpu": [ "x64" ], @@ -13300,10 +13310,38 @@ "darwin" ] }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.52.5.tgz", + "integrity": "sha512-QofO7i7JycsYOWxe0GFqhLmF6l1TqBswJMvICnRUjqCx8b47MTo46W8AoeQwiokAx3zVryVnxtBMcGcnX12LvA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.52.5.tgz", + "integrity": "sha512-jr21b/99ew8ujZubPo9skbrItHEIE50WdV86cdSoRkKtmWa+DDr6fu2c/xyRT0F/WazZpam6kk7IHBerSL7LDQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.24.0.tgz", - "integrity": "sha512-0KXvIJQMOImLCVCz9uvvdPgfyWo93aHHp8ui3FrtOP57svqrF/roSSR5pjqL2hcMp0ljeGlU4q9o/rQaAQ3AYA==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.52.5.tgz", + "integrity": "sha512-PsNAbcyv9CcecAUagQefwX8fQn9LQ4nZkpDboBOttmyffnInRy8R8dSg6hxxl2Re5QhHBf6FYIDhIj5v982ATQ==", "cpu": [ "arm" ], @@ -13315,9 +13353,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.24.0.tgz", - "integrity": "sha512-it2BW6kKFVh8xk/BnHfakEeoLPv8STIISekpoF+nBgWM4d55CZKc7T4Dx1pEbTnYm/xEKMgy1MNtYuoA8RFIWw==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.52.5.tgz", + "integrity": "sha512-Fw4tysRutyQc/wwkmcyoqFtJhh0u31K+Q6jYjeicsGJJ7bbEq8LwPWV/w0cnzOqR2m694/Af6hpFayLJZkG2VQ==", "cpu": [ "arm" ], @@ -13329,9 +13367,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.24.0.tgz", - "integrity": "sha512-i0xTLXjqap2eRfulFVlSnM5dEbTVque/3Pi4g2y7cxrs7+a9De42z4XxKLYJ7+OhE3IgxvfQM7vQc43bwTgPwA==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.52.5.tgz", + "integrity": "sha512-a+3wVnAYdQClOTlyapKmyI6BLPAFYs0JM8HRpgYZQO02rMR09ZcV9LbQB+NL6sljzG38869YqThrRnfPMCDtZg==", "cpu": [ "arm64" ], @@ -13343,9 +13381,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.24.0.tgz", - "integrity": "sha512-9E6MKUJhDuDh604Qco5yP/3qn3y7SLXYuiC0Rpr89aMScS2UAmK1wHP2b7KAa1nSjWJc/f/Lc0Wl1L47qjiyQw==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.52.5.tgz", + "integrity": "sha512-AvttBOMwO9Pcuuf7m9PkC1PUIKsfaAJ4AYhy944qeTJgQOqJYJ9oVl2nYgY7Rk0mkbsuOpCAYSs6wLYB2Xiw0Q==", "cpu": [ "arm64" ], @@ -13356,10 +13394,24 @@ "linux" ] }, - "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.24.0.tgz", - "integrity": "sha512-2XFFPJ2XMEiF5Zi2EBf4h73oR1V/lycirxZxHZNc93SqDN/IWhYYSYj8I9381ikUFXZrz2v7r2tOVk2NBwxrWw==", + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.52.5.tgz", + "integrity": "sha512-DkDk8pmXQV2wVrF6oq5tONK6UHLz/XcEVow4JTTerdeV1uqPeHxwcg7aFsfnSm9L+OO8WJsWotKM2JJPMWrQtA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.52.5.tgz", + "integrity": "sha512-W/b9ZN/U9+hPQVvlGwjzi+Wy4xdoH2I8EjaCkMvzpI7wJUs8sWJ03Rq96jRnHkSrcHTpQe8h5Tg3ZzUPGauvAw==", "cpu": [ "ppc64" ], @@ -13371,9 +13423,23 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.24.0.tgz", - "integrity": "sha512-M3Dg4hlwuntUCdzU7KjYqbbd+BLq3JMAOhCKdBE3TcMGMZbKkDdJ5ivNdehOssMCIokNHFOsv7DO4rlEOfyKpg==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.52.5.tgz", + "integrity": "sha512-sjQLr9BW7R/ZiXnQiWPkErNfLMkkWIoCz7YMn27HldKsADEKa5WYdobaa1hmN6slu9oWQbB6/jFpJ+P2IkVrmw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.52.5.tgz", + "integrity": "sha512-hq3jU/kGyjXWTvAh2awn8oHroCbrPm8JqM7RUpKjalIRWWXE01CQOf/tUNWNHjmbMHg/hmNCwc/Pz3k1T/j/Lg==", "cpu": [ "riscv64" ], @@ -13385,9 +13451,9 @@ ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.24.0.tgz", - "integrity": "sha512-mjBaoo4ocxJppTorZVKWFpy1bfFj9FeCMJqzlMQGjpNPY9JwQi7OuS1axzNIk0nMX6jSgy6ZURDZ2w0QW6D56g==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.52.5.tgz", + "integrity": "sha512-gn8kHOrku8D4NGHMK1Y7NA7INQTRdVOntt1OCYypZPRt6skGbddska44K8iocdpxHTMMNui5oH4elPH4QOLrFQ==", "cpu": [ "s390x" ], @@ -13399,9 +13465,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.24.0.tgz", - "integrity": "sha512-ZXFk7M72R0YYFN5q13niV0B7G8/5dcQ9JDp8keJSfr3GoZeXEoMHP/HlvqROA3OMbMdfr19IjCeNAnPUG93b6A==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.52.5.tgz", + "integrity": "sha512-hXGLYpdhiNElzN770+H2nlx+jRog8TyynpTVzdlc6bndktjKWyZyiCsuDAlpd+j+W+WNqfcyAWz9HxxIGfZm1Q==", "cpu": [ "x64" ], @@ -13413,9 +13479,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.24.0.tgz", - "integrity": "sha512-w1i+L7kAXZNdYl+vFvzSZy8Y1arS7vMgIy8wusXJzRrPyof5LAb02KGr1PD2EkRcl73kHulIID0M501lN+vobQ==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.52.5.tgz", + "integrity": "sha512-arCGIcuNKjBoKAXD+y7XomR9gY6Mw7HnFBv5Rw7wQRvwYLR7gBAgV7Mb2QTyjXfTveBNFAtPt46/36vV9STLNg==", "cpu": [ "x64" ], @@ -13426,10 +13492,24 @@ "linux" ] }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.52.5.tgz", + "integrity": "sha512-QoFqB6+/9Rly/RiPjaomPLmR/13cgkIGfA40LHly9zcH1S0bN2HVFYk3a1eAyHQyjs3ZJYlXvIGtcCs5tko9Cw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.24.0.tgz", - "integrity": "sha512-VXBrnPWgBpVDCVY6XF3LEW0pOU51KbaHhccHw6AS6vBWIC60eqsH19DAeeObl+g8nKAz04QFdl/Cefta0xQtUQ==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.52.5.tgz", + "integrity": "sha512-w0cDWVR6MlTstla1cIfOGyl8+qb93FlAVutcor14Gf5Md5ap5ySfQ7R9S/NjNaMLSFdUnKGEasmVnu3lCMqB7w==", "cpu": [ "arm64" ], @@ -13441,9 +13521,9 @@ ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.24.0.tgz", - "integrity": "sha512-xrNcGDU0OxVcPTH/8n/ShH4UevZxKIO6HJFK0e15XItZP2UcaiLFd5kiX7hJnqCbSztUF8Qot+JWBC/QXRPYWQ==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.52.5.tgz", + "integrity": "sha512-Aufdpzp7DpOTULJCuvzqcItSGDH73pF3ko/f+ckJhxQyHtp67rHw3HMNxoIdDMUITJESNE6a8uh4Lo4SLouOUg==", "cpu": [ "ia32" ], @@ -13454,10 +13534,24 @@ "win32" ] }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.52.5.tgz", + "integrity": "sha512-UGBUGPFp1vkj6p8wCRraqNhqwX/4kNQPS57BCFc8wYh0g94iVIW33wJtQAx3G7vrjjNtRaxiMUylM0ktp/TRSQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.24.0.tgz", - "integrity": "sha512-fbMkAF7fufku0N2dE5TBXcNlg0pt0cJue4xBRE2Qc5Vqikxr4VCgKj/ht6SMdFcOacVA9rqF70APJ8RN/4vMJw==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.52.5.tgz", + "integrity": "sha512-TAcgQh2sSkykPRWLrdyy2AiceMckNf5loITqXxFI5VuQjS5tSuw3WlwdN8qv8vzjLAUTvYaH/mVjSFpbkFbpTg==", "cpu": [ "x64" ], @@ -13582,12 +13676,6 @@ "split2": "^4.0.0" } }, - "node_modules/@sinclair/typebox": { - "version": "0.27.8", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", - "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", - "dev": true - }, "node_modules/@sindresorhus/slugify": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@sindresorhus/slugify/-/slugify-1.1.0.tgz", @@ -14944,6 +15032,17 @@ "integrity": "sha512-hWtVTC2q7hc7xZ/RLbxapMvDMgUnDvKvMOpKal4DrMyfGBUfB1oKaZlIRr6mJL+If3bAP6sV/QneGzF6tJjZDg==", "license": "MIT" }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, "node_modules/@types/command-line-args": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/@types/command-line-args/-/command-line-args-5.2.3.tgz", @@ -14983,6 +15082,13 @@ "@types/ms": "*" } }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/eslint": { "version": "9.6.1", "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz", @@ -15006,9 +15112,9 @@ } }, "node_modules/@types/estree": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", - "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", "dev": true, "license": "MIT" }, @@ -15147,12 +15253,12 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "20.17.30", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.17.30.tgz", - "integrity": "sha512-7zf4YyHA+jvBNfVrk2Gtvs6x7E8V+YDW05bNfG2XkWDJfYRXrTiP/DsB2zSYTaHX0bGIujTBQdMVAhb+j7mwpg==", + "version": "20.19.23", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.23.tgz", + "integrity": "sha512-yIdlVVVHXpmqRhtyovZAcSy0MiPcYWGkoO4CGe/+jpP0hmNuihm4XhHbADpK++MsiLHP5MVlv+bcgdF99kSiFQ==", "license": "MIT", "dependencies": { - "undici-types": "~6.19.2" + "undici-types": "~6.21.0" } }, "node_modules/@types/node-fetch": { @@ -15165,6 +15271,12 @@ "form-data": "^4.0.0" } }, + "node_modules/@types/node/node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, "node_modules/@types/nodemailer": { "version": "6.4.14", "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.14.tgz", @@ -15904,96 +16016,88 @@ "dev": true }, "node_modules/@vitest/expect": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-1.2.2.tgz", - "integrity": "sha512-3jpcdPAD7LwHUUiT2pZTj2U82I2Tcgg2oVPvKxhn6mDI2On6tfvPQTjAI4628GUGDZrCm4Zna9iQHm5cEexOAg==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.4.tgz", + "integrity": "sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==", "dev": true, + "license": "MIT", "dependencies": { - "@vitest/spy": "1.2.2", - "@vitest/utils": "1.2.2", - "chai": "^4.3.10" + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.4.tgz", + "integrity": "sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" }, "funding": { "url": "https://opencollective.com/vitest" } }, "node_modules/@vitest/runner": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-1.2.2.tgz", - "integrity": "sha512-JctG7QZ4LSDXr5CsUweFgcpEvrcxOV1Gft7uHrvkQ+fsAVylmWQvnaAr/HDp3LAH1fztGMQZugIheTWjaGzYIg==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.4.tgz", + "integrity": "sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==", "dev": true, + "license": "MIT", "dependencies": { - "@vitest/utils": "1.2.2", - "p-limit": "^5.0.0", - "pathe": "^1.1.1" + "@vitest/utils": "3.2.4", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" }, "funding": { "url": "https://opencollective.com/vitest" } }, - "node_modules/@vitest/runner/node_modules/p-limit": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-5.0.0.tgz", - "integrity": "sha512-/Eaoq+QyLSiXQ4lyYV23f14mZRQcXnxfHrN0vCai+ak9G0pp9iEQukIIZq5NccEvwRB8PUnZT0KsOoDCINS1qQ==", - "dev": true, - "dependencies": { - "yocto-queue": "^1.0.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@vitest/runner/node_modules/yocto-queue": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.0.0.tgz", - "integrity": "sha512-9bnSc/HEW2uRy67wc+T8UwauLuPJVn28jb+GtJY16iiKWyvmYJRXVT4UamsAEGQfPohgr2q4Tq0sQbQlxTfi1g==", - "dev": true, - "engines": { - "node": ">=12.20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/@vitest/snapshot": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-1.2.2.tgz", - "integrity": "sha512-SmGY4saEw1+bwE1th6S/cZmPxz/Q4JWsl7LvbQIky2tKE35US4gd0Mjzqfr84/4OD0tikGWaWdMja/nWL5NIPA==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.4.tgz", + "integrity": "sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==", "dev": true, + "license": "MIT", "dependencies": { - "magic-string": "^0.30.5", - "pathe": "^1.1.1", - "pretty-format": "^29.7.0" + "@vitest/pretty-format": "3.2.4", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" }, "funding": { "url": "https://opencollective.com/vitest" } }, "node_modules/@vitest/spy": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-1.2.2.tgz", - "integrity": "sha512-k9Gcahssw8d7X3pSLq3e3XEu/0L78mUkCjivUqCQeXJm9clfXR/Td8+AP+VC1O6fKPIDLcHDTAmBOINVuv6+7g==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.4.tgz", + "integrity": "sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==", "dev": true, + "license": "MIT", "dependencies": { - "tinyspy": "^2.2.0" + "tinyspy": "^4.0.3" }, "funding": { "url": "https://opencollective.com/vitest" } }, "node_modules/@vitest/utils": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-1.2.2.tgz", - "integrity": "sha512-WKITBHLsBHlpjnDQahr+XK6RE7MiAsgrIkr0pGhQ9ygoxBfUeG0lUG5iLlzqjmKSlBv3+j5EGsriBzh+C3Tq9g==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.4.tgz", + "integrity": "sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==", "dev": true, + "license": "MIT", "dependencies": { - "diff-sequences": "^29.6.3", - "estree-walker": "^3.0.3", - "loupe": "^2.3.7", - "pretty-format": "^29.7.0" + "@vitest/pretty-format": "3.2.4", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" }, "funding": { "url": "https://opencollective.com/vitest" @@ -17030,12 +17134,13 @@ } }, "node_modules/assertion-error": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", - "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", "dev": true, + "license": "MIT", "engines": { - "node": "*" + "node": ">=12" } }, "node_modules/async": { @@ -17931,10 +18036,11 @@ } }, "node_modules/bundle-require": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-4.0.2.tgz", - "integrity": "sha512-jwzPOChofl67PSTW2SGubV9HBQAhhR2i6nskiOThauo9dzwDUgOWQScFVaJkjEfYX+UXiD+LEx8EblQMc2wIag==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/bundle-require/-/bundle-require-5.1.0.tgz", + "integrity": "sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==", "dev": true, + "license": "MIT", "dependencies": { "load-tsconfig": "^0.2.3" }, @@ -17942,7 +18048,7 @@ "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "peerDependencies": { - "esbuild": ">=0.17" + "esbuild": ">=0.18" } }, "node_modules/bytes": { @@ -18189,21 +18295,20 @@ } }, "node_modules/chai": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/chai/-/chai-4.4.1.tgz", - "integrity": "sha512-13sOfMv2+DWduEU+/xbun3LScLoqN17nBeTLUsmDfKdoiC1fr0n9PU4guu4AhRcOVFk/sW8LyZWHuhWtQZiF+g==", + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", "dev": true, + "license": "MIT", "dependencies": { - "assertion-error": "^1.1.0", - "check-error": "^1.0.3", - "deep-eql": "^4.1.3", - "get-func-name": "^2.0.2", - "loupe": "^2.3.6", - "pathval": "^1.1.1", - "type-detect": "^4.0.8" + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" }, "engines": { - "node": ">=4" + "node": ">=18" } }, "node_modules/chalk": { @@ -18270,15 +18375,13 @@ } }, "node_modules/check-error": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", - "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.1.tgz", + "integrity": "sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==", "dev": true, - "dependencies": { - "get-func-name": "^2.0.2" - }, + "license": "MIT", "engines": { - "node": "*" + "node": ">= 16" } }, "node_modules/chokidar": { @@ -19056,13 +19159,11 @@ } }, "node_modules/deep-eql": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", - "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", "dev": true, - "dependencies": { - "type-detect": "^4.0.0" - }, + "license": "MIT", "engines": { "node": ">=6" } @@ -19297,15 +19398,6 @@ "node": ">=0.3.1" } }, - "node_modules/diff-sequences": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", - "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", - "dev": true, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, "node_modules/dir-glob": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", @@ -19837,40 +19929,62 @@ "license": "MIT" }, "node_modules/esbuild": { - "version": "0.18.20", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.18.20.tgz", - "integrity": "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.11.tgz", + "integrity": "sha512-KohQwyzrKTQmhXDW1PjCv3Tyspn9n5GcY2RTDqeORIdIJY8yKIF7sTSopFmn/wpMPW4rdPXI0UE5LJLuq3bx0Q==", "dev": true, "hasInstallScript": true, + "license": "MIT", "bin": { "esbuild": "bin/esbuild" }, "engines": { - "node": ">=12" + "node": ">=18" }, "optionalDependencies": { - "@esbuild/android-arm": "0.18.20", - "@esbuild/android-arm64": "0.18.20", - "@esbuild/android-x64": "0.18.20", - "@esbuild/darwin-arm64": "0.18.20", - "@esbuild/darwin-x64": "0.18.20", - "@esbuild/freebsd-arm64": "0.18.20", - "@esbuild/freebsd-x64": "0.18.20", - "@esbuild/linux-arm": "0.18.20", - "@esbuild/linux-arm64": "0.18.20", - "@esbuild/linux-ia32": "0.18.20", - "@esbuild/linux-loong64": "0.18.20", - "@esbuild/linux-mips64el": "0.18.20", - "@esbuild/linux-ppc64": "0.18.20", - "@esbuild/linux-riscv64": "0.18.20", - "@esbuild/linux-s390x": "0.18.20", - "@esbuild/linux-x64": "0.18.20", - "@esbuild/netbsd-x64": "0.18.20", - "@esbuild/openbsd-x64": "0.18.20", - "@esbuild/sunos-x64": "0.18.20", - "@esbuild/win32-arm64": "0.18.20", - "@esbuild/win32-ia32": "0.18.20", - "@esbuild/win32-x64": "0.18.20" + "@esbuild/aix-ppc64": "0.25.11", + "@esbuild/android-arm": "0.25.11", + "@esbuild/android-arm64": "0.25.11", + "@esbuild/android-x64": "0.25.11", + "@esbuild/darwin-arm64": "0.25.11", + "@esbuild/darwin-x64": "0.25.11", + "@esbuild/freebsd-arm64": "0.25.11", + "@esbuild/freebsd-x64": "0.25.11", + "@esbuild/linux-arm": "0.25.11", + "@esbuild/linux-arm64": "0.25.11", + "@esbuild/linux-ia32": "0.25.11", + "@esbuild/linux-loong64": "0.25.11", + "@esbuild/linux-mips64el": "0.25.11", + "@esbuild/linux-ppc64": "0.25.11", + "@esbuild/linux-riscv64": "0.25.11", + "@esbuild/linux-s390x": "0.25.11", + "@esbuild/linux-x64": "0.25.11", + "@esbuild/netbsd-arm64": "0.25.11", + "@esbuild/netbsd-x64": "0.25.11", + "@esbuild/openbsd-arm64": "0.25.11", + "@esbuild/openbsd-x64": "0.25.11", + "@esbuild/openharmony-arm64": "0.25.11", + "@esbuild/sunos-x64": "0.25.11", + "@esbuild/win32-arm64": "0.25.11", + "@esbuild/win32-ia32": "0.25.11", + "@esbuild/win32-x64": "0.25.11" + } + }, + "node_modules/esbuild/node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.11.tgz", + "integrity": "sha512-rOREuNIQgaiR+9QuNkbkxubbp8MSO9rONmwP5nKncnWJ9v5jQ4JxFnLu4zDSRPf3x4u+2VN4pM4RdyIzDty/wQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" } }, "node_modules/escalade": { @@ -20405,6 +20519,7 @@ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", "dev": true, + "license": "MIT", "dependencies": { "@types/estree": "^1.0.0" } @@ -20478,6 +20593,16 @@ "node": ">=0.10.0" } }, + "node_modules/expect-type": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.2.2.tgz", + "integrity": "sha512-JhFGDVJ7tmDJItKhYgJCGLOWjuK9vPxiXoUFLwLDc99NlmklilbiQJwoctZtt13+xMw91MCk/REan6MWHqDjyA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/exponential-backoff": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.2.tgz", @@ -20867,6 +20992,24 @@ "reusify": "^1.0.4" } }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, "node_modules/fecha": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz", @@ -21004,6 +21147,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/fix-dts-default-cjs-exports": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz", + "integrity": "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "magic-string": "^0.30.17", + "mlly": "^1.7.4", + "rollup": "^4.34.8" + } + }, "node_modules/flat-cache": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", @@ -21534,15 +21689,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/get-func-name": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", - "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", - "dev": true, - "engines": { - "node": "*" - } - }, "node_modules/get-intrinsic": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", @@ -21596,18 +21742,6 @@ "node": ">= 0.4" } }, - "node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/get-symbol-description": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.0.tgz", @@ -21625,10 +21759,11 @@ } }, "node_modules/get-tsconfig": { - "version": "4.7.2", - "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.7.2.tgz", - "integrity": "sha512-wuMsz4leaj5hbGgg4IvDU0bqJagpftG5l5cXIAvo8uZrqn0NJqwtfupTN00VnkQJPcIRrxYrm1Ue24btpCha2A==", + "version": "4.13.0", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.0.tgz", + "integrity": "sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==", "dev": true, + "license": "MIT", "dependencies": { "resolve-pkg-maps": "^1.0.0" }, @@ -22343,15 +22478,6 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, - "node_modules/human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", - "dev": true, - "engines": { - "node": ">=10.17.0" - } - }, "node_modules/iconv-lite": { "version": "0.6.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", @@ -22902,18 +23028,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/is-stream": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", - "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", - "dev": true, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/is-string": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz", @@ -23392,12 +23506,6 @@ "node": ">=6" } }, - "node_modules/jsonc-parser": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.0.tgz", - "integrity": "sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==", - "dev": true - }, "node_modules/jsonfile": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", @@ -23809,12 +23917,16 @@ "license": "MIT" }, "node_modules/lilconfig": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.0.0.tgz", - "integrity": "sha512-K2U4W2Ff5ibV7j7ydLr+zLAkIg5JJ4lPn1Ltsdt+Tz/IjQ8buJ55pZAxoP34lqIiwtF9iAvtLv3JGv7CAyAg+g==", + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", "dev": true, + "license": "MIT", "engines": { "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" } }, "node_modules/limiter": { @@ -23856,6 +23968,7 @@ "resolved": "https://registry.npmjs.org/load-tsconfig/-/load-tsconfig-0.2.5.tgz", "integrity": "sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==", "dev": true, + "license": "MIT", "engines": { "node": "^12.20.0 || ^14.13.1 || >=16.0.0" } @@ -23870,22 +23983,6 @@ "node": ">=6.11.5" } }, - "node_modules/local-pkg": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-0.5.0.tgz", - "integrity": "sha512-ok6z3qlYyCDS4ZEU27HaU6x/xZa9Whf8jD4ptH5UZTQYZVYeb9bnZ3ojVhiJNLiXK1Hfc0GNbLXcmZ5plLDDBg==", - "dev": true, - "dependencies": { - "mlly": "^1.4.2", - "pkg-types": "^1.0.3" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, "node_modules/localforage": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/localforage/-/localforage-1.10.0.tgz", @@ -24035,13 +24132,11 @@ "integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==" }, "node_modules/loupe": { - "version": "2.3.7", - "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", - "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", "dev": true, - "dependencies": { - "get-func-name": "^2.0.1" - } + "license": "MIT" }, "node_modules/lru-cache": { "version": "6.0.0", @@ -24072,15 +24167,13 @@ } }, "node_modules/magic-string": { - "version": "0.30.7", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.7.tgz", - "integrity": "sha512-8vBuFF/I/+OSLRmdf2wwFCJCz+nSn0m6DPvGH1fS/KiQoSaR+sETbov0eIk9KhEKy8CYqIkIAnbohxT/4H0kuA==", + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", "dev": true, + "license": "MIT", "dependencies": { - "@jridgewell/sourcemap-codec": "^1.4.15" - }, - "engines": { - "node": ">=12" + "@jridgewell/sourcemap-codec": "^1.5.5" } }, "node_modules/make-dir": { @@ -24513,15 +24606,16 @@ "dev": true }, "node_modules/mlly": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.4.2.tgz", - "integrity": "sha512-i/Ykufi2t1EZ6NaPLdfnZk2AX8cs0d+mTzVKuPfqPKPatxLApaBoxJQ9x1/uckXtrS/U5oisPMDkNs0yQTaBRg==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.8.0.tgz", + "integrity": "sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==", "dev": true, + "license": "MIT", "dependencies": { - "acorn": "^8.10.0", - "pathe": "^1.1.1", - "pkg-types": "^1.0.3", - "ufo": "^1.3.0" + "acorn": "^8.15.0", + "pathe": "^2.0.3", + "pkg-types": "^1.3.1", + "ufo": "^1.6.1" } }, "node_modules/mnemonist": { @@ -24828,9 +24922,9 @@ "license": "MIT" }, "node_modules/nanoid": { - "version": "3.3.8", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz", - "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==", + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", "funding": [ { "type": "github", @@ -25279,33 +25373,6 @@ "node": ">=0.10.0" } }, - "node_modules/npm-run-path": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.1.0.tgz", - "integrity": "sha512-sJOdmRGrY2sjNTRMbSvluQqg+8X7ZK61yvzBEIDhz4f8z1TZFYABsqjjCBd/0PUNE9M6QDgHJXQkGUEm7Q+l9Q==", - "dev": true, - "dependencies": { - "path-key": "^4.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/npm-run-path/node_modules/path-key": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", - "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", - "dev": true, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/npmlog": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz", @@ -25355,13 +25422,6 @@ "node": "^14.16.0 || >=16.10.0" } }, - "node_modules/nypm/node_modules/pathe": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", - "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", - "dev": true, - "license": "MIT" - }, "node_modules/nypm/node_modules/pkg-types": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-2.3.0.tgz", @@ -27958,18 +28018,20 @@ } }, "node_modules/pathe": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.1.tgz", - "integrity": "sha512-d+RQGp0MAYTIaDBIMmOfMwz3E+LOZnxx1HZd5R18mmCZY0QBlK0LDZfPc8FW8Ed2DlvsuE6PRjroDY+wg4+j/Q==", - "dev": true + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" }, "node_modules/pathval": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", - "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", "dev": true, + "license": "MIT", "engines": { - "node": "*" + "node": ">= 14.16" } }, "node_modules/pause": { @@ -28382,16 +28444,24 @@ } }, "node_modules/pkg-types": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.0.3.tgz", - "integrity": "sha512-nN7pYi0AQqJnoLPC9eHFQ8AcyaixBUOwvqc5TDnIKCMEE6I0y8P7OKA7fPexsXGCGxQDl/cmrLAp26LhcwxZ4A==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", + "integrity": "sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==", "dev": true, + "license": "MIT", "dependencies": { - "jsonc-parser": "^3.2.0", - "mlly": "^1.2.0", - "pathe": "^1.1.0" + "confbox": "^0.1.8", + "mlly": "^1.7.4", + "pathe": "^2.0.1" } }, + "node_modules/pkg-types/node_modules/confbox": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/confbox/-/confbox-0.1.8.tgz", + "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", + "dev": true, + "license": "MIT" + }, "node_modules/pkijs": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.2.4.tgz", @@ -28430,9 +28500,9 @@ } }, "node_modules/postcss": { - "version": "8.4.47", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.47.tgz", - "integrity": "sha512-56rxCq7G/XfB4EkXq9Egn5GCqugWvDFjafDOThIdMBsI15iqPqR5r15TfSr1YPYeEI19YeaXMCbY6u88Y76GLQ==", + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", "dev": true, "funding": [ { @@ -28450,8 +28520,8 @@ ], "license": "MIT", "dependencies": { - "nanoid": "^3.3.7", - "picocolors": "^1.1.0", + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", "source-map-js": "^1.2.1" }, "engines": { @@ -28725,32 +28795,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", - "dev": true, - "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/pretty-format/node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, "node_modules/prism-react-renderer": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/prism-react-renderer/-/prism-react-renderer-2.4.1.tgz", @@ -29339,397 +29383,6 @@ "node": ">=18.0.0" } }, - "node_modules/react-email/node_modules/@esbuild/aix-ppc64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.0.tgz", - "integrity": "sha512-O7vun9Sf8DFjH2UtqK8Ku3LkquL9SZL8OLY1T5NZkA34+wG3OQF7cl4Ql8vdNzM6fzBbYfLaiRLIOZ+2FOCgBQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/android-arm": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.0.tgz", - "integrity": "sha512-PTyWCYYiU0+1eJKmw21lWtC+d08JDZPQ5g+kFyxP0V+es6VPPSUhM6zk8iImp2jbV6GwjX4pap0JFbUQN65X1g==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/android-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.0.tgz", - "integrity": "sha512-grvv8WncGjDSyUBjN9yHXNt+cq0snxXbDxy5pJtzMKGmmpPxeAmAhWxXI+01lU5rwZomDgD3kJwulEnhTRUd6g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/android-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.0.tgz", - "integrity": "sha512-m/ix7SfKG5buCnxasr52+LI78SQ+wgdENi9CqyCXwjVR2X4Jkz+BpC3le3AoBPYTC9NHklwngVXvbJ9/Akhrfg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/darwin-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.0.tgz", - "integrity": "sha512-mVwdUb5SRkPayVadIOI78K7aAnPamoeFR2bT5nszFUZ9P8UpK4ratOdYbZZXYSqPKMHfS1wdHCJk1P1EZpRdvw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/darwin-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.0.tgz", - "integrity": "sha512-DgDaYsPWFTS4S3nWpFcMn/33ZZwAAeAFKNHNa1QN0rI4pUjgqf0f7ONmXf6d22tqTY+H9FNdgeaAa+YIFUn2Rg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/freebsd-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.0.tgz", - "integrity": "sha512-VN4ocxy6dxefN1MepBx/iD1dH5K8qNtNe227I0mnTRjry8tj5MRk4zprLEdG8WPyAPb93/e4pSgi1SoHdgOa4w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/freebsd-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.0.tgz", - "integrity": "sha512-mrSgt7lCh07FY+hDD1TxiTyIHyttn6vnjesnPoVDNmDfOmggTLXRv8Id5fNZey1gl/V2dyVK1VXXqVsQIiAk+A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/linux-arm": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.0.tgz", - "integrity": "sha512-vkB3IYj2IDo3g9xX7HqhPYxVkNQe8qTK55fraQyTzTX/fxaDtXiEnavv9geOsonh2Fd2RMB+i5cbhu2zMNWJwg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/linux-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.0.tgz", - "integrity": "sha512-9QAQjTWNDM/Vk2bgBl17yWuZxZNQIF0OUUuPZRKoDtqF2k4EtYbpyiG5/Dk7nqeK6kIJWPYldkOcBqjXjrUlmg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/linux-ia32": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.0.tgz", - "integrity": "sha512-43ET5bHbphBegyeqLb7I1eYn2P/JYGNmzzdidq/w0T8E2SsYL1U6un2NFROFRg1JZLTzdCoRomg8Rvf9M6W6Gg==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/linux-loong64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.0.tgz", - "integrity": "sha512-fC95c/xyNFueMhClxJmeRIj2yrSMdDfmqJnyOY4ZqsALkDrrKJfIg5NTMSzVBr5YW1jf+l7/cndBfP3MSDpoHw==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/linux-mips64el": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.0.tgz", - "integrity": "sha512-nkAMFju7KDW73T1DdH7glcyIptm95a7Le8irTQNO/qtkoyypZAnjchQgooFUDQhNAy4iu08N79W4T4pMBwhPwQ==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/linux-ppc64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.0.tgz", - "integrity": "sha512-NhyOejdhRGS8Iwv+KKR2zTq2PpysF9XqY+Zk77vQHqNbo/PwZCzB5/h7VGuREZm1fixhs4Q/qWRSi5zmAiO4Fw==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/linux-riscv64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.0.tgz", - "integrity": "sha512-5S/rbP5OY+GHLC5qXp1y/Mx//e92L1YDqkiBbO9TQOvuFXM+iDqUNG5XopAnXoRH3FjIUDkeGcY1cgNvnXp/kA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/linux-s390x": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.0.tgz", - "integrity": "sha512-XM2BFsEBz0Fw37V0zU4CXfcfuACMrppsMFKdYY2WuTS3yi8O1nFOhil/xhKTmE1nPmVyvQJjJivgDT+xh8pXJA==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/linux-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.0.tgz", - "integrity": "sha512-9yl91rHw/cpwMCNytUDxwj2XjFpxML0y9HAOH9pNVQDpQrBxHy01Dx+vaMu0N1CKa/RzBD2hB4u//nfc+Sd3Cw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/netbsd-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.0.tgz", - "integrity": "sha512-jl+qisSB5jk01N5f7sPCsBENCOlPiS/xptD5yxOx2oqQfyourJwIKLRA2yqWdifj3owQZCL2sn6o08dBzZGQzA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/openbsd-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.0.tgz", - "integrity": "sha512-2gwwriSMPcCFRlPlKx3zLQhfN/2WjJ2NSlg5TKLQOJdV0mSxIcYNTMhk3H3ulL/cak+Xj0lY1Ym9ysDV1igceg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/sunos-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.0.tgz", - "integrity": "sha512-bxI7ThgLzPrPz484/S9jLlvUAHYMzy6I0XiU1ZMeAEOBcS0VePBFxh1JjTQt3Xiat5b6Oh4x7UC7IwKQKIJRIg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/win32-arm64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.0.tgz", - "integrity": "sha512-ZUAc2YK6JW89xTbXvftxdnYy3m4iHIkDtK3CLce8wg8M2L+YZhIvO1DKpxrd0Yr59AeNNkTiic9YLf6FTtXWMw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/win32-ia32": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.0.tgz", - "integrity": "sha512-eSNxISBu8XweVEWG31/JzjkIGbGIJN/TrRoiSVZwZ6pkC6VX4Im/WV2cz559/TXLcYbcrDN8JtKgd9DJVIo8GA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/react-email/node_modules/@esbuild/win32-x64": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.0.tgz", - "integrity": "sha512-ZENoHJBxA20C2zFzh6AI4fT6RraMzjYw4xKWemRTRmRVtN9c5DcH9r/f2ihEkMjOW5eGgrwCslG/+Y/3bL+DHQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, "node_modules/react-email/node_modules/chokidar": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", @@ -29772,47 +29425,6 @@ "node": ">=18" } }, - "node_modules/react-email/node_modules/esbuild": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.0.tgz", - "integrity": "sha512-BXq5mqc8ltbaN34cDqWuYKyNhX8D/Z0J1xdtdQ8UcIIIyJyz+ZMKUt58tF3SrZ85jcfN/PZYhjR5uDQAYNVbuw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.25.0", - "@esbuild/android-arm": "0.25.0", - "@esbuild/android-arm64": "0.25.0", - "@esbuild/android-x64": "0.25.0", - "@esbuild/darwin-arm64": "0.25.0", - "@esbuild/darwin-x64": "0.25.0", - "@esbuild/freebsd-arm64": "0.25.0", - "@esbuild/freebsd-x64": "0.25.0", - "@esbuild/linux-arm": "0.25.0", - "@esbuild/linux-arm64": "0.25.0", - "@esbuild/linux-ia32": "0.25.0", - "@esbuild/linux-loong64": "0.25.0", - "@esbuild/linux-mips64el": "0.25.0", - "@esbuild/linux-ppc64": "0.25.0", - "@esbuild/linux-riscv64": "0.25.0", - "@esbuild/linux-s390x": "0.25.0", - "@esbuild/linux-x64": "0.25.0", - "@esbuild/netbsd-arm64": "0.25.0", - "@esbuild/netbsd-x64": "0.25.0", - "@esbuild/openbsd-arm64": "0.25.0", - "@esbuild/openbsd-x64": "0.25.0", - "@esbuild/sunos-x64": "0.25.0", - "@esbuild/win32-arm64": "0.25.0", - "@esbuild/win32-ia32": "0.25.0", - "@esbuild/win32-x64": "0.25.0" - } - }, "node_modules/react-email/node_modules/glob": { "version": "11.0.3", "resolved": "https://registry.npmjs.org/glob/-/glob-11.0.3.tgz", @@ -30104,12 +29716,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/react-is": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", - "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", - "dev": true - }, "node_modules/react-promise-suspense": { "version": "0.3.4", "resolved": "https://registry.npmjs.org/react-promise-suspense/-/react-promise-suspense-0.3.4.tgz", @@ -30609,13 +30215,13 @@ } }, "node_modules/rollup": { - "version": "4.24.0", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.24.0.tgz", - "integrity": "sha512-DOmrlGSXNk1DM0ljiQA+i+o0rSLhtii1je5wgk60j49d1jHT5YYttBv1iWOnYSTG+fZZESUOSNiAl89SIet+Cg==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.52.5.tgz", + "integrity": "sha512-3GuObel8h7Kqdjt0gxkEzaifHTqLVW56Y/bjN7PSQtkKr0w3V/QYSdt6QWYtd7A1xUtYQigtdUfgj1RvWVtorw==", "dev": true, "license": "MIT", "dependencies": { - "@types/estree": "1.0.6" + "@types/estree": "1.0.8" }, "bin": { "rollup": "dist/bin/rollup" @@ -30625,22 +30231,28 @@ "npm": ">=8.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.24.0", - "@rollup/rollup-android-arm64": "4.24.0", - "@rollup/rollup-darwin-arm64": "4.24.0", - "@rollup/rollup-darwin-x64": "4.24.0", - "@rollup/rollup-linux-arm-gnueabihf": "4.24.0", - "@rollup/rollup-linux-arm-musleabihf": "4.24.0", - "@rollup/rollup-linux-arm64-gnu": "4.24.0", - "@rollup/rollup-linux-arm64-musl": "4.24.0", - "@rollup/rollup-linux-powerpc64le-gnu": "4.24.0", - "@rollup/rollup-linux-riscv64-gnu": "4.24.0", - "@rollup/rollup-linux-s390x-gnu": "4.24.0", - "@rollup/rollup-linux-x64-gnu": "4.24.0", - "@rollup/rollup-linux-x64-musl": "4.24.0", - "@rollup/rollup-win32-arm64-msvc": "4.24.0", - "@rollup/rollup-win32-ia32-msvc": "4.24.0", - "@rollup/rollup-win32-x64-msvc": "4.24.0", + "@rollup/rollup-android-arm-eabi": "4.52.5", + "@rollup/rollup-android-arm64": "4.52.5", + "@rollup/rollup-darwin-arm64": "4.52.5", + "@rollup/rollup-darwin-x64": "4.52.5", + "@rollup/rollup-freebsd-arm64": "4.52.5", + "@rollup/rollup-freebsd-x64": "4.52.5", + "@rollup/rollup-linux-arm-gnueabihf": "4.52.5", + "@rollup/rollup-linux-arm-musleabihf": "4.52.5", + "@rollup/rollup-linux-arm64-gnu": "4.52.5", + "@rollup/rollup-linux-arm64-musl": "4.52.5", + "@rollup/rollup-linux-loong64-gnu": "4.52.5", + "@rollup/rollup-linux-ppc64-gnu": "4.52.5", + "@rollup/rollup-linux-riscv64-gnu": "4.52.5", + "@rollup/rollup-linux-riscv64-musl": "4.52.5", + "@rollup/rollup-linux-s390x-gnu": "4.52.5", + "@rollup/rollup-linux-x64-gnu": "4.52.5", + "@rollup/rollup-linux-x64-musl": "4.52.5", + "@rollup/rollup-openharmony-arm64": "4.52.5", + "@rollup/rollup-win32-arm64-msvc": "4.52.5", + "@rollup/rollup-win32-ia32-msvc": "4.52.5", + "@rollup/rollup-win32-x64-gnu": "4.52.5", + "@rollup/rollup-win32-x64-msvc": "4.52.5", "fsevents": "~2.3.2" } }, @@ -31145,7 +30757,8 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", - "dev": true + "dev": true, + "license": "ISC" }, "node_modules/signal-exit": { "version": "3.0.7", @@ -31829,7 +31442,8 @@ "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/stacktrace-parser": { "version": "0.1.11", @@ -31868,10 +31482,11 @@ } }, "node_modules/std-env": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.6.0.tgz", - "integrity": "sha512-aFZ19IgVmhdB2uX599ve2kE6BIE3YMnQ6Gp6BURhW/oIzpXGKr878TQfAQZn1+i0Flcc/UKUy1gOlcfaUBCryg==", - "dev": true + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" }, "node_modules/stdin-discarder": { "version": "0.1.0", @@ -32104,18 +31719,6 @@ "node": ">=4" } }, - "node_modules/strip-final-newline": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", - "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", - "dev": true, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/strip-json-comments": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", @@ -32128,17 +31731,25 @@ } }, "node_modules/strip-literal": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-1.3.0.tgz", - "integrity": "sha512-PugKzOsyXpArk0yWmUwqOZecSO0GH0bPoctLcqNDH9J04pVW3lflYE0ujElBGTloevcxF5MofAOZ7C5l2b+wLg==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", "dev": true, + "license": "MIT", "dependencies": { - "acorn": "^8.10.0" + "js-tokens": "^9.0.1" }, "funding": { "url": "https://github.com/sponsors/antfu" } }, + "node_modules/strip-literal/node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, "node_modules/strnum": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.0.5.tgz", @@ -32175,14 +31786,15 @@ } }, "node_modules/sucrase": { - "version": "3.34.0", - "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.34.0.tgz", - "integrity": "sha512-70/LQEZ07TEcxiU2dz51FKaE6hCTWC6vr7FOk3Gr0U60C3shtAN+H+BFr9XlYe5xqf3RA8nrc+VIwzCfnxuXJw==", + "version": "3.35.0", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.0.tgz", + "integrity": "sha512-8EbVDiu9iN/nESwxeSxDKe0dunta1GOlHufmSSXxMD2z2/tMZpDMpvXQGsc+ajGo8y2uYUmixaSRUc/QPoQ0GA==", "dev": true, + "license": "MIT", "dependencies": { "@jridgewell/gen-mapping": "^0.3.2", "commander": "^4.0.0", - "glob": "7.1.6", + "glob": "^10.3.10", "lines-and-columns": "^1.1.6", "mz": "^2.7.0", "pirates": "^4.0.1", @@ -32193,7 +31805,17 @@ "sucrase-node": "bin/sucrase-node" }, "engines": { - "node": ">=8" + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/sucrase/node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" } }, "node_modules/sucrase/node_modules/commander": { @@ -32206,25 +31828,68 @@ } }, "node_modules/sucrase/node_modules/glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "version": "10.4.5", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", + "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", "dev": true, + "license": "ISC", "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" }, - "engines": { - "node": "*" + "bin": { + "glob": "dist/esm/bin.mjs" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/sucrase/node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/sucrase/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/sucrase/node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, "node_modules/supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", @@ -32708,10 +32373,11 @@ } }, "node_modules/tinybench": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.5.1.tgz", - "integrity": "sha512-65NKvSuAVDP/n4CqH+a9w2kTlLReS9vhsAP06MWx+/89nMinJyB2icyl58RIcqCmIggpojIGeuJGhjU1aGMBSg==", - "dev": true + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" }, "node_modules/tinyexec": { "version": "0.3.2", @@ -32720,20 +32386,62 @@ "dev": true, "license": "MIT" }, - "node_modules/tinypool": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-0.8.2.tgz", - "integrity": "sha512-SUszKYe5wgsxnNOVlBYO6IC+8VGWdVGZWAqUxp3UErNBtptZvWbwyUOyzNL59zigz2rCA92QiL3wvG+JDSdJdQ==", + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", "engines": { "node": ">=14.0.0" } }, "node_modules/tinyspy": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-2.2.1.tgz", - "integrity": "sha512-KYad6Vy5VDWV4GH3fjpseMQ/XU2BhIYP7Vzd0LG44qRWm/Yt2WCOTicFdvmgo6gWaqooMQCawTtILVQJupKu7A==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz", + "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=14.0.0" } @@ -32995,24 +32703,28 @@ "license": "0BSD" }, "node_modules/tsup": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/tsup/-/tsup-8.0.1.tgz", - "integrity": "sha512-hvW7gUSG96j53ZTSlT4j/KL0q1Q2l6TqGBFc6/mu/L46IoNWqLLUzLRLP1R8Q7xrJTmkDxxDoojV5uCVs1sVOg==", + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/tsup/-/tsup-8.5.0.tgz", + "integrity": "sha512-VmBp77lWNQq6PfuMqCHD3xWl22vEoWsKajkF8t+yMBawlUS8JzEI+vOVMeuNZIuMML8qXRizFKi9oD5glKQVcQ==", "dev": true, + "license": "MIT", "dependencies": { - "bundle-require": "^4.0.0", - "cac": "^6.7.12", - "chokidar": "^3.5.1", - "debug": "^4.3.1", - "esbuild": "^0.19.2", - "execa": "^5.0.0", - "globby": "^11.0.3", - "joycon": "^3.0.1", - "postcss-load-config": "^4.0.1", + "bundle-require": "^5.1.0", + "cac": "^6.7.14", + "chokidar": "^4.0.3", + "consola": "^3.4.0", + "debug": "^4.4.0", + "esbuild": "^0.25.0", + "fix-dts-default-cjs-exports": "^1.0.0", + "joycon": "^3.1.1", + "picocolors": "^1.1.1", + "postcss-load-config": "^6.0.1", "resolve-from": "^5.0.0", - "rollup": "^4.0.2", + "rollup": "^4.34.8", "source-map": "0.8.0-beta.0", - "sucrase": "^3.20.3", + "sucrase": "^3.35.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.11", "tree-kill": "^1.2.2" }, "bin": { @@ -33043,365 +32755,30 @@ } } }, - "node_modules/tsup/node_modules/@esbuild/android-arm": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.9.tgz", - "integrity": "sha512-jkYjjq7SdsWuNI6b5quymW0oC83NN5FdRPuCbs9HZ02mfVdAP8B8eeqLSYU3gb6OJEaY5CQabtTFbqBf26H3GA==", - "cpu": [ - "arm" - ], + "node_modules/tsup/node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", "dev": true, - "optional": true, - "os": [ - "android" - ], + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/android-arm64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.9.tgz", - "integrity": "sha512-q4cR+6ZD0938R19MyEW3jEsMzbb/1rulLXiNAJQADD/XYp7pT+rOS5JGxvpRW8dFDEfjW4wLgC/3FXIw4zYglQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/android-x64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.9.tgz", - "integrity": "sha512-KOqoPntWAH6ZxDwx1D6mRntIgZh9KodzgNOy5Ebt9ghzffOk9X2c1sPwtM9P+0eXbefnDhqYfkh5PLP5ULtWFA==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/darwin-arm64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.9.tgz", - "integrity": "sha512-KBJ9S0AFyLVx2E5D8W0vExqRW01WqRtczUZ8NRu+Pi+87opZn5tL4Y0xT0mA4FtHctd0ZgwNoN639fUUGlNIWw==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/darwin-x64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.9.tgz", - "integrity": "sha512-vE0VotmNTQaTdX0Q9dOHmMTao6ObjyPm58CHZr1UK7qpNleQyxlFlNCaHsHx6Uqv86VgPmR4o2wdNq3dP1qyDQ==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/freebsd-arm64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.9.tgz", - "integrity": "sha512-uFQyd/o1IjiEk3rUHSwUKkqZwqdvuD8GevWF065eqgYfexcVkxh+IJgwTaGZVu59XczZGcN/YMh9uF1fWD8j1g==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/freebsd-x64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.9.tgz", - "integrity": "sha512-WMLgWAtkdTbTu1AWacY7uoj/YtHthgqrqhf1OaEWnZb7PQgpt8eaA/F3LkV0E6K/Lc0cUr/uaVP/49iE4M4asA==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/linux-arm": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.9.tgz", - "integrity": "sha512-C/ChPohUYoyUaqn1h17m/6yt6OB14hbXvT8EgM1ZWaiiTYz7nWZR0SYmMnB5BzQA4GXl3BgBO1l8MYqL/He3qw==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/linux-arm64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.9.tgz", - "integrity": "sha512-PiPblfe1BjK7WDAKR1Cr9O7VVPqVNpwFcPWgfn4xu0eMemzRp442hXyzF/fSwgrufI66FpHOEJk0yYdPInsmyQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/linux-ia32": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.9.tgz", - "integrity": "sha512-f37i/0zE0MjDxijkPSQw1CO/7C27Eojqb+r3BbHVxMLkj8GCa78TrBZzvPyA/FNLUMzP3eyHCVkAopkKVja+6Q==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/linux-loong64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.9.tgz", - "integrity": "sha512-t6mN147pUIf3t6wUt3FeumoOTPfmv9Cc6DQlsVBpB7eCpLOqQDyWBP1ymXn1lDw4fNUSb/gBcKAmvTP49oIkaA==", - "cpu": [ - "loong64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/linux-mips64el": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.9.tgz", - "integrity": "sha512-jg9fujJTNTQBuDXdmAg1eeJUL4Jds7BklOTkkH80ZgQIoCTdQrDaHYgbFZyeTq8zbY+axgptncko3v9p5hLZtw==", - "cpu": [ - "mips64el" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/linux-ppc64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.9.tgz", - "integrity": "sha512-tkV0xUX0pUUgY4ha7z5BbDS85uI7ABw3V1d0RNTii7E9lbmV8Z37Pup2tsLV46SQWzjOeyDi1Q7Wx2+QM8WaCQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/linux-riscv64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.9.tgz", - "integrity": "sha512-DfLp8dj91cufgPZDXr9p3FoR++m3ZJ6uIXsXrIvJdOjXVREtXuQCjfMfvmc3LScAVmLjcfloyVtpn43D56JFHg==", - "cpu": [ - "riscv64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/linux-s390x": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.9.tgz", - "integrity": "sha512-zHbglfEdC88KMgCWpOl/zc6dDYJvWGLiUtmPRsr1OgCViu3z5GncvNVdf+6/56O2Ca8jUU+t1BW261V6kp8qdw==", - "cpu": [ - "s390x" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/linux-x64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.9.tgz", - "integrity": "sha512-JUjpystGFFmNrEHQnIVG8hKwvA2DN5o7RqiO1CVX8EN/F/gkCjkUMgVn6hzScpwnJtl2mPR6I9XV1oW8k9O+0A==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/netbsd-x64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.9.tgz", - "integrity": "sha512-GThgZPAwOBOsheA2RUlW5UeroRfESwMq/guy8uEe3wJlAOjpOXuSevLRd70NZ37ZrpO6RHGHgEHvPg1h3S1Jug==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/openbsd-x64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.9.tgz", - "integrity": "sha512-Ki6PlzppaFVbLnD8PtlVQfsYw4S9n3eQl87cqgeIw+O3sRr9IghpfSKY62mggdt1yCSZ8QWvTZ9jo9fjDSg9uw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/sunos-x64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.9.tgz", - "integrity": "sha512-MLHj7k9hWh4y1ddkBpvRj2b9NCBhfgBt3VpWbHQnXRedVun/hC7sIyTGDGTfsGuXo4ebik2+3ShjcPbhtFwWDw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/win32-arm64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.9.tgz", - "integrity": "sha512-GQoa6OrQ8G08guMFgeXPH7yE/8Dt0IfOGWJSfSH4uafwdC7rWwrfE6P9N8AtPGIjUzdo2+7bN8Xo3qC578olhg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/win32-ia32": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.9.tgz", - "integrity": "sha512-UOozV7Ntykvr5tSOlGCrqU3NBr3d8JqPes0QWN2WOXfvkWVGRajC+Ym0/Wj88fUgecUCLDdJPDF0Nna2UK3Qtg==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/tsup/node_modules/@esbuild/win32-x64": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.9.tgz", - "integrity": "sha512-oxoQgglOP7RH6iasDrhY+R/3cHrfwIDvRlT4CGChflq6twk8iENeVvMJjmvBb94Ik1Z+93iGO27err7w6l54GQ==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" } }, "node_modules/tsup/node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, + "license": "MIT", "dependencies": { - "ms": "2.1.2" + "ms": "^2.1.3" }, "engines": { "node": ">=6.0" @@ -33412,94 +32789,61 @@ } } }, - "node_modules/tsup/node_modules/esbuild": { - "version": "0.19.9", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.9.tgz", - "integrity": "sha512-U9CHtKSy+EpPsEBa+/A2gMs/h3ylBC0H0KSqIg7tpztHerLi6nrrcoUJAkNCEPumx8yJ+Byic4BVwHgRbN0TBg==", + "node_modules/tsup/node_modules/postcss-load-config": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", + "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", "dev": true, - "hasInstallScript": true, - "bin": { - "esbuild": "bin/esbuild" + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.1.1" }, "engines": { - "node": ">=12" + "node": ">= 18" }, - "optionalDependencies": { - "@esbuild/android-arm": "0.19.9", - "@esbuild/android-arm64": "0.19.9", - "@esbuild/android-x64": "0.19.9", - "@esbuild/darwin-arm64": "0.19.9", - "@esbuild/darwin-x64": "0.19.9", - "@esbuild/freebsd-arm64": "0.19.9", - "@esbuild/freebsd-x64": "0.19.9", - "@esbuild/linux-arm": "0.19.9", - "@esbuild/linux-arm64": "0.19.9", - "@esbuild/linux-ia32": "0.19.9", - "@esbuild/linux-loong64": "0.19.9", - "@esbuild/linux-mips64el": "0.19.9", - "@esbuild/linux-ppc64": "0.19.9", - "@esbuild/linux-riscv64": "0.19.9", - "@esbuild/linux-s390x": "0.19.9", - "@esbuild/linux-x64": "0.19.9", - "@esbuild/netbsd-x64": "0.19.9", - "@esbuild/openbsd-x64": "0.19.9", - "@esbuild/sunos-x64": "0.19.9", - "@esbuild/win32-arm64": "0.19.9", - "@esbuild/win32-ia32": "0.19.9", - "@esbuild/win32-x64": "0.19.9" + "peerDependencies": { + "jiti": ">=1.21.0", + "postcss": ">=8.0.9", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + }, + "postcss": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } } }, - "node_modules/tsup/node_modules/execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "node_modules/tsup/node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", "dev": true, - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - }, + "license": "MIT", "engines": { - "node": ">=10" + "node": ">= 14.18.0" }, "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, - "node_modules/tsup/node_modules/is-stream": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/tsup/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true - }, - "node_modules/tsup/node_modules/npm-run-path": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "dev": true, - "dependencies": { - "path-key": "^3.0.0" - }, - "engines": { - "node": ">=8" + "type": "individual", + "url": "https://paulmillr.com/funding/" } }, "node_modules/tsup/node_modules/resolve-from": { @@ -33523,15 +32867,6 @@ "node": ">= 8" } }, - "node_modules/tsup/node_modules/strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dev": true, - "engines": { - "node": ">=6" - } - }, "node_modules/tsup/node_modules/tr46": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/tr46/-/tr46-1.0.1.tgz", @@ -33559,13 +32894,14 @@ } }, "node_modules/tsx": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.4.0.tgz", - "integrity": "sha512-4fwcEjRUxW20ciSaMB8zkpGwCPxuRGnadDuj/pBk5S9uT29zvWz15PK36GrKJo45mSJomDxVejZ73c6lr3811Q==", + "version": "4.20.6", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.20.6.tgz", + "integrity": "sha512-ytQKuwgmrrkDTFP4LjR0ToE2nqgy886GpvRSpU0JAnrdBYppuY5rLkRUYPU1yCryb24SsKBTL/hlDQAEFVwtZg==", "dev": true, + "license": "MIT", "dependencies": { - "esbuild": "~0.18.20", - "get-tsconfig": "^4.7.2" + "esbuild": "~0.25.0", + "get-tsconfig": "^4.7.5" }, "bin": { "tsx": "dist/cli.mjs" @@ -33646,15 +32982,6 @@ "node": ">= 0.8.0" } }, - "node_modules/type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/type-fest": { "version": "0.20.2", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", @@ -33767,10 +33094,11 @@ } }, "node_modules/ufo": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.3.2.tgz", - "integrity": "sha512-o+ORpgGwaYQXgqGDwd+hkS4PuZ3QnmqMMxRuajK/a38L6fTpcE5GPIfrf+L/KemFzfUpeUQc1rRS1iDBozvnFA==", - "dev": true + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.6.1.tgz", + "integrity": "sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA==", + "dev": true, + "license": "MIT" }, "node_modules/uglify-js": { "version": "3.17.4", @@ -34155,22 +33483,100 @@ "node": ">=0.6.0" } }, - "node_modules/vite": { - "version": "5.4.9", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.9.tgz", - "integrity": "sha512-20OVpJHh0PAM0oSOELa5GaZNWeDjcAvQjGXy2Uyr+Tp+/D2/Hdz6NLgpJLsarPTA2QJ6v8mX2P1ZfbsSKvdMkg==", + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", "dev": true, "license": "MIT", "dependencies": { - "esbuild": "^0.21.3", - "postcss": "^8.4.43", - "rollup": "^4.20.0" + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vite-node/node_modules/@types/node": { + "version": "24.9.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.9.1.tgz", + "integrity": "sha512-QoiaXANRkSXK6p0Duvt56W208du4P9Uye9hWLWgGMDTEoKPhuenzNcC4vGUmrNkiOKTlIrBoyNQYNpSwfEZXSg==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/vite-node/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/vite-node/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/vite-node/node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/vite-node/node_modules/vite": { + "version": "7.1.12", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.12.tgz", + "integrity": "sha512-ZWyE8YXEXqJrrSLvYgrRP7p62OziLW7xI5HYGWFzOvupfAlrLvURSzv/FyGyy0eidogEM3ujU+kUG1zuHgb6Ug==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" }, "bin": { "vite": "bin/vite.js" }, "engines": { - "node": "^18.0.0 || >=20.0.0" + "node": "^20.19.0 || >=22.12.0" }, "funding": { "url": "https://github.com/vitejs/vite?sponsor=1" @@ -34179,19 +33585,25 @@ "fsevents": "~2.3.3" }, "peerDependencies": { - "@types/node": "^18.0.0 || >=20.0.0", - "less": "*", + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", "lightningcss": "^1.21.0", - "sass": "*", - "sass-embedded": "*", - "stylus": "*", - "sugarss": "*", - "terser": "^5.4.0" + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" }, "peerDependenciesMeta": { "@types/node": { "optional": true }, + "jiti": { + "optional": true + }, "less": { "optional": true }, @@ -34212,509 +33624,61 @@ }, "terser": { "optional": true - } - } - }, - "node_modules/vite-node": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-1.2.2.tgz", - "integrity": "sha512-1as4rDTgVWJO3n1uHmUYqq7nsFgINQ9u+mRcXpjeOMJUmviqNKjcZB7UfRZrlM7MjYXMKpuWp5oGkjaFLnjawg==", - "dev": true, - "dependencies": { - "cac": "^6.7.14", - "debug": "^4.3.4", - "pathe": "^1.1.1", - "picocolors": "^1.0.0", - "vite": "^5.0.0" - }, - "bin": { - "vite-node": "vite-node.mjs" - }, - "engines": { - "node": "^18.0.0 || >=20.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/vite-node/node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dev": true, - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { + }, + "tsx": { + "optional": true + }, + "yaml": { "optional": true } } }, - "node_modules/vite-node/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true - }, - "node_modules/vite/node_modules/@esbuild/android-arm": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", - "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/android-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", - "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/android-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", - "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/darwin-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", - "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/darwin-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", - "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/freebsd-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", - "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/freebsd-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", - "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/linux-arm": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", - "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/linux-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", - "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/linux-ia32": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", - "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/linux-loong64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", - "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/linux-mips64el": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", - "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/linux-ppc64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", - "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/linux-riscv64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", - "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/linux-s390x": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", - "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/linux-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", - "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/netbsd-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", - "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/openbsd-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", - "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/sunos-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", - "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/win32-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", - "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/win32-ia32": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", - "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/@esbuild/win32-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", - "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/vite/node_modules/esbuild": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", - "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=12" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.21.5", - "@esbuild/android-arm": "0.21.5", - "@esbuild/android-arm64": "0.21.5", - "@esbuild/android-x64": "0.21.5", - "@esbuild/darwin-arm64": "0.21.5", - "@esbuild/darwin-x64": "0.21.5", - "@esbuild/freebsd-arm64": "0.21.5", - "@esbuild/freebsd-x64": "0.21.5", - "@esbuild/linux-arm": "0.21.5", - "@esbuild/linux-arm64": "0.21.5", - "@esbuild/linux-ia32": "0.21.5", - "@esbuild/linux-loong64": "0.21.5", - "@esbuild/linux-mips64el": "0.21.5", - "@esbuild/linux-ppc64": "0.21.5", - "@esbuild/linux-riscv64": "0.21.5", - "@esbuild/linux-s390x": "0.21.5", - "@esbuild/linux-x64": "0.21.5", - "@esbuild/netbsd-x64": "0.21.5", - "@esbuild/openbsd-x64": "0.21.5", - "@esbuild/sunos-x64": "0.21.5", - "@esbuild/win32-arm64": "0.21.5", - "@esbuild/win32-ia32": "0.21.5", - "@esbuild/win32-x64": "0.21.5" - } - }, "node_modules/vitest": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-1.2.2.tgz", - "integrity": "sha512-d5Ouvrnms3GD9USIK36KG8OZ5bEvKEkITFtnGv56HFaSlbItJuYr7hv2Lkn903+AvRAgSixiamozUVfORUekjw==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz", + "integrity": "sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==", "dev": true, + "license": "MIT", "dependencies": { - "@vitest/expect": "1.2.2", - "@vitest/runner": "1.2.2", - "@vitest/snapshot": "1.2.2", - "@vitest/spy": "1.2.2", - "@vitest/utils": "1.2.2", - "acorn-walk": "^8.3.2", - "cac": "^6.7.14", - "chai": "^4.3.10", - "debug": "^4.3.4", - "execa": "^8.0.1", - "local-pkg": "^0.5.0", - "magic-string": "^0.30.5", - "pathe": "^1.1.1", - "picocolors": "^1.0.0", - "std-env": "^3.5.0", - "strip-literal": "^1.3.0", - "tinybench": "^2.5.1", - "tinypool": "^0.8.2", - "vite": "^5.0.0", - "vite-node": "1.2.2", - "why-is-node-running": "^2.2.2" + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.4", + "@vitest/mocker": "3.2.4", + "@vitest/pretty-format": "^3.2.4", + "@vitest/runner": "3.2.4", + "@vitest/snapshot": "3.2.4", + "@vitest/spy": "3.2.4", + "@vitest/utils": "3.2.4", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" }, "bin": { "vitest": "vitest.mjs" }, "engines": { - "node": "^18.0.0 || >=20.0.0" + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" }, "funding": { "url": "https://opencollective.com/vitest" }, "peerDependencies": { "@edge-runtime/vm": "*", - "@types/node": "^18.0.0 || >=20.0.0", - "@vitest/browser": "^1.0.0", - "@vitest/ui": "^1.0.0", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.4", + "@vitest/ui": "3.2.4", "happy-dom": "*", "jsdom": "*" }, @@ -34722,6 +33686,9 @@ "@edge-runtime/vm": { "optional": true }, + "@types/debug": { + "optional": true + }, "@types/node": { "optional": true }, @@ -34739,13 +33706,41 @@ } } }, - "node_modules/vitest/node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "node_modules/vitest/node_modules/@vitest/mocker": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.4.tgz", + "integrity": "sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==", "dev": true, + "license": "MIT", "dependencies": { - "ms": "2.1.2" + "@vitest/spy": "3.2.4", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/vitest/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" }, "engines": { "node": ">=6.0" @@ -34756,93 +33751,92 @@ } } }, - "node_modules/vitest/node_modules/execa": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", - "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==", - "dev": true, - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^8.0.1", - "human-signals": "^5.0.0", - "is-stream": "^3.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^5.1.0", - "onetime": "^6.0.0", - "signal-exit": "^4.1.0", - "strip-final-newline": "^3.0.0" - }, - "engines": { - "node": ">=16.17" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, - "node_modules/vitest/node_modules/get-stream": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", - "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", - "dev": true, - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/vitest/node_modules/human-signals": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", - "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==", - "dev": true, - "engines": { - "node": ">=16.17.0" - } - }, - "node_modules/vitest/node_modules/mimic-fn": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", - "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", + "node_modules/vitest/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=12" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/sponsors/jonschlinkert" } }, - "node_modules/vitest/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true - }, - "node_modules/vitest/node_modules/onetime": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", - "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", + "node_modules/vitest/node_modules/vite": { + "version": "7.1.12", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.12.tgz", + "integrity": "sha512-ZWyE8YXEXqJrrSLvYgrRP7p62OziLW7xI5HYGWFzOvupfAlrLvURSzv/FyGyy0eidogEM3ujU+kUG1zuHgb6Ug==", "dev": true, + "license": "MIT", "dependencies": { - "mimic-fn": "^4.0.0" + "esbuild": "^0.25.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" }, "engines": { - "node": ">=12" + "node": "^20.19.0 || >=22.12.0" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/vitest/node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "dev": true, - "engines": { - "node": ">=14" + "url": "https://github.com/vitejs/vite?sponsor=1" }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } } }, "node_modules/w3c-xmlserializer": { @@ -34944,13 +33938,6 @@ "node": ">=10.13.0" } }, - "node_modules/webpack/node_modules/@types/estree": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", - "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", - "dev": true, - "license": "MIT" - }, "node_modules/webpack/node_modules/eslint-scope": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", @@ -35061,10 +34048,11 @@ } }, "node_modules/why-is-node-running": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.2.2.tgz", - "integrity": "sha512-6tSwToZxTOcotxHeA+qGCq1mVzKR3CwcJGmVcY+QE8SHy6TnpFnh8PAvPNHYr7EcuVeG0QSMxtYCuO1ta/G/oA==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", "dev": true, + "license": "MIT", "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" @@ -35455,11 +34443,15 @@ "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" }, "node_modules/yaml": { - "version": "2.3.4", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.3.4.tgz", - "integrity": "sha512-8aAvwVUSHpfEqTQ4w/KMlf3HcRdt50E5ODIQJBw1fQ5RL34xabzxtUlzTXVqc4rkZsPbvrXKWnABCD7kWSmocA==", + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz", + "integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, "engines": { - "node": ">= 14" + "node": ">= 14.6" } }, "node_modules/yargs": { diff --git a/backend/package.json b/backend/package.json index 17be524f2..9bcd63cf1 100644 --- a/backend/package.json +++ b/backend/package.json @@ -40,10 +40,10 @@ "type:check": "node --max-old-space-size=8192 ./node_modules/.bin/tsc --noEmit", "lint:fix": "node --max-old-space-size=8192 ./node_modules/.bin/eslint --fix --ext js,ts ./src", "lint": "node --max-old-space-size=8192 ./node_modules/.bin/eslint 'src/**/*.ts'", - "test:unit": "vitest run -c vitest.unit.config.ts", - "test:e2e": "vitest run -c vitest.e2e.config.ts --bail=1", - "test:e2e-watch": "vitest -c vitest.e2e.config.ts --bail=1", - "test:e2e-coverage": "vitest run --coverage -c vitest.e2e.config.ts", + "test:unit": "vitest run -c vitest.unit.config.mts", + "test:e2e": "vitest run -c vitest.e2e.config.mts --bail=1", + "test:e2e-watch": "vitest -c vitest.e2e.config.mts --bail=1", + "test:e2e-coverage": "vitest run --coverage -c vitest.e2e.config.mts", "generate:component": "tsx ./scripts/create-backend-file.ts", "generate:schema": "tsx ./scripts/generate-schema-types.ts && eslint --fix --ext ts ./src/db/schemas", "auditlog-migration:latest": "node ./dist/db/rename-migrations-to-mjs.mjs && knex --knexfile ./dist/db/auditlog-knexfile.mjs --client pg migrate:latest", @@ -98,7 +98,7 @@ "@types/jsrp": "^0.2.6", "@types/libsodium-wrappers": "^0.7.13", "@types/lodash.isequal": "^4.5.8", - "@types/node": "^20.17.30", + "@types/node": "^20.19.0", "@types/nodemailer": "^6.4.14", "@types/passport-google-oauth20": "^2.0.14", "@types/pg": "^8.10.9", @@ -130,10 +130,10 @@ "ts-node": "^10.9.2", "tsc-alias": "^1.8.8", "tsconfig-paths": "^4.2.0", - "tsup": "^8.0.1", + "tsup": "^8.5.0", "tsx": "^4.4.0", "typescript": "^5.3.2", - "vitest": "^1.2.2" + "vitest": "^3.0.6" }, "dependencies": { "@aws-sdk/client-elasticache": "^3.637.0", diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts index 273e6d982..a2bc332f8 100644 --- a/backend/src/@types/fastify.d.ts +++ b/backend/src/@types/fastify.d.ts @@ -135,9 +135,23 @@ import { TWorkflowIntegrationServiceFactory } from "@app/services/workflow-integ declare module "@fastify/request-context" { interface RequestContextData { reqId: string; + ip?: string; + userAgent?: string; orgId?: string; + orgName?: string; + userAuthInfo?: { + userId: string; + email: string; + }; + projectDetails?: { + id: string; + name: string; + slug: string; + }; identityAuthInfo?: { identityId: string; + identityName: string; + authMethod: string; oidc?: { claims: Record; }; diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts index bbc27ebc1..7ff31ed99 100644 --- a/backend/src/@types/knex.d.ts +++ b/backend/src/@types/knex.d.ts @@ -62,6 +62,9 @@ import { TCertificateSecretsUpdate, TCertificatesInsert, TCertificatesUpdate, + TCertificateSyncs, + TCertificateSyncsInsert, + TCertificateSyncsUpdate, TCertificateTemplateEstConfigs, TCertificateTemplateEstConfigsInsert, TCertificateTemplateEstConfigsUpdate, @@ -738,6 +741,11 @@ declare module "knex/types/tables" { TPkiSubscribersUpdate >; [TableName.PkiSync]: KnexOriginal.CompositeTableType; + [TableName.CertificateSync]: KnexOriginal.CompositeTableType< + TCertificateSyncs, + TCertificateSyncsInsert, + TCertificateSyncsUpdate + >; [TableName.UserGroupMembership]: KnexOriginal.CompositeTableType< TUserGroupMembership, TUserGroupMembershipInsert, diff --git a/backend/src/db/migrations/20251018061215_sub-org.ts b/backend/src/db/migrations/20251018061215_sub-org.ts index 6378fa66a..089aeef90 100644 --- a/backend/src/db/migrations/20251018061215_sub-org.ts +++ b/backend/src/db/migrations/20251018061215_sub-org.ts @@ -2,7 +2,7 @@ import { Knex } from "knex"; import { dropConstraintIfExists } from "@app/db/migrations/utils/dropConstraintIfExists"; -import { AccessScope, TableName } from "../schemas"; +import { TableName } from "../schemas"; export async function up(knex: Knex): Promise { const hasParentOrgId = await knex.schema.hasColumn(TableName.Organization, "parentOrgId"); @@ -18,8 +18,6 @@ export async function up(knex: Knex): Promise { await dropConstraintIfExists(TableName.Organization, "organizations_slug_unique", knex); t.unique(["rootOrgId", "parentOrgId", "slug"]); }); - - // had to switch to raw for null not distinct } const hasIdentityOrgCol = await knex.schema.hasColumn(TableName.Identity, "orgId"); @@ -28,24 +26,6 @@ export async function up(knex: Knex): Promise { t.uuid("orgId"); t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE"); }); - - await knex.raw( - ` - UPDATE ?? AS identity - SET "orgId" = membership."scopeOrgId" - FROM ?? AS membership - WHERE - membership."actorIdentityId" = identity."id" - AND membership."scope" = ? -`, - [TableName.Identity, TableName.Membership, AccessScope.Organization] - ); - - await knex.raw(`DELETE FROM ?? WHERE "orgId" IS NULL`, [TableName.Identity]); - - await knex.schema.alterTable(TableName.Identity, (t) => { - t.uuid("orgId").notNullable().alter(); - }); } } diff --git a/backend/src/db/migrations/20251019061215_sub-org-identity-backfill.ts b/backend/src/db/migrations/20251019061215_sub-org-identity-backfill.ts new file mode 100644 index 000000000..9054a03ee --- /dev/null +++ b/backend/src/db/migrations/20251019061215_sub-org-identity-backfill.ts @@ -0,0 +1,48 @@ +import { Knex } from "knex"; + +import { chunkArray } from "@app/lib/fn"; + +import { AccessScope, TableName } from "../schemas"; + +export async function up(knex: Knex): Promise { + await knex.transaction(async (tx) => { + const hasIdentityOrgCol = await tx.schema.hasColumn(TableName.Identity, "orgId"); + if (hasIdentityOrgCol) { + const identityMemberships = await tx(TableName.Membership) + .where({ + scope: AccessScope.Organization + }) + .whereNotNull("actorIdentityId") + .select("actorIdentityId", "scopeOrgId"); + + const identityToOrgMapping: Record = {}; + identityMemberships.forEach((el) => { + if (el.actorIdentityId) { + identityToOrgMapping[el.actorIdentityId] = el.scopeOrgId; + } + }); + + const batchMemberships = chunkArray(identityMemberships, 500); + for await (const membership of batchMemberships) { + const identityIds = membership.map((el) => el.actorIdentityId).filter(Boolean) as string[]; + if (identityIds.length) { + const identities = await tx(TableName.Identity).whereIn("id", identityIds).select("*"); + await tx(TableName.Identity) + .insert( + identities.map((el) => ({ + ...el, + orgId: identityToOrgMapping[el.id] + })) + ) + .onConflict("id") + .merge(); + } + } + } + }); +} + +export async function down(): Promise {} + +const config = { transaction: false }; +export { config }; diff --git a/backend/src/db/migrations/20251021112356_add-certificate-auto-renewal.ts b/backend/src/db/migrations/20251021112356_add-certificate-auto-renewal.ts new file mode 100644 index 000000000..583ffec90 --- /dev/null +++ b/backend/src/db/migrations/20251021112356_add-certificate-auto-renewal.ts @@ -0,0 +1,51 @@ +import { Knex } from "knex"; + +import { TableName } from "../schemas"; + +export async function up(knex: Knex): Promise { + if (await knex.schema.hasColumn(TableName.PkiApiEnrollmentConfig, "autoRenewDays")) { + await knex.schema.alterTable(TableName.PkiApiEnrollmentConfig, (t) => { + t.renameColumn("autoRenewDays", "renewBeforeDays"); + }); + } + + if (!(await knex.schema.hasColumn(TableName.Certificate, "renewBeforeDays"))) { + await knex.schema.alterTable(TableName.Certificate, (t) => { + t.integer("renewBeforeDays").nullable(); + t.uuid("renewedFromCertificateId").nullable(); + t.uuid("renewedByCertificateId").nullable(); + t.text("renewalError").nullable(); + t.string("keyAlgorithm").nullable(); + t.string("signatureAlgorithm").nullable(); + t.foreign("renewedFromCertificateId").references("id").inTable(TableName.Certificate).onDelete("SET NULL"); + t.foreign("renewedByCertificateId").references("id").inTable(TableName.Certificate).onDelete("SET NULL"); + t.index("renewedFromCertificateId"); + t.index("renewedByCertificateId"); + t.index("renewBeforeDays"); + }); + } +} + +export async function down(knex: Knex): Promise { + if (await knex.schema.hasColumn(TableName.Certificate, "renewBeforeDays")) { + await knex.schema.alterTable(TableName.Certificate, (t) => { + t.dropForeign(["renewedFromCertificateId"]); + t.dropForeign(["renewedByCertificateId"]); + t.dropIndex("renewedFromCertificateId"); + t.dropIndex("renewedByCertificateId"); + t.dropIndex("renewBeforeDays"); + t.dropColumn("renewBeforeDays"); + t.dropColumn("renewedFromCertificateId"); + t.dropColumn("renewedByCertificateId"); + t.dropColumn("renewalError"); + t.dropColumn("keyAlgorithm"); + t.dropColumn("signatureAlgorithm"); + }); + } + + if (await knex.schema.hasColumn(TableName.PkiApiEnrollmentConfig, "renewBeforeDays")) { + await knex.schema.alterTable(TableName.PkiApiEnrollmentConfig, (t) => { + t.renameColumn("renewBeforeDays", "autoRenewDays"); + }); + } +} diff --git a/backend/src/db/migrations/20251021124744_fix-project-deletion-approval-policy-constraint.ts b/backend/src/db/migrations/20251021124744_fix-project-deletion-approval-policy-constraint.ts new file mode 100644 index 000000000..88a38c6d6 --- /dev/null +++ b/backend/src/db/migrations/20251021124744_fix-project-deletion-approval-policy-constraint.ts @@ -0,0 +1,68 @@ +import { Knex } from "knex"; + +import { TableName } from "../schemas"; + +// Fix for 20250722152841_add-policies-environments-table.ts migration. +// 20250722152841_add-policies-environments-table.ts introduced a bug where you can no longer delete a project if it has any approval policy environments. + +export async function up(knex: Knex): Promise { + // Fix SecretApprovalPolicyEnvironment to cascade delete when environment is deleted + // note: this won't actually happen, as we prevent deletion of environments with active approval policies + + // in the old migration it was ON DELETE SET NULL, which doesn't work because envId is not a nullable col + await knex.schema.alterTable(TableName.SecretApprovalPolicyEnvironment, (t) => { + t.dropForeign(["envId"]); + t.foreign("envId").references("id").inTable(TableName.Environment).onDelete("CASCADE"); + }); + + // Fix AccessApprovalPolicyEnvironment to cascade delete when environment is deleted + // note: this won't actually happen, as we prevent deletion of environments with active approval policies + + // in the old migration it was ON DELETE SET NULL, which doesn't work because envId is not a nullable col + await knex.schema.alterTable(TableName.AccessApprovalPolicyEnvironment, (t) => { + t.dropForeign(["envId"]); + t.foreign("envId").references("id").inTable(TableName.Environment).onDelete("CASCADE"); + }); + + // Fix SecretApprovalPolicy to CASCADE instead of SET NULL + + // in the old migration it was ON DELETE SET NULL, which doesn't work because envId is not a nullable col + await knex.schema.alterTable(TableName.SecretApprovalPolicy, (t) => { + t.dropForeign(["envId"]); + t.foreign("envId").references("id").inTable(TableName.Environment).onDelete("CASCADE"); + }); + + // Fix AccessApprovalPolicy to CASCADE instead of SET NULL + + // in the old migration it was ON DELETE SET NULL, which doesn't work because envId is not a nullable col + await knex.schema.alterTable(TableName.AccessApprovalPolicy, (t) => { + t.dropForeign(["envId"]); + t.foreign("envId").references("id").inTable(TableName.Environment).onDelete("CASCADE"); + }); +} + +export async function down(knex: Knex): Promise { + // Revert SecretApprovalPolicyEnvironment + await knex.schema.alterTable(TableName.SecretApprovalPolicyEnvironment, (t) => { + t.dropForeign(["envId"]); + t.foreign("envId").references("id").inTable(TableName.Environment); + }); + + // Revert AccessApprovalPolicyEnvironment + await knex.schema.alterTable(TableName.AccessApprovalPolicyEnvironment, (t) => { + t.dropForeign(["envId"]); + t.foreign("envId").references("id").inTable(TableName.Environment); + }); + + // Revert SecretApprovalPolicy back to SET NULL + await knex.schema.alterTable(TableName.SecretApprovalPolicy, (t) => { + t.dropForeign(["envId"]); + t.foreign("envId").references("id").inTable(TableName.Environment).onDelete("SET NULL"); + }); + + // Revert AccessApprovalPolicy back to SET NULL + await knex.schema.alterTable(TableName.AccessApprovalPolicy, (t) => { + t.dropForeign(["envId"]); + t.foreign("envId").references("id").inTable(TableName.Environment).onDelete("SET NULL"); + }); +} diff --git a/backend/src/db/migrations/20251023123213_block-duplicate-sync-destinations-setting.ts b/backend/src/db/migrations/20251023123213_block-duplicate-sync-destinations-setting.ts new file mode 100644 index 000000000..7675eb3e1 --- /dev/null +++ b/backend/src/db/migrations/20251023123213_block-duplicate-sync-destinations-setting.ts @@ -0,0 +1,27 @@ +import { Knex } from "knex"; + +import { TableName } from "../schemas"; + +export async function up(knex: Knex): Promise { + const hasOrgBlockDuplicateColumn = await knex.schema.hasColumn( + TableName.Organization, + "blockDuplicateSecretSyncDestinations" + ); + if (!hasOrgBlockDuplicateColumn) { + await knex.schema.table(TableName.Organization, (table) => { + table.boolean("blockDuplicateSecretSyncDestinations").notNullable().defaultTo(false); + }); + } +} + +export async function down(knex: Knex): Promise { + const hasOrgBlockDuplicateColumn = await knex.schema.hasColumn( + TableName.Organization, + "blockDuplicateSecretSyncDestinations" + ); + if (hasOrgBlockDuplicateColumn) { + await knex.schema.table(TableName.Organization, (table) => { + table.dropColumn("blockDuplicateSecretSyncDestinations"); + }); + } +} diff --git a/backend/src/db/migrations/20251028064623_pam-account-rotation-status.ts b/backend/src/db/migrations/20251028064623_pam-account-rotation-status.ts new file mode 100644 index 000000000..b3ad123e8 --- /dev/null +++ b/backend/src/db/migrations/20251028064623_pam-account-rotation-status.ts @@ -0,0 +1,29 @@ +import { Knex } from "knex"; + +import { TableName } from "../schemas"; + +export async function up(knex: Knex): Promise { + if (!(await knex.schema.hasColumn(TableName.PamAccount, "rotationStatus"))) { + await knex.schema.alterTable(TableName.PamAccount, (t) => { + t.string("rotationStatus").nullable(); + }); + } + if (!(await knex.schema.hasColumn(TableName.PamAccount, "encryptedLastRotationMessage"))) { + await knex.schema.alterTable(TableName.PamAccount, (t) => { + t.binary("encryptedLastRotationMessage").nullable(); + }); + } +} + +export async function down(knex: Knex): Promise { + if (await knex.schema.hasColumn(TableName.PamAccount, "rotationStatus")) { + await knex.schema.alterTable(TableName.PamAccount, (t) => { + t.dropColumn("rotationStatus"); + }); + } + if (await knex.schema.hasColumn(TableName.PamAccount, "encryptedLastRotationMessage")) { + await knex.schema.alterTable(TableName.PamAccount, (t) => { + t.dropColumn("encryptedLastRotationMessage"); + }); + } +} diff --git a/backend/src/db/migrations/20251028120000_add-certificate-sync-table.ts b/backend/src/db/migrations/20251028120000_add-certificate-sync-table.ts new file mode 100644 index 000000000..14904e5bd --- /dev/null +++ b/backend/src/db/migrations/20251028120000_add-certificate-sync-table.ts @@ -0,0 +1,35 @@ +import { Knex } from "knex"; + +import { TableName } from "@app/db/schemas"; +import { createOnUpdateTrigger, dropOnUpdateTrigger } from "@app/db/utils"; +import { CertificateSyncStatus } from "@app/services/certificate-sync/certificate-sync-enums"; + +export async function up(knex: Knex): Promise { + if (!(await knex.schema.hasTable(TableName.CertificateSync))) { + await knex.schema.createTable(TableName.CertificateSync, (t) => { + t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid()); + t.uuid("pkiSyncId").notNullable(); + t.foreign("pkiSyncId").references("id").inTable(TableName.PkiSync).onDelete("CASCADE"); + t.uuid("certificateId").notNullable(); + t.foreign("certificateId").references("id").inTable(TableName.Certificate).onDelete("CASCADE"); + t.string("syncStatus").defaultTo(CertificateSyncStatus.Pending); + t.text("lastSyncMessage"); + t.datetime("lastSyncedAt"); + t.timestamps(true, true, true); + + // Ensure unique combination of pki sync and certificate + t.unique(["pkiSyncId", "certificateId"]); + + t.index("pkiSyncId"); + t.index("certificateId"); + t.index("syncStatus"); + }); + + await createOnUpdateTrigger(knex, TableName.CertificateSync); + } +} + +export async function down(knex: Knex): Promise { + await knex.schema.dropTableIfExists(TableName.CertificateSync); + await dropOnUpdateTrigger(knex, TableName.CertificateSync); +} diff --git a/backend/src/db/migrations/20251028155708_identity-access-token-remove-fk-for-identity-id.ts b/backend/src/db/migrations/20251028155708_identity-access-token-remove-fk-for-identity-id.ts new file mode 100644 index 000000000..0974f39c2 --- /dev/null +++ b/backend/src/db/migrations/20251028155708_identity-access-token-remove-fk-for-identity-id.ts @@ -0,0 +1,22 @@ +import { Knex } from "knex"; + +import { TableName } from "../schemas"; + +export async function up(knex: Knex): Promise { + await knex.transaction(async (tx) => { + await tx.schema.alterTable(TableName.IdentityAccessToken, (table) => { + table.dropForeign("identityId"); + }); + }); +} + +export async function down(knex: Knex): Promise { + await knex.transaction(async (tx) => { + await tx.schema.alterTable(TableName.IdentityAccessToken, (table) => { + table.foreign("identityId").references("id").inTable(TableName.Identity); + }); + }); +} + +const config = { transaction: false }; +export { config }; diff --git a/backend/src/db/migrations/20251028160921_delete-no-org-identities.ts b/backend/src/db/migrations/20251028160921_delete-no-org-identities.ts new file mode 100644 index 000000000..0eb0e7ae0 --- /dev/null +++ b/backend/src/db/migrations/20251028160921_delete-no-org-identities.ts @@ -0,0 +1,30 @@ +import { Knex } from "knex"; + +import { TableName } from "../schemas"; + +const MIGRATION_TIMEOUT = 30 * 60 * 1000; // 30 minutes + +export async function up(knex: Knex): Promise { + const result = await knex.raw("SHOW statement_timeout"); + const originalTimeout = result.rows[0].statement_timeout; + + await knex.transaction(async (tx) => { + try { + await tx.raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`); + const hasIdentityOrgCol = await tx.schema.hasColumn(TableName.Identity, "orgId"); + if (hasIdentityOrgCol) { + await tx(TableName.Identity).whereNull("orgId").delete(); + await tx.schema.alterTable(TableName.Identity, (t) => { + t.uuid("orgId").notNullable().alter(); + }); + } + } finally { + await tx.raw(`SET statement_timeout = '${originalTimeout}'`); + } + }); +} + +export async function down(): Promise {} + +const config = { transaction: false }; +export { config }; diff --git a/backend/src/db/migrations/20251031044512_add-certificate-sync-external-identifier.ts b/backend/src/db/migrations/20251031044512_add-certificate-sync-external-identifier.ts new file mode 100644 index 000000000..69e15795a --- /dev/null +++ b/backend/src/db/migrations/20251031044512_add-certificate-sync-external-identifier.ts @@ -0,0 +1,21 @@ +import { Knex } from "knex"; + +import { TableName } from "../schemas"; + +export async function up(knex: Knex): Promise { + if (!(await knex.schema.hasColumn(TableName.CertificateSync, "externalIdentifier"))) { + await knex.schema.alterTable(TableName.CertificateSync, (t) => { + t.text("externalIdentifier").nullable(); + t.index("externalIdentifier"); + }); + } +} + +export async function down(knex: Knex): Promise { + if (await knex.schema.hasColumn(TableName.CertificateSync, "externalIdentifier")) { + await knex.schema.alterTable(TableName.CertificateSync, (t) => { + t.dropIndex("externalIdentifier"); + t.dropColumn("externalIdentifier"); + }); + } +} diff --git a/backend/src/db/schemas/certificate-syncs.ts b/backend/src/db/schemas/certificate-syncs.ts new file mode 100644 index 000000000..241684db2 --- /dev/null +++ b/backend/src/db/schemas/certificate-syncs.ts @@ -0,0 +1,24 @@ +// Code generated by automation script, DO NOT EDIT. +// Automated by pulling database and generating zod schema +// To update. Just run npm run generate:schema +// Written by akhilmhdh. + +import { z } from "zod"; + +import { TImmutableDBKeys } from "./models"; + +export const CertificateSyncsSchema = z.object({ + id: z.string().uuid(), + pkiSyncId: z.string().uuid(), + certificateId: z.string().uuid(), + syncStatus: z.string().default("pending").nullable().optional(), + lastSyncMessage: z.string().nullable().optional(), + lastSyncedAt: z.date().nullable().optional(), + createdAt: z.date(), + updatedAt: z.date(), + externalIdentifier: z.string().nullable().optional() +}); + +export type TCertificateSyncs = z.infer; +export type TCertificateSyncsInsert = Omit, TImmutableDBKeys>; +export type TCertificateSyncsUpdate = Partial, TImmutableDBKeys>>; diff --git a/backend/src/db/schemas/certificates.ts b/backend/src/db/schemas/certificates.ts index 63122f662..8a3ae8f84 100644 --- a/backend/src/db/schemas/certificates.ts +++ b/backend/src/db/schemas/certificates.ts @@ -27,7 +27,13 @@ export const CertificatesSchema = z.object({ extendedKeyUsages: z.string().array().nullable().optional(), projectId: z.string(), pkiSubscriberId: z.string().uuid().nullable().optional(), - profileId: z.string().uuid().nullable().optional() + profileId: z.string().uuid().nullable().optional(), + renewBeforeDays: z.number().nullable().optional(), + renewedFromCertificateId: z.string().uuid().nullable().optional(), + renewedByCertificateId: z.string().uuid().nullable().optional(), + renewalError: z.string().nullable().optional(), + keyAlgorithm: z.string().nullable().optional(), + signatureAlgorithm: z.string().nullable().optional() }); export type TCertificates = z.infer; diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts index 4f0f221ff..fba195746 100644 --- a/backend/src/db/schemas/index.ts +++ b/backend/src/db/schemas/index.ts @@ -17,6 +17,7 @@ export * from "./certificate-authority-crl"; export * from "./certificate-authority-secret"; export * from "./certificate-bodies"; export * from "./certificate-secrets"; +export * from "./certificate-syncs"; export * from "./certificate-template-est-configs"; export * from "./certificate-templates"; export * from "./certificates"; diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts index 86bc929b8..e10c6dcbe 100644 --- a/backend/src/db/schemas/models.ts +++ b/backend/src/db/schemas/models.ts @@ -161,6 +161,7 @@ export enum TableName { AppConnection = "app_connections", SecretSync = "secret_syncs", PkiSync = "pki_syncs", + CertificateSync = "certificate_syncs", KmipClient = "kmip_clients", KmipOrgConfig = "kmip_org_configs", KmipOrgServerCertificates = "kmip_org_server_certificates", diff --git a/backend/src/db/schemas/organizations.ts b/backend/src/db/schemas/organizations.ts index a1c01151f..3cc7fe858 100644 --- a/backend/src/db/schemas/organizations.ts +++ b/backend/src/db/schemas/organizations.ts @@ -40,7 +40,8 @@ export const OrganizationsSchema = z.object({ googleSsoAuthEnforced: z.boolean().default(false), googleSsoAuthLastUsed: z.date().nullable().optional(), parentOrgId: z.string().uuid().nullable().optional(), - rootOrgId: z.string().uuid().nullable().optional() + rootOrgId: z.string().uuid().nullable().optional(), + blockDuplicateSecretSyncDestinations: z.boolean().default(false) }); export type TOrganizations = z.infer; diff --git a/backend/src/db/schemas/pam-accounts.ts b/backend/src/db/schemas/pam-accounts.ts index 7e78e0874..4f097a16d 100644 --- a/backend/src/db/schemas/pam-accounts.ts +++ b/backend/src/db/schemas/pam-accounts.ts @@ -21,7 +21,9 @@ export const PamAccountsSchema = z.object({ updatedAt: z.date(), rotationEnabled: z.boolean().default(false), rotationIntervalSeconds: z.number().nullable().optional(), - lastRotatedAt: z.date().nullable().optional() + lastRotatedAt: z.date().nullable().optional(), + rotationStatus: z.string().nullable().optional(), + encryptedLastRotationMessage: zodBuffer.nullable().optional() }); export type TPamAccounts = z.infer; diff --git a/backend/src/db/schemas/pki-api-enrollment-configs.ts b/backend/src/db/schemas/pki-api-enrollment-configs.ts index 710b0dee4..7a1beccdb 100644 --- a/backend/src/db/schemas/pki-api-enrollment-configs.ts +++ b/backend/src/db/schemas/pki-api-enrollment-configs.ts @@ -10,7 +10,7 @@ import { TImmutableDBKeys } from "./models"; export const PkiApiEnrollmentConfigsSchema = z.object({ id: z.string().uuid(), autoRenew: z.boolean().default(false).nullable().optional(), - autoRenewDays: z.number().nullable().optional(), + renewBeforeDays: z.number().nullable().optional(), createdAt: z.date(), updatedAt: z.date() }); diff --git a/backend/src/ee/routes/v1/dynamic-secret-lease-router.ts b/backend/src/ee/routes/v1/dynamic-secret-lease-router.ts index 26c27d0d3..62911d523 100644 --- a/backend/src/ee/routes/v1/dynamic-secret-lease-router.ts +++ b/backend/src/ee/routes/v1/dynamic-secret-lease-router.ts @@ -2,7 +2,6 @@ import { z } from "zod"; import { DynamicSecretLeasesSchema } from "@app/db/schemas"; import { ApiDocsTags, DYNAMIC_SECRET_LEASES } from "@app/lib/api-docs"; -import { daysToMillisecond } from "@app/lib/dates"; import { removeTrailingSlash } from "@app/lib/fn"; import { ms } from "@app/lib/ms"; import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; @@ -32,8 +31,8 @@ export const registerDynamicSecretLeaseRouter = async (server: FastifyZodProvide const valMs = ms(val); if (valMs < 60 * 1000) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" }); - if (valMs > daysToMillisecond(1)) - ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" }); + if (valMs > ms("10y")) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than 10 years" }); }), path: z.string().trim().default("/").transform(removeTrailingSlash).describe(DYNAMIC_SECRET_LEASES.CREATE.path), environmentSlug: z.string().min(1).describe(DYNAMIC_SECRET_LEASES.CREATE.environmentSlug), @@ -127,8 +126,8 @@ export const registerDynamicSecretLeaseRouter = async (server: FastifyZodProvide const valMs = ms(val); if (valMs < 60 * 1000) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" }); - if (valMs > daysToMillisecond(1)) - ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" }); + if (valMs > ms("10y")) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than 10 years" }); }), projectSlug: z.string().min(1).describe(DYNAMIC_SECRET_LEASES.RENEW.projectSlug), path: z diff --git a/backend/src/ee/routes/v1/dynamic-secret-lease-routers/kubernetes-lease-router.ts b/backend/src/ee/routes/v1/dynamic-secret-lease-routers/kubernetes-lease-router.ts index f2751c635..30de7f08a 100644 --- a/backend/src/ee/routes/v1/dynamic-secret-lease-routers/kubernetes-lease-router.ts +++ b/backend/src/ee/routes/v1/dynamic-secret-lease-routers/kubernetes-lease-router.ts @@ -2,7 +2,6 @@ import { z } from "zod"; import { DynamicSecretLeasesSchema } from "@app/db/schemas"; import { ApiDocsTags, DYNAMIC_SECRET_LEASES } from "@app/lib/api-docs"; -import { daysToMillisecond } from "@app/lib/dates"; import { removeTrailingSlash } from "@app/lib/fn"; import { ms } from "@app/lib/ms"; import { writeLimit } from "@app/server/config/rateLimiter"; @@ -32,8 +31,8 @@ export const registerKubernetesDynamicSecretLeaseRouter = async (server: Fastify const valMs = ms(val); if (valMs < 60 * 1000) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be greater than 1min" }); - if (valMs > daysToMillisecond(1)) - ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" }); + if (valMs > ms("10y")) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than 10 years" }); }), path: z.string().trim().default("/").transform(removeTrailingSlash).describe(DYNAMIC_SECRET_LEASES.CREATE.path), environmentSlug: z.string().min(1).describe(DYNAMIC_SECRET_LEASES.CREATE.environmentSlug), diff --git a/backend/src/ee/routes/v1/dynamic-secret-router.ts b/backend/src/ee/routes/v1/dynamic-secret-router.ts index b1b3cea8e..0e48206dc 100644 --- a/backend/src/ee/routes/v1/dynamic-secret-router.ts +++ b/backend/src/ee/routes/v1/dynamic-secret-router.ts @@ -3,7 +3,6 @@ import { z } from "zod"; import { DynamicSecretLeasesSchema } from "@app/db/schemas"; import { DynamicSecretProviderSchema } from "@app/ee/services/dynamic-secret/providers/models"; import { ApiDocsTags, DYNAMIC_SECRETS } from "@app/lib/api-docs"; -import { daysToMillisecond } from "@app/lib/dates"; import { removeTrailingSlash } from "@app/lib/fn"; import { ms } from "@app/lib/ms"; import { isValidHandleBarTemplate } from "@app/lib/template/validate-handlebars"; @@ -60,8 +59,8 @@ export const registerDynamicSecretRouter = async (server: FastifyZodProvider) => const valMs = ms(val); if (valMs < 60 * 1000) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" }); - if (valMs > daysToMillisecond(1)) - ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" }); + if (valMs > ms("10y")) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than 10 years" }); }), maxTTL: z .string() @@ -72,8 +71,8 @@ export const registerDynamicSecretRouter = async (server: FastifyZodProvider) => const valMs = ms(val); if (valMs < 60 * 1000) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" }); - if (valMs > daysToMillisecond(1)) - ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" }); + if (valMs > ms("10y")) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than 10 years" }); }) .nullable(), path: z.string().describe(DYNAMIC_SECRETS.CREATE.path).trim().default("/").transform(removeTrailingSlash), @@ -130,8 +129,8 @@ export const registerDynamicSecretRouter = async (server: FastifyZodProvider) => const valMs = ms(val); if (valMs < 60 * 1000) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" }); - if (valMs > daysToMillisecond(1)) - ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" }); + if (valMs > ms("10y")) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than 10 years" }); }), maxTTL: z .string() @@ -142,8 +141,8 @@ export const registerDynamicSecretRouter = async (server: FastifyZodProvider) => const valMs = ms(val); if (valMs < 60 * 1000) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" }); - if (valMs > daysToMillisecond(1)) - ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than a day" }); + if (valMs > ms("10y")) + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than 10 years" }); }) .nullable(), newName: z.string().describe(DYNAMIC_SECRETS.UPDATE.newName).optional(), diff --git a/backend/src/ee/routes/v1/kmip-spec-router.ts b/backend/src/ee/routes/v1/kmip-spec-router.ts index 6fcf05d99..1e3305ac7 100644 --- a/backend/src/ee/routes/v1/kmip-spec-router.ts +++ b/backend/src/ee/routes/v1/kmip-spec-router.ts @@ -182,7 +182,8 @@ export const registerKmipSpecRouter = async (server: FastifyZodProvider) => { algorithm: z.string(), isActive: z.boolean(), createdAt: z.date(), - updatedAt: z.date() + updatedAt: z.date(), + kmipMetadata: z.record(z.any()).nullish() }) } }, @@ -384,7 +385,8 @@ export const registerKmipSpecRouter = async (server: FastifyZodProvider) => { isActive: z.boolean(), algorithm: z.string(), createdAt: z.date(), - updatedAt: z.date() + updatedAt: z.date(), + kmipMetadata: z.record(z.any()).nullish() }) .array() }) diff --git a/backend/src/ee/routes/v1/pam-account-routers/index.ts b/backend/src/ee/routes/v1/pam-account-routers/index.ts index 568412c84..60d621467 100644 --- a/backend/src/ee/routes/v1/pam-account-routers/index.ts +++ b/backend/src/ee/routes/v1/pam-account-routers/index.ts @@ -1,3 +1,8 @@ +import { + CreateMySQLAccountSchema, + SanitizedMySQLAccountWithResourceSchema, + UpdateMySQLAccountSchema +} from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas"; import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums"; import { CreatePostgresAccountSchema, @@ -16,5 +21,14 @@ export const PAM_ACCOUNT_REGISTER_ROUTER_MAP: Record { + registerPamResourceEndpoints({ + server, + resourceType: PamResource.MySQL, + accountResponseSchema: SanitizedMySQLAccountWithResourceSchema, + createAccountSchema: CreateMySQLAccountSchema, + updateAccountSchema: UpdateMySQLAccountSchema + }); } }; diff --git a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts index 647f39d8d..d2e0183ff 100644 --- a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts +++ b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import { PamFoldersSchema } from "@app/db/schemas"; import { EventType } from "@app/ee/services/audit-log/audit-log-types"; +import { SanitizedMySQLAccountWithResourceSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas"; import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums"; import { SanitizedPostgresAccountWithResourceSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas"; import { BadRequestError } from "@app/lib/errors"; @@ -10,8 +11,10 @@ import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; import { AuthMode } from "@app/services/auth/auth-type"; -// Use z.union([...]) when more resources are added -const SanitizedAccountSchema = SanitizedPostgresAccountWithResourceSchema; +const SanitizedAccountSchema = z.union([ + SanitizedPostgresAccountWithResourceSchema, + SanitizedMySQLAccountWithResourceSchema +]); export const registerPamAccountRouter = async (server: FastifyZodProvider) => { server.route({ diff --git a/backend/src/ee/routes/v1/pam-resource-routers/index.ts b/backend/src/ee/routes/v1/pam-resource-routers/index.ts index 6b53781ae..821532598 100644 --- a/backend/src/ee/routes/v1/pam-resource-routers/index.ts +++ b/backend/src/ee/routes/v1/pam-resource-routers/index.ts @@ -1,3 +1,8 @@ +import { + CreateMySQLResourceSchema, + MySQLResourceSchema, + UpdateMySQLResourceSchema +} from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas"; import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums"; import { CreatePostgresResourceSchema, @@ -16,5 +21,14 @@ export const PAM_RESOURCE_REGISTER_ROUTER_MAP: Record { + registerPamResourceEndpoints({ + server, + resourceType: PamResource.MySQL, + resourceResponseSchema: MySQLResourceSchema, + createResourceSchema: CreateMySQLResourceSchema, + updateResourceSchema: UpdateMySQLResourceSchema + }); } }; diff --git a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts index d42a73021..6563c86c7 100644 --- a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts +++ b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-router.ts @@ -1,6 +1,10 @@ import { z } from "zod"; import { EventType } from "@app/ee/services/audit-log/audit-log-types"; +import { + MySQLResourceListItemSchema, + SanitizedMySQLResourceSchema +} from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas"; import { PostgresResourceListItemSchema, SanitizedPostgresResourceSchema @@ -9,10 +13,12 @@ import { readLimit } from "@app/server/config/rateLimiter"; import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; import { AuthMode } from "@app/services/auth/auth-type"; -// Use z.union([...]) when more resources are added -const SanitizedResourceSchema = SanitizedPostgresResourceSchema; +const SanitizedResourceSchema = z.union([SanitizedPostgresResourceSchema, SanitizedMySQLResourceSchema]); -const ResourceOptionsSchema = z.discriminatedUnion("resource", [PostgresResourceListItemSchema]); +const ResourceOptionsSchema = z.discriminatedUnion("resource", [ + PostgresResourceListItemSchema, + MySQLResourceListItemSchema +]); export const registerPamResourceRouter = async (server: FastifyZodProvider) => { server.route({ diff --git a/backend/src/ee/routes/v1/pam-session-router.ts b/backend/src/ee/routes/v1/pam-session-router.ts index c353fddfa..5fe10e434 100644 --- a/backend/src/ee/routes/v1/pam-session-router.ts +++ b/backend/src/ee/routes/v1/pam-session-router.ts @@ -2,14 +2,14 @@ import { z } from "zod"; import { PamSessionsSchema } from "@app/db/schemas"; import { EventType } from "@app/ee/services/audit-log/audit-log-types"; +import { MySQLSessionCredentialsSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas"; import { PostgresSessionCredentialsSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas"; import { PamSessionCommandLogSchema, SanitizedSessionSchema } from "@app/ee/services/pam-session/pam-session-schemas"; import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; import { AuthMode } from "@app/services/auth/auth-type"; -// Use z.union([]) once there's multiple -const SessionCredentialsSchema = PostgresSessionCredentialsSchema; +const SessionCredentialsSchema = z.union([PostgresSessionCredentialsSchema, MySQLSessionCredentialsSchema]); export const registerPamSessionRouter = async (server: FastifyZodProvider) => { // Meant to be hit solely by gateway identities diff --git a/backend/src/ee/routes/v1/saml-router.ts b/backend/src/ee/routes/v1/saml-router.ts index 76bff60e8..00add4adc 100644 --- a/backend/src/ee/routes/v1/saml-router.ts +++ b/backend/src/ee/routes/v1/saml-router.ts @@ -7,6 +7,7 @@ // All the any rules are disabled because passport typesense with fastify is really poor import { Authenticator } from "@fastify/passport"; +import { requestContext } from "@fastify/request-context"; import fastifySession from "@fastify/session"; import { MultiSamlStrategy } from "@node-saml/passport-saml"; import { FastifyRequest } from "fastify"; @@ -17,6 +18,7 @@ import { ApiDocsTags, SamlSso } from "@app/lib/api-docs"; import { getConfig } from "@app/lib/config/env"; import { BadRequestError } from "@app/lib/errors"; import { logger } from "@app/lib/logger"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; import { SanitizedSamlConfigSchema } from "@app/server/routes/sanitizedSchema/directory-config"; @@ -102,15 +104,15 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => { }, // eslint-disable-next-line async (req, profile, cb) => { + if (!profile) throw new BadRequestError({ message: "Missing profile" }); + + const email = + profile?.email ?? + // entra sends data in this format + (profile["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/email"] as string) ?? + (profile?.emailAddress as string); // emailRippling is added because in Rippling the field `email` reserved\ + try { - if (!profile) throw new BadRequestError({ message: "Missing profile" }); - - const email = - profile?.email ?? - // entra sends data in this format - (profile["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/email"] as string) ?? - (profile?.emailAddress as string); // emailRippling is added because in Rippling the field `email` reserved\ - const firstName = (profile.firstName ?? // entra sends data in this format profile["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/firstName"]) as string; @@ -144,7 +146,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => { }) .filter((el) => el.key && !["email", "firstName", "lastName"].includes(el.key)); - const { isUserCompleted, providerAuthToken } = await server.services.saml.samlLogin({ + const { isUserCompleted, providerAuthToken, user, organization } = await server.services.saml.samlLogin({ externalId: profile.nameID, email: email.toLowerCase(), firstName, @@ -154,8 +156,32 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => { orgId: (req as unknown as FastifyRequest).ssoConfig?.orgId, metadata: userMetadata }); + + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.user.email": email.toLowerCase(), + "infisical.user.id": user.id, + "infisical.organization.id": organization.id, + "infisical.organization.name": organization.name, + "infisical.auth.method": AuthAttemptAuthMethod.SAML, + "infisical.auth.result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + cb(null, { isUserCompleted, providerAuthToken }); } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.user.email": email.toLowerCase(), + "infisical.auth.method": AuthAttemptAuthMethod.SAML, + "infisical.auth.result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + logger.error(error); cb(error as Error); } diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts index 6ceaa7778..c6ac6ff3b 100644 --- a/backend/src/ee/services/audit-log/audit-log-types.ts +++ b/backend/src/ee/services/audit-log/audit-log-types.ts @@ -340,6 +340,8 @@ export enum EventType { ISSUE_PKI_SUBSCRIBER_CERT = "issue-pki-subscriber-cert", SIGN_PKI_SUBSCRIBER_CERT = "sign-pki-subscriber-cert", AUTOMATED_RENEW_SUBSCRIBER_CERT = "automated-renew-subscriber-cert", + AUTOMATED_RENEW_CERTIFICATE = "automated-renew-certificate", + AUTOMATED_RENEW_CERTIFICATE_FAILED = "automated-renew-certificate-failed", LIST_PKI_SUBSCRIBER_CERTS = "list-pki-subscriber-certs", GET_SUBSCRIBER_ACTIVE_CERT_BUNDLE = "get-subscriber-active-cert-bundle", CREATE_KMS = "create-kms", @@ -367,6 +369,9 @@ export enum EventType { ISSUE_CERTIFICATE_FROM_PROFILE = "issue-certificate-from-profile", SIGN_CERTIFICATE_FROM_PROFILE = "sign-certificate-from-profile", ORDER_CERTIFICATE_FROM_PROFILE = "order-certificate-from-profile", + RENEW_CERTIFICATE = "renew-certificate", + UPDATE_CERTIFICATE_RENEWAL_CONFIG = "update-certificate-renewal-config", + DISABLE_CERTIFICATE_RENEWAL_CONFIG = "disable-certificate-renewal-config", ATTEMPT_CREATE_SLACK_INTEGRATION = "attempt-create-slack-integration", ATTEMPT_REINSTALL_SLACK_INTEGRATION = "attempt-reinstall-slack-integration", GET_PROJECT_SLACK_CONFIG = "get-project-slack-config", @@ -421,6 +426,7 @@ export enum EventType { SECRET_SYNC_REMOVE_SECRETS = "secret-sync-remove-secrets", GET_PKI_SYNCS = "get-pki-syncs", GET_PKI_SYNC = "get-pki-sync", + GET_PKI_SYNC_CERTIFICATES = "get-pki-sync-certificates", CREATE_PKI_SYNC = "create-pki-sync", UPDATE_PKI_SYNC = "update-pki-sync", DELETE_PKI_SYNC = "delete-pki-sync", @@ -2458,6 +2464,29 @@ interface AutomatedRenewPkiSubscriberCert { }; } +interface AutomatedRenewCertificate { + type: EventType.AUTOMATED_RENEW_CERTIFICATE; + metadata: { + certificateId: string; + commonName: string; + profileId: string; + renewBeforeDays: string; + profileName: string; + }; +} + +interface AutomatedRenewCertificateFailed { + type: EventType.AUTOMATED_RENEW_CERTIFICATE_FAILED; + metadata: { + certificateId: string; + commonName: string; + profileId: string; + renewBeforeDays: string; + profileName: string; + error: string; + }; +} + interface SignPkiSubscriberCert { type: EventType.SIGN_PKI_SUBSCRIBER_CERT; metadata: { @@ -2720,6 +2749,16 @@ interface OrderCertificateFromProfile { }; } +interface RenewCertificate { + type: EventType.RENEW_CERTIFICATE; + metadata: { + originalCertificateId: string; + newCertificateId: string; + profileName: string; + commonName: string; + }; +} + interface AttemptCreateSlackIntegration { type: EventType.ATTEMPT_CREATE_SLACK_INTEGRATION; metadata: { @@ -3123,6 +3162,16 @@ interface GetPkiSyncEvent { }; } +interface GetPkiSyncCertificatesEvent { + type: EventType.GET_PKI_SYNC_CERTIFICATES; + metadata: { + syncId: string; + count: number; + certificateIds: string[]; + destination: string; + }; +} + interface CreatePkiSyncEvent { type: EventType.CREATE_PKI_SYNC; metadata: { @@ -4009,6 +4058,23 @@ interface PamResourceDeleteEvent { }; } +interface UpdateCertificateRenewalConfigEvent { + type: EventType.UPDATE_CERTIFICATE_RENEWAL_CONFIG; + metadata: { + certificateId: string; + renewBeforeDays: string; + commonName: string; + }; +} + +interface DisableCertificateRenewalConfigEvent { + type: EventType.DISABLE_CERTIFICATE_RENEWAL_CONFIG; + metadata: { + certificateId: string; + commonName: string; + }; +} + export type Event = | CreateSubOrganizationEvent | UpdateSubOrganizationEvent @@ -4216,6 +4282,7 @@ export type Event = | IssueCertificateFromProfile | SignCertificateFromProfile | OrderCertificateFromProfile + | RenewCertificate | GetAzureAdCsTemplatesEvent | AttemptCreateSlackIntegration | AttemptReinstallSlackIntegration @@ -4273,6 +4340,7 @@ export type Event = | SecretSyncRemoveSecretsEvent | GetPkiSyncsEvent | GetPkiSyncEvent + | GetPkiSyncCertificatesEvent | CreatePkiSyncEvent | UpdatePkiSyncEvent | DeletePkiSyncEvent @@ -4373,4 +4441,8 @@ export type Event = | PamResourceGetEvent | PamResourceCreateEvent | PamResourceUpdateEvent - | PamResourceDeleteEvent; + | PamResourceDeleteEvent + | UpdateCertificateRenewalConfigEvent + | DisableCertificateRenewalConfigEvent + | AutomatedRenewCertificate + | AutomatedRenewCertificateFailed; diff --git a/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts b/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts index d2d683a84..137207659 100644 --- a/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts +++ b/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts @@ -112,7 +112,7 @@ export const dynamicSecretServiceFactory = ({ const existingDynamicSecret = await dynamicSecretDAL.findOne({ name, folderId: folder.id }); if (existingDynamicSecret) - throw new BadRequestError({ message: "Provided dynamic secret already exist under the folder" }); + throw new BadRequestError({ message: "Provided dynamic secret already exists under the folder" }); const selectedProvider = dynamicSecretProviders[provider.type]; const inputs = await selectedProvider.validateProviderInputs(provider.inputs, { projectId }); @@ -265,7 +265,7 @@ export const dynamicSecretServiceFactory = ({ if (newName) { const existingDynamicSecret = await dynamicSecretDAL.findOne({ name: newName, folderId: folder.id }); if (existingDynamicSecret) - throw new BadRequestError({ message: "Provided dynamic secret already exist under the folder" }); + throw new BadRequestError({ message: "Provided dynamic secret already exists under the folder" }); } const { encryptor: secretManagerEncryptor, decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({ diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts index fd4954a00..eaec31e50 100644 --- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts +++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts @@ -25,7 +25,7 @@ import { KmsDataKey } from "@app/services/kms/kms-types"; import { TNotificationServiceFactory } from "@app/services/notification/notification-service"; import { NotificationType } from "@app/services/notification/notification-types"; import { TOrgDALFactory } from "@app/services/org/org-dal"; -import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service"; +import { TSmtpService } from "@app/services/smtp/smtp-service"; import { TLicenseServiceFactory } from "../license/license-service"; import { PamResource } from "../pam-resource/pam-resource-enums"; @@ -61,8 +61,7 @@ export const gatewayV2ServiceFactory = ({ relayDAL, permissionService, orgDAL, - notificationService, - smtpService + notificationService }: TGatewayV2ServiceFactoryDep) => { const $validateIdentityAccessToGateway = async (orgId: string, actorId: string, actorAuthMethod: ActorAuthMethod) => { const orgLicensePlan = await licenseService.getPlan(orgId); @@ -931,15 +930,17 @@ export const gatewayV2ServiceFactory = ({ })) ); - await smtpService.sendMail({ - recipients: admins.map((admin) => admin.user.email).filter((v): v is string => !!v), - subjectLine: "Gateway Health Alert", - substitutions: { - type: "gateway", - names: gatewayNames - }, - template: SmtpTemplates.HealthAlert - }); + // Temporarily disabled email notifications due to excessive noise. Will be revised later + // + // await smtpService.sendMail({ + // recipients: admins.map((admin) => admin.user.email).filter((v): v is string => !!v), + // subjectLine: "Gateway Health Alert", + // substitutions: { + // type: "gateway", + // names: gatewayNames + // }, + // template: SmtpTemplates.HealthAlert + // }); await Promise.all(gateways.map((gw) => gatewayV2DAL.updateById(gw.id, { healthAlertedAt: new Date() }))); } catch (error) { diff --git a/backend/src/ee/services/kmip/kmip-operation-service.ts b/backend/src/ee/services/kmip/kmip-operation-service.ts index b3eace6bc..3955fd0ca 100644 --- a/backend/src/ee/services/kmip/kmip-operation-service.ts +++ b/backend/src/ee/services/kmip/kmip-operation-service.ts @@ -341,7 +341,8 @@ export const kmipOperationServiceFactory = ({ algorithm: completeKeyDetails.internalKms.encryptionAlgorithm, isActive: !key.isDisabled, createdAt: key.createdAt, - updatedAt: key.updatedAt + updatedAt: key.updatedAt, + kmipMetadata: key.kmipMetadata as Record }; }; diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.ts index e80ec7cf5..cbe1bed7e 100644 --- a/backend/src/ee/services/oidc/oidc-config-service.ts +++ b/backend/src/ee/services/oidc/oidc-config-service.ts @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/no-unsafe-call */ import { ForbiddenError } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import { Issuer, Issuer as OpenIdIssuer, Strategy as OpenIdStrategy, TokenSet } from "openid-client"; import { AccessScope, OrganizationActionScope, OrgMembershipStatus, TableName, TUsers } from "@app/db/schemas"; @@ -15,6 +16,7 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissio import { getConfig } from "@app/lib/config/env"; import { crypto } from "@app/lib/crypto"; import { BadRequestError, ForbiddenRequestError, NotFoundError, OidcAuthError } from "@app/lib/errors"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { OrgServiceActor } from "@app/lib/types"; import { ActorType, AuthMethod, AuthTokenType } from "@app/services/auth/auth-type"; import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service"; @@ -471,7 +473,7 @@ export const oidcConfigServiceFactory = ({ }); } - return { isUserCompleted, providerAuthToken }; + return { isUserCompleted, providerAuthToken, user }; }; const updateOidcCfg = async ({ @@ -754,10 +756,35 @@ export const oidcConfigServiceFactory = ({ callbackPort, manageGroupMemberships: oidcCfg.manageGroupMemberships }) - .then(({ isUserCompleted, providerAuthToken }) => { + .then(({ isUserCompleted, providerAuthToken, user }) => { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.user.email": claims?.email?.toLowerCase(), + "infisical.user.id": user.id, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.auth.method": AuthAttemptAuthMethod.OIDC, + "infisical.auth.result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + cb(null, { isUserCompleted, providerAuthToken }); }) .catch((error) => { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.user.email": claims?.email?.toLowerCase(), + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.auth.method": AuthAttemptAuthMethod.OIDC, + "infisical.auth.result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + cb(error); }); } diff --git a/backend/src/ee/services/pam-account/pam-account-fns.ts b/backend/src/ee/services/pam-account/pam-account-fns.ts index fdc440991..aae703eeb 100644 --- a/backend/src/ee/services/pam-account/pam-account-fns.ts +++ b/backend/src/ee/services/pam-account/pam-account-fns.ts @@ -45,17 +45,47 @@ export const decryptAccountCredentials = async ({ return JSON.parse(decryptedPlainTextBlob.toString()) as TPamAccountCredentials; }; -export const decryptAccount = async ( +export const decryptAccountMessage = async ({ + projectId, + encryptedMessage, + kmsService +}: { + projectId: string; + encryptedMessage: Buffer; + kmsService: Pick; +}) => { + const { decryptor } = await kmsService.createCipherPairWithDataKey({ + type: KmsDataKey.SecretManager, + projectId + }); + + const decryptedPlainTextBlob = decryptor({ + cipherTextBlob: encryptedMessage + }); + + return decryptedPlainTextBlob.toString(); +}; + +export const decryptAccount = async < + T extends { encryptedCredentials: Buffer; encryptedLastRotationMessage?: Buffer | null } +>( account: T, projectId: string, kmsService: Pick -): Promise => { +): Promise => { return { ...account, credentials: await decryptAccountCredentials({ encryptedCredentials: account.encryptedCredentials, projectId, kmsService - }) - } as T & { credentials: TPamAccountCredentials }; + }), + lastRotationMessage: account.encryptedLastRotationMessage + ? await decryptAccountMessage({ + encryptedMessage: account.encryptedLastRotationMessage, + projectId, + kmsService + }) + : null + }; }; diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts index fd3615013..00b84943f 100644 --- a/backend/src/ee/services/pam-account/pam-account-service.ts +++ b/backend/src/ee/services/pam-account/pam-account-service.ts @@ -15,6 +15,7 @@ import { logger } from "@app/lib/logger"; import { OrgServiceActor } from "@app/lib/types"; import { ActorType } from "@app/services/auth/auth-type"; import { TKmsServiceFactory } from "@app/services/kms/kms-service"; +import { KmsDataKey } from "@app/services/kms/kms-types"; import { TProjectDALFactory } from "@app/services/project/project-dal"; import { TUserDALFactory } from "@app/services/user/user-dal"; @@ -353,6 +354,7 @@ export const pamAccountServiceFactory = ({ TPamAccounts & { resource: Pick & { rotationCredentialsConfigured: boolean }; credentials: TPamAccountCredentials; + lastRotationMessage: string | null; } > = []; @@ -376,6 +378,7 @@ export const pamAccountServiceFactory = ({ ) { // Decrypt the account only if the user has permission to read it const decryptedAccount = await decryptAccount(account, account.projectId, kmsService); + decryptedAndPermittedAccounts.push({ ...decryptedAccount, resource: { @@ -575,10 +578,10 @@ export const pamAccountServiceFactory = ({ for (let i = 0; i < accounts.length; i += ROTATION_CONCURRENCY_LIMIT) { const batch = accounts.slice(i, i + ROTATION_CONCURRENCY_LIMIT); - const rotationPromises = batch.map(async (account) => - pamAccountDAL.transaction(async (tx) => { - let logResourceType = "unknown"; - try { + const rotationPromises = batch.map(async (account) => { + let logResourceType = "unknown"; + try { + await pamAccountDAL.transaction(async (tx) => { const resource = await pamResourceDAL.findById(account.resourceId, tx); if (!resource || !resource.encryptedRotationAccountCredentials) return; logResourceType = resource.resourceType; @@ -619,7 +622,9 @@ export const pamAccountServiceFactory = ({ account.id, { encryptedCredentials, - lastRotatedAt: new Date() + lastRotatedAt: new Date(), + rotationStatus: "success", + encryptedLastRotationMessage: null }, tx ); @@ -640,32 +645,45 @@ export const pamAccountServiceFactory = ({ } } }); - } catch (error) { - logger.error(error, `Failed to rotate credentials for account [accountId=${account.id}]`); + }); + } catch (error) { + logger.error(error, `Failed to rotate credentials for account [accountId=${account.id}]`); - const errorMessage = error instanceof Error ? error.message : "An unknown error occurred"; + const errorMessage = error instanceof Error ? error.message : "An unknown error occurred"; - await auditLogService.createAuditLog({ - projectId: account.projectId, - actor: { - type: ActorType.PLATFORM, - metadata: {} - }, - event: { - type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION_FAILED, - metadata: { - accountId: account.id, - accountName: account.name, - resourceId: account.resourceId, - resourceType: logResourceType, - errorMessage - } + const { encryptor } = await kmsService.createCipherPairWithDataKey({ + type: KmsDataKey.SecretManager, + projectId: account.projectId + }); + + const { cipherTextBlob: encryptedMessage } = encryptor({ + plainText: Buffer.from(errorMessage) + }); + + await pamAccountDAL.updateById(account.id, { + rotationStatus: "failed", + encryptedLastRotationMessage: encryptedMessage + }); + + await auditLogService.createAuditLog({ + projectId: account.projectId, + actor: { + type: ActorType.PLATFORM, + metadata: {} + }, + event: { + type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION_FAILED, + metadata: { + accountId: account.id, + accountName: account.name, + resourceId: account.resourceId, + resourceType: logResourceType, + errorMessage } - }); - throw error; // Rollback transaction - } - }) - ); + } + }); + } + }); // eslint-disable-next-line no-await-in-loop await Promise.all(rotationPromises); diff --git a/backend/src/ee/services/pam-resource/mysql/mysql-resource-fns.ts b/backend/src/ee/services/pam-resource/mysql/mysql-resource-fns.ts new file mode 100644 index 000000000..4010d208b --- /dev/null +++ b/backend/src/ee/services/pam-resource/mysql/mysql-resource-fns.ts @@ -0,0 +1,8 @@ +import { MySQLResourceListItemSchema } from "./mysql-resource-schemas"; + +export const getMySQLResourceListItem = () => { + return { + name: MySQLResourceListItemSchema.shape.name.value, + resource: MySQLResourceListItemSchema.shape.resource.value + }; +}; diff --git a/backend/src/ee/services/pam-resource/mysql/mysql-resource-schemas.ts b/backend/src/ee/services/pam-resource/mysql/mysql-resource-schemas.ts new file mode 100644 index 000000000..8d3589a8a --- /dev/null +++ b/backend/src/ee/services/pam-resource/mysql/mysql-resource-schemas.ts @@ -0,0 +1,76 @@ +import { z } from "zod"; + +import { PamResource } from "../pam-resource-enums"; +import { + BaseCreatePamAccountSchema, + BaseCreatePamResourceSchema, + BasePamAccountSchema, + BasePamAccountSchemaWithResource, + BasePamResourceSchema, + BaseUpdatePamAccountSchema, + BaseUpdatePamResourceSchema +} from "../pam-resource-schemas"; +import { + BaseSqlAccountCredentialsSchema, + BaseSqlResourceConnectionDetailsSchema +} from "../shared/sql/sql-resource-schemas"; + +// Resources +export const MySQLResourceConnectionDetailsSchema = BaseSqlResourceConnectionDetailsSchema.extend({ + // MySQL db in many cases the db will not be provided when making connection + database: z.string().trim() +}); +export const MySQLAccountCredentialsSchema = BaseSqlAccountCredentialsSchema; + +const BaseMySQLResourceSchema = BasePamResourceSchema.extend({ resourceType: z.literal(PamResource.MySQL) }); + +export const MySQLResourceSchema = BaseMySQLResourceSchema.extend({ + connectionDetails: MySQLResourceConnectionDetailsSchema, + rotationAccountCredentials: MySQLAccountCredentialsSchema.nullable().optional() +}); + +export const SanitizedMySQLResourceSchema = BaseMySQLResourceSchema.extend({ + connectionDetails: MySQLResourceConnectionDetailsSchema, + rotationAccountCredentials: MySQLAccountCredentialsSchema.pick({ + username: true + }) + .nullable() + .optional() +}); + +export const MySQLResourceListItemSchema = z.object({ + name: z.literal("MySQL"), + resource: z.literal(PamResource.MySQL) +}); + +export const CreateMySQLResourceSchema = BaseCreatePamResourceSchema.extend({ + connectionDetails: MySQLResourceConnectionDetailsSchema, + rotationAccountCredentials: MySQLAccountCredentialsSchema.nullable().optional() +}); + +export const UpdateMySQLResourceSchema = BaseUpdatePamResourceSchema.extend({ + connectionDetails: MySQLResourceConnectionDetailsSchema.optional(), + rotationAccountCredentials: MySQLAccountCredentialsSchema.nullable().optional() +}); + +// Accounts +export const MySQLAccountSchema = BasePamAccountSchema.extend({ + credentials: MySQLAccountCredentialsSchema +}); + +export const CreateMySQLAccountSchema = BaseCreatePamAccountSchema.extend({ + credentials: MySQLAccountCredentialsSchema +}); + +export const UpdateMySQLAccountSchema = BaseUpdatePamAccountSchema.extend({ + credentials: MySQLAccountCredentialsSchema.optional() +}); + +export const SanitizedMySQLAccountWithResourceSchema = BasePamAccountSchemaWithResource.extend({ + credentials: MySQLAccountCredentialsSchema.pick({ + username: true + }) +}); + +// Sessions +export const MySQLSessionCredentialsSchema = MySQLResourceConnectionDetailsSchema.and(MySQLAccountCredentialsSchema); diff --git a/backend/src/ee/services/pam-resource/mysql/mysql-resource-types.ts b/backend/src/ee/services/pam-resource/mysql/mysql-resource-types.ts new file mode 100644 index 000000000..43c2eea51 --- /dev/null +++ b/backend/src/ee/services/pam-resource/mysql/mysql-resource-types.ts @@ -0,0 +1,16 @@ +import { z } from "zod"; + +import { + MySQLAccountCredentialsSchema, + MySQLAccountSchema, + MySQLResourceConnectionDetailsSchema, + MySQLResourceSchema +} from "./mysql-resource-schemas"; + +// Resources +export type TMySQLResource = z.infer; +export type TMySQLResourceConnectionDetails = z.infer; + +// Accounts +export type TMySQLAccount = z.infer; +export type TMySQLAccountCredentials = z.infer; diff --git a/backend/src/ee/services/pam-resource/pam-resource-enums.ts b/backend/src/ee/services/pam-resource/pam-resource-enums.ts index fbc260fba..dff1cc650 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-enums.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-enums.ts @@ -1,3 +1,4 @@ export enum PamResource { - Postgres = "postgres" + Postgres = "postgres", + MySQL = "mysql" } diff --git a/backend/src/ee/services/pam-resource/pam-resource-factory.ts b/backend/src/ee/services/pam-resource/pam-resource-factory.ts index 298b1664c..151fa7ea1 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-factory.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-factory.ts @@ -5,5 +5,6 @@ import { sqlResourceFactory } from "./shared/sql/sql-resource-factory"; type TPamResourceFactoryImplementation = TPamResourceFactory; export const PAM_RESOURCE_FACTORY_MAP: Record = { - [PamResource.Postgres]: sqlResourceFactory as TPamResourceFactoryImplementation + [PamResource.Postgres]: sqlResourceFactory as TPamResourceFactoryImplementation, + [PamResource.MySQL]: sqlResourceFactory as TPamResourceFactoryImplementation }; diff --git a/backend/src/ee/services/pam-resource/pam-resource-fns.ts b/backend/src/ee/services/pam-resource/pam-resource-fns.ts index 9d7493e68..cad087d2f 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-fns.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-fns.ts @@ -3,11 +3,12 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service"; import { KmsDataKey } from "@app/services/kms/kms-types"; import { decryptAccountCredentials } from "../pam-account/pam-account-fns"; +import { getMySQLResourceListItem } from "./mysql/mysql-resource-fns"; import { TPamResource, TPamResourceConnectionDetails } from "./pam-resource-types"; import { getPostgresResourceListItem } from "./postgres/postgres-resource-fns"; export const listResourceOptions = () => { - return [getPostgresResourceListItem()].sort((a, b) => a.name.localeCompare(b.name)); + return [getPostgresResourceListItem(), getMySQLResourceListItem()].sort((a, b) => a.name.localeCompare(b.name)); }; // Resource diff --git a/backend/src/ee/services/pam-resource/pam-resource-schemas.ts b/backend/src/ee/services/pam-resource/pam-resource-schemas.ts index 7f6165d88..17ed1ccd1 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-schemas.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-schemas.ts @@ -33,7 +33,9 @@ export const BasePamAccountSchemaWithResource = BasePamAccountSchema.extend({ resourceType: true }).extend({ rotationCredentialsConfigured: z.boolean() - }) + }), + lastRotationMessage: z.string().nullable().optional(), + rotationStatus: z.string().nullable().optional() }); export const BaseCreatePamAccountSchema = z.object({ diff --git a/backend/src/ee/services/pam-resource/pam-resource-types.ts b/backend/src/ee/services/pam-resource/pam-resource-types.ts index f2016420a..1ca9db3e2 100644 --- a/backend/src/ee/services/pam-resource/pam-resource-types.ts +++ b/backend/src/ee/services/pam-resource/pam-resource-types.ts @@ -1,4 +1,10 @@ import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service"; +import { + TMySQLAccount, + TMySQLAccountCredentials, + TMySQLResource, + TMySQLResourceConnectionDetails +} from "./mysql/mysql-resource-types"; import { PamResource } from "./pam-resource-enums"; import { TPostgresAccount, @@ -8,12 +14,13 @@ import { } from "./postgres/postgres-resource-types"; // Resource types -export type TPamResource = TPostgresResource; -export type TPamResourceConnectionDetails = TPostgresResourceConnectionDetails; +export type TPamResource = TPostgresResource | TMySQLResource; +export type TPamResourceConnectionDetails = TPostgresResourceConnectionDetails | TMySQLResourceConnectionDetails; // Account types -export type TPamAccount = TPostgresAccount; -export type TPamAccountCredentials = TPostgresAccountCredentials; +export type TPamAccount = TPostgresAccount | TMySQLAccount; +// eslint-disable-next-line @typescript-eslint/no-duplicate-type-constituents +export type TPamAccountCredentials = TPostgresAccountCredentials | TMySQLAccountCredentials; // Resource DTOs export type TCreateResourceDTO = Pick< diff --git a/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts b/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts index 73defd6e6..99ce2d25f 100644 --- a/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts +++ b/backend/src/ee/services/pam-resource/shared/sql/sql-resource-factory.ts @@ -1,4 +1,6 @@ -import knex, { Knex } from "knex"; +import knex from "knex"; +import mysql, { Connection } from "mysql2/promise"; +import * as pg from "pg"; import tls, { PeerCertificate } from "tls"; import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns"; @@ -20,30 +22,162 @@ const EXTERNAL_REQUEST_TIMEOUT = 10 * 1000; const TEST_CONNECTION_USERNAME = "infisical-gateway-connection-test"; const TEST_CONNECTION_PASSWORD = "infisical-gateway-connection-test-password"; +const SIMPLE_QUERY = "select 1"; -const SQL_CONNECTION_CLIENT_MAP = { - [PamResource.Postgres]: "pg" -}; +export interface SqlResourceConnection { + /** + * Check and see if the connection is good or not. + * + * @param connectOnly when true, if we only want to know that making the connection is possible or not, + * we don't care about authentication failures + * @returns Promise to be resolved when the connection is good, otherwise an error will be errbacked + */ + validate: (connectOnly: boolean) => Promise; -const getConnectionConfig = ( - resourceType: PamResource, - { host, sslEnabled, sslRejectUnauthorized, sslCertificate }: TSqlResourceConnectionDetails -) => { - switch (resourceType) { + /** + * Rotate password and return the new credentials. + * + * @param currentCredentials the current credentials to rotate + * + * @returns Promise to be resolved with the new credentials + */ + rotateCredentials: ( + currentCredentials: TSqlAccountCredentials, + newPassword: string + ) => Promise; + + /** + * Close the connection. + * + * @returns Promise for closing the connection + */ + close: () => Promise; +} + +const makeSqlConnection = ( + proxyPort: number, + config: { + connectionDetails: TSqlResourceConnectionDetails; + resourceType: PamResource; + username?: string; + password?: string; + } +): SqlResourceConnection => { + const { connectionDetails, resourceType, username, password } = config; + const { host, sslEnabled, sslRejectUnauthorized, sslCertificate } = connectionDetails; + const actualUsername = username ?? TEST_CONNECTION_USERNAME; // Use provided username or fallback + const actualPassword = password ?? TEST_CONNECTION_PASSWORD; // Use provided password or fallback + switch (config.resourceType) { case PamResource.Postgres: { + const client = knex({ + client: "pg", + connection: { + host: "localhost", + port: proxyPort, + user: actualUsername, + password: actualPassword, + database: connectionDetails.database, + connectionTimeoutMillis: EXTERNAL_REQUEST_TIMEOUT, + ssl: sslEnabled + ? { + rejectUnauthorized: sslRejectUnauthorized, + ca: sslCertificate, + servername: host, + // When using proxy, we need to bypass hostname validation since we connect to localhost + // but validate the certificate against the actual hostname + checkServerIdentity: (hostname: string, cert: PeerCertificate) => { + return tls.checkServerIdentity(host, cert); + } + } + : false + } + }); return { - ssl: sslEnabled - ? { - rejectUnauthorized: sslRejectUnauthorized, - ca: sslCertificate, - servername: host, - // When using proxy, we need to bypass hostname validation since we connect to localhost - // but validate the certificate against the actual hostname - checkServerIdentity: (hostname: string, cert: PeerCertificate) => { - return tls.checkServerIdentity(host, cert); + validate: async (connectOnly) => { + try { + await client.raw(SIMPLE_QUERY); + } catch (error) { + if (error instanceof pg.DatabaseError) { + // Hacky way to know if we successfully hit the database. + // TODO: potentially two approaches to solve the problem. + // 1. change the work flow, add account first then resource + // 2. modify relay to add a new endpoint for returning if the target host is healthy or not + // (like being able to do an auth handshake regardless pass or not) + if ( + connectOnly && + (error.message === `password authentication failed for user "${TEST_CONNECTION_USERNAME}"` || + error.message.includes("no pg_hba.conf entry for host")) + ) { + return; } } - : false + throw new BadRequestError({ + message: `Unable to validate connection to ${resourceType}: ${(error as Error).message || String(error)}` + }); + } + }, + rotateCredentials: async (currentCredentials, newPassword) => { + // Note: The generated random password is not really going to make SQL Injection possible. + // The reason we are not using parameters binding is that the "ALTER USER" syntax is DDL, + // parameters binding is not supported. But just in case if the this code got copied + // around and repurposed, let's just do some naive escaping regardless + await client.raw(`ALTER USER :username: WITH PASSWORD '${newPassword.replace(/'/g, "''")}'`, { + username: currentCredentials.username + }); + return { username: currentCredentials.username, password: newPassword }; + }, + close: () => client.destroy() + }; + } + case PamResource.MySQL: { + return { + validate: async (connectOnly) => { + let client: Connection | null = null; + try { + // Notice: the reason we are not using Knex for mysql2 is because we don't need any fancy feature from Knex. + // mysql2 doesn't provide custom ssl verification function pass in. + // ref: https://github.com/sidorares/node-mysql2/blob/2543272a2ada8d8a07f74582549d7dd3fe948e2d/lib/base/connection.js#L358-L362 + // and then even I tried to workaround it with Knex's pool afterCreate hook, but then encounter a bug: + // ref: https://github.com/knex/knex/issues/5352 + // It appears that using Knex causing more troubles than not, we are just checking the connections, + // so it's much easier to create raw connection with the driver lib directly + client = await mysql.createConnection({ + host: "localhost", + port: proxyPort, + user: actualUsername, // Use provided username or fallback + password: actualPassword, // Use provided password or fallback + database: connectionDetails.database, + ssl: sslEnabled + ? { + rejectUnauthorized: sslRejectUnauthorized, + ca: sslCertificate + } + : undefined + }); + await client.query(SIMPLE_QUERY); + } catch (error) { + if (connectOnly) { + // Hacky way to know if we successfully hit the database. + if ( + error instanceof Error && + error.message.startsWith(`Access denied for user '${TEST_CONNECTION_USERNAME}'@`) + ) { + return; + } + } + // TODO: handle other errors, and throw standardlized errors providing user-friendly msg + throw error; + } finally { + await client?.end(); + } + }, + rotateCredentials: async () => { + // TODO: the pwd rotation for MySQL is not supported yet + throw new BadRequestError({ + message: "Unsupported operation" + }); + }, + close: async () => {} }; } default: @@ -62,10 +196,9 @@ export const executeWithGateway = async ( password?: string; }, gatewayV2Service: Pick, - operation: (client: Knex) => Promise + operation: (connection: SqlResourceConnection) => Promise ): Promise => { - const { connectionDetails, resourceType, gatewayId, username, password } = config; - + const { connectionDetails, gatewayId } = config; const [targetHost] = await verifyHostInputValidity(connectionDetails.host, true); const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({ gatewayId, @@ -79,22 +212,11 @@ export const executeWithGateway = async ( return withGatewayV2Proxy( async (proxyPort) => { - const client = knex({ - client: SQL_CONNECTION_CLIENT_MAP[resourceType], - connection: { - database: connectionDetails.database, - port: proxyPort, - host: "localhost", - user: username ?? TEST_CONNECTION_USERNAME, // Use provided username or fallback - password: password ?? TEST_CONNECTION_PASSWORD, // Use provided password or fallback - connectionTimeoutMillis: EXTERNAL_REQUEST_TIMEOUT, - ...getConnectionConfig(resourceType, connectionDetails) - } - }); + const connection = makeSqlConnection(proxyPort, config); try { - return await operation(client); + return await operation(connection); } finally { - await client.destroy(); + await connection.close(); } }, { @@ -115,25 +237,14 @@ export const sqlResourceFactory: TPamResourceFactory { try { await executeWithGateway({ connectionDetails, gatewayId, resourceType }, gatewayV2Service, async (client) => { - await client.raw("Select 1"); + await client.validate(true); }); return connectionDetails; } catch (error) { - // Hacky way to know if we successfully hit the database - if (error instanceof BadRequestError) { - if (error.message === `password authentication failed for user "${TEST_CONNECTION_USERNAME}"`) { - return connectionDetails; - } - - if (error.message.includes("no pg_hba.conf entry for host")) { - return connectionDetails; - } - - if (error.message === "Connection terminated unexpectedly") { - throw new BadRequestError({ - message: "Connection terminated unexpectedly. Verify that host and port are correct" - }); - } + if (error instanceof BadRequestError && error.message === "Connection terminated unexpectedly") { + throw new BadRequestError({ + message: "Connection terminated unexpectedly. Verify that host and port are correct" + }); } throw new BadRequestError({ @@ -156,11 +267,12 @@ export const sqlResourceFactory: TPamResourceFactory { - await client.raw("Select 1"); + await client.validate(false); } ); return credentials; } catch (error) { + // TODO: extract these logic into each SQL connection if (error instanceof BadRequestError) { if (error.message === `password authentication failed for user "${credentials.username}"`) { throw new BadRequestError({ @@ -185,10 +297,9 @@ export const sqlResourceFactory: TPamResourceFactory { + const newPassword = alphaNumericNanoId(32); try { - const newPassword = alphaNumericNanoId(32); - - await executeWithGateway( + return await executeWithGateway( { connectionDetails, gatewayId, @@ -197,20 +308,8 @@ export const sqlResourceFactory: TPamResourceFactory { - switch (resourceType) { - case PamResource.Postgres: - await client.raw(`ALTER USER ?? WITH PASSWORD '${newPassword}'`, [currentCredentials.username]); - break; - default: - throw new BadRequestError({ - message: `Password rotation for ${resourceType as PamResource} is not supported.` - }); - } - } + (client) => client.rotateCredentials(currentCredentials, newPassword) ); - - return { username: currentCredentials.username, password: newPassword }; } catch (error) { if (error instanceof BadRequestError) { if (error.message === `password authentication failed for user "${rotationAccountCredentials.username}"`) { @@ -232,8 +331,10 @@ export const sqlResourceFactory: TPamResourceFactory admin.user.email).filter((v): v is string => !!v), - subjectLine: "Relay Health Alert", - substitutions: { - type: "relay", - names: relayNames - }, - template: SmtpTemplates.HealthAlert - }); + // Temporarily disabled email notifications due to excessive noise. Will be revised later + // + // await smtpService.sendMail({ + // recipients: admins.map((admin) => admin.user.email).filter((v): v is string => !!v), + // subjectLine: "Relay Health Alert", + // substitutions: { + // type: "relay", + // names: relayNames + // }, + // template: SmtpTemplates.HealthAlert + // }); } await Promise.all(relays.map((r) => relayDAL.updateById(r.id, { healthAlertedAt: new Date() }))); diff --git a/backend/src/ee/services/saml-config/saml-config-service.ts b/backend/src/ee/services/saml-config/saml-config-service.ts index c99ae8b28..7206bd293 100644 --- a/backend/src/ee/services/saml-config/saml-config-service.ts +++ b/backend/src/ee/services/saml-config/saml-config-service.ts @@ -769,7 +769,7 @@ export const samlConfigServiceFactory = ({ }); } - return { isUserCompleted, providerAuthToken }; + return { isUserCompleted, providerAuthToken, user, organization }; }; return { diff --git a/backend/src/ee/services/saml-config/saml-config-types.ts b/backend/src/ee/services/saml-config/saml-config-types.ts index 983ec4db7..5ca3e09fb 100644 --- a/backend/src/ee/services/saml-config/saml-config-types.ts +++ b/backend/src/ee/services/saml-config/saml-config-types.ts @@ -1,4 +1,4 @@ -import { TSamlConfigs } from "@app/db/schemas"; +import { TOrganizations, TSamlConfigs, TUsers } from "@app/db/schemas"; import { TOrgPermission } from "@app/lib/types"; import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type"; @@ -78,5 +78,7 @@ export type TSamlConfigServiceFactory = { samlLogin: (arg: TSamlLoginDTO) => Promise<{ isUserCompleted: boolean; providerAuthToken: string; + user: TUsers; + organization: TOrganizations; }>; }; diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts index affec39ad..a10a3f568 100644 --- a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts +++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts @@ -1517,7 +1517,7 @@ export const secretApprovalRequestServiceFactory = ({ })) ); if (secrets.length) - throw new BadRequestError({ message: `Secret already exist: ${secrets.map((el) => el.key).join(",")}` }); + throw new BadRequestError({ message: `Secret already exists: ${secrets.map((el) => el.key).join(",")}` }); commits.push( ...createdSecrets.map((createdSecret) => ({ diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts index dde9b4e35..0cb606cbf 100644 --- a/backend/src/lib/api-docs/constants.ts +++ b/backend/src/lib/api-docs/constants.ts @@ -2348,6 +2348,9 @@ export const AppConnections = { RAILWAY: { apiToken: "The API token used to authenticate with Railway." }, + NORTHFLANK: { + apiToken: "The API token used to authenticate with Northflank." + }, CHECKLY: { apiKey: "The API key used to authenticate with Checkly." }, @@ -2376,6 +2379,12 @@ export const AppConnections = { }, LARAVEL_FORGE: { apiToken: "The API token used to authenticate with Laravel Forge." + }, + CHEF: { + serverUrl: "The URL of the Chef server to connect to.", + orgName: "The short name of the Chef organization to connect to.", + userName: "The username used to access Chef.", + privateKey: "The private key used to access Chef." } } }; @@ -2620,6 +2629,16 @@ export const SecretSyncs = { siteName: "The name of the Netlify site to sync secrets to.", siteId: "The ID of the Netlify site to sync secrets to.", context: "The Netlify context to sync secrets to." + }, + CHEF: { + dataBagName: "The name of the Chef data bag to sync secrets to.", + dataBagItemName: "The name of the Chef data bag item to sync secrets to." + }, + NORTHFLANK: { + projectId: "The ID of the Northflank project to sync secrets to.", + projectName: "The name of the Northflank project to sync secrets to.", + secretGroupId: "The ID of the Northflank secret group to sync secrets to.", + secretGroupName: "The name of the Northflank secret group to sync secrets to." } } }; diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.ts index 5ae0e5b1d..46abe4bf1 100644 --- a/backend/src/lib/gateway-v2/gateway-v2.ts +++ b/backend/src/lib/gateway-v2/gateway-v2.ts @@ -7,6 +7,7 @@ import https from "https"; import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns"; import { splitPemChain } from "@app/services/certificate/certificate-fns"; +import { getConfig } from "../config/env"; import { BadRequestError } from "../errors"; import { GatewayProxyProtocol } from "../gateway/types"; import { logger } from "../logger"; @@ -80,6 +81,8 @@ const createGatewayConnection = async ( gateway: { clientCertificate: string; clientPrivateKey: string; serverCertificateChain: string }, protocol: GatewayProxyProtocol ): Promise => { + const appCfg = getConfig(); + const protocolToAlpn = { [GatewayProxyProtocol.Http]: "infisical-http-proxy", [GatewayProxyProtocol.Tcp]: "infisical-tcp-proxy", @@ -94,7 +97,8 @@ const createGatewayConnection = async ( minVersion: "TLSv1.2", maxVersion: "TLSv1.3", rejectUnauthorized: true, - ALPNProtocols: [protocolToAlpn[protocol]] + ALPNProtocols: [protocolToAlpn[protocol]], + checkServerIdentity: appCfg.isDevelopmentMode ? () => undefined : tls.checkServerIdentity }; return new Promise((resolve, reject) => { diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.ts new file mode 100644 index 000000000..5f650ffc6 --- /dev/null +++ b/backend/src/lib/telemetry/metrics.ts @@ -0,0 +1,100 @@ +import { requestContext } from "@fastify/request-context"; +import opentelemetry from "@opentelemetry/api"; + +import { getConfig } from "../config/env"; + +const infisicalMeter = opentelemetry.metrics.getMeter("Infisical"); + +export enum AuthAttemptAuthMethod { + EMAIL = "email", + SAML = "saml", + OIDC = "oidc", + GOOGLE = "google", + GITHUB = "github", + GITLAB = "gitlab", + TOKEN_AUTH = "token-auth", + UNIVERSAL_AUTH = "universal-auth", + KUBERNETES_AUTH = "kubernetes-auth", + GCP_AUTH = "gcp-auth", + ALICLOUD_AUTH = "alicloud-auth", + AWS_AUTH = "aws-auth", + AZURE_AUTH = "azure-auth", + TLS_CERT_AUTH = "tls-cert-auth", + OCI_AUTH = "oci-auth", + OIDC_AUTH = "oidc-auth", + JWT_AUTH = "jwt-auth", + LDAP_AUTH = "ldap-auth" +} + +export enum AuthAttemptAuthResult { + SUCCESS = "success", + FAILURE = "failure" +} + +export const authAttemptCounter = infisicalMeter.createCounter("infisical.auth.attempt.count", { + description: "Authentication attempts (both successful and failed)", + unit: "{attempt}" +}); + +export const secretReadCounter = infisicalMeter.createCounter("infisical.secret.read.count", { + description: "Number of secret read operations", + unit: "{operation}" +}); + +export const recordSecretReadMetric = (params: { environment: string; secretPath: string; name?: string }) => { + const appCfg = getConfig(); + + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + const attributes: Record = { + "infisical.environment": params.environment, + "infisical.secret.path": params.secretPath, + ...(params.name ? { "infisical.secret.name": params.name } : {}) + }; + + const orgId = requestContext.get("orgId"); + if (orgId) { + attributes["infisical.organization.id"] = orgId; + } + + const orgName = requestContext.get("orgName"); + if (orgName) { + attributes["infisical.organization.name"] = orgName; + } + + const projectDetails = requestContext.get("projectDetails"); + if (projectDetails?.id) { + attributes["infisical.project.id"] = projectDetails.id; + } + if (projectDetails?.name) { + attributes["infisical.project.name"] = projectDetails.name; + } + + const userAuthInfo = requestContext.get("userAuthInfo"); + if (userAuthInfo?.userId) { + attributes["infisical.user.id"] = userAuthInfo.userId; + } + if (userAuthInfo?.email) { + attributes["infisical.user.email"] = userAuthInfo.email; + } + + const identityAuthInfo = requestContext.get("identityAuthInfo"); + if (identityAuthInfo?.identityId) { + attributes["infisical.identity.id"] = identityAuthInfo.identityId; + } + if (identityAuthInfo?.identityName) { + attributes["infisical.identity.name"] = identityAuthInfo.identityName; + } + + const userAgent = requestContext.get("userAgent"); + if (userAgent) { + attributes["user_agent.original"] = userAgent; + } + + const ip = requestContext.get("ip"); + if (ip) { + attributes["client.address"] = ip; + } + + secretReadCounter.add(1, attributes); + } +}; diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts index 9d8c472f4..3e6b1dd19 100644 --- a/backend/src/queue/queue-service.ts +++ b/backend/src/queue/queue-service.ts @@ -78,6 +78,7 @@ export enum QueueName { SecretReminderMigration = "secret-reminder-migration", UserNotification = "user-notification", HealthAlert = "health-alert", + CertificateV3AutoRenewal = "certificate-v3-auto-renewal", PamAccountRotation = "pam-account-rotation" } @@ -128,6 +129,7 @@ export enum QueueJobs { SecretReminderMigration = "secret-reminder-migration", UserNotification = "user-notification-job", HealthAlert = "health-alert", + CertificateV3DailyAutoRenewal = "certificate-v3-daily-auto-renewal", PamAccountRotation = "pam-account-rotation" } @@ -359,6 +361,10 @@ export type TQueueJobTypes = { name: QueueJobs.HealthAlert; payload: undefined; }; + [QueueName.CertificateV3AutoRenewal]: { + name: QueueJobs.CertificateV3DailyAutoRenewal; + payload: undefined; + }; [QueueName.PamAccountRotation]: { name: QueueJobs.PamAccountRotation; payload: undefined; diff --git a/backend/src/server/app.ts b/backend/src/server/app.ts index f1176b932..60b678f63 100644 --- a/backend/src/server/app.ts +++ b/backend/src/server/app.ts @@ -141,7 +141,9 @@ export const main = async ({ await server.register(fastifyRequestContext, { defaultStoreValues: (req) => ({ reqId: req.id, - log: req.log.child({ reqId: req.id }) + log: req.log.child({ reqId: req.id }), + ip: req.realIp, + userAgent: req.headers["user-agent"] }) }); diff --git a/backend/src/server/plugins/api-metrics.ts b/backend/src/server/plugins/api-metrics.ts index 2e3a20a23..4233bc86d 100644 --- a/backend/src/server/plugins/api-metrics.ts +++ b/backend/src/server/plugins/api-metrics.ts @@ -1,12 +1,26 @@ +import { requestContext } from "@fastify/request-context"; import opentelemetry from "@opentelemetry/api"; import fp from "fastify-plugin"; -export const apiMetrics = fp(async (fastify) => { - const apiMeter = opentelemetry.metrics.getMeter("API"); - const latencyHistogram = apiMeter.createHistogram("API_latency", { - unit: "ms" - }); +const apiMeter = opentelemetry.metrics.getMeter("API"); +const latencyHistogram = apiMeter.createHistogram("API_latency", { + unit: "ms" +}); + +const infisicalMeter = opentelemetry.metrics.getMeter("Infisical"); + +const requestCounter = infisicalMeter.createCounter("infisical.http.server.request.count", { + description: "Total number of API requests to Infisical (covers both human users and machine identities)", + unit: "{request}" +}); + +const requestDurationHistogram = infisicalMeter.createHistogram("infisical.http.server.request.duration", { + description: "API request latency", + unit: "s" +}); + +export const apiMetrics = fp(async (fastify) => { fastify.addHook("onResponse", async (request, reply) => { const { method } = request; const route = request.routerPath; @@ -17,5 +31,67 @@ export const apiMetrics = fp(async (fastify) => { method, statusCode }); + + const orgId = requestContext.get("orgId"); + const orgName = requestContext.get("orgName"); + const userAuthInfo = requestContext.get("userAuthInfo"); + const identityAuthInfo = requestContext.get("identityAuthInfo"); + const projectDetails = requestContext.get("projectDetails"); + const userAgent = requestContext.get("userAgent"); + const ip = requestContext.get("ip"); + + const attributes: Record = { + "http.request.method": method, + "http.route": route, + "http.response.status_code": statusCode + }; + + if (orgId) { + attributes["infisical.organization.id"] = orgId; + } + if (orgName) { + attributes["infisical.organization.name"] = orgName; + } + + if (userAuthInfo) { + if (userAuthInfo.userId) { + attributes["infisical.user.id"] = userAuthInfo.userId; + } + if (userAuthInfo.email) { + attributes["infisical.user.email"] = userAuthInfo.email; + } + } + + if (identityAuthInfo) { + if (identityAuthInfo.identityId) { + attributes["infisical.identity.id"] = identityAuthInfo.identityId; + } + if (identityAuthInfo.identityName) { + attributes["infisical.identity.name"] = identityAuthInfo.identityName; + } + if (identityAuthInfo.authMethod) { + attributes["infisical.auth.method"] = identityAuthInfo.authMethod; + } + } + + if (projectDetails) { + if (projectDetails.id) { + attributes["infisical.project.id"] = projectDetails.id; + } + if (projectDetails.name) { + attributes["infisical.project.name"] = projectDetails.name; + } + } + + if (userAgent) { + attributes["user_agent.original"] = userAgent; + } + + if (ip) { + attributes["client.address"] = ip; + } + + requestCounter.add(1, attributes); + requestDurationHistogram.record(reply.elapsedTime / 1000, attributes); }); }); diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.ts index b33f2fbe6..31f3139ec 100644 --- a/backend/src/server/plugins/auth/inject-identity.ts +++ b/backend/src/server/plugins/auth/inject-identity.ts @@ -1,4 +1,4 @@ -import { requestContext } from "@fastify/request-context"; +import { requestContext, RequestContextData } from "@fastify/request-context"; import { FastifyRequest } from "fastify"; import fp from "fastify-plugin"; import type { JwtPayload } from "jsonwebtoken"; @@ -138,6 +138,11 @@ export const injectIdentity = fp( return; } + // Authentication is handled on a route-level + if (req.url === "/api/v1/relays/heartbeat-instance-relay") { + return; + } + // Authentication is handled on a route-level here. if (req.url.includes("/api/v1/workflow-integrations/microsoft-teams/message-endpoint")) { return; @@ -154,10 +159,11 @@ export const injectIdentity = fp( switch (authMode) { case AuthMode.JWT: { - const { user, tokenVersionId, orgId, rootOrgId, parentOrgId } = + const { user, tokenVersionId, orgId, orgName, rootOrgId, parentOrgId } = await server.services.authToken.fnValidateJwtIdentity(token, subOrganizationSelector); requestContext.set("orgId", orgId); - + requestContext.set("orgName", orgName); + requestContext.set("userAuthInfo", { userId: user.id, email: user.email || "" }); req.auth = { authMode: AuthMode.JWT, user, @@ -181,6 +187,7 @@ export const injectIdentity = fp( ); const serverCfg = await getServerCfg(); requestContext.set("orgId", identity.orgId); + requestContext.set("orgName", identity.orgName); req.auth = { authMode: AuthMode.IDENTITY_ACCESS_TOKEN, actor, @@ -193,24 +200,23 @@ export const injectIdentity = fp( isInstanceAdmin: serverCfg?.adminIdentityIds?.includes(identity.identityId), token }; + const identityAuthInfo: RequestContextData["identityAuthInfo"] = { + identityId: identity.identityId, + identityName: identity.name, + authMethod: identity.authMethod + }; + if (token?.identityAuth?.oidc) { - requestContext.set("identityAuthInfo", { - identityId: identity.identityId, - oidc: token?.identityAuth?.oidc - }); + identityAuthInfo.oidc = token?.identityAuth?.oidc; } if (token?.identityAuth?.kubernetes) { - requestContext.set("identityAuthInfo", { - identityId: identity.identityId, - kubernetes: token?.identityAuth?.kubernetes - }); + identityAuthInfo.kubernetes = token?.identityAuth?.kubernetes; } if (token?.identityAuth?.aws) { - requestContext.set("identityAuthInfo", { - identityId: identity.identityId, - aws: token?.identityAuth?.aws - }); + identityAuthInfo.aws = token?.identityAuth?.aws; } + + requestContext.set("identityAuthInfo", identityAuthInfo); break; } case AuthMode.SERVICE_TOKEN: { diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts index 62df05eec..8d10a8630 100644 --- a/backend/src/server/plugins/error-handler.ts +++ b/backend/src/server/plugins/error-handler.ts @@ -1,4 +1,5 @@ import { ForbiddenError, PureAbility } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import opentelemetry from "@opentelemetry/api"; import fastifyPlugin from "fastify-plugin"; import jwt from "jsonwebtoken"; @@ -47,6 +48,12 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider unit: "1" }); + const infisicalMeter = opentelemetry.metrics.getMeter("Infisical"); + const errorCounter = infisicalMeter.createCounter("infisical.http.server.error.count", { + description: "Total number of API errors in Infisical (covers both human users and machine identities)", + unit: "{error}" + }); + server.setErrorHandler((error, req, res) => { req.log.error(error); if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { @@ -61,6 +68,67 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider type: errorType, name: error.name }); + + const orgId = requestContext.get("orgId"); + const orgName = requestContext.get("orgName"); + const userAuthInfo = requestContext.get("userAuthInfo"); + const identityAuthInfo = requestContext.get("identityAuthInfo"); + const projectDetails = requestContext.get("projectDetails"); + + const attributes: Record = { + "http.request.method": method, + "http.route": route, + "error.type": errorType, + "error.name": error.name + }; + + if (orgId) { + attributes["infisical.organization.id"] = orgId; + } + if (orgName) { + attributes["infisical.organization.name"] = orgName; + } + + if (userAuthInfo) { + if (userAuthInfo.userId) { + attributes["infisical.user.id"] = userAuthInfo.userId; + } + if (userAuthInfo.email) { + attributes["infisical.user.email"] = userAuthInfo.email; + } + } + + if (identityAuthInfo) { + if (identityAuthInfo.identityId) { + attributes["infisical.identity.id"] = identityAuthInfo.identityId; + } + if (identityAuthInfo.identityName) { + attributes["infisical.identity.name"] = identityAuthInfo.identityName; + } + if (identityAuthInfo.authMethod) { + attributes["infisical.auth.method"] = identityAuthInfo.authMethod; + } + } + + if (projectDetails) { + if (projectDetails.id) { + attributes["infisical.project.id"] = projectDetails.id; + } + if (projectDetails.name) { + attributes["infisical.project.name"] = projectDetails.name; + } + } + + const userAgent = req.headers["user-agent"]; + if (userAgent) { + attributes["user_agent.original"] = userAgent; + } + + if (req.realIp) { + attributes["client.address"] = req.realIp; + } + + errorCounter.add(1, attributes); } if (error instanceof BadRequestError) { diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts index 0125df798..e2009e7fa 100644 --- a/backend/src/server/routes/index.ts +++ b/backend/src/server/routes/index.ts @@ -172,11 +172,13 @@ import { internalCertificateAuthorityServiceFactory } from "@app/services/certif import { certificateEstV3ServiceFactory } from "@app/services/certificate-est-v3/certificate-est-v3-service"; import { certificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal"; import { certificateProfileServiceFactory } from "@app/services/certificate-profile/certificate-profile-service"; +import { certificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal"; import { certificateTemplateDALFactory } from "@app/services/certificate-template/certificate-template-dal"; import { certificateTemplateEstConfigDALFactory } from "@app/services/certificate-template/certificate-template-est-config-dal"; import { certificateTemplateServiceFactory } from "@app/services/certificate-template/certificate-template-service"; import { certificateTemplateV2DALFactory } from "@app/services/certificate-template-v2/certificate-template-v2-dal"; import { certificateTemplateV2ServiceFactory } from "@app/services/certificate-template-v2/certificate-template-v2-service"; +import { certificateV3QueueServiceFactory } from "@app/services/certificate-v3/certificate-v3-queue"; import { certificateV3ServiceFactory } from "@app/services/certificate-v3/certificate-v3-service"; import { cmekServiceFactory } from "@app/services/cmek/cmek-service"; import { convertorServiceFactory } from "@app/services/convertor/convertor-service"; @@ -607,6 +609,10 @@ export const registerRoutes = async ( const membershipGroupService = membershipGroupServiceFactory({ membershipGroupDAL, membershipRoleDAL, + accessApprovalPolicyDAL, + accessApprovalPolicyApproverDAL, + secretApprovalPolicyDAL, + secretApprovalPolicyApproverDAL: sapApproverDAL, roleDAL, permissionService, orgDAL @@ -1059,6 +1065,7 @@ export const registerRoutes = async ( const certificateDAL = certificateDALFactory(db); const certificateBodyDAL = certificateBodyDALFactory(db); const certificateSecretDAL = certificateSecretDALFactory(db); + const certificateSyncDAL = certificateSyncDALFactory(db); const pkiAlertDAL = pkiAlertDALFactory(db); const pkiCollectionDAL = pkiCollectionDALFactory(db); @@ -1707,7 +1714,8 @@ export const registerRoutes = async ( licenseService, permissionService, kmsService, - membershipIdentityDAL + membershipIdentityDAL, + orgDAL }); const identityAwsAuthService = identityAwsAuthServiceFactory({ @@ -1960,6 +1968,8 @@ export const registerRoutes = async ( secretImportDAL, permissionService, appConnectionService, + projectDAL, + orgDAL, folderDAL, secretSyncQueue, projectBotService, @@ -2022,7 +2032,8 @@ export const registerRoutes = async ( certificateBodyDAL, certificateSecretDAL, certificateAuthorityDAL, - certificateAuthorityCertDAL + certificateAuthorityCertDAL, + certificateSyncDAL }); const pkiSyncCleanup = pkiSyncCleanupQueueServiceFactory({ @@ -2133,17 +2144,29 @@ export const registerRoutes = async ( permissionService, pkiCollectionDAL, pkiCollectionItemDAL, + certificateSyncDAL, pkiSyncDAL, pkiSyncQueue }); const certificateV3Service = certificateV3ServiceFactory({ certificateDAL, + certificateSecretDAL, certificateAuthorityDAL, certificateProfileDAL, certificateTemplateV2Service, internalCaService: internalCertificateAuthorityService, - permissionService + permissionService, + certificateSyncDAL, + pkiSyncDAL, + pkiSyncQueue + }); + + const certificateV3Queue = certificateV3QueueServiceFactory({ + queueService, + certificateDAL, + certificateV3Service, + auditLogService }); const certificateEstV3Service = certificateEstV3ServiceFactory({ @@ -2178,6 +2201,8 @@ export const registerRoutes = async ( const pkiSyncService = pkiSyncServiceFactory({ pkiSyncDAL, + certificateDAL, + certificateSyncDAL, pkiSubscriberDAL, appConnectionService, permissionService, @@ -2333,6 +2358,7 @@ export const registerRoutes = async ( await dailyReminderQueueService.startSecretReminderMigrationJob(); await dailyExpiringPkiItemAlert.startSendingAlerts(); await pkiSubscriberQueue.startDailyAutoRenewalJob(); + await certificateV3Queue.init(); await kmsService.startService(hsmStatus); await microsoftTeamsService.start(); await dynamicSecretQueueService.init(); diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts index c799ef0f0..9a4d7f38b 100644 --- a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts +++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts @@ -48,6 +48,7 @@ import { ChecklyConnectionListItemSchema, SanitizedChecklyConnectionSchema } from "@app/services/app-connection/checkly"; +import { ChefConnectionListItemSchema, SanitizedChefConnectionSchema } from "@app/services/app-connection/chef"; import { CloudflareConnectionListItemSchema, SanitizedCloudflareConnectionSchema @@ -88,6 +89,10 @@ import { NetlifyConnectionListItemSchema, SanitizedNetlifyConnectionSchema } from "@app/services/app-connection/netlify"; +import { + NorthflankConnectionListItemSchema, + SanitizedNorthflankConnectionSchema +} from "@app/services/app-connection/northflank"; import { OktaConnectionListItemSchema, SanitizedOktaConnectionSchema } from "@app/services/app-connection/okta"; import { PostgresConnectionListItemSchema, @@ -160,10 +165,12 @@ const SanitizedAppConnectionSchema = z.union([ ...SanitizedSupabaseConnectionSchema.options, ...SanitizedDigitalOceanConnectionSchema.options, ...SanitizedNetlifyConnectionSchema.options, + ...SanitizedNorthflankConnectionSchema.options, ...SanitizedOktaConnectionSchema.options, ...SanitizedAzureADCSConnectionSchema.options, ...SanitizedRedisConnectionSchema.options, - ...SanitizedLaravelForgeConnectionSchema.options + ...SanitizedLaravelForgeConnectionSchema.options, + ...SanitizedChefConnectionSchema.options ]); const AppConnectionOptionsSchema = z.discriminatedUnion("app", [ @@ -203,10 +210,12 @@ const AppConnectionOptionsSchema = z.discriminatedUnion("app", [ SupabaseConnectionListItemSchema, DigitalOceanConnectionListItemSchema, NetlifyConnectionListItemSchema, + NorthflankConnectionListItemSchema, OktaConnectionListItemSchema, AzureADCSConnectionListItemSchema, RedisConnectionListItemSchema, - LaravelForgeConnectionListItemSchema + LaravelForgeConnectionListItemSchema, + ChefConnectionListItemSchema ]); export const registerAppConnectionRouter = async (server: FastifyZodProvider) => { diff --git a/backend/src/server/routes/v1/app-connection-routers/chef-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/chef-connection-router.ts new file mode 100644 index 000000000..6bfd83391 --- /dev/null +++ b/backend/src/server/routes/v1/app-connection-routers/chef-connection-router.ts @@ -0,0 +1,85 @@ +import z from "zod"; + +import { readLimit } from "@app/server/config/rateLimiter"; +import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; +import { AppConnection } from "@app/services/app-connection/app-connection-enums"; +import { + CreateChefConnectionSchema, + SanitizedChefConnectionSchema, + UpdateChefConnectionSchema +} from "@app/services/app-connection/chef"; +import { AuthMode } from "@app/services/auth/auth-type"; + +import { registerAppConnectionEndpoints } from "./app-connection-endpoints"; + +export const registerChefConnectionRouter = async (server: FastifyZodProvider) => { + registerAppConnectionEndpoints({ + app: AppConnection.Chef, + server, + sanitizedResponseSchema: SanitizedChefConnectionSchema, + createSchema: CreateChefConnectionSchema, + updateSchema: UpdateChefConnectionSchema + }); + + server.route({ + method: "GET", + url: `/:connectionId/data-bags`, + config: { + rateLimit: readLimit + }, + schema: { + params: z.object({ + connectionId: z.string().uuid() + }), + response: { + 200: z + .object({ + name: z.string() + }) + .array() + } + }, + onRequest: verifyAuth([AuthMode.JWT]), + handler: async (req) => { + const { connectionId } = req.params; + const dataBags = await server.services.appConnection.chef.listDataBags(connectionId, req.permission); + + return dataBags; + } + }); + + server.route({ + method: "GET", + url: `/:connectionId/data-bag-items`, + config: { + rateLimit: readLimit + }, + schema: { + params: z.object({ + connectionId: z.string().uuid() + }), + querystring: z.object({ + dataBagName: z.string() + }), + response: { + 200: z + .object({ + name: z.string() + }) + .array() + } + }, + onRequest: verifyAuth([AuthMode.JWT]), + handler: async (req) => { + const { connectionId } = req.params; + const { dataBagName } = req.query; + const dataBagItems = await server.services.appConnection.chef.listDataBagItems( + connectionId, + dataBagName, + req.permission + ); + + return dataBagItems; + } + }); +}; diff --git a/backend/src/server/routes/v1/app-connection-routers/index.ts b/backend/src/server/routes/v1/app-connection-routers/index.ts index 2e3da4420..32e9efe4c 100644 --- a/backend/src/server/routes/v1/app-connection-routers/index.ts +++ b/backend/src/server/routes/v1/app-connection-routers/index.ts @@ -13,6 +13,7 @@ import { registerAzureKeyVaultConnectionRouter } from "./azure-key-vault-connect import { registerBitbucketConnectionRouter } from "./bitbucket-connection-router"; import { registerCamundaConnectionRouter } from "./camunda-connection-router"; import { registerChecklyConnectionRouter } from "./checkly-connection-router"; +import { registerChefConnectionRouter } from "./chef-connection-router"; import { registerCloudflareConnectionRouter } from "./cloudflare-connection-router"; import { registerDatabricksConnectionRouter } from "./databricks-connection-router"; import { registerDigitalOceanConnectionRouter } from "./digital-ocean-connection-router"; @@ -29,6 +30,7 @@ import { registerLdapConnectionRouter } from "./ldap-connection-router"; import { registerMsSqlConnectionRouter } from "./mssql-connection-router"; import { registerMySqlConnectionRouter } from "./mysql-connection-router"; import { registerNetlifyConnectionRouter } from "./netlify-connection-router"; +import { registerNorthflankConnectionRouter } from "./northflank-connection-router"; import { registerOktaConnectionRouter } from "./okta-connection-router"; import { registerPostgresConnectionRouter } from "./postgres-connection-router"; import { registerRailwayConnectionRouter } from "./railway-connection-router"; @@ -83,6 +85,8 @@ export const APP_CONNECTION_REGISTER_ROUTER_MAP: Record { + registerAppConnectionEndpoints({ + app: AppConnection.Northflank, + server, + sanitizedResponseSchema: SanitizedNorthflankConnectionSchema, + createSchema: CreateNorthflankConnectionSchema, + updateSchema: UpdateNorthflankConnectionSchema + }); + + // The below endpoints are not exposed and for Infisical App use + server.route({ + method: "GET", + url: `/:connectionId/projects`, + config: { + rateLimit: readLimit + }, + schema: { + params: z.object({ + connectionId: z.string().uuid() + }), + response: { + 200: z.object({ + projects: z + .object({ + name: z.string(), + id: z.string() + }) + .array() + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT]), + handler: async (req) => { + const { connectionId } = req.params; + const projects = await server.services.appConnection.northflank.listProjects(connectionId, req.permission); + return { projects }; + } + }); + + server.route({ + method: "GET", + url: `/:connectionId/projects/:projectId/secret-groups`, + config: { + rateLimit: readLimit + }, + schema: { + params: z.object({ + connectionId: z.string().uuid(), + projectId: z.string() + }), + response: { + 200: z.object({ + secretGroups: z + .object({ + name: z.string(), + id: z.string() + }) + .array() + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT]), + handler: async (req) => { + const { connectionId, projectId } = req.params; + const secretGroups = await server.services.appConnection.northflank.listSecretGroups( + connectionId, + projectId, + req.permission + ); + return { secretGroups }; + } + }); +}; diff --git a/backend/src/server/routes/v1/certificate-profiles-router.ts b/backend/src/server/routes/v1/certificate-profiles-router.ts index 2292c3ba8..08f532bc4 100644 --- a/backend/src/server/routes/v1/certificate-profiles-router.ts +++ b/backend/src/server/routes/v1/certificate-profiles-router.ts @@ -42,7 +42,7 @@ export const registerCertificateProfilesRouter = async (server: FastifyZodProvid apiConfig: z .object({ autoRenew: z.boolean().default(false), - autoRenewDays: z.number().min(1).max(365).optional() + renewBeforeDays: z.number().min(1).max(30).optional() }) .optional() }) @@ -121,9 +121,7 @@ export const registerCertificateProfilesRouter = async (server: FastifyZodProvid limit: z.coerce.number().min(1).max(100).default(20), search: z.string().optional(), enrollmentType: z.nativeEnum(EnrollmentType).optional(), - caId: z.string().uuid().optional(), - includeMetrics: z.coerce.boolean().optional().default(false), - expiringDays: z.coerce.number().min(1).max(365).optional().default(7) + caId: z.string().uuid().optional() }), response: { 200: z.object({ @@ -150,7 +148,7 @@ export const registerCertificateProfilesRouter = async (server: FastifyZodProvid .object({ id: z.string(), autoRenew: z.boolean(), - autoRenewDays: z.number().optional() + renewBeforeDays: z.number().optional() }) .optional() }).array(), @@ -195,10 +193,6 @@ export const registerCertificateProfilesRouter = async (server: FastifyZodProvid params: z.object({ id: z.string().uuid() }), - querystring: z.object({ - includeMetrics: z.coerce.boolean().optional().default(false), - expiringDays: z.coerce.number().min(1).max(365).optional().default(7) - }), response: { 200: z.object({ certificateProfile: PkiCertificateProfilesSchema.extend({ @@ -230,17 +224,7 @@ export const registerCertificateProfilesRouter = async (server: FastifyZodProvid .object({ id: z.string(), autoRenew: z.boolean(), - autoRenewDays: z.number().optional() - }) - .optional(), - metrics: z - .object({ - profileId: z.string(), - totalCertificates: z.number(), - activeCertificates: z.number(), - expiredCertificates: z.number(), - expiringCertificates: z.number(), - revokedCertificates: z.number() + renewBeforeDays: z.number().optional() }) .optional() }) @@ -257,20 +241,6 @@ export const registerCertificateProfilesRouter = async (server: FastifyZodProvid profileId: req.params.id }); - let result = certificateProfile; - - if (req.query.includeMetrics) { - const metrics = await server.services.certificateProfile.getProfileMetrics({ - actor: req.permission.type, - actorId: req.permission.id, - actorAuthMethod: req.permission.authMethod, - actorOrgId: req.permission.orgId, - profileId: req.params.id, - expiringDays: req.query.expiringDays - }); - result = { ...certificateProfile, metrics }; - } - await server.services.auditLog.createAuditLog({ ...req.auditLogInfo, projectId: certificateProfile.projectId, @@ -283,7 +253,7 @@ export const registerCertificateProfilesRouter = async (server: FastifyZodProvid } }); - return { certificateProfile: result }; + return { certificateProfile }; } }); @@ -355,7 +325,7 @@ export const registerCertificateProfilesRouter = async (server: FastifyZodProvid apiConfig: z .object({ autoRenew: z.boolean().default(false), - autoRenewDays: z.number().min(1).max(365).optional() + renewBeforeDays: z.number().min(1).max(30).optional() }) .optional() }) diff --git a/backend/src/server/routes/v1/organization-router.ts b/backend/src/server/routes/v1/organization-router.ts index 76b3eae51..d4b0058f9 100644 --- a/backend/src/server/routes/v1/organization-router.ts +++ b/backend/src/server/routes/v1/organization-router.ts @@ -323,7 +323,11 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => { .min(1, "Max Shared Secret view count cannot be lower than 1") .max(1000, "Max Shared Secret view count cannot exceed 1000") .nullable() + .optional(), + blockDuplicateSecretSyncDestinations: z + .boolean() .optional() + .describe("Block duplicate secret sync destinations across the organization") }), response: { 200: z.object({ diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts index 3f803a1e0..6460b7d65 100644 --- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts +++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts @@ -26,7 +26,7 @@ export const registerSyncPkiEndpoints = ({ syncOptions?: Record; description?: string; isAutoSyncEnabled?: boolean; - subscriberId?: string; + subscriberId?: string | null; }>; updateSchema: z.ZodType<{ connectionId?: string; @@ -35,7 +35,7 @@ export const registerSyncPkiEndpoints = ({ syncOptions?: Record; description?: string; isAutoSyncEnabled?: boolean; - subscriberId?: string; + subscriberId?: string | null; }>; responseSchema: z.ZodTypeAny; syncOptions: { diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts index 158d9e4dc..0710a91fc 100644 --- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts +++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts @@ -2,10 +2,11 @@ import { z } from "zod"; import { EventType } from "@app/ee/services/audit-log/audit-log-types"; import { ApiDocsTags } from "@app/lib/api-docs"; -import { readLimit } from "@app/server/config/rateLimiter"; +import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; import { AppConnection } from "@app/services/app-connection/app-connection-enums"; import { AuthMode } from "@app/services/auth/auth-type"; +import { CertificateSyncStatus } from "@app/services/certificate-sync/certificate-sync-enums"; import { PkiSync } from "@app/services/pki-sync/pki-sync-enums"; const PkiSyncSchema = z.object({ @@ -60,7 +61,8 @@ const PkiSyncSchema = z.object({ name: z.string() }) .nullable() - .optional() + .optional(), + hasCertificate: z.boolean().optional() }); const PkiSyncOptionsSchema = z.object({ @@ -76,6 +78,27 @@ const PkiSyncOptionsSchema = z.object({ minCertificateNameLength: z.number().optional() }); +const PkiSyncCertificateSchema = z.object({ + id: z.string().uuid(), + pkiSyncId: z.string().uuid(), + certificateId: z.string().uuid(), + syncStatus: z.nativeEnum(CertificateSyncStatus), + lastSyncMessage: z.string().nullable().optional(), + lastSyncedAt: z.date().nullable().optional(), + createdAt: z.date(), + updatedAt: z.date(), + certificateSerialNumber: z.string().optional(), + certificateCommonName: z.string().optional(), + certificateAltNames: z.string().optional(), + certificateStatus: z.string().optional(), + certificateNotBefore: z.date().optional(), + certificateNotAfter: z.date().optional(), + certificateRenewBeforeDays: z.number().nullish(), + certificateRenewalError: z.string().nullish(), + pkiSyncName: z.string().optional(), + pkiSyncDestination: z.string().optional() +}); + export const registerPkiSyncRouter = async (server: FastifyZodProvider) => { server.route({ method: "GET", @@ -111,7 +134,8 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider) => { tags: [ApiDocsTags.PkiSyncs], description: "List all the PKI Syncs for the specified project.", querystring: z.object({ - projectId: z.string().trim().min(1) + projectId: z.string().trim().min(1), + certificateId: z.string().uuid().optional() }), response: { 200: z.object({ pkiSyncs: PkiSyncSchema.array() }) @@ -120,11 +144,11 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider) => { onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), handler: async (req) => { const { - query: { projectId }, + query: { projectId, certificateId }, permission } = req; - const pkiSyncs = await server.services.pkiSync.listPkiSyncsByProjectId({ projectId }, permission); + const pkiSyncs = await server.services.pkiSync.listPkiSyncsByProjectId({ projectId, certificateId }, permission); await server.services.auditLog.createAuditLog({ ...req.auditLogInfo, @@ -179,4 +203,163 @@ export const registerPkiSyncRouter = async (server: FastifyZodProvider) => { return pkiSync; } }); + + server.route({ + method: "GET", + url: "/:pkiSyncId/certificates", + config: { + rateLimit: readLimit + }, + schema: { + hide: false, + tags: [ApiDocsTags.PkiSyncs], + description: "List all certificates associated with a PKI Sync.", + params: z.object({ + pkiSyncId: z.string().uuid() + }), + querystring: z.object({ + offset: z.coerce.number().min(0).default(0), + limit: z.coerce.number().min(1).max(100).default(20) + }), + response: { + 200: z.object({ + certificates: PkiSyncCertificateSchema.array(), + totalCount: z.number() + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + handler: async (req) => { + const { pkiSyncId } = req.params; + const { offset, limit } = req.query; + + const { certificates, totalCount, pkiSyncInfo } = await server.services.pkiSync.listPkiSyncCertificates( + { pkiSyncId, offset, limit }, + req.permission + ); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: pkiSyncInfo.projectId, + event: { + type: EventType.GET_PKI_SYNC_CERTIFICATES, + metadata: { + syncId: pkiSyncId, + destination: pkiSyncInfo.destination, + count: certificates.length, + certificateIds: certificates.map((c) => c.certificateId) + } + } + }); + + return { certificates, totalCount }; + } + }); + + server.route({ + method: "POST", + url: "/:pkiSyncId/certificates", + config: { + rateLimit: writeLimit + }, + schema: { + hide: false, + tags: [ApiDocsTags.PkiSyncs], + description: "Add certificates to a PKI Sync.", + params: z.object({ + pkiSyncId: z.string().uuid() + }), + body: z.object({ + certificateIds: z.array(z.string().uuid()).min(1, "At least one certificate ID is required") + }), + response: { + 200: z.object({ + addedCertificates: z.array( + z.object({ + id: z.string().uuid(), + pkiSyncId: z.string().uuid(), + certificateId: z.string().uuid(), + syncStatus: z.string().default("pending").optional().nullable(), + lastSyncMessage: z.string().optional().nullable(), + lastSyncedAt: z.date().optional().nullable(), + createdAt: z.date(), + updatedAt: z.date() + }) + ) + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + handler: async (req) => { + const { pkiSyncId } = req.params; + const { certificateIds } = req.body; + + const { addedCertificates, pkiSyncInfo } = await server.services.pkiSync.addCertificatesToPkiSync( + { pkiSyncId, certificateIds }, + req.permission + ); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: pkiSyncInfo.projectId, + event: { + type: EventType.UPDATE_PKI_SYNC, + metadata: { + pkiSyncId, + name: pkiSyncInfo.name + } + } + }); + + return { addedCertificates }; + } + }); + + server.route({ + method: "DELETE", + url: "/:pkiSyncId/certificates", + config: { + rateLimit: writeLimit + }, + schema: { + hide: false, + tags: [ApiDocsTags.PkiSyncs], + description: "Remove certificates from a PKI Sync.", + params: z.object({ + pkiSyncId: z.string().uuid() + }), + body: z.object({ + certificateIds: z.array(z.string().uuid()).min(1, "At least one certificate ID is required") + }), + response: { + 200: z.object({ + removedCount: z.number() + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + handler: async (req) => { + const { pkiSyncId } = req.params; + const { certificateIds } = req.body; + + const { removedCount, pkiSyncInfo } = await server.services.pkiSync.removeCertificatesFromPkiSync( + { pkiSyncId, certificateIds }, + req.permission + ); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: pkiSyncInfo.projectId, + event: { + type: EventType.UPDATE_PKI_SYNC, + metadata: { + pkiSyncId, + name: pkiSyncInfo.name + } + } + }); + + return { removedCount }; + } + }); }; diff --git a/backend/src/server/routes/v1/project-router.ts b/backend/src/server/routes/v1/project-router.ts index 3bd050ac8..70548395d 100644 --- a/backend/src/server/routes/v1/project-router.ts +++ b/backend/src/server/routes/v1/project-router.ts @@ -1201,12 +1201,17 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => { querystring: z.object({ friendlyName: z.string().optional().describe(PROJECTS.LIST_CERTIFICATES.friendlyName), commonName: z.string().optional().describe(PROJECTS.LIST_CERTIFICATES.commonName), - offset: z.coerce.number().min(0).max(100).default(0).describe(PROJECTS.LIST_CERTIFICATES.offset), - limit: z.coerce.number().min(1).max(100).default(25).describe(PROJECTS.LIST_CERTIFICATES.limit) + offset: z.coerce.number().min(0).default(0).describe(PROJECTS.LIST_CERTIFICATES.offset), + limit: z.coerce.number().min(1).max(100).default(25).describe(PROJECTS.LIST_CERTIFICATES.limit), + forPkiSync: z.coerce + .boolean() + .default(false) + .optional() + .describe("Retrieve only certificates available for PKI sync") }), response: { 200: z.object({ - certificates: z.array(CertificatesSchema), + certificates: z.array(CertificatesSchema.extend({ hasPrivateKey: z.boolean() })), totalCount: z.number() }) } diff --git a/backend/src/server/routes/v1/secret-sync-routers/chef-sync-router.ts b/backend/src/server/routes/v1/secret-sync-routers/chef-sync-router.ts new file mode 100644 index 000000000..6972a9b70 --- /dev/null +++ b/backend/src/server/routes/v1/secret-sync-routers/chef-sync-router.ts @@ -0,0 +1,13 @@ +import { ChefSyncSchema, CreateChefSyncSchema, UpdateChefSyncSchema } from "@app/services/secret-sync/chef"; +import { SecretSync } from "@app/services/secret-sync/secret-sync-enums"; + +import { registerSyncSecretsEndpoints } from "./secret-sync-endpoints"; + +export const registerChefSyncRouter = async (server: FastifyZodProvider) => + registerSyncSecretsEndpoints({ + destination: SecretSync.Chef, + server, + responseSchema: ChefSyncSchema, + createSchema: CreateChefSyncSchema, + updateSchema: UpdateChefSyncSchema + }); diff --git a/backend/src/server/routes/v1/secret-sync-routers/index.ts b/backend/src/server/routes/v1/secret-sync-routers/index.ts index e778dbd7c..d305dc342 100644 --- a/backend/src/server/routes/v1/secret-sync-routers/index.ts +++ b/backend/src/server/routes/v1/secret-sync-routers/index.ts @@ -10,6 +10,7 @@ import { registerAzureKeyVaultSyncRouter } from "./azure-key-vault-sync-router"; import { registerBitbucketSyncRouter } from "./bitbucket-sync-router"; import { registerCamundaSyncRouter } from "./camunda-sync-router"; import { registerChecklySyncRouter } from "./checkly-sync-router"; +import { registerChefSyncRouter } from "./chef-sync-router"; import { registerCloudflarePagesSyncRouter } from "./cloudflare-pages-sync-router"; import { registerCloudflareWorkersSyncRouter } from "./cloudflare-workers-sync-router"; import { registerDatabricksSyncRouter } from "./databricks-sync-router"; @@ -23,6 +24,7 @@ import { registerHerokuSyncRouter } from "./heroku-sync-router"; import { registerHumanitecSyncRouter } from "./humanitec-sync-router"; import { registerLaravelForgeSyncRouter } from "./laravel-forge-sync-router"; import { registerNetlifySyncRouter } from "./netlify-sync-router"; +import { registerNorthflankSyncRouter } from "./northflank-sync-router"; import { registerRailwaySyncRouter } from "./railway-sync-router"; import { registerRenderSyncRouter } from "./render-sync-router"; import { registerSupabaseSyncRouter } from "./supabase-sync-router"; @@ -64,6 +66,8 @@ export const SECRET_SYNC_REGISTER_ROUTER_MAP: Record + registerSyncSecretsEndpoints({ + destination: SecretSync.Northflank, + server, + responseSchema: NorthflankSyncSchema, + createSchema: CreateNorthflankSyncSchema, + updateSchema: UpdateNorthflankSyncSchema + }); diff --git a/backend/src/server/routes/v1/secret-sync-routers/secret-sync-router.ts b/backend/src/server/routes/v1/secret-sync-routers/secret-sync-router.ts index 1bfa32eeb..85adf12f1 100644 --- a/backend/src/server/routes/v1/secret-sync-routers/secret-sync-router.ts +++ b/backend/src/server/routes/v1/secret-sync-routers/secret-sync-router.ts @@ -24,6 +24,7 @@ import { AzureKeyVaultSyncListItemSchema, AzureKeyVaultSyncSchema } from "@app/s import { BitbucketSyncListItemSchema, BitbucketSyncSchema } from "@app/services/secret-sync/bitbucket"; import { CamundaSyncListItemSchema, CamundaSyncSchema } from "@app/services/secret-sync/camunda"; import { ChecklySyncListItemSchema, ChecklySyncSchema } from "@app/services/secret-sync/checkly/checkly-sync-schemas"; +import { ChefSyncListItemSchema, ChefSyncSchema } from "@app/services/secret-sync/chef"; import { CloudflarePagesSyncListItemSchema, CloudflarePagesSyncSchema @@ -46,6 +47,7 @@ import { HerokuSyncListItemSchema, HerokuSyncSchema } from "@app/services/secret import { HumanitecSyncListItemSchema, HumanitecSyncSchema } from "@app/services/secret-sync/humanitec"; import { LaravelForgeSyncListItemSchema, LaravelForgeSyncSchema } from "@app/services/secret-sync/laravel-forge"; import { NetlifySyncListItemSchema, NetlifySyncSchema } from "@app/services/secret-sync/netlify"; +import { NorthflankSyncListItemSchema, NorthflankSyncSchema } from "@app/services/secret-sync/northflank"; import { RailwaySyncListItemSchema, RailwaySyncSchema } from "@app/services/secret-sync/railway/railway-sync-schemas"; import { RenderSyncListItemSchema, RenderSyncSchema } from "@app/services/secret-sync/render/render-sync-schemas"; import { SupabaseSyncListItemSchema, SupabaseSyncSchema } from "@app/services/secret-sync/supabase"; @@ -85,8 +87,10 @@ const SecretSyncSchema = z.discriminatedUnion("destination", [ ChecklySyncSchema, DigitalOceanAppPlatformSyncSchema, NetlifySyncSchema, + NorthflankSyncSchema, BitbucketSyncSchema, - LaravelForgeSyncSchema + LaravelForgeSyncSchema, + ChefSyncSchema ]); const SecretSyncOptionsSchema = z.discriminatedUnion("destination", [ @@ -119,8 +123,10 @@ const SecretSyncOptionsSchema = z.discriminatedUnion("destination", [ ChecklySyncListItemSchema, SupabaseSyncListItemSchema, NetlifySyncListItemSchema, + NorthflankSyncListItemSchema, BitbucketSyncListItemSchema, - LaravelForgeSyncListItemSchema + LaravelForgeSyncListItemSchema, + ChefSyncListItemSchema ]); export const registerSecretSyncRouter = async (server: FastifyZodProvider) => { diff --git a/backend/src/server/routes/v1/sso-router.ts b/backend/src/server/routes/v1/sso-router.ts index 366fa331d..32b09b337 100644 --- a/backend/src/server/routes/v1/sso-router.ts +++ b/backend/src/server/routes/v1/sso-router.ts @@ -7,6 +7,7 @@ // All the any rules are disabled because passport typesense with fastify is really poor import { Authenticator } from "@fastify/passport"; +import { requestContext } from "@fastify/request-context"; import fastifySession from "@fastify/session"; import RedisStore from "connect-redis"; import { CronJob } from "cron"; @@ -21,6 +22,7 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors"; import { logger } from "@app/lib/logger"; import { ms } from "@app/lib/ms"; import { fetchGithubEmails, fetchGithubUser } from "@app/lib/requests/github"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { authRateLimit } from "@app/server/config/rateLimiter"; import { addAuthOriginDomainCookie } from "@app/server/lib/cookie"; import { AuthMethod } from "@app/services/auth/auth-type"; @@ -51,30 +53,54 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => { }, // eslint-disable-next-line async (req, _accessToken, _refreshToken, profile, cb) => { - try { - // @ts-expect-error this is because this is express type and not fastify - const callbackPort = req.session.get("callbackPort"); - // @ts-expect-error this is because this is express type and not fastify - const orgSlug = req.session.get("orgSlug"); + // @ts-expect-error this is because this is express type and not fastify + const callbackPort = req.session.get("callbackPort"); + // @ts-expect-error this is because this is express type and not fastify + const orgSlug = req.session.get("orgSlug"); - const email = profile?.emails?.[0]?.value; - if (!email) - throw new NotFoundError({ - message: "Email not found", - name: "OauthGoogleRegister" + const email = profile?.emails?.[0]?.value; + if (!email) + throw new NotFoundError({ + message: "Email not found", + name: "OauthGoogleRegister" + }); + + try { + const { isUserCompleted, providerAuthToken, user, orgId, orgName } = + await server.services.login.oauth2Login({ + email, + firstName: profile?.name?.givenName || "", + lastName: profile?.name?.familyName || "", + authMethod: AuthMethod.GOOGLE, + callbackPort, + orgSlug }); - const { isUserCompleted, providerAuthToken } = await server.services.login.oauth2Login({ - email, - firstName: profile?.name?.givenName || "", - lastName: profile?.name?.familyName || "", - authMethod: AuthMethod.GOOGLE, - callbackPort, - orgSlug - }); + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.user.email": email, + "infisical.user.id": user.id, + "infisical.organization.id": orgId, + "infisical.organization.name": orgName, + "infisical.auth.method": AuthAttemptAuthMethod.GOOGLE, + "infisical.auth.result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + cb(null, { isUserCompleted, providerAuthToken }); } catch (error) { logger.error(error); + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.user.email": email, + "infisical.auth.method": AuthAttemptAuthMethod.GOOGLE, + "infisical.auth.result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } cb(error as Error, false); } } @@ -101,27 +127,50 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => { }, // eslint-disable-next-line async (req: any, accessToken: string, _refreshToken: string, _profile: any, done: Function) => { + const ghEmails = await fetchGithubEmails(accessToken); + const { email } = ghEmails.filter((gitHubEmail) => gitHubEmail.primary)[0]; + + if (!email) throw new Error("No primary email found"); + try { - const ghEmails = await fetchGithubEmails(accessToken); - const { email } = ghEmails.filter((gitHubEmail) => gitHubEmail.primary)[0]; - - if (!email) throw new Error("No primary email found"); - // profile does not get automatically populated so we need to manually fetch user info - const user = await fetchGithubUser(accessToken); + const githubUser = await fetchGithubUser(accessToken); const callbackPort = req.session.get("callbackPort"); - const { isUserCompleted, providerAuthToken } = await server.services.login.oauth2Login({ - email, - firstName: user.name || user.login, - lastName: "", - authMethod: AuthMethod.GITHUB, - callbackPort - }); + const { isUserCompleted, providerAuthToken, user, orgId, orgName } = + await server.services.login.oauth2Login({ + email, + firstName: githubUser.name || githubUser.login, + lastName: "", + authMethod: AuthMethod.GITHUB, + callbackPort + }); + + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.user.email": email, + "infisical.user.id": user.id, + "infisical.organization.id": orgId, + "infisical.organization.name": orgName, + "infisical.auth.method": AuthAttemptAuthMethod.GITHUB, + "infisical.auth.result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } done(null, { isUserCompleted, providerAuthToken, externalProviderAccessToken: accessToken }); } catch (err) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.user.email": email, + "infisical.auth.method": AuthAttemptAuthMethod.GITHUB, + "infisical.auth.result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } logger.error(err); done(err as Error, false); } @@ -147,20 +196,45 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => { pkce: true }, async (req: any, _accessToken: string, _refreshToken: string, profile: any, cb: any) => { + const email = profile.emails[0].value; + try { const callbackPort = req.session.get("callbackPort"); - const email = profile.emails[0].value; - const { isUserCompleted, providerAuthToken } = await server.services.login.oauth2Login({ - email, - firstName: profile.displayName || profile.username || "", - lastName: "", - authMethod: AuthMethod.GITLAB, - callbackPort - }); + const { isUserCompleted, providerAuthToken, user, orgId, orgName } = + await server.services.login.oauth2Login({ + email, + firstName: profile.displayName || profile.username || "", + lastName: "", + authMethod: AuthMethod.GITLAB, + callbackPort + }); + + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.user.email": email, + "infisical.user.id": user.id, + "infisical.organization.id": orgId, + "infisical.organization.name": orgName, + "infisical.auth.method": AuthAttemptAuthMethod.GITLAB, + "infisical.auth.result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } return cb(null, { isUserCompleted, providerAuthToken }); } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.user.email": email, + "infisical.auth.method": AuthAttemptAuthMethod.GITLAB, + "infisical.auth.result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + logger.error(error); cb(error as Error, false); } diff --git a/backend/src/server/routes/v3/certificates-router.ts b/backend/src/server/routes/v3/certificates-router.ts index 549310738..d2d696596 100644 --- a/backend/src/server/routes/v3/certificates-router.ts +++ b/backend/src/server/routes/v3/certificates-router.ts @@ -18,6 +18,7 @@ import { CertKeyUsageType, CertSubjectAlternativeNameType } from "@app/services/certificate-common/certificate-constants"; +import { extractCertificateRequestFromCSR } from "@app/services/certificate-common/certificate-csr-utils"; import { mapEnumsForValidation } from "@app/services/certificate-common/certificate-utils"; import { validateTemplateRegexField } from "@app/services/certificate-template/certificate-template-validators"; @@ -84,8 +85,8 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) => }) ) .optional(), - signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(), - keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional() + signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm), + keyAlgorithm: z.nativeEnum(CertKeyAlgorithm) }) .refine(validateTtlAndDateFields, { message: @@ -169,9 +170,7 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) => .min(1, "TTL cannot be empty") .refine((val) => ms(val) > 0, "TTL must be a positive number"), notBefore: validateCaDateField.optional(), - notAfter: validateCaDateField.optional(), - signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(), - keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional() + notAfter: validateCaDateField.optional() }) .refine(validateTtlAndDateFields, { message: @@ -192,6 +191,8 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) => }, onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), handler: async (req) => { + const certificateRequest = extractCertificateRequestFromCSR(req.body.csr); + const data = await server.services.certificateV3.signCertificateFromProfile({ actor: req.permission.type, actorId: req.permission.id, @@ -203,9 +204,7 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) => ttl: req.body.ttl }, notBefore: req.body.notBefore ? new Date(req.body.notBefore) : undefined, - notAfter: req.body.notAfter ? new Date(req.body.notAfter) : undefined, - signatureAlgorithm: req.body.signatureAlgorithm, - keyAlgorithm: req.body.keyAlgorithm + notAfter: req.body.notAfter ? new Date(req.body.notAfter) : undefined }); await server.services.auditLog.createAuditLog({ @@ -217,7 +216,7 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) => certificateProfileId: req.body.profileId, certificateId: data.certificateId, profileName: data.profileName, - commonName: "" + commonName: certificateRequest.commonName || "" } } }); @@ -260,8 +259,8 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) => notBefore: validateCaDateField.optional(), notAfter: validateCaDateField.optional(), commonName: validateTemplateRegexField.optional(), - signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm).optional(), - keyAlgorithm: z.nativeEnum(CertKeyAlgorithm).optional() + signatureAlgorithm: z.nativeEnum(CertSignatureAlgorithm), + keyAlgorithm: z.nativeEnum(CertKeyAlgorithm) }) .refine(validateTtlAndDateFields, { message: @@ -343,4 +342,145 @@ export const registerCertificatesRouter = async (server: FastifyZodProvider) => return data; } }); + + server.route({ + method: "POST", + url: "/:certificateId/renew", + config: { + rateLimit: writeLimit + }, + schema: { + hide: false, + tags: [ApiDocsTags.PkiCertificates], + params: z.object({ + certificateId: z.string().uuid() + }), + response: { + 200: z.object({ + certificate: z.string().trim(), + issuingCaCertificate: z.string().trim(), + certificateChain: z.string().trim(), + privateKey: z.string().trim().optional(), + serialNumber: z.string().trim(), + certificateId: z.string() + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + handler: async (req) => { + const data = await server.services.certificateV3.renewCertificate({ + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + certificateId: req.params.certificateId + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: data.projectId, + event: { + type: EventType.RENEW_CERTIFICATE, + metadata: { + originalCertificateId: req.params.certificateId, + newCertificateId: data.certificateId, + profileName: data.profileName, + commonName: data.commonName + } + } + }); + + return data; + } + }); + + server.route({ + method: "PATCH", + url: "/:certificateId/config", + config: { + rateLimit: writeLimit + }, + schema: { + hide: false, + tags: [ApiDocsTags.PkiCertificates], + params: z.object({ + certificateId: z.string().uuid() + }), + body: z + .object({ + renewBeforeDays: z.number().int().min(1).max(30).optional(), + enableAutoRenewal: z.boolean().optional() + }) + .refine((data) => !(data.renewBeforeDays !== undefined && data.enableAutoRenewal === false), { + message: "Cannot specify both renewBeforeDays and enableAutoRenewal=false" + }), + response: { + 200: z.object({ + message: z.string(), + renewBeforeDays: z.number().optional() + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]), + handler: async (req) => { + if (req.body.enableAutoRenewal === false) { + const data = await server.services.certificateV3.disableRenewalConfig({ + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + certificateId: req.params.certificateId + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: data.projectId, + event: { + type: EventType.DISABLE_CERTIFICATE_RENEWAL_CONFIG, + metadata: { + certificateId: req.params.certificateId, + commonName: data.commonName + } + } + }); + + return { + message: "Auto-renewal disabled successfully" + }; + } + + if (req.body.renewBeforeDays !== undefined) { + const data = await server.services.certificateV3.updateRenewalConfig({ + actor: req.permission.type, + actorId: req.permission.id, + actorAuthMethod: req.permission.authMethod, + actorOrgId: req.permission.orgId, + certificateId: req.params.certificateId, + renewBeforeDays: req.body.renewBeforeDays + }); + + await server.services.auditLog.createAuditLog({ + ...req.auditLogInfo, + projectId: data.projectId, + event: { + type: EventType.UPDATE_CERTIFICATE_RENEWAL_CONFIG, + metadata: { + certificateId: req.params.certificateId, + renewBeforeDays: req.body.renewBeforeDays.toString(), + commonName: data.commonName + } + } + }); + + return { + message: "Certificate configuration updated successfully", + renewBeforeDays: data.renewBeforeDays + }; + } + + return { + message: "No configuration changes requested" + }; + } + }); }; diff --git a/backend/src/server/routes/v3/external-migration-router.ts b/backend/src/server/routes/v3/external-migration-router.ts index f0737e01d..367490c82 100644 --- a/backend/src/server/routes/v3/external-migration-router.ts +++ b/backend/src/server/routes/v3/external-migration-router.ts @@ -393,6 +393,56 @@ export const registerExternalMigrationRouter = async (server: FastifyZodProvider } }); + server.route({ + method: "GET", + url: "/vault/kubernetes-roles", + config: { + rateLimit: readLimit + }, + schema: { + querystring: z.object({ + namespace: z.string(), + mountPath: z.string() + }), + response: { + 200: z.object({ + roles: z.array( + z.object({ + name: z.string(), + mountPath: z.string(), + allowed_kubernetes_namespaces: z.array(z.string()).nullish(), + allowed_kubernetes_namespace_selector: z.string().nullish(), + token_max_ttl: z.number().nullish(), + token_default_ttl: z.number().nullish(), + token_default_audiences: z.array(z.string()).nullish(), + service_account_name: z.string().nullish(), + kubernetes_role_name: z.string().nullish(), + kubernetes_role_type: z.string().nullish(), + generated_role_rules: z.string().nullish(), + name_template: z.string().nullish(), + extra_annotations: z.record(z.string()).nullish(), + extra_labels: z.record(z.string()).nullish(), + config: z.object({ + kubernetes_host: z.string(), + kubernetes_ca_cert: z.string().nullish() + }) + }) + ) + }) + } + }, + onRequest: verifyAuth([AuthMode.JWT]), + handler: async (req) => { + const roles = await server.services.migration.getVaultKubernetesRoles({ + actor: req.permission, + namespace: req.query.namespace, + mountPath: req.query.mountPath + }); + + return { roles }; + } + }); + server.route({ method: "GET", url: "/vault/secret-paths", diff --git a/backend/src/services/app-connection/app-connection-enums.ts b/backend/src/services/app-connection/app-connection-enums.ts index 54b70c7d3..1c184a436 100644 --- a/backend/src/services/app-connection/app-connection-enums.ts +++ b/backend/src/services/app-connection/app-connection-enums.ts @@ -38,7 +38,9 @@ export enum AppConnection { Netlify = "netlify", Okta = "okta", Redis = "redis", - LaravelForge = "laravel-forge" + LaravelForge = "laravel-forge", + Chef = "chef", + Northflank = "northflank" } export enum AWSRegion { diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.ts index 464f718ce..3c511fd4d 100644 --- a/backend/src/services/app-connection/app-connection-fns.ts +++ b/backend/src/services/app-connection/app-connection-fns.ts @@ -68,6 +68,7 @@ import { } from "./bitbucket"; import { CamundaConnectionMethod, getCamundaConnectionListItem, validateCamundaConnectionCredentials } from "./camunda"; import { ChecklyConnectionMethod, getChecklyConnectionListItem, validateChecklyConnectionCredentials } from "./checkly"; +import { ChefConnectionMethod, getChefConnectionListItem, validateChefConnectionCredentials } from "./chef"; import { CloudflareConnectionMethod } from "./cloudflare/cloudflare-connection-enum"; import { getCloudflareConnectionListItem, @@ -113,6 +114,11 @@ import { getMsSqlConnectionListItem, MsSqlConnectionMethod } from "./mssql"; import { MySqlConnectionMethod } from "./mysql/mysql-connection-enums"; import { getMySqlConnectionListItem } from "./mysql/mysql-connection-fns"; import { getNetlifyConnectionListItem, validateNetlifyConnectionCredentials } from "./netlify"; +import { + getNorthflankConnectionListItem, + NorthflankConnectionMethod, + validateNorthflankConnectionCredentials +} from "./northflank"; import { getOktaConnectionListItem, OktaConnectionMethod, validateOktaConnectionCredentials } from "./okta"; import { getPostgresConnectionListItem, PostgresConnectionMethod } from "./postgres"; import { getRailwayConnectionListItem, validateRailwayConnectionCredentials } from "./railway"; @@ -203,8 +209,10 @@ export const listAppConnectionOptions = (projectType?: ProjectType) => { getSupabaseConnectionListItem(), getDigitalOceanConnectionListItem(), getNetlifyConnectionListItem(), + getNorthflankConnectionListItem(), getOktaConnectionListItem(), - getRedisConnectionListItem() + getRedisConnectionListItem(), + getChefConnectionListItem() ] .filter((option) => { switch (projectType) { @@ -332,8 +340,10 @@ export const validateAppConnectionCredentials = async ( [AppConnection.Checkly]: validateChecklyConnectionCredentials as TAppConnectionCredentialsValidator, [AppConnection.Supabase]: validateSupabaseConnectionCredentials as TAppConnectionCredentialsValidator, [AppConnection.DigitalOcean]: validateDigitalOceanConnectionCredentials as TAppConnectionCredentialsValidator, - [AppConnection.Okta]: validateOktaConnectionCredentials as TAppConnectionCredentialsValidator, [AppConnection.Netlify]: validateNetlifyConnectionCredentials as TAppConnectionCredentialsValidator, + [AppConnection.Northflank]: validateNorthflankConnectionCredentials as TAppConnectionCredentialsValidator, + [AppConnection.Okta]: validateOktaConnectionCredentials as TAppConnectionCredentialsValidator, + [AppConnection.Chef]: validateChefConnectionCredentials as TAppConnectionCredentialsValidator, [AppConnection.Redis]: validateRedisConnectionCredentials as TAppConnectionCredentialsValidator }; @@ -345,6 +355,8 @@ export const getAppConnectionMethodName = (method: TAppConnection["method"]) => case GitHubConnectionMethod.App: case GitHubRadarConnectionMethod.App: return "GitHub App"; + case GitHubConnectionMethod.Pat: + return "Personal Access Token"; case AzureKeyVaultConnectionMethod.OAuth: case AzureAppConfigurationConnectionMethod.OAuth: case AzureClientSecretsConnectionMethod.OAuth: @@ -374,6 +386,7 @@ export const getAppConnectionMethodName = (method: TAppConnection["method"]) => case BitbucketConnectionMethod.ApiToken: case ZabbixConnectionMethod.ApiToken: case DigitalOceanConnectionMethod.ApiToken: + case NorthflankConnectionMethod.ApiToken: case OktaConnectionMethod.ApiToken: case LaravelForgeConnectionMethod.ApiToken: return "API Token"; @@ -399,6 +412,8 @@ export const getAppConnectionMethodName = (method: TAppConnection["method"]) => case RenderConnectionMethod.ApiKey: case ChecklyConnectionMethod.ApiKey: return "API Key"; + case ChefConnectionMethod.UserKey: + return "User Key"; case SupabaseConnectionMethod.AccessToken: return "Access Token"; default: @@ -470,9 +485,11 @@ export const TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM: Record< [AppConnection.Supabase]: platformManagedCredentialsNotSupported, [AppConnection.DigitalOcean]: platformManagedCredentialsNotSupported, [AppConnection.Netlify]: platformManagedCredentialsNotSupported, + [AppConnection.Northflank]: platformManagedCredentialsNotSupported, [AppConnection.Okta]: platformManagedCredentialsNotSupported, [AppConnection.Redis]: platformManagedCredentialsNotSupported, - [AppConnection.LaravelForge]: platformManagedCredentialsNotSupported + [AppConnection.LaravelForge]: platformManagedCredentialsNotSupported, + [AppConnection.Chef]: platformManagedCredentialsNotSupported }; export const enterpriseAppCheck = async ( diff --git a/backend/src/services/app-connection/app-connection-maps.ts b/backend/src/services/app-connection/app-connection-maps.ts index c01d9d1b4..08ca0c681 100644 --- a/backend/src/services/app-connection/app-connection-maps.ts +++ b/backend/src/services/app-connection/app-connection-maps.ts @@ -40,7 +40,9 @@ export const APP_CONNECTION_NAME_MAP: Record = { [AppConnection.DigitalOcean]: "DigitalOcean App Platform", [AppConnection.Netlify]: "Netlify", [AppConnection.Okta]: "Okta", - [AppConnection.Redis]: "Redis" + [AppConnection.Redis]: "Redis", + [AppConnection.Chef]: "Chef", + [AppConnection.Northflank]: "Northflank" }; export const APP_CONNECTION_PLAN_MAP: Record = { @@ -83,5 +85,7 @@ export const APP_CONNECTION_PLAN_MAP: Record>>; @@ -320,8 +334,10 @@ export type TAppConnectionInput = { id: string } & ( | TSupabaseConnectionInput | TDigitalOceanConnectionInput | TNetlifyConnectionInput + | TNorthflankConnectionInput | TOktaConnectionInput | TRedisConnectionInput + | TChefConnectionInput ); export type TSqlConnectionInput = @@ -385,8 +401,10 @@ export type TAppConnectionConfig = | TSupabaseConnectionConfig | TDigitalOceanConnectionConfig | TNetlifyConnectionConfig + | TNorthflankConnectionConfig | TOktaConnectionConfig - | TRedisConnectionConfig; + | TRedisConnectionConfig + | TChefConnectionConfig; export type TValidateAppConnectionCredentialsSchema = | TValidateAwsConnectionCredentialsSchema @@ -427,8 +445,10 @@ export type TValidateAppConnectionCredentialsSchema = | TValidateSupabaseConnectionCredentialsSchema | TValidateDigitalOceanCredentialsSchema | TValidateNetlifyConnectionCredentialsSchema + | TValidateNorthflankConnectionCredentialsSchema | TValidateOktaConnectionCredentialsSchema - | TValidateRedisConnectionCredentialsSchema; + | TValidateRedisConnectionCredentialsSchema + | TValidateChefConnectionCredentialsSchema; export type TListAwsConnectionKmsKeys = { connectionId: string; diff --git a/backend/src/services/app-connection/chef/chef-connection-enums.ts b/backend/src/services/app-connection/chef/chef-connection-enums.ts new file mode 100644 index 000000000..58e59c3ba --- /dev/null +++ b/backend/src/services/app-connection/chef/chef-connection-enums.ts @@ -0,0 +1,3 @@ +export enum ChefConnectionMethod { + UserKey = "user-key" +} diff --git a/backend/src/services/app-connection/chef/chef-connection-fns.ts b/backend/src/services/app-connection/chef/chef-connection-fns.ts new file mode 100644 index 000000000..1b35628bc --- /dev/null +++ b/backend/src/services/app-connection/chef/chef-connection-fns.ts @@ -0,0 +1,288 @@ +import { AxiosError } from "axios"; +import crypto from "crypto"; + +import { request } from "@app/lib/config/request"; +import { BadRequestError } from "@app/lib/errors"; +import { removeTrailingSlash } from "@app/lib/fn"; +import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator"; +import { IntegrationUrls } from "@app/services/integration-auth/integration-list"; + +import { TChefDataBagItemContent } from "../../secret-sync/chef/chef-sync-types"; +import { AppConnection } from "../app-connection-enums"; +import { ChefConnectionMethod } from "./chef-connection-enums"; +import { + TChefConnection, + TChefConnectionConfig, + TChefDataBag, + TChefDataBagItem, + TGetChefDataBagItem, + TUpdateChefDataBagItem +} from "./chef-connection-types"; + +export const getChefServerUrl = async (serverUrl?: string) => { + const chefServerUrl = serverUrl ? removeTrailingSlash(serverUrl) : IntegrationUrls.CHEF_API_URL; + + await blockLocalAndPrivateIpAddresses(chefServerUrl); + + return chefServerUrl; +}; + +// Helper to ensure private key is in proper PEM format +const formatPrivateKey = (key: string): string => { + let formattedKey = key.trim(); + + // Ensure proper line breaks in PEM format (handle escaped newlines) + formattedKey = formattedKey.replace(/\\n/g, "\n"); + + // Remove any extra whitespace between lines + formattedKey = formattedKey.replace(/\n\s+/g, "\n"); + + // If key doesn't have headers, add PKCS#1 RSA headers + if (!formattedKey.includes("BEGIN")) { + formattedKey = `-----BEGIN RSA PRIVATE KEY-----\n${formattedKey}\n-----END RSA PRIVATE KEY-----`; + } + + // Ensure the key has proper line breaks after headers and before footers + formattedKey = formattedKey.replace(/(-----BEGIN[^-]+-----)\s*/g, "$1\n").replace(/\s*(-----END[^-]+-----)/g, "\n$1"); + + // Remove any duplicate newlines + formattedKey = formattedKey.replace(/\n{3,}/g, "\n\n"); + + return formattedKey; +}; + +const getChefAuthHeaders = ( + method: string, + path: string, + body: string, + userId: string, + privateKey: string, + apiVersion: "1.0" | "1.3" = "1.3" +) => { + const timestamp = new Date().toISOString().replace(/\.\d{3}Z$/, "Z"); // Remove milliseconds from timestamp + + // Calculate content hash based on version + let contentHash: string; + if (apiVersion === "1.3") { + contentHash = crypto.createHash("sha256").update(body).digest("base64"); + } else { + contentHash = crypto.createHash("sha1").update(body).digest("base64"); + } + + // Build canonical request based on version + let canonicalRequest: string; + if (apiVersion === "1.3") { + canonicalRequest = [ + `Method:${method}`, + `Path:${path}`, + `X-Ops-Content-Hash:${contentHash}`, + "X-Ops-Sign:version=1.3", + `X-Ops-Timestamp:${timestamp}`, + `X-Ops-UserId:${userId}`, + "X-Ops-Server-API-Version:1" + ].join("\n"); + } else { + const hashedPath = crypto.createHash("sha1").update(path).digest("base64"); + canonicalRequest = [ + `Method:${method}`, + `Hashed Path:${hashedPath}`, + `X-Ops-Content-Hash:${contentHash}`, + `X-Ops-Timestamp:${timestamp}`, + `X-Ops-UserId:${userId}` + ].join("\n"); + } + + // Format the private key properly + const formattedKey = formatPrivateKey(privateKey); + + // Sign the canonical request + const sign = crypto.createSign(apiVersion === "1.3" ? "RSA-SHA256" : "RSA-SHA1"); + sign.update(canonicalRequest); + const signature = sign.sign(formattedKey, "base64"); + + // Split signature into 60-character chunks + const authHeaders: Record = {}; + const signatureLines = signature.match(/.{1,60}/g) || []; + signatureLines.forEach((line, index) => { + authHeaders[`X-Ops-Authorization-${index + 1}`] = line; + }); + + return { + Accept: "application/json", + "Content-Type": "application/json", + "X-Chef-Version": "14.0.0", + "X-Ops-Timestamp": timestamp, + "X-Ops-UserId": userId, + "X-Ops-Sign": apiVersion === "1.3" ? "version=1.3" : "algorithm=sha1;version=1.0", + "X-Ops-Content-Hash": contentHash, + ...(apiVersion === "1.3" && { "X-Ops-Server-API-Version": "1" }), + ...authHeaders + }; +}; + +export const getChefConnectionListItem = () => { + return { + name: "Chef" as const, + app: AppConnection.Chef as const, + methods: Object.values(ChefConnectionMethod) as [ChefConnectionMethod.UserKey] + }; +}; + +export const validateChefConnectionCredentials = async (config: TChefConnectionConfig) => { + const { credentials: inputCredentials } = config; + + try { + const path = `/organizations/${inputCredentials.orgName}/users/${inputCredentials.userName}`; + + const hostServerUrl = await getChefServerUrl(inputCredentials.serverUrl); + + const headers = getChefAuthHeaders("GET", path, "", inputCredentials.userName, inputCredentials.privateKey); + + await request.get(`${hostServerUrl}${path}`, { + headers + }); + } catch (error: unknown) { + if (error instanceof AxiosError) { + throw new BadRequestError({ + message: `Failed to validate Chef credentials: ${error.message || "Unknown error"}` + }); + } + throw new BadRequestError({ + message: "Unable to validate Chef connection: verify credentials" + }); + } + + return inputCredentials; +}; + +export const listChefDataBags = async (appConnection: TChefConnection): Promise => { + const { + credentials: { serverUrl, userName, privateKey, orgName } + } = appConnection; + + try { + const path = `/organizations/${orgName}/data`; + const body = ""; + + const hostServerUrl = await getChefServerUrl(serverUrl); + + const headers = getChefAuthHeaders("GET", path, body, userName, privateKey); + + const res = await request.get>(`${hostServerUrl}${path}`, { + headers + }); + + return Object.keys(res.data).map((name) => ({ + name + })); + } catch (error) { + if (error instanceof AxiosError) { + throw new BadRequestError({ + message: `Failed to list Chef data bags: ${error.message || "Unknown error"}` + }); + } + throw new BadRequestError({ + message: "Unable to list Chef data bags" + }); + } +}; + +export const listChefDataBagItems = async ( + appConnection: TChefConnection, + dataBagName: string +): Promise => { + const { + credentials: { serverUrl, userName, privateKey, orgName } + } = appConnection; + + try { + const path = `/organizations/${orgName}/data/${dataBagName}`; + const body = ""; + + const hostServerUrl = await getChefServerUrl(serverUrl); + + const headers = getChefAuthHeaders("GET", path, body, userName, privateKey); + + const res = await request.get>(`${hostServerUrl}${path}`, { + headers + }); + + return Object.keys(res.data).map((name) => ({ + name + })); + } catch (error) { + if (error instanceof AxiosError) { + throw new BadRequestError({ + message: `Failed to list Chef data bag items: ${error.message || "Unknown error"}` + }); + } + throw new BadRequestError({ + message: "Unable to list Chef data bag items" + }); + } +}; + +export const getChefDataBagItem = async ({ + serverUrl, + userName, + privateKey, + orgName, + dataBagName, + dataBagItemName +}: TGetChefDataBagItem): Promise => { + try { + const path = `/organizations/${orgName}/data/${dataBagName}/${dataBagItemName}`; + const body = ""; + + const hostServerUrl = await getChefServerUrl(serverUrl); + + const headers = getChefAuthHeaders("GET", path, body, userName, privateKey); + + const res = await request.get(`${hostServerUrl}${path}`, { + headers + }); + + return res.data; + } catch (error) { + if (error instanceof AxiosError) { + throw new BadRequestError({ + message: `Failed to get Chef data bag item: ${error.message || "Unknown error"}` + }); + } + throw new BadRequestError({ + message: "Unable to get Chef data bag item" + }); + } +}; + +export const updateChefDataBagItem = async ({ + serverUrl, + userName, + privateKey, + orgName, + dataBagName, + dataBagItemName, + data +}: TUpdateChefDataBagItem): Promise => { + try { + const path = `/organizations/${orgName}/data/${dataBagName}/${dataBagItemName}`; + const body = JSON.stringify(data); + + const hostServerUrl = await getChefServerUrl(serverUrl); + + const headers = getChefAuthHeaders("PUT", path, body, userName, privateKey); + + await request.put(`${hostServerUrl}${path}`, data, { + headers + }); + } catch (error) { + if (error instanceof AxiosError) { + throw new BadRequestError({ + message: `Failed to update Chef data bag item: ${error.message || "Unknown error"}` + }); + } + throw new BadRequestError({ + message: "Unable to update Chef data bag item" + }); + } +}; diff --git a/backend/src/services/app-connection/chef/chef-connection-schemas.ts b/backend/src/services/app-connection/chef/chef-connection-schemas.ts new file mode 100644 index 000000000..e5a3687a2 --- /dev/null +++ b/backend/src/services/app-connection/chef/chef-connection-schemas.ts @@ -0,0 +1,77 @@ +import z from "zod"; + +import { AppConnections } from "@app/lib/api-docs"; +import { AppConnection } from "@app/services/app-connection/app-connection-enums"; +import { + BaseAppConnectionSchema, + GenericCreateAppConnectionFieldsSchema, + GenericUpdateAppConnectionFieldsSchema +} from "@app/services/app-connection/app-connection-schemas"; + +import { ChefConnectionMethod } from "./chef-connection-enums"; + +export const ChefConnectionUserKeyCredentialsSchema = z.object({ + serverUrl: z + .string() + .trim() + .url("Valid Chef Server URL required") + .optional() + .describe(AppConnections.CREDENTIALS.CHEF.serverUrl), + orgName: z + .string() + .trim() + .min(1, "Organization name required") + .max(256, "Organization name cannot exceed 256 characters") + .describe(AppConnections.CREDENTIALS.CHEF.orgName), + userName: z + .string() + .trim() + .min(1, "User name required") + .max(256, "User name cannot exceed 256 characters") + .describe(AppConnections.CREDENTIALS.CHEF.userName), + privateKey: z + .string() + .trim() + .min(1, "Private key required") + .max(16384, "Private key cannot exceed 16384 characters") + .describe(AppConnections.CREDENTIALS.CHEF.privateKey) +}); + +const BaseChefConnectionSchema = BaseAppConnectionSchema.extend({ app: z.literal(AppConnection.Chef) }); + +export const ChefConnectionSchema = BaseChefConnectionSchema.extend({ + method: z.literal(ChefConnectionMethod.UserKey), + credentials: ChefConnectionUserKeyCredentialsSchema +}); + +export const SanitizedChefConnectionSchema = z.discriminatedUnion("method", [ + BaseChefConnectionSchema.extend({ + method: z.literal(ChefConnectionMethod.UserKey), + credentials: ChefConnectionUserKeyCredentialsSchema.pick({ serverUrl: true, orgName: true, userName: true }) + }) +]); + +export const ValidateChefConnectionCredentialsSchema = z.discriminatedUnion("method", [ + z.object({ + method: z.literal(ChefConnectionMethod.UserKey).describe(AppConnections.CREATE(AppConnection.Chef).method), + credentials: ChefConnectionUserKeyCredentialsSchema.describe(AppConnections.CREATE(AppConnection.Chef).credentials) + }) +]); + +export const CreateChefConnectionSchema = ValidateChefConnectionCredentialsSchema.and( + GenericCreateAppConnectionFieldsSchema(AppConnection.Chef) +); + +export const UpdateChefConnectionSchema = z + .object({ + credentials: ChefConnectionUserKeyCredentialsSchema.optional().describe( + AppConnections.UPDATE(AppConnection.Chef).credentials + ) + }) + .and(GenericUpdateAppConnectionFieldsSchema(AppConnection.Chef)); + +export const ChefConnectionListItemSchema = z.object({ + name: z.literal("Chef"), + app: z.literal(AppConnection.Chef), + methods: z.nativeEnum(ChefConnectionMethod).array() +}); diff --git a/backend/src/services/app-connection/chef/chef-connection-service.ts b/backend/src/services/app-connection/chef/chef-connection-service.ts new file mode 100644 index 000000000..c989e7eaf --- /dev/null +++ b/backend/src/services/app-connection/chef/chef-connection-service.ts @@ -0,0 +1,39 @@ +import { ForbiddenRequestError } from "@app/lib/errors"; +import { OrgServiceActor } from "@app/lib/types"; + +import { AppConnection } from "../app-connection-enums"; +import { listChefDataBagItems, listChefDataBags } from "./chef-connection-fns"; +import { TChefConnection } from "./chef-connection-types"; + +type TGetAppConnectionFunc = ( + app: AppConnection, + connectionId: string, + actor: OrgServiceActor +) => Promise; + +export const chefConnectionService = (getAppConnection: TGetAppConnectionFunc) => { + const listDataBags = async (appConnectionId: string, actor: OrgServiceActor) => { + const appConnection = await getAppConnection(AppConnection.Chef, appConnectionId, actor); + + if (!appConnection) { + throw new ForbiddenRequestError({ message: "App connection not found" }); + } + + return listChefDataBags(appConnection); + }; + + const listDataBagItems = async (appConnectionId: string, dataBagName: string, actor: OrgServiceActor) => { + const appConnection = await getAppConnection(AppConnection.Chef, appConnectionId, actor); + + if (!appConnection) { + throw new ForbiddenRequestError({ message: "App connection not found" }); + } + + return listChefDataBagItems(appConnection, dataBagName); + }; + + return { + listDataBags, + listDataBagItems + }; +}; diff --git a/backend/src/services/app-connection/chef/chef-connection-types.ts b/backend/src/services/app-connection/chef/chef-connection-types.ts new file mode 100644 index 000000000..a2da80d3d --- /dev/null +++ b/backend/src/services/app-connection/chef/chef-connection-types.ts @@ -0,0 +1,50 @@ +import z from "zod"; + +import { DiscriminativePick } from "@app/lib/types"; +import { TChefDataBagItemContent } from "@app/services/secret-sync/chef"; + +import { AppConnection } from "../app-connection-enums"; +import { + ChefConnectionSchema, + CreateChefConnectionSchema, + ValidateChefConnectionCredentialsSchema +} from "./chef-connection-schemas"; + +export type TChefConnection = z.infer; + +export type TChefConnectionInput = z.infer & { + app: AppConnection.Chef; +}; + +export type TValidateChefConnectionCredentialsSchema = typeof ValidateChefConnectionCredentialsSchema; + +export type TChefConnectionConfig = DiscriminativePick & { + orgName: string; +}; + +export type TChefDataBag = { + name: string; +}; + +export type TChefDataBagItem = { + name: string; +}; + +export type TGetChefDataBagItem = { + serverUrl?: string; + userName: string; + privateKey: string; + orgName: string; + dataBagName: string; + dataBagItemName: string; +}; + +export type TUpdateChefDataBagItem = { + serverUrl?: string; + userName: string; + privateKey: string; + orgName: string; + dataBagName: string; + dataBagItemName: string; + data: TChefDataBagItemContent; +}; diff --git a/backend/src/services/app-connection/chef/index.ts b/backend/src/services/app-connection/chef/index.ts new file mode 100644 index 000000000..e02479d0e --- /dev/null +++ b/backend/src/services/app-connection/chef/index.ts @@ -0,0 +1,4 @@ +export * from "./chef-connection-enums"; +export * from "./chef-connection-fns"; +export * from "./chef-connection-schemas"; +export * from "./chef-connection-types"; diff --git a/backend/src/services/app-connection/github/github-connection-enums.ts b/backend/src/services/app-connection/github/github-connection-enums.ts index 77a4eebac..18dac354f 100644 --- a/backend/src/services/app-connection/github/github-connection-enums.ts +++ b/backend/src/services/app-connection/github/github-connection-enums.ts @@ -1,4 +1,5 @@ export enum GitHubConnectionMethod { OAuth = "oauth", - App = "github-app" + App = "github-app", + Pat = "pat" } diff --git a/backend/src/services/app-connection/github/github-connection-fns.ts b/backend/src/services/app-connection/github/github-connection-fns.ts index 5cbf5c60d..806df039f 100644 --- a/backend/src/services/app-connection/github/github-connection-fns.ts +++ b/backend/src/services/app-connection/github/github-connection-fns.ts @@ -248,10 +248,18 @@ export const makePaginatedGitHubRequest = async ( ): Promise => { const { credentials, method } = appConnection; - const token = - method === GitHubConnectionMethod.OAuth - ? credentials.accessToken - : await getGitHubAppAuthToken(appConnection, gatewayService, gatewayV2Service); + let token: string; + + switch (method) { + case GitHubConnectionMethod.OAuth: + token = credentials.accessToken; + break; + case GitHubConnectionMethod.Pat: + token = credentials.personalAccessToken; + break; + default: + token = await getGitHubAppAuthToken(appConnection, gatewayService, gatewayV2Service); + } const baseUrl = `https://${await getGitHubInstanceApiUrl(appConnection)}${path}`; const initialUrlObj = new URL(baseUrl); @@ -460,6 +468,35 @@ export const validateGitHubConnectionCredentials = async ( gatewayV2Service: Pick ) => { const { credentials, method } = config; + + // PAT validation + if (method === GitHubConnectionMethod.Pat) { + try { + const apiUrl = await getGitHubInstanceApiUrl(config); + await requestWithGitHubGateway(config, gatewayService, gatewayV2Service, { + url: `https://${apiUrl}/user`, + method: "GET", + headers: { + Accept: "application/vnd.github+json", + Authorization: `Bearer ${credentials.personalAccessToken}`, + "X-GitHub-Api-Version": "2022-11-28" + } + }); + + return { + personalAccessToken: credentials.personalAccessToken, + instanceType: credentials.instanceType, + host: credentials.host + }; + } catch (e: unknown) { + logger.error(e, "Unable to verify GitHub PAT connection"); + + throw new BadRequestError({ + message: "Unable to validate Personal Access Token: verify token has proper permissions" + }); + } + } + const { INF_APP_CONNECTION_GITHUB_OAUTH_CLIENT_ID, INF_APP_CONNECTION_GITHUB_OAUTH_CLIENT_SECRET, diff --git a/backend/src/services/app-connection/github/github-connection-schemas.ts b/backend/src/services/app-connection/github/github-connection-schemas.ts index 1b8aa9c3f..20ef2c0e0 100644 --- a/backend/src/services/app-connection/github/github-connection-schemas.ts +++ b/backend/src/services/app-connection/github/github-connection-schemas.ts @@ -38,6 +38,19 @@ export const GitHubConnectionAppInputCredentialsSchema = z.union([ }) ]); +export const GitHubConnectionPatInputCredentialsSchema = z.union([ + z.object({ + personalAccessToken: z.string().trim().min(1, "Personal Access Token required"), + instanceType: z.literal("server"), + host: z.string().trim().min(1, "Host is required for server instance type") + }), + z.object({ + personalAccessToken: z.string().trim().min(1, "Personal Access Token required"), + instanceType: z.literal("cloud").optional(), + host: z.string().trim().optional() + }) +]); + export const GitHubConnectionOAuthOutputCredentialsSchema = z.union([ z.object({ accessToken: z.string(), @@ -64,6 +77,19 @@ export const GitHubConnectionAppOutputCredentialsSchema = z.union([ }) ]); +export const GitHubConnectionPatOutputCredentialsSchema = z.union([ + z.object({ + personalAccessToken: z.string(), + instanceType: z.literal("server"), + host: z.string().trim().min(1) + }), + z.object({ + personalAccessToken: z.string(), + instanceType: z.literal("cloud").optional(), + host: z.string().trim().optional() + }) +]); + export const ValidateGitHubConnectionCredentialsSchema = z.discriminatedUnion("method", [ z.object({ method: z.literal(GitHubConnectionMethod.App).describe(AppConnections.CREATE(AppConnection.GitHub).method), @@ -76,6 +102,12 @@ export const ValidateGitHubConnectionCredentialsSchema = z.discriminatedUnion("m credentials: GitHubConnectionOAuthInputCredentialsSchema.describe( AppConnections.CREATE(AppConnection.GitHub).credentials ) + }), + z.object({ + method: z.literal(GitHubConnectionMethod.Pat).describe(AppConnections.CREATE(AppConnection.GitHub).method), + credentials: GitHubConnectionPatInputCredentialsSchema.describe( + AppConnections.CREATE(AppConnection.GitHub).credentials + ) }) ]); @@ -88,7 +120,11 @@ export const CreateGitHubConnectionSchema = ValidateGitHubConnectionCredentialsS export const UpdateGitHubConnectionSchema = z .object({ credentials: z - .union([GitHubConnectionAppInputCredentialsSchema, GitHubConnectionOAuthInputCredentialsSchema]) + .union([ + GitHubConnectionAppInputCredentialsSchema, + GitHubConnectionOAuthInputCredentialsSchema, + GitHubConnectionPatInputCredentialsSchema + ]) .optional() .describe(AppConnections.UPDATE(AppConnection.GitHub).credentials) }) @@ -110,6 +146,10 @@ export const GitHubConnectionSchema = z.intersection( z.object({ method: z.literal(GitHubConnectionMethod.OAuth), credentials: GitHubConnectionOAuthOutputCredentialsSchema + }), + z.object({ + method: z.literal(GitHubConnectionMethod.Pat), + credentials: GitHubConnectionPatOutputCredentialsSchema }) ]) ); @@ -128,6 +168,13 @@ export const SanitizedGitHubConnectionSchema = z.discriminatedUnion("method", [ instanceType: z.union([z.literal("server"), z.literal("cloud")]).optional(), host: z.string().optional() }) + }), + BaseGitHubConnectionSchema.extend({ + method: z.literal(GitHubConnectionMethod.Pat), + credentials: z.object({ + instanceType: z.union([z.literal("server"), z.literal("cloud")]).optional(), + host: z.string().optional() + }) }) ]); diff --git a/backend/src/services/app-connection/gitlab/gitlab-connection-enums.ts b/backend/src/services/app-connection/gitlab/gitlab-connection-enums.ts index 3bd01d147..f409a61cf 100644 --- a/backend/src/services/app-connection/gitlab/gitlab-connection-enums.ts +++ b/backend/src/services/app-connection/gitlab/gitlab-connection-enums.ts @@ -5,5 +5,6 @@ export enum GitLabConnectionMethod { export enum GitLabAccessTokenType { Project = "project", - Personal = "personal" + Personal = "personal", + Group = "group" } diff --git a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts index 425c9c4d2..5eb9202fd 100644 --- a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts +++ b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts @@ -21,6 +21,8 @@ import { THCVaultKubernetesAuthConfig, THCVaultKubernetesAuthRole, THCVaultKubernetesAuthRoleWithConfig, + THCVaultKubernetesRole, + THCVaultKubernetesSecretsConfig, THCVaultMount, THCVaultMountResponse } from "./hc-vault-connection-types"; @@ -816,3 +818,122 @@ export const getHCVaultKubernetesAuthRoles = async ( }); } }; + +export const getHCVaultKubernetesRoles = async ( + namespace: string, + mountPath: string, + connection: THCVaultConnection, + gatewayService: Pick +): Promise => { + // Remove trailing slash from mount path + const cleanMountPath = mountPath.endsWith("/") ? mountPath.slice(0, -1) : mountPath; + + try { + const instanceUrl = await getHCVaultInstanceUrl(connection); + const accessToken = await getHCVaultAccessToken(connection, gatewayService); + // 1. Get the Kubernetes secrets engine configuration for this mount + const { data: configResponse } = await requestWithHCVaultGateway<{ data: THCVaultKubernetesSecretsConfig }>( + connection, + gatewayService, + { + url: `${instanceUrl}/v1/${cleanMountPath}/config`, + method: "GET", + headers: { + "X-Vault-Token": accessToken, + "X-Vault-Namespace": namespace + } + } + ); + + const kubernetesConfig = configResponse.data; + + // 2. List all roles in this mount + let roleNames: string[] = []; + try { + const { data: roleListResponse } = await requestWithHCVaultGateway<{ data: { keys: string[] } }>( + connection, + gatewayService, + { + url: `${instanceUrl}/v1/${cleanMountPath}/roles?list=true`, + method: "GET", + headers: { + "X-Vault-Token": accessToken, + "X-Vault-Namespace": namespace + } + } + ); + roleNames = roleListResponse.data.keys || []; + } catch (error) { + // Vault returns 404 when no roles are configured yet + if (error && typeof error === "object" && "response" in error) { + const axiosError = error as { response?: { status?: number } }; + if (axiosError.response?.status === 404) { + return []; + } + } + + throw error; + } + + if (!roleNames || roleNames.length === 0) { + return []; + } + + // 3. Fetch details for each role with concurrency control + const limiter = createConcurrencyLimiter(HC_VAULT_CONCURRENCY_LIMIT); + + const roleDetailsPromises = roleNames.map((roleName) => + limiter(async () => { + const { data: roleResponse } = await requestWithHCVaultGateway<{ + data: { + allowed_kubernetes_namespaces?: string[]; + allowed_kubernetes_namespace_selector?: string; + token_max_ttl?: number; + token_default_ttl?: number; + token_default_audiences?: string[]; + service_account_name?: string; + kubernetes_role_name?: string; + kubernetes_role_type?: string; + generated_role_rules?: string; + name_template?: string; + extra_annotations?: Record; + extra_labels?: Record; + }; + }>(connection, gatewayService, { + url: `${instanceUrl}/v1/${cleanMountPath}/roles/${roleName}`, + method: "GET", + headers: { + "X-Vault-Token": accessToken, + "X-Vault-Namespace": namespace + } + }); + + // 4. Merge the role with the config + return { + ...roleResponse.data, + name: roleName, + config: kubernetesConfig, + mountPath: cleanMountPath + } as THCVaultKubernetesRole; + }) + ); + + const roles = await Promise.all(roleDetailsPromises); + + return roles; + } catch (error: unknown) { + logger.error(error, "Unable to list HC Vault Kubernetes secrets engine roles"); + + if (error instanceof AxiosError) { + const errorMessage = + (error.response?.data as { errors?: string[] })?.errors?.[0] || error.message || "Unknown error"; + throw new BadRequestError({ + message: `Failed to list Kubernetes secrets engine roles: ${errorMessage}` + }); + } + + throw new BadRequestError({ + message: "Unable to list Kubernetes secrets engine roles from HashiCorp Vault" + }); + } +}; diff --git a/backend/src/services/app-connection/hc-vault/hc-vault-connection-types.ts b/backend/src/services/app-connection/hc-vault/hc-vault-connection-types.ts index d25dbc9e6..2b1956c84 100644 --- a/backend/src/services/app-connection/hc-vault/hc-vault-connection-types.ts +++ b/backend/src/services/app-connection/hc-vault/hc-vault-connection-types.ts @@ -95,3 +95,26 @@ export type THCVaultKubernetesAuthRoleWithConfig = THCVaultKubernetesAuthRole & config: THCVaultKubernetesAuthConfig; mountPath: string; }; + +export type THCVaultKubernetesSecretsConfig = { + kubernetes_host: string; + kubernetes_ca_cert?: string; +}; + +export type THCVaultKubernetesRole = { + name: string; + allowed_kubernetes_namespaces?: string[]; + allowed_kubernetes_namespace_selector?: string; + token_max_ttl?: number; + token_default_ttl?: number; + token_default_audiences?: string[]; + service_account_name?: string; + kubernetes_role_name?: string; + kubernetes_role_type?: string; + generated_role_rules?: string; + name_template?: string; + extra_annotations?: Record; + extra_labels?: Record; + config: THCVaultKubernetesSecretsConfig; + mountPath: string; +}; diff --git a/backend/src/services/app-connection/northflank/index.ts b/backend/src/services/app-connection/northflank/index.ts new file mode 100644 index 000000000..94aee2a74 --- /dev/null +++ b/backend/src/services/app-connection/northflank/index.ts @@ -0,0 +1,5 @@ +export * from "./northflank-connection-enums"; +export * from "./northflank-connection-fns"; +export * from "./northflank-connection-schemas"; +export * from "./northflank-connection-service"; +export * from "./northflank-connection-types"; diff --git a/backend/src/services/app-connection/northflank/northflank-connection-enums.ts b/backend/src/services/app-connection/northflank/northflank-connection-enums.ts new file mode 100644 index 000000000..0f4f1bd06 --- /dev/null +++ b/backend/src/services/app-connection/northflank/northflank-connection-enums.ts @@ -0,0 +1,3 @@ +export enum NorthflankConnectionMethod { + ApiToken = "api-token" +} diff --git a/backend/src/services/app-connection/northflank/northflank-connection-fns.ts b/backend/src/services/app-connection/northflank/northflank-connection-fns.ts new file mode 100644 index 000000000..462934800 --- /dev/null +++ b/backend/src/services/app-connection/northflank/northflank-connection-fns.ts @@ -0,0 +1,114 @@ +import { AxiosError } from "axios"; + +import { request } from "@app/lib/config/request"; +import { BadRequestError } from "@app/lib/errors"; +import { AppConnection } from "@app/services/app-connection/app-connection-enums"; + +import { NorthflankConnectionMethod } from "./northflank-connection-enums"; +import { + TNorthflankConnection, + TNorthflankConnectionConfig, + TNorthflankProject, + TNorthflankSecretGroup +} from "./northflank-connection-types"; + +const NORTHFLANK_API_URL = "https://api.northflank.com"; + +export const getNorthflankConnectionListItem = () => { + return { + name: "Northflank" as const, + app: AppConnection.Northflank as const, + methods: Object.values(NorthflankConnectionMethod) + }; +}; + +export const validateNorthflankConnectionCredentials = async (config: TNorthflankConnectionConfig) => { + const { credentials } = config; + + try { + await request.get(`${NORTHFLANK_API_URL}/v1/projects`, { + headers: { + Authorization: `Bearer ${credentials.apiToken}`, + Accept: "application/json" + } + }); + } catch (error: unknown) { + if (error instanceof AxiosError) { + throw new BadRequestError({ + message: `Failed to validate Northflank credentials: ${error.message || "Unknown error"}` + }); + } + + throw new BadRequestError({ + message: `Failed to validate Northflank credentials - verify API token is correct` + }); + } + + return credentials; +}; + +export const listProjects = async (appConnection: TNorthflankConnection): Promise => { + const { credentials } = appConnection; + + try { + const { + data: { + data: { projects } + } + } = await request.get<{ data: { projects: TNorthflankProject[] } }>(`${NORTHFLANK_API_URL}/v1/projects`, { + headers: { + Authorization: `Bearer ${credentials.apiToken}`, + Accept: "application/json" + } + }); + + return projects; + } catch (error: unknown) { + if (error instanceof AxiosError) { + throw new BadRequestError({ + message: `Failed to list Northflank projects: ${error.message || "Unknown error"}` + }); + } + + throw new BadRequestError({ + message: "Unable to list Northflank projects", + error + }); + } +}; + +export const listSecretGroups = async ( + appConnection: TNorthflankConnection, + projectId: string +): Promise => { + const { credentials } = appConnection; + + try { + const { + data: { + data: { secrets } + } + } = await request.get<{ data: { secrets: TNorthflankSecretGroup[] } }>( + `${NORTHFLANK_API_URL}/v1/projects/${projectId}/secrets`, + { + headers: { + Authorization: `Bearer ${credentials.apiToken}`, + Accept: "application/json" + } + } + ); + + return secrets; + } catch (error: unknown) { + if (error instanceof AxiosError) { + throw new BadRequestError({ + message: `Failed to list Northflank secret groups: ${error.message || "Unknown error"}` + }); + } + + throw new BadRequestError({ + message: "Unable to list Northflank secret groups", + error + }); + } +}; diff --git a/backend/src/services/app-connection/northflank/northflank-connection-schemas.ts b/backend/src/services/app-connection/northflank/northflank-connection-schemas.ts new file mode 100644 index 000000000..95be757f6 --- /dev/null +++ b/backend/src/services/app-connection/northflank/northflank-connection-schemas.ts @@ -0,0 +1,60 @@ +import z from "zod"; + +import { AppConnections } from "@app/lib/api-docs"; +import { AppConnection } from "@app/services/app-connection/app-connection-enums"; +import { + BaseAppConnectionSchema, + GenericCreateAppConnectionFieldsSchema, + GenericUpdateAppConnectionFieldsSchema +} from "@app/services/app-connection/app-connection-schemas"; + +import { NorthflankConnectionMethod } from "./northflank-connection-enums"; + +export const NorthflankConnectionApiTokenCredentialsSchema = z.object({ + apiToken: z.string().trim().min(1, "API Token required").describe(AppConnections.CREDENTIALS.NORTHFLANK.apiToken) +}); + +const BaseNorthflankConnectionSchema = BaseAppConnectionSchema.extend({ + app: z.literal(AppConnection.Northflank) +}); + +export const NorthflankConnectionSchema = BaseNorthflankConnectionSchema.extend({ + method: z.literal(NorthflankConnectionMethod.ApiToken), + credentials: NorthflankConnectionApiTokenCredentialsSchema +}); + +export const SanitizedNorthflankConnectionSchema = z.discriminatedUnion("method", [ + BaseNorthflankConnectionSchema.extend({ + method: z.literal(NorthflankConnectionMethod.ApiToken), + credentials: NorthflankConnectionApiTokenCredentialsSchema.pick({}) + }) +]); + +export const ValidateNorthflankConnectionCredentialsSchema = z.discriminatedUnion("method", [ + z.object({ + method: z + .literal(NorthflankConnectionMethod.ApiToken) + .describe(AppConnections.CREATE(AppConnection.Northflank).method), + credentials: NorthflankConnectionApiTokenCredentialsSchema.describe( + AppConnections.CREATE(AppConnection.Northflank).credentials + ) + }) +]); + +export const CreateNorthflankConnectionSchema = ValidateNorthflankConnectionCredentialsSchema.and( + GenericCreateAppConnectionFieldsSchema(AppConnection.Northflank) +); + +export const UpdateNorthflankConnectionSchema = z + .object({ + credentials: NorthflankConnectionApiTokenCredentialsSchema.optional().describe( + AppConnections.UPDATE(AppConnection.Northflank).credentials + ) + }) + .and(GenericUpdateAppConnectionFieldsSchema(AppConnection.Northflank)); + +export const NorthflankConnectionListItemSchema = z.object({ + name: z.literal("Northflank"), + app: z.literal(AppConnection.Northflank), + methods: z.nativeEnum(NorthflankConnectionMethod).array() +}); diff --git a/backend/src/services/app-connection/northflank/northflank-connection-service.ts b/backend/src/services/app-connection/northflank/northflank-connection-service.ts new file mode 100644 index 000000000..faf248bbc --- /dev/null +++ b/backend/src/services/app-connection/northflank/northflank-connection-service.ts @@ -0,0 +1,50 @@ +import { logger } from "@app/lib/logger"; +import { OrgServiceActor } from "@app/lib/types"; + +import { AppConnection } from "../app-connection-enums"; +import { + listProjects as getNorthflankProjects, + listSecretGroups as getNorthflankSecretGroups +} from "./northflank-connection-fns"; +import { TNorthflankConnection, TNorthflankSecretGroup } from "./northflank-connection-types"; + +type TGetAppConnectionFunc = ( + app: AppConnection, + connectionId: string, + actor: OrgServiceActor +) => Promise; + +export const northflankConnectionService = (getAppConnection: TGetAppConnectionFunc) => { + const listProjects = async (connectionId: string, actor: OrgServiceActor) => { + const appConnection = await getAppConnection(AppConnection.Northflank, connectionId, actor); + try { + const projects = await getNorthflankProjects(appConnection); + + return projects; + } catch (error) { + logger.error({ error, connectionId, actor: actor.type }, "Failed to establish connection with Northflank"); + return []; + } + }; + + const listSecretGroups = async ( + connectionId: string, + projectId: string, + actor: OrgServiceActor + ): Promise => { + const appConnection = await getAppConnection(AppConnection.Northflank, connectionId, actor); + try { + const secretGroups = await getNorthflankSecretGroups(appConnection, projectId); + + return secretGroups; + } catch (error) { + logger.error({ error, connectionId, projectId, actor: actor.type }, "Failed to list Northflank secret groups"); + return []; + } + }; + + return { + listProjects, + listSecretGroups + }; +}; diff --git a/backend/src/services/app-connection/northflank/northflank-connection-types.ts b/backend/src/services/app-connection/northflank/northflank-connection-types.ts new file mode 100644 index 000000000..c007e27d3 --- /dev/null +++ b/backend/src/services/app-connection/northflank/northflank-connection-types.ts @@ -0,0 +1,35 @@ +import z from "zod"; + +import { DiscriminativePick } from "@app/lib/types"; + +import { AppConnection } from "../app-connection-enums"; +import { + CreateNorthflankConnectionSchema, + NorthflankConnectionSchema, + ValidateNorthflankConnectionCredentialsSchema +} from "./northflank-connection-schemas"; + +export type TNorthflankConnection = z.infer; + +export type TNorthflankConnectionInput = z.infer & { + app: AppConnection.Northflank; +}; + +export type TValidateNorthflankConnectionCredentialsSchema = typeof ValidateNorthflankConnectionCredentialsSchema; + +export type TNorthflankConnectionConfig = DiscriminativePick< + TNorthflankConnection, + "method" | "app" | "credentials" +> & { + orgId: string; +}; + +export type TNorthflankProject = { + id: string; + name: string; +}; + +export type TNorthflankSecretGroup = { + id: string; + name: string; +}; diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.ts index 28a986fe8..fb7213109 100644 --- a/backend/src/services/auth-token/auth-token-service.ts +++ b/backend/src/services/auth-token/auth-token-service.ts @@ -210,6 +210,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, membershipUserDAL, orgD if (!user || !user.isAccepted) throw new NotFoundError({ message: `User with ID '${session.userId}' not found` }); let orgId = ""; + let orgName = ""; let rootOrgId = ""; let parentOrgId = ""; if (token.organizationId) { @@ -235,9 +236,11 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, membershipUserDAL, orgD throw new ForbiddenRequestError({ message: "User organization membership is inactive" }); } orgId = subOrganization.id; + orgName = subOrganization.name; rootOrgId = token.organizationId; parentOrgId = subOrganization.parentOrgId as string; } else { + const organization = await orgDAL.findOne({ id: token.organizationId }); const orgMembership = await membershipUserDAL.findOne({ actorUserId: user.id, scopeOrgId: token.organizationId, @@ -253,12 +256,13 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, membershipUserDAL, orgD } orgId = token.organizationId; + orgName = organization.name; rootOrgId = token.organizationId; parentOrgId = token.organizationId; } } - return { user, tokenVersionId: token.tokenVersionId, orgId, rootOrgId, parentOrgId }; + return { user, tokenVersionId: token.tokenVersionId, orgId, orgName, rootOrgId, parentOrgId }; }; return { diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts index 31a9cc5a8..b9c759703 100644 --- a/backend/src/services/auth/auth-login-service.ts +++ b/backend/src/services/auth/auth-login-service.ts @@ -16,6 +16,7 @@ import { getUserPrivateKey } from "@app/lib/crypto/srp"; import { BadRequestError, DatabaseError, ForbiddenRequestError, UnauthorizedError } from "@app/lib/errors"; import { getMinExpiresIn, removeTrailingSlash } from "@app/lib/fn"; import { logger } from "@app/lib/logger"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { getUserAgentType } from "@app/server/plugins/audit-log"; import { getServerCfg } from "@app/services/super-admin/super-admin-service"; @@ -385,63 +386,94 @@ export const authLoginServiceFactory = ({ providerAuthToken?: string; captchaToken?: string; }) => { - const usersByUsername = await userDAL.findUserEncKeyByUsername({ - username: email - }); - const userEnc = - usersByUsername?.length > 1 ? usersByUsername.find((el) => el.username === email) : usersByUsername?.[0]; + const appCfg = getConfig(); - if (!userEnc) throw new BadRequestError({ message: "User not found" }); + try { + const usersByUsername = await userDAL.findUserEncKeyByUsername({ + username: email + }); + const userEnc = + usersByUsername?.length > 1 ? usersByUsername.find((el) => el.username === email) : usersByUsername?.[0]; - if (userEnc.encryptionVersion !== UserEncryption.V2) { - throw new BadRequestError({ message: "Legacy encryption scheme not supported", name: "LegacyEncryptionScheme" }); - } + if (!userEnc) throw new BadRequestError({ message: "User not found" }); - if (!userEnc.hashedPassword) { - if (userEnc.authMethods?.includes(AuthMethod.EMAIL)) { + if (userEnc.encryptionVersion !== UserEncryption.V2) { throw new BadRequestError({ message: "Legacy encryption scheme not supported", name: "LegacyEncryptionScheme" }); } - throw new BadRequestError({ message: "No password found" }); - } - - const { authMethod, organizationId } = getAuthMethodAndOrgId(email, providerAuthToken); - await verifyCaptcha(userEnc, captchaToken); - - if (!(await crypto.hashing().compareHash(password, userEnc.hashedPassword))) { - await userDAL.update( - { id: userEnc.userId }, - { - $incr: { - consecutiveFailedPasswordAttempts: 1 - } + if (!userEnc.hashedPassword) { + if (userEnc.authMethods?.includes(AuthMethod.EMAIL)) { + throw new BadRequestError({ + message: "Legacy encryption scheme not supported", + name: "LegacyEncryptionScheme" + }); } - ); - throw new BadRequestError({ message: "Invalid username or email" }); + throw new BadRequestError({ message: "No password found" }); + } + + const { authMethod, organizationId } = getAuthMethodAndOrgId(email, providerAuthToken); + await verifyCaptcha(userEnc, captchaToken); + + if (!(await crypto.hashing().compareHash(password, userEnc.hashedPassword))) { + await userDAL.update( + { id: userEnc.userId }, + { + $incr: { + consecutiveFailedPasswordAttempts: 1 + } + } + ); + + throw new BadRequestError({ message: "Invalid username or email" }); + } + + const token = await generateUserTokens({ + user: { + ...userEnc, + id: userEnc.userId + }, + ip, + userAgent, + authMethod, + organizationId + }); + + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.organization.id": organizationId, + "infisical.user.email": email, + "infisical.user.id": userEnc.userId, + "infisical.auth.method": AuthAttemptAuthMethod.EMAIL, + "infisical.auth.result": AuthAttemptAuthResult.SUCCESS, + "client.address": ip, + "user_agent.original": userAgent + }); + } + + return { + tokens: { + accessToken: token.access, + refreshToken: token.refresh + }, + user: userEnc + } as const; + } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.user.email": email, + "infisical.auth.method": AuthAttemptAuthMethod.EMAIL, + "infisical.auth.result": AuthAttemptAuthResult.FAILURE, + "client.address": ip, + "user_agent.original": userAgent + }); + } + + throw error; } - - const token = await generateUserTokens({ - user: { - ...userEnc, - id: userEnc.userId - }, - ip, - userAgent, - authMethod, - organizationId - }); - - return { - tokens: { - accessToken: token.access, - refreshToken: token.refresh - }, - user: userEnc - } as const; }; const selectOrganization = async ({ @@ -965,7 +997,8 @@ export const authLoginServiceFactory = ({ expiresIn: appCfg.JWT_PROVIDER_AUTH_LIFETIME } ); - return { isUserCompleted, providerAuthToken }; + + return { isUserCompleted, providerAuthToken, user, orgId, orgName }; }; /** diff --git a/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts b/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts index 4937a5331..26f59a402 100644 --- a/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts +++ b/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts @@ -192,7 +192,7 @@ export const castDbEntryToAzureAdCsCertificateAuthority = ( ca: Awaited> ): TAzureAdCsCertificateAuthority & { credentials: unknown } => { if (!ca.externalCa?.id) { - throw new BadRequestError({ message: "Malformed Azure AD Certificate Service certificate authority" }); + throw new BadRequestError({ message: "Malformed Active Directory Certificate Service certificate authority" }); } if (!ca.externalCa.dnsAppConnectionId) { @@ -776,7 +776,7 @@ export const AzureAdCsCertificateAuthorityFns = ({ const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(subscriber.caId); if (!ca.externalCa || ca.externalCa.type !== CaType.AZURE_AD_CS) { - throw new BadRequestError({ message: "CA is not an Azure AD Certificate Service CA" }); + throw new BadRequestError({ message: "CA is not an Active Directory Certificate Service CA" }); } const azureCa = castDbEntryToAzureAdCsCertificateAuthority(ca); diff --git a/backend/src/services/certificate-authority/certificate-authority-maps.ts b/backend/src/services/certificate-authority/certificate-authority-maps.ts index ef844a1ed..bae444cae 100644 --- a/backend/src/services/certificate-authority/certificate-authority-maps.ts +++ b/backend/src/services/certificate-authority/certificate-authority-maps.ts @@ -2,8 +2,8 @@ import { CaCapability, CaType } from "./certificate-authority-enums"; export const CERTIFICATE_AUTHORITIES_TYPE_MAP: Record = { [CaType.INTERNAL]: "Internal", - [CaType.ACME]: "ACME", - [CaType.AZURE_AD_CS]: "Azure AD Certificate Service" + [CaType.ACME]: "ACME-compatible CA", + [CaType.AZURE_AD_CS]: "Active Directory Certificate Service" }; export const CERTIFICATE_AUTHORITIES_CAPABILITIES_MAP: Record = { diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts index 5b9cd78ee..a7292e366 100644 --- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts +++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts @@ -2,12 +2,14 @@ import { ForbiddenError, subject } from "@casl/ability"; import * as x509 from "@peculiar/x509"; import slugify from "@sindresorhus/slugify"; +import { Knex } from "knex"; import { ActionProjectType, TableName, TCertificateAuthorities, TCertificateTemplates } from "@app/db/schemas"; import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types"; import { ProjectPermissionActions, ProjectPermissionCertificateActions, + ProjectPermissionCertificateProfileActions, ProjectPermissionPkiTemplateActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission"; @@ -1180,7 +1182,9 @@ export const internalCertificateAuthorityServiceFactory = ({ extendedKeyUsages, signatureAlgorithm, keyAlgorithm, - isFromProfile + isFromProfile, + internal = false, + tx }: TIssueCertFromCaDTO) => { let ca: TCertificateAuthorityWithAssociatedCa | undefined; let certificateTemplate: TCertificateTemplates | undefined; @@ -1210,19 +1214,28 @@ export const internalCertificateAuthorityServiceFactory = ({ throw new NotFoundError({ message: `Internal CA with ID '${caId}' not found` }); } - const { permission } = await permissionService.getProjectPermission({ - actor, - actorId, - projectId: ca.projectId, - actorAuthMethod, - actorOrgId, - actionProjectType: ActionProjectType.CertificateManager - }); + if (!internal) { + const { permission } = await permissionService.getProjectPermission({ + actor, + actorId, + projectId: ca.projectId, + actorAuthMethod, + actorOrgId, + actionProjectType: ActionProjectType.CertificateManager + }); - ForbiddenError.from(permission).throwUnlessCan( - ProjectPermissionCertificateActions.Create, - ProjectPermissionSub.Certificates - ); + if (isFromProfile) { + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionCertificateProfileActions.IssueCert, + ProjectPermissionSub.CertificateProfiles + ); + } else { + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionCertificateActions.Create, + ProjectPermissionSub.Certificates + ); + } + } if (ca.status !== CaStatus.ACTIVE) throw new BadRequestError({ message: "CA is not active" }); if (!ca.internalCa.activeCaCertId) @@ -1473,7 +1486,7 @@ export const internalCertificateAuthorityServiceFactory = ({ plainText: Buffer.from(certificateChainPem) }); - await certificateDAL.transaction(async (tx) => { + const executeIssueCertOperations = async (transaction: Knex) => { const cert = await certificateDAL.create( { caId: (ca as TCertificateAuthorities).id, @@ -1488,9 +1501,11 @@ export const internalCertificateAuthorityServiceFactory = ({ notAfter: notAfterDate, keyUsages: selectedKeyUsages, extendedKeyUsages: selectedExtendedKeyUsages, - projectId: ca!.projectId + projectId: ca!.projectId, + keyAlgorithm: effectiveKeyAlgorithm, + signatureAlgorithm: signatureAlgorithm || ca!.internalCa!.keyAlgorithm }, - tx + transaction ); await certificateBodyDAL.create( @@ -1499,7 +1514,7 @@ export const internalCertificateAuthorityServiceFactory = ({ encryptedCertificate, encryptedCertificateChain }, - tx + transaction ); await certificateSecretDAL.create( @@ -1507,7 +1522,7 @@ export const internalCertificateAuthorityServiceFactory = ({ certId: cert.id, encryptedPrivateKey }, - tx + transaction ); if (collectionId) { @@ -1516,12 +1531,18 @@ export const internalCertificateAuthorityServiceFactory = ({ pkiCollectionId: collectionId, certId: cert.id }, - tx + transaction ); } return cert; - }); + }; + + if (tx) { + await executeIssueCertOperations(tx); + } else { + await certificateDAL.transaction(executeIssueCertOperations); + } return { certificate: leafCert.toString("pem"), @@ -1593,10 +1614,17 @@ export const internalCertificateAuthorityServiceFactory = ({ actionProjectType: ActionProjectType.CertificateManager }); - ForbiddenError.from(permission).throwUnlessCan( - ProjectPermissionCertificateActions.Create, - ProjectPermissionSub.Certificates - ); + if (dto.isFromProfile && dto.profileId) { + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionCertificateProfileActions.IssueCert, + ProjectPermissionSub.CertificateProfiles + ); + } else { + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionCertificateActions.Create, + ProjectPermissionSub.Certificates + ); + } } if (ca.status !== CaStatus.ACTIVE) throw new BadRequestError({ message: "CA is not active" }); @@ -1700,7 +1728,8 @@ export const internalCertificateAuthorityServiceFactory = ({ certificateAuthorityDAL, certificateAuthoritySecretDAL, projectDAL, - kmsService + kmsService, + signatureAlgorithm: alg }); const caCrl = await certificateAuthorityCrlDAL.findOne({ caSecretId: caSecret.id }); @@ -1917,7 +1946,9 @@ export const internalCertificateAuthorityServiceFactory = ({ notAfter: notAfterDate, keyUsages: selectedKeyUsages, extendedKeyUsages: selectedExtendedKeyUsages, - projectId: ca!.projectId + projectId: ca!.projectId, + keyAlgorithm: keyAlgorithm || ca!.internalCa!.keyAlgorithm, + signatureAlgorithm: signatureAlgorithm || ca!.internalCa!.keyAlgorithm }, tx ); diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts index 22cb86d28..b4b037933 100644 --- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts +++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-types.ts @@ -1,3 +1,4 @@ +import { Knex } from "knex"; import { z } from "zod"; import { TCertificateAuthorityCrlDALFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-dal"; @@ -139,6 +140,9 @@ export type TIssueCertFromCaDTO = { signatureAlgorithm?: CertSignatureAlgorithm; keyAlgorithm?: CertKeyAlgorithm; isFromProfile?: boolean; + profileId?: string; + internal?: boolean; + tx?: Knex; } & Omit; export type TSignCertFromCaDTO = @@ -159,6 +163,7 @@ export type TSignCertFromCaDTO = signatureAlgorithm?: string; keyAlgorithm?: string; isFromProfile?: boolean; + profileId?: string; } | ({ isInternal: false; @@ -177,6 +182,7 @@ export type TSignCertFromCaDTO = signatureAlgorithm?: string; keyAlgorithm?: string; isFromProfile?: boolean; + profileId?: string; } & Omit); export type TGetCaCertificateTemplatesDTO = { diff --git a/backend/src/services/certificate-common/certificate-constants.ts b/backend/src/services/certificate-common/certificate-constants.ts index bbd589110..4cc3afb8b 100644 --- a/backend/src/services/certificate-common/certificate-constants.ts +++ b/backend/src/services/certificate-common/certificate-constants.ts @@ -175,6 +175,26 @@ export enum CertSignatureAlgorithm { ECDSA_SHA512 = "ECDSA-SHA512" } +export enum CertificateRenewalErrorType { + TEMPLATE_VALIDATION_FAILED = "TEMPLATE_VALIDATION_FAILED", + CA_NOT_FOUND = "CA_NOT_FOUND", + CA_INACTIVE = "CA_INACTIVE", + CERTIFICATE_OUTLIVES_CA = "CERTIFICATE_OUTLIVES_CA", + TTL_TOO_SHORT = "TTL_TOO_SHORT", + NOT_ELIGIBLE = "NOT_ELIGIBLE", + VALIDITY_EXCEEDS_MAXIMUM = "VALIDITY_EXCEEDS_MAXIMUM", + NOT_ALLOWED_BY_TEMPLATE = "NOT_ALLOWED_BY_TEMPLATE", + UNKNOWN_ERROR = "UNKNOWN_ERROR" +} + +export const CERTIFICATE_RENEWAL_CONFIG = { + MIN_RENEW_BEFORE_DAYS: 1, + MAX_RENEW_BEFORE_DAYS: 30, + QUEUE_BATCH_SIZE: 100, + DAILY_CRON_SCHEDULE: "0 0 * * *", + QUEUE_START_DELAY_MS: 5000 +} as const; + export const SAN_TYPE_OPTIONS = Object.values(CertSubjectAlternativeNameType); export const KEY_USAGE_OPTIONS = Object.values(CertKeyUsageType); export const EXTENDED_KEY_USAGE_OPTIONS = Object.values(CertExtendedKeyUsageType); diff --git a/backend/src/services/certificate-common/certificate-csr-utils.ts b/backend/src/services/certificate-common/certificate-csr-utils.ts new file mode 100644 index 000000000..7578950af --- /dev/null +++ b/backend/src/services/certificate-common/certificate-csr-utils.ts @@ -0,0 +1,183 @@ +import * as x509 from "@peculiar/x509"; + +import { BadRequestError } from "@app/lib/errors"; + +import { + CertExtendedKeyUsageOIDToName, + CertKeyAlgorithm, + CertKeyUsage, + CertSignatureAlgorithm, + mapLegacyAltNameType, + TAltNameMapping, + TAltNameType +} from "../certificate/certificate-types"; +import { parseDistinguishedName } from "../certificate-authority/certificate-authority-fns"; +import { validateAndMapAltNameType } from "../certificate-authority/certificate-authority-validators"; +import { TCertificateRequest } from "../certificate-template-v2/certificate-template-v2-types"; +import { mapLegacyExtendedKeyUsageToStandard, mapLegacyKeyUsageToStandard } from "./certificate-constants"; + +/** + * Extracts certificate request data from a CSR string + * @param csr - The CSR in PEM format + * @returns TCertificateRequest object with parsed CSR data + */ +export const extractCertificateRequestFromCSR = (csr: string): TCertificateRequest => { + const csrObj = new x509.Pkcs10CertificateRequest(csr); + const subject = parseDistinguishedName(csrObj.subject); + + const certificateRequest: TCertificateRequest = { + commonName: subject.commonName, + organization: subject.organization, + organizationUnit: subject.ou, + locality: subject.locality, + state: subject.province, + country: subject.country + }; + + const csrKeyUsageExtension = csrObj.getExtension("2.5.29.15") as x509.KeyUsagesExtension; + if (csrKeyUsageExtension) { + const csrKeyUsages = Object.values(CertKeyUsage).filter( + // eslint-disable-next-line no-bitwise + (keyUsage) => (x509.KeyUsageFlags[keyUsage] & csrKeyUsageExtension.usages) !== 0 + ); + certificateRequest.keyUsages = csrKeyUsages.map(mapLegacyKeyUsageToStandard); + } + + const csrExtendedKeyUsageExtension = csrObj.getExtension("2.5.29.37") as x509.ExtendedKeyUsageExtension; + if (csrExtendedKeyUsageExtension) { + const csrExtendedKeyUsages = csrExtendedKeyUsageExtension.usages.map( + (ekuOid) => CertExtendedKeyUsageOIDToName[ekuOid as string] + ); + certificateRequest.extendedKeyUsages = csrExtendedKeyUsages.map(mapLegacyExtendedKeyUsageToStandard); + } + + const sanExtension = csrObj.extensions.find((ext) => ext.type === "2.5.29.17"); + if (sanExtension) { + const sanNames = new x509.GeneralNames(sanExtension.value); + const altNamesArray: TAltNameMapping[] = sanNames.items + .filter( + (value) => + value.type === TAltNameType.EMAIL || + value.type === TAltNameType.DNS || + value.type === TAltNameType.IP || + value.type === TAltNameType.URL + ) + .map((name): TAltNameMapping => { + const altNameType = validateAndMapAltNameType(name.value); + if (!altNameType) { + throw new BadRequestError({ message: `Invalid altName from CSR: ${name.value}` }); + } + return altNameType; + }); + + certificateRequest.subjectAlternativeNames = altNamesArray.map((altName) => ({ + type: mapLegacyAltNameType(altName.type), + value: altName.value + })); + } + + return certificateRequest; +}; + +/** + * Extracts the key algorithm and signature algorithm from a CSR + * @param csr - The CSR in PEM format + * @returns Object containing keyAlgorithm and signatureAlgorithm + */ +export const extractAlgorithmsFromCSR = (csr: string) => { + const csrObj = new x509.Pkcs10CertificateRequest(csr); + + // Extract key algorithm from public key + const { publicKey } = csrObj; + let keyAlgorithm: CertKeyAlgorithm; + + if (publicKey.algorithm.name === "RSASSA-PKCS1-v1_5") { + const rsaPublicKey = publicKey as unknown as { algorithm: { modulusLength: number } }; + const keySize = rsaPublicKey.algorithm.modulusLength; + switch (keySize) { + case 2048: + keyAlgorithm = CertKeyAlgorithm.RSA_2048; + break; + case 3072: + keyAlgorithm = CertKeyAlgorithm.RSA_3072; + break; + case 4096: + keyAlgorithm = CertKeyAlgorithm.RSA_4096; + break; + default: + throw new BadRequestError({ + message: `Unsupported RSA key size in CSR: ${keySize}. Supported: 2048, 3072, 4096` + }); + } + } else if (publicKey.algorithm.name === "ECDSA") { + const ecPublicKey = publicKey as unknown as { algorithm: { namedCurve: string } }; + const { namedCurve } = ecPublicKey.algorithm; + switch (namedCurve) { + case "P-256": + keyAlgorithm = CertKeyAlgorithm.ECDSA_P256; + break; + case "P-384": + keyAlgorithm = CertKeyAlgorithm.ECDSA_P384; + break; + case "P-521": + keyAlgorithm = CertKeyAlgorithm.ECDSA_P521; + break; + default: + throw new BadRequestError({ + message: `Unsupported ECDSA curve in CSR: ${namedCurve}. Supported: P-256, P-384, P-521` + }); + } + } else { + throw new BadRequestError({ + message: `Unsupported key algorithm in CSR: ${publicKey.algorithm.name}. Supported: RSASSA-PKCS1-v1_5, ECDSA` + }); + } + + const signatureAlgorithm = csrObj.signatureAlgorithm.name; + const hashName = (csrObj.signatureAlgorithm as unknown as { hash?: { name: string } }).hash?.name; + + let normalizedSignatureAlg: CertSignatureAlgorithm; + + if (signatureAlgorithm === "RSASSA-PKCS1-v1_5") { + switch (hashName) { + case "SHA-256": + normalizedSignatureAlg = CertSignatureAlgorithm.RSA_SHA256; + break; + case "SHA-384": + normalizedSignatureAlg = CertSignatureAlgorithm.RSA_SHA384; + break; + case "SHA-512": + normalizedSignatureAlg = CertSignatureAlgorithm.RSA_SHA512; + break; + default: + throw new BadRequestError({ + message: `Unsupported RSA hash algorithm in CSR: ${hashName}. Supported: SHA-256, SHA-384, SHA-512` + }); + } + } else if (signatureAlgorithm === "ECDSA") { + switch (hashName) { + case "SHA-256": + normalizedSignatureAlg = CertSignatureAlgorithm.ECDSA_SHA256; + break; + case "SHA-384": + normalizedSignatureAlg = CertSignatureAlgorithm.ECDSA_SHA384; + break; + case "SHA-512": + normalizedSignatureAlg = CertSignatureAlgorithm.ECDSA_SHA512; + break; + default: + throw new BadRequestError({ + message: `Unsupported ECDSA hash algorithm in CSR: ${hashName}. Supported: SHA-256, SHA-384, SHA-512` + }); + } + } else { + throw new BadRequestError({ + message: `Unsupported signature algorithm in CSR: ${signatureAlgorithm}. Supported: RSASSA-PKCS1-v1_5, ECDSA` + }); + } + + return { + keyAlgorithm, + signatureAlgorithm: normalizedSignatureAlg + }; +}; diff --git a/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts b/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts index f6dbfba52..0d8ef30d0 100644 --- a/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts +++ b/backend/src/services/certificate-est-v3/certificate-est-v3-service.ts @@ -3,31 +3,15 @@ import * as x509 from "@peculiar/x509"; import { extractX509CertFromChain } from "@app/lib/certificates/extract-certificate"; import { BadRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors"; import { isCertChainValid } from "@app/services/certificate/certificate-fns"; -import { - CertExtendedKeyUsageOIDToName, - CertKeyUsage, - mapLegacyAltNameType, - TAltNameMapping, - TAltNameType -} from "@app/services/certificate/certificate-types"; import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal"; import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal"; -import { - getCaCertChain, - getCaCertChains, - parseDistinguishedName -} from "@app/services/certificate-authority/certificate-authority-fns"; -import { validateAndMapAltNameType } from "@app/services/certificate-authority/certificate-authority-validators"; +import { getCaCertChain, getCaCertChains } from "@app/services/certificate-authority/certificate-authority-fns"; import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service"; -import { - mapLegacyExtendedKeyUsageToStandard, - mapLegacyKeyUsageToStandard -} from "@app/services/certificate-common/certificate-constants"; +import { extractCertificateRequestFromCSR } from "@app/services/certificate-common/certificate-csr-utils"; import { mapEnumsForValidation } from "@app/services/certificate-common/certificate-utils"; import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal"; import { EnrollmentType } from "@app/services/certificate-profile/certificate-profile-types"; import { TCertificateTemplateV2ServiceFactory } from "@app/services/certificate-template-v2/certificate-template-v2-service"; -import { TCertificateRequest } from "@app/services/certificate-template-v2/certificate-template-v2-types"; import { TEstEnrollmentConfigDALFactory } from "@app/services/enrollment-config/est-enrollment-config-dal"; import { TKmsServiceFactory } from "@app/services/kms/kms-service"; import { TProjectDALFactory } from "@app/services/project/project-dal"; @@ -61,63 +45,6 @@ export const certificateEstV3ServiceFactory = ({ certificateProfileDAL, estEnrollmentConfigDAL }: TCertificateEstV3ServiceFactoryDep) => { - const extractCertificateRequestFromCSR = (csr: string): TCertificateRequest => { - const csrObj = new x509.Pkcs10CertificateRequest(csr); - const subject = parseDistinguishedName(csrObj.subject); - - const certificateRequest: TCertificateRequest = { - commonName: subject.commonName, - organization: subject.organization, - organizationUnit: subject.ou, - locality: subject.locality, - state: subject.province, - country: subject.country - }; - - const csrKeyUsageExtension = csrObj.getExtension("2.5.29.15") as x509.KeyUsagesExtension; - if (csrKeyUsageExtension) { - const csrKeyUsages = Object.values(CertKeyUsage).filter( - // eslint-disable-next-line no-bitwise - (keyUsage) => (x509.KeyUsageFlags[keyUsage] & csrKeyUsageExtension.usages) !== 0 - ); - certificateRequest.keyUsages = csrKeyUsages.map(mapLegacyKeyUsageToStandard); - } - - const csrExtendedKeyUsageExtension = csrObj.getExtension("2.5.29.37") as x509.ExtendedKeyUsageExtension; - if (csrExtendedKeyUsageExtension) { - const csrExtendedKeyUsages = csrExtendedKeyUsageExtension.usages.map( - (ekuOid) => CertExtendedKeyUsageOIDToName[ekuOid as string] - ); - certificateRequest.extendedKeyUsages = csrExtendedKeyUsages.map(mapLegacyExtendedKeyUsageToStandard); - } - - const sanExtension = csrObj.extensions.find((ext) => ext.type === "2.5.29.17"); - if (sanExtension) { - const sanNames = new x509.GeneralNames(sanExtension.value); - const altNamesArray: TAltNameMapping[] = sanNames.items - .filter( - (value) => - value.type === TAltNameType.EMAIL || - value.type === TAltNameType.DNS || - value.type === TAltNameType.IP || - value.type === TAltNameType.URL - ) - .map((name): TAltNameMapping => { - const altNameType = validateAndMapAltNameType(name.value); - if (!altNameType) { - throw new BadRequestError({ message: `Invalid altName from CSR: ${name.value}` }); - } - return altNameType; - }); - - certificateRequest.subjectAlternativeNames = altNamesArray.map((altName) => ({ - type: mapLegacyAltNameType(altName.type), - value: altName.value - })); - } - - return certificateRequest; - }; const simpleEnrollByProfile = async ({ csr, profileId, diff --git a/backend/src/services/certificate-profile/certificate-profile-dal.ts b/backend/src/services/certificate-profile/certificate-profile-dal.ts index 20cb9f3bc..b66475bbf 100644 --- a/backend/src/services/certificate-profile/certificate-profile-dal.ts +++ b/backend/src/services/certificate-profile/certificate-profile-dal.ts @@ -10,10 +10,8 @@ import { TCertificateProfile, TCertificateProfileCertificate, TCertificateProfileInsert, - TCertificateProfileMetrics, TCertificateProfileUpdate, - TCertificateProfileWithConfigs, - TCertificateProfileWithRawMetrics + TCertificateProfileWithConfigs } from "./certificate-profile-types"; export type TCertificateProfileDALFactory = ReturnType; @@ -109,7 +107,7 @@ export const certificateProfileDALFactory = (db: TDbClient) => { db.ref("encryptedCaChain").withSchema(TableName.PkiEstEnrollmentConfig).as("estConfigEncryptedCaChain"), db.ref("id").withSchema(TableName.PkiApiEnrollmentConfig).as("apiConfigId"), db.ref("autoRenew").withSchema(TableName.PkiApiEnrollmentConfig).as("apiConfigAutoRenew"), - db.ref("autoRenewDays").withSchema(TableName.PkiApiEnrollmentConfig).as("apiConfigAutoRenewDays") + db.ref("renewBeforeDays").withSchema(TableName.PkiApiEnrollmentConfig).as("apiConfigRenewBeforeDays") ) .where(`${TableName.PkiCertificateProfile}.id`, id) .first(); @@ -132,7 +130,7 @@ export const certificateProfileDALFactory = (db: TDbClient) => { ? ({ id: result.apiConfigId, autoRenew: !!result.apiConfigAutoRenew, - autoRenewDays: result.apiConfigAutoRenewDays || undefined + renewBeforeDays: result.apiConfigRenewBeforeDays || undefined } as TCertificateProfileWithConfigs["apiConfig"]) : undefined; @@ -203,21 +201,11 @@ export const certificateProfileDALFactory = (db: TDbClient) => { search?: string; enrollmentType?: EnrollmentType; caId?: string; - includeMetrics?: boolean; - expiringDays?: number; } = {}, tx?: Knex - ): Promise => { + ): Promise => { try { - const { - offset = 0, - limit = 20, - search, - enrollmentType, - caId, - includeMetrics = false, - expiringDays = 7 - } = options; + const { offset = 0, limit = 20, search, enrollmentType, caId } = options; let baseQuery = (tx || db)(TableName.PkiCertificateProfile).where( `${TableName.PkiCertificateProfile}.projectId`, @@ -242,7 +230,7 @@ export const certificateProfileDALFactory = (db: TDbClient) => { baseQuery = baseQuery.where(`${TableName.PkiCertificateProfile}.caId`, caId); } - let query = baseQuery + const query = baseQuery .leftJoin( TableName.PkiEstEnrollmentConfig, `${TableName.PkiCertificateProfile}.estConfigId`, @@ -264,55 +252,9 @@ export const certificateProfileDALFactory = (db: TDbClient) => { db.ref("encryptedCaChain").withSchema(TableName.PkiEstEnrollmentConfig).as("estEncryptedCaChain"), db.ref("id").withSchema(TableName.PkiApiEnrollmentConfig).as("apiId"), db.ref("autoRenew").withSchema(TableName.PkiApiEnrollmentConfig).as("apiAutoRenew"), - db.ref("autoRenewDays").withSchema(TableName.PkiApiEnrollmentConfig).as("apiAutoRenewDays") + db.ref("renewBeforeDays").withSchema(TableName.PkiApiEnrollmentConfig).as("apiRenewBeforeDays") ); - if (includeMetrics) { - query = query.leftJoin( - TableName.Certificate, - `${TableName.PkiCertificateProfile}.id`, - `${TableName.Certificate}.profileId` - ); - - const now = new Date(); - const expiringDate = new Date(); - expiringDate.setDate(now.getDate() + expiringDays); - - query = query - .select( - selectAllTableCols(TableName.PkiCertificateProfile), - db.ref("id").withSchema(TableName.PkiEstEnrollmentConfig).as("estId"), - db - .ref("disableBootstrapCaValidation") - .withSchema(TableName.PkiEstEnrollmentConfig) - .as("estDisableBootstrapCaValidation"), - db.ref("hashedPassphrase").withSchema(TableName.PkiEstEnrollmentConfig).as("estHashedPassphrase"), - db.ref("encryptedCaChain").withSchema(TableName.PkiEstEnrollmentConfig).as("estEncryptedCaChain"), - db.ref("id").withSchema(TableName.PkiApiEnrollmentConfig).as("apiId"), - db.ref("autoRenew").withSchema(TableName.PkiApiEnrollmentConfig).as("apiAutoRenew"), - db.ref("autoRenewDays").withSchema(TableName.PkiApiEnrollmentConfig).as("apiAutoRenewDays"), - db.raw("COUNT(certificates.id) as total_certificates"), - db.raw( - 'COUNT(CASE WHEN certificates."revokedAt" IS NULL AND certificates."notAfter" > ? THEN 1 END) as active_certificates', - [expiringDate] - ), - db.raw( - 'COUNT(CASE WHEN certificates."revokedAt" IS NULL AND certificates."notAfter" <= ? THEN 1 END) as expired_certificates', - [now] - ), - db.raw( - 'COUNT(CASE WHEN certificates."revokedAt" IS NULL AND certificates."notAfter" > ? AND certificates."notAfter" <= ? THEN 1 END) as expiring_certificates', - [now, expiringDate] - ), - db.raw('COUNT(CASE WHEN certificates."revokedAt" IS NOT NULL THEN 1 END) as revoked_certificates') - ) - .groupBy( - `${TableName.PkiCertificateProfile}.id`, - `${TableName.PkiEstEnrollmentConfig}.id`, - `${TableName.PkiApiEnrollmentConfig}.id` - ); - } - const results = (await query .orderBy(`${TableName.PkiCertificateProfile}.createdAt`, "desc") .offset(offset) @@ -333,7 +275,7 @@ export const certificateProfileDALFactory = (db: TDbClient) => { ? { id: result.apiId as string, autoRenew: !!result.apiAutoRenew, - autoRenewDays: (result.apiAutoRenewDays as number) || undefined + renewBeforeDays: (result.apiRenewBeforeDays as number) || undefined } : undefined; @@ -353,17 +295,6 @@ export const certificateProfileDALFactory = (db: TDbClient) => { apiConfig }; - if (includeMetrics) { - return { - ...baseProfile, - total_certificates: result.total_certificates, - active_certificates: result.active_certificates, - expired_certificates: result.expired_certificates, - expiring_certificates: result.expiring_certificates, - revoked_certificates: result.revoked_certificates - } as TCertificateProfileWithRawMetrics & TCertificateProfileWithConfigs; - } - return baseProfile as TCertificateProfileWithConfigs; }); } catch (error) { @@ -485,45 +416,6 @@ export const certificateProfileDALFactory = (db: TDbClient) => { } }; - const getProfileMetrics = async ( - profileId: string, - expiringDays: number = 7, - tx?: Knex - ): Promise => { - try { - const now = new Date(); - const expiringDate = new Date(); - expiringDate.setDate(now.getDate() + expiringDays); - - const metrics = await (tx || db)(TableName.Certificate) - .where("profileId", profileId) - .select( - db.raw("COUNT(*) as total_certificates"), - db.raw('COUNT(CASE WHEN "revokedAt" IS NULL AND "notAfter" > ? THEN 1 END) as active_certificates', [ - expiringDate - ]), - db.raw('COUNT(CASE WHEN "revokedAt" IS NULL AND "notAfter" <= ? THEN 1 END) as expired_certificates', [now]), - db.raw( - 'COUNT(CASE WHEN "revokedAt" IS NULL AND "notAfter" > ? AND "notAfter" <= ? THEN 1 END) as expiring_certificates', - [now, expiringDate] - ), - db.raw('COUNT(CASE WHEN "revokedAt" IS NOT NULL THEN 1 END) as revoked_certificates') - ) - .first(); - - return { - profileId, - totalCertificates: parseInt(String((metrics as Record)?.total_certificates || 0), 10), - activeCertificates: parseInt(String((metrics as Record)?.active_certificates || 0), 10), - expiredCertificates: parseInt(String((metrics as Record)?.expired_certificates || 0), 10), - expiringCertificates: parseInt(String((metrics as Record)?.expiring_certificates || 0), 10), - revokedCertificates: parseInt(String((metrics as Record)?.revoked_certificates || 0), 10) - }; - } catch (error) { - throw new DatabaseError({ error, name: "Get certificate profile metrics" }); - } - }; - const isProfileInUse = async (profileId: string, tx?: Knex) => { try { const doc = await (tx || db)(TableName.Certificate).where("profileId", profileId).count("*").first(); @@ -546,7 +438,6 @@ export const certificateProfileDALFactory = (db: TDbClient) => { countByProjectId, findByNameAndProjectId, getCertificatesByProfile, - getProfileMetrics, isProfileInUse }; }; diff --git a/backend/src/services/certificate-profile/certificate-profile-schemas.ts b/backend/src/services/certificate-profile/certificate-profile-schemas.ts index 7b3e2cc57..8ac494fe6 100644 --- a/backend/src/services/certificate-profile/certificate-profile-schemas.ts +++ b/backend/src/services/certificate-profile/certificate-profile-schemas.ts @@ -25,7 +25,7 @@ export const createCertificateProfileSchema = z apiConfig: z .object({ autoRenew: z.boolean().default(false), - autoRenewDays: z.number().min(1).max(365).optional() + renewBeforeDays: z.number().min(1).max(30).optional() }) .optional() }) @@ -75,7 +75,7 @@ export const updateCertificateProfileSchema = z apiConfig: z .object({ autoRenew: z.boolean().default(false), - autoRenewDays: z.number().min(1).max(365).optional() + renewBeforeDays: z.number().min(1).max(30).optional() }) .optional() }) @@ -127,8 +127,3 @@ export const listCertificatesByProfileSchema = z.object({ status: z.enum(["active", "expired", "revoked"]).optional(), search: z.string().optional() }); - -export const getCertificateProfileMetricsSchema = z.object({ - profileId: z.string().uuid(), - expiringDays: z.coerce.number().min(1).max(365).default(30) -}); diff --git a/backend/src/services/certificate-profile/certificate-profile-service.test.ts b/backend/src/services/certificate-profile/certificate-profile-service.test.ts index dd2d7d2d6..bb30b8d5c 100644 --- a/backend/src/services/certificate-profile/certificate-profile-service.test.ts +++ b/backend/src/services/certificate-profile/certificate-profile-service.test.ts @@ -47,7 +47,6 @@ describe("CertificateProfileService", () => { findByNameAndProjectId: vi.fn(), findByIdWithConfigs: vi.fn(), getCertificatesByProfile: vi.fn(), - getProfileMetrics: vi.fn(), isProfileInUse: vi.fn(), transaction: vi.fn(), find: vi.fn(), @@ -110,7 +109,7 @@ describe("CertificateProfileService", () => { apiConfig: { id: "api-config-123", autoRenew: true, - autoRenewDays: 30 + renewBeforeDays: 30 } }; @@ -202,7 +201,7 @@ describe("CertificateProfileService", () => { certificateTemplateId: "template-123", apiConfig: { autoRenew: true, - autoRenewDays: 30 + renewBeforeDays: 30 } }; @@ -323,7 +322,7 @@ describe("CertificateProfileService", () => { certificateTemplateId: "template-123", apiConfig: { autoRenew: true, - autoRenewDays: 30 + renewBeforeDays: 30 } }; @@ -493,9 +492,7 @@ describe("CertificateProfileService", () => { limit: 20, search: undefined, enrollmentType: undefined, - caId: undefined, - includeMetrics: false, - expiringDays: 30 + caId: undefined }); }); @@ -515,51 +512,7 @@ describe("CertificateProfileService", () => { limit: 5, search: "test", enrollmentType: EnrollmentType.API, - caId: "ca-123", - includeMetrics: false, - expiringDays: 30 - }); - }); - - it("should list profiles with metrics when includeMetrics is true", async () => { - const mockProfilesWithMetrics = [ - { - ...sampleProfile, - total_certificates: 10, - active_certificates: 8, - expired_certificates: 1, - expiring_certificates: 1, - revoked_certificates: 0 - } - ]; - (mockCertificateProfileDAL.findByProjectId as any).mockResolvedValue(mockProfilesWithMetrics); - - const result = await service.listProfiles({ - ...mockActor, - projectId: "project-123", - includeMetrics: true, - expiringDays: 15 - }); - - expect(result.profiles).toHaveLength(1); - expect(result.profiles[0]).toHaveProperty("metrics"); - expect(result.profiles[0].metrics).toEqual({ - profileId: sampleProfile.id, - totalCertificates: 10, - activeCertificates: 8, - expiredCertificates: 1, - expiringCertificates: 1, - revokedCertificates: 0 - }); - - expect(mockCertificateProfileDAL.findByProjectId).toHaveBeenCalledWith("project-123", { - offset: 0, - limit: 20, - search: undefined, - enrollmentType: undefined, - caId: undefined, - includeMetrics: true, - expiringDays: 15 + caId: "ca-123" }); }); }); @@ -659,54 +612,6 @@ describe("CertificateProfileService", () => { }); }); - describe("getProfileMetrics", () => { - const mockMetrics = { - profileId: "profile-123", - totalCertificates: 10, - activeCertificates: 8, - expiredCertificates: 1, - expiringCertificates: 2, - revokedCertificates: 1 - }; - - beforeEach(() => { - (mockCertificateProfileDAL.findById as any).mockResolvedValue(sampleProfile); - (mockCertificateProfileDAL.getProfileMetrics as any).mockResolvedValue(mockMetrics); - }); - - it("should get profile metrics successfully", async () => { - const result = await service.getProfileMetrics({ - ...mockActor, - profileId: "profile-123" - }); - - expect(result).toEqual(mockMetrics); - expect(mockCertificateProfileDAL.findById).toHaveBeenCalledWith("profile-123"); - expect(mockCertificateProfileDAL.getProfileMetrics).toHaveBeenCalledWith("profile-123", 30); - }); - - it("should get profile metrics with custom expiring days", async () => { - await service.getProfileMetrics({ - ...mockActor, - profileId: "profile-123", - expiringDays: 60 - }); - - expect(mockCertificateProfileDAL.getProfileMetrics).toHaveBeenCalledWith("profile-123", 60); - }); - - it("should throw NotFoundError when profile not found", async () => { - (mockCertificateProfileDAL.findById as any).mockResolvedValue(null); - - await expect( - service.getProfileMetrics({ - ...mockActor, - profileId: "profile-123" - }) - ).rejects.toThrow(NotFoundError); - }); - }); - describe("comprehensive certificate profile scenarios", () => { describe("profile configuration validation", () => { it("should validate EST enrollment configuration", async () => { @@ -761,7 +666,7 @@ describe("CertificateProfileService", () => { certificateTemplateId: "template-123", apiConfig: { autoRenew: true, - autoRenewDays: 30 + renewBeforeDays: 30 } }; @@ -786,7 +691,7 @@ describe("CertificateProfileService", () => { certificateTemplateId: "template-123", apiConfig: { autoRenew: true, - autoRenewDays: 7 + renewBeforeDays: 7 } }; @@ -808,7 +713,7 @@ describe("CertificateProfileService", () => { expect(mockApiEnrollmentConfigDAL.create).toHaveBeenCalledWith( { autoRenew: true, - autoRenewDays: 7 + renewBeforeDays: 7 }, undefined ); @@ -929,53 +834,6 @@ describe("CertificateProfileService", () => { }); }); - describe("metrics and monitoring", () => { - it("should calculate profile metrics correctly", async () => { - const detailedMetrics = { - profileId: "profile-123", - totalCertificates: 50, - activeCertificates: 40, - expiredCertificates: 5, - expiringCertificates: 3, - revokedCertificates: 2 - }; - - (mockCertificateProfileDAL.findById as any).mockResolvedValue(sampleProfile); - (mockCertificateProfileDAL.getProfileMetrics as any).mockResolvedValue(detailedMetrics); - - const result = await service.getProfileMetrics({ - ...mockActor, - profileId: "profile-123", - expiringDays: 14 - }); - - expect(result).toEqual(detailedMetrics); - expect(mockCertificateProfileDAL.getProfileMetrics).toHaveBeenCalledWith("profile-123", 14); - }); - - it("should handle zero certificate metrics", async () => { - const emptyMetrics = { - profileId: "profile-123", - totalCertificates: 0, - activeCertificates: 0, - expiredCertificates: 0, - expiringCertificates: 0, - revokedCertificates: 0 - }; - - (mockCertificateProfileDAL.findById as any).mockResolvedValue(sampleProfile); - (mockCertificateProfileDAL.getProfileMetrics as any).mockResolvedValue(emptyMetrics); - - const result = await service.getProfileMetrics({ - ...mockActor, - profileId: "profile-123" - }); - - expect(result.totalCertificates).toBe(0); - expect(result.activeCertificates).toBe(0); - }); - }); - describe("error scenarios", () => { it("should handle database connection errors gracefully", async () => { (mockCertificateProfileDAL.findById as any).mockRejectedValue(new Error("Database connection failed")); diff --git a/backend/src/services/certificate-profile/certificate-profile-service.ts b/backend/src/services/certificate-profile/certificate-profile-service.ts index c43dee889..f858a8d4f 100644 --- a/backend/src/services/certificate-profile/certificate-profile-service.ts +++ b/backend/src/services/certificate-profile/certificate-profile-service.ts @@ -27,10 +27,8 @@ import { TCertificateProfile, TCertificateProfileCertificate, TCertificateProfileInsert, - TCertificateProfileMetrics, TCertificateProfileUpdate, - TCertificateProfileWithConfigs, - TCertificateProfileWithRawMetrics + TCertificateProfileWithConfigs } from "./certificate-profile-types"; const validateAndEncryptPemCaChain = async ( @@ -225,7 +223,7 @@ export const certificateProfileServiceFactory = ({ const apiConfig = await apiEnrollmentConfigDAL.create( { autoRenew: data.apiConfig.autoRenew, - autoRenewDays: data.apiConfig.autoRenewDays + renewBeforeDays: data.apiConfig.renewBeforeDays }, tx ); @@ -343,7 +341,7 @@ export const certificateProfileServiceFactory = ({ existingProfile.apiConfigId, { autoRenew: apiConfig.autoRenew, - autoRenewDays: apiConfig.autoRenewDays + renewBeforeDays: apiConfig.renewBeforeDays }, tx ); @@ -361,18 +359,14 @@ export const certificateProfileServiceFactory = ({ actorId, actorAuthMethod, actorOrgId, - profileId, - includeMetrics = false, - expiringDays = 30 + profileId }: { actor: ActorType; actorId: string; actorAuthMethod: ActorAuthMethod; actorOrgId: string; profileId: string; - includeMetrics?: boolean; - expiringDays?: number; - }): Promise => { + }): Promise => { const profile = await certificateProfileDAL.findById(profileId); if (!profile) { throw new NotFoundError({ message: "Certificate profile not found" }); @@ -393,14 +387,6 @@ export const certificateProfileServiceFactory = ({ const converted = convertDalToService(profile); - if (includeMetrics) { - const metrics = await certificateProfileDAL.getProfileMetrics(profileId, expiringDays); - return { - ...converted, - metrics - }; - } - return converted; }; @@ -506,9 +492,7 @@ export const certificateProfileServiceFactory = ({ limit = 20, search, enrollmentType, - caId, - includeMetrics = false, - expiringDays = 30 + caId }: { actor: ActorType; actorId: string; @@ -520,10 +504,8 @@ export const certificateProfileServiceFactory = ({ search?: string; enrollmentType?: EnrollmentType; caId?: string; - includeMetrics?: boolean; - expiringDays?: number; }): Promise<{ - profiles: (TCertificateProfileWithConfigs & { metrics?: TCertificateProfileMetrics })[]; + profiles: TCertificateProfileWithConfigs[]; totalCount: number; }> => { const { permission } = await permissionService.getProjectPermission({ @@ -544,9 +526,7 @@ export const certificateProfileServiceFactory = ({ limit, search, enrollmentType, - caId, - includeMetrics, - expiringDays + caId }); const totalCount = await certificateProfileDAL.countByProjectId(projectId, { @@ -591,27 +571,12 @@ export const certificateProfileServiceFactory = ({ } const converted = convertDalToService(profileWithConfigs); - let result: TCertificateProfileWithConfigs & { metrics?: TCertificateProfileMetrics } = { + const result: TCertificateProfileWithConfigs = { ...converted, estConfig: decryptedEstConfig, apiConfig: profileWithConfigs.apiConfig }; - if (includeMetrics) { - const profileWithMetrics = profile as TCertificateProfileWithRawMetrics; - result = { - ...result, - metrics: { - profileId: converted.id, - totalCertificates: parseInt(String(profileWithMetrics.total_certificates || 0), 10), - activeCertificates: parseInt(String(profileWithMetrics.active_certificates || 0), 10), - expiredCertificates: parseInt(String(profileWithMetrics.expired_certificates || 0), 10), - expiringCertificates: parseInt(String(profileWithMetrics.expiring_certificates || 0), 10), - revokedCertificates: parseInt(String(profileWithMetrics.revoked_certificates || 0), 10) - } - }; - } - return result; }) ); @@ -709,43 +674,6 @@ export const certificateProfileServiceFactory = ({ return certificates; }; - const getProfileMetrics = async ({ - actor, - actorId, - actorAuthMethod, - actorOrgId, - profileId, - expiringDays = 30 - }: { - actor: ActorType; - actorId: string; - actorAuthMethod: ActorAuthMethod; - actorOrgId: string; - profileId: string; - expiringDays?: number; - }): Promise => { - const profile = await certificateProfileDAL.findById(profileId); - if (!profile) { - throw new NotFoundError({ message: "Certificate profile not found" }); - } - - const { permission } = await permissionService.getProjectPermission({ - actor, - actorId, - projectId: profile.projectId, - actorAuthMethod, - actorOrgId, - actionProjectType: ActionProjectType.CertificateManager - }); - ForbiddenError.from(permission).throwUnlessCan( - ProjectPermissionCertificateProfileActions.Read, - ProjectPermissionSub.CertificateProfiles - ); - - const metrics = await certificateProfileDAL.getProfileMetrics(profileId, expiringDays); - return metrics; - }; - const getEstConfigurationByProfile = async ( params: | { @@ -818,7 +746,6 @@ export const certificateProfileServiceFactory = ({ listProfiles, deleteProfile, getProfileCertificates, - getProfileMetrics, getEstConfigurationByProfile }; }; diff --git a/backend/src/services/certificate-profile/certificate-profile-types.ts b/backend/src/services/certificate-profile/certificate-profile-types.ts index a6d53a0f3..5dac470c8 100644 --- a/backend/src/services/certificate-profile/certificate-profile-types.ts +++ b/backend/src/services/certificate-profile/certificate-profile-types.ts @@ -26,7 +26,7 @@ export type TCertificateProfileUpdate = Omit; + +type CertificateSyncFindFilter = Parameters>[0]; + +export const certificateSyncDALFactory = (db: TDbClient) => { + const certificateSyncOrm = ormify(db, TableName.CertificateSync); + + const findByPkiSyncId = async (pkiSyncId: string, tx?: Knex) => { + try { + const docs = await (tx || db.replicaNode())(TableName.CertificateSync) + .where({ pkiSyncId }) + .select(selectAllTableCols(TableName.CertificateSync)); + return docs; + } catch (error) { + throw new DatabaseError({ error, name: "FindByPkiSyncId" }); + } + }; + + const findByCertificateId = async (certificateId: string, tx?: Knex) => { + try { + const docs = await (tx || db.replicaNode())(TableName.CertificateSync) + .where({ certificateId }) + .select(selectAllTableCols(TableName.CertificateSync)); + return docs; + } catch (error) { + throw new DatabaseError({ error, name: "FindByCertificateId" }); + } + }; + + const findByPkiSyncAndCertificate = async (pkiSyncId: string, certificateId: string, tx?: Knex) => { + try { + const doc = await (tx || db.replicaNode())(TableName.CertificateSync) + .where({ pkiSyncId, certificateId }) + .select(selectAllTableCols(TableName.CertificateSync)) + .first(); + return doc; + } catch (error) { + throw new DatabaseError({ error, name: "FindByPkiSyncAndCertificate" }); + } + }; + + const findCertificateIdsByPkiSyncId = async (pkiSyncId: string, tx?: Knex): Promise => { + try { + const docs = (await (tx || db.replicaNode())(TableName.CertificateSync) + .where({ pkiSyncId }) + .select("certificateId")) as Array<{ certificateId: string }>; + return docs.map((doc) => doc.certificateId); + } catch (error) { + throw new DatabaseError({ error, name: "FindCertificateIdsByPkiSyncId" }); + } + }; + + const findPkiSyncIdsByCertificateId = async (certificateId: string, tx?: Knex): Promise => { + try { + const docs = (await (tx || db.replicaNode())(TableName.CertificateSync) + .where({ certificateId }) + .select("pkiSyncId")) as Array<{ pkiSyncId: string }>; + return docs.map((doc) => doc.pkiSyncId); + } catch (error) { + throw new DatabaseError({ error, name: "FindPkiSyncIdsByCertificateId" }); + } + }; + + const addCertificates = async ( + pkiSyncId: string, + certificateData: Array<{ certificateId: string; externalIdentifier?: string }>, + tx?: Knex + ): Promise => { + try { + const insertData = certificateData.map(({ certificateId, externalIdentifier }) => ({ + pkiSyncId, + certificateId, + syncStatus: CertificateSyncStatus.Pending, + externalIdentifier + })); + + const docs = await (tx || db)(TableName.CertificateSync).insert(insertData).returning("*"); + + return docs; + } catch (error) { + throw new DatabaseError({ error, name: "AddCertificates" }); + } + }; + + const removeCertificates = async (pkiSyncId: string, certificateIds: string[], tx?: Knex): Promise => { + try { + const deletedCount = await (tx || db)(TableName.CertificateSync) + .where({ pkiSyncId }) + .whereIn("certificateId", certificateIds) + .del(); + + return deletedCount; + } catch (error) { + throw new DatabaseError({ error, name: "RemoveCertificates" }); + } + }; + + const removeAllCertificatesFromSync = async (pkiSyncId: string, tx?: Knex): Promise => { + try { + const deletedCount = await (tx || db)(TableName.CertificateSync).where({ pkiSyncId }).del(); + return deletedCount; + } catch (error) { + throw new DatabaseError({ error, name: "RemoveAllCertificatesFromSync" }); + } + }; + + const updateSyncStatus = async ( + pkiSyncId: string, + certificateId: string, + status: string, + message?: string, + tx?: Knex + ): Promise => { + try { + const updateData: Partial = { + syncStatus: status, + lastSyncedAt: new Date() + }; + + if (message !== undefined) { + updateData.lastSyncMessage = message; + } + + const docs = await (tx || db)(TableName.CertificateSync) + .where({ pkiSyncId, certificateId }) + .update(updateData) + .returning("*"); + + return docs[0]; + } catch (error) { + throw new DatabaseError({ error, name: "UpdateSyncStatus" }); + } + }; + + const bulkUpdateSyncStatus = async ( + updates: Array<{ + pkiSyncId: string; + certificateId: string; + status: string; + message?: string; + }>, + tx?: Knex + ): Promise => { + try { + if (tx) { + for (const update of updates) { + // eslint-disable-next-line no-await-in-loop + await updateSyncStatus(update.pkiSyncId, update.certificateId, update.status, update.message, tx); + } + } else { + await certificateSyncOrm.transaction(async (trx) => { + for (const update of updates) { + // eslint-disable-next-line no-await-in-loop + await updateSyncStatus(update.pkiSyncId, update.certificateId, update.status, update.message, trx); + } + }); + } + } catch (error) { + throw new DatabaseError({ error, name: "BulkUpdateSyncStatus" }); + } + }; + + const findWithDetails = async ( + options: { + filter?: CertificateSyncFindFilter; + pkiSyncId?: string; + offset?: number; + limit?: number; + }, + tx?: Knex + ): Promise<{ + certificateDetails: (TCertificateSyncs & { + certificateSerialNumber?: string; + certificateCommonName?: string; + certificateAltNames?: string; + certificateStatus?: string; + certificateNotBefore?: Date; + certificateNotAfter?: Date; + certificateRenewBeforeDays?: number | null; + certificateRenewedByCertificateId?: string; + certificateRenewalError?: string; + pkiSyncName?: string; + pkiSyncDestination?: string; + })[]; + totalCount: number; + }> => { + try { + const { filter, pkiSyncId, offset, limit } = options; + + const baseQuery = (tx || db.replicaNode())(TableName.CertificateSync) + .leftJoin(TableName.Certificate, `${TableName.CertificateSync}.certificateId`, `${TableName.Certificate}.id`) + .leftJoin(TableName.PkiSync, `${TableName.CertificateSync}.pkiSyncId`, `${TableName.PkiSync}.id`); + + if (filter) { + // eslint-disable-next-line @typescript-eslint/no-misused-promises + void baseQuery.where(buildFindFilter(filter)); + } + if (pkiSyncId) { + void baseQuery.where(`${TableName.CertificateSync}.pkiSyncId`, pkiSyncId); + } + + const countResult = await baseQuery.clone().count("* as count"); + const totalCount = Number((countResult[0] as unknown as { count: string | number }).count); + + const query = baseQuery + .select(selectAllTableCols(TableName.CertificateSync)) + .select( + db.ref("serialNumber").withSchema(TableName.Certificate).as("certificateSerialNumber"), + db.ref("commonName").withSchema(TableName.Certificate).as("certificateCommonName"), + db.ref("altNames").withSchema(TableName.Certificate).as("certificateAltNames"), + db.ref("status").withSchema(TableName.Certificate).as("certificateStatus"), + db.ref("notBefore").withSchema(TableName.Certificate).as("certificateNotBefore"), + db.ref("notAfter").withSchema(TableName.Certificate).as("certificateNotAfter"), + db.ref("renewBeforeDays").withSchema(TableName.Certificate).as("certificateRenewBeforeDays"), + db.ref("renewedByCertificateId").withSchema(TableName.Certificate).as("certificateRenewedByCertificateId"), + db.ref("renewalError").withSchema(TableName.Certificate).as("certificateRenewalError"), + db.ref("name").withSchema(TableName.PkiSync).as("pkiSyncName"), + db.ref("destination").withSchema(TableName.PkiSync).as("pkiSyncDestination") + ) + .orderBy(`${TableName.CertificateSync}.createdAt`, "desc"); + + if (offset !== undefined) { + void query.offset(offset); + } + if (limit !== undefined) { + void query.limit(limit); + } + + const certificateDetails = (await query) as (TCertificateSyncs & { + certificateSerialNumber?: string; + certificateCommonName?: string; + certificateAltNames?: string; + certificateStatus?: string; + certificateNotBefore?: Date; + certificateNotAfter?: Date; + certificateRenewBeforeDays?: number; + certificateRenewedByCertificateId?: string; + certificateRenewalError?: string; + pkiSyncName?: string; + pkiSyncDestination?: string; + })[]; + + return { certificateDetails, totalCount }; + } catch (error) { + throw new DatabaseError({ error, name: "FindWithDetails" }); + } + }; + + return { + ...certificateSyncOrm, + findByPkiSyncId, + findByCertificateId, + findByPkiSyncAndCertificate, + findCertificateIdsByPkiSyncId, + findPkiSyncIdsByCertificateId, + addCertificates, + removeCertificates, + removeAllCertificatesFromSync, + updateSyncStatus, + bulkUpdateSyncStatus, + findWithDetails + }; +}; diff --git a/backend/src/services/certificate-sync/certificate-sync-enums.ts b/backend/src/services/certificate-sync/certificate-sync-enums.ts new file mode 100644 index 000000000..7b9eedafb --- /dev/null +++ b/backend/src/services/certificate-sync/certificate-sync-enums.ts @@ -0,0 +1,7 @@ +export enum CertificateSyncStatus { + Pending = "pending", + Syncing = "syncing", + Succeeded = "succeeded", + Failed = "failed", + Running = "running" +} diff --git a/backend/src/services/certificate-template-v2/certificate-template-v2-service.ts b/backend/src/services/certificate-template-v2/certificate-template-v2-service.ts index c1942b793..0046ae0e5 100644 --- a/backend/src/services/certificate-template-v2/certificate-template-v2-service.ts +++ b/backend/src/services/certificate-template-v2/certificate-template-v2-service.ts @@ -762,32 +762,36 @@ export const certificateTemplateV2ServiceFactory = ({ actorId, actorAuthMethod, actorOrgId, - templateId + templateId, + internal = false }: { actor: ActorType; actorId: string; actorAuthMethod: ActorAuthMethod; actorOrgId: string; templateId: string; + internal?: boolean; }): Promise => { const template = await certificateTemplateV2DAL.findById(templateId); if (!template) { throw new NotFoundError({ message: "Certificate template not found" }); } - const { permission } = await permissionService.getProjectPermission({ - actor, - actorId, - projectId: template.projectId, - actorAuthMethod, - actorOrgId, - actionProjectType: ActionProjectType.CertificateManager - }); + if (!internal) { + const { permission } = await permissionService.getProjectPermission({ + actor, + actorId, + projectId: template.projectId, + actorAuthMethod, + actorOrgId, + actionProjectType: ActionProjectType.CertificateManager + }); - ForbiddenError.from(permission).throwUnlessCan( - ProjectPermissionPkiTemplateActions.Read, - ProjectPermissionSub.CertificateTemplates - ); + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionPkiTemplateActions.Read, + ProjectPermissionSub.CertificateTemplates + ); + } return template; }; diff --git a/backend/src/services/certificate-v3/certificate-v3-queue.ts b/backend/src/services/certificate-v3/certificate-v3-queue.ts new file mode 100644 index 000000000..db7349cd5 --- /dev/null +++ b/backend/src/services/certificate-v3/certificate-v3-queue.ts @@ -0,0 +1,163 @@ +/* eslint-disable no-await-in-loop */ +import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types"; +import { getConfig } from "@app/lib/config/env"; +import { logger } from "@app/lib/logger"; +import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue"; + +import { ActorType } from "../auth/auth-type"; +import { TCertificateDALFactory } from "../certificate/certificate-dal"; +import { CERTIFICATE_RENEWAL_CONFIG } from "../certificate-common/certificate-constants"; +import { TCertificateV3ServiceFactory } from "./certificate-v3-service"; + +type TCertificateV3QueueServiceFactoryDep = { + queueService: TQueueServiceFactory; + certificateDAL: Pick; + certificateV3Service: TCertificateV3ServiceFactory; + auditLogService: Pick; +}; + +export const certificateV3QueueServiceFactory = ({ + queueService, + certificateDAL, + certificateV3Service, + auditLogService +}: TCertificateV3QueueServiceFactoryDep) => { + const appCfg = getConfig(); + + const init = async () => { + if (appCfg.isSecondaryInstance) { + return; + } + + await queueService.stopRepeatableJob( + QueueName.CertificateV3AutoRenewal, + QueueJobs.CertificateV3DailyAutoRenewal, + { pattern: CERTIFICATE_RENEWAL_CONFIG.DAILY_CRON_SCHEDULE, utc: true }, + QueueName.CertificateV3AutoRenewal + ); + + await queueService.startPg( + QueueJobs.CertificateV3DailyAutoRenewal, + async () => { + try { + logger.info(`${QueueJobs.CertificateV3DailyAutoRenewal}: queue task started`); + + const { QUEUE_BATCH_SIZE } = CERTIFICATE_RENEWAL_CONFIG; + let offset = 0; + let hasMore = true; + let totalCertificatesFound = 0; + let totalCertificatesRenewed = 0; + + while (hasMore) { + const certificates = await certificateDAL.findCertificatesEligibleForRenewal({ + limit: QUEUE_BATCH_SIZE, + offset + }); + + if (certificates.length === 0) { + hasMore = false; + break; + } + + totalCertificatesFound += certificates.length; + logger.info( + `${QueueJobs.CertificateV3DailyAutoRenewal}: found ${certificates.length} certificates eligible for renewal (batch ${Math.floor(offset / QUEUE_BATCH_SIZE) + 1}, total found so far: ${totalCertificatesFound})` + ); + + for (const certificate of certificates) { + try { + if (certificate.renewBeforeDays) { + const { MIN_RENEW_BEFORE_DAYS, MAX_RENEW_BEFORE_DAYS } = CERTIFICATE_RENEWAL_CONFIG; + if ( + certificate.renewBeforeDays < MIN_RENEW_BEFORE_DAYS || + certificate.renewBeforeDays > MAX_RENEW_BEFORE_DAYS + ) { + // eslint-disable-next-line no-continue + continue; + } + } + + await certificateV3Service.renewCertificate({ + actor: ActorType.PLATFORM, + actorId: "", + actorAuthMethod: null, + actorOrgId: "", + certificateId: certificate.id, + internal: true + }); + + totalCertificatesRenewed += 1; + + await auditLogService.createAuditLog({ + projectId: certificate.projectId, + actor: { + type: ActorType.PLATFORM, + metadata: {} + }, + event: { + type: EventType.AUTOMATED_RENEW_CERTIFICATE, + metadata: { + certificateId: certificate.id, + commonName: certificate.commonName || "", + profileId: certificate.profileId!, + renewBeforeDays: certificate.renewBeforeDays?.toString() || "", + profileName: certificate.profileName || "" + } + } + }); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger.error(error, `Failed to renew certificate ${certificate.id}: ${errorMessage}`); + await auditLogService.createAuditLog({ + projectId: certificate.projectId, + actor: { + type: ActorType.PLATFORM, + metadata: {} + }, + event: { + type: EventType.AUTOMATED_RENEW_CERTIFICATE_FAILED, + metadata: { + certificateId: certificate.id, + commonName: certificate.commonName || "", + profileId: certificate.profileId || "", + renewBeforeDays: certificate.renewBeforeDays?.toString() || "", + profileName: certificate.profileName || "", + error: errorMessage + } + } + }); + } + } + + offset += QUEUE_BATCH_SIZE; + } + + logger.info( + `${QueueJobs.CertificateV3DailyAutoRenewal}: queue task completed. Renewed ${totalCertificatesRenewed} certificates out of ${totalCertificatesFound}` + ); + } catch (error) { + logger.error(error, `${QueueJobs.CertificateV3DailyAutoRenewal}: certificate renewal failed`); + throw error; + } + }, + { + batchSize: 1, + workerCount: 1, + pollingIntervalSeconds: 60 + } + ); + + await queueService.schedulePg( + QueueJobs.CertificateV3DailyAutoRenewal, + CERTIFICATE_RENEWAL_CONFIG.DAILY_CRON_SCHEDULE, + undefined, + { tz: "UTC" } + ); + }; + + return { + init + }; +}; + +export type TCertificateV3QueueServiceFactory = ReturnType; diff --git a/backend/src/services/certificate-v3/certificate-v3-service.test.ts b/backend/src/services/certificate-v3/certificate-v3-service.test.ts index 95f9a5077..d11cce056 100644 --- a/backend/src/services/certificate-v3/certificate-v3-service.test.ts +++ b/backend/src/services/certificate-v3/certificate-v3-service.test.ts @@ -7,10 +7,12 @@ import { ForbiddenError } from "@casl/ability"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types"; -import { ForbiddenRequestError, NotFoundError } from "@app/lib/errors"; +import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors"; import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal"; -import { ACMESANType, CertificateOrderStatus } from "@app/services/certificate/certificate-types"; +import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal"; +import { ACMESANType, CertificateOrderStatus, CertStatus } from "@app/services/certificate/certificate-types"; import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal"; +import { CaStatus } from "@app/services/certificate-authority/certificate-authority-enums"; import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service"; import { CertExtendedKeyUsageType, @@ -23,14 +25,32 @@ import { EnrollmentType } from "@app/services/certificate-profile/certificate-pr import { TCertificateTemplateV2ServiceFactory } from "@app/services/certificate-template-v2/certificate-template-v2-service"; import { ActorType, AuthMethod } from "../auth/auth-type"; +import { + extractAlgorithmsFromCSR, + extractCertificateRequestFromCSR +} from "../certificate-common/certificate-csr-utils"; import { certificateV3ServiceFactory, TCertificateV3ServiceFactory } from "./certificate-v3-service"; +vi.mock("../certificate-common/certificate-csr-utils", () => ({ + extractCertificateRequestFromCSR: vi.fn(), + extractAlgorithmsFromCSR: vi.fn() +})); + describe("CertificateV3Service", () => { let service: TCertificateV3ServiceFactory; - const mockCertificateDAL: Pick = { + const mockCertificateDAL: Pick = { findOne: vi.fn(), - updateById: vi.fn() + findById: vi.fn(), + updateById: vi.fn(), + transaction: vi.fn().mockImplementation(async (callback: (tx: any) => Promise) => { + const mockTx = {}; + return callback(mockTx); + }) + }; + + const mockCertificateSecretDAL: Pick = { + findOne: vi.fn() }; const mockCertificateAuthorityDAL: Pick = { @@ -76,7 +96,7 @@ describe("CertificateV3Service", () => { beforeEach(() => { // Reset all mocks before each test - vi.clearAllMocks(); + vi.resetAllMocks(); // Mock ForbiddenError.from static method vi.spyOn(ForbiddenError, "from").mockReturnValue({ @@ -95,13 +115,36 @@ describe("CertificateV3Service", () => { } }); + vi.mocked(extractCertificateRequestFromCSR).mockReturnValue({ + commonName: "test.example.com", + keyUsages: [CertKeyUsageType.DIGITAL_SIGNATURE], + extendedKeyUsages: [CertExtendedKeyUsageType.SERVER_AUTH] + }); + + vi.mocked(extractAlgorithmsFromCSR).mockReturnValue({ + keyAlgorithm: "RSA_2048" as any, + signatureAlgorithm: "RSA-SHA256" as any + }); + service = certificateV3ServiceFactory({ certificateDAL: mockCertificateDAL, + certificateSecretDAL: mockCertificateSecretDAL, certificateAuthorityDAL: mockCertificateAuthorityDAL, certificateProfileDAL: mockCertificateProfileDAL, certificateTemplateV2Service: mockCertificateTemplateV2Service, internalCaService: mockInternalCaService, - permissionService: mockPermissionService + permissionService: mockPermissionService, + certificateSyncDAL: { + findPkiSyncIdsByCertificateId: vi.fn().mockResolvedValue([]), + addCertificates: vi.fn().mockResolvedValue([]), + findByPkiSyncAndCertificate: vi.fn().mockResolvedValue(null) + }, + pkiSyncDAL: { + find: vi.fn().mockResolvedValue([]) + }, + pkiSyncQueue: { + queuePkiSyncSyncCertificatesById: vi.fn().mockResolvedValue(undefined) + } }); }); @@ -641,6 +684,11 @@ describe("CertificateV3Service", () => { vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile); vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA); vi.mocked(mockCertificateTemplateV2Service.getTemplateV2ById).mockResolvedValue(mockTemplate); + vi.mocked(mockCertificateTemplateV2Service.validateCertificateRequest).mockResolvedValue({ + isValid: true, + errors: [], + warnings: [] + }); vi.mocked(mockInternalCaService.signCertFromCa).mockResolvedValue(mockSignResult as any); vi.mocked(mockCertificateDAL.findOne).mockResolvedValue(mockCertRecord); vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCertRecord); @@ -1460,4 +1508,714 @@ describe("CertificateV3Service", () => { ).resolves.toBeDefined(); }); }); + + describe("renewCertificate", () => { + const mockOriginalCert = { + id: "cert-123", + status: CertStatus.ACTIVE, + serialNumber: "123456", + friendlyName: "Test Certificate", + commonName: "test.example.com", + notBefore: new Date("2024-01-01"), + notAfter: new Date("2024-02-01"), // 31 days + revokedAt: null, + renewedByCertificateId: null, + profileId: "profile-123", + renewBeforeDays: 7, + caId: "ca-123", + pkiSubscriberId: null, + keyUsages: ["digital_signature", "key_agreement"], + extendedKeyUsages: ["server_auth"], + altNames: "test.example.com,api.example.com", + projectId: "project-123", + createdAt: new Date(), + updatedAt: new Date(), + certificateTemplateId: "template-123", + revocationReason: null, + caCertId: null, + renewedFromCertificateId: null, + renewalError: null, + keyAlgorithm: "RSA_2048", + signatureAlgorithm: "RSA-SHA256" + }; + + const mockProfile = { + id: "profile-123", + projectId: "project-123", + enrollmentType: EnrollmentType.API, + caId: "ca-123", + certificateTemplateId: "template-123", + apiConfig: { + id: "api-config-123", + autoRenew: true, + renewBeforeDays: 14 + }, + createdAt: new Date(), + updatedAt: new Date(), + slug: "test-profile", + description: "Test profile" + }; + + const mockCA = { + id: "ca-123", + projectId: "project-123", + status: CaStatus.ACTIVE, + createdAt: new Date(), + updatedAt: new Date(), + enableDirectIssuance: true, + name: "Test CA", + requireTemplateForIssuance: false, + externalCa: undefined, + parentCaId: null, + type: "ROOT", + friendlyName: "Test CA", + organization: "Test Org", + ou: "Test OU", + country: "US", + province: "CA", + locality: "SF", + commonName: "Test CA", + keyAlgorithm: "RSA_2048", + notAfter: "2025-01-01T00:00:00Z", + notBefore: "2024-01-01T00:00:00Z", + maxPathLength: -1, + activeCaCertId: "cert-123", + dn: "CN=Test CA,O=Test Org,OU=Test OU,C=US", + serialNumber: "123456789", + internalCa: { + id: "internal-ca-123", + parentCaId: null, + type: "ROOT", + friendlyName: "Test CA", + organization: "Test Org", + ou: "Test OU", + country: "US", + province: "CA", + locality: "SF", + commonName: "Test CA", + keyAlgorithm: "RSA_2048", + notAfter: "2025-01-01T00:00:00Z", + notBefore: "2024-01-01T00:00:00Z", + maxPathLength: -1, + activeCaCertId: "cert-123", + dn: "CN=Test CA,O=Test Org,OU=Test OU,C=US", + serialNumber: "123456789" + } + }; + + const mockTemplate = { + id: "template-123", + projectId: "project-123", + name: "Test Template", + createdAt: new Date(), + updatedAt: new Date(), + algorithms: { + signature: ["SHA256-RSA", "SHA384-RSA"], + keyType: ["RSA_2048", "RSA_4096"] + } + }; + + beforeEach(() => { + // Mock current date to be within renewal window + vi.useFakeTimers(); + vi.setSystemTime(new Date("2024-01-26")); // 6 days before cert expires, within renewal window + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it("should successfully renew eligible certificate", async () => { + // Mock the initial findById call + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert); + vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile); + vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA); + vi.mocked(mockCertificateTemplateV2Service.getTemplateV2ById).mockResolvedValue(mockTemplate); + vi.mocked(mockCertificateTemplateV2Service.validateCertificateRequest).mockResolvedValue({ + isValid: true, + errors: [], + warnings: [] + }); + vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue({ + certificate: "renewed-cert", + certificateChain: "renewed-chain", + issuingCaCertificate: "issuing-ca", + privateKey: "private-key", + serialNumber: "789012", + ca: mockCA + }); + + const newCert = { ...mockOriginalCert, id: "cert-456", serialNumber: "789012" }; + vi.mocked(mockCertificateDAL.findOne).mockResolvedValue(newCert); + vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(newCert); + + // Mock the transaction to return the expected structure + vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise) => { + const mockTx = {}; + const result = await callback(mockTx); + return result; + }); + + const result = await service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }); + + expect(result).toHaveProperty("certificate", "renewed-cert"); + expect(result).toHaveProperty("certificateId", "cert-456"); + expect(mockCertificateDAL.updateById).toHaveBeenCalledWith( + "cert-456", + { + profileId: "profile-123", + renewBeforeDays: 14, + renewedFromCertificateId: "cert-123" + }, + {} + ); + expect(mockCertificateDAL.updateById).toHaveBeenCalledWith( + "cert-123", + { + renewedByCertificateId: "cert-456", + renewalError: null + }, + {} + ); + }); + + it("should validate certificate against current template during renewal", async () => { + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile); + vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA); + vi.mocked(mockCertificateTemplateV2Service.getTemplateV2ById).mockResolvedValue(mockTemplate); + vi.mocked(mockCertificateTemplateV2Service.validateCertificateRequest).mockResolvedValue({ + isValid: false, + errors: ["Subject alternative name not allowed"], + warnings: [] + }); + vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any); + + // Mock updateById to handle the renewal error logging + vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockOriginalCert); + + // Set up transaction mock to properly handle errors + vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise) => { + const mockTx = {}; + return callback(mockTx); + }); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow(BadRequestError); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow("Certificate renewal failed. Errors: Subject alternative name not allowed"); + + // Should store template validation error + expect(mockCertificateDAL.updateById).toHaveBeenCalledWith("cert-123", { + renewalError: "Template validation failed: Subject alternative name not allowed" + }); + }); + + it("should reject renewal if certificate is not from a profile", async () => { + const certWithoutProfile = { ...mockOriginalCert, profileId: null }; + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(certWithoutProfile); + + // Set up transaction mock to properly handle errors + vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise) => { + const mockTx = {}; + return callback(mockTx); + }); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow(ForbiddenRequestError); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow("Only certificates issued from a profile can be renewed"); + }); + + it("should reject renewal if certificate was issued from CSR (external private key)", async () => { + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile); + vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue(null as any); + + vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise) => { + const mockTx = {}; + return callback(mockTx); + }); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow(ForbiddenRequestError); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow("certificates issued from CSR (external private key) cannot be renewed"); + }); + + it("should reject renewal if certificate is already renewed", async () => { + const alreadyRenewedCert = { ...mockOriginalCert, renewedByCertificateId: "cert-456" }; + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(alreadyRenewedCert); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile); + vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA); + vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any); + + // Mock updateById to handle the renewal error logging + vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(alreadyRenewedCert); + + // Set up transaction mock to properly handle errors + vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise) => { + const mockTx = {}; + return callback(mockTx); + }); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow(BadRequestError); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow("Certificate has already been renewed"); + }); + + it("should reject renewal if certificate is expired", async () => { + const expiredCert = { + ...mockOriginalCert, + notAfter: new Date("2024-01-20") // Expired 6 days ago + }; + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(expiredCert); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile); + vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA); + vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any); + + // Mock updateById to handle the renewal error logging + vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(expiredCert); + + // Set up transaction mock to properly handle errors + vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise) => { + const mockTx = {}; + return callback(mockTx); + }); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow(BadRequestError); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow("Certificate is already expired"); + }); + + it("should reject renewal if certificate is revoked", async () => { + const revokedCert = { + ...mockOriginalCert, + revokedAt: new Date("2024-01-15") + }; + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(revokedCert); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile); + vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA); + vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any); + + // Mock updateById to handle the renewal error logging + vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(revokedCert); + + // Set up transaction mock to properly handle errors + vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise) => { + const mockTx = {}; + return callback(mockTx); + }); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow(BadRequestError); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow("Certificate is revoked and cannot be renewed"); + }); + + it("should reject renewal if CA is inactive", async () => { + const inactiveCA = { ...mockCA, status: CaStatus.DISABLED }; + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile); + vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(inactiveCA); + vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any); + + // Mock updateById to handle the renewal error logging + vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockOriginalCert); + + // Set up transaction mock to properly handle errors + vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise) => { + const mockTx = {}; + return callback(mockTx); + }); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow(BadRequestError); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow("Certificate is not eligible for renewal: Certificate Authority is disabled, must be active"); + }); + + it("should reject renewal if new certificate would outlive CA", async () => { + const shortLivedCA = { + ...mockCA, + internalCa: { + ...mockCA.internalCa, + notAfter: "2024-01-28T00:00:00Z" + } + }; + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile); + vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(shortLivedCA); + vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any); + + // Mock updateById to handle the renewal error logging + vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockOriginalCert); + + // Set up transaction mock to properly handle errors + vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise) => { + const mockTx = {}; + return callback(mockTx); + }); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow(BadRequestError); + + await expect( + service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }) + ).rejects.toThrow(/New certificate would expire \(.+\) after its issuing CA \(.+\)/); + }); + + it("should allow manual renewal outside window (manual renewal always bypasses window)", async () => { + vi.setSystemTime(new Date("2024-01-15")); // 17 days before expiry, outside 7-day window + + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockOriginalCert); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile); + vi.mocked(mockCertificateAuthorityDAL.findByIdWithAssociatedCa).mockResolvedValue(mockCA); + vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any); + vi.mocked(mockCertificateTemplateV2Service.getTemplateV2ById).mockResolvedValue(mockTemplate); + vi.mocked(mockCertificateTemplateV2Service.validateCertificateRequest).mockResolvedValue({ + isValid: true, + errors: [], + warnings: [] + }); + vi.mocked(mockInternalCaService.issueCertFromCa).mockResolvedValue({ + certificate: "renewed-cert", + certificateChain: "renewed-chain", + issuingCaCertificate: "issuing-ca", + privateKey: "private-key", + serialNumber: "789012", + ca: mockCA + }); + + const newCert = { ...mockOriginalCert, id: "cert-456", serialNumber: "789012" }; + vi.mocked(mockCertificateDAL.findOne).mockResolvedValue(newCert); + vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(newCert); + + // Set up transaction mock to properly handle the renewal process + vi.mocked(mockCertificateDAL.transaction).mockImplementation(async (callback: (tx: any) => Promise) => { + const mockTx = {}; + return callback(mockTx); + }); + + const result = await service.renewCertificate({ + certificateId: "cert-123", + ...mockActor + }); + + expect(result).toHaveProperty("certificate", "renewed-cert"); + }); + }); + + describe("updateRenewalConfig", () => { + it("should update renewal configuration successfully", async () => { + const mockCert = { + id: "cert-123", + profileId: "profile-123", + renewedByCertificateId: null, + notBefore: new Date("2026-01-01"), + notAfter: new Date("2026-02-01"), + projectId: "project-123", + status: CertStatus.ACTIVE, + revokedAt: null, + commonName: "" + }; + + const mockProfile = { + id: "profile-123", + enrollmentType: EnrollmentType.API, + projectId: "project-123" + }; + + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any); + vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any); + vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCert as any); + + const result = await service.updateRenewalConfig({ + actor: ActorType.USER, + actorId: "user-123", + actorAuthMethod: AuthMethod.EMAIL, + actorOrgId: "org-123", + certificateId: "cert-123", + renewBeforeDays: 7 + }); + + expect(result).toEqual({ + projectId: "project-123", + renewBeforeDays: 7, + commonName: "" + }); + + expect(mockCertificateDAL.updateById).toHaveBeenCalledWith("cert-123", { + renewBeforeDays: 7 + }); + }); + + it("should reject update if certificate is not from profile", async () => { + const mockCert = { + id: "cert-123", + profileId: null, + renewedByCertificateId: null, + projectId: "project-123" + }; + + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any); + + await expect( + service.updateRenewalConfig({ + actor: ActorType.USER, + actorId: "user-123", + actorAuthMethod: AuthMethod.EMAIL, + actorOrgId: "org-123", + certificateId: "cert-123", + renewBeforeDays: 7 + }) + ).rejects.toThrow(BadRequestError); + + await expect( + service.updateRenewalConfig({ + actor: ActorType.USER, + actorId: "user-123", + actorAuthMethod: AuthMethod.EMAIL, + actorOrgId: "org-123", + certificateId: "cert-123", + renewBeforeDays: 7 + }) + ).rejects.toThrow("Certificate is not eligible for auto-renewal: certificate was not issued from a profile"); + }); + + it("should reject update if certificate is already renewed", async () => { + const mockCert = { + id: "cert-123", + profileId: "profile-123", + renewedByCertificateId: "cert-456", + projectId: "project-123", + status: CertStatus.ACTIVE, + revokedAt: null, + notBefore: new Date("2026-01-01"), + notAfter: new Date("2026-02-01") + }; + + const mockProfile = { + id: "profile-123", + enrollmentType: EnrollmentType.API, + projectId: "project-123" + }; + + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any); + vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any); + + await expect( + service.updateRenewalConfig({ + actor: ActorType.USER, + actorId: "user-123", + actorAuthMethod: AuthMethod.EMAIL, + actorOrgId: "org-123", + certificateId: "cert-123", + renewBeforeDays: 7 + }) + ).rejects.toThrow(BadRequestError); + + await expect( + service.updateRenewalConfig({ + actor: ActorType.USER, + actorId: "user-123", + actorAuthMethod: AuthMethod.EMAIL, + actorOrgId: "org-123", + certificateId: "cert-123", + renewBeforeDays: 7 + }) + ).rejects.toThrow("Certificate is not eligible for auto-renewal: certificate has already been renewed"); + }); + + it("should reject update if renewBeforeDays >= certificate TTL", async () => { + const mockCert = { + id: "cert-123", + profileId: "profile-123", + renewedByCertificateId: null, + notBefore: new Date("2026-01-01"), + notAfter: new Date("2026-01-08"), + projectId: "project-123", + status: CertStatus.ACTIVE, + revokedAt: null + }; + + const mockProfile = { + id: "profile-123", + enrollmentType: EnrollmentType.API, + projectId: "project-123" + }; + + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any); + vi.mocked(mockCertificateSecretDAL.findOne).mockResolvedValue({ id: "secret-123", certId: "cert-123" } as any); + + await expect( + service.updateRenewalConfig({ + actor: ActorType.USER, + actorId: "user-123", + actorAuthMethod: AuthMethod.EMAIL, + actorOrgId: "org-123", + certificateId: "cert-123", + renewBeforeDays: 8 // Greater than 7-day TTL + }) + ).rejects.toThrow(BadRequestError); + + await expect( + service.updateRenewalConfig({ + actor: ActorType.USER, + actorId: "user-123", + actorAuthMethod: AuthMethod.EMAIL, + actorOrgId: "org-123", + certificateId: "cert-123", + renewBeforeDays: 8 + }) + ).rejects.toThrow("Invalid renewal configuration: renewal threshold exceeds certificate validity period"); + }); + }); + + describe("disableRenewalConfig", () => { + it("should disable renewal configuration successfully", async () => { + const mockCert = { + id: "cert-123", + profileId: "profile-123", + projectId: "project-123", + commonName: "" + }; + + const mockProfile = { + id: "profile-123", + enrollmentType: EnrollmentType.API, + projectId: "project-123" + }; + + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any); + vi.mocked(mockCertificateProfileDAL.findByIdWithConfigs).mockResolvedValue(mockProfile as any); + vi.mocked(mockCertificateDAL.updateById).mockResolvedValue(mockCert as any); + + const result = await service.disableRenewalConfig({ + actor: ActorType.USER, + actorId: "user-123", + actorAuthMethod: AuthMethod.EMAIL, + actorOrgId: "org-123", + certificateId: "cert-123" + }); + + expect(result).toEqual({ + projectId: "project-123", + commonName: "" + }); + + expect(mockCertificateDAL.updateById).toHaveBeenCalledWith("cert-123", { + renewBeforeDays: null + }); + }); + + it("should reject disable if certificate is not from profile", async () => { + const mockCert = { + id: "cert-123", + profileId: null, + projectId: "project-123" + }; + + vi.mocked(mockCertificateDAL.findById).mockResolvedValue(mockCert as any); + + await expect( + service.disableRenewalConfig({ + actor: ActorType.USER, + actorId: "user-123", + actorAuthMethod: AuthMethod.EMAIL, + actorOrgId: "org-123", + certificateId: "cert-123" + }) + ).rejects.toThrow(BadRequestError); + + await expect( + service.disableRenewalConfig({ + actor: ActorType.USER, + actorId: "user-123", + actorAuthMethod: AuthMethod.EMAIL, + actorOrgId: "org-123", + certificateId: "cert-123" + }) + ).rejects.toThrow("Certificate is not eligible for auto-renewal: certificate was not issued from a profile"); + }); + }); }); diff --git a/backend/src/services/certificate-v3/certificate-v3-service.ts b/backend/src/services/certificate-v3/certificate-v3-service.ts index 1c11b0a00..51c79f135 100644 --- a/backend/src/services/certificate-v3/certificate-v3-service.ts +++ b/backend/src/services/certificate-v3/certificate-v3-service.ts @@ -1,50 +1,73 @@ import { ForbiddenError } from "@casl/ability"; import { randomUUID } from "crypto"; +import RE2 from "re2"; import { ActionProjectType } from "@app/db/schemas"; import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types"; import { + ProjectPermissionCertificateActions, ProjectPermissionCertificateProfileActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission"; import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors"; import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type"; import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal"; +import { TCertificateSecretDALFactory } from "@app/services/certificate/certificate-secret-dal"; import { + CertExtendedKeyUsage, CertificateOrderStatus, CertKeyAlgorithm, - CertSignatureAlgorithm + CertKeyType, + CertKeyUsage, + CertSignatureAlgorithm, + CertStatus } from "@app/services/certificate/certificate-types"; import { TCertificateAuthorityDALFactory, TCertificateAuthorityWithAssociatedCa } from "@app/services/certificate-authority/certificate-authority-dal"; -import { CaType } from "@app/services/certificate-authority/certificate-authority-enums"; +import { CaStatus, CaType } from "@app/services/certificate-authority/certificate-authority-enums"; import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service"; import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal"; import { EnrollmentType } from "@app/services/certificate-profile/certificate-profile-types"; import { TCertificateTemplateV2ServiceFactory } from "@app/services/certificate-template-v2/certificate-template-v2-service"; import { CertSubjectAlternativeNameType } from "../certificate-common/certificate-constants"; +import { + extractAlgorithmsFromCSR, + extractCertificateRequestFromCSR +} from "../certificate-common/certificate-csr-utils"; import { bufferToString, buildCertificateSubjectFromTemplate, buildSubjectAlternativeNamesFromTemplate, + convertExtendedKeyUsageArrayFromLegacy, convertExtendedKeyUsageArrayToLegacy, + convertKeyUsageArrayFromLegacy, convertKeyUsageArrayToLegacy, mapEnumsForValidation, normalizeDateForApi } from "../certificate-common/certificate-utils"; +import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal"; +import { TPkiSyncDALFactory } from "../pki-sync/pki-sync-dal"; +import { TPkiSyncQueueFactory } from "../pki-sync/pki-sync-queue"; +import { addRenewedCertificateToSyncs, triggerAutoSyncForCertificate } from "../pki-sync/pki-sync-utils"; import { TCertificateFromProfileResponse, TCertificateOrderResponse, + TDisableRenewalConfigDTO, + TDisableRenewalResponse, TIssueCertificateFromProfileDTO, TOrderCertificateFromProfileDTO, - TSignCertificateFromProfileDTO + TRenewalConfigResponse, + TRenewCertificateDTO, + TSignCertificateFromProfileDTO, + TUpdateRenewalConfigDTO } from "./certificate-v3-types"; type TCertificateV3ServiceFactoryDep = { - certificateDAL: Pick; + certificateDAL: Pick; + certificateSecretDAL: Pick; certificateAuthorityDAL: Pick; certificateProfileDAL: Pick; certificateTemplateV2Service: Pick< @@ -53,6 +76,12 @@ type TCertificateV3ServiceFactoryDep = { >; internalCaService: Pick; permissionService: Pick; + certificateSyncDAL: Pick< + TCertificateSyncDALFactory, + "findPkiSyncIdsByCertificateId" | "addCertificates" | "findByPkiSyncAndCertificate" + >; + pkiSyncDAL: Pick; + pkiSyncQueue: Pick; }; export type TCertificateV3ServiceFactory = ReturnType; @@ -95,6 +124,77 @@ const validateProfileAndPermissions = async ( return profile; }; +const validateRenewalEligibility = ( + certificate: { + id: string; + status: string; + notBefore: Date; + notAfter: Date; + revokedAt?: Date | null; + renewedByCertificateId?: string | null; + profileId?: string | null; + caId?: string | null; + pkiSubscriberId?: string | null; + }, + ca: TCertificateAuthorityWithAssociatedCa +) => { + const errors: string[] = []; + + if (certificate.status !== CertStatus.ACTIVE) { + errors.push(`Certificate status is ${certificate.status}, must be ${CertStatus.ACTIVE}`); + } + + const now = new Date(); + if (certificate.notAfter <= now) { + errors.push("Certificate is already expired"); + } + + if (certificate.revokedAt) { + errors.push("Certificate is revoked and cannot be renewed"); + } + + const caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL; + const isInternalCa = caType === CaType.INTERNAL; + const isConnectedExternalCa = caType === CaType.ACME || caType === CaType.AZURE_AD_CS; + const isImportedCertificate = certificate.pkiSubscriberId != null && !certificate.profileId; + + if (!isInternalCa && !isConnectedExternalCa) { + errors.push(`CA type ${String(caType)} does not support renewal`); + } + + if (isImportedCertificate) { + errors.push("Externally imported certificates cannot be renewed"); + } + + if (ca.status !== CaStatus.ACTIVE) { + errors.push(`Certificate Authority is ${ca.status}, must be ${CaStatus.ACTIVE}`); + } + + if (certificate.renewedByCertificateId) { + errors.push("Certificate has already been renewed"); + } + + const certificateTtlInDays = Math.ceil( + (certificate.notAfter.getTime() - certificate.notBefore.getTime()) / (24 * 60 * 60 * 1000) + ); + + if (ca.internalCa?.notAfter) { + const caExpiryDate = new Date(ca.internalCa.notAfter); + const proposedCertExpiryDate = new Date(now.getTime() + certificateTtlInDays * 24 * 60 * 60 * 1000); + + if (proposedCertExpiryDate > caExpiryDate) { + errors.push( + `New certificate would expire (${proposedCertExpiryDate.toISOString()}) after its issuing CA (${caExpiryDate.toISOString()})` + ); + } + } + + return { + isEligible: errors.length === 0, + errors + }; +}; + const validateCaSupport = (ca: TCertificateAuthorityWithAssociatedCa, operation: string) => { const caType = (ca.externalCa?.type as CaType) ?? CaType.INTERNAL; if (caType !== CaType.INTERNAL) { @@ -129,11 +229,11 @@ const validateAlgorithmCompatibility = ( const keyType = parts[parts.length - 1]; if (caKeyAlgorithm.startsWith("RSA")) { - return keyType === "RSA"; + return keyType === CertKeyType.RSA; } if (caKeyAlgorithm.startsWith("EC")) { - return keyType === "ECDSA"; + return keyType === CertKeyType.ECDSA; } return false; @@ -155,13 +255,93 @@ const extractCertificateFromBuffer = (certData: Buffer | { rawData: Buffer } | s return bufferToString(certData as unknown as Buffer); }; +const parseKeyUsages = (keyUsages: unknown): CertKeyUsage[] => { + if (!keyUsages) return []; + if (Array.isArray(keyUsages)) return keyUsages as CertKeyUsage[]; + return (keyUsages as string).split(",").map((usage) => usage.trim() as CertKeyUsage); +}; + +const parseExtendedKeyUsages = (extendedKeyUsages: unknown): CertExtendedKeyUsage[] => { + if (!extendedKeyUsages) return []; + if (Array.isArray(extendedKeyUsages)) return extendedKeyUsages as CertExtendedKeyUsage[]; + return (extendedKeyUsages as string).split(",").map((usage) => usage.trim() as CertExtendedKeyUsage); +}; + +const isValidRenewalTiming = (renewBeforeDays: number, certificateExpiryDate: Date): boolean => { + const renewalDate = new Date(certificateExpiryDate.getTime() - renewBeforeDays * 24 * 60 * 60 * 1000); + const tomorrow = new Date(); + tomorrow.setDate(tomorrow.getDate() + 1); + tomorrow.setHours(0, 0, 0, 0); + + return renewalDate >= tomorrow; +}; + +const calculateRenewalThreshold = ( + profileRenewBeforeDays: number | undefined, + certificateTtlInDays: number +): number | undefined => { + if (!profileRenewBeforeDays) { + return undefined; + } + + if (certificateTtlInDays > profileRenewBeforeDays) { + return profileRenewBeforeDays; + } + + return Math.max(1, certificateTtlInDays - 1); +}; + +const parseTtlToDays = (ttl: string): number => { + const match = ttl.match(new RE2("^(\\d+)([dhm])$")); + if (!match) { + throw new BadRequestError({ message: `Invalid TTL format: ${ttl}` }); + } + + const [, value, unit] = match; + const numValue = parseInt(value, 10); + + switch (unit) { + case "d": + return numValue; + case "h": + return Math.ceil(numValue / 24); + case "m": + return Math.ceil(numValue / (24 * 60)); + default: + throw new BadRequestError({ message: `Unsupported TTL unit: ${unit}` }); + } +}; + +const calculateFinalRenewBeforeDays = ( + profile: { apiConfig?: { autoRenew?: boolean; renewBeforeDays?: number } }, + ttl: string, + certificateExpiryDate: Date +): number | undefined => { + if (!profile.apiConfig?.autoRenew || !profile.apiConfig.renewBeforeDays) { + return undefined; + } + + const certificateTtlInDays = parseTtlToDays(ttl); + const renewBeforeDays = calculateRenewalThreshold(profile.apiConfig.renewBeforeDays, certificateTtlInDays); + + if (!renewBeforeDays) { + return undefined; + } + + return isValidRenewalTiming(renewBeforeDays, certificateExpiryDate) ? renewBeforeDays : undefined; +}; + export const certificateV3ServiceFactory = ({ certificateDAL, + certificateSecretDAL, certificateAuthorityDAL, certificateProfileDAL, certificateTemplateV2Service, internalCaService, - permissionService + permissionService, + certificateSyncDAL, + pkiSyncDAL, + pkiSyncQueue }: TCertificateV3ServiceFactoryDep) => { const issueCertificateFromProfile = async ({ profileId, @@ -198,7 +378,8 @@ export const certificateV3ServiceFactory = ({ actorId, actorAuthMethod, actorOrgId, - templateId: profile.certificateTemplateId + templateId: profile.certificateTemplateId, + internal: true }); if (!template) { throw new NotFoundError({ message: "Certificate template not found for this profile" }); @@ -222,10 +403,6 @@ export const certificateV3ServiceFactory = ({ validateCaSupport(ca, "direct certificate issuance"); - if (!actorAuthMethod) { - throw new BadRequestError({ message: "Authentication method is required for certificate issuance" }); - } - validateAlgorithmCompatibility(ca, template); const effectiveSignatureAlgorithm = certificateRequest.signatureAlgorithm as CertSignatureAlgorithm | undefined; @@ -274,7 +451,16 @@ export const certificateV3ServiceFactory = ({ throw new NotFoundError({ message: "Certificate was issued but could not be found in database" }); } - await certificateDAL.updateById(cert.id, { profileId }); + const finalRenewBeforeDays = calculateFinalRenewBeforeDays( + profile, + certificateRequest.validity.ttl, + new Date(cert.notAfter) + ); + + await certificateDAL.updateById(cert.id, { + profileId, + renewBeforeDays: finalRenewBeforeDays + }); return { certificate: bufferToString(certificate), @@ -284,7 +470,8 @@ export const certificateV3ServiceFactory = ({ serialNumber, certificateId: cert.id, projectId: profile.projectId, - profileName: profile.slug + profileName: profile.slug, + commonName: cert.commonName || "" }; }; @@ -294,8 +481,6 @@ export const certificateV3ServiceFactory = ({ validity, notBefore, notAfter, - signatureAlgorithm, - keyAlgorithm, actor, actorId, actorAuthMethod, @@ -319,38 +504,40 @@ export const certificateV3ServiceFactory = ({ validateCaSupport(ca, "CSR signing"); - if (!actorAuthMethod) { - throw new BadRequestError({ message: "Authentication method is required for certificate signing" }); - } - const template = await certificateTemplateV2Service.getTemplateV2ById({ actor, actorId, actorAuthMethod, actorOrgId, - templateId: profile.certificateTemplateId + templateId: profile.certificateTemplateId, + internal: true }); if (!template) { throw new NotFoundError({ message: "Certificate template not found for this profile" }); } + const certificateRequest = extractCertificateRequestFromCSR(csr); + const mappedCertificateRequest = mapEnumsForValidation(certificateRequest); + + const { keyAlgorithm: extractedKeyAlgorithm, signatureAlgorithm: extractedSignatureAlgorithm } = + extractAlgorithmsFromCSR(csr); + + const validationResult = await certificateTemplateV2Service.validateCertificateRequest( + profile.certificateTemplateId, + mappedCertificateRequest + ); + + if (!validationResult.isValid) { + throw new BadRequestError({ + message: `Certificate request validation failed: ${validationResult.errors.join(", ")}` + }); + } + validateAlgorithmCompatibility(ca, template); - const effectiveSignatureAlgorithm = signatureAlgorithm; - const effectiveKeyAlgorithm = keyAlgorithm; - - if (template.algorithms?.keyAlgorithm && !effectiveKeyAlgorithm) { - throw new BadRequestError({ - message: "Key algorithm is required by template policy but not provided in request" - }); - } - - if (template.algorithms?.signature && !effectiveSignatureAlgorithm) { - throw new BadRequestError({ - message: "Signature algorithm is required by template policy but not provided in request" - }); - } + const effectiveSignatureAlgorithm = extractedSignatureAlgorithm; + const effectiveKeyAlgorithm = extractedKeyAlgorithm; const { certificate, certificateChain, issuingCaCertificate, serialNumber } = await internalCaService.signCertFromCa({ @@ -371,7 +558,12 @@ export const certificateV3ServiceFactory = ({ throw new NotFoundError({ message: "Certificate was signed but could not be found in database" }); } - await certificateDAL.updateById(cert.id, { profileId }); + const finalRenewBeforeDays = calculateFinalRenewBeforeDays(profile, validity.ttl, new Date(cert.notAfter)); + + await certificateDAL.updateById(cert.id, { + profileId, + renewBeforeDays: finalRenewBeforeDays + }); const certificateString = extractCertificateFromBuffer(certificate as unknown as Buffer); const certificateChainString = extractCertificateFromBuffer(certificateChain as unknown as Buffer); @@ -383,7 +575,8 @@ export const certificateV3ServiceFactory = ({ serialNumber, certificateId: cert.id, projectId: profile.projectId, - profileName: profile.slug + profileName: profile.slug, + commonName: cert.commonName || "" }; }; @@ -479,9 +672,413 @@ export const certificateV3ServiceFactory = ({ }); }; + const renewCertificate = async ({ + certificateId, + actor, + actorId, + actorAuthMethod, + actorOrgId, + internal = false + }: TRenewCertificateDTO & { internal?: boolean }): Promise => { + const renewalResult = await certificateDAL.transaction(async (tx) => { + const originalCert = await certificateDAL.findById(certificateId, tx); + if (!originalCert) { + throw new NotFoundError({ message: "Certificate not found" }); + } + + if (!originalCert.profileId) { + throw new ForbiddenRequestError({ + message: "Only certificates issued from a profile can be renewed" + }); + } + + const originalSignatureAlgorithm = originalCert.signatureAlgorithm as CertSignatureAlgorithm; + const originalKeyAlgorithm = originalCert.keyAlgorithm as CertKeyAlgorithm; + + if (!originalSignatureAlgorithm || !originalKeyAlgorithm) { + throw new BadRequestError({ + message: + "Original certificate does not have algorithm information stored. Cannot renew certificate issued before algorithm tracking was implemented." + }); + } + + const profile = await certificateProfileDAL.findByIdWithConfigs(originalCert.profileId); + if (!profile) { + throw new NotFoundError({ message: "Certificate profile not found" }); + } + + if (profile.enrollmentType !== EnrollmentType.API) { + throw new ForbiddenRequestError({ + message: "Certificate is not eligible for renewal: EST certificates cannot be renewed through this endpoint" + }); + } + + const certificateSecret = await certificateSecretDAL.findOne({ certId: originalCert.id }, tx); + if (!certificateSecret) { + throw new ForbiddenRequestError({ + message: + "Certificate is not eligible for renewal: certificates issued from CSR (external private key) cannot be renewed" + }); + } + + if (!internal) { + const { permission } = await permissionService.getProjectPermission({ + actor, + actorId, + projectId: profile.projectId, + actorAuthMethod, + actorOrgId, + actionProjectType: ActionProjectType.CertificateManager + }); + + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionCertificateProfileActions.IssueCert, + ProjectPermissionSub.CertificateProfiles + ); + } + + const ca = await certificateAuthorityDAL.findByIdWithAssociatedCa(profile.caId); + if (!ca) { + throw new NotFoundError({ message: "Certificate Authority not found" }); + } + + const eligibilityCheck = validateRenewalEligibility(originalCert, ca); + if (!eligibilityCheck.isEligible) { + await certificateDAL.updateById(originalCert.id, { + renewalError: `Certificate is not eligible for renewal: ${eligibilityCheck.errors.join(", ")}` + }); + throw new BadRequestError({ + message: `Certificate is not eligible for renewal: ${eligibilityCheck.errors.join(", ")}` + }); + } + + validateCaSupport(ca, "direct certificate issuance"); + + const template = await certificateTemplateV2Service.getTemplateV2ById({ + actor, + actorId, + actorAuthMethod, + actorOrgId, + templateId: profile.certificateTemplateId, + internal + }); + + if (!template) { + throw new NotFoundError({ message: "Certificate template not found for this profile" }); + } + + const originalTtlInDays = Math.ceil( + (new Date(originalCert.notAfter).getTime() - new Date(originalCert.notBefore).getTime()) / (1000 * 60 * 60 * 24) + ); + const ttl = `${originalTtlInDays}d`; + + const certificateRequest = { + commonName: originalCert.commonName || undefined, + keyUsages: convertKeyUsageArrayFromLegacy(parseKeyUsages(originalCert.keyUsages)), + extendedKeyUsages: convertExtendedKeyUsageArrayFromLegacy( + parseExtendedKeyUsages(originalCert.extendedKeyUsages) + ), + subjectAlternativeNames: originalCert.altNames + ? originalCert.altNames.split(",").map((san) => { + const trimmed = san.trim(); + + const isIpv4 = new RE2("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$").test(trimmed); + const isIpv6 = new RE2("^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$").test(trimmed); + if (isIpv4 || isIpv6) { + return { + type: CertSubjectAlternativeNameType.IP_ADDRESS, + value: trimmed + }; + } + + if (new RE2("^[^@]+@[^@]+\\.[^@]+$").test(trimmed)) { + return { + type: CertSubjectAlternativeNameType.EMAIL, + value: trimmed + }; + } + + if (new RE2("^[a-zA-Z][a-zA-Z0-9+.-]*:").test(trimmed)) { + return { + type: CertSubjectAlternativeNameType.URI, + value: trimmed + }; + } + + return { + type: CertSubjectAlternativeNameType.DNS_NAME, + value: trimmed + }; + }) + : [], + validity: { + ttl + }, + signatureAlgorithm: originalCert.signatureAlgorithm || undefined, + keyAlgorithm: originalCert.keyAlgorithm || undefined + }; + + const validationResult = await certificateTemplateV2Service.validateCertificateRequest( + profile.certificateTemplateId, + certificateRequest + ); + + if (!validationResult.isValid) { + await certificateDAL.updateById(originalCert.id, { + renewalError: `Template validation failed: ${validationResult.errors.join(", ")}` + }); + + throw new BadRequestError({ + message: `Certificate renewal failed. Errors: ${validationResult.errors.join(", ")}` + }); + } + + validateAlgorithmCompatibility(ca, template); + const notBefore = new Date(); + const notAfter = new Date(Date.now() + parseTtlToDays(ttl) * 24 * 60 * 60 * 1000); + + const finalRenewBeforeDays = calculateFinalRenewBeforeDays(profile, ttl, notAfter); + + const { certificate, certificateChain, issuingCaCertificate, serialNumber } = + await internalCaService.issueCertFromCa({ + caId: ca.id, + friendlyName: originalCert.friendlyName || originalCert.commonName || "Renewed Certificate", + commonName: originalCert.commonName || "", + altNames: originalCert.altNames || "", + ttl, + notBefore: normalizeDateForApi(notBefore), + notAfter: normalizeDateForApi(notAfter), + keyUsages: parseKeyUsages(originalCert.keyUsages), + extendedKeyUsages: parseExtendedKeyUsages(originalCert.extendedKeyUsages), + signatureAlgorithm: originalSignatureAlgorithm, + keyAlgorithm: originalKeyAlgorithm, + isFromProfile: true, + actor, + actorId, + actorAuthMethod, + actorOrgId, + internal: true, + tx + }); + + const newCert = await certificateDAL.findOne({ serialNumber, caId: ca.id }, tx); + if (!newCert) { + throw new NotFoundError({ message: "Certificate was signed but could not be found in database" }); + } + + await certificateDAL.updateById( + newCert.id, + { + profileId: originalCert.profileId, + renewBeforeDays: finalRenewBeforeDays, + renewedFromCertificateId: originalCert.id + }, + tx + ); + + await certificateDAL.updateById( + originalCert.id, + { + renewedByCertificateId: newCert.id, + renewalError: null + }, + tx + ); + + await addRenewedCertificateToSyncs(originalCert.id, newCert.id, { certificateSyncDAL }, tx); + + return { + certificate, + certificateChain, + issuingCaCertificate, + serialNumber, + newCert, + originalCert, + profile + }; + }); + + await triggerAutoSyncForCertificate(renewalResult.newCert.id, { + certificateSyncDAL, + pkiSyncDAL, + pkiSyncQueue + }); + + return { + certificate: renewalResult.certificate, + issuingCaCertificate: renewalResult.issuingCaCertificate, + certificateChain: renewalResult.certificateChain, + serialNumber: renewalResult.serialNumber, + certificateId: renewalResult.newCert.id, + projectId: renewalResult.profile.projectId, + profileName: renewalResult.profile.slug, + commonName: renewalResult.originalCert.commonName || "" + }; + }; + + const updateRenewalConfig = async ({ + certificateId, + renewBeforeDays, + actor, + actorId, + actorAuthMethod, + actorOrgId + }: TUpdateRenewalConfigDTO): Promise => { + const certificate = await certificateDAL.findById(certificateId); + if (!certificate) { + throw new NotFoundError({ message: "Certificate not found" }); + } + + const { permission } = await permissionService.getProjectPermission({ + actor, + actorId, + projectId: certificate.projectId, + actorAuthMethod, + actorOrgId, + actionProjectType: ActionProjectType.CertificateManager + }); + + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionCertificateActions.Edit, + ProjectPermissionSub.Certificates + ); + + if (!certificate.profileId) { + throw new BadRequestError({ + message: "Certificate is not eligible for auto-renewal: certificate was not issued from a profile" + }); + } + + const profile = await certificateProfileDAL.findByIdWithConfigs(certificate.profileId); + if (!profile) { + throw new NotFoundError({ message: "Certificate profile not found" }); + } + + if (profile.enrollmentType !== EnrollmentType.API) { + throw new ForbiddenRequestError({ + message: "Certificate is not eligible for auto-renewal: EST certificates cannot be auto-renewed" + }); + } + + const certificateSecret = await certificateSecretDAL.findOne({ certId: certificate.id }); + if (!certificateSecret) { + throw new ForbiddenRequestError({ + message: + "Certificate is not eligible for auto-renewal: certificates issued from CSR (external private key) cannot be auto-renewed" + }); + } + + if (certificate.status !== CertStatus.ACTIVE) { + throw new BadRequestError({ + message: `Certificate is not eligible for auto-renewal: certificate status is ${certificate.status}, must be active` + }); + } + + const now = new Date(); + if (certificate.notAfter <= now) { + throw new BadRequestError({ + message: "Certificate is not eligible for auto-renewal: certificate has expired" + }); + } + + if (certificate.revokedAt) { + throw new BadRequestError({ + message: "Certificate is not eligible for auto-renewal: certificate has been revoked" + }); + } + + if (certificate.renewedByCertificateId) { + throw new BadRequestError({ + message: "Certificate is not eligible for auto-renewal: certificate has already been renewed" + }); + } + + const certificateTtlInDays = Math.ceil( + (new Date(certificate.notAfter).getTime() - new Date(certificate.notBefore).getTime()) / (24 * 60 * 60 * 1000) + ); + + if (renewBeforeDays >= certificateTtlInDays) { + throw new BadRequestError({ + message: "Invalid renewal configuration: renewal threshold exceeds certificate validity period" + }); + } + + if (!isValidRenewalTiming(renewBeforeDays, new Date(certificate.notAfter))) { + throw new BadRequestError({ + message: "Invalid renewal configuration: renewal would be triggered immediately or in the past" + }); + } + + await certificateDAL.updateById(certificateId, { + renewBeforeDays + }); + + return { + projectId: certificate.projectId, + renewBeforeDays, + commonName: certificate.commonName || "" + }; + }; + + const disableRenewalConfig = async ({ + certificateId, + actor, + actorId, + actorAuthMethod, + actorOrgId + }: TDisableRenewalConfigDTO): Promise => { + const certificate = await certificateDAL.findById(certificateId); + if (!certificate) { + throw new NotFoundError({ message: "Certificate not found" }); + } + + const { permission } = await permissionService.getProjectPermission({ + actor, + actorId, + projectId: certificate.projectId, + actorAuthMethod, + actorOrgId, + actionProjectType: ActionProjectType.CertificateManager + }); + + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionCertificateActions.Edit, + ProjectPermissionSub.Certificates + ); + + if (!certificate.profileId) { + throw new BadRequestError({ + message: "Certificate is not eligible for auto-renewal: certificate was not issued from a profile" + }); + } + + const profile = await certificateProfileDAL.findByIdWithConfigs(certificate.profileId); + if (!profile) { + throw new NotFoundError({ message: "Certificate profile not found" }); + } + + if (profile.enrollmentType !== EnrollmentType.API) { + throw new ForbiddenRequestError({ + message: "Certificate is not eligible for auto-renewal: EST certificates cannot be auto-renewed" + }); + } + + await certificateDAL.updateById(certificateId, { + renewBeforeDays: null + }); + + return { + projectId: certificate.projectId, + commonName: certificate.commonName || "" + }; + }; + return { issueCertificateFromProfile, signCertificateFromProfile, - orderCertificateFromProfile + orderCertificateFromProfile, + renewCertificate, + updateRenewalConfig, + disableRenewalConfig }; }; diff --git a/backend/src/services/certificate-v3/certificate-v3-types.ts b/backend/src/services/certificate-v3/certificate-v3-types.ts index b54042c5c..a62a25b73 100644 --- a/backend/src/services/certificate-v3/certificate-v3-types.ts +++ b/backend/src/services/certificate-v3/certificate-v3-types.ts @@ -35,8 +35,6 @@ export type TSignCertificateFromProfileDTO = { }; notBefore?: Date; notAfter?: Date; - signatureAlgorithm?: string; - keyAlgorithm?: string; } & Omit; export type TOrderCertificateFromProfileDTO = { @@ -68,6 +66,7 @@ export type TCertificateFromProfileResponse = { certificateId: string; projectId: string; profileName: string; + commonName: string; }; export type TCertificateOrderResponse = { @@ -97,3 +96,27 @@ export type TCertificateOrderResponse = { projectId: string; profileName: string; }; + +export type TRenewCertificateDTO = { + certificateId: string; +} & Omit; + +export type TUpdateRenewalConfigDTO = { + certificateId: string; + renewBeforeDays: number; +} & Omit; + +export type TDisableRenewalConfigDTO = { + certificateId: string; +} & Omit; + +export type TRenewalConfigResponse = { + projectId: string; + renewBeforeDays: number; + commonName: string; +}; + +export type TDisableRenewalResponse = { + projectId: string; + commonName: string; +}; diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.ts index 88808bd63..7af79319b 100644 --- a/backend/src/services/certificate/certificate-dal.ts +++ b/backend/src/services/certificate/certificate-dal.ts @@ -1,7 +1,9 @@ +import RE2 from "re2"; + import { TDbClient } from "@app/db"; import { TableName, TCertificates } from "@app/db/schemas"; import { DatabaseError } from "@app/lib/errors"; -import { ormify } from "@app/lib/knex"; +import { ormify, selectAllTableCols } from "@app/lib/knex"; import { CertStatus } from "./certificate-types"; @@ -60,11 +62,13 @@ export const certificateDALFactory = (db: TDbClient) => { .where(`${TableName.Project}.id`, projectId); if (friendlyName) { - query = query.andWhere(`${TableName.Certificate}.friendlyName`, friendlyName); + const sanitizedValue = String(friendlyName).replace(new RE2("[%_\\\\]", "g"), "\\$&"); + query = query.andWhere(`${TableName.Certificate}.friendlyName`, "like", `%${sanitizedValue}%`); } if (commonName) { - query = query.andWhere(`${TableName.Certificate}.commonName`, commonName); + const sanitizedValue = String(commonName).replace(new RE2("[%_\\\\]", "g"), "\\$&"); + query = query.andWhere(`${TableName.Certificate}.commonName`, "like", `%${sanitizedValue}%`); } const count = await query.count("*").first(); @@ -114,12 +118,210 @@ export const certificateDALFactory = (db: TDbClient) => { } }; + const findActiveCertificatesByIds = async (certificateIds: string[]): Promise => { + try { + if (certificateIds.length === 0) { + return []; + } + + const certs = await db + .replicaNode()(TableName.Certificate) + .whereIn("id", certificateIds) + .where({ status: CertStatus.ACTIVE }) + .where("notAfter", ">", new Date()) + .orderBy("notBefore", "desc") + .select("*"); + + return certs; + } catch (error) { + throw new DatabaseError({ error, name: "Find active certificates by IDs" }); + } + }; + + const findActiveCertificatesForSync = async ( + filter: Partial, + options?: { limit?: number; offset?: number } + ): Promise<(TCertificates & { hasPrivateKey: boolean })[]> => { + try { + let query = db + .replicaNode()(TableName.Certificate) + .leftJoin(TableName.CertificateSecret, `${TableName.Certificate}.id`, `${TableName.CertificateSecret}.certId`) + .select(selectAllTableCols(TableName.Certificate)) + .select(db.ref(`${TableName.CertificateSecret}.certId`).as("privateKeyRef")) + .where({ status: CertStatus.ACTIVE }) + .where("notAfter", ">", new Date()) + .whereNull("renewedByCertificateId"); + + Object.entries(filter).forEach(([key, value]) => { + if (value !== undefined && value !== null) { + if (key === "friendlyName" || key === "commonName") { + const sanitizedValue = String(value).replace(new RE2("[%_\\\\]", "g"), "\\$&"); + query = query.andWhere(`${TableName.Certificate}.${key}`, "like", `%${sanitizedValue}%`); + } else { + query = query.andWhere(`${TableName.Certificate}.${key}`, value); + } + } + }); + + if (options?.offset) { + query = query.offset(options.offset); + } + + if (options?.limit) { + query = query.limit(options.limit); + } + + query = query.orderBy("createdAt", "desc"); + + const certs = await query; + return certs.map((cert) => ({ ...cert, hasPrivateKey: Boolean(cert.privateKeyRef) })); + } catch (error) { + throw new DatabaseError({ error, name: "Find active certificates for sync" }); + } + }; + + const countActiveCertificatesForSync = async ({ + projectId, + friendlyName, + commonName + }: { + projectId: string; + friendlyName?: string; + commonName?: string; + }) => { + try { + interface CountResult { + count: string; + } + + let query = db + .replicaNode()(TableName.Certificate) + .join(TableName.CertificateAuthority, `${TableName.Certificate}.caId`, `${TableName.CertificateAuthority}.id`) + .join(TableName.Project, `${TableName.CertificateAuthority}.projectId`, `${TableName.Project}.id`) + .where(`${TableName.Project}.id`, projectId) + .where(`${TableName.Certificate}.status`, CertStatus.ACTIVE) + .where(`${TableName.Certificate}.notAfter`, ">", new Date()) + .whereNull(`${TableName.Certificate}.renewedByCertificateId`); + + if (friendlyName) { + const sanitizedValue = String(friendlyName).replace(new RE2("[%_\\\\]", "g"), "\\$&"); + query = query.andWhere(`${TableName.Certificate}.friendlyName`, "like", `%${sanitizedValue}%`); + } + + if (commonName) { + const sanitizedValue = String(commonName).replace(new RE2("[%_\\\\]", "g"), "\\$&"); + query = query.andWhere(`${TableName.Certificate}.commonName`, "like", `%${sanitizedValue}%`); + } + + const count = await query.count("*").first(); + + return parseInt((count as unknown as CountResult).count || "0", 10); + } catch (error) { + throw new DatabaseError({ error, name: "Count active certificates for sync" }); + } + }; + + const findCertificatesEligibleForRenewal = async ({ + limit, + offset + }: { + limit: number; + offset: number; + }): Promise<(TCertificates & { profileName?: string })[]> => { + try { + const now = new Date(); + const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999); + + const certs = (await db + .replicaNode()(TableName.Certificate) + .select(selectAllTableCols(TableName.Certificate)) + .select(db.ref("slug").withSchema(TableName.PkiCertificateProfile).as("profileName")) + .leftJoin( + TableName.PkiCertificateProfile, + `${TableName.Certificate}.profileId`, + `${TableName.PkiCertificateProfile}.id` + ) + .innerJoin(TableName.CertificateSecret, `${TableName.Certificate}.id`, `${TableName.CertificateSecret}.certId`) + .where(`${TableName.Certificate}.status`, CertStatus.ACTIVE) + .whereNull(`${TableName.Certificate}.renewedByCertificateId`) + .whereNull(`${TableName.Certificate}.renewalError`) + .whereNull(`${TableName.Certificate}.revokedAt`) + .whereNotNull(`${TableName.Certificate}.profileId`) + .whereNotNull(`${TableName.Certificate}.notAfter`) + .where(`${TableName.Certificate}.notAfter`, ">", now) + .whereNotNull(`${TableName.Certificate}.renewBeforeDays`) + .where(`${TableName.Certificate}.renewBeforeDays`, ">", 0) + .whereRaw( + `"${TableName.Certificate}"."notAfter" - INTERVAL '1 day' * "${TableName.Certificate}"."renewBeforeDays" <= ?`, + [endOfDay] + ) + .limit(limit) + .offset(offset) + .orderBy(`${TableName.Certificate}.notAfter`, "asc")) as TCertificates[]; + + return certs; + } catch (error) { + throw new DatabaseError({ error, name: "Find certificates eligible for renewal" }); + } + }; + + const findWithPrivateKeyInfo = async ( + filter: Partial, + options?: { offset?: number; limit?: number; sort?: [string, "asc" | "desc"][] } + ): Promise<(TCertificates & { hasPrivateKey: boolean })[]> => { + try { + let query = db + .replicaNode()(TableName.Certificate) + .leftJoin(TableName.CertificateSecret, `${TableName.Certificate}.id`, `${TableName.CertificateSecret}.certId`) + .select(selectAllTableCols(TableName.Certificate)) + .select(db.ref(`${TableName.CertificateSecret}.certId`).as("privateKeyRef")); + + Object.entries(filter).forEach(([key, value]) => { + if (value !== undefined && value !== null) { + if (key === "friendlyName" || key === "commonName") { + const sanitizedValue = String(value).replace(new RE2("[%_\\\\]", "g"), "\\$&"); + query = query.andWhere(`${TableName.Certificate}.${key}`, "like", `%${sanitizedValue}%`); + } else { + query = query.andWhere(`${TableName.Certificate}.${key}`, value); + } + } + }); + + if (options?.offset) { + query = query.offset(options.offset); + } + if (options?.limit) { + query = query.limit(options.limit); + } + if (options?.sort) { + options.sort.forEach(([column, direction]) => { + query = query.orderBy(column, direction); + }); + } + + const results = await query; + return results.map((row) => { + return { + ...row, + hasPrivateKey: row.privateKeyRef !== null + }; + }); + } catch (error) { + throw new DatabaseError({ error, name: "Find certificates with private key info" }); + } + }; + return { ...certificateOrm, countCertificatesInProject, + countActiveCertificatesForSync, countCertificatesForPkiSubscriber, findLatestActiveCertForSubscriber, findAllActiveCertsForSubscriber, - findExpiredSyncedCertificates + findExpiredSyncedCertificates, + findActiveCertificatesByIds, + findActiveCertificatesForSync, + findCertificatesEligibleForRenewal, + findWithPrivateKeyInfo }; }; diff --git a/backend/src/services/certificate/certificate-service.ts b/backend/src/services/certificate/certificate-service.ts index 91731c387..eb8006f00 100644 --- a/backend/src/services/certificate/certificate-service.ts +++ b/backend/src/services/certificate/certificate-service.ts @@ -18,12 +18,13 @@ import { TCertificateAuthorityDALFactory } from "@app/services/certificate-autho import { CaCapability, CaType } from "@app/services/certificate-authority/certificate-authority-enums"; import { caSupportsCapability } from "@app/services/certificate-authority/certificate-authority-maps"; import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal"; +import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal"; import { TKmsServiceFactory } from "@app/services/kms/kms-service"; import { TPkiCollectionDALFactory } from "@app/services/pki-collection/pki-collection-dal"; import { TPkiCollectionItemDALFactory } from "@app/services/pki-collection/pki-collection-item-dal"; import { TPkiSyncDALFactory } from "@app/services/pki-sync/pki-sync-dal"; import { TPkiSyncQueueFactory } from "@app/services/pki-sync/pki-sync-queue"; -import { triggerAutoSyncForSubscriber } from "@app/services/pki-sync/pki-sync-utils"; +import { triggerAutoSyncForCertificate } from "@app/services/pki-sync/pki-sync-utils"; import { TProjectDALFactory } from "@app/services/project/project-dal"; import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns"; @@ -57,6 +58,7 @@ type TCertificateServiceFactoryDep = { projectDAL: Pick; kmsService: Pick; permissionService: Pick; + certificateSyncDAL: Pick; pkiSyncDAL: Pick; pkiSyncQueue: Pick; }; @@ -76,6 +78,7 @@ export const certificateServiceFactory = ({ projectDAL, kmsService, permissionService, + certificateSyncDAL, pkiSyncDAL, pkiSyncQueue }: TCertificateServiceFactoryDep) => { @@ -166,10 +169,12 @@ export const certificateServiceFactory = ({ const deletedCert = await certificateDAL.deleteById(cert.id); - // Trigger auto sync for PKI syncs connected to this certificate's subscriber - if (cert.pkiSubscriberId) { - await triggerAutoSyncForSubscriber(cert.pkiSubscriberId, { pkiSyncDAL, pkiSyncQueue }); - } + // Trigger auto sync for PKI syncs connected to this certificate + await triggerAutoSyncForCertificate(cert.id, { + certificateSyncDAL, + pkiSyncDAL, + pkiSyncQueue + }); return { deletedCert @@ -235,10 +240,12 @@ export const certificateServiceFactory = ({ } ); - // Trigger auto sync for PKI syncs connected to this certificate's subscriber - if (cert.pkiSubscriberId) { - await triggerAutoSyncForSubscriber(cert.pkiSubscriberId, { pkiSyncDAL, pkiSyncQueue }); - } + // Trigger auto sync for PKI syncs connected to this certificate + await triggerAutoSyncForCertificate(cert.id, { + certificateSyncDAL, + pkiSyncDAL, + pkiSyncQueue + }); // Note: External CA revocation handling would go here for supported CA types // Currently, only internal CAs and ACME CAs support revocation diff --git a/backend/src/services/certificate/certificate-types.ts b/backend/src/services/certificate/certificate-types.ts index 9da331be8..d654c96ba 100644 --- a/backend/src/services/certificate/certificate-types.ts +++ b/backend/src/services/certificate/certificate-types.ts @@ -21,6 +21,11 @@ export enum CertKeyAlgorithm { ECDSA_P521 = "EC_secp521r1" } +export enum CertKeyType { + RSA = "RSA", + ECDSA = "ECDSA" +} + export enum CertSignatureAlgorithm { RSA_SHA256 = "RSA-SHA256", RSA_SHA384 = "RSA-SHA384", diff --git a/backend/src/services/enrollment-config/api-enrollment-config-dal.ts b/backend/src/services/enrollment-config/api-enrollment-config-dal.ts index 1edfdae6c..ec4b8f76b 100644 --- a/backend/src/services/enrollment-config/api-enrollment-config-dal.ts +++ b/backend/src/services/enrollment-config/api-enrollment-config-dal.ts @@ -69,15 +69,15 @@ export const apiEnrollmentConfigDALFactory = (db: TDbClient) => { const profiles = await query .where((qb) => { void qb - .whereNull(`${TableName.PkiApiEnrollmentConfig}.autoRenewDays`) - .orWhere(`${TableName.PkiApiEnrollmentConfig}.autoRenewDays`, "<=", renewalThresholdDays); + .whereNull(`${TableName.PkiApiEnrollmentConfig}.renewBeforeDays`) + .orWhere(`${TableName.PkiApiEnrollmentConfig}.renewBeforeDays`, "<=", renewalThresholdDays); }) .select((tx || db).ref("id").withSchema(TableName.PkiCertificateProfile)) .select((tx || db).ref("name").withSchema(TableName.PkiCertificateProfile)) .select((tx || db).ref("projectId").withSchema(TableName.PkiCertificateProfile)) - .select((tx || db).ref("autoRenewDays").withSchema(TableName.PkiCertificateProfile)); + .select((tx || db).ref("renewBeforeDays").withSchema(TableName.PkiCertificateProfile)); - return profiles as Array<{ id: string; name: string; projectId: string; autoRenewDays?: number }>; + return profiles as Array<{ id: string; name: string; projectId: string; renewBeforeDays?: number }>; } catch (error) { throw new DatabaseError({ error, name: "Find profiles for auto renewal" }); } diff --git a/backend/src/services/enrollment-config/enrollment-config-types.ts b/backend/src/services/enrollment-config/enrollment-config-types.ts index 516f135fd..d2e03e4da 100644 --- a/backend/src/services/enrollment-config/enrollment-config-types.ts +++ b/backend/src/services/enrollment-config/enrollment-config-types.ts @@ -25,5 +25,5 @@ export interface TEstConfigData { export interface TApiConfigData { autoRenew: boolean; - autoRenewDays?: number; + renewBeforeDays?: number; } diff --git a/backend/src/services/external-migration/external-migration-fns/import.ts b/backend/src/services/external-migration/external-migration-fns/import.ts index 62888c5bf..3ffd11088 100644 --- a/backend/src/services/external-migration/external-migration-fns/import.ts +++ b/backend/src/services/external-migration/external-migration-fns/import.ts @@ -82,7 +82,7 @@ export const importDataIntoInfisicalFn = async ({ if (existingEnv) { throw new BadRequestError({ - message: `Environment with slug '${slug}' already exist`, + message: `Environment with slug '${slug}' already exists`, name: "CreateEnvironment" }); } @@ -312,7 +312,7 @@ export const importDataIntoInfisicalFn = async ({ ); if (secretsByKeys.length) { throw new BadRequestError({ - message: `Secret already exist: ${secretsByKeys.map((el) => el.key).join(",")}` + message: `Secret already exists: ${secretsByKeys.map((el) => el.key).join(",")}` }); } await fnSecretBulkInsert({ diff --git a/backend/src/services/external-migration/external-migration-service.ts b/backend/src/services/external-migration/external-migration-service.ts index bc2a24c07..42fdc2c26 100644 --- a/backend/src/services/external-migration/external-migration-service.ts +++ b/backend/src/services/external-migration/external-migration-service.ts @@ -19,6 +19,7 @@ import { convertVaultValueToString, getHCVaultAuthMounts, getHCVaultKubernetesAuthRoles, + getHCVaultKubernetesRoles, getHCVaultSecretsForPath, HCVaultAuthType, listHCVaultMounts, @@ -762,6 +763,56 @@ export const externalMigrationServiceFactory = ({ return roles; }; + const getVaultKubernetesRoles = async ({ + actor, + namespace, + mountPath + }: { + actor: OrgServiceActor; + namespace: string; + mountPath: string; + }) => { + const { hasRole } = await permissionService.getOrgPermission({ + scope: OrganizationActionScope.Any, + actor: actor.type, + actorId: actor.id, + orgId: actor.orgId, + actorAuthMethod: actor.authMethod, + actorOrgId: actor.orgId + }); + + if (!hasRole(OrgMembershipRole.Admin)) { + throw new ForbiddenRequestError({ message: "Only admins can get Kubernetes roles" }); + } + + const vaultConfig = await vaultExternalMigrationConfigDAL.findOne({ + orgId: actor.orgId, + namespace + }); + + if (!vaultConfig) { + throw new NotFoundError({ message: "Vault migration config not found for this namespace" }); + } + + if (!vaultConfig.connection) { + throw new BadRequestError({ message: "Vault migration connection is not configured for this namespace" }); + } + + const credentials = await decryptAppConnectionCredentials({ + orgId: vaultConfig.orgId, + encryptedCredentials: vaultConfig.connection.encryptedCredentials, + kmsService, + projectId: null + }); + + const connection = { + ...vaultConfig.connection, + credentials + } as THCVaultConnection; + + return getHCVaultKubernetesRoles(namespace, mountPath, connection, gatewayService); + }; + return { importEnvKeyData, importVaultData, @@ -776,6 +827,7 @@ export const externalMigrationServiceFactory = ({ getVaultAuthMounts, getVaultSecretPaths, importVaultSecrets, - getVaultKubernetesAuthRoles + getVaultKubernetesAuthRoles, + getVaultKubernetesRoles }; }; diff --git a/backend/src/services/identity-access-token/identity-access-token-service.ts b/backend/src/services/identity-access-token/identity-access-token-service.ts index 02660a0ae..3479d929e 100644 --- a/backend/src/services/identity-access-token/identity-access-token-service.ts +++ b/backend/src/services/identity-access-token/identity-access-token-service.ts @@ -210,6 +210,7 @@ export const identityAccessTokenServiceFactory = ({ }); } let orgId = ""; + let orgName = ""; let parentOrgId = ""; const identityOrgDetails = await orgDAL.findOne({ id: identityAccessToken.identityScopeOrgId }); const rootOrgId = identityOrgDetails.rootOrgId || identityOrgDetails.id; @@ -229,8 +230,12 @@ export const identityAccessTokenServiceFactory = ({ throw new BadRequestError({ message: "Identity does not belong to any organization" }); } orgId = subOrganization.id; + orgName = subOrganization.name; + parentOrgId = subOrganization.parentOrgId as string; } else { + const organization = await orgDAL.findOne({ id: rootOrgId }); + const identityOrgMembership = await membershipIdentityDAL.findOne({ scope: AccessScope.Organization, actorIdentityId: identityAccessToken.identityId, @@ -242,6 +247,7 @@ export const identityAccessTokenServiceFactory = ({ } orgId = rootOrgId; + orgName = organization.name; parentOrgId = rootOrgId; } @@ -253,7 +259,7 @@ export const identityAccessTokenServiceFactory = ({ await validateAccessTokenExp({ ...identityAccessToken, accessTokenNumUses }); await accessTokenQueue.updateIdentityAccessTokenStatus(identityAccessToken.id, Number(accessTokenNumUses) + 1); - return { ...identityAccessToken, orgId, rootOrgId, parentOrgId }; + return { ...identityAccessToken, orgId, rootOrgId, parentOrgId, orgName }; }; return { renewAccessToken, revokeAccessToken, fnValidateIdentityAccessToken }; diff --git a/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts b/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts index c6f6f1376..525da1e10 100644 --- a/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts +++ b/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/no-unsafe-assignment */ import { ForbiddenError } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import { AxiosError } from "axios"; import { AccessScope, IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas"; @@ -22,6 +23,7 @@ import { } from "@app/lib/errors"; import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip"; import { logger } from "@app/lib/logger"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { ActorType, AuthTokenType } from "../auth/auth-type"; import { TIdentityDALFactory } from "../identity/identity-dal"; @@ -65,6 +67,7 @@ export const identityAliCloudAuthServiceFactory = ({ orgDAL }: TIdentityAliCloudAuthServiceFactoryDep) => { const login = async ({ identityId, ...params }: TLoginAliCloudAuthDTO) => { + const appCfg = getConfig(); const identityAliCloudAuth = await identityAliCloudAuthDAL.findOne({ identityId }); if (!identityAliCloudAuth) { throw new NotFoundError({ @@ -75,73 +78,103 @@ export const identityAliCloudAuthServiceFactory = ({ const identity = await identityDAL.findById(identityAliCloudAuth.identityId); if (!identity) throw new UnauthorizedError({ message: "Identity not found" }); - const requestUrl = new URL("https://sts.aliyuncs.com"); + const org = await orgDAL.findById(identity.orgId); - for (const key of Object.keys(params)) { - requestUrl.searchParams.set(key, (params as Record)[key]); - } + try { + const requestUrl = new URL("https://sts.aliyuncs.com"); - const { data } = await request.get(requestUrl.toString()).catch((err: AxiosError) => { - logger.error(err.response, "AliCloudIdentityLogin: Failed to authenticate with Alibaba Cloud"); - throw err; - }); + for (const key of Object.keys(params)) { + requestUrl.searchParams.set(key, (params as Record)[key]); + } - if (identityAliCloudAuth.allowedArns) { - // In the future we could do partial checks for role ARNs - const isAccountAllowed = identityAliCloudAuth.allowedArns.split(",").some((arn) => arn.trim() === data.Arn); + const { data } = await request.get(requestUrl.toString()).catch((err: AxiosError) => { + logger.error(err.response, "AliCloudIdentityLogin: Failed to authenticate with Alibaba Cloud"); + throw err; + }); - if (!isAccountAllowed) - throw new UnauthorizedError({ - message: "Access denied: Alibaba Cloud account ARN not allowed." - }); - } + if (identityAliCloudAuth.allowedArns) { + // In the future we could do partial checks for role ARNs + const isAccountAllowed = identityAliCloudAuth.allowedArns.split(",").some((arn) => arn.trim() === data.Arn); - // Generate the token - const identityAccessToken = await identityAliCloudAuthDAL.transaction(async (tx) => { - await membershipIdentityDAL.update( - { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, - { - lastLoginAuthMethod: IdentityAuthMethod.ALICLOUD_AUTH, - lastLoginTime: new Date() - }, - tx - ); - const newToken = await identityAccessTokenDAL.create( + if (!isAccountAllowed) + throw new UnauthorizedError({ + message: "Access denied: Alibaba Cloud account ARN not allowed." + }); + } + + // Generate the token + const identityAccessToken = await identityAliCloudAuthDAL.transaction(async (tx) => { + await membershipIdentityDAL.update( + { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, + { + lastLoginAuthMethod: IdentityAuthMethod.ALICLOUD_AUTH, + lastLoginTime: new Date() + }, + tx + ); + const newToken = await identityAccessTokenDAL.create( + { + identityId: identityAliCloudAuth.identityId, + isAccessTokenRevoked: false, + accessTokenTTL: identityAliCloudAuth.accessTokenTTL, + accessTokenMaxTTL: identityAliCloudAuth.accessTokenMaxTTL, + accessTokenNumUses: 0, + accessTokenNumUsesLimit: identityAliCloudAuth.accessTokenNumUsesLimit, + authMethod: IdentityAuthMethod.ALICLOUD_AUTH + }, + tx + ); + return newToken; + }); + + const accessToken = crypto.jwt().sign( { identityId: identityAliCloudAuth.identityId, - isAccessTokenRevoked: false, - accessTokenTTL: identityAliCloudAuth.accessTokenTTL, - accessTokenMaxTTL: identityAliCloudAuth.accessTokenMaxTTL, - accessTokenNumUses: 0, - accessTokenNumUsesLimit: identityAliCloudAuth.accessTokenNumUsesLimit, - authMethod: IdentityAuthMethod.ALICLOUD_AUTH - }, - tx + identityAccessTokenId: identityAccessToken.id, + authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN + } as TIdentityAccessTokenJwtPayload, + appCfg.AUTH_SECRET, + Number(identityAccessToken.accessTokenTTL) === 0 + ? undefined + : { + expiresIn: Number(identityAccessToken.accessTokenTTL) + } ); - return newToken; - }); - const appCfg = getConfig(); - const accessToken = crypto.jwt().sign( - { - identityId: identityAliCloudAuth.identityId, - identityAccessTokenId: identityAccessToken.id, - authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN - } as TIdentityAccessTokenJwtPayload, - appCfg.AUTH_SECRET, - Number(identityAccessToken.accessTokenTTL) === 0 - ? undefined - : { - expiresIn: Number(identityAccessToken.accessTokenTTL) - } - ); + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityAliCloudAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.ALICLOUD_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } - return { - identityAliCloudAuth, - accessToken, - identityAccessToken, - identity - }; + return { + identityAliCloudAuth, + accessToken, + identityAccessToken, + identity + }; + } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityAliCloudAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.ALICLOUD_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + throw error; + } }; const attachAliCloudAuth = async ({ diff --git a/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts b/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts index e61e8296b..81fab3fde 100644 --- a/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts +++ b/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts @@ -1,5 +1,6 @@ -/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access */ import { ForbiddenError } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import axios from "axios"; import RE2 from "re2"; @@ -22,6 +23,7 @@ import { } from "@app/lib/errors"; import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip"; import { logger } from "@app/lib/logger"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { ActorType, AuthTokenType } from "../auth/auth-type"; import { TIdentityDALFactory } from "../identity/identity-dal"; @@ -98,6 +100,7 @@ export const identityAwsAuthServiceFactory = ({ orgDAL }: TIdentityAwsAuthServiceFactoryDep) => { const login = async ({ identityId, iamHttpRequestMethod, iamRequestBody, iamRequestHeaders }: TLoginAwsAuthDTO) => { + const appCfg = getConfig(); const identityAwsAuth = await identityAwsAuthDAL.findOne({ identityId }); if (!identityAwsAuth) { throw new NotFoundError({ message: "AWS auth method not found for identity, did you configure AWS auth?" }); @@ -106,127 +109,156 @@ export const identityAwsAuthServiceFactory = ({ const identity = await identityDAL.findById(identityAwsAuth.identityId); if (!identity) throw new UnauthorizedError({ message: "Identity not found" }); - const headers: TAwsGetCallerIdentityHeaders = JSON.parse(Buffer.from(iamRequestHeaders, "base64").toString()); - const body: string = Buffer.from(iamRequestBody, "base64").toString(); + const org = await orgDAL.findById(identity.orgId); + try { + const headers: TAwsGetCallerIdentityHeaders = JSON.parse(Buffer.from(iamRequestHeaders, "base64").toString()); + const body: string = Buffer.from(iamRequestBody, "base64").toString(); - const authHeader = headers.Authorization || headers.authorization; - const region = authHeader ? awsRegionFromHeader(authHeader) : null; + const authHeader = headers.Authorization || headers.authorization; + const region = authHeader ? awsRegionFromHeader(authHeader) : null; - if (!isValidAwsRegion(region)) { - throw new BadRequestError({ message: "Invalid AWS region" }); - } + if (!isValidAwsRegion(region)) { + throw new BadRequestError({ message: "Invalid AWS region" }); + } - const url = region ? `https://sts.${region}.amazonaws.com` : identityAwsAuth.stsEndpoint; + const url = region ? `https://sts.${region}.amazonaws.com` : identityAwsAuth.stsEndpoint; - const { - data: { - GetCallerIdentityResponse: { - GetCallerIdentityResult: { Account, Arn, UserId } + const { + data: { + GetCallerIdentityResponse: { + GetCallerIdentityResult: { Account, Arn, UserId } + } + } + }: { data: TGetCallerIdentityResponse } = await axios({ + method: iamHttpRequestMethod, + url, + headers, + data: body + }); + + if (identityAwsAuth.allowedAccountIds) { + // validate if Account is in the list of allowed Account IDs + + const isAccountAllowed = identityAwsAuth.allowedAccountIds + .split(",") + .map((accountId) => accountId.trim()) + .some((accountId) => accountId === Account); + + if (!isAccountAllowed) + throw new UnauthorizedError({ + message: "Access denied: AWS account ID not allowed." + }); + } + + if (identityAwsAuth.allowedPrincipalArns) { + // validate if Arn is in the list of allowed Principal ARNs + + const formattedArn = extractPrincipalArn(Arn); + + const isArnAllowed = identityAwsAuth.allowedPrincipalArns + .split(",") + .map((principalArn) => principalArn.trim()) + .some((principalArn) => { + // convert wildcard ARN to a regular expression: "arn:aws:iam::123456789012:*" -> "^arn:aws:iam::123456789012:.*$" + // considers exact matches + wildcard matches + // heavily validated in router + const regex = new RE2(`^${principalArn.replaceAll("*", ".*")}$`); + return regex.test(formattedArn) || regex.test(extractPrincipalArn(Arn, true)); + }); + + if (!isArnAllowed) { + logger.error( + `AWS Auth Login: AWS principal ARN not allowed [principal-arn=${formattedArn}] [raw-arn=${Arn}] [identity-id=${identity.id}]` + ); + + throw new UnauthorizedError({ + message: `Access denied: AWS principal ARN not allowed. [principal-arn=${formattedArn}]` + }); } } - }: { data: TGetCallerIdentityResponse } = await axios({ - method: iamHttpRequestMethod, - url, - headers, - data: body - }); - if (identityAwsAuth.allowedAccountIds) { - // validate if Account is in the list of allowed Account IDs - - const isAccountAllowed = identityAwsAuth.allowedAccountIds - .split(",") - .map((accountId) => accountId.trim()) - .some((accountId) => accountId === Account); - - if (!isAccountAllowed) - throw new UnauthorizedError({ - message: "Access denied: AWS account ID not allowed." - }); - } - - if (identityAwsAuth.allowedPrincipalArns) { - // validate if Arn is in the list of allowed Principal ARNs - - const formattedArn = extractPrincipalArn(Arn); - - const isArnAllowed = identityAwsAuth.allowedPrincipalArns - .split(",") - .map((principalArn) => principalArn.trim()) - .some((principalArn) => { - // convert wildcard ARN to a regular expression: "arn:aws:iam::123456789012:*" -> "^arn:aws:iam::123456789012:.*$" - // considers exact matches + wildcard matches - // heavily validated in router - const regex = new RE2(`^${principalArn.replaceAll("*", ".*")}$`); - return regex.test(formattedArn) || regex.test(extractPrincipalArn(Arn, true)); - }); - - if (!isArnAllowed) { - logger.error( - `AWS Auth Login: AWS principal ARN not allowed [principal-arn=${formattedArn}] [raw-arn=${Arn}] [identity-id=${identity.id}]` + const identityAccessToken = await identityAwsAuthDAL.transaction(async (tx) => { + await membershipIdentityDAL.update( + { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, + { + lastLoginAuthMethod: IdentityAuthMethod.AWS_AUTH, + lastLoginTime: new Date() + }, + tx ); + const newToken = await identityAccessTokenDAL.create( + { + identityId: identityAwsAuth.identityId, + isAccessTokenRevoked: false, + accessTokenTTL: identityAwsAuth.accessTokenTTL, + accessTokenMaxTTL: identityAwsAuth.accessTokenMaxTTL, + accessTokenNumUses: 0, + accessTokenNumUsesLimit: identityAwsAuth.accessTokenNumUsesLimit, + authMethod: IdentityAuthMethod.AWS_AUTH + }, + tx + ); + return newToken; + }); - throw new UnauthorizedError({ - message: `Access denied: AWS principal ARN not allowed. [principal-arn=${formattedArn}]` - }); - } - } - - const identityAccessToken = await identityAwsAuthDAL.transaction(async (tx) => { - await membershipIdentityDAL.update( - { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, - { - lastLoginAuthMethod: IdentityAuthMethod.AWS_AUTH, - lastLoginTime: new Date() - }, - tx - ); - const newToken = await identityAccessTokenDAL.create( + const splitArn = extractPrincipalArnEntity(Arn); + const accessToken = crypto.jwt().sign( { identityId: identityAwsAuth.identityId, - isAccessTokenRevoked: false, - accessTokenTTL: identityAwsAuth.accessTokenTTL, - accessTokenMaxTTL: identityAwsAuth.accessTokenMaxTTL, - accessTokenNumUses: 0, - accessTokenNumUsesLimit: identityAwsAuth.accessTokenNumUsesLimit, - authMethod: IdentityAuthMethod.AWS_AUTH - }, - tx + identityAccessTokenId: identityAccessToken.id, + authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN, + identityAuth: { + aws: { + accountId: Account, + arn: Arn, + userId: UserId, + + // Derived from ARN + partition: splitArn.Partition, + service: splitArn.Service, + resourceType: splitArn.Type, + resourceName: splitArn.FriendlyName + } + } + } as TIdentityAccessTokenJwtPayload, + appCfg.AUTH_SECRET, + // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error + Number(identityAccessToken.accessTokenTTL) === 0 + ? undefined + : { + expiresIn: Number(identityAccessToken.accessTokenTTL) + } ); - return newToken; - }); - const appCfg = getConfig(); - const splitArn = extractPrincipalArnEntity(Arn); - const accessToken = crypto.jwt().sign( - { - identityId: identityAwsAuth.identityId, - identityAccessTokenId: identityAccessToken.id, - authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN, - identityAuth: { - aws: { - accountId: Account, - arn: Arn, - userId: UserId, + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityAwsAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.AWS_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } - // Derived from ARN - partition: splitArn.Partition, - service: splitArn.Service, - resourceType: splitArn.Type, - resourceName: splitArn.FriendlyName - } - } - } as TIdentityAccessTokenJwtPayload, - appCfg.AUTH_SECRET, - // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error - Number(identityAccessToken.accessTokenTTL) === 0 - ? undefined - : { - expiresIn: Number(identityAccessToken.accessTokenTTL) - } - ); - - return { accessToken, identityAwsAuth, identityAccessToken, identity }; + return { accessToken, identityAwsAuth, identityAccessToken, identity }; + } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityAwsAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.AWS_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + throw error; + } }; const attachAwsAuth = async ({ diff --git a/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts b/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts index f75aeba4f..17f274e7c 100644 --- a/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts +++ b/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts @@ -1,4 +1,5 @@ import { ForbiddenError } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import { AccessScope, IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas"; import { TLicenseServiceFactory } from "@app/ee/services/license/license-service"; @@ -18,6 +19,7 @@ import { UnauthorizedError } from "@app/lib/errors"; import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { ActorType, AuthTokenType } from "../auth/auth-type"; import { TIdentityDALFactory } from "../identity/identity-dal"; @@ -61,6 +63,7 @@ export const identityAzureAuthServiceFactory = ({ orgDAL }: TIdentityAzureAuthServiceFactoryDep) => { const login = async ({ identityId, jwt: azureJwt }: TLoginAzureAuthDTO) => { + const appCfg = getConfig(); const identityAzureAuth = await identityAzureAuthDAL.findOne({ identityId }); if (!identityAzureAuth) { throw new NotFoundError({ message: "Azure auth method not found for identity, did you configure Azure Auth?" }); @@ -69,69 +72,99 @@ export const identityAzureAuthServiceFactory = ({ const identity = await identityDAL.findById(identityAzureAuth.identityId); if (!identity) throw new UnauthorizedError({ message: "Identity not found" }); - const azureIdentity = await validateAzureIdentity({ - tenantId: identityAzureAuth.tenantId, - resource: identityAzureAuth.resource, - jwt: azureJwt - }); + const org = await orgDAL.findById(identity.orgId); - if (azureIdentity.tid !== identityAzureAuth.tenantId) - throw new UnauthorizedError({ message: "Tenant ID mismatch" }); + try { + const azureIdentity = await validateAzureIdentity({ + tenantId: identityAzureAuth.tenantId, + resource: identityAzureAuth.resource, + jwt: azureJwt + }); - if (identityAzureAuth.allowedServicePrincipalIds) { - // validate if the service principal id is in the list of allowed service principal ids + if (azureIdentity.tid !== identityAzureAuth.tenantId) + throw new UnauthorizedError({ message: "Tenant ID mismatch" }); - const isServicePrincipalAllowed = identityAzureAuth.allowedServicePrincipalIds - .split(",") - .map((servicePrincipalId) => servicePrincipalId.trim()) - .some((servicePrincipalId) => servicePrincipalId === azureIdentity.oid); + if (identityAzureAuth.allowedServicePrincipalIds) { + // validate if the service principal id is in the list of allowed service principal ids - if (!isServicePrincipalAllowed) { - throw new UnauthorizedError({ message: `Service principal '${azureIdentity.oid}' not allowed` }); + const isServicePrincipalAllowed = identityAzureAuth.allowedServicePrincipalIds + .split(",") + .map((servicePrincipalId) => servicePrincipalId.trim()) + .some((servicePrincipalId) => servicePrincipalId === azureIdentity.oid); + + if (!isServicePrincipalAllowed) { + throw new UnauthorizedError({ message: `Service principal '${azureIdentity.oid}' not allowed` }); + } } - } - const identityAccessToken = await identityAzureAuthDAL.transaction(async (tx) => { - await membershipIdentityDAL.update( - { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, - { - lastLoginAuthMethod: IdentityAuthMethod.AZURE_AUTH, - lastLoginTime: new Date() - }, - tx - ); - const newToken = await identityAccessTokenDAL.create( + const identityAccessToken = await identityAzureAuthDAL.transaction(async (tx) => { + await membershipIdentityDAL.update( + { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, + { + lastLoginAuthMethod: IdentityAuthMethod.AZURE_AUTH, + lastLoginTime: new Date() + }, + tx + ); + const newToken = await identityAccessTokenDAL.create( + { + identityId: identityAzureAuth.identityId, + isAccessTokenRevoked: false, + accessTokenTTL: identityAzureAuth.accessTokenTTL, + accessTokenMaxTTL: identityAzureAuth.accessTokenMaxTTL, + accessTokenNumUses: 0, + accessTokenNumUsesLimit: identityAzureAuth.accessTokenNumUsesLimit, + authMethod: IdentityAuthMethod.AZURE_AUTH + }, + tx + ); + return newToken; + }); + + const accessToken = crypto.jwt().sign( { identityId: identityAzureAuth.identityId, - isAccessTokenRevoked: false, - accessTokenTTL: identityAzureAuth.accessTokenTTL, - accessTokenMaxTTL: identityAzureAuth.accessTokenMaxTTL, - accessTokenNumUses: 0, - accessTokenNumUsesLimit: identityAzureAuth.accessTokenNumUsesLimit, - authMethod: IdentityAuthMethod.AZURE_AUTH - }, - tx + identityAccessTokenId: identityAccessToken.id, + authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN + } as TIdentityAccessTokenJwtPayload, + appCfg.AUTH_SECRET, + // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error + Number(identityAccessToken.accessTokenTTL) === 0 + ? undefined + : { + expiresIn: Number(identityAccessToken.accessTokenTTL) + } ); - return newToken; - }); - const appCfg = getConfig(); - const accessToken = crypto.jwt().sign( - { - identityId: identityAzureAuth.identityId, - identityAccessTokenId: identityAccessToken.id, - authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN - } as TIdentityAccessTokenJwtPayload, - appCfg.AUTH_SECRET, - // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error - Number(identityAccessToken.accessTokenTTL) === 0 - ? undefined - : { - expiresIn: Number(identityAccessToken.accessTokenTTL) - } - ); + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityAzureAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.AZURE_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } - return { accessToken, identityAzureAuth, identityAccessToken, identity }; + return { accessToken, identityAzureAuth, identityAccessToken, identity }; + } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityAzureAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.AZURE_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + throw error; + } }; const attachAzureAuth = async ({ diff --git a/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts b/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts index 67adb6c1e..3e0035e82 100644 --- a/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts +++ b/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts @@ -1,4 +1,5 @@ import { ForbiddenError } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import { AccessScope, IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas"; import { TLicenseServiceFactory } from "@app/ee/services/license/license-service"; @@ -18,6 +19,7 @@ import { UnauthorizedError } from "@app/lib/errors"; import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { ActorType, AuthTokenType } from "../auth/auth-type"; import { TIdentityDALFactory } from "../identity/identity-dal"; @@ -59,6 +61,7 @@ export const identityGcpAuthServiceFactory = ({ orgDAL }: TIdentityGcpAuthServiceFactoryDep) => { const login = async ({ identityId, jwt: gcpJwt }: TLoginGcpAuthDTO) => { + const appCfg = getConfig(); const identityGcpAuth = await identityGcpAuthDAL.findOne({ identityId }); if (!identityGcpAuth) { throw new NotFoundError({ message: "GCP auth method not found for identity, did you configure GCP auth?" }); @@ -67,108 +70,140 @@ export const identityGcpAuthServiceFactory = ({ const identity = await identityDAL.findById(identityGcpAuth.identityId); if (!identity) throw new UnauthorizedError({ message: "Identity not found" }); - let gcpIdentityDetails: TGcpIdentityDetails; - switch (identityGcpAuth.type) { - case "gce": { - gcpIdentityDetails = await validateIdTokenIdentity({ - identityId, - jwt: gcpJwt - }); - break; + const org = await orgDAL.findById(identity.orgId); + try { + let gcpIdentityDetails: TGcpIdentityDetails; + switch (identityGcpAuth.type) { + case "gce": { + gcpIdentityDetails = await validateIdTokenIdentity({ + identityId, + jwt: gcpJwt + }); + break; + } + case "iam": { + gcpIdentityDetails = await validateIamIdentity({ + identityId, + jwt: gcpJwt + }); + break; + } + default: { + throw new BadRequestError({ message: "Invalid GCP Auth type" }); + } } - case "iam": { - gcpIdentityDetails = await validateIamIdentity({ - identityId, - jwt: gcpJwt - }); - break; + + if (identityGcpAuth.allowedServiceAccounts) { + // validate if the service account is in the list of allowed service accounts + + const isServiceAccountAllowed = identityGcpAuth.allowedServiceAccounts + .split(",") + .map((serviceAccount) => serviceAccount.trim()) + .some((serviceAccount) => serviceAccount === gcpIdentityDetails.email); + + if (!isServiceAccountAllowed) + throw new UnauthorizedError({ + message: "Access denied: GCP service account not allowed." + }); } - default: { - throw new BadRequestError({ message: "Invalid GCP Auth type" }); + + if ( + identityGcpAuth.type === "gce" && + identityGcpAuth.allowedProjects && + gcpIdentityDetails.computeEngineDetails + ) { + // validate if the project that the service account belongs to is in the list of allowed projects + + const isProjectAllowed = identityGcpAuth.allowedProjects + .split(",") + .map((project) => project.trim()) + .some((project) => project === gcpIdentityDetails.computeEngineDetails?.project_id); + + if (!isProjectAllowed) + throw new UnauthorizedError({ + message: "Access denied: GCP project not allowed." + }); } - } - if (identityGcpAuth.allowedServiceAccounts) { - // validate if the service account is in the list of allowed service accounts + if (identityGcpAuth.type === "gce" && identityGcpAuth.allowedZones && gcpIdentityDetails.computeEngineDetails) { + const isZoneAllowed = identityGcpAuth.allowedZones + .split(",") + .map((zone) => zone.trim()) + .some((zone) => zone === gcpIdentityDetails.computeEngineDetails?.zone); - const isServiceAccountAllowed = identityGcpAuth.allowedServiceAccounts - .split(",") - .map((serviceAccount) => serviceAccount.trim()) - .some((serviceAccount) => serviceAccount === gcpIdentityDetails.email); + if (!isZoneAllowed) + throw new UnauthorizedError({ + message: "Access denied: GCP zone not allowed." + }); + } - if (!isServiceAccountAllowed) - throw new UnauthorizedError({ - message: "Access denied: GCP service account not allowed." - }); - } - - if (identityGcpAuth.type === "gce" && identityGcpAuth.allowedProjects && gcpIdentityDetails.computeEngineDetails) { - // validate if the project that the service account belongs to is in the list of allowed projects - - const isProjectAllowed = identityGcpAuth.allowedProjects - .split(",") - .map((project) => project.trim()) - .some((project) => project === gcpIdentityDetails.computeEngineDetails?.project_id); - - if (!isProjectAllowed) - throw new UnauthorizedError({ - message: "Access denied: GCP project not allowed." - }); - } - - if (identityGcpAuth.type === "gce" && identityGcpAuth.allowedZones && gcpIdentityDetails.computeEngineDetails) { - const isZoneAllowed = identityGcpAuth.allowedZones - .split(",") - .map((zone) => zone.trim()) - .some((zone) => zone === gcpIdentityDetails.computeEngineDetails?.zone); - - if (!isZoneAllowed) - throw new UnauthorizedError({ - message: "Access denied: GCP zone not allowed." - }); - } - - const identityAccessToken = await identityGcpAuthDAL.transaction(async (tx) => { - await membershipIdentityDAL.update( - { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, - { - lastLoginAuthMethod: IdentityAuthMethod.GCP_AUTH, - lastLoginTime: new Date() - }, - tx - ); - const newToken = await identityAccessTokenDAL.create( + const identityAccessToken = await identityGcpAuthDAL.transaction(async (tx) => { + await membershipIdentityDAL.update( + { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, + { + lastLoginAuthMethod: IdentityAuthMethod.GCP_AUTH, + lastLoginTime: new Date() + }, + tx + ); + const newToken = await identityAccessTokenDAL.create( + { + identityId: identityGcpAuth.identityId, + isAccessTokenRevoked: false, + accessTokenTTL: identityGcpAuth.accessTokenTTL, + accessTokenMaxTTL: identityGcpAuth.accessTokenMaxTTL, + accessTokenNumUses: 0, + accessTokenNumUsesLimit: identityGcpAuth.accessTokenNumUsesLimit, + authMethod: IdentityAuthMethod.GCP_AUTH + }, + tx + ); + return newToken; + }); + const accessToken = crypto.jwt().sign( { identityId: identityGcpAuth.identityId, - isAccessTokenRevoked: false, - accessTokenTTL: identityGcpAuth.accessTokenTTL, - accessTokenMaxTTL: identityGcpAuth.accessTokenMaxTTL, - accessTokenNumUses: 0, - accessTokenNumUsesLimit: identityGcpAuth.accessTokenNumUsesLimit, - authMethod: IdentityAuthMethod.GCP_AUTH - }, - tx + identityAccessTokenId: identityAccessToken.id, + authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN + } as TIdentityAccessTokenJwtPayload, + appCfg.AUTH_SECRET, + // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error + Number(identityAccessToken.accessTokenTTL) === 0 + ? undefined + : { + expiresIn: Number(identityAccessToken.accessTokenTTL) + } ); - return newToken; - }); - const appCfg = getConfig(); - const accessToken = crypto.jwt().sign( - { - identityId: identityGcpAuth.identityId, - identityAccessTokenId: identityAccessToken.id, - authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN - } as TIdentityAccessTokenJwtPayload, - appCfg.AUTH_SECRET, - // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error - Number(identityAccessToken.accessTokenTTL) === 0 - ? undefined - : { - expiresIn: Number(identityAccessToken.accessTokenTTL) - } - ); + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityGcpAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.GCP_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } - return { accessToken, identityGcpAuth, identityAccessToken, identity }; + return { accessToken, identityGcpAuth, identityAccessToken, identity }; + } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityGcpAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.GCP_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + throw error; + } }; const attachGcpAuth = async ({ diff --git a/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts b/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts index debd90933..3cf93fd16 100644 --- a/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts +++ b/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts @@ -1,4 +1,5 @@ import { ForbiddenError } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import https from "https"; import jwt from "jsonwebtoken"; import { JwksClient } from "jwks-rsa"; @@ -21,6 +22,7 @@ import { UnauthorizedError } from "@app/lib/errors"; import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { getValueByDot } from "@app/lib/template/dot-access"; import { ActorType, AuthTokenType } from "../auth/auth-type"; @@ -67,6 +69,7 @@ export const identityJwtAuthServiceFactory = ({ orgDAL }: TIdentityJwtAuthServiceFactoryDep) => { const login = async ({ identityId, jwt: jwtValue }: TLoginJwtAuthDTO) => { + const appCfg = getConfig(); const identityJwtAuth = await identityJwtAuthDAL.findOne({ identityId }); if (!identityJwtAuth) { throw new NotFoundError({ message: "JWT auth method not found for identity, did you configure JWT auth?" }); @@ -75,176 +78,205 @@ export const identityJwtAuthServiceFactory = ({ const identity = await identityDAL.findById(identityJwtAuth.identityId); if (!identity) throw new UnauthorizedError({ message: "Identity not found" }); - const { decryptor: orgDataKeyDecryptor } = await kmsService.createCipherPairWithDataKey({ - type: KmsDataKey.Organization, - orgId: identity.orgId - }); - - const decodedToken = crypto.jwt().decode(jwtValue, { complete: true }); - if (!decodedToken) { - throw new UnauthorizedError({ - message: "Invalid JWT" + const org = await orgDAL.findById(identity.orgId); + try { + const { decryptor: orgDataKeyDecryptor } = await kmsService.createCipherPairWithDataKey({ + type: KmsDataKey.Organization, + orgId: identity.orgId }); - } - let tokenData: Record = {}; - - if (identityJwtAuth.configurationType === JwtConfigurationType.JWKS) { - let client: JwksClient; - if (identityJwtAuth.jwksUrl.includes("https:")) { - const decryptedJwksCaCert = orgDataKeyDecryptor({ - cipherTextBlob: identityJwtAuth.encryptedJwksCaCert - }).toString(); - - const requestAgent = new https.Agent({ ca: decryptedJwksCaCert, rejectUnauthorized: !!decryptedJwksCaCert }); - client = new JwksClient({ - jwksUri: identityJwtAuth.jwksUrl, - requestAgent - }); - } else { - client = new JwksClient({ - jwksUri: identityJwtAuth.jwksUrl + const decodedToken = crypto.jwt().decode(jwtValue, { complete: true }); + if (!decodedToken) { + throw new UnauthorizedError({ + message: "Invalid JWT" }); } - const { kid } = decodedToken.header as { kid: string }; - const jwtSigningKey = await client.getSigningKey(kid); + let tokenData: Record = {}; - try { - tokenData = crypto.jwt().verify(jwtValue, jwtSigningKey.getPublicKey()) as Record; - } catch (error) { - if (error instanceof jwt.JsonWebTokenError) { - throw new UnauthorizedError({ - message: `Access denied: ${error.message}` + if (identityJwtAuth.configurationType === JwtConfigurationType.JWKS) { + let client: JwksClient; + if (identityJwtAuth.jwksUrl.includes("https:")) { + const decryptedJwksCaCert = orgDataKeyDecryptor({ + cipherTextBlob: identityJwtAuth.encryptedJwksCaCert + }).toString(); + + const requestAgent = new https.Agent({ ca: decryptedJwksCaCert, rejectUnauthorized: !!decryptedJwksCaCert }); + client = new JwksClient({ + jwksUri: identityJwtAuth.jwksUrl, + requestAgent + }); + } else { + client = new JwksClient({ + jwksUri: identityJwtAuth.jwksUrl }); } - throw error; - } - } else { - const decryptedPublicKeys = orgDataKeyDecryptor({ cipherTextBlob: identityJwtAuth.encryptedPublicKeys }) - .toString() - .split(","); + const { kid } = decodedToken.header as { kid: string }; + const jwtSigningKey = await client.getSigningKey(kid); - const errors: string[] = []; - let isMatchAnyKey = false; - for (const publicKey of decryptedPublicKeys) { try { - tokenData = crypto.jwt().verify(jwtValue, publicKey) as Record; - isMatchAnyKey = true; + tokenData = crypto.jwt().verify(jwtValue, jwtSigningKey.getPublicKey()) as Record; } catch (error) { if (error instanceof jwt.JsonWebTokenError) { - errors.push(error.message); + throw new UnauthorizedError({ + message: `Access denied: ${error.message}` + }); + } + + throw error; + } + } else { + const decryptedPublicKeys = orgDataKeyDecryptor({ cipherTextBlob: identityJwtAuth.encryptedPublicKeys }) + .toString() + .split(","); + + const errors: string[] = []; + let isMatchAnyKey = false; + for (const publicKey of decryptedPublicKeys) { + try { + tokenData = crypto.jwt().verify(jwtValue, publicKey) as Record; + isMatchAnyKey = true; + } catch (error) { + if (error instanceof jwt.JsonWebTokenError) { + errors.push(error.message); + } } } - } - if (!isMatchAnyKey) { - throw new UnauthorizedError({ - message: `Access denied: JWT verification failed with all keys. Errors - ${errors.join("; ")}` - }); - } - } - - if (identityJwtAuth.boundIssuer) { - if (tokenData.iss !== identityJwtAuth.boundIssuer) { - throw new ForbiddenRequestError({ - message: "Access denied: issuer mismatch" - }); - } - } - - if (identityJwtAuth.boundSubject) { - if (!tokenData.sub) { - throw new UnauthorizedError({ - message: "Access denied: token has no subject field" - }); - } - - if (!doesFieldValueMatchJwtPolicy(tokenData.sub, identityJwtAuth.boundSubject)) { - throw new ForbiddenRequestError({ - message: "Access denied: subject not allowed" - }); - } - } - - if (identityJwtAuth.boundAudiences) { - if (!tokenData.aud) { - throw new UnauthorizedError({ - message: "Access denied: token has no audience field" - }); - } - - if ( - !identityJwtAuth.boundAudiences - .split(", ") - .some((policyValue) => doesFieldValueMatchJwtPolicy(tokenData.aud, policyValue)) - ) { - throw new UnauthorizedError({ - message: "Access denied: token audience not allowed" - }); - } - } - - if (identityJwtAuth.boundClaims) { - Object.keys(identityJwtAuth.boundClaims).forEach((claimKey) => { - const claimValue = (identityJwtAuth.boundClaims as Record)[claimKey]; - const value = getValueByDot(tokenData, claimKey); - - if (!value) { + if (!isMatchAnyKey) { throw new UnauthorizedError({ - message: `Access denied: token has no ${claimKey} field` + message: `Access denied: JWT verification failed with all keys. Errors - ${errors.join("; ")}` + }); + } + } + + if (identityJwtAuth.boundIssuer) { + if (tokenData.iss !== identityJwtAuth.boundIssuer) { + throw new ForbiddenRequestError({ + message: "Access denied: issuer mismatch" + }); + } + } + + if (identityJwtAuth.boundSubject) { + if (!tokenData.sub) { + throw new UnauthorizedError({ + message: "Access denied: token has no subject field" }); } - // handle both single and multi-valued claims - if (!claimValue.split(", ").some((claimEntry) => doesFieldValueMatchJwtPolicy(value, claimEntry))) { - throw new UnauthorizedError({ - message: `Access denied: claim mismatch for field ${claimKey}` + if (!doesFieldValueMatchJwtPolicy(tokenData.sub, identityJwtAuth.boundSubject)) { + throw new ForbiddenRequestError({ + message: "Access denied: subject not allowed" }); } + } + + if (identityJwtAuth.boundAudiences) { + if (!tokenData.aud) { + throw new UnauthorizedError({ + message: "Access denied: token has no audience field" + }); + } + + if ( + !identityJwtAuth.boundAudiences + .split(", ") + .some((policyValue) => doesFieldValueMatchJwtPolicy(tokenData.aud, policyValue)) + ) { + throw new UnauthorizedError({ + message: "Access denied: token audience not allowed" + }); + } + } + + if (identityJwtAuth.boundClaims) { + Object.keys(identityJwtAuth.boundClaims).forEach((claimKey) => { + const claimValue = (identityJwtAuth.boundClaims as Record)[claimKey]; + const value = getValueByDot(tokenData, claimKey); + + if (!value) { + throw new UnauthorizedError({ + message: `Access denied: token has no ${claimKey} field` + }); + } + + // handle both single and multi-valued claims + if (!claimValue.split(", ").some((claimEntry) => doesFieldValueMatchJwtPolicy(value, claimEntry))) { + throw new UnauthorizedError({ + message: `Access denied: claim mismatch for field ${claimKey}` + }); + } + }); + } + + const identityAccessToken = await identityJwtAuthDAL.transaction(async (tx) => { + await membershipIdentityDAL.update( + { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, + { lastLoginAuthMethod: IdentityAuthMethod.JWT_AUTH, lastLoginTime: new Date() }, + tx + ); + const newToken = await identityAccessTokenDAL.create( + { + identityId: identityJwtAuth.identityId, + isAccessTokenRevoked: false, + accessTokenTTL: identityJwtAuth.accessTokenTTL, + accessTokenMaxTTL: identityJwtAuth.accessTokenMaxTTL, + accessTokenNumUses: 0, + accessTokenNumUsesLimit: identityJwtAuth.accessTokenNumUsesLimit, + authMethod: IdentityAuthMethod.JWT_AUTH + }, + tx + ); + + return newToken; }); - } - const identityAccessToken = await identityJwtAuthDAL.transaction(async (tx) => { - await membershipIdentityDAL.update( - { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, - { lastLoginAuthMethod: IdentityAuthMethod.JWT_AUTH, lastLoginTime: new Date() }, - tx - ); - const newToken = await identityAccessTokenDAL.create( + const accessToken = crypto.jwt().sign( { identityId: identityJwtAuth.identityId, - isAccessTokenRevoked: false, - accessTokenTTL: identityJwtAuth.accessTokenTTL, - accessTokenMaxTTL: identityJwtAuth.accessTokenMaxTTL, - accessTokenNumUses: 0, - accessTokenNumUsesLimit: identityJwtAuth.accessTokenNumUsesLimit, - authMethod: IdentityAuthMethod.JWT_AUTH - }, - tx + identityAccessTokenId: identityAccessToken.id, + authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN + } as TIdentityAccessTokenJwtPayload, + appCfg.AUTH_SECRET, + // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error + Number(identityAccessToken.accessTokenTTL) === 0 + ? undefined + : { + expiresIn: Number(identityAccessToken.accessTokenTTL) + } ); - return newToken; - }); + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityJwtAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.JWT_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } - const appCfg = getConfig(); - const accessToken = crypto.jwt().sign( - { - identityId: identityJwtAuth.identityId, - identityAccessTokenId: identityAccessToken.id, - authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN - } as TIdentityAccessTokenJwtPayload, - appCfg.AUTH_SECRET, - // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error - Number(identityAccessToken.accessTokenTTL) === 0 - ? undefined - : { - expiresIn: Number(identityAccessToken.accessTokenTTL) - } - ); - - return { accessToken, identityJwtAuth, identityAccessToken, identity }; + return { accessToken, identityJwtAuth, identityAccessToken, identity }; + } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityJwtAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.JWT_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + throw error; + } }; const attachJwtAuth = async ({ diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts index 49fb597f5..b633dc433 100644 --- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts +++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts @@ -1,4 +1,5 @@ import { ForbiddenError } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import axios, { AxiosError } from "axios"; import https from "https"; import RE2 from "re2"; @@ -37,6 +38,7 @@ import { GatewayHttpProxyActions, GatewayProxyProtocol, withGatewayProxy } from import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2"; import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip"; import { logger } from "@app/lib/logger"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { ActorType, AuthTokenType } from "../auth/auth-type"; import { TIdentityDALFactory } from "../identity/identity-dal"; @@ -182,6 +184,7 @@ export const identityKubernetesAuthServiceFactory = ({ }; const login = async ({ identityId, jwt: serviceAccountJwt }: TLoginKubernetesAuthDTO) => { + const appCfg = getConfig(); const identityKubernetesAuth = await identityKubernetesAuthDAL.findOne({ identityId }); if (!identityKubernetesAuth) { throw new NotFoundError({ @@ -192,294 +195,328 @@ export const identityKubernetesAuthServiceFactory = ({ const identity = await identityDAL.findById(identityKubernetesAuth.identityId); if (!identity) throw new UnauthorizedError({ message: "Identity not found" }); - const { decryptor } = await kmsService.createCipherPairWithDataKey({ - type: KmsDataKey.Organization, - orgId: identity.orgId - }); + const org = await orgDAL.findById(identity.orgId); - let caCert = ""; - if (identityKubernetesAuth.encryptedKubernetesCaCertificate) { - caCert = decryptor({ cipherTextBlob: identityKubernetesAuth.encryptedKubernetesCaCertificate }).toString(); - } + try { + const { decryptor } = await kmsService.createCipherPairWithDataKey({ + type: KmsDataKey.Organization, + orgId: identity.orgId + }); - const tokenReviewCallbackRaw = async (host = identityKubernetesAuth.kubernetesHost, port?: number) => { - logger.info({ host, port }, "tokenReviewCallbackRaw: Processing kubernetes token review using raw API"); - - if (!host || !identityKubernetesAuth.kubernetesHost) { - throw new BadRequestError({ - message: "Kubernetes host is required when token review mode is set to API" - }); + let caCert = ""; + if (identityKubernetesAuth.encryptedKubernetesCaCertificate) { + caCert = decryptor({ cipherTextBlob: identityKubernetesAuth.encryptedKubernetesCaCertificate }).toString(); } - let tokenReviewerJwt = ""; - if (identityKubernetesAuth.encryptedKubernetesTokenReviewerJwt) { - tokenReviewerJwt = decryptor({ - cipherTextBlob: identityKubernetesAuth.encryptedKubernetesTokenReviewerJwt - }).toString(); - } else { - // if no token reviewer is provided means the incoming token has to act as reviewer - tokenReviewerJwt = serviceAccountJwt; - } + const tokenReviewCallbackRaw = async (host = identityKubernetesAuth.kubernetesHost, port?: number) => { + logger.info({ host, port }, "tokenReviewCallbackRaw: Processing kubernetes token review using raw API"); - let servername = identityKubernetesAuth.kubernetesHost; - if (servername.startsWith("https://") || servername.startsWith("http://")) { - servername = new RE2("^https?:\\/\\/").replace(servername, ""); - } + if (!host || !identityKubernetesAuth.kubernetesHost) { + throw new BadRequestError({ + message: "Kubernetes host is required when token review mode is set to API" + }); + } - // get the last colon index, if it has a port, remove it, including the colon - const lastColonIndex = servername.lastIndexOf(":"); - if (lastColonIndex !== -1) { - servername = servername.substring(0, lastColonIndex); - } + let tokenReviewerJwt = ""; + if (identityKubernetesAuth.encryptedKubernetesTokenReviewerJwt) { + tokenReviewerJwt = decryptor({ + cipherTextBlob: identityKubernetesAuth.encryptedKubernetesTokenReviewerJwt + }).toString(); + } else { + // if no token reviewer is provided means the incoming token has to act as reviewer + tokenReviewerJwt = serviceAccountJwt; + } - const baseUrl = port ? `${host}:${port}` : host; + let servername = identityKubernetesAuth.kubernetesHost; + if (servername.startsWith("https://") || servername.startsWith("http://")) { + servername = new RE2("^https?:\\/\\/").replace(servername, ""); + } - const res = await axios - .post( - `${baseUrl}/apis/authentication.k8s.io/v1/tokenreviews`, - { - apiVersion: "authentication.k8s.io/v1", - kind: "TokenReview", - spec: { - token: serviceAccountJwt, - ...(identityKubernetesAuth.allowedAudience ? { audiences: [identityKubernetesAuth.allowedAudience] } : {}) - } - }, - { - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${tokenReviewerJwt}` + // get the last colon index, if it has a port, remove it, including the colon + const lastColonIndex = servername.lastIndexOf(":"); + if (lastColonIndex !== -1) { + servername = servername.substring(0, lastColonIndex); + } + + const baseUrl = port ? `${host}:${port}` : host; + + const res = await axios + .post( + `${baseUrl}/apis/authentication.k8s.io/v1/tokenreviews`, + { + apiVersion: "authentication.k8s.io/v1", + kind: "TokenReview", + spec: { + token: serviceAccountJwt, + ...(identityKubernetesAuth.allowedAudience + ? { audiences: [identityKubernetesAuth.allowedAudience] } + : {}) + } }, - signal: AbortSignal.timeout(10000), - timeout: 10000, - httpsAgent: new https.Agent({ - ca: caCert, - rejectUnauthorized: Boolean(caCert), - servername - }) - } - ) - .catch((err) => { - if (err instanceof AxiosError) { - if (err.response) { - const { message } = err?.response?.data as unknown as { message?: string }; - - if (message) { - throw new UnauthorizedError({ - message, - name: "KubernetesTokenReviewRequestError" - }); - } - } - } - throw err; - }); - - return res.data; - }; - - const tokenReviewCallbackThroughGateway = async (host: string, port?: number) => { - logger.info( - { - host, - port - }, - "tokenReviewCallbackThroughGateway: Processing kubernetes token review using gateway" - ); - - const res = await axios - .post( - `${host}:${port}/apis/authentication.k8s.io/v1/tokenreviews`, - { - apiVersion: "authentication.k8s.io/v1", - kind: "TokenReview", - spec: { - token: serviceAccountJwt, - ...(identityKubernetesAuth.allowedAudience ? { audiences: [identityKubernetesAuth.allowedAudience] } : {}) - } - }, - { - headers: { - "Content-Type": "application/json", - "x-infisical-action": GatewayHttpProxyActions.UseGatewayK8sServiceAccount - }, - signal: AbortSignal.timeout(10000), - timeout: 10000 - } - ) - .catch((err) => { - if (err instanceof AxiosError) { - if (err.response) { - let { message } = err?.response?.data as unknown as { message?: string }; - - if (!message && typeof err.response.data === "string") { - message = err.response.data; - } - - if (message) { - throw new UnauthorizedError({ - message, - name: "KubernetesTokenReviewRequestError" - }); - } - } - } - throw err; - }); - - return res.data; - }; - - let data: TCreateTokenReviewResponse | undefined; - - if (identityKubernetesAuth.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway) { - if (!identityKubernetesAuth.gatewayId && !identityKubernetesAuth.gatewayV2Id) { - throw new BadRequestError({ - message: "Gateway ID is required when token review mode is set to Gateway" - }); - } - - data = await $gatewayProxyWrapper( - { - gatewayId: (identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayId) as string, - reviewTokenThroughGateway: true - }, - tokenReviewCallbackThroughGateway - ); - } else if (identityKubernetesAuth.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api) { - if (!identityKubernetesAuth.kubernetesHost) { - throw new BadRequestError({ - message: "Kubernetes host is required when token review mode is set to API" - }); - } - - let { kubernetesHost } = identityKubernetesAuth; - if (kubernetesHost.startsWith("https://") || kubernetesHost.startsWith("http://")) { - kubernetesHost = new RE2("^https?:\\/\\/").replace(kubernetesHost, ""); - } - - const [k8sHost, k8sPort] = kubernetesHost.split(":"); - - data = - identityKubernetesAuth.gatewayId || identityKubernetesAuth.gatewayV2Id - ? await $gatewayProxyWrapper( - { - gatewayId: (identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayId) as string, - targetHost: k8sHost, - targetPort: k8sPort ? Number(k8sPort) : 443, - reviewTokenThroughGateway: false + { + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${tokenReviewerJwt}` }, - tokenReviewCallbackRaw - ) - : await tokenReviewCallbackRaw(); - } else { - throw new BadRequestError({ - message: `Invalid token review mode: ${identityKubernetesAuth.tokenReviewMode}` - }); - } + signal: AbortSignal.timeout(10000), + timeout: 10000, + httpsAgent: new https.Agent({ + ca: caCert, + rejectUnauthorized: Boolean(caCert), + servername + }) + } + ) + .catch((err) => { + if (err instanceof AxiosError) { + if (err.response) { + const { message } = err?.response?.data as unknown as { message?: string }; - if (!data) { - throw new BadRequestError({ - message: "Failed to review token" - }); - } + if (message) { + throw new UnauthorizedError({ + message, + name: "KubernetesTokenReviewRequestError" + }); + } + } + } + throw err; + }); - if ("error" in data.status) - throw new UnauthorizedError({ message: data.status.error, name: "KubernetesTokenReviewError" }); + return res.data; + }; - // check the response to determine if the token is valid - if (!(data.status && data.status.authenticated)) - throw new UnauthorizedError({ - message: "Kubernetes token not authenticated", - name: "KubernetesTokenReviewError" + const tokenReviewCallbackThroughGateway = async (host: string, port?: number) => { + logger.info( + { + host, + port + }, + "tokenReviewCallbackThroughGateway: Processing kubernetes token review using gateway" + ); + + const res = await axios + .post( + `${host}:${port}/apis/authentication.k8s.io/v1/tokenreviews`, + { + apiVersion: "authentication.k8s.io/v1", + kind: "TokenReview", + spec: { + token: serviceAccountJwt, + ...(identityKubernetesAuth.allowedAudience + ? { audiences: [identityKubernetesAuth.allowedAudience] } + : {}) + } + }, + { + headers: { + "Content-Type": "application/json", + "x-infisical-action": GatewayHttpProxyActions.UseGatewayK8sServiceAccount + }, + signal: AbortSignal.timeout(10000), + timeout: 10000 + } + ) + .catch((err) => { + if (err instanceof AxiosError) { + if (err.response) { + let { message } = err?.response?.data as unknown as { message?: string }; + + if (!message && typeof err.response.data === "string") { + message = err.response.data; + } + + if (message) { + throw new UnauthorizedError({ + message, + name: "KubernetesTokenReviewRequestError" + }); + } + } + } + throw err; + }); + + return res.data; + }; + + let data: TCreateTokenReviewResponse | undefined; + + if (identityKubernetesAuth.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway) { + if (!identityKubernetesAuth.gatewayId && !identityKubernetesAuth.gatewayV2Id) { + throw new BadRequestError({ + message: "Gateway ID is required when token review mode is set to Gateway" + }); + } + + data = await $gatewayProxyWrapper( + { + gatewayId: (identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayId) as string, + reviewTokenThroughGateway: true + }, + tokenReviewCallbackThroughGateway + ); + } else if (identityKubernetesAuth.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api) { + if (!identityKubernetesAuth.kubernetesHost) { + throw new BadRequestError({ + message: "Kubernetes host is required when token review mode is set to API" + }); + } + + let { kubernetesHost } = identityKubernetesAuth; + if (kubernetesHost.startsWith("https://") || kubernetesHost.startsWith("http://")) { + kubernetesHost = new RE2("^https?:\\/\\/").replace(kubernetesHost, ""); + } + + const [k8sHost, k8sPort] = kubernetesHost.split(":"); + + data = + identityKubernetesAuth.gatewayId || identityKubernetesAuth.gatewayV2Id + ? await $gatewayProxyWrapper( + { + gatewayId: (identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayId) as string, + targetHost: k8sHost, + targetPort: k8sPort ? Number(k8sPort) : 443, + reviewTokenThroughGateway: false + }, + tokenReviewCallbackRaw + ) + : await tokenReviewCallbackRaw(); + } else { + throw new BadRequestError({ + message: `Invalid token review mode: ${identityKubernetesAuth.tokenReviewMode}` + }); + } + + if (!data) { + throw new BadRequestError({ + message: "Failed to review token" + }); + } + + if ("error" in data.status) + throw new UnauthorizedError({ message: data.status.error, name: "KubernetesTokenReviewError" }); + + // check the response to determine if the token is valid + if (!(data.status && data.status.authenticated)) + throw new UnauthorizedError({ + message: "Kubernetes token not authenticated", + name: "KubernetesTokenReviewError" + }); + + const { namespace: targetNamespace, name: targetName } = extractK8sUsername(data.status.user.username); + + if (identityKubernetesAuth.allowedNamespaces) { + // validate if [targetNamespace] is in the list of allowed namespaces + + const isNamespaceAllowed = identityKubernetesAuth.allowedNamespaces + .split(",") + .map((namespace) => namespace.trim()) + .some((namespace) => namespace === targetNamespace); + + if (!isNamespaceAllowed) + throw new UnauthorizedError({ + message: "Access denied: K8s namespace not allowed." + }); + } + + if (identityKubernetesAuth.allowedNames) { + // validate if [targetName] is in the list of allowed names + + const isNameAllowed = identityKubernetesAuth.allowedNames + .split(",") + .map((name) => name.trim()) + .some((name) => name === targetName); + + if (!isNameAllowed) + throw new UnauthorizedError({ + message: "Access denied: K8s name not allowed." + }); + } + + if (identityKubernetesAuth.allowedAudience) { + // validate if [audience] is in the list of allowed audiences + const isAudienceAllowed = data.status.audiences.some( + (audience) => audience === identityKubernetesAuth.allowedAudience + ); + + if (!isAudienceAllowed) + throw new UnauthorizedError({ + message: "Access denied: K8s audience not allowed." + }); + } + + const identityAccessToken = await identityKubernetesAuthDAL.transaction(async (tx) => { + await membershipIdentityDAL.update( + { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, + { lastLoginAuthMethod: IdentityAuthMethod.KUBERNETES_AUTH, lastLoginTime: new Date() }, + tx + ); + const newToken = await identityAccessTokenDAL.create( + { + identityId: identityKubernetesAuth.identityId, + isAccessTokenRevoked: false, + accessTokenTTL: identityKubernetesAuth.accessTokenTTL, + accessTokenMaxTTL: identityKubernetesAuth.accessTokenMaxTTL, + accessTokenNumUses: 0, + accessTokenNumUsesLimit: identityKubernetesAuth.accessTokenNumUsesLimit, + authMethod: IdentityAuthMethod.KUBERNETES_AUTH + }, + tx + ); + return newToken; }); - const { namespace: targetNamespace, name: targetName } = extractK8sUsername(data.status.user.username); - - if (identityKubernetesAuth.allowedNamespaces) { - // validate if [targetNamespace] is in the list of allowed namespaces - - const isNamespaceAllowed = identityKubernetesAuth.allowedNamespaces - .split(",") - .map((namespace) => namespace.trim()) - .some((namespace) => namespace === targetNamespace); - - if (!isNamespaceAllowed) - throw new UnauthorizedError({ - message: "Access denied: K8s namespace not allowed." - }); - } - - if (identityKubernetesAuth.allowedNames) { - // validate if [targetName] is in the list of allowed names - - const isNameAllowed = identityKubernetesAuth.allowedNames - .split(",") - .map((name) => name.trim()) - .some((name) => name === targetName); - - if (!isNameAllowed) - throw new UnauthorizedError({ - message: "Access denied: K8s name not allowed." - }); - } - - if (identityKubernetesAuth.allowedAudience) { - // validate if [audience] is in the list of allowed audiences - const isAudienceAllowed = data.status.audiences.some( - (audience) => audience === identityKubernetesAuth.allowedAudience - ); - - if (!isAudienceAllowed) - throw new UnauthorizedError({ - message: "Access denied: K8s audience not allowed." - }); - } - - const identityAccessToken = await identityKubernetesAuthDAL.transaction(async (tx) => { - await membershipIdentityDAL.update( - { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, - { lastLoginAuthMethod: IdentityAuthMethod.KUBERNETES_AUTH, lastLoginTime: new Date() }, - tx - ); - const newToken = await identityAccessTokenDAL.create( + const accessToken = crypto.jwt().sign( { identityId: identityKubernetesAuth.identityId, - isAccessTokenRevoked: false, - accessTokenTTL: identityKubernetesAuth.accessTokenTTL, - accessTokenMaxTTL: identityKubernetesAuth.accessTokenMaxTTL, - accessTokenNumUses: 0, - accessTokenNumUsesLimit: identityKubernetesAuth.accessTokenNumUsesLimit, - authMethod: IdentityAuthMethod.KUBERNETES_AUTH - }, - tx + identityAccessTokenId: identityAccessToken.id, + authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN, + identityAuth: { + kubernetes: { + namespace: targetNamespace, + name: targetName + } + } + } as TIdentityAccessTokenJwtPayload, + appCfg.AUTH_SECRET, + // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error + Number(identityAccessToken.accessTokenTTL) === 0 + ? undefined + : { + expiresIn: Number(identityAccessToken.accessTokenTTL) + } ); - return newToken; - }); - const appCfg = getConfig(); - const accessToken = crypto.jwt().sign( - { - identityId: identityKubernetesAuth.identityId, - identityAccessTokenId: identityAccessToken.id, - authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN, - identityAuth: { - kubernetes: { - namespace: targetNamespace, - name: targetName - } - } - } as TIdentityAccessTokenJwtPayload, - appCfg.AUTH_SECRET, - // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error - Number(identityAccessToken.accessTokenTTL) === 0 - ? undefined - : { - expiresIn: Number(identityAccessToken.accessTokenTTL) - } - ); + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityKubernetesAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.KUBERNETES_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } - return { accessToken, identityKubernetesAuth, identityAccessToken, identity }; + return { accessToken, identityKubernetesAuth, identityAccessToken, identity }; + } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityKubernetesAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.KUBERNETES_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + throw error; + } }; const attachKubernetesAuth = async ({ @@ -719,7 +756,8 @@ export const identityKubernetesAuthServiceFactory = ({ ); } - const shouldUpdateGatewayId = Boolean(gatewayId); + // Strict check to see if gateway ID is undefined. It should update the gateway ID to null if its strictly set to null. + const shouldUpdateGatewayId = Boolean(gatewayId !== undefined); const gatewayIdValue = isGatewayV1 ? gatewayId : null; const gatewayV2IdValue = isGatewayV1 ? null : gatewayId; diff --git a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts index 272e45c4e..d327dabee 100644 --- a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts +++ b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/no-unsafe-assignment */ import { ForbiddenError } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import slugify from "@sindresorhus/slugify"; import { AccessScope, IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas"; @@ -29,6 +30,7 @@ import { } from "@app/lib/errors"; import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip"; import { logger } from "@app/lib/logger"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { ActorType, AuthTokenType } from "../auth/auth-type"; import { TIdentityDALFactory } from "../identity/identity-dal"; @@ -151,6 +153,7 @@ export const identityLdapAuthServiceFactory = ({ }; const login = async ({ identityId }: TLoginLdapAuthDTO) => { + const appCfg = getConfig(); const identityLdapAuth = await identityLdapAuthDAL.findOne({ identityId }); if (!identityLdapAuth) { @@ -162,6 +165,7 @@ export const identityLdapAuthServiceFactory = ({ const identity = await identityDAL.findById(identityLdapAuth.identityId); if (!identity) throw new UnauthorizedError({ message: "Identity not found" }); + const org = await orgDAL.findById(identity.orgId); const plan = await licenseService.getPlan(identity.orgId); if (!plan.ldap) { throw new BadRequestError({ @@ -170,44 +174,72 @@ export const identityLdapAuthServiceFactory = ({ }); } - const identityAccessToken = await identityLdapAuthDAL.transaction(async (tx) => { - await membershipIdentityDAL.update( - { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, - { lastLoginAuthMethod: IdentityAuthMethod.LDAP_AUTH, lastLoginTime: new Date() }, - tx - ); - const newToken = await identityAccessTokenDAL.create( + try { + const identityAccessToken = await identityLdapAuthDAL.transaction(async (tx) => { + await membershipIdentityDAL.update( + { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, + { lastLoginAuthMethod: IdentityAuthMethod.LDAP_AUTH, lastLoginTime: new Date() }, + tx + ); + const newToken = await identityAccessTokenDAL.create( + { + identityId: identityLdapAuth.identityId, + isAccessTokenRevoked: false, + accessTokenTTL: identityLdapAuth.accessTokenTTL, + accessTokenMaxTTL: identityLdapAuth.accessTokenMaxTTL, + accessTokenNumUses: 0, + accessTokenNumUsesLimit: identityLdapAuth.accessTokenNumUsesLimit, + authMethod: IdentityAuthMethod.LDAP_AUTH + }, + tx + ); + return newToken; + }); + + const accessToken = crypto.jwt().sign( { identityId: identityLdapAuth.identityId, - isAccessTokenRevoked: false, - accessTokenTTL: identityLdapAuth.accessTokenTTL, - accessTokenMaxTTL: identityLdapAuth.accessTokenMaxTTL, - accessTokenNumUses: 0, - accessTokenNumUsesLimit: identityLdapAuth.accessTokenNumUsesLimit, - authMethod: IdentityAuthMethod.LDAP_AUTH - }, - tx + identityAccessTokenId: identityAccessToken.id, + authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN + } as TIdentityAccessTokenJwtPayload, + appCfg.AUTH_SECRET, + // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error + Number(identityAccessToken.accessTokenTTL) === 0 + ? undefined + : { + expiresIn: Number(identityAccessToken.accessTokenTTL) + } ); - return newToken; - }); - const appCfg = getConfig(); - const accessToken = crypto.jwt().sign( - { - identityId: identityLdapAuth.identityId, - identityAccessTokenId: identityAccessToken.id, - authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN - } as TIdentityAccessTokenJwtPayload, - appCfg.AUTH_SECRET, - // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error - Number(identityAccessToken.accessTokenTTL) === 0 - ? undefined - : { - expiresIn: Number(identityAccessToken.accessTokenTTL) - } - ); + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityLdapAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.LDAP_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } - return { accessToken, identityLdapAuth, identityAccessToken, identity }; + return { accessToken, identityLdapAuth, identityAccessToken, identity }; + } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityLdapAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.LDAP_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + throw error; + } }; const attachLdapAuth = async ({ diff --git a/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts b/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts index 6d7f0c4d3..c75abc76b 100644 --- a/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts +++ b/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/no-unsafe-assignment */ import { ForbiddenError } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import { AxiosError } from "axios"; import RE2 from "re2"; @@ -23,6 +24,7 @@ import { } from "@app/lib/errors"; import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip"; import { logger } from "@app/lib/logger"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { ActorType, AuthTokenType } from "../auth/auth-type"; import { TIdentityDALFactory } from "../identity/identity-dal"; @@ -63,6 +65,7 @@ export const identityOciAuthServiceFactory = ({ orgDAL }: TIdentityOciAuthServiceFactoryDep) => { const login = async ({ identityId, headers, userOcid }: TLoginOciAuthDTO) => { + const appCfg = getConfig(); const identityOciAuth = await identityOciAuthDAL.findOne({ identityId }); if (!identityOciAuth) { throw new NotFoundError({ message: "OCI auth method not found for identity, did you configure OCI auth?" }); @@ -71,80 +74,109 @@ export const identityOciAuthServiceFactory = ({ const identity = await identityDAL.findById(identityOciAuth.identityId); if (!identity) throw new UnauthorizedError({ message: "Identity not found" }); - // Validate OCI host format. Ensures that the host is in "identity..oraclecloud.com" format. - if (!headers.host || !new RE2("^identity\\.([a-z]{2}-[a-z]+-[1-9])\\.oraclecloud\\.com$").test(headers.host)) { - throw new BadRequestError({ - message: "Invalid OCI host format. Expected format: identity..oraclecloud.com" - }); - } - - const { data } = await request - .get(`https://${headers.host}/20160918/users/${userOcid}`, { - headers - }) - .catch((err: AxiosError) => { - logger.error(err.response, "OciIdentityLogin: Failed to authenticate with Oracle Cloud"); - throw err; - }); - - if (data.compartmentId !== identityOciAuth.tenancyOcid) { - throw new UnauthorizedError({ - message: "Access denied: OCI account isn't part of tenancy." - }); - } - - if (identityOciAuth.allowedUsernames) { - const isAccountAllowed = identityOciAuth.allowedUsernames.split(",").some((name) => name.trim() === data.name); - - if (!isAccountAllowed) - throw new UnauthorizedError({ - message: "Access denied: OCI account username not allowed." + const org = await orgDAL.findById(identity.orgId); + try { + // Validate OCI host format. Ensures that the host is in "identity..oraclecloud.com" format. + if (!headers.host || !new RE2("^identity\\.([a-z]{2}-[a-z]+-[1-9])\\.oraclecloud\\.com$").test(headers.host)) { + throw new BadRequestError({ + message: "Invalid OCI host format. Expected format: identity..oraclecloud.com" }); - } + } - // Generate the token - const identityAccessToken = await identityOciAuthDAL.transaction(async (tx) => { - await membershipIdentityDAL.update( - { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, - { lastLoginAuthMethod: IdentityAuthMethod.OCI_AUTH, lastLoginTime: new Date() }, - tx - ); - const newToken = await identityAccessTokenDAL.create( + const { data } = await request + .get(`https://${headers.host}/20160918/users/${userOcid}`, { + headers + }) + .catch((err: AxiosError) => { + logger.error(err.response, "OciIdentityLogin: Failed to authenticate with Oracle Cloud"); + throw err; + }); + + if (data.compartmentId !== identityOciAuth.tenancyOcid) { + throw new UnauthorizedError({ + message: "Access denied: OCI account isn't part of tenancy." + }); + } + + if (identityOciAuth.allowedUsernames) { + const isAccountAllowed = identityOciAuth.allowedUsernames.split(",").some((name) => name.trim() === data.name); + + if (!isAccountAllowed) + throw new UnauthorizedError({ + message: "Access denied: OCI account username not allowed." + }); + } + + // Generate the token + const identityAccessToken = await identityOciAuthDAL.transaction(async (tx) => { + await membershipIdentityDAL.update( + { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, + { lastLoginAuthMethod: IdentityAuthMethod.OCI_AUTH, lastLoginTime: new Date() }, + tx + ); + const newToken = await identityAccessTokenDAL.create( + { + identityId: identityOciAuth.identityId, + isAccessTokenRevoked: false, + accessTokenTTL: identityOciAuth.accessTokenTTL, + accessTokenMaxTTL: identityOciAuth.accessTokenMaxTTL, + accessTokenNumUses: 0, + accessTokenNumUsesLimit: identityOciAuth.accessTokenNumUsesLimit, + authMethod: IdentityAuthMethod.OCI_AUTH + }, + tx + ); + return newToken; + }); + + const accessToken = crypto.jwt().sign( { identityId: identityOciAuth.identityId, - isAccessTokenRevoked: false, - accessTokenTTL: identityOciAuth.accessTokenTTL, - accessTokenMaxTTL: identityOciAuth.accessTokenMaxTTL, - accessTokenNumUses: 0, - accessTokenNumUsesLimit: identityOciAuth.accessTokenNumUsesLimit, - authMethod: IdentityAuthMethod.OCI_AUTH - }, - tx + identityAccessTokenId: identityAccessToken.id, + authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN + } as TIdentityAccessTokenJwtPayload, + appCfg.AUTH_SECRET, + Number(identityAccessToken.accessTokenTTL) === 0 + ? undefined + : { + expiresIn: Number(identityAccessToken.accessTokenTTL) + } ); - return newToken; - }); - const appCfg = getConfig(); - const accessToken = crypto.jwt().sign( - { - identityId: identityOciAuth.identityId, - identityAccessTokenId: identityAccessToken.id, - authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN - } as TIdentityAccessTokenJwtPayload, - appCfg.AUTH_SECRET, - Number(identityAccessToken.accessTokenTTL) === 0 - ? undefined - : { - expiresIn: Number(identityAccessToken.accessTokenTTL) - } - ); + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityOciAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.OCI_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } - return { - identityOciAuth, - accessToken, - identityAccessToken, - identity - }; + return { + identityOciAuth, + accessToken, + identityAccessToken, + identity + }; + } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityOciAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.OCI_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + throw error; + } }; const attachOciAuth = async ({ diff --git a/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts b/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts index 628b69f14..a03beeb3b 100644 --- a/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts +++ b/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts @@ -1,4 +1,5 @@ import { ForbiddenError } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import axios from "axios"; import https from "https"; import jwt from "jsonwebtoken"; @@ -22,6 +23,7 @@ import { UnauthorizedError } from "@app/lib/errors"; import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { getValueByDot } from "@app/lib/template/dot-access"; import { ActorType, AuthTokenType } from "../auth/auth-type"; @@ -67,6 +69,7 @@ export const identityOidcAuthServiceFactory = ({ orgDAL }: TIdentityOidcAuthServiceFactoryDep) => { const login = async ({ identityId, jwt: oidcJwt }: TLoginOidcAuthDTO) => { + const appCfg = getConfig(); const identityOidcAuth = await identityOidcAuthDAL.findOne({ identityId }); if (!identityOidcAuth) { throw new NotFoundError({ message: "OIDC auth method not found for identity, did you configure OIDC auth?" }); @@ -75,151 +78,180 @@ export const identityOidcAuthServiceFactory = ({ const identity = await identityDAL.findById(identityOidcAuth.identityId); if (!identity) throw new UnauthorizedError({ message: "Identity not found" }); - const { decryptor } = await kmsService.createCipherPairWithDataKey({ - type: KmsDataKey.Organization, - orgId: identity.orgId - }); - - let caCert = ""; - if (identityOidcAuth.encryptedCaCertificate) { - caCert = decryptor({ cipherTextBlob: identityOidcAuth.encryptedCaCertificate }).toString(); - } - - const requestAgent = new https.Agent({ ca: caCert, rejectUnauthorized: !!caCert }); - const { data: discoveryDoc } = await axios.get<{ jwks_uri: string }>( - `${identityOidcAuth.oidcDiscoveryUrl}/.well-known/openid-configuration`, - { - httpsAgent: identityOidcAuth.oidcDiscoveryUrl.includes("https") ? requestAgent : undefined - } - ); - const jwksUri = discoveryDoc.jwks_uri; - - const decodedToken = crypto.jwt().decode(oidcJwt, { complete: true }); - if (!decodedToken) { - throw new UnauthorizedError({ - message: "Invalid JWT" - }); - } - - const client = new JwksClient({ - jwksUri, - requestAgent: identityOidcAuth.oidcDiscoveryUrl.includes("https") ? requestAgent : undefined - }); - - const { kid } = decodedToken.header as { kid: string }; - const oidcSigningKey = await client.getSigningKey(kid); - - let tokenData: Record; + const org = await orgDAL.findById(identity.orgId); try { - tokenData = crypto.jwt().verify(oidcJwt, oidcSigningKey.getPublicKey(), { - issuer: identityOidcAuth.boundIssuer - }) as Record; - } catch (error) { - if (error instanceof jwt.JsonWebTokenError) { + const { decryptor } = await kmsService.createCipherPairWithDataKey({ + type: KmsDataKey.Organization, + orgId: identity.orgId + }); + + let caCert = ""; + if (identityOidcAuth.encryptedCaCertificate) { + caCert = decryptor({ cipherTextBlob: identityOidcAuth.encryptedCaCertificate }).toString(); + } + + const requestAgent = new https.Agent({ ca: caCert, rejectUnauthorized: !!caCert }); + const { data: discoveryDoc } = await axios.get<{ jwks_uri: string }>( + `${identityOidcAuth.oidcDiscoveryUrl}/.well-known/openid-configuration`, + { + httpsAgent: identityOidcAuth.oidcDiscoveryUrl.includes("https") ? requestAgent : undefined + } + ); + const jwksUri = discoveryDoc.jwks_uri; + + const decodedToken = crypto.jwt().decode(oidcJwt, { complete: true }); + if (!decodedToken) { throw new UnauthorizedError({ - message: `Access denied: ${error.message}` + message: "Invalid JWT" + }); + } + + const client = new JwksClient({ + jwksUri, + requestAgent: identityOidcAuth.oidcDiscoveryUrl.includes("https") ? requestAgent : undefined + }); + + const { kid } = decodedToken.header as { kid: string }; + const oidcSigningKey = await client.getSigningKey(kid); + + let tokenData: Record; + try { + tokenData = crypto.jwt().verify(oidcJwt, oidcSigningKey.getPublicKey(), { + issuer: identityOidcAuth.boundIssuer + }) as Record; + } catch (error) { + if (error instanceof jwt.JsonWebTokenError) { + throw new UnauthorizedError({ + message: `Access denied: ${error.message}` + }); + } + throw error; + } + + if (identityOidcAuth.boundSubject) { + if (!doesFieldValueMatchOidcPolicy(tokenData.sub, identityOidcAuth.boundSubject)) { + throw new ForbiddenRequestError({ + message: "Access denied: OIDC subject not allowed." + }); + } + } + + if (identityOidcAuth.boundAudiences) { + if ( + !identityOidcAuth.boundAudiences + .split(", ") + .some((policyValue) => doesAudValueMatchOidcPolicy(tokenData.aud, policyValue)) + ) { + throw new UnauthorizedError({ + message: "Access denied: OIDC audience not allowed." + }); + } + } + + if (identityOidcAuth.boundClaims) { + Object.keys(identityOidcAuth.boundClaims).forEach((claimKey) => { + const claimValue = (identityOidcAuth.boundClaims as Record)[claimKey]; + const value = getValueByDot(tokenData, claimKey); + + if (!value) { + throw new UnauthorizedError({ + message: `Access denied: token has no ${claimKey} field` + }); + } + + // handle both single and multi-valued claims + if (!claimValue.split(", ").some((claimEntry) => doesFieldValueMatchOidcPolicy(value, claimEntry))) { + throw new UnauthorizedError({ + message: "Access denied: OIDC claim not allowed." + }); + } + }); + } + + const filteredClaims: Record = {}; + if (identityOidcAuth.claimMetadataMapping) { + Object.keys(identityOidcAuth.claimMetadataMapping).forEach((permissionKey) => { + const claimKey = (identityOidcAuth.claimMetadataMapping as Record)[permissionKey]; + const value = getValueByDot(tokenData, claimKey); + if (!value) { + throw new UnauthorizedError({ + message: `Access denied: token has no ${claimKey} field` + }); + } + filteredClaims[permissionKey] = value.toString(); + }); + } + + const identityAccessToken = await identityOidcAuthDAL.transaction(async (tx) => { + await membershipIdentityDAL.update( + { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, + { lastLoginAuthMethod: IdentityAuthMethod.OIDC_AUTH, lastLoginTime: new Date() }, + tx + ); + const newToken = await identityAccessTokenDAL.create( + { + identityId: identityOidcAuth.identityId, + isAccessTokenRevoked: false, + accessTokenTTL: identityOidcAuth.accessTokenTTL, + accessTokenMaxTTL: identityOidcAuth.accessTokenMaxTTL, + accessTokenNumUses: 0, + accessTokenNumUsesLimit: identityOidcAuth.accessTokenNumUsesLimit, + authMethod: IdentityAuthMethod.OIDC_AUTH + }, + tx + ); + return newToken; + }); + + const accessToken = crypto.jwt().sign( + { + identityId: identityOidcAuth.identityId, + identityAccessTokenId: identityAccessToken.id, + authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN, + identityAuth: { + oidc: { + claims: filteredClaims + } + } + } as TIdentityAccessTokenJwtPayload, + appCfg.AUTH_SECRET, + // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error + Number(identityAccessToken.accessTokenTTL) === 0 + ? undefined + : { + expiresIn: Number(identityAccessToken.accessTokenTTL) + } + ); + + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityOidcAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.OIDC_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + + return { accessToken, identityOidcAuth, identityAccessToken, identity, oidcTokenData: tokenData }; + } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityOidcAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.OIDC_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") }); } throw error; } - - if (identityOidcAuth.boundSubject) { - if (!doesFieldValueMatchOidcPolicy(tokenData.sub, identityOidcAuth.boundSubject)) { - throw new ForbiddenRequestError({ - message: "Access denied: OIDC subject not allowed." - }); - } - } - - if (identityOidcAuth.boundAudiences) { - if ( - !identityOidcAuth.boundAudiences - .split(", ") - .some((policyValue) => doesAudValueMatchOidcPolicy(tokenData.aud, policyValue)) - ) { - throw new UnauthorizedError({ - message: "Access denied: OIDC audience not allowed." - }); - } - } - - if (identityOidcAuth.boundClaims) { - Object.keys(identityOidcAuth.boundClaims).forEach((claimKey) => { - const claimValue = (identityOidcAuth.boundClaims as Record)[claimKey]; - const value = getValueByDot(tokenData, claimKey); - - if (!value) { - throw new UnauthorizedError({ - message: `Access denied: token has no ${claimKey} field` - }); - } - - // handle both single and multi-valued claims - if (!claimValue.split(", ").some((claimEntry) => doesFieldValueMatchOidcPolicy(value, claimEntry))) { - throw new UnauthorizedError({ - message: "Access denied: OIDC claim not allowed." - }); - } - }); - } - - const filteredClaims: Record = {}; - if (identityOidcAuth.claimMetadataMapping) { - Object.keys(identityOidcAuth.claimMetadataMapping).forEach((permissionKey) => { - const claimKey = (identityOidcAuth.claimMetadataMapping as Record)[permissionKey]; - const value = getValueByDot(tokenData, claimKey); - if (!value) { - throw new UnauthorizedError({ - message: `Access denied: token has no ${claimKey} field` - }); - } - filteredClaims[permissionKey] = value.toString(); - }); - } - - const identityAccessToken = await identityOidcAuthDAL.transaction(async (tx) => { - await membershipIdentityDAL.update( - { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, - { lastLoginAuthMethod: IdentityAuthMethod.OIDC_AUTH, lastLoginTime: new Date() }, - tx - ); - const newToken = await identityAccessTokenDAL.create( - { - identityId: identityOidcAuth.identityId, - isAccessTokenRevoked: false, - accessTokenTTL: identityOidcAuth.accessTokenTTL, - accessTokenMaxTTL: identityOidcAuth.accessTokenMaxTTL, - accessTokenNumUses: 0, - accessTokenNumUsesLimit: identityOidcAuth.accessTokenNumUsesLimit, - authMethod: IdentityAuthMethod.OIDC_AUTH - }, - tx - ); - return newToken; - }); - - const appCfg = getConfig(); - const accessToken = crypto.jwt().sign( - { - identityId: identityOidcAuth.identityId, - identityAccessTokenId: identityAccessToken.id, - authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN, - identityAuth: { - oidc: { - claims: filteredClaims - } - } - } as TIdentityAccessTokenJwtPayload, - appCfg.AUTH_SECRET, - // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error - Number(identityAccessToken.accessTokenTTL) === 0 - ? undefined - : { - expiresIn: Number(identityAccessToken.accessTokenTTL) - } - ); - - return { accessToken, identityOidcAuth, identityAccessToken, identity, oidcTokenData: tokenData }; }; const attachOidcAuth = async ({ diff --git a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts index 24c82ccac..60670d035 100644 --- a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts +++ b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts @@ -1,4 +1,5 @@ import { ForbiddenError } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import { AccessScope, IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas"; import { TLicenseServiceFactory } from "@app/ee/services/license/license-service"; @@ -19,6 +20,7 @@ import { UnauthorizedError } from "@app/lib/errors"; import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { ActorType, AuthTokenType } from "../auth/auth-type"; import { TIdentityDALFactory } from "../identity/identity-dal"; @@ -27,6 +29,7 @@ import { TIdentityAccessTokenJwtPayload } from "../identity-access-token/identit import { TKmsServiceFactory } from "../kms/kms-service"; import { KmsDataKey } from "../kms/kms-types"; import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal"; +import { TOrgDALFactory } from "../org/org-dal"; import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns"; import { TIdentityTlsCertAuthDALFactory } from "./identity-tls-cert-auth-dal"; import { TIdentityTlsCertAuthServiceFactory } from "./identity-tls-cert-auth-types"; @@ -42,6 +45,7 @@ type TIdentityTlsCertAuthServiceFactoryDep = { licenseService: Pick; permissionService: Pick; kmsService: Pick; + orgDAL: Pick; }; const parseSubjectDetails = (data: string) => { @@ -60,9 +64,11 @@ export const identityTlsCertAuthServiceFactory = ({ membershipIdentityDAL, licenseService, permissionService, - kmsService + kmsService, + orgDAL }: TIdentityTlsCertAuthServiceFactoryDep): TIdentityTlsCertAuthServiceFactory => { const login: TIdentityTlsCertAuthServiceFactory["login"] = async ({ identityId, clientCertificate }) => { + const appCfg = getConfig(); const identityTlsCertAuth = await identityTlsCertAuthDAL.findOne({ identityId }); if (!identityTlsCertAuth) { throw new NotFoundError({ @@ -73,94 +79,124 @@ export const identityTlsCertAuthServiceFactory = ({ const identity = await identityDAL.findById(identityTlsCertAuth.identityId); if (!identity) throw new UnauthorizedError({ message: "Identity not found" }); - const { decryptor } = await kmsService.createCipherPairWithDataKey({ - type: KmsDataKey.Organization, - orgId: identity.orgId - }); + const org = await orgDAL.findById(identity.orgId); - const caCertificate = decryptor({ - cipherTextBlob: identityTlsCertAuth.encryptedCaCertificate - }).toString(); - - const leafCertificate = extractX509CertFromChain(decodeURIComponent(clientCertificate))?.[0]; - if (!leafCertificate) { - throw new BadRequestError({ message: "Missing client certificate" }); - } - - const clientCertificateX509 = new crypto.nativeCrypto.X509Certificate(leafCertificate); - const caCertificateX509 = new crypto.nativeCrypto.X509Certificate(caCertificate); - - const isValidCertificate = clientCertificateX509.verify(caCertificateX509.publicKey); - if (!isValidCertificate) - throw new UnauthorizedError({ - message: "Access denied: Certificate not issued by the provided CA." + try { + const { decryptor } = await kmsService.createCipherPairWithDataKey({ + type: KmsDataKey.Organization, + orgId: identity.orgId }); - if (new Date(clientCertificateX509.validTo) < new Date()) { - throw new UnauthorizedError({ - message: "Access denied: Certificate has expired." - }); - } + const caCertificate = decryptor({ + cipherTextBlob: identityTlsCertAuth.encryptedCaCertificate + }).toString(); - if (new Date(clientCertificateX509.validFrom) > new Date()) { - throw new UnauthorizedError({ - message: "Access denied: Certificate not yet valid." - }); - } + const leafCertificate = extractX509CertFromChain(decodeURIComponent(clientCertificate))?.[0]; + if (!leafCertificate) { + throw new BadRequestError({ message: "Missing client certificate" }); + } - const subjectDetails = parseSubjectDetails(clientCertificateX509.subject); - if (identityTlsCertAuth.allowedCommonNames) { - const isValidCommonName = identityTlsCertAuth.allowedCommonNames.split(",").includes(subjectDetails.CN); - if (!isValidCommonName) { + const clientCertificateX509 = new crypto.nativeCrypto.X509Certificate(leafCertificate); + const caCertificateX509 = new crypto.nativeCrypto.X509Certificate(caCertificate); + + const isValidCertificate = clientCertificateX509.verify(caCertificateX509.publicKey); + if (!isValidCertificate) throw new UnauthorizedError({ - message: "Access denied: TLS Certificate Auth common name not allowed." + message: "Access denied: Certificate not issued by the provided CA." + }); + + if (new Date(clientCertificateX509.validTo) < new Date()) { + throw new UnauthorizedError({ + message: "Access denied: Certificate has expired." }); } - } - // Generate the token - const identityAccessToken = await identityTlsCertAuthDAL.transaction(async (tx) => { - await membershipIdentityDAL.update( - { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, - { lastLoginAuthMethod: IdentityAuthMethod.TLS_CERT_AUTH, lastLoginTime: new Date() }, - tx - ); - const newToken = await identityAccessTokenDAL.create( + if (new Date(clientCertificateX509.validFrom) > new Date()) { + throw new UnauthorizedError({ + message: "Access denied: Certificate not yet valid." + }); + } + + const subjectDetails = parseSubjectDetails(clientCertificateX509.subject); + if (identityTlsCertAuth.allowedCommonNames) { + const isValidCommonName = identityTlsCertAuth.allowedCommonNames.split(",").includes(subjectDetails.CN); + if (!isValidCommonName) { + throw new UnauthorizedError({ + message: "Access denied: TLS Certificate Auth common name not allowed." + }); + } + } + + // Generate the token + const identityAccessToken = await identityTlsCertAuthDAL.transaction(async (tx) => { + await membershipIdentityDAL.update( + { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, + { lastLoginAuthMethod: IdentityAuthMethod.TLS_CERT_AUTH, lastLoginTime: new Date() }, + tx + ); + const newToken = await identityAccessTokenDAL.create( + { + identityId: identityTlsCertAuth.identityId, + isAccessTokenRevoked: false, + accessTokenTTL: identityTlsCertAuth.accessTokenTTL, + accessTokenMaxTTL: identityTlsCertAuth.accessTokenMaxTTL, + accessTokenNumUses: 0, + accessTokenNumUsesLimit: identityTlsCertAuth.accessTokenNumUsesLimit, + authMethod: IdentityAuthMethod.TLS_CERT_AUTH + }, + tx + ); + return newToken; + }); + + const accessToken = crypto.jwt().sign( { identityId: identityTlsCertAuth.identityId, - isAccessTokenRevoked: false, - accessTokenTTL: identityTlsCertAuth.accessTokenTTL, - accessTokenMaxTTL: identityTlsCertAuth.accessTokenMaxTTL, - accessTokenNumUses: 0, - accessTokenNumUsesLimit: identityTlsCertAuth.accessTokenNumUsesLimit, - authMethod: IdentityAuthMethod.TLS_CERT_AUTH - }, - tx + identityAccessTokenId: identityAccessToken.id, + authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN + } as TIdentityAccessTokenJwtPayload, + appCfg.AUTH_SECRET, + Number(identityAccessToken.accessTokenTTL) === 0 + ? undefined + : { + expiresIn: Number(identityAccessToken.accessTokenTTL) + } ); - return newToken; - }); - const appCfg = getConfig(); - const accessToken = crypto.jwt().sign( - { - identityId: identityTlsCertAuth.identityId, - identityAccessTokenId: identityAccessToken.id, - authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN - } as TIdentityAccessTokenJwtPayload, - appCfg.AUTH_SECRET, - Number(identityAccessToken.accessTokenTTL) === 0 - ? undefined - : { - expiresIn: Number(identityAccessToken.accessTokenTTL) - } - ); + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityTlsCertAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.TLS_CERT_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } - return { - identityTlsCertAuth, - accessToken, - identityAccessToken, - identity - }; + return { + identityTlsCertAuth, + accessToken, + identityAccessToken, + identity + }; + } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityTlsCertAuth.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.TLS_CERT_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + throw error; + } }; const attachTlsCertAuth: TIdentityTlsCertAuthServiceFactory["attachTlsCertAuth"] = async ({ diff --git a/backend/src/services/identity-ua/identity-ua-service.ts b/backend/src/services/identity-ua/identity-ua-service.ts index 00ab1610d..26bd01627 100644 --- a/backend/src/services/identity-ua/identity-ua-service.ts +++ b/backend/src/services/identity-ua/identity-ua-service.ts @@ -1,4 +1,5 @@ import { ForbiddenError } from "@casl/ability"; +import { requestContext } from "@fastify/request-context"; import { AccessScope, IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas"; import { TLicenseServiceFactory } from "@app/ee/services/license/license-service"; @@ -21,6 +22,7 @@ import { } from "@app/lib/errors"; import { checkIPAgainstBlocklist, extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip"; import { logger } from "@app/lib/logger"; +import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics"; import { ActorType, AuthTokenType } from "../auth/auth-type"; import { TIdentityDALFactory } from "../identity/identity-dal"; @@ -77,6 +79,7 @@ export const identityUaServiceFactory = ({ identityDAL }: TIdentityUaServiceFactoryDep) => { const login = async (clientId: string, clientSecret: string, ip: string) => { + const appCfg = getConfig(); const identityUa = await identityUaDAL.findOne({ clientId }); if (!identityUa) { throw new UnauthorizedError({ @@ -84,196 +87,226 @@ export const identityUaServiceFactory = ({ }); } - checkIPAgainstBlocklist({ - ipAddress: ip, - trustedIps: identityUa.clientSecretTrustedIps as TIp[] - }); + const identity = await identityDAL.findById(identityUa.identityId); + const org = await orgDAL.findById(identity.orgId); - const LOCKOUT_KEY = `lockout:identity:${identityUa.identityId}:${IdentityAuthMethod.UNIVERSAL_AUTH}:${clientId}`; - - const lockoutRaw = await keyStore.getItem(LOCKOUT_KEY); - - let lockout: LockoutObject | undefined; - if (lockoutRaw) { - lockout = JSON.parse(lockoutRaw) as LockoutObject; - } - - if (lockout && lockout.lockedOut) { - throw new UnauthorizedError({ - message: "This identity auth method is temporarily locked, please try again later" + try { + checkIPAgainstBlocklist({ + ipAddress: ip, + trustedIps: identityUa.clientSecretTrustedIps as TIp[] }); - } - const clientSecretPrefix = clientSecret.slice(0, 4); - const clientSecretInfo = await identityUaClientSecretDAL.find({ - identityUAId: identityUa.id, - isClientSecretRevoked: false, - clientSecretPrefix - }); + const LOCKOUT_KEY = `lockout:identity:${identityUa.identityId}:${IdentityAuthMethod.UNIVERSAL_AUTH}:${clientId}`; - let validClientSecretInfo: (typeof clientSecretInfo)[0] | null = null; - for await (const info of clientSecretInfo) { - const isMatch = await crypto.hashing().compareHash(clientSecret, info.clientSecretHash); + const lockoutRaw = await keyStore.getItem(LOCKOUT_KEY); - if (isMatch) { - validClientSecretInfo = info; - break; + let lockout: LockoutObject | undefined; + if (lockoutRaw) { + lockout = JSON.parse(lockoutRaw) as LockoutObject; } - } - if (!validClientSecretInfo) { - if (identityUa.lockoutEnabled) { - let lock: Awaited> | undefined; - try { - lock = await keyStore.acquireLock([KeyStorePrefixes.IdentityLockoutLock(LOCKOUT_KEY)], 300, { - retryCount: 3, - retryDelay: 300, - retryJitter: 100 - }); + if (lockout && lockout.lockedOut) { + throw new UnauthorizedError({ + message: "This identity auth method is temporarily locked, please try again later" + }); + } - // Re-fetch the latest lockout data while holding the lock - const lockoutRawNew = await keyStore.getItem(LOCKOUT_KEY); - if (lockoutRawNew) { - lockout = JSON.parse(lockoutRawNew) as LockoutObject; - } else { - lockout = { - lockedOut: false, - failedAttempts: 0 - }; - } + const clientSecretPrefix = clientSecret.slice(0, 4); + const clientSecretInfo = await identityUaClientSecretDAL.find({ + identityUAId: identityUa.id, + isClientSecretRevoked: false, + clientSecretPrefix + }); - if (lockout.lockedOut) { - throw new UnauthorizedError({ - message: "This identity auth method is temporarily locked, please try again later" - }); - } + let validClientSecretInfo: (typeof clientSecretInfo)[0] | null = null; + for await (const info of clientSecretInfo) { + const isMatch = await crypto.hashing().compareHash(clientSecret, info.clientSecretHash); - lockout.failedAttempts += 1; - if (lockout.failedAttempts >= identityUa.lockoutThreshold) { - lockout.lockedOut = true; - } - - await keyStore.setItemWithExpiry( - LOCKOUT_KEY, - lockout.lockedOut ? identityUa.lockoutDurationSeconds : identityUa.lockoutCounterResetSeconds, - JSON.stringify(lockout) - ); - } catch (e) { - if (lock === undefined) { - logger.info( - `identity login failed to acquire lock [identityId=${identityUa.identityId}] [authMethod=${IdentityAuthMethod.UNIVERSAL_AUTH}]` - ); - throw new RateLimitError({ message: "Failed to acquire lock: rate limit exceeded" }); - } - throw e; - } finally { - if (lock) { - await lock.release(); - } + if (isMatch) { + validClientSecretInfo = info; + break; } } - throw new UnauthorizedError({ message: "Invalid credentials" }); - } else if (lockout) { - // If credentials are valid, clear any existing lockout record - await keyStore.deleteItem(LOCKOUT_KEY); - } + if (!validClientSecretInfo) { + if (identityUa.lockoutEnabled) { + let lock: Awaited> | undefined; + try { + lock = await keyStore.acquireLock([KeyStorePrefixes.IdentityLockoutLock(LOCKOUT_KEY)], 300, { + retryCount: 3, + retryDelay: 300, + retryJitter: 100 + }); - const { clientSecretTTL, clientSecretNumUses, clientSecretNumUsesLimit } = validClientSecretInfo; - if (Number(clientSecretTTL) > 0) { - const clientSecretCreated = new Date(validClientSecretInfo.createdAt); - const ttlInMilliseconds = Number(clientSecretTTL) * 1000; - const currentDate = new Date(); - const expirationTime = new Date(clientSecretCreated.getTime() + ttlInMilliseconds); + // Re-fetch the latest lockout data while holding the lock + const lockoutRawNew = await keyStore.getItem(LOCKOUT_KEY); + if (lockoutRawNew) { + lockout = JSON.parse(lockoutRawNew) as LockoutObject; + } else { + lockout = { + lockedOut: false, + failedAttempts: 0 + }; + } - if (currentDate > expirationTime) { + if (lockout.lockedOut) { + throw new UnauthorizedError({ + message: "This identity auth method is temporarily locked, please try again later" + }); + } + + lockout.failedAttempts += 1; + if (lockout.failedAttempts >= identityUa.lockoutThreshold) { + lockout.lockedOut = true; + } + + await keyStore.setItemWithExpiry( + LOCKOUT_KEY, + lockout.lockedOut ? identityUa.lockoutDurationSeconds : identityUa.lockoutCounterResetSeconds, + JSON.stringify(lockout) + ); + } catch (e) { + if (lock === undefined) { + logger.info( + `identity login failed to acquire lock [identityId=${identityUa.identityId}] [authMethod=${IdentityAuthMethod.UNIVERSAL_AUTH}]` + ); + throw new RateLimitError({ message: "Failed to acquire lock: rate limit exceeded" }); + } + throw e; + } finally { + if (lock) { + await lock.release(); + } + } + } + + throw new UnauthorizedError({ message: "Invalid credentials" }); + } else if (lockout) { + // If credentials are valid, clear any existing lockout record + await keyStore.deleteItem(LOCKOUT_KEY); + } + + const { clientSecretTTL, clientSecretNumUses, clientSecretNumUsesLimit } = validClientSecretInfo; + if (Number(clientSecretTTL) > 0) { + const clientSecretCreated = new Date(validClientSecretInfo.createdAt); + const ttlInMilliseconds = Number(clientSecretTTL) * 1000; + const currentDate = new Date(); + const expirationTime = new Date(clientSecretCreated.getTime() + ttlInMilliseconds); + + if (currentDate > expirationTime) { + await identityUaClientSecretDAL.updateById(validClientSecretInfo.id, { + isClientSecretRevoked: true + }); + + throw new UnauthorizedError({ + message: "Access denied due to expired client secret" + }); + } + } + + if (clientSecretNumUsesLimit > 0 && clientSecretNumUses >= clientSecretNumUsesLimit) { + // number of times client secret can be used for + // a login operation reached await identityUaClientSecretDAL.updateById(validClientSecretInfo.id, { isClientSecretRevoked: true }); - throw new UnauthorizedError({ - message: "Access denied due to expired client secret" + message: "Access denied due to client secret usage limit reached" }); } - } - if (clientSecretNumUsesLimit > 0 && clientSecretNumUses >= clientSecretNumUsesLimit) { - // number of times client secret can be used for - // a login operation reached - await identityUaClientSecretDAL.updateById(validClientSecretInfo.id, { - isClientSecretRevoked: true + const accessTokenTTLParams = + Number(identityUa.accessTokenPeriod) === 0 + ? { + accessTokenTTL: identityUa.accessTokenTTL, + accessTokenMaxTTL: identityUa.accessTokenMaxTTL + } + : { + accessTokenTTL: identityUa.accessTokenPeriod, + // We set a very large Max TTL for periodic tokens to ensure that clients (even outdated ones) can always renew their token + // without them having to update their SDKs, CLIs, etc. This workaround sets it to 30 years to emulate "forever" + accessTokenMaxTTL: 1000000000 + }; + + const identityAccessToken = await identityUaDAL.transaction(async (tx) => { + const uaClientSecretDoc = await identityUaClientSecretDAL.incrementUsage(validClientSecretInfo!.id, tx); + await membershipIdentityDAL.update( + { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, + { + lastLoginAuthMethod: IdentityAuthMethod.UNIVERSAL_AUTH, + lastLoginTime: new Date() + }, + tx + ); + const newToken = await identityAccessTokenDAL.create( + { + identityId: identityUa.identityId, + isAccessTokenRevoked: false, + identityUAClientSecretId: uaClientSecretDoc.id, + accessTokenNumUses: 0, + accessTokenNumUsesLimit: identityUa.accessTokenNumUsesLimit, + accessTokenPeriod: identityUa.accessTokenPeriod, + authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, + ...accessTokenTTLParams + }, + tx + ); + + return newToken; }); - throw new UnauthorizedError({ - message: "Access denied due to client secret usage limit reached" - }); - } - const accessTokenTTLParams = - Number(identityUa.accessTokenPeriod) === 0 - ? { - accessTokenTTL: identityUa.accessTokenTTL, - accessTokenMaxTTL: identityUa.accessTokenMaxTTL - } - : { - accessTokenTTL: identityUa.accessTokenPeriod, - // We set a very large Max TTL for periodic tokens to ensure that clients (even outdated ones) can always renew their token - // without them having to update their SDKs, CLIs, etc. This workaround sets it to 30 years to emulate "forever" - accessTokenMaxTTL: 1000000000 - }; - - const identity = await identityDAL.findById(identityUa.identityId); - const identityAccessToken = await identityUaDAL.transaction(async (tx) => { - const uaClientSecretDoc = await identityUaClientSecretDAL.incrementUsage(validClientSecretInfo!.id, tx); - await membershipIdentityDAL.update( - { scope: AccessScope.Organization, scopeOrgId: identity.orgId, actorIdentityId: identity.id }, - { - lastLoginAuthMethod: IdentityAuthMethod.UNIVERSAL_AUTH, - lastLoginTime: new Date() - }, - tx - ); - const newToken = await identityAccessTokenDAL.create( + const accessToken = crypto.jwt().sign( { identityId: identityUa.identityId, - isAccessTokenRevoked: false, - identityUAClientSecretId: uaClientSecretDoc.id, - accessTokenNumUses: 0, - accessTokenNumUsesLimit: identityUa.accessTokenNumUsesLimit, - accessTokenPeriod: identityUa.accessTokenPeriod, - authMethod: IdentityAuthMethod.UNIVERSAL_AUTH, - ...accessTokenTTLParams - }, - tx + clientSecretId: validClientSecretInfo.id, + identityAccessTokenId: identityAccessToken.id, + authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN + } as TIdentityAccessTokenJwtPayload, + appCfg.AUTH_SECRET, + // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error + Number(identityAccessToken.accessTokenTTL) === 0 + ? undefined + : { + expiresIn: Number(identityAccessToken.accessTokenTTL) + } ); - return newToken; - }); + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityUa.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.UNIVERSAL_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } - const appCfg = getConfig(); - const accessToken = crypto.jwt().sign( - { - identityId: identityUa.identityId, - clientSecretId: validClientSecretInfo.id, - identityAccessTokenId: identityAccessToken.id, - authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN - } as TIdentityAccessTokenJwtPayload, - appCfg.AUTH_SECRET, - // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error - Number(identityAccessToken.accessTokenTTL) === 0 - ? undefined - : { - expiresIn: Number(identityAccessToken.accessTokenTTL) - } - ); - - return { - accessToken, - identityUa, - validClientSecretInfo, - identityAccessToken, - identity, - ...accessTokenTTLParams - }; + return { + accessToken, + identityUa, + validClientSecretInfo, + identityAccessToken, + identity, + ...accessTokenTTLParams + }; + } catch (error) { + if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) { + authAttemptCounter.add(1, { + "infisical.identity.id": identityUa.identityId, + "infisical.identity.name": identity.name, + "infisical.organization.id": org.id, + "infisical.organization.name": org.name, + "infisical.identity.auth_method": AuthAttemptAuthMethod.UNIVERSAL_AUTH, + "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE, + "client.address": requestContext.get("ip"), + "user_agent.original": requestContext.get("userAgent") + }); + } + throw error; + } }; const attachUniversalAuth = async ({ diff --git a/backend/src/services/integration-auth/integration-list.ts b/backend/src/services/integration-auth/integration-list.ts index 0608bbd4b..e4e1d3126 100644 --- a/backend/src/services/integration-auth/integration-list.ts +++ b/backend/src/services/integration-auth/integration-list.ts @@ -104,7 +104,8 @@ export enum IntegrationUrls { GCP_SERVICE_USAGE_URL = "https://serviceusage.googleapis.com", GCP_CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform", - GITHUB_USER_INSTALLATIONS = "https://api.github.com/user/installations" + GITHUB_USER_INSTALLATIONS = "https://api.github.com/user/installations", + CHEF_API_URL = "https://api.chef.io" } export const getIntegrationOptions = async () => { diff --git a/backend/src/services/kms/kms-key-dal.ts b/backend/src/services/kms/kms-key-dal.ts index a0dd12191..36ffa3366 100644 --- a/backend/src/services/kms/kms-key-dal.ts +++ b/backend/src/services/kms/kms-key-dal.ts @@ -112,7 +112,8 @@ export const kmskeyDALFactory = (db: TDbClient) => { ...KmsKeysSchema.parse(entry), isActive: !entry.isDisabled, algorithm: entry.internalKmsEncryptionAlgorithm, - version: entry.internalKmsVersion + version: entry.internalKmsVersion, + kmipMetadata: entry.kmipMetadata as Record })); } catch (error) { throw new DatabaseError({ error, name: "Find project cmeks" }); diff --git a/backend/src/services/kms/kms-service.ts b/backend/src/services/kms/kms-service.ts index b665df4ed..8f868978d 100644 --- a/backend/src/services/kms/kms-service.ts +++ b/backend/src/services/kms/kms-service.ts @@ -401,13 +401,6 @@ export const kmsServiceFactory = ({ const cipher = symmetricCipherService(SymmetricKeyAlgorithm.AES_GCM_256); - const expectedByteLength = getByteLengthForSymmetricEncryptionAlgorithm(algorithm as SymmetricKeyAlgorithm); - if (key.byteLength !== expectedByteLength) { - throw new BadRequestError({ - message: `Invalid key length for ${algorithm}. Expected ${expectedByteLength} bytes but got ${key.byteLength} bytes` - }); - } - const encryptedKeyMaterial = cipher.encrypt(key, ROOT_ENCRYPTION_KEY); const sanitizedName = name ? slugify(name) : slugify(alphaNumericNanoId(8).toLowerCase()); const dbQuery = async (db: Knex) => { diff --git a/backend/src/services/membership-group/membership-group-service.ts b/backend/src/services/membership-group/membership-group-service.ts index 18f6b3ad1..0aedccd15 100644 --- a/backend/src/services/membership-group/membership-group-service.ts +++ b/backend/src/services/membership-group/membership-group-service.ts @@ -1,5 +1,15 @@ -import { AccessScope, ProjectMembershipRole, TemporaryPermissionMode, TMembershipRolesInsert } from "@app/db/schemas"; +import { + AccessScope, + ProjectMembershipRole, + TableName, + TemporaryPermissionMode, + TMembershipRolesInsert +} from "@app/db/schemas"; +import { TAccessApprovalPolicyApproverDALFactory } from "@app/ee/services/access-approval-policy/access-approval-policy-approver-dal"; +import { TAccessApprovalPolicyDALFactory } from "@app/ee/services/access-approval-policy/access-approval-policy-dal"; import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types"; +import { TSecretApprovalPolicyApproverDALFactory } from "@app/ee/services/secret-approval-policy/secret-approval-policy-approver-dal"; +import { TSecretApprovalPolicyDALFactory } from "@app/ee/services/secret-approval-policy/secret-approval-policy-dal"; import { BadRequestError, NotFoundError } from "@app/lib/errors"; import { groupBy } from "@app/lib/fn"; import { ms } from "@app/lib/ms"; @@ -23,6 +33,10 @@ import { newProjectMembershipGroupFactory } from "./project/project-membership-g type TMembershipGroupServiceFactoryDep = { membershipGroupDAL: TMembershipGroupDALFactory; membershipRoleDAL: Pick; + accessApprovalPolicyDAL: Pick; + accessApprovalPolicyApproverDAL: Pick; + secretApprovalPolicyDAL: Pick; + secretApprovalPolicyApproverDAL: Pick; roleDAL: Pick; permissionService: TPermissionServiceFactory; orgDAL: TOrgDALFactory; @@ -33,6 +47,10 @@ export type TMembershipGroupServiceFactory = ReturnType policyId); + if (accessApprovalPolicyApprovers.length > 0) { + const accessApprovalPolicies = await accessApprovalPolicyDAL.find({ + $in: { + [`${TableName.AccessApprovalPolicy}.id` as "id"]: [...new Set(accessApprovalPolicyApproverGroupIds)] + }, + projectId: existingMembership.scopeProjectId ?? undefined, + deletedAt: null + }); + + if (accessApprovalPolicies.length > 0) { + throw new BadRequestError({ + message: "This group is assigned to an approval policy and cannot be deleted" + }); + } + } + + // check if group is assigned to any secret approval policy + const secretApprovalPolicyApprovers = await secretApprovalPolicyApproverDAL.find({ + approverGroupId: dto.selector.groupId + }); + const secretApprovalPolicyApproverGroupIds = secretApprovalPolicyApprovers.map(({ policyId }) => policyId); + if (secretApprovalPolicyApprovers.length > 0) { + const secretApprovalPolicies = await secretApprovalPolicyDAL.find({ + $in: { + [`${TableName.SecretApprovalPolicy}.id` as "id"]: [...new Set(secretApprovalPolicyApproverGroupIds)] + }, + projectId: existingMembership.scopeProjectId ?? undefined, + deletedAt: null + }); + if (secretApprovalPolicies.length > 0) { + throw new BadRequestError({ + message: "This group is assigned to a secret approval policy and cannot be deleted" + }); + } + } + const membershipDoc = await membershipGroupDAL.transaction(async (tx) => { await membershipRoleDAL.delete({ membershipId: existingMembership.id }, tx); const doc = await membershipGroupDAL.deleteById(existingMembership.id, tx); diff --git a/backend/src/services/org/org-schema.ts b/backend/src/services/org/org-schema.ts index 4a3bdb06e..be5c300b5 100644 --- a/backend/src/services/org/org-schema.ts +++ b/backend/src/services/org/org-schema.ts @@ -27,5 +27,6 @@ export const sanitizedOrganizationSchema = OrganizationsSchema.pick({ scannerProductEnabled: true, shareSecretsProductEnabled: true, maxSharedSecretLifetime: true, - maxSharedSecretViewLimit: true + maxSharedSecretViewLimit: true, + blockDuplicateSecretSyncDestinations: true }); diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts index 51d907e05..b0bbd9a2a 100644 --- a/backend/src/services/org/org-service.ts +++ b/backend/src/services/org/org-service.ts @@ -405,7 +405,8 @@ export const orgServiceFactory = ({ scannerProductEnabled, shareSecretsProductEnabled, maxSharedSecretLifetime, - maxSharedSecretViewLimit + maxSharedSecretViewLimit, + blockDuplicateSecretSyncDestinations } }: TUpdateOrgDTO) => { const appCfg = getConfig(); @@ -516,7 +517,7 @@ export const orgServiceFactory = ({ if (slug) { const existingOrg = await orgDAL.findOne({ slug, rootOrgId: null }); if (existingOrg && existingOrg?.id !== orgId) - throw new BadRequestError({ message: `Organization with slug ${slug} already exist` }); + throw new BadRequestError({ message: `Organization with slug ${slug} already exists` }); } if (googleSsoAuthEnforced) { @@ -589,7 +590,8 @@ export const orgServiceFactory = ({ scannerProductEnabled, shareSecretsProductEnabled, maxSharedSecretLifetime, - maxSharedSecretViewLimit + maxSharedSecretViewLimit, + blockDuplicateSecretSyncDestinations }); if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` }); return org; @@ -1147,7 +1149,7 @@ export const orgServiceFactory = ({ const doesIncidentContactExist = await incidentContactDAL.findOne(orgId, { email }); if (doesIncidentContactExist) { throw new BadRequestError({ - message: "Incident contact already exist", + message: "Incident contact already exists", name: "Incident contact exist" }); } diff --git a/backend/src/services/org/org-types.ts b/backend/src/services/org/org-types.ts index 48680456c..2587045bb 100644 --- a/backend/src/services/org/org-types.ts +++ b/backend/src/services/org/org-types.ts @@ -90,6 +90,7 @@ export type TUpdateOrgDTO = { shareSecretsProductEnabled: boolean; maxSharedSecretLifetime: number; maxSharedSecretViewLimit: number | null; + blockDuplicateSecretSyncDestinations: boolean; }>; } & TOrgPermission; diff --git a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-fns.ts b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-fns.ts index f78bd790e..3e07420b5 100644 --- a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-fns.ts +++ b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-fns.ts @@ -3,7 +3,9 @@ import * as AWS from "aws-sdk"; import RE2 from "re2"; import { z } from "zod"; +import { TCertificateSyncs } from "@app/db/schemas"; import { BadRequestError, NotFoundError } from "@app/lib/errors"; +import { logger } from "@app/lib/logger"; import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal"; import { AppConnection, AWSRegion } from "@app/services/app-connection/app-connection-enums"; import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns"; @@ -14,6 +16,9 @@ import { AwsConnectionAssumeRoleCredentialsSchema } from "@app/services/app-connection/aws/aws-connection-schemas"; import { TAwsConnectionConfig } from "@app/services/app-connection/aws/aws-connection-types"; +import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal"; +import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal"; +import { CertificateSyncStatus } from "@app/services/certificate-sync/certificate-sync-enums"; import { createConnectionQueue, RateLimitConfig } from "@app/services/connection-queue"; import { TKmsServiceFactory } from "@app/services/kms/kms-service"; import { TCertificateMap } from "@app/services/pki-sync/pki-sync-types"; @@ -88,39 +93,6 @@ const shouldSkipCertificateExport = (certificate: AWS.ACM.CertificateSummary): b return isAwsIssuedCertificate(certificate); }; -const findTagByKey = (tags: AWS.ACM.TagList | undefined, key: string): AWS.ACM.Tag | undefined => { - if (!tags || !Array.isArray(tags)) { - return undefined; - } - return tags.find((tag: AWS.ACM.Tag) => tag.Key === key && tag.Value); -}; - -const findInfisicalCertificateTag = (tags: AWS.ACM.TagList | undefined): AWS.ACM.Tag | undefined => { - return findTagByKey(tags, INFISICAL_CERTIFICATE_TAG); -}; - -const validateCertificateIdentification = ( - certName: string, - existingCert: { arn?: string; Tags?: AWS.ACM.TagList; cert?: string; privateKey?: string; certificateChain?: string } -): boolean => { - if (!existingCert?.arn || !existingCert?.Tags) { - return false; - } - - const certNameTag = findInfisicalCertificateTag(existingCert.Tags); - - if (!certNameTag || !certNameTag.Value) { - return false; - } - - return certNameTag.Value === certName; -}; - -type TAwsCertificateManagerPkiSyncFactoryDeps = { - appConnectionDAL: Pick; - kmsService: Pick; -}; - const validateCertificateNameSchema = (schema: string): void => { if (!schema.includes("{{certificateId}}")) { throw new Error( @@ -174,6 +146,21 @@ const generateCertificateName = (certificateName: string, pkiSync: TPkiSyncWithC return sanitizedCertificateName; }; +type TAwsCertificateManagerPkiSyncFactoryDeps = { + appConnectionDAL: Pick; + kmsService: Pick; + certificateSyncDAL: Pick< + TCertificateSyncDALFactory, + | "removeCertificates" + | "addCertificates" + | "findByPkiSyncAndCertificate" + | "updateSyncStatus" + | "updateById" + | "findByPkiSyncId" + >; + certificateDAL: Pick; +}; + const getAwsAcmClient = async ( connectionId: string, region: AWSRegion, @@ -230,7 +217,9 @@ const getAwsAcmClient = async ( export const awsCertificateManagerPkiSyncFactory = ({ kmsService, - appConnectionDAL + appConnectionDAL, + certificateSyncDAL, + certificateDAL }: TAwsCertificateManagerPkiSyncFactoryDeps) => { const deleteCertificateFromAcm = async ( acm: AWS.ACM, @@ -392,79 +381,201 @@ export const awsCertificateManagerPkiSyncFactory = ({ kmsService ); - const { acmCertificates } = await $getAwsAcmCertificates(acm, pkiSync.id); + const { + acmCertificates + }: { + acmCertificates: Record< + string, + { cert: string; privateKey: string; certificateChain?: string; arn?: string; Tags?: AWS.ACM.TagList } + >; + } = await $getAwsAcmCertificates(acm, pkiSync.id); + + const acmCertificatesByArn = new Map(); + Object.values(acmCertificates).forEach((acmCert) => { + if (acmCert.arn) { + acmCertificatesByArn.set(acmCert.arn, acmCert); + } + }); + + const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id); + const syncRecordsByCertId = new Map(); + const syncRecordsByExternalId = new Map(); + + existingSyncRecords.forEach((record: TCertificateSyncs) => { + if (record.certificateId) { + syncRecordsByCertId.set(record.certificateId, record); + } + if (record.externalIdentifier) { + syncRecordsByExternalId.set(record.externalIdentifier, record); + } + }); const setCertificates: CertificateImportRequest[] = []; + const validationErrors: Array<{ name: string; error: string }> = []; - const activeCertificateNames = Object.keys(certificateMap); + const syncOptions = pkiSync.syncOptions as { preserveArn?: boolean; canRemoveCertificates?: boolean } | undefined; + const preserveArn = syncOptions?.preserveArn ?? true; + const canRemoveCertificates = syncOptions?.canRemoveCertificates ?? true; - Object.entries(certificateMap).forEach(([certName, certData]) => { - const { cert, privateKey, certificateChain } = certData; - const certificateName = generateCertificateName(certName, pkiSync); + const activeExternalIdentifiers = new Set(); - const existingCert = Object.values(acmCertificates).find((acmCert) => - validateCertificateIdentification(certName, acmCert) - ); - - const shouldUpdateCert = !existingCert || existingCert.cert !== cert; + for (const [certName, certData] of Object.entries(certificateMap)) { + const { cert, privateKey, certificateChain, certificateId } = certData; try { validateCertificateContent(cert, privateKey); } catch (validationError) { - throw new PkiSyncError({ - message: `Certificate validation failed for ${certName}: ${validationError instanceof Error ? validationError.message : String(validationError)}`, - shouldRetry: false, - context: { - certificateName, - certName - } + const errorMessage = validationError instanceof Error ? validationError.message : String(validationError); + validationErrors.push({ + name: certName, + error: `Certificate validation failed: ${errorMessage}` }); + // eslint-disable-next-line no-continue + continue; } - if (shouldUpdateCert) { + if (preserveArn && certificateId && typeof certificateId === "string") { + const certificate = await certificateDAL.findById(certificateId); + if (certificate?.renewedByCertificateId) { + // eslint-disable-next-line no-continue + continue; + } + } + + const certificateName = generateCertificateName(certName, pkiSync); + + let targetArn: string | undefined; + let shouldCreateNew = false; + + if (!certificateId || typeof certificateId !== "string") { + shouldCreateNew = true; + } else { + const currentCertificate = await certificateDAL.findById(certificateId); + const isRenewal = !!currentCertificate?.renewedFromCertificateId; + + if (isRenewal) { + const currentSyncRecord = syncRecordsByCertId.get(certificateId); + const oldCertificateId = currentCertificate.renewedFromCertificateId; + const oldSyncRecord = oldCertificateId ? syncRecordsByCertId.get(oldCertificateId) : undefined; + + if (currentSyncRecord?.externalIdentifier) { + const existingAcmCert = acmCertificatesByArn.get(currentSyncRecord.externalIdentifier); + + if (existingAcmCert) { + if (!preserveArn && oldSyncRecord?.externalIdentifier === currentSyncRecord.externalIdentifier) { + shouldCreateNew = true; + } else if (preserveArn && oldSyncRecord?.externalIdentifier === currentSyncRecord.externalIdentifier) { + targetArn = currentSyncRecord.externalIdentifier; + shouldCreateNew = true; + activeExternalIdentifiers.add(targetArn); + + if (oldCertificateId && oldSyncRecord) { + await certificateSyncDAL.removeCertificates(pkiSync.id, [oldCertificateId]); + } + } else { + targetArn = currentSyncRecord.externalIdentifier; + activeExternalIdentifiers.add(targetArn); + shouldCreateNew = false; + } + } else { + shouldCreateNew = true; + } + } else if (preserveArn && oldSyncRecord?.externalIdentifier) { + const existingAcmCert = acmCertificatesByArn.get(oldSyncRecord.externalIdentifier); + + if (existingAcmCert) { + targetArn = oldSyncRecord.externalIdentifier; + shouldCreateNew = true; + activeExternalIdentifiers.add(targetArn); + if (oldCertificateId) { + await certificateSyncDAL.removeCertificates(pkiSync.id, [oldCertificateId]); + } + } else { + shouldCreateNew = true; + } + } else { + shouldCreateNew = true; + } + } else { + const existingSyncRecord = syncRecordsByCertId.get(certificateId); + if (existingSyncRecord?.externalIdentifier) { + const existingAcmCert = acmCertificatesByArn.get(existingSyncRecord.externalIdentifier); + if (existingAcmCert) { + targetArn = existingSyncRecord.externalIdentifier; + activeExternalIdentifiers.add(targetArn); + shouldCreateNew = false; + } else { + shouldCreateNew = true; + } + } else { + shouldCreateNew = true; + } + } + } + + if (shouldCreateNew) { setCertificates.push({ key: certName, name: certificateName, cert, privateKey, certificateChain, - existingArn: existingCert?.arn + existingArn: targetArn, + certificateId: certificateId as string }); } - }); - // Identify expired/removed certificates that need to be cleaned up from ACM - const certificatesToRemove = Object.values(acmCertificates) - .filter((acmCert) => { - if (!acmCert.arn || !acmCert.Tags) { - return false; + if (targetArn) { + activeExternalIdentifiers.add(targetArn); + } + } + + const certificatesToRemove: string[] = []; + + if (canRemoveCertificates) { + existingSyncRecords.forEach((syncRecord) => { + if (syncRecord.externalIdentifier && !activeExternalIdentifiers.has(syncRecord.externalIdentifier)) { + const acmCert = acmCertificatesByArn.get(syncRecord.externalIdentifier); + if (acmCert?.arn) { + certificatesToRemove.push(acmCert.arn); + } } + }); - const certNameTag = findInfisicalCertificateTag(acmCert.Tags); - if (!certNameTag || !certNameTag.Value) { - return false; + Object.values(acmCertificates).forEach((acmCert) => { + if (acmCert.arn && acmCert.Tags) { + const hasInfisicalTag = acmCert.Tags.some((tag) => tag.Key === INFISICAL_CERTIFICATE_TAG && tag.Value); + + if (hasInfisicalTag) { + const isTrackedInSyncRecords = existingSyncRecords.some( + (record) => record.externalIdentifier === acmCert.arn + ); + const isInActiveSet = activeExternalIdentifiers.has(acmCert.arn); + if (!isTrackedInSyncRecords && !isInActiveSet && !certificatesToRemove.includes(acmCert.arn)) { + certificatesToRemove.push(acmCert.arn); + } + } } - - const isActive = activeCertificateNames.includes(certNameTag.Value); - return !isActive; - }) - .map((acmCert) => acmCert.arn!) - .filter((arn) => arn); + }); + } const uploadResults = await executeWithConcurrencyLimit( setCertificates, - async ({ key, name, cert, privateKey, certificateChain, existingArn }) => { + async ({ key, name, cert, privateKey, certificateChain, existingArn, certificateId }) => { try { const importParams: AWS.ACM.ImportCertificateRequest = { Certificate: cert, - PrivateKey: privateKey, - Tags: [ + PrivateKey: privateKey + }; + + if (!existingArn) { + importParams.Tags = [ { Key: INFISICAL_CERTIFICATE_TAG, Value: key } - ] - }; + ]; + } if (certificateChain && certificateChain.trim().length > 0) { importParams.CertificateChain = certificateChain; @@ -478,6 +589,57 @@ export const awsCertificateManagerPkiSyncFactory = ({ syncId: pkiSync.id }); + if (existingArn && response.CertificateArn) { + try { + // Small delay to ensure AWS ACM has processed the certificate import + await new Promise((resolve) => { + setTimeout(() => resolve(), 500); + }); + + await withRateLimitRetry( + () => + acm + .addTagsToCertificate({ + CertificateArn: response.CertificateArn!, + Tags: [ + { + Key: INFISICAL_CERTIFICATE_TAG, + Value: key + } + ] + }) + .promise(), + { + operation: "add-tags-to-certificate", + syncId: pkiSync.id + } + ); + } catch (tagError) { + const errorMessage = tagError instanceof Error ? tagError.message : "Unknown tagging error"; + logger.warn( + `Failed to add tags to certificate ${key} (ARN: ${response.CertificateArn}): ${errorMessage}` + ); + } + } + + if (response.CertificateArn && certificateId) { + const existingCertSync = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId); + if (existingCertSync) { + await certificateSyncDAL.updateById(existingCertSync.id, { + externalIdentifier: response.CertificateArn, + syncStatus: CertificateSyncStatus.Succeeded, + lastSyncedAt: new Date() + }); + } else { + await certificateSyncDAL.addCertificates(pkiSync.id, [ + { + certificateId, + externalIdentifier: response.CertificateArn + } + ]); + } + } + return { key, name, success: true, response }; } catch (error) { const errorMessage = error instanceof Error ? error.message : "Unknown error"; @@ -520,15 +682,21 @@ export const awsCertificateManagerPkiSyncFactory = ({ const details: { failedUploads?: Array<{ name: string; error: string }>; failedRemovals?: Array<{ name: string; error: string }>; + validationErrors?: Array<{ name: string; error: string }>; } = {}; + if (validationErrors.length > 0) { + details.validationErrors = validationErrors; + } + if (failedUploads.length > 0) { details.failedUploads = failedUploads.map((failure, index) => { - const certificateName = setCertificates[index]?.name || "unknown"; + const certificateRequest = setCertificates[index]; + const certificateName = certificateRequest?.name || certificateRequest?.key || "unknown"; let errorMessage = "Unknown error"; if (failure.status === "rejected") { - errorMessage = failure.reason instanceof Error ? failure.reason.message : "Unknown error"; + errorMessage = failure.reason instanceof Error ? failure.reason.message : String(failure.reason); } return { @@ -567,7 +735,8 @@ export const awsCertificateManagerPkiSyncFactory = ({ const removeCertificates = async ( pkiSync: TPkiSyncWithCredentials, - certificateNames: string[] + certificateNames: string[], + deps?: { certificateSyncDAL?: TCertificateSyncDALFactory; certificateMap?: TCertificateMap } ): Promise => { const destinationConfig = pkiSync.destinationConfig as TAwsCertificateManagerPkiSyncConfig; const acm = await getAwsAcmClient( @@ -577,22 +746,33 @@ export const awsCertificateManagerPkiSyncFactory = ({ kmsService ); - const { acmCertificates } = await $getAwsAcmCertificates(acm, pkiSync.id); - + const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id); const certificateArnsToRemove: string[] = []; - + const certificateIdToArnMap = new Map(); for (const certName of certificateNames) { - const matchingCerts = Object.values(acmCertificates).filter((acmCert) => - validateCertificateIdentification(certName, acmCert) - ); + const certificateData = deps?.certificateMap?.[certName]; + if (certificateData?.certificateId) { + const { certificateId } = certificateData; - for (const acmCert of matchingCerts) { - if (acmCert.arn) { - certificateArnsToRemove.push(acmCert.arn); + if (typeof certificateId === "string") { + const syncRecord = existingSyncRecords.find((record) => record.certificateId === certificateId); + + if (syncRecord?.externalIdentifier) { + certificateArnsToRemove.push(syncRecord.externalIdentifier); + certificateIdToArnMap.set(certificateId, syncRecord.externalIdentifier); + } } } } + if (certificateArnsToRemove.length === 0) { + return { + removed: 0, + failed: 0, + skipped: certificateNames.length + }; + } + const results = await executeWithConcurrencyLimit( certificateArnsToRemove, async (certificateArn) => @@ -602,6 +782,38 @@ export const awsCertificateManagerPkiSyncFactory = ({ const failedRemovals = results.filter((result) => result.status === "rejected"); + if (failedRemovals.length > 0 && deps?.certificateSyncDAL) { + for (const failure of failedRemovals) { + if (failure.status === "rejected") { + const failedArn = certificateArnsToRemove[results.indexOf(failure)]; + const certificateId = Array.from(certificateIdToArnMap.entries()).find(([, arn]) => arn === failedArn)?.[0]; + + if (certificateId) { + const errorMessage = failure.reason instanceof Error ? failure.reason.message : "Unknown error"; + await deps.certificateSyncDAL.updateSyncStatus( + pkiSync.id, + certificateId, + CertificateSyncStatus.Failed, + `Failed to remove from AWS: ${errorMessage}` + ); + } + } + } + } + + const successfulRemovals = results.filter((result) => result.status === "fulfilled"); + if (successfulRemovals.length > 0) { + const successfulArns = new Set(successfulRemovals.map((_, index) => certificateArnsToRemove[index])); + + const certificateIdsToRemove = Array.from(certificateIdToArnMap.entries()) + .filter(([, arn]) => successfulArns.has(arn)) + .map(([certificateId]) => certificateId); + + if (certificateIdsToRemove.length > 0) { + await certificateSyncDAL.removeCertificates(pkiSync.id, certificateIdsToRemove); + } + } + if (failedRemovals.length > 0) { const failedReasons = failedRemovals.map((failure) => { if (failure.status === "rejected") { diff --git a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts index eb9ae5444..3b9f5c881 100644 --- a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts +++ b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-schemas.ts @@ -14,6 +14,7 @@ export const AwsCertificateManagerPkiSyncConfigSchema = z.object({ const AwsCertificateManagerPkiSyncOptionsSchema = z.object({ canImportCertificates: z.boolean().default(false), canRemoveCertificates: z.boolean().default(true), + preserveArn: z.boolean().default(true), certificateNameSchema: z .string() .optional() @@ -28,6 +29,9 @@ const AwsCertificateManagerPkiSyncOptionsSchema = z.object({ const testName = schema .replace(new RE2("\\{\\{certificateId\\}\\}", "g"), "test-cert-id") + .replace(new RE2("\\{\\{profileId\\}\\}", "g"), "test-profile-id") + .replace(new RE2("\\{\\{commonName\\}\\}", "g"), "test-common-name") + .replace(new RE2("\\{\\{friendlyName\\}\\}", "g"), "test-friendly-name") .replace(new RE2("\\{\\{environment\\}\\}", "g"), "test-env"); const hasForbiddenChars = AWS_CERTIFICATE_MANAGER_CERTIFICATE_NAMING.FORBIDDEN_CHARACTERS.split("").some( @@ -43,7 +47,7 @@ const AwsCertificateManagerPkiSyncOptionsSchema = z.object({ }, { message: - "Certificate name schema must include {{certificateId}} placeholder and result in names that contain only alphanumeric characters, spaces, hyphens, and underscores and be 1-256 characters long when compiled for AWS Certificate Manager" + "Certificate name schema must include {{certificateId}} placeholder and result in names that contain only alphanumeric characters, spaces, hyphens, and underscores and be 1-256 characters long when compiled for AWS Certificate Manager. Available placeholders: {{certificateId}}, {{profileId}}, {{commonName}}, {{friendlyName}}, {{environment}}" } ) }); @@ -60,9 +64,10 @@ export const CreateAwsCertificateManagerPkiSyncSchema = z.object({ isAutoSyncEnabled: z.boolean().default(true), destinationConfig: AwsCertificateManagerPkiSyncConfigSchema, syncOptions: AwsCertificateManagerPkiSyncOptionsSchema.optional().default({}), - subscriberId: z.string().optional(), + subscriberId: z.string().nullish(), connectionId: z.string(), - projectId: z.string().trim().min(1) + projectId: z.string().trim().min(1), + certificateIds: z.array(z.string().uuid()).optional() }); export const UpdateAwsCertificateManagerPkiSyncSchema = z.object({ @@ -71,7 +76,7 @@ export const UpdateAwsCertificateManagerPkiSyncSchema = z.object({ isAutoSyncEnabled: z.boolean().optional(), destinationConfig: AwsCertificateManagerPkiSyncConfigSchema.optional(), syncOptions: AwsCertificateManagerPkiSyncOptionsSchema.optional(), - subscriberId: z.string().optional(), + subscriberId: z.string().nullish(), connectionId: z.string().optional() }); diff --git a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-types.ts b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-types.ts index 717e86438..8b2b8b87e 100644 --- a/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-types.ts +++ b/backend/src/services/pki-sync/aws-certificate-manager/aws-certificate-manager-pki-sync-types.ts @@ -39,6 +39,7 @@ export interface SyncCertificatesResult { details?: { failedUploads?: Array<{ name: string; error: string }>; failedRemovals?: Array<{ name: string; error: string }>; + validationErrors?: Array<{ name: string; error: string }>; }; } @@ -55,4 +56,5 @@ export interface CertificateImportRequest { privateKey: string; certificateChain?: string; existingArn?: string; + certificateId?: string; } diff --git a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-fns.ts b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-fns.ts index b423f42db..765d0b8ba 100644 --- a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-fns.ts +++ b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-fns.ts @@ -2,10 +2,14 @@ import { AxiosError } from "axios"; import * as crypto from "crypto"; +import { TCertificateSyncs } from "@app/db/schemas"; import { request } from "@app/lib/config/request"; import { logger } from "@app/lib/logger"; import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal"; import { getAzureConnectionAccessToken } from "@app/services/app-connection/azure-key-vault"; +import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal"; +import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal"; +import { CertificateSyncStatus } from "@app/services/certificate-sync/certificate-sync-enums"; import { createConnectionQueue, RateLimitConfig } from "@app/services/connection-queue"; import { TKmsServiceFactory } from "@app/services/kms/kms-service"; import { matchesCertificateNameSchema } from "@app/services/pki-sync/pki-sync-fns"; @@ -32,7 +36,9 @@ const extractCertificateNameFromId = (certificateId: string): string => { }; const isInfisicalManagedCertificate = (certificateName: string, pkiSync: TPkiSyncWithCredentials): boolean => { - const syncOptions = pkiSync.syncOptions as { certificateNameSchema?: string } | undefined; + const syncOptions = pkiSync.syncOptions as + | { certificateNameSchema?: string; canRemoveCertificates?: boolean } + | undefined; const certificateNameSchema = syncOptions?.certificateNameSchema; if (certificateNameSchema) { @@ -46,6 +52,16 @@ const isInfisicalManagedCertificate = (certificateName: string, pkiSync: TPkiSyn type TAzureKeyVaultPkiSyncFactoryDeps = { appConnectionDAL: Pick; kmsService: Pick; + certificateSyncDAL: Pick< + TCertificateSyncDALFactory, + | "removeCertificates" + | "addCertificates" + | "findByPkiSyncAndCertificate" + | "updateById" + | "findByPkiSyncId" + | "updateSyncStatus" + >; + certificateDAL: Pick; }; const parseCertificateX509Props = (certPem: string) => { @@ -188,7 +204,12 @@ const parseCertificateKeyProps = (certPem: string) => { } }; -export const azureKeyVaultPkiSyncFactory = ({ kmsService, appConnectionDAL }: TAzureKeyVaultPkiSyncFactoryDeps) => { +export const azureKeyVaultPkiSyncFactory = ({ + kmsService, + appConnectionDAL, + certificateSyncDAL, + certificateDAL +}: TAzureKeyVaultPkiSyncFactoryDeps) => { const $getAzureKeyVaultCertificates = async (accessToken: string, vaultBaseUrl: string, syncId = "unknown") => { const paginateAzureKeyVaultCertificates = async () => { let result: GetAzureKeyVaultCertificate[] = []; @@ -325,48 +346,126 @@ export const azureKeyVaultPkiSyncFactory = ({ kmsService, appConnectionDAL }: TA pkiSync.id ); + const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id); + const syncRecordsByCertId = new Map(); + const syncRecordsByExternalId = new Map(); + + existingSyncRecords.forEach((record: TCertificateSyncs) => { + if (record.certificateId) { + syncRecordsByCertId.set(record.certificateId, record); + } + if (record.externalIdentifier) { + syncRecordsByExternalId.set(record.externalIdentifier, record); + } + }); + const setCertificates: { key: string; cert: string; privateKey: string; certificateChain?: string; + certificateId?: string; }[] = []; - // Track which certificates should exist in Azure Key Vault - const activeCertificateNames = Object.keys(certificateMap); + const syncOptions = pkiSync.syncOptions as + | { certificateNameSchema?: string; canRemoveCertificates?: boolean; enableVersioning?: boolean } + | undefined; + const canRemoveCertificates = syncOptions?.canRemoveCertificates ?? true; + const enableVersioning = syncOptions?.enableVersioning ?? true; + + const activeExternalIdentifiers = new Set(); // Iterate through certificates to sync to Azure Key Vault - Object.entries(certificateMap).forEach(([certName, { cert, privateKey, certificateChain }]) => { + for (const [certName, { cert, privateKey, certificateChain, certificateId }] of Object.entries(certificateMap)) { if (disabledAzureKeyVaultCertificateKeys.includes(certName)) { - return; + // eslint-disable-next-line no-continue + continue; } - const existingCert = vaultCertificates[certName]; - const shouldUpdateCert = !existingCert || existingCert.cert !== cert; + if (enableVersioning && typeof certificateId === "string") { + const certificate = await certificateDAL.findById(certificateId); + if (certificate?.renewedByCertificateId) { + // eslint-disable-next-line no-continue + continue; + } + } - if (shouldUpdateCert) { + let targetCertName = certName; + let shouldCreateNew = false; + + if (typeof certificateId === "string") { + const existingSyncRecord = syncRecordsByCertId.get(certificateId); + + if (existingSyncRecord?.externalIdentifier) { + const existingAzureCert = vaultCertificates[existingSyncRecord.externalIdentifier]; + + if (existingAzureCert && enableVersioning) { + targetCertName = existingSyncRecord.externalIdentifier; + activeExternalIdentifiers.add(targetCertName); + + const shouldUpdateCert = existingAzureCert.cert !== cert; + if (shouldUpdateCert) { + shouldCreateNew = true; + } + } else if (!existingAzureCert) { + shouldCreateNew = true; + } else if (!enableVersioning) { + shouldCreateNew = true; + } + } else { + shouldCreateNew = true; + } + } else { + shouldCreateNew = true; + } + + if (shouldCreateNew || !vaultCertificates[targetCertName] || vaultCertificates[targetCertName].cert !== cert) { setCertificates.push({ - key: certName, + key: targetCertName, cert, privateKey, - certificateChain + certificateChain, + certificateId }); } - }); - // Identify expired/removed certificates that need to be cleaned up from Azure Key Vault - // Only remove certificates that were managed by Infisical (match naming schema) - const certificatesToRemove = Object.keys(vaultCertificates).filter( - (vaultCertName) => - isInfisicalManagedCertificate(vaultCertName, pkiSync) && - !activeCertificateNames.includes(vaultCertName) && - !disabledAzureKeyVaultCertificateKeys.includes(vaultCertName) - ); + if (targetCertName) { + activeExternalIdentifiers.add(targetCertName); + } + } + + const certificatesToRemove: string[] = []; + + if (canRemoveCertificates) { + existingSyncRecords.forEach((syncRecord) => { + if (syncRecord.externalIdentifier && !activeExternalIdentifiers.has(syncRecord.externalIdentifier)) { + if (vaultCertificates[syncRecord.externalIdentifier]) { + certificatesToRemove.push(syncRecord.externalIdentifier); + } + } + }); + + Object.keys(vaultCertificates).forEach((certificateName) => { + const isInfisicalManaged = isInfisicalManagedCertificate(certificateName, pkiSync); + + if (isInfisicalManaged) { + const isTrackedInSyncRecords = existingSyncRecords.some( + (record) => record.externalIdentifier === certificateName + ); + + const isInActiveSet = activeExternalIdentifiers.has(certificateName); + + if (!isTrackedInSyncRecords && !isInActiveSet && !certificatesToRemove.includes(certificateName)) { + certificatesToRemove.push(certificateName); + } + } + }); + } // Upload certificates to Azure Key Vault with rate limiting const uploadResults = await executeWithConcurrencyLimit( setCertificates, - async ({ key, cert, privateKey, certificateChain }) => { + async ({ key, cert, privateKey, certificateChain, certificateId }) => { try { // Combine private key, certificate, and certificate chain in PEM format for Azure Key Vault let combinedPem = ""; @@ -428,6 +527,31 @@ export const azureKeyVaultPkiSyncFactory = ({ kmsService, appConnectionDAL }: TA } ); + if (certificateId) { + const existingCertSync = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId); + if (existingCertSync) { + await certificateSyncDAL.updateById(existingCertSync.id, { + externalIdentifier: key, + syncStatus: CertificateSyncStatus.Succeeded, + lastSyncedAt: new Date() + }); + } else { + await certificateSyncDAL.addCertificates(pkiSync.id, [ + { + certificateId, + externalIdentifier: key + } + ]); + } + + if (enableVersioning) { + const currentCertificate = await certificateDAL.findById(certificateId); + if (currentCertificate?.renewedFromCertificateId) { + await certificateSyncDAL.removeCertificates(pkiSync.id, [currentCertificate.renewedFromCertificateId]); + } + } + } + return { key, success: true, response: response.data as unknown }; } catch (error) { if (error instanceof AxiosError) { @@ -599,19 +723,43 @@ export const azureKeyVaultPkiSyncFactory = ({ kmsService, appConnectionDAL }: TA }; }; - const removeCertificates = async (pkiSync: TPkiSyncWithCredentials, certificateNames: string[]) => { + const removeCertificates = async ( + pkiSync: TPkiSyncWithCredentials, + certificateNames: string[], + deps?: { certificateSyncDAL?: TCertificateSyncDALFactory; certificateMap?: TCertificateMap } + ) => { const { accessToken } = await getAzureConnectionAccessToken(pkiSync.connection.id, appConnectionDAL, kmsService); // Cast destination config to Azure Key Vault config const destinationConfig = pkiSync.destinationConfig as TAzureKeyVaultPkiSyncConfig; - // Only remove certificates that are managed by Infisical (match naming schema) - const infisicalManagedCertNames = certificateNames.filter((certName) => - isInfisicalManagedCertificate(certName, pkiSync) - ); + const existingSyncRecords = await certificateSyncDAL.findByPkiSyncId(pkiSync.id); + const certificateNamesToRemove: string[] = []; + const certificateIdToNameMap = new Map(); + + for (const certName of certificateNames) { + if (deps?.certificateMap?.[certName]?.certificateId) { + const { certificateId } = deps.certificateMap[certName]; + + const syncRecord = existingSyncRecords.find((record) => record.certificateId === certificateId); + + if (syncRecord?.externalIdentifier && typeof certificateId === "string") { + certificateNamesToRemove.push(syncRecord.externalIdentifier); + certificateIdToNameMap.set(certificateId, syncRecord.externalIdentifier); + } + } + } + + if (certificateNamesToRemove.length === 0) { + return { + removed: 0, + failed: 0, + skipped: certificateNames.length + }; + } const results = await executeWithConcurrencyLimit( - infisicalManagedCertNames, + certificateNamesToRemove, async (certName) => { try { const response = await request.delete( @@ -646,8 +794,44 @@ export const azureKeyVaultPkiSyncFactory = ({ kmsService, appConnectionDAL }: TA }, { operation: "remove-specific-certificates", syncId: pkiSync.id } ); + const failedRemovals = results.filter((result) => result.status === "rejected"); + if (failedRemovals.length > 0 && deps?.certificateSyncDAL) { + for (const failure of failedRemovals) { + if (failure.status === "rejected") { + const failedCertName = certificateNamesToRemove[results.indexOf(failure)]; + + const certificateId = Array.from(certificateIdToNameMap.entries()).find( + ([, name]) => name === failedCertName + )?.[0]; + + if (certificateId) { + const errorMessage = (failure.reason as Error)?.message || "Unknown error"; + await deps.certificateSyncDAL.updateSyncStatus( + pkiSync.id, + certificateId, + CertificateSyncStatus.Failed, + `Failed to remove from Azure: ${errorMessage}` + ); + } + } + } + } + + const successfulRemovals = results.filter((result) => result.status === "fulfilled"); + if (successfulRemovals.length > 0) { + const successfulCertNames = new Set(successfulRemovals.map((_, index) => certificateNamesToRemove[index])); + + const certificateIdsToRemove = Array.from(certificateIdToNameMap.entries()) + .filter(([, name]) => successfulCertNames.has(name)) + .map(([certificateId]) => certificateId); + + if (certificateIdsToRemove.length > 0) { + await certificateSyncDAL.removeCertificates(pkiSync.id, certificateIdsToRemove); + } + } + if (failedRemovals.length > 0) { const failedReasons = failedRemovals.map((failure) => { if (failure.status === "rejected") { @@ -660,16 +844,16 @@ export const azureKeyVaultPkiSyncFactory = ({ kmsService, appConnectionDAL }: TA message: `Failed to remove ${failedRemovals.length} certificate(s) from Azure Key Vault`, context: { failedReasons, - totalCertificates: infisicalManagedCertNames.length, + totalCertificates: certificateNamesToRemove.length, failedCount: failedRemovals.length } }); } return { - removed: infisicalManagedCertNames.length - failedRemovals.length, + removed: certificateNamesToRemove.length - failedRemovals.length, failed: failedRemovals.length, - skipped: certificateNames.length - infisicalManagedCertNames.length + skipped: certificateNames.length - certificateNamesToRemove.length }; }; diff --git a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts index ef6347e82..90f4a119b 100644 --- a/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts +++ b/backend/src/services/pki-sync/azure-key-vault/azure-key-vault-pki-sync-schemas.ts @@ -14,6 +14,7 @@ export const AzureKeyVaultPkiSyncConfigSchema = z.object({ const AzureKeyVaultPkiSyncOptionsSchema = z.object({ canImportCertificates: z.boolean().default(false), canRemoveCertificates: z.boolean().default(true), + enableVersioning: z.boolean().default(true), certificateNameSchema: z .string() .optional() @@ -50,9 +51,10 @@ export const CreateAzureKeyVaultPkiSyncSchema = z.object({ isAutoSyncEnabled: z.boolean().default(true), destinationConfig: AzureKeyVaultPkiSyncConfigSchema, syncOptions: AzureKeyVaultPkiSyncOptionsSchema.optional().default({}), - subscriberId: z.string().optional(), + subscriberId: z.string().nullish(), connectionId: z.string(), - projectId: z.string().trim().min(1) + projectId: z.string().trim().min(1), + certificateIds: z.array(z.string().uuid()).optional() }); export const UpdateAzureKeyVaultPkiSyncSchema = z.object({ @@ -61,7 +63,7 @@ export const UpdateAzureKeyVaultPkiSyncSchema = z.object({ isAutoSyncEnabled: z.boolean().optional(), destinationConfig: AzureKeyVaultPkiSyncConfigSchema.optional(), syncOptions: AzureKeyVaultPkiSyncOptionsSchema.optional(), - subscriberId: z.string().optional(), + subscriberId: z.string().nullish(), connectionId: z.string().optional() }); diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.ts index 75f312fff..961687f85 100644 --- a/backend/src/services/pki-sync/pki-sync-fns.ts +++ b/backend/src/services/pki-sync/pki-sync-fns.ts @@ -4,6 +4,8 @@ import { z, ZodSchema } from "zod"; import { TLicenseServiceFactory } from "@app/ee/services/license/license-service"; import { BadRequestError } from "@app/lib/errors"; import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal"; +import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal"; +import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal"; import { TKmsServiceFactory } from "@app/services/kms/kms-service"; import { AWS_CERTIFICATE_MANAGER_PKI_SYNC_LIST_OPTION } from "./aws-certificate-manager/aws-certificate-manager-pki-sync-constants"; @@ -184,6 +186,8 @@ export const PkiSyncFns = { dependencies: { appConnectionDAL: Pick; kmsService: Pick; + certificateDAL: TCertificateDALFactory; + certificateSyncDAL: TCertificateSyncDALFactory; } ): Promise<{ uploaded: number; @@ -194,17 +198,28 @@ export const PkiSyncFns = { failedUploads?: Array<{ name: string; error: string }>; failedRemovals?: Array<{ name: string; error: string }>; skippedCertificates?: Array<{ name: string; reason: string }>; + validationErrors?: Array<{ name: string; error: string }>; }; }> => { switch (pkiSync.destination) { case PkiSync.AzureKeyVault: { checkPkiSyncDestination(pkiSync, PkiSync.AzureKeyVault); - const azureKeyVaultPkiSync = azureKeyVaultPkiSyncFactory(dependencies); + const azureKeyVaultPkiSync = azureKeyVaultPkiSyncFactory({ + appConnectionDAL: dependencies.appConnectionDAL, + kmsService: dependencies.kmsService, + certificateDAL: dependencies.certificateDAL, + certificateSyncDAL: dependencies.certificateSyncDAL + }); return azureKeyVaultPkiSync.syncCertificates(pkiSync, certificateMap); } case PkiSync.AwsCertificateManager: { checkPkiSyncDestination(pkiSync, PkiSync.AwsCertificateManager); - const awsCertificateManagerPkiSync = awsCertificateManagerPkiSyncFactory(dependencies); + const awsCertificateManagerPkiSync = awsCertificateManagerPkiSyncFactory({ + appConnectionDAL: dependencies.appConnectionDAL, + kmsService: dependencies.kmsService, + certificateDAL: dependencies.certificateDAL, + certificateSyncDAL: dependencies.certificateSyncDAL + }); return awsCertificateManagerPkiSync.syncCertificates(pkiSync, certificateMap); } default: @@ -218,19 +233,38 @@ export const PkiSyncFns = { dependencies: { appConnectionDAL: Pick; kmsService: Pick; + certificateSyncDAL: TCertificateSyncDALFactory; + certificateDAL: TCertificateDALFactory; + certificateMap: TCertificateMap; } ): Promise => { switch (pkiSync.destination) { case PkiSync.AzureKeyVault: { checkPkiSyncDestination(pkiSync, PkiSync.AzureKeyVault); - const azureKeyVaultPkiSync = azureKeyVaultPkiSyncFactory(dependencies); - await azureKeyVaultPkiSync.removeCertificates(pkiSync, certificateNames); + const azureKeyVaultPkiSync = azureKeyVaultPkiSyncFactory({ + appConnectionDAL: dependencies.appConnectionDAL, + kmsService: dependencies.kmsService, + certificateDAL: dependencies.certificateDAL, + certificateSyncDAL: dependencies.certificateSyncDAL + }); + await azureKeyVaultPkiSync.removeCertificates(pkiSync, certificateNames, { + certificateSyncDAL: dependencies.certificateSyncDAL, + certificateMap: dependencies.certificateMap + }); break; } case PkiSync.AwsCertificateManager: { checkPkiSyncDestination(pkiSync, PkiSync.AwsCertificateManager); - const awsCertificateManagerPkiSync = awsCertificateManagerPkiSyncFactory(dependencies); - await awsCertificateManagerPkiSync.removeCertificates(pkiSync, certificateNames); + const awsCertificateManagerPkiSync = awsCertificateManagerPkiSyncFactory({ + appConnectionDAL: dependencies.appConnectionDAL, + kmsService: dependencies.kmsService, + certificateDAL: dependencies.certificateDAL, + certificateSyncDAL: dependencies.certificateSyncDAL + }); + await awsCertificateManagerPkiSync.removeCertificates(pkiSync, certificateNames, { + certificateSyncDAL: dependencies.certificateSyncDAL, + certificateMap: dependencies.certificateMap + }); break; } default: diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.ts index 5967a6c97..608162ead 100644 --- a/backend/src/services/pki-sync/pki-sync-queue.ts +++ b/backend/src/services/pki-sync/pki-sync-queue.ts @@ -5,6 +5,7 @@ import { AxiosError } from "axios"; import { Job } from "bullmq"; import handlebars from "handlebars"; +import { TCertificates } from "@app/db/schemas"; import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types"; import { TLicenseServiceFactory } from "@app/ee/services/license/license-service"; import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore"; @@ -25,6 +26,8 @@ import { TCertificateSecretDALFactory } from "../certificate/certificate-secret- import { TCertificateAuthorityCertDALFactory } from "../certificate-authority/certificate-authority-cert-dal"; import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal"; import { getCaCertChain } from "../certificate-authority/certificate-authority-fns"; +import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal"; +import { CertificateSyncStatus } from "../certificate-sync/certificate-sync-enums"; import { TPkiSyncDALFactory } from "./pki-sync-dal"; import { PkiSyncStatus } from "./pki-sync-enums"; import { PkiSyncError } from "./pki-sync-errors"; @@ -55,14 +58,12 @@ type TPkiSyncQueueFactoryDep = { auditLogService: Pick; projectDAL: TProjectDALFactory; licenseService: Pick; - certificateDAL: Pick< - TCertificateDALFactory, - "findLatestActiveCertForSubscriber" | "findAllActiveCertsForSubscriber" | "create" - >; + certificateDAL: TCertificateDALFactory; certificateBodyDAL: Pick; certificateSecretDAL: Pick; certificateAuthorityDAL: Pick; certificateAuthorityCertDAL: Pick; + certificateSyncDAL: TCertificateSyncDALFactory; }; type PkiSyncActionJob = Job< @@ -93,7 +94,8 @@ export const pkiSyncQueueFactory = ({ certificateBodyDAL, certificateSecretDAL, certificateAuthorityDAL, - certificateAuthorityCertDAL + certificateAuthorityCertDAL, + certificateSyncDAL }: TPkiSyncQueueFactoryDep) => { const appCfg = getConfig(); @@ -153,25 +155,39 @@ export const pkiSyncQueueFactory = ({ const $getInfisicalCertificates = async ( pkiSync: TPkiSyncRaw | TPkiSyncWithCredentials - ): Promise => { - const { projectId, subscriberId } = pkiSync; - - if (!subscriberId) { - throw new PkiSyncError({ - message: "Invalid PKI Sync source configuration: subscriber no longer exists. Please update source subscriber.", - shouldRetry: false - }); - } + ): Promise<{ certificateMap: TCertificateMap; certificateMetadata: Map }> => { + const { projectId, subscriberId, id: pkiSyncId } = pkiSync; const certificateMap: TCertificateMap = {}; + const certificateMetadata = new Map(); + let certificates: Array<{ id: string; projectId: string; caCertId?: string | null }> = []; try { - // Get all active certificates for the subscriber (not just the latest) - const certificates = await certificateDAL.findAllActiveCertsForSubscriber({ - subscriberId - }); + if (subscriberId) { + const subscriberCertificates = await certificateDAL.findAllActiveCertsForSubscriber({ + subscriberId + }); + certificates.push(...subscriberCertificates); + } + + const certificateIds = await certificateSyncDAL.findCertificateIdsByPkiSyncId(pkiSyncId); + if (certificateIds.length > 0) { + const directCertificates = await certificateDAL.findActiveCertificatesByIds(certificateIds); + certificates.push(...directCertificates); + } + + const uniqueCertificates = certificates.filter( + (cert, index, self) => self.findIndex((c) => c.id === cert.id) === index + ); + + if (uniqueCertificates.length === 0) { + return { certificateMap, certificateMetadata }; + } + + certificates = uniqueCertificates; for (const certificate of certificates) { + const cert = certificate as TCertificates; try { // Get the certificate body and decrypt the certificate data const certBody = await certificateBodyDAL.findOne({ certId: certificate.id }); @@ -246,19 +262,45 @@ export const pkiSyncQueueFactory = ({ if (certificateNameSchema) { const environment = "global"; - certificateName = handlebars.compile(certificateNameSchema)({ + const templateData = { certificateId: certificate.id.replace(/-/g, ""), + profileId: cert.profileId?.replace(/-/g, "") || certificate.id.replace(/-/g, ""), + commonName: cert.commonName || "", + friendlyName: cert.friendlyName || "", environment - }); + }; + certificateName = handlebars.compile(certificateNameSchema)(templateData); } else { - certificateName = `Infisical-${certificate.id.replace(/-/g, "")}`; + const stableId = cert.profileId + ? `${cert.profileId.replace(/-/g, "")}-${(cert.commonName || "").replace(/[^a-zA-Z0-9]/g, "")}` + : certificate.id.replace(/-/g, ""); + certificateName = `Infisical-${stableId}`; + } + + const alternativeNames: string[] = []; + + const legacyName = `Infisical-${certificate.id.replace(/-/g, "")}`; + if (legacyName !== certificateName) { + alternativeNames.push(legacyName); + } + + if (cert.renewedFromCertificateId) { + const originalLegacyName = `Infisical-${cert.renewedFromCertificateId.replace(/-/g, "")}`; + alternativeNames.push(originalLegacyName); } certificateMap[certificateName] = { cert: certificatePem, privateKey: certPrivateKey || "", - certificateChain + certificateChain, + alternativeNames, + certificateId: certificate.id }; + + certificateMetadata.set(certificateName, { + id: certificate.id, + name: certificateName + }); } else { logger.warn({ certificateId: certificate.id, subscriberId }, "Certificate body not found for certificate"); } @@ -281,7 +323,7 @@ export const pkiSyncQueueFactory = ({ }); } - return certificateMap; + return { certificateMap, certificateMetadata }; }; const queuePkiSyncSyncCertificatesById = async (payload: TQueuePkiSyncSyncCertificatesByIdDTO) => @@ -348,12 +390,17 @@ export const pkiSyncQueueFactory = ({ try { const { - connection: { orgId, encryptedCredentials, projectId: appConnectionProjectId } + connection: { id: connectionId, orgId, projectId: appConnectionProjectId } } = pkiSync; + const appConnection = await appConnectionDAL.findById(connectionId); + if (!appConnection) { + throw new Error(`App connection not found: ${connectionId}`); + } + const credentials = await decryptAppConnectionCredentials({ orgId, - encryptedCredentials, + encryptedCredentials: appConnection.encryptedCredentials, kmsService, projectId: appConnectionProjectId }); @@ -366,11 +413,24 @@ export const pkiSyncQueueFactory = ({ } } as TPkiSyncWithCredentials; - const certificateMap = await $getInfisicalCertificates(pkiSync); + const { certificateMap, certificateMetadata } = await $getInfisicalCertificates(pkiSync); + + const statusUpdates = Array.from(certificateMetadata.entries()).map(([, metadata]) => ({ + pkiSyncId: pkiSync.id, + certificateId: metadata.id, + status: CertificateSyncStatus.Running, + message: "Syncing certificate to destination" + })); + + if (statusUpdates.length > 0) { + await certificateSyncDAL.bulkUpdateSyncStatus(statusUpdates); + } const syncResult = await PkiSyncFns.syncCertificates(pkiSyncWithCredentials, certificateMap, { appConnectionDAL, - kmsService + kmsService, + certificateDAL, + certificateSyncDAL }); logger.info( @@ -384,6 +444,60 @@ export const pkiSyncQueueFactory = ({ "PKI sync operation completed with certificate cleanup" ); + const postSyncUpdates: Array<{ + pkiSyncId: string; + certificateId: string; + status: string; + message?: string; + }> = []; + + for (const [, metadata] of certificateMetadata.entries()) { + postSyncUpdates.push({ + pkiSyncId: pkiSync.id, + certificateId: metadata.id, + status: CertificateSyncStatus.Succeeded, + message: "Certificate successfully synced to destination" + }); + } + + if (syncResult.details?.validationErrors) { + for (const validationError of syncResult.details.validationErrors) { + const metadata = certificateMetadata.get(validationError.name); + if (metadata) { + const updateIndex = postSyncUpdates.findIndex((u) => u.certificateId === metadata.id); + if (updateIndex >= 0) { + postSyncUpdates[updateIndex] = { + pkiSyncId: pkiSync.id, + certificateId: metadata.id, + status: CertificateSyncStatus.Failed, + message: `${validationError.error}` + }; + } + } + } + } + + if (syncResult.details?.failedUploads) { + for (const failure of syncResult.details.failedUploads) { + const metadata = certificateMetadata.get(failure.name); + if (metadata) { + const updateIndex = postSyncUpdates.findIndex((u) => u.certificateId === metadata.id); + if (updateIndex >= 0) { + postSyncUpdates[updateIndex] = { + pkiSyncId: pkiSync.id, + certificateId: metadata.id, + status: CertificateSyncStatus.Failed, + message: `Failed to sync certificate: ${failure.error}` + }; + } + } + } + } + + if (postSyncUpdates.length > 0) { + await certificateSyncDAL.bulkUpdateSyncStatus(postSyncUpdates); + } + isSynced = true; } catch (err) { logger.error( @@ -550,17 +664,22 @@ export const pkiSyncQueueFactory = ({ try { const { - connection: { orgId, encryptedCredentials, projectId: appConnectionProjectId } + connection: { id: connectionId, orgId, projectId: appConnectionProjectId } } = pkiSync; + const appConnection = await appConnectionDAL.findById(connectionId); + if (!appConnection) { + throw new Error(`App connection not found: ${connectionId}`); + } + const credentials = await decryptAppConnectionCredentials({ orgId, - encryptedCredentials, + encryptedCredentials: appConnection.encryptedCredentials, kmsService, projectId: appConnectionProjectId }); - const certificateMap = await $getInfisicalCertificates(pkiSync); + const { certificateMap } = await $getInfisicalCertificates(pkiSync); await PkiSyncFns.removeCertificates( { @@ -573,7 +692,10 @@ export const pkiSyncQueueFactory = ({ Object.keys(certificateMap), { appConnectionDAL, - kmsService + kmsService, + certificateSyncDAL, + certificateDAL, + certificateMap } ); diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.ts index f92c9e19f..02a76db2a 100644 --- a/backend/src/services/pki-sync/pki-sync-service.ts +++ b/backend/src/services/pki-sync/pki-sync-service.ts @@ -1,6 +1,6 @@ import { ForbiddenError, subject } from "@casl/ability"; -import { ActionProjectType } from "@app/db/schemas"; +import { ActionProjectType, TCertificateSyncs } from "@app/db/schemas"; import { TLicenseServiceFactory } from "@app/ee/services/license/license-service"; import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types"; import { ProjectPermissionPkiSyncActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission"; @@ -10,17 +10,24 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enums import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service"; import { TPkiSubscriberDALFactory } from "@app/services/pki-subscriber/pki-subscriber-dal"; +import { TCertificateDALFactory } from "../certificate/certificate-dal"; +import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal"; +import { CertificateSyncStatus } from "../certificate-sync/certificate-sync-enums"; import { TPkiSyncDALFactory } from "./pki-sync-dal"; import { PkiSync, PkiSyncStatus } from "./pki-sync-enums"; import { enterprisePkiSyncCheck, getPkiSyncProviderCapabilities, listPkiSyncOptions } from "./pki-sync-fns"; import { PKI_SYNC_CONNECTION_MAP, PKI_SYNC_NAME_MAP } from "./pki-sync-maps"; import { TPkiSyncQueueFactory } from "./pki-sync-queue"; import { + TAddCertificatesToPkiSyncDTO, TCreatePkiSyncDTO, TDeletePkiSyncDTO, TFindPkiSyncByIdDTO, + TListPkiSyncCertificatesDTO, TListPkiSyncsByProjectId, TPkiSync, + TPkiSyncCertificate, + TRemoveCertificatesFromPkiSyncDTO, TTriggerPkiSyncImportCertificatesByIdDTO, TTriggerPkiSyncRemoveCertificatesByIdDTO, TTriggerPkiSyncSyncCertificatesByIdDTO, @@ -42,6 +49,17 @@ type TPkiSyncServiceFactoryDep = { TPkiSyncDALFactory, "findById" | "findByProjectIdWithSubscribers" | "findByNameAndProjectId" | "create" | "updateById" | "deleteById" >; + certificateDAL: Pick; + certificateSyncDAL: Pick< + TCertificateSyncDALFactory, + | "findByPkiSyncId" + | "findByCertificateId" + | "findCertificateIdsByPkiSyncId" + | "addCertificates" + | "removeCertificates" + | "removeAllCertificatesFromSync" + | "findWithDetails" + >; pkiSubscriberDAL: Pick; appConnectionService: Pick; permissionService: Pick; @@ -56,12 +74,41 @@ export type TPkiSyncServiceFactory = ReturnType; export const pkiSyncServiceFactory = ({ pkiSyncDAL, + certificateDAL, + certificateSyncDAL, pkiSubscriberDAL, appConnectionService, permissionService, licenseService, pkiSyncQueue }: TPkiSyncServiceFactoryDep) => { + const validateCertificatesProjectOwnership = async (certificateIds: string[], expectedProjectId: string) => { + if (certificateIds.length === 0) return; + + const certificates = await certificateDAL.findActiveCertificatesByIds(certificateIds); + + if (certificates.length !== certificateIds.length) { + const foundIds = certificates.map((cert) => cert.id); + const missingIds = certificateIds.filter((id) => !foundIds.includes(id)); + throw new NotFoundError({ + message: `Certificates not found or not active: ${missingIds.join(", ")}` + }); + } + + const invalidProjectCertificates = certificates.filter((cert) => cert.projectId !== expectedProjectId); + if (invalidProjectCertificates.length > 0) { + throw new BadRequestError({ + message: `Certificates do not belong to the same project: ${invalidProjectCertificates.map((cert) => cert.id).join(", ")}` + }); + } + + const invalidRenewedCertificates = certificates.filter((cert) => cert.renewedByCertificateId); + if (invalidRenewedCertificates.length > 0) { + throw new BadRequestError({ + message: `Cannot add renewed certificates to PKI sync: ${invalidRenewedCertificates.map((cert) => cert.id).join(", ")}` + }); + } + }; const createPkiSync = async ( { name, @@ -72,7 +119,8 @@ export const pkiSyncServiceFactory = ({ syncOptions = {}, subscriberId, connectionId, - projectId + projectId, + certificateIds = [] }: Omit, actor: OrgServiceActor ): Promise => { @@ -114,6 +162,10 @@ export const pkiSyncServiceFactory = ({ ...syncOptions }; + if (certificateIds.length > 0) { + await validateCertificatesProjectOwnership(certificateIds, projectId); + } + try { const pkiSync = await pkiSyncDAL.create({ name, @@ -128,6 +180,13 @@ export const pkiSyncServiceFactory = ({ ...(isAutoSyncEnabled && { syncStatus: PkiSyncStatus.Pending }) }); + if (certificateIds.length > 0) { + await certificateSyncDAL.addCertificates( + pkiSync.id, + certificateIds.map((id) => ({ certificateId: id })) + ); + } + if (pkiSync.isAutoSyncEnabled) { await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSync.id }); } @@ -152,7 +211,8 @@ export const pkiSyncServiceFactory = ({ destinationConfig, syncOptions, subscriberId, - connectionId + connectionId, + certificateIds }: Omit, actor: OrgServiceActor ): Promise => { @@ -221,6 +281,20 @@ export const pkiSyncServiceFactory = ({ }; } + if (certificateIds !== undefined) { + if (certificateIds.length > 0) { + await validateCertificatesProjectOwnership(certificateIds, pkiSync.projectId); + } + + await certificateSyncDAL.removeAllCertificatesFromSync(id); + if (certificateIds.length > 0) { + await certificateSyncDAL.addCertificates( + id, + certificateIds.map((certId) => ({ certificateId: certId })) + ); + } + } + const updatedPkiSync = await pkiSyncDAL.updateById(id, { name, description, @@ -266,7 +340,7 @@ export const pkiSyncServiceFactory = ({ }; const listPkiSyncsByProjectId = async ( - { projectId }: TListPkiSyncsByProjectId, + { projectId, certificateId }: TListPkiSyncsByProjectId, actor: OrgServiceActor ): Promise => { const { permission } = await permissionService.getProjectPermission({ @@ -282,6 +356,29 @@ export const pkiSyncServiceFactory = ({ const pkiSyncsWithSubscribers = await pkiSyncDAL.findByProjectIdWithSubscribers(projectId); + if (certificateId) { + const syncsWithCertificateInfo = await Promise.all( + pkiSyncsWithSubscribers.map(async (sync) => { + try { + const certificateSyncs = await certificateSyncDAL.findByPkiSyncId(sync.id); + const hasCertificate = certificateSyncs.some((certSync) => certSync.certificateId === certificateId); + + return { + ...sync, + hasCertificate + }; + } catch (error) { + return { + ...sync, + hasCertificate: false + }; + } + }) + ); + + return syncsWithCertificateInfo as TPkiSync[]; + } + return pkiSyncsWithSubscribers as TPkiSync[]; }; @@ -433,6 +530,145 @@ export const pkiSyncServiceFactory = ({ return listPkiSyncOptions(); }; + const addCertificatesToPkiSync = async ( + { pkiSyncId, certificateIds }: Omit, + actor: OrgServiceActor + ): Promise<{ + addedCertificates: TCertificateSyncs[]; + pkiSyncInfo: { projectId: string; destination: string; name: string }; + }> => { + const pkiSync = await pkiSyncDAL.findById(pkiSyncId); + if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" }); + + const { permission } = await permissionService.getProjectPermission({ + actor: actor.type, + actorId: actor.id, + actorAuthMethod: actor.authMethod, + actorOrgId: actor.orgId, + actionProjectType: ActionProjectType.CertificateManager, + projectId: pkiSync.projectId + }); + + ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionPkiSyncActions.Edit, ProjectPermissionSub.PkiSyncs); + + await validateCertificatesProjectOwnership(certificateIds, pkiSync.projectId); + + const addedCertificates = await certificateSyncDAL.addCertificates( + pkiSyncId, + certificateIds.map((id) => ({ certificateId: id })) + ); + + if (pkiSync.isAutoSyncEnabled) { + await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSyncId }); + } + + return { + addedCertificates, + pkiSyncInfo: { + projectId: pkiSync.projectId, + destination: pkiSync.destination, + name: pkiSync.name + } + }; + }; + + const removeCertificatesFromPkiSync = async ( + { pkiSyncId, certificateIds }: Omit, + actor: OrgServiceActor + ): Promise<{ removedCount: number; pkiSyncInfo: { projectId: string; destination: string; name: string } }> => { + const pkiSync = await pkiSyncDAL.findById(pkiSyncId); + if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" }); + + const { permission } = await permissionService.getProjectPermission({ + actor: actor.type, + actorId: actor.id, + actorAuthMethod: actor.authMethod, + actorOrgId: actor.orgId, + actionProjectType: ActionProjectType.CertificateManager, + projectId: pkiSync.projectId + }); + + ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionPkiSyncActions.Edit, ProjectPermissionSub.PkiSyncs); + + const removedCount = await certificateSyncDAL.removeCertificates(pkiSyncId, certificateIds); + + if (pkiSync.isAutoSyncEnabled) { + await pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSyncId }); + } + + return { + removedCount, + pkiSyncInfo: { + projectId: pkiSync.projectId, + destination: pkiSync.destination, + name: pkiSync.name + } + }; + }; + + const listPkiSyncCertificates = async ( + { pkiSyncId, offset = 0, limit = 20 }: Omit, + actor: OrgServiceActor + ): Promise<{ + certificates: TPkiSyncCertificate[]; + totalCount: number; + pkiSyncInfo: { projectId: string; destination: string; name: string }; + }> => { + const pkiSync = await pkiSyncDAL.findById(pkiSyncId); + if (!pkiSync) throw new NotFoundError({ message: "PKI sync not found" }); + + const { permission } = await permissionService.getProjectPermission({ + actor: actor.type, + actorId: actor.id, + actorAuthMethod: actor.authMethod, + actorOrgId: actor.orgId, + actionProjectType: ActionProjectType.CertificateManager, + projectId: pkiSync.projectId + }); + + ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionPkiSyncActions.Read, ProjectPermissionSub.PkiSyncs); + + const result = await certificateSyncDAL.findWithDetails({ + pkiSyncId, + offset, + limit + }); + const { certificateDetails, totalCount } = result; + + const certificates = certificateDetails.map((detail) => ({ + id: detail.id, + pkiSyncId: detail.pkiSyncId, + certificateId: detail.certificateId, + syncStatus: (detail.syncStatus as CertificateSyncStatus) || CertificateSyncStatus.Pending, + lastSyncMessage: detail.lastSyncMessage || undefined, + lastSyncedAt: detail.lastSyncedAt || undefined, + createdAt: detail.createdAt, + updatedAt: detail.updatedAt, + certificateSerialNumber: detail.certificateSerialNumber || undefined, + certificateCommonName: detail.certificateCommonName || undefined, + certificateAltNames: detail.certificateAltNames || undefined, + certificateStatus: detail.certificateStatus || undefined, + certificateNotBefore: detail.certificateNotBefore || undefined, + certificateNotAfter: detail.certificateNotAfter || undefined, + certificateRenewBeforeDays: !detail.certificateRenewedByCertificateId + ? detail.certificateRenewBeforeDays || undefined + : undefined, + certificateRenewalError: detail.certificateRenewalError || undefined, + pkiSyncName: detail.pkiSyncName || undefined, + pkiSyncDestination: detail.pkiSyncDestination || undefined + })); + + return { + certificates, + totalCount, + pkiSyncInfo: { + projectId: pkiSync.projectId, + destination: pkiSync.destination, + name: pkiSync.name + } + }; + }; + return { createPkiSync, updatePkiSync, @@ -442,6 +678,9 @@ export const pkiSyncServiceFactory = ({ triggerPkiSyncSyncCertificatesById, triggerPkiSyncImportCertificatesById, triggerPkiSyncRemoveCertificatesById, - getPkiSyncOptions + getPkiSyncOptions, + addCertificatesToPkiSync, + removeCertificatesFromPkiSync, + listPkiSyncCertificates }; }; diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.ts index bf750beee..f42f64a1b 100644 --- a/backend/src/services/pki-sync/pki-sync-types.ts +++ b/backend/src/services/pki-sync/pki-sync-types.ts @@ -2,6 +2,7 @@ import { Job } from "bullmq"; import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types"; import { QueueJobs } from "@app/queue"; +import { CertificateSyncStatus } from "@app/services/certificate-sync/certificate-sync-enums"; import { ResourceMetadataDTO } from "@app/services/resource-metadata/resource-metadata-schema"; import { TPkiSyncDALFactory } from "./pki-sync-dal"; @@ -70,7 +71,10 @@ export type TPkiSyncListItem = TPkiSync & { appConnectionApp: string; }; -export type TCertificateMap = Record; +export type TCertificateMap = Record< + string, + { cert: string; privateKey: string; certificateChain?: string; alternativeNames?: string[]; certificateId?: string } +>; export type TCreatePkiSyncDTO = { name: string; @@ -79,9 +83,10 @@ export type TCreatePkiSyncDTO = { isAutoSyncEnabled?: boolean; destinationConfig: Record; syncOptions?: Record; - subscriberId?: string; + subscriberId?: string | null; connectionId: string; projectId: string; + certificateIds?: string[]; auditLogInfo: AuditLogInfo; resourceMetadata?: ResourceMetadataDTO; }; @@ -94,8 +99,9 @@ export type TUpdatePkiSyncDTO = { isAutoSyncEnabled?: boolean; destinationConfig?: Record; syncOptions?: Record; - subscriberId?: string; + subscriberId?: string | null; connectionId?: string; + certificateIds?: string[]; auditLogInfo: AuditLogInfo; resourceMetadata?: ResourceMetadataDTO; }; @@ -108,6 +114,7 @@ export type TDeletePkiSyncDTO = { export type TListPkiSyncsByProjectId = { projectId: string; + certificateId?: string; }; export type TFindPkiSyncByIdDTO = { @@ -133,6 +140,48 @@ export type TTriggerPkiSyncRemoveCertificatesByIdDTO = { auditLogInfo: AuditLogInfo; }; +export type TAddCertificatesToPkiSyncDTO = { + pkiSyncId: string; + certificateIds: string[]; + projectId?: string; + auditLogInfo: AuditLogInfo; +}; + +export type TRemoveCertificatesFromPkiSyncDTO = { + pkiSyncId: string; + certificateIds: string[]; + projectId?: string; + auditLogInfo: AuditLogInfo; +}; + +export type TListPkiSyncCertificatesDTO = { + pkiSyncId: string; + projectId?: string; + offset?: number; + limit?: number; +}; + +export type TPkiSyncCertificate = { + id: string; + pkiSyncId: string; + certificateId: string; + syncStatus: CertificateSyncStatus; + lastSyncMessage?: string; + lastSyncedAt?: Date; + createdAt: Date; + updatedAt: Date; + certificateSerialNumber?: string; + certificateCommonName?: string; + certificateAltNames?: string; + certificateStatus?: string; + certificateNotBefore?: Date; + certificateNotAfter?: Date; + certificateRenewBeforeDays?: number; + certificateRenewalError?: string; + pkiSyncName?: string; + pkiSyncDestination?: string; +}; + export type TPkiSyncRaw = NonNullable>>; export type TQueuePkiSyncSyncCertificatesByIdDTO = { diff --git a/backend/src/services/pki-sync/pki-sync-utils.ts b/backend/src/services/pki-sync/pki-sync-utils.ts index a81864a17..d216ddd5a 100644 --- a/backend/src/services/pki-sync/pki-sync-utils.ts +++ b/backend/src/services/pki-sync/pki-sync-utils.ts @@ -1,5 +1,8 @@ +import { Knex } from "knex"; + import { logger } from "@app/lib/logger"; +import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal"; import { TPkiSyncDALFactory } from "./pki-sync-dal"; import { TPkiSyncQueueFactory } from "./pki-sync-queue"; @@ -25,3 +28,78 @@ export const triggerAutoSyncForSubscriber = async ( logger.error(error, `Failed to trigger auto sync for subscriber ${subscriberId}:`); } }; + +export const triggerAutoSyncForCertificate = async ( + certificateId: string, + dependencies: { + certificateSyncDAL: Pick; + pkiSyncDAL: Pick; + pkiSyncQueue: Pick; + } +) => { + try { + const pkiSyncIds = await dependencies.certificateSyncDAL.findPkiSyncIdsByCertificateId(certificateId); + + if (pkiSyncIds.length === 0) { + return; + } + + const allPkiSyncs = await dependencies.pkiSyncDAL.find({ + isAutoSyncEnabled: true, + $in: { + id: pkiSyncIds + } + }); + + const syncPromises = allPkiSyncs.map((pkiSync) => + dependencies.pkiSyncQueue.queuePkiSyncSyncCertificatesById({ syncId: pkiSync.id }) + ); + await Promise.all(syncPromises); + } catch (error) { + logger.error(error, `Failed to trigger auto sync for certificate ${certificateId}:`); + } +}; + +export const addRenewedCertificateToSyncs = async ( + oldCertificateId: string, + newCertificateId: string, + dependencies: { + certificateSyncDAL: Pick< + TCertificateSyncDALFactory, + "findPkiSyncIdsByCertificateId" | "addCertificates" | "findByPkiSyncAndCertificate" + >; + }, + tx?: Knex +) => { + try { + const pkiSyncIds = await dependencies.certificateSyncDAL.findPkiSyncIdsByCertificateId(oldCertificateId); + + if (pkiSyncIds.length === 0) { + return; + } + + const addPromises = pkiSyncIds.map(async (pkiSyncId) => { + const oldCertificateRecord = await dependencies.certificateSyncDAL.findByPkiSyncAndCertificate( + pkiSyncId, + oldCertificateId + ); + + await dependencies.certificateSyncDAL.addCertificates( + pkiSyncId, + [ + { + certificateId: newCertificateId, + externalIdentifier: oldCertificateRecord?.externalIdentifier || undefined + } + ], + tx + ); + }); + await Promise.all(addPromises); + + logger.info(`Successfully added renewed certificate ${newCertificateId} to PKI sync(s)`); + } catch (error) { + logger.error(error, `Failed to add renewed certificate ${newCertificateId} to syncs:`); + throw error; + } +}; diff --git a/backend/src/services/project-env/project-env-service.ts b/backend/src/services/project-env/project-env-service.ts index bf0bb18af..c402b6030 100644 --- a/backend/src/services/project-env/project-env-service.ts +++ b/backend/src/services/project-env/project-env-service.ts @@ -76,7 +76,7 @@ export const projectEnvServiceFactory = ({ const existingEnv = envs.find(({ slug: envSlug }) => envSlug === slug); if (existingEnv) throw new BadRequestError({ - message: "Environment with slug already exist", + message: "Environment with slug already exists", name: "CreateEnvironment" }); @@ -171,7 +171,7 @@ export const projectEnvServiceFactory = ({ const existingEnv = await projectEnvDAL.findOne({ slug, projectId }); if (existingEnv && existingEnv.id !== id) { throw new BadRequestError({ - message: "Environment with slug already exist", + message: "Environment with slug already exists", name: "UpdateEnvironment" }); } diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.ts index 19a13f45b..727cc9aa9 100644 --- a/backend/src/services/project/project-service.ts +++ b/backend/src/services/project/project-service.ts @@ -10,7 +10,8 @@ import { ProjectType, ProjectVersion, TableName, - TProjectEnvironments + TProjectEnvironments, + TProjects } from "@app/db/schemas"; import { TLicenseServiceFactory } from "@app/ee/services/license/license-service"; import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission"; @@ -40,7 +41,8 @@ import { TSshHostGroupDALFactory } from "@app/ee/services/ssh-host-group/ssh-hos import { PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore"; import { getConfig } from "@app/lib/config/env"; import { crypto } from "@app/lib/crypto/cryptography"; -import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors"; +import { DatabaseErrorCode } from "@app/lib/error-codes"; +import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors"; import { groupBy } from "@app/lib/fn"; import { alphaNumericNanoId } from "@app/lib/nanoid"; import { TProjectPermission } from "@app/lib/types"; @@ -154,7 +156,14 @@ type TProjectServiceFactoryDep = { >; pkiSubscriberDAL: Pick; certificateAuthorityDAL: Pick; - certificateDAL: Pick; + certificateDAL: Pick< + TCertificateDALFactory, + | "find" + | "countCertificatesInProject" + | "findWithPrivateKeyInfo" + | "findActiveCertificatesForSync" + | "countActiveCertificatesForSync" + >; certificateTemplateDAL: Pick; pkiAlertDAL: Pick; pkiCollectionDAL: Pick; @@ -303,19 +312,34 @@ export const projectServiceFactory = ({ }); } - const project = await projectDAL.create( - { - name: workspaceName, - type, - description: workspaceDescription, - orgId: organization.id, - slug: projectSlug || slugify(`${workspaceName}-${alphaNumericNanoId(4)}`), - kmsSecretManagerKeyId: kmsKeyId, - version: ProjectVersion.V3, - pitVersionLimit: 10 - }, - tx - ); + const slug = projectSlug || slugify(`${workspaceName}-${alphaNumericNanoId(4)}`); + + let project: TProjects; + try { + project = await projectDAL.create( + { + name: workspaceName, + type, + description: workspaceDescription, + orgId: organization.id, + slug, + kmsSecretManagerKeyId: kmsKeyId, + version: ProjectVersion.V3, + pitVersionLimit: 10 + }, + tx + ); + } catch (err) { + if ( + err instanceof DatabaseError && + (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation + ) { + throw new BadRequestError({ + message: `A project with the slug "${slug}" already exists in your organization. Please choose a different name or slug.` + }); + } + throw err; + } if (type === ProjectType.SSH) { await bootstrapSshProject({ @@ -579,39 +603,36 @@ export const projectServiceFactory = ({ }); ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings); - if (update.slug) { - const existingProject = await projectDAL.findOne({ - slug: update.slug, - orgId: actorOrgId - }); - if (existingProject && existingProject.id !== project.id) { - throw new BadRequestError({ - message: `Failed to update project slug. The project "${existingProject.name}" with the slug "${existingProject.slug}" already exists in your organization. Please choose a unique slug for your project.` - }); - } - } - if (update.secretDetectionIgnoreValues && !hasRole(ProjectMembershipRole.Admin)) { throw new ForbiddenRequestError({ message: "Only admins can update secret detection ignore values" }); } - const updatedProject = await projectDAL.updateById(project.id, { - name: update.name, - description: update.description, - autoCapitalization: update.autoCapitalization, - enforceCapitalization: update.autoCapitalization, - hasDeleteProtection: update.hasDeleteProtection, - slug: update.slug, - secretSharing: update.secretSharing, - defaultProduct: update.defaultProduct, - showSnapshotsLegacy: update.showSnapshotsLegacy, - secretDetectionIgnoreValues: update.secretDetectionIgnoreValues, - pitVersionLimit: update.pitVersionLimit - }); + try { + const updatedProject = await projectDAL.updateById(project.id, { + name: update.name, + description: update.description, + autoCapitalization: update.autoCapitalization, + enforceCapitalization: update.autoCapitalization, + hasDeleteProtection: update.hasDeleteProtection, + slug: update.slug, + secretSharing: update.secretSharing, + defaultProduct: update.defaultProduct, + showSnapshotsLegacy: update.showSnapshotsLegacy, + secretDetectionIgnoreValues: update.secretDetectionIgnoreValues, + pitVersionLimit: update.pitVersionLimit + }); - return updatedProject; + return updatedProject; + } catch (err) { + if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) { + throw new BadRequestError({ + message: `Failed to update project. A project with the slug "${update.slug}" already exists in your organization. Please choose a different slug.` + }); + } + throw err; + } }; const toggleAutoCapitalization = async ({ @@ -915,6 +936,7 @@ export const projectServiceFactory = ({ offset = 0, friendlyName, commonName, + forPkiSync = false, actorId, actorOrgId, actorAuthMethod, @@ -938,20 +960,35 @@ export const projectServiceFactory = ({ ProjectPermissionSub.Certificates ); - const certificates = await certificateDAL.find( - { - projectId, - ...(friendlyName && { friendlyName }), - ...(commonName && { commonName }) - }, - { offset, limit, sort: [["updatedAt", "desc"]] } - ); + const certificates = forPkiSync + ? await certificateDAL.findActiveCertificatesForSync( + { + projectId, + ...(friendlyName && { friendlyName }), + ...(commonName && { commonName }) + }, + { offset, limit } + ) + : await certificateDAL.findWithPrivateKeyInfo( + { + projectId, + ...(friendlyName && { friendlyName }), + ...(commonName && { commonName }) + }, + { offset, limit, sort: [["notAfter", "desc"]] } + ); - const count = await certificateDAL.countCertificatesInProject({ - projectId, - friendlyName, - commonName - }); + const count = forPkiSync + ? await certificateDAL.countActiveCertificatesForSync({ + projectId, + friendlyName, + commonName + }) + : await certificateDAL.countCertificatesInProject({ + projectId, + friendlyName, + commonName + }); return { certificates, diff --git a/backend/src/services/project/project-types.ts b/backend/src/services/project/project-types.ts index 318b08a8d..9e0745236 100644 --- a/backend/src/services/project/project-types.ts +++ b/backend/src/services/project/project-types.ts @@ -142,6 +142,7 @@ export type TListProjectCertsDTO = { limit: number; friendlyName?: string; commonName?: string; + forPkiSync?: boolean; } & Omit; export type TListProjectAlertsDTO = TProjectPermission; diff --git a/backend/src/services/secret-sync/chef/chef-sync-constants.ts b/backend/src/services/secret-sync/chef/chef-sync-constants.ts new file mode 100644 index 000000000..567b25bbe --- /dev/null +++ b/backend/src/services/secret-sync/chef/chef-sync-constants.ts @@ -0,0 +1,10 @@ +import { AppConnection } from "@app/services/app-connection/app-connection-enums"; +import { SecretSync } from "@app/services/secret-sync/secret-sync-enums"; +import { TSecretSyncListItem } from "@app/services/secret-sync/secret-sync-types"; + +export const CHEF_SYNC_LIST_OPTION: TSecretSyncListItem = { + name: "Chef", + destination: SecretSync.Chef, + connection: AppConnection.Chef, + canImportSecrets: true +}; diff --git a/backend/src/services/secret-sync/chef/chef-sync-fns.ts b/backend/src/services/secret-sync/chef/chef-sync-fns.ts new file mode 100644 index 000000000..7f32b398a --- /dev/null +++ b/backend/src/services/secret-sync/chef/chef-sync-fns.ts @@ -0,0 +1,151 @@ +import { getChefDataBagItem, updateChefDataBagItem } from "@app/services/app-connection/chef"; +import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns"; +import { TSecretMap } from "@app/services/secret-sync/secret-sync-types"; + +import { + ChefSecret, + TChefDataBagItemContent, + TChefSecret, + TChefSecrets, + TChefSyncWithCredentials, + TGetChefSecrets +} from "./chef-sync-types"; + +const getChefSecretsRaw = async ({ + serverUrl, + userName, + privateKey, + orgName, + dataBagName, + dataBagItemName +}: TGetChefSecrets): Promise => { + const dataBagItem = await getChefDataBagItem({ + serverUrl, + userName, + privateKey, + orgName, + dataBagName, + dataBagItemName + }); + + // Ensure the data bag item has an id field + if (!dataBagItem.id) { + dataBagItem.id = dataBagItemName; + } + + return dataBagItem; +}; + +const getChefSecrets = async (secretSync: TChefSyncWithCredentials): Promise => { + const { + connection, + destinationConfig: { dataBagName, dataBagItemName } + } = secretSync; + + const { serverUrl, userName, privateKey, orgName } = connection.credentials; + + const dataBagItem = await getChefSecretsRaw({ + serverUrl, + orgName, + userName, + privateKey, + dataBagName, + dataBagItemName + }); + + const { id, ...existingSecrets } = dataBagItem; + + // Convert data bag item to key-value pairs + const secrets: ChefSecret[] = []; + Object.entries(existingSecrets).forEach(([key, value]) => { + if (key !== "id" && value !== null && value !== undefined) { + secrets.push({ key, value: String(value) }); + } + }); + + return { id, secrets }; +}; + +const updateChefSecrets = async ( + secretSync: TChefSyncWithCredentials, + id: string, + secrets: Record +) => { + const { + connection, + destinationConfig: { dataBagName, dataBagItemName } + } = secretSync; + + const { serverUrl, userName, privateKey, orgName } = connection.credentials; + + // Chef data bag items must have an 'id' field + const dataBagItemContent: TChefDataBagItemContent = { + id, + ...secrets + }; + + await updateChefDataBagItem({ + serverUrl, + orgName, + userName, + privateKey, + dataBagName, + dataBagItemName, + data: dataBagItemContent + }); +}; + +export const ChefSyncFns = { + async syncSecrets(secretSync: TChefSyncWithCredentials, secretMap: TSecretMap) { + const { + environment, + syncOptions: { disableSecretDeletion, keySchema } + } = secretSync; + + const { id, secrets } = await getChefSecrets(secretSync); + + // Create a map of the existing secrets + const updatedSecretsMap = new Map(secrets.map((secret) => [secret.key, secret.value])); + + // Add/update new secrets + for (const [key, { value }] of Object.entries(secretMap)) { + updatedSecretsMap.set(key, value); + } + + // Delete secrets if not disabled + if (!disableSecretDeletion) { + secrets.forEach((secret) => { + if (!matchesSchema(secret.key, environment?.slug || "", keySchema)) return; + + if (!secretMap[secret.key]) { + updatedSecretsMap.delete(secret.key); + } + }); + } + + // Convert map to object for Chef API + const updatedSecrets = Object.fromEntries(updatedSecretsMap.entries()); + + await updateChefSecrets(secretSync, id, updatedSecrets); + }, + + async getSecrets(secretSync: TChefSyncWithCredentials): Promise { + const { secrets } = await getChefSecrets(secretSync); + + return Object.fromEntries(secrets.map((secret) => [secret.key, { value: secret.value }])); + }, + + async removeSecrets(secretSync: TChefSyncWithCredentials, secretMap: TSecretMap) { + const { id, secrets: existingSecrets } = await getChefSecrets(secretSync); + + const newSecrets = existingSecrets.filter((secret) => !Object.hasOwn(secretMap, secret.key)); + + if (newSecrets.length === existingSecrets.length) { + return; + } + + const updatedSecrets = Object.fromEntries(newSecrets.map((secret) => [secret.key, secret.value])); + + await updateChefSecrets(secretSync, id, updatedSecrets); + } +}; diff --git a/backend/src/services/secret-sync/chef/chef-sync-schemas.ts b/backend/src/services/secret-sync/chef/chef-sync-schemas.ts new file mode 100644 index 000000000..c2e09011e --- /dev/null +++ b/backend/src/services/secret-sync/chef/chef-sync-schemas.ts @@ -0,0 +1,46 @@ +import { z } from "zod"; + +import { SecretSyncs } from "@app/lib/api-docs"; +import { AppConnection } from "@app/services/app-connection/app-connection-enums"; +import { SecretSync } from "@app/services/secret-sync/secret-sync-enums"; +import { + BaseSecretSyncSchema, + GenericCreateSecretSyncFieldsSchema, + GenericUpdateSecretSyncFieldsSchema +} from "@app/services/secret-sync/secret-sync-schemas"; +import { TSyncOptionsConfig } from "@app/services/secret-sync/secret-sync-types"; + +const ChefSyncDestinationConfigSchema = z.object({ + dataBagName: z + .string() + .min(1, "Data Bag Name is required") + .max(256, "Data Bag Name cannot exceed 256 characters") + .describe(SecretSyncs.DESTINATION_CONFIG.CHEF.dataBagName), + dataBagItemName: z + .string() + .min(1, "Data Bag Item Name is required") + .max(256, "Data Bag Item Name cannot exceed 256 characters") + .describe(SecretSyncs.DESTINATION_CONFIG.CHEF.dataBagItemName) +}); + +const ChefSyncOptionsConfig: TSyncOptionsConfig = { canImportSecrets: true }; + +export const ChefSyncSchema = BaseSecretSyncSchema(SecretSync.Chef, ChefSyncOptionsConfig).extend({ + destination: z.literal(SecretSync.Chef), + destinationConfig: ChefSyncDestinationConfigSchema +}); + +export const CreateChefSyncSchema = GenericCreateSecretSyncFieldsSchema(SecretSync.Chef, ChefSyncOptionsConfig).extend({ + destinationConfig: ChefSyncDestinationConfigSchema +}); + +export const UpdateChefSyncSchema = GenericUpdateSecretSyncFieldsSchema(SecretSync.Chef, ChefSyncOptionsConfig).extend({ + destinationConfig: ChefSyncDestinationConfigSchema.optional() +}); + +export const ChefSyncListItemSchema = z.object({ + name: z.literal("Chef"), + connection: z.literal(AppConnection.Chef), + destination: z.literal(SecretSync.Chef), + canImportSecrets: z.literal(true) +}); diff --git a/backend/src/services/secret-sync/chef/chef-sync-types.ts b/backend/src/services/secret-sync/chef/chef-sync-types.ts new file mode 100644 index 000000000..464e0372d --- /dev/null +++ b/backend/src/services/secret-sync/chef/chef-sync-types.ts @@ -0,0 +1,41 @@ +import z from "zod"; + +import { TChefConnection } from "@app/services/app-connection/chef"; + +import { ChefSyncListItemSchema, ChefSyncSchema, CreateChefSyncSchema } from "./chef-sync-schemas"; + +export type TChefSyncListItem = z.infer; + +export type TChefSync = z.infer; + +export type TChefSyncInput = z.infer; + +export type TChefSyncWithCredentials = TChefSync & { + connection: TChefConnection; +}; + +export type TGetChefSecrets = { + serverUrl?: string; + userName: string; + privateKey: string; + orgName: string; + dataBagName: string; + dataBagItemName: string; +}; + +export type TChefSecret = string | number | boolean | null; + +export type TChefDataBagItemContent = { + id: string; + [key: string]: TChefSecret; +}; + +export type TChefSecrets = { + id: string; + secrets: ChefSecret[]; +}; + +export type ChefSecret = { + key: string; + value: string; +}; diff --git a/backend/src/services/secret-sync/chef/index.ts b/backend/src/services/secret-sync/chef/index.ts new file mode 100644 index 000000000..c8599c867 --- /dev/null +++ b/backend/src/services/secret-sync/chef/index.ts @@ -0,0 +1,4 @@ +export * from "./chef-sync-constants"; +export * from "./chef-sync-fns"; +export * from "./chef-sync-schemas"; +export * from "./chef-sync-types"; diff --git a/backend/src/services/secret-sync/github/github-sync-fns.ts b/backend/src/services/secret-sync/github/github-sync-fns.ts index 4b174ca2a..e7116d604 100644 --- a/backend/src/services/secret-sync/github/github-sync-fns.ts +++ b/backend/src/services/secret-sync/github/github-sync-fns.ts @@ -211,10 +211,18 @@ export const GithubSyncFns = { } const { connection } = secretSync; - const token = - connection.method === GitHubConnectionMethod.OAuth - ? connection.credentials.accessToken - : await getGitHubAppAuthToken(connection, gatewayService, gatewayV2Service); + let token: string; + + switch (connection.method) { + case GitHubConnectionMethod.OAuth: + token = connection.credentials.accessToken; + break; + case GitHubConnectionMethod.Pat: + token = connection.credentials.personalAccessToken; + break; + default: + token = await getGitHubAppAuthToken(connection, gatewayService, gatewayV2Service); + } const encryptedSecrets = await getEncryptedSecrets(secretSync, gatewayService, gatewayV2Service); const publicKey = await getPublicKey(secretSync, gatewayService, gatewayV2Service, token); @@ -269,10 +277,18 @@ export const GithubSyncFns = { const secretMap = Object.fromEntries(Object.entries(ogSecretMap).map(([i, v]) => [i.toUpperCase(), v])); const { connection } = secretSync; - const token = - connection.method === GitHubConnectionMethod.OAuth - ? connection.credentials.accessToken - : await getGitHubAppAuthToken(connection, gatewayService, gatewayV2Service); + let token: string; + + switch (connection.method) { + case GitHubConnectionMethod.OAuth: + token = connection.credentials.accessToken; + break; + case GitHubConnectionMethod.Pat: + token = connection.credentials.personalAccessToken; + break; + default: + token = await getGitHubAppAuthToken(connection, gatewayService, gatewayV2Service); + } const encryptedSecrets = await getEncryptedSecrets(secretSync, gatewayService, gatewayV2Service); diff --git a/backend/src/services/secret-sync/northflank/index.ts b/backend/src/services/secret-sync/northflank/index.ts new file mode 100644 index 000000000..7fab276cf --- /dev/null +++ b/backend/src/services/secret-sync/northflank/index.ts @@ -0,0 +1,4 @@ +export * from "./northflank-sync-constants"; +export * from "./northflank-sync-fns"; +export * from "./northflank-sync-schemas"; +export * from "./northflank-sync-types"; diff --git a/backend/src/services/secret-sync/northflank/northflank-sync-constants.ts b/backend/src/services/secret-sync/northflank/northflank-sync-constants.ts new file mode 100644 index 000000000..d4b851217 --- /dev/null +++ b/backend/src/services/secret-sync/northflank/northflank-sync-constants.ts @@ -0,0 +1,10 @@ +import { AppConnection } from "@app/services/app-connection/app-connection-enums"; +import { SecretSync } from "@app/services/secret-sync/secret-sync-enums"; +import { TSecretSyncListItem } from "@app/services/secret-sync/secret-sync-types"; + +export const NORTHFLANK_SYNC_LIST_OPTION: TSecretSyncListItem = { + name: "Northflank", + destination: SecretSync.Northflank, + connection: AppConnection.Northflank, + canImportSecrets: true +}; diff --git a/backend/src/services/secret-sync/northflank/northflank-sync-fns.ts b/backend/src/services/secret-sync/northflank/northflank-sync-fns.ts new file mode 100644 index 000000000..396aa9ac8 --- /dev/null +++ b/backend/src/services/secret-sync/northflank/northflank-sync-fns.ts @@ -0,0 +1,165 @@ +import { AxiosError } from "axios"; + +import { request } from "@app/lib/config/request"; +import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns"; +import { TSecretMap } from "@app/services/secret-sync/secret-sync-types"; + +import { SecretSyncError } from "../secret-sync-errors"; +import { TNorthflankSyncWithCredentials } from "./northflank-sync-types"; + +const NORTHFLANK_API_URL = "https://api.northflank.com"; + +const buildNorthflankAPIErrorMessage = (error: unknown): string => { + let errorMessage = "Northflank API returned an error."; + + if (error && typeof error === "object" && "response" in error) { + const axiosError = error as AxiosError; + + if (axiosError.response?.data) { + // This is the shape of the error response from the Northflank API + const responseData = axiosError.response.data as { + error?: { message?: string; details?: Record }; + message?: string; + }; + const errorParts = []; + + if (responseData.error?.message) { + errorParts.push(responseData.error.message); + } else if (responseData.message) { + errorParts.push(responseData.message); + } + + if (responseData.error?.details) { + const { details } = responseData.error; + + // Flatten the details object into a string + Object.entries(details).forEach(([field, fieldErrors]) => { + if (Array.isArray(fieldErrors)) { + fieldErrors.forEach((fieldError) => errorParts.push(`${field}: ${fieldError}`)); + } else { + errorParts.push(`${field}: ${String(fieldErrors)}`); + } + }); + } + + errorMessage += ` ${errorParts.join(". ")}`; + } + } + + return errorMessage; +}; + +const getNorthflankSecrets = async (secretSync: TNorthflankSyncWithCredentials): Promise> => { + const { + destinationConfig: { projectId, secretGroupId }, + connection: { + credentials: { apiToken } + } + } = secretSync; + + try { + const { + data: { + data: { + secrets: { variables } + } + } + } = await request.get<{ + data: { + secrets: { + variables: Record; + }; + }; + }>(`${NORTHFLANK_API_URL}/v1/projects/${projectId}/secrets/${secretGroupId}/details`, { + headers: { + Authorization: `Bearer ${apiToken}`, + Accept: "application/json" + } + }); + + return variables; + } catch (error: unknown) { + throw new SecretSyncError({ + error, + message: `Failed to fetch Northflank secrets. ${buildNorthflankAPIErrorMessage(error)}` + }); + } +}; + +const updateNorthflankSecrets = async ( + secretSync: TNorthflankSyncWithCredentials, + variables: Record +): Promise => { + const { + destinationConfig: { projectId, secretGroupId }, + connection: { + credentials: { apiToken } + } + } = secretSync; + + try { + await request.patch( + `${NORTHFLANK_API_URL}/v1/projects/${projectId}/secrets/${secretGroupId}`, + { + secrets: { + variables + } + }, + { + headers: { + Authorization: `Bearer ${apiToken}`, + Accept: "application/json" + } + } + ); + } catch (error: unknown) { + throw new SecretSyncError({ + error, + message: `Failed to update Northflank secrets. ${buildNorthflankAPIErrorMessage(error)}` + }); + } +}; + +export const NorthflankSyncFns = { + syncSecrets: async (secretSync: TNorthflankSyncWithCredentials, secretMap: TSecretMap): Promise => { + const northflankSecrets = await getNorthflankSecrets(secretSync); + + const updatedVariables: Record = {}; + + for (const [key, value] of Object.entries(northflankSecrets)) { + const shouldKeep = + !secretMap[key] && // this prevents duplicates from infisical secrets, because we add all of them to the updateVariables in the next loop + (secretSync.syncOptions.disableSecretDeletion || + !matchesSchema(key, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema)); + + if (shouldKeep) { + updatedVariables[key] = value; + } + } + + for (const [key, { value }] of Object.entries(secretMap)) { + updatedVariables[key] = value; + } + + await updateNorthflankSecrets(secretSync, updatedVariables); + }, + + getSecrets: async (secretSync: TNorthflankSyncWithCredentials): Promise => { + const northflankSecrets = await getNorthflankSecrets(secretSync); + return Object.fromEntries(Object.entries(northflankSecrets).map(([key, value]) => [key, { value }])); + }, + + removeSecrets: async (secretSync: TNorthflankSyncWithCredentials, secretMap: TSecretMap): Promise => { + const northflankSecrets = await getNorthflankSecrets(secretSync); + + const updatedVariables: Record = {}; + + for (const [key, value] of Object.entries(northflankSecrets)) { + if (!(key in secretMap)) { + updatedVariables[key] = value; + } + } + + await updateNorthflankSecrets(secretSync, updatedVariables); + } +}; diff --git a/backend/src/services/secret-sync/northflank/northflank-sync-schemas.ts b/backend/src/services/secret-sync/northflank/northflank-sync-schemas.ts new file mode 100644 index 000000000..55cdeae23 --- /dev/null +++ b/backend/src/services/secret-sync/northflank/northflank-sync-schemas.ts @@ -0,0 +1,54 @@ +import { z } from "zod"; + +import { SecretSyncs } from "@app/lib/api-docs"; +import { AppConnection } from "@app/services/app-connection/app-connection-enums"; +import { SecretSync } from "@app/services/secret-sync/secret-sync-enums"; +import { + BaseSecretSyncSchema, + GenericCreateSecretSyncFieldsSchema, + GenericUpdateSecretSyncFieldsSchema +} from "@app/services/secret-sync/secret-sync-schemas"; +import { TSyncOptionsConfig } from "@app/services/secret-sync/secret-sync-types"; + +const NorthflankSyncDestinationConfigSchema = z.object({ + projectId: z + .string() + .trim() + .min(1, "Project ID is required") + .describe(SecretSyncs.DESTINATION_CONFIG.NORTHFLANK.projectId), + projectName: z.string().trim().optional().describe(SecretSyncs.DESTINATION_CONFIG.NORTHFLANK.projectName), + secretGroupId: z + .string() + .trim() + .min(1, "Secret Group ID is required") + .describe(SecretSyncs.DESTINATION_CONFIG.NORTHFLANK.secretGroupId), + secretGroupName: z.string().trim().optional().describe(SecretSyncs.DESTINATION_CONFIG.NORTHFLANK.secretGroupName) +}); + +const NorthflankSyncOptionsConfig: TSyncOptionsConfig = { canImportSecrets: true }; + +export const NorthflankSyncSchema = BaseSecretSyncSchema(SecretSync.Northflank, NorthflankSyncOptionsConfig).extend({ + destination: z.literal(SecretSync.Northflank), + destinationConfig: NorthflankSyncDestinationConfigSchema +}); + +export const CreateNorthflankSyncSchema = GenericCreateSecretSyncFieldsSchema( + SecretSync.Northflank, + NorthflankSyncOptionsConfig +).extend({ + destinationConfig: NorthflankSyncDestinationConfigSchema +}); + +export const UpdateNorthflankSyncSchema = GenericUpdateSecretSyncFieldsSchema( + SecretSync.Northflank, + NorthflankSyncOptionsConfig +).extend({ + destinationConfig: NorthflankSyncDestinationConfigSchema.optional() +}); + +export const NorthflankSyncListItemSchema = z.object({ + name: z.literal("Northflank"), + connection: z.literal(AppConnection.Northflank), + destination: z.literal(SecretSync.Northflank), + canImportSecrets: z.literal(true) +}); diff --git a/backend/src/services/secret-sync/northflank/northflank-sync-types.ts b/backend/src/services/secret-sync/northflank/northflank-sync-types.ts new file mode 100644 index 000000000..019ae2843 --- /dev/null +++ b/backend/src/services/secret-sync/northflank/northflank-sync-types.ts @@ -0,0 +1,19 @@ +import { z } from "zod"; + +import { TNorthflankConnection } from "@app/services/app-connection/northflank"; + +import { + CreateNorthflankSyncSchema, + NorthflankSyncListItemSchema, + NorthflankSyncSchema +} from "./northflank-sync-schemas"; + +export type TNorthflankSyncListItem = z.infer; + +export type TNorthflankSync = z.infer; + +export type TNorthflankSyncInput = z.infer; + +export type TNorthflankSyncWithCredentials = TNorthflankSync & { + connection: TNorthflankConnection; +}; diff --git a/backend/src/services/secret-sync/secret-sync-enums.ts b/backend/src/services/secret-sync/secret-sync-enums.ts index 235b3db3a..835a314ca 100644 --- a/backend/src/services/secret-sync/secret-sync-enums.ts +++ b/backend/src/services/secret-sync/secret-sync-enums.ts @@ -28,8 +28,10 @@ export enum SecretSync { Checkly = "checkly", DigitalOceanAppPlatform = "digital-ocean-app-platform", Netlify = "netlify", + Northflank = "northflank", Bitbucket = "bitbucket", - LaravelForge = "laravel-forge" + LaravelForge = "laravel-forge", + Chef = "chef" } export enum SecretSyncInitialSyncBehavior { diff --git a/backend/src/services/secret-sync/secret-sync-fns.ts b/backend/src/services/secret-sync/secret-sync-fns.ts index 85fc27250..77845535f 100644 --- a/backend/src/services/secret-sync/secret-sync-fns.ts +++ b/backend/src/services/secret-sync/secret-sync-fns.ts @@ -34,6 +34,7 @@ import { BITBUCKET_SYNC_LIST_OPTION, BitbucketSyncFns } from "./bitbucket"; import { CAMUNDA_SYNC_LIST_OPTION, camundaSyncFactory } from "./camunda"; import { CHECKLY_SYNC_LIST_OPTION } from "./checkly/checkly-sync-constants"; import { ChecklySyncFns } from "./checkly/checkly-sync-fns"; +import { CHEF_SYNC_LIST_OPTION, ChefSyncFns } from "./chef"; import { CLOUDFLARE_PAGES_SYNC_LIST_OPTION } from "./cloudflare-pages/cloudflare-pages-constants"; import { CloudflarePagesSyncFns } from "./cloudflare-pages/cloudflare-pages-fns"; import { CLOUDFLARE_WORKERS_SYNC_LIST_OPTION, CloudflareWorkersSyncFns } from "./cloudflare-workers"; @@ -49,9 +50,9 @@ import { HC_VAULT_SYNC_LIST_OPTION, HCVaultSyncFns } from "./hc-vault"; import { HEROKU_SYNC_LIST_OPTION, HerokuSyncFns } from "./heroku"; import { HUMANITEC_SYNC_LIST_OPTION } from "./humanitec"; import { HumanitecSyncFns } from "./humanitec/humanitec-sync-fns"; -import { LARAVEL_FORGE_SYNC_LIST_OPTION } from "./laravel-forge"; -import { LaravelForgeSyncFns } from "./laravel-forge/laravel-forge-sync-fns"; +import { LARAVEL_FORGE_SYNC_LIST_OPTION, LaravelForgeSyncFns } from "./laravel-forge"; import { NETLIFY_SYNC_LIST_OPTION, NetlifySyncFns } from "./netlify"; +import { NORTHFLANK_SYNC_LIST_OPTION, NorthflankSyncFns } from "./northflank"; import { RAILWAY_SYNC_LIST_OPTION } from "./railway/railway-sync-constants"; import { RailwaySyncFns } from "./railway/railway-sync-fns"; import { RENDER_SYNC_LIST_OPTION, RenderSyncFns } from "./render"; @@ -93,8 +94,10 @@ const SECRET_SYNC_LIST_OPTIONS: Record = { [SecretSync.Checkly]: CHECKLY_SYNC_LIST_OPTION, [SecretSync.DigitalOceanAppPlatform]: DIGITAL_OCEAN_APP_PLATFORM_SYNC_LIST_OPTION, [SecretSync.Netlify]: NETLIFY_SYNC_LIST_OPTION, + [SecretSync.Northflank]: NORTHFLANK_SYNC_LIST_OPTION, [SecretSync.Bitbucket]: BITBUCKET_SYNC_LIST_OPTION, - [SecretSync.LaravelForge]: LARAVEL_FORGE_SYNC_LIST_OPTION + [SecretSync.LaravelForge]: LARAVEL_FORGE_SYNC_LIST_OPTION, + [SecretSync.Chef]: CHEF_SYNC_LIST_OPTION }; export const listSecretSyncOptions = () => { @@ -278,10 +281,14 @@ export const SecretSyncFns = { return DigitalOceanAppPlatformSyncFns.syncSecrets(secretSync, schemaSecretMap); case SecretSync.Netlify: return NetlifySyncFns.syncSecrets(secretSync, schemaSecretMap); + case SecretSync.Northflank: + return NorthflankSyncFns.syncSecrets(secretSync, schemaSecretMap); case SecretSync.Bitbucket: return BitbucketSyncFns.syncSecrets(secretSync, schemaSecretMap); case SecretSync.LaravelForge: return LaravelForgeSyncFns.syncSecrets(secretSync, schemaSecretMap); + case SecretSync.Chef: + return ChefSyncFns.syncSecrets(secretSync, schemaSecretMap); default: throw new Error( `Unhandled sync destination for sync secrets fns: ${(secretSync as TSecretSyncWithCredentials).destination}` @@ -395,12 +402,18 @@ export const SecretSyncFns = { case SecretSync.Netlify: secretMap = await NetlifySyncFns.getSecrets(secretSync); break; + case SecretSync.Northflank: + secretMap = await NorthflankSyncFns.getSecrets(secretSync); + break; case SecretSync.Bitbucket: secretMap = await BitbucketSyncFns.getSecrets(secretSync); break; case SecretSync.LaravelForge: secretMap = await LaravelForgeSyncFns.getSecrets(secretSync); break; + case SecretSync.Chef: + secretMap = await ChefSyncFns.getSecrets(secretSync); + break; default: throw new Error( `Unhandled sync destination for get secrets fns: ${(secretSync as TSecretSyncWithCredentials).destination}` @@ -492,10 +505,14 @@ export const SecretSyncFns = { return DigitalOceanAppPlatformSyncFns.removeSecrets(secretSync, schemaSecretMap); case SecretSync.Netlify: return NetlifySyncFns.removeSecrets(secretSync, schemaSecretMap); + case SecretSync.Northflank: + return NorthflankSyncFns.removeSecrets(secretSync, schemaSecretMap); case SecretSync.Bitbucket: return BitbucketSyncFns.removeSecrets(secretSync, schemaSecretMap); case SecretSync.LaravelForge: return LaravelForgeSyncFns.removeSecrets(secretSync, schemaSecretMap); + case SecretSync.Chef: + return ChefSyncFns.removeSecrets(secretSync, schemaSecretMap); default: throw new Error( `Unhandled sync destination for remove secrets fns: ${(secretSync as TSecretSyncWithCredentials).destination}` diff --git a/backend/src/services/secret-sync/secret-sync-maps.ts b/backend/src/services/secret-sync/secret-sync-maps.ts index 0ec8aede0..86cb189c3 100644 --- a/backend/src/services/secret-sync/secret-sync-maps.ts +++ b/backend/src/services/secret-sync/secret-sync-maps.ts @@ -32,8 +32,10 @@ export const SECRET_SYNC_NAME_MAP: Record = { [SecretSync.Checkly]: "Checkly", [SecretSync.DigitalOceanAppPlatform]: "Digital Ocean App Platform", [SecretSync.Netlify]: "Netlify", + [SecretSync.Northflank]: "Northflank", [SecretSync.Bitbucket]: "Bitbucket", - [SecretSync.LaravelForge]: "Laravel Forge" + [SecretSync.LaravelForge]: "Laravel Forge", + [SecretSync.Chef]: "Chef" }; export const SECRET_SYNC_CONNECTION_MAP: Record = { @@ -66,8 +68,10 @@ export const SECRET_SYNC_CONNECTION_MAP: Record = { [SecretSync.Checkly]: AppConnection.Checkly, [SecretSync.DigitalOceanAppPlatform]: AppConnection.DigitalOcean, [SecretSync.Netlify]: AppConnection.Netlify, + [SecretSync.Northflank]: AppConnection.Northflank, [SecretSync.Bitbucket]: AppConnection.Bitbucket, - [SecretSync.LaravelForge]: AppConnection.LaravelForge + [SecretSync.LaravelForge]: AppConnection.LaravelForge, + [SecretSync.Chef]: AppConnection.Chef }; export const SECRET_SYNC_PLAN_MAP: Record = { @@ -100,8 +104,10 @@ export const SECRET_SYNC_PLAN_MAP: Record = { [SecretSync.Checkly]: SecretSyncPlanType.Regular, [SecretSync.DigitalOceanAppPlatform]: SecretSyncPlanType.Regular, [SecretSync.Netlify]: SecretSyncPlanType.Regular, + [SecretSync.Northflank]: SecretSyncPlanType.Regular, [SecretSync.Bitbucket]: SecretSyncPlanType.Regular, - [SecretSync.LaravelForge]: SecretSyncPlanType.Regular + [SecretSync.LaravelForge]: SecretSyncPlanType.Regular, + [SecretSync.Chef]: SecretSyncPlanType.Regular }; export const SECRET_SYNC_SKIP_FIELDS_MAP: Record = { @@ -143,8 +149,10 @@ export const SECRET_SYNC_SKIP_FIELDS_MAP: Record = { [SecretSync.Checkly]: ["groupName", "accountName"], [SecretSync.DigitalOceanAppPlatform]: ["appName"], [SecretSync.Netlify]: ["accountName", "siteName"], + [SecretSync.Northflank]: [], [SecretSync.Bitbucket]: [], - [SecretSync.LaravelForge]: [] + [SecretSync.LaravelForge]: [], + [SecretSync.Chef]: [] }; const defaultDuplicateCheck: DestinationDuplicateCheckFn = () => true; @@ -203,6 +211,8 @@ export const DESTINATION_DUPLICATE_CHECK_MAP: Record; permissionService: Pick; + projectDAL: Pick; + orgDAL: Pick; projectBotService: Pick; folderDAL: Pick; keyStore: Pick; @@ -68,6 +72,8 @@ export const secretSyncServiceFactory = ({ secretImportDAL, permissionService, appConnectionService, + projectDAL, + orgDAL, projectBotService, secretSyncQueue, keyStore, @@ -225,6 +231,61 @@ export const secretSyncServiceFactory = ({ return secretSync as TSecretSync; }; + const checkDuplicateDestination = async ( + { destination, destinationConfig, excludeSyncId, projectId }: TCheckDuplicateDestinationDTO, + actor: OrgServiceActor + ) => { + const skipFields = SECRET_SYNC_SKIP_FIELDS_MAP[destination]; + const { permission } = await permissionService.getProjectPermission({ + actor: actor.type, + actorId: actor.id, + actorAuthMethod: actor.authMethod, + actorOrgId: actor.orgId, + actionProjectType: ActionProjectType.SecretManager, + projectId + }); + + ForbiddenError.from(permission).throwUnlessCan( + ProjectPermissionSecretSyncActions.Read, + ProjectPermissionSub.SecretSyncs + ); + + if (!destinationConfig || Object.keys(destinationConfig).length === 0) { + return { hasDuplicate: false, duplicateProjectId: undefined }; + } + + try { + const existingSyncs = await secretSyncDAL.findByDestinationAndOrgId(destination, actor.orgId); + + const duplicates = existingSyncs.filter((sync) => { + if (sync.id === excludeSyncId) { + return false; + } + + try { + const baseFieldsMatch = deepEqualSkipFields(sync.destinationConfig, destinationConfig, skipFields); + if (baseFieldsMatch) { + return DESTINATION_DUPLICATE_CHECK_MAP[destination]( + sync.destinationConfig as Record, + destinationConfig + ); + } + return false; + } catch { + return false; + } + }); + + const hasDuplicate = duplicates.length > 0; + return { + hasDuplicate, + duplicateProjectId: hasDuplicate ? duplicates[0].projectId : undefined + }; + } catch (error) { + return { hasDuplicate: false, duplicateProjectId: undefined }; + } + }; + const createSecretSync = async ( { projectId, secretPath, environment, ...params }: TCreateSecretSyncDTO, actor: OrgServiceActor @@ -271,6 +332,30 @@ export const secretSyncServiceFactory = ({ message: `Could not find folder with path "${secretPath}" in environment "${environment}" for project with ID "${projectId}"` }); + const project = await projectDAL.findById(projectId); + if (!project) { + throw new NotFoundError({ message: "Project not found" }); + } + + const organization = await orgDAL.findById(project.orgId); + if (organization?.blockDuplicateSecretSyncDestinations) { + const duplicateCheck = await checkDuplicateDestination( + { + destination: params.destination, + destinationConfig: params.destinationConfig, + projectId + }, + actor + ); + if (duplicateCheck.hasDuplicate) { + throw new BadRequestError({ + message: `A secret sync with this destination already exists${ + duplicateCheck.duplicateProjectId ? ` in project ${duplicateCheck.duplicateProjectId}` : "" + }.` + }); + } + } + const destinationApp = SECRET_SYNC_CONNECTION_MAP[params.destination]; // validates permission to connect and app is valid for sync destination @@ -369,6 +454,33 @@ export const secretSyncServiceFactory = ({ let { folderId } = secretSync; + if (params.destinationConfig) { + const project = await projectDAL.findById(secretSync.projectId); + if (!project) { + throw new NotFoundError({ message: "Project not found" }); + } + const organization = await orgDAL.findById(project.orgId); + + if (organization?.blockDuplicateSecretSyncDestinations) { + const duplicateCheck = await checkDuplicateDestination( + { + destination, + destinationConfig: params.destinationConfig, + projectId: secretSync.projectId, + excludeSyncId: secretSync.id + }, + actor + ); + if (duplicateCheck.hasDuplicate) { + throw new BadRequestError({ + message: `A secret sync with this destination already exists${ + duplicateCheck.duplicateProjectId ? ` in project ${duplicateCheck.duplicateProjectId}` : "" + }.` + }); + } + } + } + if (params.connectionId) { const destinationApp = SECRET_SYNC_CONNECTION_MAP[secretSync.destination as SecretSync]; @@ -703,61 +815,6 @@ export const secretSyncServiceFactory = ({ return updatedSecretSync as TSecretSync; }; - const checkDuplicateDestination = async ( - { destination, destinationConfig, excludeSyncId, projectId }: TCheckDuplicateDestinationDTO, - actor: OrgServiceActor - ) => { - const skipFields = SECRET_SYNC_SKIP_FIELDS_MAP[destination]; - const { permission } = await permissionService.getProjectPermission({ - actor: actor.type, - actorId: actor.id, - actorAuthMethod: actor.authMethod, - actorOrgId: actor.orgId, - actionProjectType: ActionProjectType.SecretManager, - projectId - }); - - ForbiddenError.from(permission).throwUnlessCan( - ProjectPermissionSecretSyncActions.Read, - ProjectPermissionSub.SecretSyncs - ); - - if (!destinationConfig || Object.keys(destinationConfig).length === 0) { - return { hasDuplicate: false, duplicateProjectId: undefined }; - } - - try { - const existingSyncs = await secretSyncDAL.findByDestinationAndOrgId(destination, actor.orgId); - - const duplicates = existingSyncs.filter((sync) => { - if (sync.id === excludeSyncId) { - return false; - } - - try { - const baseFieldsMatch = deepEqualSkipFields(sync.destinationConfig, destinationConfig, skipFields); - if (baseFieldsMatch) { - return DESTINATION_DUPLICATE_CHECK_MAP[destination]( - sync.destinationConfig as Record, - destinationConfig - ); - } - return false; - } catch { - return false; - } - }); - - const hasDuplicate = duplicates.length > 0; - return { - hasDuplicate, - duplicateProjectId: hasDuplicate ? duplicates[0].projectId : undefined - }; - } catch (error) { - return { hasDuplicate: false, duplicateProjectId: undefined }; - } - }; - return { listSecretSyncOptions, listSecretSyncsByProjectId, diff --git a/backend/src/services/secret-sync/secret-sync-types.ts b/backend/src/services/secret-sync/secret-sync-types.ts index 9719f0a9e..d6ef0b3fc 100644 --- a/backend/src/services/secret-sync/secret-sync-types.ts +++ b/backend/src/services/secret-sync/secret-sync-types.ts @@ -21,6 +21,7 @@ import { TCamundaSyncListItem, TCamundaSyncWithCredentials } from "@app/services/secret-sync/camunda"; +import { TChefSync, TChefSyncInput, TChefSyncListItem, TChefSyncWithCredentials } from "@app/services/secret-sync/chef"; import { TDatabricksSync, TDatabricksSyncInput, @@ -124,6 +125,12 @@ import { TLaravelForgeSyncWithCredentials } from "./laravel-forge"; import { TNetlifySync, TNetlifySyncInput, TNetlifySyncListItem, TNetlifySyncWithCredentials } from "./netlify"; +import { + TNorthflankSync, + TNorthflankSyncInput, + TNorthflankSyncListItem, + TNorthflankSyncWithCredentials +} from "./northflank"; import { TRailwaySync, TRailwaySyncInput, @@ -163,6 +170,7 @@ export type TSecretSync = | TGitHubSync | TGcpSync | TAzureKeyVaultSync + | TChefSync | TAzureAppConfigurationSync | TAzureDevOpsSync | TDatabricksSync @@ -187,6 +195,7 @@ export type TSecretSync = | TChecklySync | TSupabaseSync | TNetlifySync + | TNorthflankSync | TBitbucketSync; export type TSecretSyncWithCredentials = @@ -195,6 +204,7 @@ export type TSecretSyncWithCredentials = | TGitHubSyncWithCredentials | TGcpSyncWithCredentials | TAzureKeyVaultSyncWithCredentials + | TChefSyncWithCredentials | TAzureAppConfigurationSyncWithCredentials | TAzureDevOpsSyncWithCredentials | TDatabricksSyncWithCredentials @@ -219,6 +229,7 @@ export type TSecretSyncWithCredentials = | TSupabaseSyncWithCredentials | TDigitalOceanAppPlatformSyncWithCredentials | TNetlifySyncWithCredentials + | TNorthflankSyncWithCredentials | TBitbucketSyncWithCredentials | TLaravelForgeSyncWithCredentials; @@ -228,6 +239,7 @@ export type TSecretSyncInput = | TGitHubSyncInput | TGcpSyncInput | TAzureKeyVaultSyncInput + | TChefSyncInput | TAzureAppConfigurationSyncInput | TAzureDevOpsSyncInput | TDatabricksSyncInput @@ -252,6 +264,7 @@ export type TSecretSyncInput = | TSupabaseSyncInput | TDigitalOceanAppPlatformSyncInput | TNetlifySyncInput + | TNorthflankSyncInput | TBitbucketSyncInput | TLaravelForgeSyncInput; @@ -261,6 +274,7 @@ export type TSecretSyncListItem = | TGitHubSyncListItem | TGcpSyncListItem | TAzureKeyVaultSyncListItem + | TChefSyncListItem | TAzureAppConfigurationSyncListItem | TAzureDevOpsSyncListItem | TDatabricksSyncListItem @@ -286,6 +300,7 @@ export type TSecretSyncListItem = | TSupabaseSyncListItem | TDigitalOceanAppPlatformSyncListItem | TNetlifySyncListItem + | TNorthflankSyncListItem | TBitbucketSyncListItem; export type TSyncOptionsConfig = { diff --git a/backend/src/services/secret-tag/secret-tag-service.ts b/backend/src/services/secret-tag/secret-tag-service.ts index 8a08c44dd..58913e08c 100644 --- a/backend/src/services/secret-tag/secret-tag-service.ts +++ b/backend/src/services/secret-tag/secret-tag-service.ts @@ -35,7 +35,7 @@ export const secretTagServiceFactory = ({ secretTagDAL, permissionService }: TSe ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Create, ProjectPermissionSub.Tags); const existingTag = await secretTagDAL.findOne({ slug, projectId }); - if (existingTag) throw new BadRequestError({ message: "Tag already exist" }); + if (existingTag) throw new BadRequestError({ message: "Tag already exists" }); const newTag = await secretTagDAL.create({ projectId, @@ -53,7 +53,7 @@ export const secretTagServiceFactory = ({ secretTagDAL, permissionService }: TSe if (slug) { const existingTag = await secretTagDAL.findOne({ slug, projectId: tag.projectId }); - if (existingTag && existingTag.id !== tag.id) throw new BadRequestError({ message: "Tag already exist" }); + if (existingTag && existingTag.id !== tag.id) throw new BadRequestError({ message: "Tag already exists" }); } const { permission } = await permissionService.getProjectPermission({ diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts index 579b19b19..559c86843 100644 --- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts +++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts @@ -34,6 +34,7 @@ import { diff, groupBy } from "@app/lib/fn"; import { setKnexStringValue } from "@app/lib/knex"; import { logger } from "@app/lib/logger"; import { alphaNumericNanoId } from "@app/lib/nanoid"; +import { recordSecretReadMetric } from "@app/lib/telemetry/metrics"; import { ActorType } from "../auth/auth-type"; import { TCommitResourceChangeDTO, TFolderCommitServiceFactory } from "../folder-commit/folder-commit-service"; @@ -282,7 +283,7 @@ export const secretV2BridgeServiceFactory = ({ folderId }); if (inputSecret.type === SecretType.Shared && doesSecretExist) - throw new BadRequestError({ message: "Secret already exist" }); + throw new BadRequestError({ message: "Secret already exists" }); // if user creating personal check its shared also exist if (inputSecret.type === SecretType.Personal && !doesSecretExist) { @@ -527,7 +528,7 @@ export const secretV2BridgeServiceFactory = ({ type: SecretType.Shared, folderId }); - if (doesNewNameSecretExist) throw new BadRequestError({ message: "Secret with the new name already exist" }); + if (doesNewNameSecretExist) throw new BadRequestError({ message: "Secret with the new name already exists" }); ForbiddenError.from(permission).throwUnlessCan( ProjectPermissionSecretActions.Edit, subject(ProjectPermissionSub.Secrets, { @@ -1052,6 +1053,11 @@ export const secretV2BridgeServiceFactory = ({ }); throwIfMissingSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.DescribeSecret); + recordSecretReadMetric({ + environment, + secretPath: path + }); + const cachedSecretDalVersion = await keyStore.pgGetIntItem(SecretServiceCacheKeys.getSecretDalVersion(projectId)); const secretDalVersion = Number(cachedSecretDalVersion || 0); const cacheKey = SecretServiceCacheKeys.getSecretsOfServiceLayer(projectId, secretDalVersion, { @@ -1482,6 +1488,12 @@ export const secretV2BridgeServiceFactory = ({ secretTags: (secret?.tags || []).map((el) => el.slug) }); + recordSecretReadMetric({ + environment, + secretPath: path, + name: secretName + }); + // this will throw if the user doesn't have read value permission no matter what // because if its an expansion, it will fully depend on the value. const { expandSecretReferences } = expandSecretReferencesFactory({ @@ -1674,7 +1686,7 @@ export const secretV2BridgeServiceFactory = ({ } }); if (secrets.length) - throw new BadRequestError({ message: `Secret already exist: ${secrets.map((el) => el.key).join(",")}` }); + throw new BadRequestError({ message: `Secret already exists: ${secrets.map((el) => el.key).join(",")}` }); const project = await projectDAL.findById(projectId); await scanSecretPolicyViolations(projectId, secretPath, inputSecrets, project.secretDetectionIgnoreValues || []); diff --git a/backend/src/services/secret/secret-fns.ts b/backend/src/services/secret/secret-fns.ts index 3b97f5891..820260d29 100644 --- a/backend/src/services/secret/secret-fns.ts +++ b/backend/src/services/secret/secret-fns.ts @@ -525,7 +525,7 @@ export const fnSecretBlindIndexCheck = async ({ ); if (isNew) { - if (secrets.length) throw new BadRequestError({ message: "Secret already exist" }); + if (secrets.length) throw new BadRequestError({ message: "Secret already exists" }); } else { const secretKeysInDB = unique(secrets, (el) => el.secretBlindIndex as string).map( (el) => blindIndex2KeyName[el.secretBlindIndex as string] @@ -819,7 +819,7 @@ export const createManySecretsRawFnFactory = ({ ); if (secretsStoredInDB.length) throw new BadRequestError({ - message: `Secret already exist: ${secretsStoredInDB.map((el) => el.key).join(",")}` + message: `Secret already exists: ${secretsStoredInDB.map((el) => el.key).join(",")}` }); const inputSecrets = secrets.map((secret) => { diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.ts index 723cd368c..9ba1df47d 100644 --- a/backend/src/services/secret/secret-service.ts +++ b/backend/src/services/secret/secret-service.ts @@ -2751,7 +2751,7 @@ export const secretServiceFactory = ({ const existingSecretTags = await secretDAL.getSecretTags(secret.id); if (existingSecretTags.some((tag) => tagSlugs.includes(tag.slug))) { - throw new BadRequestError({ message: "One or more tags already exist on the secret" }); + throw new BadRequestError({ message: "One or more tags already exists on the secret" }); } const combinedTags = new Set([...existingSecretTags.map((tag) => tag.id), ...tags.map((el) => el.id)]); diff --git a/backend/vitest.e2e.config.ts b/backend/vitest.e2e.config.mts similarity index 86% rename from backend/vitest.e2e.config.ts rename to backend/vitest.e2e.config.mts index bb7ae8087..83554b818 100644 --- a/backend/vitest.e2e.config.ts +++ b/backend/vitest.e2e.config.mts @@ -12,13 +12,16 @@ export default defineConfig({ }, environment: "./e2e-test/vitest-environment-knex.ts", include: ["./e2e-test/**/*.spec.ts"], + pool: "threads", poolOptions: { threads: { - singleThread: true, - useAtomics: true, - isolate: false + minThreads: 1, + maxThreads: 1, + singleThread: true } }, + fileParallelism: false, + alias: { "./license-fns": path.resolve(__dirname, "./src/ee/services/license/__mocks__/license-fns") } diff --git a/backend/vitest.unit.config.ts b/backend/vitest.unit.config.mts similarity index 100% rename from backend/vitest.unit.config.ts rename to backend/vitest.unit.config.mts diff --git a/docs/api-reference/endpoints/app-connections/chef/available.mdx b/docs/api-reference/endpoints/app-connections/chef/available.mdx new file mode 100644 index 000000000..033723489 --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/chef/available.mdx @@ -0,0 +1,4 @@ +--- +title: "Available" +openapi: "GET /api/v1/app-connections/chef/available" +--- diff --git a/docs/api-reference/endpoints/app-connections/chef/create.mdx b/docs/api-reference/endpoints/app-connections/chef/create.mdx new file mode 100644 index 000000000..359b86036 --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/chef/create.mdx @@ -0,0 +1,10 @@ +--- +title: "Create" +openapi: "POST /api/v1/app-connections/chef" +--- + + + Check out the configuration docs for [Chef + Connections](/integrations/app-connections/chef) to learn how to obtain the + required credentials. + diff --git a/docs/api-reference/endpoints/app-connections/chef/delete.mdx b/docs/api-reference/endpoints/app-connections/chef/delete.mdx new file mode 100644 index 000000000..43a67f01c --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/chef/delete.mdx @@ -0,0 +1,4 @@ +--- +title: "Delete" +openapi: "DELETE /api/v1/app-connections/chef/{connectionId}" +--- diff --git a/docs/api-reference/endpoints/app-connections/chef/get-by-id.mdx b/docs/api-reference/endpoints/app-connections/chef/get-by-id.mdx new file mode 100644 index 000000000..8461cc553 --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/chef/get-by-id.mdx @@ -0,0 +1,4 @@ +--- +title: "Get by ID" +openapi: "GET /api/v1/app-connections/chef/{connectionId}" +--- diff --git a/docs/api-reference/endpoints/app-connections/chef/get-by-name.mdx b/docs/api-reference/endpoints/app-connections/chef/get-by-name.mdx new file mode 100644 index 000000000..f1042abdb --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/chef/get-by-name.mdx @@ -0,0 +1,4 @@ +--- +title: "Get by Name" +openapi: "GET /api/v1/app-connections/chef/connection-name/{connectionName}" +--- diff --git a/docs/api-reference/endpoints/app-connections/chef/list.mdx b/docs/api-reference/endpoints/app-connections/chef/list.mdx new file mode 100644 index 000000000..dc18436a7 --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/chef/list.mdx @@ -0,0 +1,4 @@ +--- +title: "List" +openapi: "GET /api/v1/app-connections/chef" +--- diff --git a/docs/api-reference/endpoints/app-connections/chef/update.mdx b/docs/api-reference/endpoints/app-connections/chef/update.mdx new file mode 100644 index 000000000..780bea960 --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/chef/update.mdx @@ -0,0 +1,10 @@ +--- +title: "Update" +openapi: "PATCH /api/v1/app-connections/chef/{connectionId}" +--- + + + Check out the configuration docs for [Chef + Connections](/integrations/app-connections/chef) to learn how to obtain the + required credentials. + diff --git a/docs/api-reference/endpoints/app-connections/northflank/available.mdx b/docs/api-reference/endpoints/app-connections/northflank/available.mdx new file mode 100644 index 000000000..99626a947 --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/northflank/available.mdx @@ -0,0 +1,4 @@ +--- +title: "Available" +openapi: "GET /api/v1/app-connections/northflank/available" +--- diff --git a/docs/api-reference/endpoints/app-connections/northflank/create.mdx b/docs/api-reference/endpoints/app-connections/northflank/create.mdx new file mode 100644 index 000000000..0ec652776 --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/northflank/create.mdx @@ -0,0 +1,8 @@ +--- +title: "Create" +openapi: "POST /api/v1/app-connections/northflank" +--- + + + Check out the configuration docs for [Northflank Connections](/integrations/app-connections/northflank) to learn how to obtain the required credentials. + diff --git a/docs/api-reference/endpoints/app-connections/northflank/delete.mdx b/docs/api-reference/endpoints/app-connections/northflank/delete.mdx new file mode 100644 index 000000000..1c3518ea5 --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/northflank/delete.mdx @@ -0,0 +1,4 @@ +--- +title: "Delete" +openapi: "DELETE /api/v1/app-connections/northflank/{connectionId}" +--- diff --git a/docs/api-reference/endpoints/app-connections/northflank/get-by-id.mdx b/docs/api-reference/endpoints/app-connections/northflank/get-by-id.mdx new file mode 100644 index 000000000..e6e24e39e --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/northflank/get-by-id.mdx @@ -0,0 +1,4 @@ +--- +title: "Get by ID" +openapi: "GET /api/v1/app-connections/northflank/{connectionId}" +--- diff --git a/docs/api-reference/endpoints/app-connections/northflank/get-by-name.mdx b/docs/api-reference/endpoints/app-connections/northflank/get-by-name.mdx new file mode 100644 index 000000000..e3ca69b31 --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/northflank/get-by-name.mdx @@ -0,0 +1,4 @@ +--- +title: "Get by Name" +openapi: "GET /api/v1/app-connections/northflank/connection-name/{connectionName}" +--- diff --git a/docs/api-reference/endpoints/app-connections/northflank/list.mdx b/docs/api-reference/endpoints/app-connections/northflank/list.mdx new file mode 100644 index 000000000..fbaf08ea6 --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/northflank/list.mdx @@ -0,0 +1,4 @@ +--- +title: "List" +openapi: "GET /api/v1/app-connections/northflank" +--- diff --git a/docs/api-reference/endpoints/app-connections/northflank/update.mdx b/docs/api-reference/endpoints/app-connections/northflank/update.mdx new file mode 100644 index 000000000..4554bd714 --- /dev/null +++ b/docs/api-reference/endpoints/app-connections/northflank/update.mdx @@ -0,0 +1,4 @@ +--- +title: "Update" +openapi: "PATCH /api/v1/app-connections/northflank/{connectionId}" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/chef/create.mdx b/docs/api-reference/endpoints/secret-syncs/chef/create.mdx new file mode 100644 index 000000000..61b816d7d --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/chef/create.mdx @@ -0,0 +1,4 @@ +--- +title: "Create" +openapi: "POST /api/v1/secret-syncs/chef" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/chef/delete.mdx b/docs/api-reference/endpoints/secret-syncs/chef/delete.mdx new file mode 100644 index 000000000..a43d83be1 --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/chef/delete.mdx @@ -0,0 +1,4 @@ +--- +title: "Delete" +openapi: "DELETE /api/v1/secret-syncs/chef/{syncId}" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/chef/get-by-id.mdx b/docs/api-reference/endpoints/secret-syncs/chef/get-by-id.mdx new file mode 100644 index 000000000..2efeb51e2 --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/chef/get-by-id.mdx @@ -0,0 +1,4 @@ +--- +title: "Get by ID" +openapi: "GET /api/v1/secret-syncs/chef/{syncId}" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/chef/get-by-name.mdx b/docs/api-reference/endpoints/secret-syncs/chef/get-by-name.mdx new file mode 100644 index 000000000..d6ac030d8 --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/chef/get-by-name.mdx @@ -0,0 +1,4 @@ +--- +title: "Get by Name" +openapi: "GET /api/v1/secret-syncs/chef/sync-name/{syncName}" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/chef/import-secrets.mdx b/docs/api-reference/endpoints/secret-syncs/chef/import-secrets.mdx new file mode 100644 index 000000000..734c89a95 --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/chef/import-secrets.mdx @@ -0,0 +1,4 @@ +--- +title: "Import Secrets" +openapi: "POST /api/v1/secret-syncs/chef/{syncId}/import-secrets" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/chef/list.mdx b/docs/api-reference/endpoints/secret-syncs/chef/list.mdx new file mode 100644 index 000000000..e38b35e43 --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/chef/list.mdx @@ -0,0 +1,4 @@ +--- +title: "List" +openapi: "GET /api/v1/secret-syncs/chef" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/chef/remove-secrets.mdx b/docs/api-reference/endpoints/secret-syncs/chef/remove-secrets.mdx new file mode 100644 index 000000000..e44df1c3e --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/chef/remove-secrets.mdx @@ -0,0 +1,4 @@ +--- +title: "Remove Secrets" +openapi: "POST /api/v1/secret-syncs/chef/{syncId}/remove-secrets" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/chef/sync-secrets.mdx b/docs/api-reference/endpoints/secret-syncs/chef/sync-secrets.mdx new file mode 100644 index 000000000..8f8eefa04 --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/chef/sync-secrets.mdx @@ -0,0 +1,4 @@ +--- +title: "Sync Secrets" +openapi: "POST /api/v1/secret-syncs/chef/{syncId}/sync-secrets" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/chef/update.mdx b/docs/api-reference/endpoints/secret-syncs/chef/update.mdx new file mode 100644 index 000000000..d5c39484d --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/chef/update.mdx @@ -0,0 +1,4 @@ +--- +title: "Update" +openapi: "PATCH /api/v1/secret-syncs/chef/{syncId}" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/northflank/create.mdx b/docs/api-reference/endpoints/secret-syncs/northflank/create.mdx new file mode 100644 index 000000000..47ae2f4b4 --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/northflank/create.mdx @@ -0,0 +1,4 @@ +--- +title: "Create" +openapi: "POST /api/v1/secret-syncs/northflank" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/northflank/delete.mdx b/docs/api-reference/endpoints/secret-syncs/northflank/delete.mdx new file mode 100644 index 000000000..12e5c6e44 --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/northflank/delete.mdx @@ -0,0 +1,4 @@ +--- +title: "Delete" +openapi: "DELETE /api/v1/secret-syncs/northflank/{syncId}" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/northflank/get-by-id.mdx b/docs/api-reference/endpoints/secret-syncs/northflank/get-by-id.mdx new file mode 100644 index 000000000..7cad153e8 --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/northflank/get-by-id.mdx @@ -0,0 +1,4 @@ +--- +title: "Get by ID" +openapi: "GET /api/v1/secret-syncs/northflank/{syncId}" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/northflank/get-by-name.mdx b/docs/api-reference/endpoints/secret-syncs/northflank/get-by-name.mdx new file mode 100644 index 000000000..487462dde --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/northflank/get-by-name.mdx @@ -0,0 +1,4 @@ +--- +title: "Get by Name" +openapi: "GET /api/v1/secret-syncs/northflank/sync-name/{syncName}" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/northflank/import-secrets.mdx b/docs/api-reference/endpoints/secret-syncs/northflank/import-secrets.mdx new file mode 100644 index 000000000..0294f4dad --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/northflank/import-secrets.mdx @@ -0,0 +1,4 @@ +--- +title: "Import Secrets" +openapi: "POST /api/v1/secret-syncs/northflank/{syncId}/import-secrets" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/northflank/list.mdx b/docs/api-reference/endpoints/secret-syncs/northflank/list.mdx new file mode 100644 index 000000000..a1926710f --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/northflank/list.mdx @@ -0,0 +1,4 @@ +--- +title: "List" +openapi: "GET /api/v1/secret-syncs/northflank" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/northflank/remove-secrets.mdx b/docs/api-reference/endpoints/secret-syncs/northflank/remove-secrets.mdx new file mode 100644 index 000000000..161ddac54 --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/northflank/remove-secrets.mdx @@ -0,0 +1,4 @@ +--- +title: "Remove Secrets" +openapi: "POST /api/v1/secret-syncs/northflank/{syncId}/remove-secrets" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/northflank/sync-secrets.mdx b/docs/api-reference/endpoints/secret-syncs/northflank/sync-secrets.mdx new file mode 100644 index 000000000..82ce1a96a --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/northflank/sync-secrets.mdx @@ -0,0 +1,4 @@ +--- +title: "Sync Secrets" +openapi: "POST /api/v1/secret-syncs/northflank/{syncId}/sync-secrets" +--- diff --git a/docs/api-reference/endpoints/secret-syncs/northflank/update.mdx b/docs/api-reference/endpoints/secret-syncs/northflank/update.mdx new file mode 100644 index 000000000..2f743e82f --- /dev/null +++ b/docs/api-reference/endpoints/secret-syncs/northflank/update.mdx @@ -0,0 +1,4 @@ +--- +title: "Update" +openapi: "PATCH /api/v1/secret-syncs/northflank/{syncId}" +--- diff --git a/docs/api-reference/overview/introduction.mdx b/docs/api-reference/overview/introduction.mdx index 6d577e15b..2f75bf0f5 100644 --- a/docs/api-reference/overview/introduction.mdx +++ b/docs/api-reference/overview/introduction.mdx @@ -7,4 +7,10 @@ Infisical's Public (REST) API provides users an alternative way to programmatica secrets via HTTPS requests. This can be useful for automating tasks, such as rotating credentials, or for integrating secret management into a larger system. -With the Public API, you can create, read, update, and delete secrets, as well as manage access control, query audit logs, and more. \ No newline at end of file +With the Public API, you can create, read, update, and delete secrets, as well as manage access control, query audit logs, and more. + +## API Versioning + +The API is versioned on a per-resource basis. A resource's version is only incremented for breaking changes, so different endpoints may have different version numbers (e.g., `/api/v4/secrets` vs. `/api/v1/secret-syncs`). + +As a best practice, always use the latest available version for each endpoint to ensure access to the most recent features and improvements. diff --git a/docs/cli/usage.mdx b/docs/cli/usage.mdx index 8d0236ed5..bedfda22c 100644 --- a/docs/cli/usage.mdx +++ b/docs/cli/usage.mdx @@ -9,11 +9,15 @@ The CLI is designed for a variety of secret management applications ranging from In the following steps, we explore how to use the Infisical CLI to fetch back environment variables from Infisical and inject them into your local development process. - + + + If you prefer learning by watching, you can follow along our step-by-step video tutorial [here](https://www.youtube.com/watch?v=EzDQC7nY3YY). + + Start by running the `infisical login` command to authenticate with Infisical. - + ```bash infisical login ``` @@ -23,7 +27,7 @@ The CLI is designed for a variety of secret management applications ranging from Next, navigate to your project and initialize Infisical. - + ```bash # navigate to your project cd /path/to/project @@ -123,23 +127,25 @@ The CLI is designed for a variety of secret management applications ranging from Starting with CLI version v0.4.0, you can now choose to log in via Infisical Cloud (US/EU) or your own self-hosted instance by simply running `infisical login` and following the on-screen instructions — no need to manually set the `INFISICAL_API_URL` environment variable. - For versions prior to v0.4.0, the CLI defaults to the US Cloud. To connect to the EU Cloud or a self-hosted instance, set the `INFISICAL_API_URL` environment variable to `https://eu.infisical.com` or your custom URL. +For versions prior to v0.4.0, the CLI defaults to the US Cloud. To connect to the EU Cloud or a self-hosted instance, set the `INFISICAL_API_URL` environment variable to `https://eu.infisical.com` or your custom URL. + ## Custom Request Headers - The Infisical CLI supports custom HTTP headers for requests to servers protected by authentication services such as Cloudflare Access. Configure these headers using the `INFISICAL_CUSTOM_HEADERS` environment variable: +The Infisical CLI supports custom HTTP headers for requests to servers protected by authentication services such as Cloudflare Access. Configure these headers using the `INFISICAL_CUSTOM_HEADERS` environment variable: - ```bash - # Syntax: headername1=headervalue1 headername2=headervalue2 - export INFISICAL_CUSTOM_HEADERS="Access-Client-Id=your-client-id Access-Client-Secret=your-client-secret" +```bash +# Syntax: headername1=headervalue1 headername2=headervalue2 +export INFISICAL_CUSTOM_HEADERS="Access-Client-Id=your-client-id Access-Client-Secret=your-client-secret" - # Execute Infisical commands after setting the environment variable - infisical secrets - ``` +# Execute Infisical commands after setting the environment variable +infisical secrets +``` + +This functionality enables secure interaction with Infisical instances that require specific authentication headers. - This functionality enables secure interaction with Infisical instances that require specific authentication headers. ## History diff --git a/docs/docs.json b/docs/docs.json index 46f5aaf70..6d8eb04cc 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -114,6 +114,7 @@ "integrations/app-connections/bitbucket", "integrations/app-connections/camunda", "integrations/app-connections/checkly", + "integrations/app-connections/chef", "integrations/app-connections/cloudflare", "integrations/app-connections/databricks", "integrations/app-connections/digital-ocean", @@ -130,6 +131,7 @@ "integrations/app-connections/mssql", "integrations/app-connections/mysql", "integrations/app-connections/netlify", + "integrations/app-connections/northflank", "integrations/app-connections/oci", "integrations/app-connections/okta", "integrations/app-connections/oracledb", @@ -176,16 +178,14 @@ "pages": [ "documentation/platform/gateways/overview", "documentation/platform/gateways/gateway-deployment", - "documentation/platform/gateways/relay-deployment", - "documentation/platform/gateways/security", { - "group": "Gateway (Deprecated)", + "group": "Relay Deployment", "pages": [ - "documentation/platform/gateways-deprecated/overview", - "documentation/platform/gateways-deprecated/gateway-security", - "documentation/platform/gateways-deprecated/networking" + "documentation/platform/gateways/relay-deployment/overview", + "documentation/platform/gateways/relay-deployment/terraform" ] - } + }, + "documentation/platform/gateways/security" ] } ] @@ -541,6 +541,7 @@ "integrations/secret-syncs/bitbucket", "integrations/secret-syncs/camunda", "integrations/secret-syncs/checkly", + "integrations/secret-syncs/chef", "integrations/secret-syncs/cloudflare-pages", "integrations/secret-syncs/cloudflare-workers", "integrations/secret-syncs/databricks", @@ -554,6 +555,7 @@ "integrations/secret-syncs/humanitec", "integrations/secret-syncs/laravel-forge", "integrations/secret-syncs/netlify", + "integrations/secret-syncs/northflank", "integrations/secret-syncs/oci-vault", "integrations/secret-syncs/railway", "integrations/secret-syncs/render", @@ -1658,6 +1660,18 @@ "api-reference/endpoints/app-connections/checkly/delete" ] }, + { + "group": "Chef", + "pages": [ + "api-reference/endpoints/app-connections/chef/list", + "api-reference/endpoints/app-connections/chef/available", + "api-reference/endpoints/app-connections/chef/get-by-id", + "api-reference/endpoints/app-connections/chef/get-by-name", + "api-reference/endpoints/app-connections/chef/create", + "api-reference/endpoints/app-connections/chef/update", + "api-reference/endpoints/app-connections/chef/delete" + ] + }, { "group": "Cloudflare", "pages": [ @@ -1850,6 +1864,18 @@ "api-reference/endpoints/app-connections/netlify/delete" ] }, + { + "group": "Northflank", + "pages": [ + "api-reference/endpoints/app-connections/northflank/list", + "api-reference/endpoints/app-connections/northflank/available", + "api-reference/endpoints/app-connections/northflank/get-by-id", + "api-reference/endpoints/app-connections/northflank/get-by-name", + "api-reference/endpoints/app-connections/northflank/create", + "api-reference/endpoints/app-connections/northflank/update", + "api-reference/endpoints/app-connections/northflank/delete" + ] + }, { "group": "OCI", "pages": [ @@ -2137,6 +2163,20 @@ "api-reference/endpoints/secret-syncs/checkly/remove-secrets" ] }, + { + "group": "Chef", + "pages": [ + "api-reference/endpoints/secret-syncs/chef/list", + "api-reference/endpoints/secret-syncs/chef/get-by-id", + "api-reference/endpoints/secret-syncs/chef/get-by-name", + "api-reference/endpoints/secret-syncs/chef/create", + "api-reference/endpoints/secret-syncs/chef/update", + "api-reference/endpoints/secret-syncs/chef/delete", + "api-reference/endpoints/secret-syncs/chef/sync-secrets", + "api-reference/endpoints/secret-syncs/chef/import-secrets", + "api-reference/endpoints/secret-syncs/chef/remove-secrets" + ] + }, { "group": "Cloudflare Pages", "pages": [ @@ -2292,6 +2332,7 @@ "api-reference/endpoints/secret-syncs/laravel-forge/update", "api-reference/endpoints/secret-syncs/laravel-forge/delete", "api-reference/endpoints/secret-syncs/laravel-forge/sync-secrets", + "api-reference/endpoints/secret-syncs/laravel-forge/import-secrets", "api-reference/endpoints/secret-syncs/laravel-forge/remove-secrets" ] }, @@ -2308,6 +2349,20 @@ "api-reference/endpoints/secret-syncs/netlify/remove-secrets" ] }, + { + "group": "Northflank", + "pages": [ + "api-reference/endpoints/secret-syncs/northflank/list", + "api-reference/endpoints/secret-syncs/northflank/get-by-id", + "api-reference/endpoints/secret-syncs/northflank/get-by-name", + "api-reference/endpoints/secret-syncs/northflank/create", + "api-reference/endpoints/secret-syncs/northflank/update", + "api-reference/endpoints/secret-syncs/northflank/delete", + "api-reference/endpoints/secret-syncs/northflank/sync-secrets", + "api-reference/endpoints/secret-syncs/northflank/import-secrets", + "api-reference/endpoints/secret-syncs/northflank/remove-secrets" + ] + }, { "group": "OCI", "pages": [ diff --git a/docs/documentation/platform/external-migrations/vault.mdx b/docs/documentation/platform/external-migrations/vault.mdx index e267cc5e9..c58e1ea6b 100644 --- a/docs/documentation/platform/external-migrations/vault.mdx +++ b/docs/documentation/platform/external-migrations/vault.mdx @@ -26,6 +26,12 @@ Infisical provides two approaches for migrating from HashiCorp Vault. This migration approach lets you set up a connection to your Vault instance once, then import specific resources as needed throughout Infisical. + + **Organization Admin Access Required:** All in-platform migration features + (importing secrets, Kubernetes configurations, and policies from Vault) are + only accessible to organization admins. + + ### Step 1: Set Up Your Vault Connection @@ -84,6 +90,19 @@ This migration approach lets you set up a connection to your Vault instance once path "auth/+/role/*" { capabilities = ["read"] } + + # Kubernetes secrets engine - for reading secrets engine configuration and roles + path "+/config" { + capabilities = ["read"] + } + + path "+/roles" { + capabilities = ["list"] + } + + path "+/roles/*" { + capabilities = ["read"] + } ``` @@ -160,6 +179,34 @@ The authentication settings (service accounts, TTL, policies, etc.) will be auto must be manually provided in the form after importing the configuration. +#### Import Kubernetes Dynamic Secret Configurations + +When creating a Kubernetes dynamic secret, you can import the configuration from a Vault Kubernetes secrets engine role: + +1. Navigate to your project and select an environment +2. Click **"+ Add Secret"** dropdown and choose **"Dynamic Secret"** +3. Select **Kubernetes** as the provider +4. Click **"Load from Vault"** at the top of the form + + ![Load Kubernetes Dynamic Secret from Vault](/images/platform/external-migrations/vault-in-platform/import-vault-kubernetes-role-modal.png) + +5. Select your Vault namespace, Kubernetes secrets engine mount, and role +6. Click **"Load Configuration"** + +The form will be automatically populated with the role's configuration including: + +- Cluster URL and CA certificate +- Credential type (Static or Dynamic) +- Service account name or Kubernetes role settings +- Allowed namespaces +- Token TTL values +- Token audiences + + + Sensitive values like cluster tokens cannot be retrieved from Vault and must + be manually provided in the form after loading the configuration. + + #### Import and Translate Access Control Policies When configuring project role-based access control, you can import Vault HCL policies and automatically translate them to Infisical permissions. diff --git a/docs/documentation/platform/gateways-deprecated/gateway-security.mdx b/docs/documentation/platform/gateways-deprecated/gateway-security.mdx deleted file mode 100644 index 93a7f662f..000000000 --- a/docs/documentation/platform/gateways-deprecated/gateway-security.mdx +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: "Gateway Security Architecture" -sidebarTitle: "Architecture" -description: "Understand the security model and tenant isolation of Infisical's Gateway" ---- - -# Gateway Security Architecture - -The Infisical Gateway enables Infisical Cloud to securely interact with private resources using mutual TLS authentication and private PKI (Public Key Infrastructure) system to ensure secure, isolated communication between multiple tenants. -This document explains the internal security architecture and how tenant isolation is maintained. - -## Security Model Overview - -### Private PKI System -Each organization (tenant) in Infisical has its own private PKI system consisting of: - -1. **Root CA**: The ultimate trust anchor for the organization -2. **Intermediate CAs**: - - Client CA: Issues certificates for cloud components - - Gateway CA: Issues certificates for gateway instances - -This hierarchical structure ensures complete isolation between organizations as each has its own independent certificate chain. - -### Certificate Hierarchy -``` -Root CA (Organization Specific) -├── Client CA -│ └── Client Certificates (Cloud Components) -└── Gateway CA - └── Gateway Certificates (Gateway Instances) -``` - -## Communication Security - -### 1. Gateway Registration -When a gateway is first deployed: - -1. Establishes initial connection using machine identity token -2. Allocates a relay address for communication -3. Exchanges certificates through a secure handshake: - - Gateway receives a unique certificate signed by organization's Gateway CA along with certificate chain for verification - -### 2. Mutual TLS Authentication -All communication between gateway and cloud uses mutual TLS (mTLS): - -- **Gateway Authentication**: - - Presents certificate signed by organization's Gateway CA - - Certificate contains unique identifiers (Organization ID, Gateway ID) - - Cloud validates complete certificate chain - -- **Cloud Authentication**: - - Presents certificate signed by organization's Client CA - - Certificate includes required organizational unit ("gateway-client") - - Gateway validates certificate chain back to organization's root CA - -### 3. Relay Communication -The relay system provides secure tunneling: - -1. **Connection Establishment**: - - Uses QUIC protocol over UDP for efficient, secure communication - - Provides built-in encryption, congestion control, and multiplexing - - Enables faster connection establishment and reduced latency - - Each organization's traffic is isolated using separate relay sessions - -2. **Traffic Isolation**: - - Each gateway gets unique relay credentials - - Traffic is end-to-end encrypted using QUIC's TLS 1.3 - - Organization's private keys never leave their environment - -## Tenant Isolation - -### Certificate-Based Isolation -- Each organization has unique root CA and intermediate CAs -- Certificates contain organization-specific identifiers -- Cross-tenant communication is cryptographically impossible - -### Gateway-Project Mapping -- Gateways are explicitly mapped to specific projects -- Access controls enforce organization boundaries -- Project-level permissions determine resource accessibility - -### Resource Access Control -1. **Project Verification**: - - Gateway verifies project membership - - Validates organization ownership - - Enforces project-level permissions - -2. **Resource Restrictions**: - - Gateways only accept connections to approved resources - - Each connection requires explicit project authorization - - Resources remain private to their assigned organization diff --git a/docs/documentation/platform/gateways-deprecated/images/gateway-highlevel-diagram.png b/docs/documentation/platform/gateways-deprecated/images/gateway-highlevel-diagram.png deleted file mode 100644 index 5f942bcf0..000000000 Binary files a/docs/documentation/platform/gateways-deprecated/images/gateway-highlevel-diagram.png and /dev/null differ diff --git a/docs/documentation/platform/gateways-deprecated/networking.mdx b/docs/documentation/platform/gateways-deprecated/networking.mdx deleted file mode 100644 index 51a81ee42..000000000 --- a/docs/documentation/platform/gateways-deprecated/networking.mdx +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: "Networking" -description: "Network configuration and firewall requirements for Infisical Gateway" ---- - -The Infisical Gateway requires outbound network connectivity to establish secure communication with Infisical's relay infrastructure. -This page outlines the required ports, protocols, and firewall configurations needed for optimal gateway usage. - -## Network Architecture - -The gateway uses a relay-based architecture to establish secure connections: - -1. **Gateway** connects outbound to **Relay Servers** using UDP/QUIC protocol -2. **Relay Servers** facilitate secure communication between Gateway and Infisical Cloud -3. All traffic is end-to-end encrypted using mutual TLS over QUIC - -## Required Network Connectivity - -### Outbound Connections (Required) - -The gateway requires the following outbound connectivity: - -| Protocol | Destination | Ports | Purpose | -|----------|-------------|-------|---------| -| UDP | Relay Servers | 49152-65535 | Allocated relay communication (TLS) | -| TCP | app.infisical.com / eu.infisical.com | 443 | API communication and relay allocation | - -### Relay Server IP Addresses - -Your firewall must allow outbound connectivity to the following Infisical relay servers on dynamically allocated ports. - - - - ``` - 54.235.197.91:49152-65535 - 18.215.196.229:49152-65535 - 3.222.120.233:49152-65535 - 34.196.115.157:49152-65535 - ``` - - - ``` - 3.125.237.40:49152-65535 - 52.28.157.98:49152-65535 - 3.125.176.90:49152-65535 - ``` - - - Please contact your Infisical account manager for dedicated relay server IP addresses. - - - - - These IP addresses are static and managed by Infisical. Any changes will be communicated with 60-day advance notice. - - -## Protocol Details - -### QUIC over UDP - -The gateway uses QUIC (Quick UDP Internet Connections) for primary communication: - -- **Port 5349**: STUN/TURN over TLS (secure relay communication) -- **Built-in features**: Connection migration, multiplexing, reduced latency -- **Encryption**: TLS 1.3 with certificate pinning - -## Understanding Firewall Behavior with UDP - -Unlike TCP connections, UDP is a stateless protocol, and depending on your organization's firewall configuration, you may need to adjust network rules accordingly. -When the gateway sends UDP packets to a relay server, the return responses need to be allowed back through the firewall. -Modern firewalls handle this through "connection tracking" (also called "stateful inspection"), but the behavior can vary depending on your firewall configuration. - - -### Connection Tracking - -Modern firewalls automatically track UDP connections and allow return responses. This is the preferred configuration as it: -- Automatically handles return responses -- Reduces firewall rule complexity -- Avoids the need for manual IP whitelisting - -In the event that your firewall does not support connection tracking, you will need to whitelist the relay IPs to explicitly define return traffic manually. - -## Common Network Scenarios - -### Corporate Firewalls - -For corporate environments with strict egress filtering: - -1. **Whitelist relay IP addresses** (listed above) -2. **Allow UDP port 5349** outbound -3. **Configure connection tracking** for UDP return traffic -4. **Allow ephemeral port range** 49152-65535 for return traffic if connection tracking is disabled - -### Cloud Environments (AWS/GCP/Azure) - -Configure security groups to allow: -- **Outbound UDP** to relay IPs on port 5349 -- **Outbound HTTPS** to app.infisical.com/eu.infisical.com on port 443 -- **Inbound UDP** on ephemeral ports (if not using stateful rules) - -## Frequently Asked Questions - - - -The gateway is designed to handle network interruptions gracefully: - -- **Automatic reconnection**: The gateway will automatically attempt to reconnect to relay servers every 5 seconds if the connection is lost -- **Connection retry logic**: Built-in retry mechanisms handle temporary network outages without manual intervention -- **Multiple relay servers**: If one relay server is unavailable, the gateway can connect to alternative relay servers -- **Persistent sessions**: Existing connections are maintained where possible during brief network interruptions -- **Graceful degradation**: The gateway logs connection issues and continues attempting to restore connectivity - -No manual intervention is typically required during network interruptions. - - - -QUIC (Quick UDP Internet Connections) provides several advantages over traditional TCP for gateway communication: - -- **Faster connection establishment**: QUIC combines transport and security handshakes, reducing connection setup time -- **Built-in encryption**: TLS 1.3 is integrated into the protocol, ensuring all traffic is encrypted by default -- **Connection migration**: QUIC connections can survive IP address changes (useful for NAT rebinding) -- **Reduced head-of-line blocking**: Multiple data streams can be multiplexed without blocking each other -- **Better performance over unreliable networks**: Advanced congestion control and packet loss recovery -- **Lower latency**: Optimized for real-time communication between gateway and cloud services - -While TCP is stateful and easier for firewalls to track, QUIC's performance benefits outweigh the additional firewall configuration requirements. - - - -No inbound ports need to be opened. The gateway only makes outbound connections: - -- **Outbound UDP** to relay servers on ports 49152-65535 -- **Outbound HTTPS** to Infisical API endpoints -- **Return responses** are handled by connection tracking or explicit IP whitelisting - -This design maintains security by avoiding the need for inbound firewall rules that could expose your network to external threats. - - - -If your firewall has strict UDP restrictions: - -1. **Work with your network team** to allow outbound UDP to the specific relay IP addresses -2. **Use explicit IP whitelisting** if connection tracking is disabled -3. **Consider network policy exceptions** for the gateway host -4. **Monitor firewall logs** to identify which specific rules are blocking traffic - -The gateway requires UDP connectivity to function - TCP-only configurations are not supported. - - - -The gateway connects to **one relay server at a time**: - -- **Single active connection**: Only one relay connection is established per gateway instance -- **Automatic failover**: If the current relay becomes unavailable, the gateway will connect to an alternative relay -- **Load distribution**: Different gateway instances may connect to different relay servers for load balancing -- **No manual selection**: The Infisical API automatically assigns the optimal relay server based on availability and proximity - -You should whitelist all relay IP addresses to ensure proper failover functionality. - - -No, relay servers cannot decrypt any traffic passing through them: - -- **End-to-end encryption**: All traffic between the gateway and Infisical Cloud is encrypted using mutual TLS with certificate pinning -- **Relay acts as a tunnel**: The relay server only forwards encrypted packets - it has no access to encryption keys -- **No data storage**: Relay servers do not store any traffic or network-identifiable information -- **Certificate isolation**: Each organization has its own private PKI system, ensuring complete tenant isolation - -The relay infrastructure is designed as a secure forwarding mechanism, similar to a VPN tunnel, where the relay provider cannot see the contents of the traffic flowing through it. - - diff --git a/docs/documentation/platform/gateways-deprecated/overview.mdx b/docs/documentation/platform/gateways-deprecated/overview.mdx deleted file mode 100644 index f81809f7b..000000000 --- a/docs/documentation/platform/gateways-deprecated/overview.mdx +++ /dev/null @@ -1,352 +0,0 @@ ---- -title: "Gateway" -sidebarTitle: "Overview" -description: "How to access private network resources from Infisical" ---- - -![Alt text](/documentation/platform/gateways-deprecated/images/gateway-highlevel-diagram.png) - -The Infisical Gateway provides secure access to private resources within your network without needing direct inbound connections to your environment. -This method keeps your resources fully protected from external access while enabling Infisical to securely interact with resources like databases. -Common use cases include generating dynamic credentials or rotating credentials for private databases. - - - Gateway is a paid feature available under the Enterprise Tier for Infisical - Cloud users. Self-hosted Infisical users can contact - [sales@infisical.com](mailto:sales@infisical.com) to purchase an enterprise - license. - - -## How It Works - -The Gateway serves as a secure intermediary that facilitates direct communication between the Infisical server and your private network. -It’s a lightweight daemon packaged within the Infisical CLI, making it easy to deploy and manage. Once set up, the Gateway establishes a connection with a relay server, ensuring that all communication between Infisical and your Gateway is fully end-to-end encrypted. -This setup guarantees that only the platform and your Gateway can decrypt the transmitted information, keeping communication with your resources secure, private and isolated. - -## Deployment - -The Infisical Gateway is seamlessly integrated into the Infisical CLI under the `gateway` command, making it simple to deploy and manage. -You can install the Gateway in all the same ways you install the Infisical CLI—whether via npm, Docker, or a binary. -For detailed installation instructions, refer to the Infisical [CLI Installation instructions](/cli/overview). - -To function, the Gateway must authenticate with Infisical. This requires a machine identity configured with the appropriate permissions to create and manage a Gateway. -Once authenticated, the Gateway establishes a secure connection with Infisical to allow your private resources to be reachable. - -### Get started - - - - 1. Navigate to **Organization Access Control** in your Infisical dashboard. - 2. Create a dedicated machine identity for your Gateway. - 3. **Best Practice:** Assign a unique identity to each Gateway for better security and management. - ![Create Gateway Identity](../../../images/platform/gateways/create-identity-for-gateway.png) - - - - You'll need to choose an authentication method to initiate communication with Infisical. View the available machine identity authentication methods [here](/documentation/platform/identities/machine-identities). - - - - Use the Infisical CLI to deploy the Gateway. You can run it directly or install it as a systemd service for production: - - - - For production deployments on Linux, install the Gateway as a systemd service: - ```bash - sudo infisical gateway install --token --domain - sudo systemctl start infisical-gateway - ``` - This will install and start the Gateway as a secure systemd service that: - - Runs with restricted privileges: - - Runs as root user (required for secure token management) - - Restricted access to home directories - - Private temporary directory - - Automatically restarts on failure - - Starts on system boot - - Manages token and domain configuration securely in `/etc/infisical/gateway.conf` - - - The install command requires: - - Linux operating system - - Root/sudo privileges - - Systemd - - - - - - The Gateway can be installed via [Helm](https://helm.sh/). Helm is a package manager for Kubernetes that allows you to define, install, and upgrade Kubernetes applications. - - For production deployments on Kubernetes, install the Gateway using the Infisical Helm chart: - - ### Install the latest Helm Chart repository - ```bash - helm repo add infisical-helm-charts 'https://dl.cloudsmith.io/public/infisical/helm-charts/helm/charts/' - ``` - - ### Update the Helm Chart repository - ```bash - helm repo update - ``` - - ### Create a Kubernetes Secret containing gateway environment variables - - The gateway supports all identity authentication methods through the use of environment variables. - The environment variables must be set in the `infisical-gateway-environment` Kubernetes secret. - - - #### Supported authentication methods - - - - The Universal Auth method is a simple and secure way to authenticate with Infisical. It requires a client ID and a client secret to authenticate with Infisical. - - - - - Your machine identity client ID. - - - Your machine identity client secret. - - - The authentication method to use. Must be `universal-auth` when using Universal Auth. - - - - - ```bash - kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=universal-auth --from-literal=INFISICAL_UNIVERSAL_AUTH_CLIENT_ID= --from-literal=INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET= - ``` - - - - The Native Kubernetes method is used to authenticate with Infisical when running in a Kubernetes environment. It requires a service account token to authenticate with Infisical. - - - - - Your machine identity ID. - - - Path to the Kubernetes service account token to use. Default: `/var/run/secrets/kubernetes.io/serviceaccount/token`. - - - The authentication method to use. Must be `kubernetes` when using Native Kubernetes. - - - - - - ```bash - kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=kubernetes --from-literal=INFISICAL_MACHINE_IDENTITY_ID= - ``` - - - - The Native Azure method is used to authenticate with Infisical when running in an Azure environment. - - - - - Your machine identity ID. - - - The authentication method to use. Must be `azure` when using Native Azure. - - - - - ```bash - kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=azure --from-literal=INFISICAL_MACHINE_IDENTITY_ID= - ``` - - - The Native GCP ID Token method is used to authenticate with Infisical when running in a GCP environment. - - - - - Your machine identity ID. - - - The authentication method to use. Must be `gcp-id-token` when using Native GCP ID Token. - - - - - ```bash - kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=gcp-id-token --from-literal=INFISICAL_MACHINE_IDENTITY_ID= - ``` - - - - The GCP IAM method is used to authenticate with Infisical with a GCP service account key. - - - - - Your machine identity ID. - - - Path to your GCP service account key file _(Must be in JSON format!)_ - - - The authentication method to use. Must be `gcp-iam` when using GCP IAM. - - - - - ```bash - kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=gcp-iam --from-literal=INFISICAL_MACHINE_IDENTITY_ID= --from-literal=INFISICAL_GCP_SERVICE_ACCOUNT_KEY_FILE_PATH= - ``` - - - - - The AWS IAM method is used to authenticate with Infisical with an AWS IAM role while running in an AWS environment like EC2, Lambda, etc. - - - - - Your machine identity ID. - - - The authentication method to use. Must be `aws-iam` when using Native AWS IAM. - - - - - ```bash - kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=aws-iam --from-literal=INFISICAL_MACHINE_IDENTITY_ID= - ``` - - - - The OIDC Auth method is used to authenticate with Infisical via identity tokens with OIDC. - - - - - Your machine identity ID. - - - The OIDC JWT from the identity provider. - - - The authentication method to use. Must be `oidc-auth` when using OIDC Auth. - - - - - ```bash - kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=oidc-auth --from-literal=INFISICAL_MACHINE_IDENTITY_ID= --from-literal=INFISICAL_JWT= - ``` - - - - The JWT Auth method is used to authenticate with Infisical via a JWT token. - - - - - The JWT token to use for authentication. - - - Your machine identity ID. - - - The authentication method to use. Must be `jwt-auth` when using JWT Auth. - - - - - ```bash - kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=jwt-auth --from-literal=INFISICAL_JWT= --from-literal=INFISICAL_MACHINE_IDENTITY_ID= - ``` - - - You can use the `INFISICAL_TOKEN` environment variable to authenticate with Infisical with a raw machine identity access token. - - - - - The machine identity access token to use for authentication. - - - - - ```bash - kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_TOKEN= - ``` - - - - - #### Other environment variables - - - - The API URL to use for the gateway. By default, `INFISICAL_API_URL` is set to `https://app.infisical.com`. - - - - - ### Install the Infisical Gateway Helm Chart - ```bash - helm install infisical-gateway infisical-helm-charts/infisical-gateway - ``` - - ### Check the gateway logs - After installing the gateway, you can check the logs to ensure it's running as expected. - - ```bash - kubectl logs deployment/infisical-gateway - ``` - - You should see the following output which indicates the gateway is running as expected. - ```bash - $ kubectl logs deployment/infisical-gateway - INF Provided relay port 5349. Using TLS - INF Connected with relay - INF 10.0.101.112:56735 - INF Starting relay connection health check - INF Gateway started successfully - INF New connection from: 10.0.1.8:34051 - INF Gateway is reachable by Infisical - ``` - - - - - For development or testing, you can run the Gateway directly. Log in with your machine identity and start the Gateway in one command: - ```bash - infisical gateway --token $(infisical login --method=universal-auth --client-id=<> --client-secret=<> --plain) - ``` - - Alternatively, if you already have the token, use it directly with the `--token` flag: - ```bash - infisical gateway --token - ``` - - Or set it as an environment variable: - ```bash - export INFISICAL_TOKEN= - infisical gateway - ``` - - - - For detailed information about the gateway command and its options, see the [gateway command documentation](/cli/commands/gateway). - - - Ensure the deployed Gateway has network access to the private resources you intend to connect with Infisical. - - - - - - To confirm your Gateway is working, check the deployment status by looking for the message **"Gateway started successfully"** in the Gateway logs. This indicates the Gateway is running properly. Next, verify its registration by opening your Infisical dashboard, navigating to **Organization Access Control**, and selecting the **Gateways** tab. Your newly deployed Gateway should appear in the list. - ![Gateway List](../../../images/platform/gateways/gateway-list.png) - - diff --git a/docs/documentation/platform/gateways/relay-deployment.mdx b/docs/documentation/platform/gateways/relay-deployment/overview.mdx similarity index 95% rename from docs/documentation/platform/gateways/relay-deployment.mdx rename to docs/documentation/platform/gateways/relay-deployment/overview.mdx index 767cf3732..ba7689196 100644 --- a/docs/documentation/platform/gateways/relay-deployment.mdx +++ b/docs/documentation/platform/gateways/relay-deployment/overview.mdx @@ -1,5 +1,5 @@ --- -title: "Relay Deployment" +title: "Overview" description: "How to deploy Infisical Relay Servers" --- @@ -107,13 +107,8 @@ To successfully deploy an Infisical Relay for use, follow these steps in order. - - Install the Infisical CLI on the server where you plan to deploy the relay. The CLI is required for relay installation and management. - - See the [CLI Installation Guide](/cli/overview) for instructions. - - This server must have a static IP address or DNS name to be identifiable by the Infisical platform. - + + Provision a server or virtual machine where you plan to deploy the relay. This server must have a static IP address or DNS name to be identifiable by the Infisical platform. @@ -133,6 +128,8 @@ To successfully deploy an Infisical Relay for use, follow these steps in order. + You can deploy the Infisical Relay in various ways. This guide provides a manual setup example using the Infisical CLI. For an infrastructure-as-code approach, see our [Terraform guide](/documentation/platform/gateways/relay-deployment/terraform). + The Infisical CLI is used to install and start the relay in your chosen environment. The CLI provides commands for both production and development scenarios, and supports a variety of options/flags to configure your deployment. To view all available flags and equivalent environment variables for relay deployment, see the [Relay CLI Command Reference](/cli/commands/relay). diff --git a/docs/documentation/platform/gateways/relay-deployment/terraform.mdx b/docs/documentation/platform/gateways/relay-deployment/terraform.mdx new file mode 100644 index 000000000..e89871cd9 --- /dev/null +++ b/docs/documentation/platform/gateways/relay-deployment/terraform.mdx @@ -0,0 +1,151 @@ +--- +title: "Terraform" +description: "How to deploy Infisical Relay Servers using Terraform" +--- + +This guide walks you through deploying an Infisical Relay server using Terraform. Select a provider below for specific instructions. + + + +The provided configuration automates the creation of the EC2 instance, sets up the necessary security group rules, and uses a startup script to install and configure the Infisical Relay service. + +### Prerequisites + +Before you start, make sure you have the following: +- An AWS account with permissions to create EC2 instances, Security Groups, and Elastic IPs. +- An existing VPC and Subnet ID in your desired AWS region. +- The AMI ID for your chosen OS (this guide uses an Ubuntu 22.04 LTS AMI). +- Credentials for the Infisical Relay to authenticate with your Infisical instance. This guide uses a Machine Identity token, but other methods are available. You can find a full list of authentication options [here](/cli/commands/relay#available-authentication-methods). + +### Terraform Configuration + +Here is the complete Terraform configuration to deploy the Infisical Relay. + +```terraform +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 5.0" + } + } +} + +provider "aws" { + region = "us-west-2" # Change to your desired AWS region +} + +# Security Group for the Infisical Relay instance +resource "aws_security_group" "infisical_relay_sg" { + name = "infisical-relay-sg" + description = "Allows inbound traffic for Infisical Relay and SSH" + vpc_id = "vpc-0c71f9c5709d88d18" # Change to your VPC ID + + # Inbound: Allows the Infisical platform to securely communicate with the Relay server. + ingress { + from_port = 8443 + to_port = 8443 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } + + # Inbound: Allows Infisical Gateway to securely communicate via the Relay. + ingress { + from_port = 2222 + to_port = 2222 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } + + # Inbound: Allows secure shell (SSH) access for administration. + ingress { + from_port = 22 + to_port = 22 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] # Restrict this to your IP in production + } + + # Outbound: Allows the Relay server to make necessary outbound connections to the Infisical platform. + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + tags = { + Name = "infisical-relay-sg" + } +} + +# Elastic IP for a static public IP address +resource "aws_eip" "infisical_relay_eip" { + tags = { + Name = "infisical-relay-eip" + } +} + +# EC2 instance to run Infisical Relay +module "infisical_relay_instance" { + source = "terraform-aws-modules/ec2-instance/aws" + version = "~> 5.6" + + name = "infisical-relay-example" + ami = "ami-065778886ef8ec7c8" # Change to your desired AMI ID + instance_type = "t3.micro" + subnet_id = "subnet-0fd2337a1c604a494" # Change to your Subnet ID + + vpc_security_group_ids = [aws_security_group.infisical_relay_sg.id] + associate_public_ip_address = false # We are using an Elastic IP instead + + user_data = <<-EOT + #!/bin/bash + set -e + # Install Infisical CLI + curl -1sLf 'https://artifacts-cli.infisical.com/setup.deb.sh' | bash + apt-get update && apt-get install -y infisical + + # Install the relay as a systemd service. + # This example uses a Machine Identity token for authentication via the INFISICAL_TOKEN environment variable. + # + # Note: For production environments, you might consider fetching the token from AWS Parameter Store or AWS Secrets Manager. + export INFISICAL_TOKEN="your-machine-identity-token" + sudo -E infisical relay systemd install \ + --name "my-relay-example" \ + --domain "https://app.infisical.com" \ + --host "${aws_eip.infisical_relay_eip.public_ip}" + + # Start and enable the service to run on boot + sudo systemctl start infisical-relay + sudo systemctl enable infisical-relay + EOT +} + +# Associate the Elastic IP with the EC2 instance +resource "aws_eip_association" "eip_assoc" { + instance_id = module.infisical_relay_instance.id + allocation_id = aws_eip.infisical_relay_eip.id +} +``` + + +The provided security group rules are open to the internet (`0.0.0.0/0`) for simplicity. In a production environment, you should restrict the `cidr_blocks` to known IP addresses for enhanced security, especially for the SSH port (22). + + +### How to Deploy + +1. **Save the configuration:** Save the code above to a file named `main.tf`. +2. **Customize values:** Update the placeholder values in `main.tf` to match your AWS environment and Infisical credentials. You'll need to replace: + - `region` in the `provider` block. + - `vpc_id` in the `aws_security_group` resource. + - `ami` and `subnet_id` in the `infisical_relay_instance` module. + - The `INFISICAL_TOKEN` environment variable in the `user_data` script (e.g., `export INFISICAL_TOKEN="your-machine-identity-token"`). + - The `--domain` in the `user_data` script if you are self-hosting Infisical. +3. **Apply the configuration:** Run the following Terraform commands in your terminal: + ```bash + terraform init + terraform plan + terraform apply + ``` + + diff --git a/docs/documentation/platform/pki/azure-adcs.mdx b/docs/documentation/platform/pki/azure-adcs.mdx index b0cea565e..23df3ed3b 100644 --- a/docs/documentation/platform/pki/azure-adcs.mdx +++ b/docs/documentation/platform/pki/azure-adcs.mdx @@ -31,7 +31,7 @@ This section walks you through the complete end-to-end process of setting up Azu Click **Create CA** and configure: - - **Type**: Choose **Azure AD Certificate Service** + - **Type**: Choose **Active Directory Certificate Services (AD CS)** - **Name**: Friendly name for this CA (e.g., "Production ADCS CA") - **App Connection**: Choose your ADCS connection from the dropdown diff --git a/docs/images/app-connections/chef/app-connection-form.png b/docs/images/app-connections/chef/app-connection-form.png new file mode 100644 index 000000000..9ba5dc8e8 Binary files /dev/null and b/docs/images/app-connections/chef/app-connection-form.png differ diff --git a/docs/images/app-connections/chef/app-connection-generated.png b/docs/images/app-connections/chef/app-connection-generated.png new file mode 100644 index 000000000..c8ab79540 Binary files /dev/null and b/docs/images/app-connections/chef/app-connection-generated.png differ diff --git a/docs/images/app-connections/chef/app-connection-option.png b/docs/images/app-connections/chef/app-connection-option.png new file mode 100644 index 000000000..2a3e46920 Binary files /dev/null and b/docs/images/app-connections/chef/app-connection-option.png differ diff --git a/docs/images/app-connections/chef/chef-connection-details.png b/docs/images/app-connections/chef/chef-connection-details.png new file mode 100644 index 000000000..9fcb7ee0d Binary files /dev/null and b/docs/images/app-connections/chef/chef-connection-details.png differ diff --git a/docs/images/app-connections/chef/chef-dashboard.png b/docs/images/app-connections/chef/chef-dashboard.png new file mode 100644 index 000000000..65195a8d0 Binary files /dev/null and b/docs/images/app-connections/chef/chef-dashboard.png differ diff --git a/docs/images/app-connections/chef/chef-folder.png b/docs/images/app-connections/chef/chef-folder.png new file mode 100644 index 000000000..29f698080 Binary files /dev/null and b/docs/images/app-connections/chef/chef-folder.png differ diff --git a/docs/images/app-connections/chef/download-starter-kit.png b/docs/images/app-connections/chef/download-starter-kit.png new file mode 100644 index 000000000..27f9582ad Binary files /dev/null and b/docs/images/app-connections/chef/download-starter-kit.png differ diff --git a/docs/images/app-connections/chef/extract-starter-kit.png b/docs/images/app-connections/chef/extract-starter-kit.png new file mode 100644 index 000000000..8743dae9b Binary files /dev/null and b/docs/images/app-connections/chef/extract-starter-kit.png differ diff --git a/docs/images/app-connections/chef/private-key-file.png b/docs/images/app-connections/chef/private-key-file.png new file mode 100644 index 000000000..052103d0e Binary files /dev/null and b/docs/images/app-connections/chef/private-key-file.png differ diff --git a/docs/images/app-connections/chef/starter-kit.png b/docs/images/app-connections/chef/starter-kit.png new file mode 100644 index 000000000..b9b9621e4 Binary files /dev/null and b/docs/images/app-connections/chef/starter-kit.png differ diff --git a/docs/images/app-connections/github/create-pat-form.png b/docs/images/app-connections/github/create-pat-form.png new file mode 100644 index 000000000..cc8abdf15 Binary files /dev/null and b/docs/images/app-connections/github/create-pat-form.png differ diff --git a/docs/images/app-connections/github/create-pat-method.png b/docs/images/app-connections/github/create-pat-method.png new file mode 100644 index 000000000..eec811705 Binary files /dev/null and b/docs/images/app-connections/github/create-pat-method.png differ diff --git a/docs/images/app-connections/github/create-pat-token-generated.png b/docs/images/app-connections/github/create-pat-token-generated.png new file mode 100644 index 000000000..430e67671 Binary files /dev/null and b/docs/images/app-connections/github/create-pat-token-generated.png differ diff --git a/docs/images/app-connections/github/pat-connection.png b/docs/images/app-connections/github/pat-connection.png new file mode 100644 index 000000000..802ed4e38 Binary files /dev/null and b/docs/images/app-connections/github/pat-connection.png differ diff --git a/docs/images/app-connections/gitlab/gitlab-group-access-token-created.png b/docs/images/app-connections/gitlab/gitlab-group-access-token-created.png new file mode 100644 index 000000000..f5a7383f2 Binary files /dev/null and b/docs/images/app-connections/gitlab/gitlab-group-access-token-created.png differ diff --git a/docs/images/app-connections/gitlab/gitlab-group-access-token-form-secret-sync.png b/docs/images/app-connections/gitlab/gitlab-group-access-token-form-secret-sync.png new file mode 100644 index 000000000..04dee5a5c Binary files /dev/null and b/docs/images/app-connections/gitlab/gitlab-group-access-token-form-secret-sync.png differ diff --git a/docs/images/app-connections/gitlab/gitlab-group-access-token-list.png b/docs/images/app-connections/gitlab/gitlab-group-access-token-list.png new file mode 100644 index 000000000..e29df0418 Binary files /dev/null and b/docs/images/app-connections/gitlab/gitlab-group-access-token-list.png differ diff --git a/docs/images/app-connections/northflank/northflank-app-connection-form.png b/docs/images/app-connections/northflank/northflank-app-connection-form.png new file mode 100644 index 000000000..226346517 Binary files /dev/null and b/docs/images/app-connections/northflank/northflank-app-connection-form.png differ diff --git a/docs/images/app-connections/northflank/northflank-app-connection-generated.png b/docs/images/app-connections/northflank/northflank-app-connection-generated.png new file mode 100644 index 000000000..89038637a Binary files /dev/null and b/docs/images/app-connections/northflank/northflank-app-connection-generated.png differ diff --git a/docs/images/app-connections/northflank/northflank-app-connection-option.png b/docs/images/app-connections/northflank/northflank-app-connection-option.png new file mode 100644 index 000000000..17106494a Binary files /dev/null and b/docs/images/app-connections/northflank/northflank-app-connection-option.png differ diff --git a/docs/images/app-connections/northflank/step-1.png b/docs/images/app-connections/northflank/step-1.png new file mode 100644 index 000000000..fe97a4a30 Binary files /dev/null and b/docs/images/app-connections/northflank/step-1.png differ diff --git a/docs/images/app-connections/northflank/step-2.png b/docs/images/app-connections/northflank/step-2.png new file mode 100644 index 000000000..e77d1e740 Binary files /dev/null and b/docs/images/app-connections/northflank/step-2.png differ diff --git a/docs/images/app-connections/northflank/step-3.png b/docs/images/app-connections/northflank/step-3.png new file mode 100644 index 000000000..739c4e48b Binary files /dev/null and b/docs/images/app-connections/northflank/step-3.png differ diff --git a/docs/images/app-connections/northflank/step-4-1.png b/docs/images/app-connections/northflank/step-4-1.png new file mode 100644 index 000000000..cd4a5dfaf Binary files /dev/null and b/docs/images/app-connections/northflank/step-4-1.png differ diff --git a/docs/images/app-connections/northflank/step-4-2.png b/docs/images/app-connections/northflank/step-4-2.png new file mode 100644 index 000000000..52789f9d1 Binary files /dev/null and b/docs/images/app-connections/northflank/step-4-2.png differ diff --git a/docs/images/app-connections/northflank/step-5.png b/docs/images/app-connections/northflank/step-5.png new file mode 100644 index 000000000..d8e9c817b Binary files /dev/null and b/docs/images/app-connections/northflank/step-5.png differ diff --git a/docs/images/app-connections/northflank/step-6.png b/docs/images/app-connections/northflank/step-6.png new file mode 100644 index 000000000..457a60cdf Binary files /dev/null and b/docs/images/app-connections/northflank/step-6.png differ diff --git a/docs/images/app-connections/northflank/step-7.png b/docs/images/app-connections/northflank/step-7.png new file mode 100644 index 000000000..76480665f Binary files /dev/null and b/docs/images/app-connections/northflank/step-7.png differ diff --git a/docs/images/integrations/github/integrations-github-config-new-pat.png b/docs/images/integrations/github/integrations-github-config-new-pat.png new file mode 100644 index 000000000..11766edfd Binary files /dev/null and b/docs/images/integrations/github/integrations-github-config-new-pat.png differ diff --git a/docs/images/platform/external-migrations/vault-in-platform/import-vault-kubernetes-role-modal.png b/docs/images/platform/external-migrations/vault-in-platform/import-vault-kubernetes-role-modal.png new file mode 100644 index 000000000..7cb345637 Binary files /dev/null and b/docs/images/platform/external-migrations/vault-in-platform/import-vault-kubernetes-role-modal.png differ diff --git a/docs/images/platform/gateways/assign-project.png b/docs/images/platform/gateways/assign-project.png deleted file mode 100644 index a1ff61909..000000000 Binary files a/docs/images/platform/gateways/assign-project.png and /dev/null differ diff --git a/docs/images/platform/gateways/create-identity-for-gateway.png b/docs/images/platform/gateways/create-identity-for-gateway.png deleted file mode 100644 index d7ef6b02a..000000000 Binary files a/docs/images/platform/gateways/create-identity-for-gateway.png and /dev/null differ diff --git a/docs/images/platform/gateways/dynamic-secret.png b/docs/images/platform/gateways/dynamic-secret.png deleted file mode 100644 index bf742413e..000000000 Binary files a/docs/images/platform/gateways/dynamic-secret.png and /dev/null differ diff --git a/docs/images/platform/gateways/edit-gateway.png b/docs/images/platform/gateways/edit-gateway.png deleted file mode 100644 index 04ef2a7d2..000000000 Binary files a/docs/images/platform/gateways/edit-gateway.png and /dev/null differ diff --git a/docs/images/platform/gateways/gateway-list.png b/docs/images/platform/gateways/gateway-list.png deleted file mode 100644 index 11f8206fe..000000000 Binary files a/docs/images/platform/gateways/gateway-list.png and /dev/null differ diff --git a/docs/images/secret-syncs/chef/select-option.png b/docs/images/secret-syncs/chef/select-option.png new file mode 100644 index 000000000..5fba1e415 Binary files /dev/null and b/docs/images/secret-syncs/chef/select-option.png differ diff --git a/docs/images/secret-syncs/chef/sync-created.png b/docs/images/secret-syncs/chef/sync-created.png new file mode 100644 index 000000000..c6383deb3 Binary files /dev/null and b/docs/images/secret-syncs/chef/sync-created.png differ diff --git a/docs/images/secret-syncs/chef/sync-destination.png b/docs/images/secret-syncs/chef/sync-destination.png new file mode 100644 index 000000000..073631956 Binary files /dev/null and b/docs/images/secret-syncs/chef/sync-destination.png differ diff --git a/docs/images/secret-syncs/chef/sync-details.png b/docs/images/secret-syncs/chef/sync-details.png new file mode 100644 index 000000000..3e8a92008 Binary files /dev/null and b/docs/images/secret-syncs/chef/sync-details.png differ diff --git a/docs/images/secret-syncs/chef/sync-options.png b/docs/images/secret-syncs/chef/sync-options.png new file mode 100644 index 000000000..75f507310 Binary files /dev/null and b/docs/images/secret-syncs/chef/sync-options.png differ diff --git a/docs/images/secret-syncs/chef/sync-review.png b/docs/images/secret-syncs/chef/sync-review.png new file mode 100644 index 000000000..de0f10f8a Binary files /dev/null and b/docs/images/secret-syncs/chef/sync-review.png differ diff --git a/docs/images/secret-syncs/chef/sync-source.png b/docs/images/secret-syncs/chef/sync-source.png new file mode 100644 index 000000000..877b104ef Binary files /dev/null and b/docs/images/secret-syncs/chef/sync-source.png differ diff --git a/docs/images/secret-syncs/northflank/configure-destination.png b/docs/images/secret-syncs/northflank/configure-destination.png new file mode 100644 index 000000000..08dcb96bf Binary files /dev/null and b/docs/images/secret-syncs/northflank/configure-destination.png differ diff --git a/docs/images/secret-syncs/northflank/configure-details.png b/docs/images/secret-syncs/northflank/configure-details.png new file mode 100644 index 000000000..edbfa0dac Binary files /dev/null and b/docs/images/secret-syncs/northflank/configure-details.png differ diff --git a/docs/images/secret-syncs/northflank/configure-source.png b/docs/images/secret-syncs/northflank/configure-source.png new file mode 100644 index 000000000..530613f03 Binary files /dev/null and b/docs/images/secret-syncs/northflank/configure-source.png differ diff --git a/docs/images/secret-syncs/northflank/configure-sync-options.png b/docs/images/secret-syncs/northflank/configure-sync-options.png new file mode 100644 index 000000000..6e03b1f5f Binary files /dev/null and b/docs/images/secret-syncs/northflank/configure-sync-options.png differ diff --git a/docs/images/secret-syncs/northflank/review-configuration.png b/docs/images/secret-syncs/northflank/review-configuration.png new file mode 100644 index 000000000..59df97a80 Binary files /dev/null and b/docs/images/secret-syncs/northflank/review-configuration.png differ diff --git a/docs/images/secret-syncs/northflank/select-option.png b/docs/images/secret-syncs/northflank/select-option.png new file mode 100644 index 000000000..0ee9ea2fa Binary files /dev/null and b/docs/images/secret-syncs/northflank/select-option.png differ diff --git a/docs/images/secret-syncs/northflank/sync-created.png b/docs/images/secret-syncs/northflank/sync-created.png new file mode 100644 index 000000000..388d78f4d Binary files /dev/null and b/docs/images/secret-syncs/northflank/sync-created.png differ diff --git a/docs/integrations/app-connections/chef.mdx b/docs/integrations/app-connections/chef.mdx new file mode 100644 index 000000000..60c49fb1f --- /dev/null +++ b/docs/integrations/app-connections/chef.mdx @@ -0,0 +1,142 @@ +--- +title: "Chef Connection" +description: "Learn how to configure a Chef Connection for Infisical." +--- + +Infisical supports the use of User Private Key to connect with Chef Server. + +Please access your **starter kit** to get all the required information to create a Chef Connection. + + + + If you download a new starter kit, your previous private key/user key will + no longer be valid. Please make sure to update all the places that use the + previous private key. + + + + ![Chef Server User Keys](/images/app-connections/chef/chef-dashboard.png) + + + ![Starter Kit](/images/app-connections/chef/starter-kit.png) + + + ![Download Starter + Kit](/images/app-connections/chef/download-starter-kit.png) + + + ![Extract Starter + Kit](/images/app-connections/chef/extract-starter-kit.png) + + + + + + + Open your starter kit's folder(or `chef-repo`) and navigate to the `.chef` + folder. + + Please make sure you have hidden files visible in your file explorer. + + ![.chef folder](/images/app-connections/chef/chef-folder.png) + + + In the `.chef` folder, you will find a `[your-username].pem` file. ![Private + Key File](/images/app-connections/chef/private-key-file.png) + + **Private Key:** Copy the content of the private key file. + + + + Open the `config.rb` file and copy the content of the file. + ![Config.rb File Content](/images/app-connections/chef/chef-connection-details.png) + + **User Name(1):** The user name of the chef user. + + **Server URL(2):** The server url of the chef server. + + **Organization Name(3):** The organization name of the chef server. + + + + +## Create a Chef Connection in Infisical via UI + + + + + + In your Infisical dashboard, navigate to the **App Connections** page in the desired project. + ![App Connections Tab](/images/app-connections/general/add-connection.png) + + + Click **+ Add Connection** and choose **Chef** Connection from the list of integrations. + ![Select Chef Connection](/images/app-connections/chef/app-connection-option.png) + + + Complete the form by providing: + - A descriptive name for the connection + - An optional description + - Server URL(optional): The URL of the Chef server to connect with (defaults to https://api.chef.io) + - Organization short name + - User name + - Private key: Your Chef user's private key (.pem file) + + ![Chef Connection Modal](/images/app-connections/chef/app-connection-form.png) + + + After submitting the form, your **Chef Connection** will be successfully created and ready to use with your Infisical project. + ![Chef Connection Created](/images/app-connections/chef/app-connection-generated.png) + + + + + + + To create a Chef Connection via API, send a request to the [Create Chef Connection](/api-reference/endpoints/app-connections/chef/create) endpoint. + + ### Sample request + + ```bash Request + curl --request POST \ + --url https://app.infisical.com/api/v1/app-connections/chef \ + --header 'Content-Type: application/json' \ + --data '{ + "name": "my-chef-connection", + "method": "user-key", + "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78", + "credentials": { + "orgName": "my-org", + "userName": "my-user", + "privateKey": "your-private-key" + } + }' + ``` + + ### Sample response + + ```bash Response + { + "appConnection": { + "id": "a1b2c3d4-5678-90ab-cdef-1234567890ab", + "name": "my-chef-connection", + "description": null, + "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78", + "version": 1, + "orgId": "abcdef12-3456-7890-abcd-ef1234567890", + "createdAt": "2025-10-13T10:15:00.000Z", + "updatedAt": "2025-10-13T10:15:00.000Z", + "isPlatformManagedCredentials": false, + "credentialsHash": "d41d8cd98f00b204e9800998ecf8427e", + "app": "chef", + "method": "user-key", + "credentials": { + "orgName": "my-org", + "userName": "my-user", + } + } + } + ``` + + + diff --git a/docs/integrations/app-connections/github.mdx b/docs/integrations/app-connections/github.mdx index e44fc405a..40eb0525f 100644 --- a/docs/integrations/app-connections/github.mdx +++ b/docs/integrations/app-connections/github.mdx @@ -3,7 +3,7 @@ title: "GitHub Connection" description: "Learn how to configure a GitHub Connection for Infisical." --- -Infisical supports two methods for connecting to GitHub. +Infisical supports three methods for connecting to GitHub. @@ -178,5 +178,72 @@ Infisical supports two methods for connecting to GitHub. + + Infisical will use a Personal Access Token to connect to GitHub. + + ## Create a Personal Access Token + + + Navigate to your user Settings > Developer settings > Personal Access Tokens to create a new Personal Access Token. + + ![integrations github config](../../images/integrations/github/integrations-github-config-settings.png) + ![integrations github config](../../images/integrations/github/integrations-github-config-dev-settings.png) + ![integrations github config](../../images/integrations/github/integrations-github-config-new-pat.png) + + Click **Generate new token** to create the token. + + + Fill in the Personal Access Token details: + - **Token name:** A descriptive name for the token (e.g., "infisical-connection-token") + - **Repository access:** Select the repositories you want to grant access to + - Select `All repositories` or `Only selected repositories` to be able to manage the secrets in the selected repositories. + - **Select scopes:** Add the following scopes: + - **Metadata**: Read-only + - **Environments**: Read and write + - **Secrets**: Read and write + + ![Personal Access Token Form](/images/app-connections/github/create-pat-form.png) + + Click **Generate token** to create the token. + + + Copy the generated token immediately as it won't be shown again. + + ![Personal Access Token Generated](/images/app-connections/github/create-pat-token-generated.png) + + + Keep your Personal Access Token secure and do not share it. Anyone with access to this token can access your GitHub account and repositories. + + + + + ## Setup GitHub Connection in Infisical + + + + Navigate to the **App Connections** page in the desired project. + ![App Connections Tab](/images/app-connections/general/add-connection.png) + + + Select the **GitHub Connection** option from the connection options modal. + ![Select GitHub Connection](/images/app-connections/github/select-github-connection.png) + + + Select the **Personal Access Token** method and fill in the **Personal Access Token** field with your Personal Access Token. + + You may optionally configure GitHub Enterprise options: + - **Gateway:** The gateway connected to your private network + - **Hostname:** The hostname at which to access your GitHub Enterprise instance + + Click **Create Connection**. + + ![Personal Access Token](/images/app-connections/github/create-pat-method.png) + + + Your **GitHub Connection** is now available for use. + ![Personal Access Token Connection](/images/app-connections/github/pat-connection.png) + + + diff --git a/docs/integrations/app-connections/gitlab.mdx b/docs/integrations/app-connections/gitlab.mdx index 4f7223d93..c9af952a7 100644 --- a/docs/integrations/app-connections/gitlab.mdx +++ b/docs/integrations/app-connections/gitlab.mdx @@ -187,31 +187,92 @@ Infisical supports two methods for connecting to GitLab: **OAuth** and **Access - - ## Setup GitLab Access Token Connection in Infisical + + Group access tokens provide access to all projects within a GitLab group, offering group-level control. - - - Navigate to the **App Connections** page in the desired project. - ![App Connections Tab](/images/app-connections/general/add-connection.png) - - - Select the **GitLab Connection** option from the connection options modal. - ![Select GitLab Connection](/images/app-connections/gitlab/select-gitlab-connection.png) - - - Select the **Access Token** method, paste your GitLab access token in the provided field, and select the appropriate token type. + + + Go to your GitLab group and navigate to Settings > Access Tokens. Click **Add new token** to create a new group access token. + ![GitLab Group Access Tokens](/images/app-connections/gitlab/gitlab-group-access-token-list.png) + + + Fill in the token details: + - **Token name**: A descriptive name for the token + - **Expiration date**: Set an appropriate expiration date + - **Select role and scopes**: Depending on your use case, add the required role and one or more of the following scopes: - ![Configure Access Token](/images/app-connections/gitlab/create-gitlab-access-token-connection.png) + + + For Secret Syncs, the required role depends on your sync destination: + - **Project variables**: Requires **Maintainer** role or higher + - **Group variables**: Requires **Owner** role - Click **Connect** to establish the connection. - - - Your **GitLab Connection** is now available for use. - ![GitLab Access Token Connection](/images/app-connections/gitlab/gitlab-access-token-connection.png) - - + Your token will require the `api` scope. + + ![GitLab Create Group Token](/images/app-connections/gitlab/gitlab-group-access-token-form-secret-sync.png) + + Click **Create group access token** to create the token. + + + Use the **Owner** role if you need to sync to group-level variables. The **Maintainer** role is sufficient only for project-level variables. + + + + To set up Secret Scanning, the required permissions depend on the data source level: + - **Project-level data source:** Requires **Maintainer** role or higher + - **Group-level data source:** Requires **Owner** role + + Your token will require the `api` scope. + + ![GitLab Create Group Token](/images/app-connections/gitlab/gitlab-group-access-token-form-secret-sync.png) + + Click **Create group access token** to create the token. + + + + + Group Access Token connections require manual token rotation when your GitLab access token expires or is regenerated. Monitor your connection status and update the token as needed. + + + + Copy the generated token immediately as it won't be shown again. + ![GitLab Group Token Created](/images/app-connections/gitlab/gitlab-group-access-token-created.png) + + Keep your access token secure and do not share it. Anyone with access to this token can access all projects within your GitLab group. + + + + + + + + +## Setup GitLab Access Token Connection in Infisical + + + + Navigate to the **App Connections** page in the desired project. + ![App Connections Tab](/images/app-connections/general/add-connection.png) + + + Select the **GitLab Connection** option from the connection options modal. + ![Select GitLab Connection](/images/app-connections/gitlab/select-gitlab-connection.png) + + + Select the **Access Token** method, paste your GitLab access token in the provided field, and select the appropriate token type. + + ![Configure Access Token](/images/app-connections/gitlab/create-gitlab-access-token-connection.png) + + Click **Connect** to establish the connection. + + + + + Your **GitLab Connection** is now available for use. + ![GitLab Access Token Connection](/images/app-connections/gitlab/gitlab-access-token-connection.png) + + diff --git a/docs/integrations/app-connections/northflank.mdx b/docs/integrations/app-connections/northflank.mdx new file mode 100644 index 000000000..0435c3e95 --- /dev/null +++ b/docs/integrations/app-connections/northflank.mdx @@ -0,0 +1,125 @@ +--- +title: "Northflank Connection" +description: "Learn how to configure a Northflank Connection for Infisical." +--- + +Infisical supports the use of [API Tokens](https://northflank.com/docs/v1/api/use-the-api) to connect with Northflank. + + + Infisical recommends creating a specific API role for the app connection and only giving access to projects that will use the integration. + + +## Create a Northflank API Token + + + + Navigate to your team page and click **Create token**. + + ![Create API Role](/images/app-connections/northflank/step-1.png) + + Click on **Create API role**. + + ![Create API Role](/images/app-connections/northflank/step-2.png) + + Select all the projects you want this role to have access to, or leave this unchecked if you want to give access to all projects. + + ![Create API Role](/images/app-connections/northflank/step-3.png) + + Add the **Projects** -> **Manage** -> **Read** permission. + + ![Create API Role](/images/app-connections/northflank/step-4-1.png) + + Add the **Config & Secrets** -> **Secret Groups** -> **List**, **Update** and **Read Values** permissions. + + ![Create API Role](/images/app-connections/northflank/step-4-2.png) + + Scroll to the bottom and save the API role. + + + Click on the **API** -> **Tokens** menu on the left and then click the **Create API token** button. + + ![Create API Token](/images/app-connections/northflank/step-5.png) + + Give a name to the API token and click the **Use role** button for the new API role you just created. + + ![Create API Token](/images/app-connections/northflank/step-6.png) + + Click the **View API token** icon to view and copy your token. + + ![Create API Token](/images/app-connections/northflank/step-7.png) + + + +## Create a Northflank Connection in Infisical + + + + + + In your Infisical dashboard, navigate to the **App Connections** page in the desired project. + + ![App Connections Tab](/images/app-connections/general/add-connection.png) + + + Click **+ Add Connection** and choose **Northflank Connection** from the list of integrations. + + ![Select Northflank Connection](/images/app-connections/northflank/northflank-app-connection-option.png) + + + Complete the form by providing: + - A descriptive name for the connection + - An optional description + - The API Token from the previous step + + ![Northflank Connection Modal](/images/app-connections/northflank/northflank-app-connection-form.png) + + + After submitting the form, your **Northflank Connection** will be successfully created and ready to use with your Infisical project. + + ![Northflank Connection Created](/images/app-connections/northflank/northflank-app-connection-generated.png) + + + + + + To create a Northflank Connection via API, send a request to the [Create Northflank Connection](/api-reference/endpoints/app-connections/northflank/create) endpoint. + + ### Sample request + + ```bash Request + curl --request POST \ + --url https://app.infisical.com/api/v1/app-connections/northflank \ + --header 'Content-Type: application/json' \ + --data '{ + "name": "my-northflank-connection", + "method": "api-token", + "projectId": "abcdef12-3456-7890-abcd-ef1234567890", + "credentials": { + "apiToken": "[API TOKEN]" + } + }' + ``` + + ### Sample response + + ```bash Response + { + "appConnection": { + "id": "a1b2c3d4-5678-90ab-cdef-1234567890ab", + "name": "my-northflank-connection", + "description": null, + "projectId": "abcdef12-3456-7890-abcd-ef1234567890", + "version": 1, + "orgId": "abcdef12-3456-7890-abcd-ef1234567890", + "createdAt": "2025-01-23T10:15:00.000Z", + "updatedAt": "2025-01-23T10:15:00.000Z", + "isPlatformManagedCredentials": false, + "credentialsHash": "d41d8cd98f00b204e9800998ecf8427e", + "app": "northflank", + "method": "api-token", + "credentials": {} + } + } + ``` + + \ No newline at end of file diff --git a/docs/integrations/platforms/kubernetes-injector.mdx b/docs/integrations/platforms/kubernetes-injector.mdx index d5d48598b..b7ecf5815 100644 --- a/docs/integrations/platforms/kubernetes-injector.mdx +++ b/docs/integrations/platforms/kubernetes-injector.mdx @@ -63,6 +63,7 @@ The Infisical Agent Injector supports the following annotations: - `init`: The init method will create an init container for the pod that will render the secrets into a shared volume mount within the pod. The agent init container will run before any other containers in the pod runs, including other init containers. - `sidecar`: The sidecar method will create a sidecar container for the pod that will render the secrets into a shared volume mount within the pod. The agent sidecar container will run alongside the main container in the pod. This means that the secrets rendered will always be in sync with your Infisical secrets. + - `sidecar-init`: The sidecar-init method will create the init container and the sidecar container from the other two methods. The init container will run before any other container and fetch the secrets from the start and the sidecar container will keep the secrets in sync throughout the lifecycle of the deployment. The agent config map annotation is used to specify the name of the config map that contains the configuration for the injector. The config map must be in the same namespace as the pod. diff --git a/docs/integrations/platforms/kubernetes/overview.mdx b/docs/integrations/platforms/kubernetes/overview.mdx index ce9afcced..71ae05c46 100644 --- a/docs/integrations/platforms/kubernetes/overview.mdx +++ b/docs/integrations/platforms/kubernetes/overview.mdx @@ -41,6 +41,29 @@ If you require stronger isolation and stricter access controls, a namespace-scop ```bash helm install --generate-name infisical-helm-charts/secrets-operator ``` + + + By default a service account is created for the operator based on the operator release name. + You can bring your own service account by setting `controllerManager.serviceAccount.create` to `false` and setting `controllerManager.serviceAccount.name` to the name of the service account you want to use in your values.yaml file. + + Example values.yaml file: + + ```yaml values.yaml + controllerManager: + serviceAccount: + create: false + name: my-service-account + # other values... + ``` + + + Please note that if you set `controllerManager.serviceAccount.create` to `false`, the service account needs to already exist in the namespace you are installing the operator in. + + + + Custom service accounts are supported in chart version `0.10.11` and above. Please upgrade your helm chart to `0.10.11` or above before attempting to use custom service accounts. + + The operator can be configured to watch and manage secrets in a specific namespace instead of having cluster-wide access. This is useful for: @@ -67,6 +90,29 @@ If you require stronger isolation and stricter access controls, a namespace-scop --set installCRDs=false ``` + + By default a service account is created for the operator based on the operator release name. + You can bring your own service account by setting `controllerManager.serviceAccount.create` to `false` and setting `controllerManager.serviceAccount.name` to the name of the service account you want to use in your values.yaml file. + + Example values.yaml file: + + ```yaml values.yaml + controllerManager: + serviceAccount: + create: false + name: my-service-account + # other values... + ``` + + + Please note that if you set `controllerManager.serviceAccount.create` to `false`, the service account needs to already exist in the namespace you are installing the operator in. + + + + Custom service accounts are supported in chart version `0.10.11` and above. Please upgrade your helm chart to `0.10.11` or above before attempting to use custom service accounts. + + + When scoped to a namespace, the operator will: - Only watch InfisicalSecrets in the specified namespace @@ -158,14 +204,17 @@ The Infisical Secrets Operator integrates with the [Sprig library](https://githu ## Global configuration -To configure global settings that will apply to all instances of `InfisicalSecret`, you can define these configurations in a Kubernetes ConfigMap. -For example, you can configure all `InfisicalSecret` instances to fetch secrets from a single backend API without specifying the `hostAPI` parameter for each instance. +To configure global settings that will apply to all CRD instances (`InfisicalSecret`, `InfisicalPushSecret`, and `InfisicalDynamicSecret`), you can define these configurations in a Kubernetes ConfigMap. +For example, you can configure all CRD instances to fetch secrets from a single backend API without specifying the `hostAPI` parameter for each instance. ### Available global properties | Property | Description | Default value | | -------- | --------------------------------------------------------------------------------- | ----------------------------- | -| hostAPI | If `hostAPI` in `InfisicalSecret` instance is left empty, this value will be used | https://app.infisical.com/api | +| hostAPI | If `hostAPI` in a CRD instance is left empty, this value will be used | https://app.infisical.com/api | +| tls.caRef.secretName | If `tls.caRef.secretName` in a CRD instance is left empty, this value will be used | - | +| tls.caRef.secretNamespace | If `tls.caRef.secretNamespace` in a CRD instance is left empty, this value will be used | - | +| tls.caRef.key | If `tls.caRef.key` in a CRD instance is left empty, this value will be used | - | ### Applying global configurations @@ -185,6 +234,9 @@ metadata: namespace: infisical-operator-system data: hostAPI: https://example.com/api # <-- global hostAPI + tls.caRef.secretName: custom-ca-certificate # <-- global TLS CA secret name + tls.caRef.secretNamespace: default # <-- global TLS CA secret namespace + tls.caRef.key: ca.crt # <-- global TLS CA secret key ``` Then apply this change via kubectl by running the following diff --git a/docs/integrations/secret-syncs/chef.mdx b/docs/integrations/secret-syncs/chef.mdx new file mode 100644 index 000000000..13f3b3474 --- /dev/null +++ b/docs/integrations/secret-syncs/chef.mdx @@ -0,0 +1,154 @@ +--- +title: "Chef Sync" +description: "Learn how to configure a Chef Sync for Infisical." +--- + +**Prerequisites:** + +- Create a [Chef Connection](/integrations/app-connections/chef) + + + + + + Navigate to **Project** > **Integrations** and select the **Secret Syncs** tab. Click on the **Add Sync** button. + + ![Secret Syncs Tab](/images/secret-syncs/general/secret-sync-tab.png) + + + ![Select Chef](/images/secret-syncs/chef/select-option.png) + + + Configure the **Source** from where secrets should be retrieved, then click **Next**. + + ![Configure Source](/images/secret-syncs/chef/sync-source.png) + + - **Environment**: The project environment to retrieve secrets from. + - **Secret Path**: The folder path to retrieve secrets from. + + + If you need to sync secrets from multiple folder locations, check out [secret imports](/documentation/platform/secret-reference#secret-imports). + + + + Configure the **Destination** to where secrets should be deployed, then click **Next**. + + ![Configure Destination](/images/secret-syncs/chef/sync-destination.png) + + - **Chef Connection**: The Chef Connection to authenticate with. + - **Data Bag**: The Data Bag to sync secrets to. + - **Data Bag Item**: The Data Bag Item to sync secrets to. + + + Configure the **Sync Options** to specify how secrets should be synced, then click **Next**. + + ![Configure Options](/images/secret-syncs/chef/sync-options.png) + + - **Initial Sync Behavior**: Determines how Infisical should resolve the initial sync. + - **Overwrite Destination Secrets**: Removes any secrets at the destination endpoint not present in Infisical. + - **Import Secrets (Prioritize Infisical)**: Imports secrets from the destination endpoint before syncing, prioritizing values from Infisical over Chef when keys conflict. + - **Import Secrets (Prioritize Chef)**: Imports secrets from the destination endpoint before syncing, prioritizing values from Chef over Infisical when keys conflict. + - **Key Schema**: Template that determines how secret names are transformed when syncing, using `{{secretKey}}` as a placeholder for the original secret name and `{{environment}}` for the environment. + + We highly recommend using a Key Schema to ensure that Infisical only manages the specific keys you intend, keeping everything else untouched. + + - **Auto-Sync Enabled**: If enabled, secrets will automatically be synced from the source location when changes occur. Disable to enforce manual syncing only. + - **Disable Secret Deletion**: If enabled, Infisical will not remove secrets from the sync destination. Enable this option if you intend to manage some secrets manually outside of Infisical. + + + Configure the **Details** of your Chef Sync, then click **Next**. + + ![Configure Details](/images/secret-syncs/chef/sync-details.png) + + - **Name**: The name of your sync. Must be slug-friendly. + - **Description**: An optional description for your sync. + + + Review your Chef Sync configuration, then click **Create Sync**. + + ![Review Configuration](/images/secret-syncs/chef/sync-review.png) + + + If enabled, your Chef Sync will begin syncing your secrets to the destination endpoint. + + ![Sync Created](/images/secret-syncs/chef/sync-created.png) + + + + + + + To create a **Chef Sync**, make an API request to the [Create Chef Sync](/api-reference/endpoints/secret-syncs/chef/create) API endpoint. + + ### Sample request + + ```bash Request + curl --request POST \ + --url https://app.infisical.com/api/v1/secret-syncs/chef \ + --header 'Content-Type: application/json' \ + --data '{ + "name": "my-chef-sync", + "projectId": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "description": "sync to chef site", + "connectionId": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "environment": "dev", + "secretPath": "/", + "isEnabled": true, + "isAutoSyncEnabled": true, + "syncOptions": { + "initialSyncBehavior": "overwrite-destination", + "disableSecretDeletion": false + }, + "destinationConfig": { + "dataBagName": "my-data-bag", + "dataBagItemName": "my-data-bag-item" + } + }' + ``` + + ### Sample response + + ```bash Response + { + "secretSync": { + "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "name": "my-chef-sync", + "description": "sync to chef site", + "folderId": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "connectionId": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "createdAt": "2025-07-19T12:00:00Z", + "updatedAt": "2025-07-19T12:00:00Z", + "syncStatus": "succeeded", + "lastSyncJobId": "job-1234", + "lastSyncMessage": null, + "lastSyncedAt": "2025-07-19T12:00:00Z", + "syncOptions": { + "initialSyncBehavior": "overwrite-destination", + "disableSecretDeletion": false + }, + "projectId": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "connection": { + "app": "chef", + "name": "my-chef-connection", + "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a" + }, + "environment": { + "slug": "dev", + "name": "Development", + "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a" + }, + "folder": { + "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "path": "/" + }, + "destination": "chef", + "destinationConfig": { + "dataBagName": "my-data-bag", + "dataBagItemName": "my-data-bag-item" + } + } + } + ``` + + + diff --git a/docs/integrations/secret-syncs/northflank.mdx b/docs/integrations/secret-syncs/northflank.mdx new file mode 100644 index 000000000..66075c967 --- /dev/null +++ b/docs/integrations/secret-syncs/northflank.mdx @@ -0,0 +1,160 @@ +--- +title: "Northflank Sync" +description: "Learn how to configure a Northflank Sync for Infisical." +--- + +**Prerequisites:** +- Create a [Northflank Connection](/integrations/app-connections/northflank) + + + + + + Navigate to **Project** > **Integrations** and select the **Secret Syncs** tab. Click on the **Add Sync** button. + + ![Secret Syncs Tab](/images/secret-syncs/general/secret-sync-tab.png) + + + ![Select Northflank](/images/secret-syncs/northflank/select-option.png) + + + Configure the **Source** from where secrets should be retrieved, then click **Next**. + + ![Configure Source](/images/secret-syncs/northflank/configure-source.png) + + - **Environment**: The project environment to retrieve secrets from. + - **Secret Path**: The folder path to retrieve secrets from. + + + If you need to sync secrets from multiple folder locations, check out [secret imports](/documentation/platform/secret-reference#secret-imports). + + + + Configure the **Destination** to where secrets should be deployed, then click **Next**. + + ![Configure Destination](/images/secret-syncs/northflank/configure-destination.png) + + - **Northflank Connection**: The Northflank Connection to authenticate with. + - **Project**: The Northflank project to sync secrets to. + - **Secret Group**: The Northflank secret group to sync secrets to. + + + Configure the **Sync Options** to specify how secrets should be synced, then click **Next**. + + ![Configure Sync Options](/images/secret-syncs/northflank/configure-sync-options.png) + + - **Initial Sync Behavior**: Determines how Infisical should resolve the initial sync. + - **Overwrite Destination Secrets**: Removes any secrets at the destination endpoint not present in Infisical. + - **Import Destination Secrets - Prioritize Infisical Values**: Imports any secrets present in the Northflank destination prior to syncing, prioritizing values from Infisical over Northflank when keys conflict. + - **Import Destination Secrets - Prioritize Northflank Values**: Imports any secrets present in the Northflank destination prior to syncing, prioritizing values from Northflank over Infisical when keys conflict. + - **Key Schema**: Template that determines how secret names are transformed when syncing, using `{{secretKey}}` as a placeholder for the original secret name and `{{environment}}` for the environment. + + We highly recommend using a Key Schema to ensure that Infisical only manages the specific keys you intend, keeping everything else untouched. + + - **Auto-Sync Enabled**: If enabled, secrets will automatically be synced from the source location when changes occur. Disable to enforce manual syncing only. + - **Disable Secret Deletion**: If enabled, Infisical will not remove secrets from the sync destination. Enable this option if you intend to manage some secrets manually outside of Infisical. + + + Configure the **Details** of your Northflank Sync, then click **Next**. + + ![Configure Details](/images/secret-syncs/northflank/configure-details.png) + + - **Name**: The name of your sync. Must be slug-friendly. + - **Description**: An optional description for your sync. + + + Review your Northflank Sync configuration, then click **Create Sync**. + + ![Review Configuration](/images/secret-syncs/northflank/review-configuration.png) + + + If enabled, your Northflank Sync will begin syncing your secrets to the destination endpoint. + + ![Sync Created](/images/secret-syncs/northflank/sync-created.png) + + + + + To create a **Northflank Sync**, make an API request to the [Create Northflank Sync](/api-reference/endpoints/secret-syncs/northflank/create) API endpoint. + + ### Sample request + + ```bash Request + curl --request POST \ + --url https://app.infisical.com/api/v1/secret-syncs/northflank \ + --header 'Content-Type: application/json' \ + --data '{ + "name": "my-northflank-sync", + "projectId": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "description": "an example sync", + "connectionId": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "environment": "dev", + "secretPath": "/my-secrets", + "isAutoSyncEnabled": true, + "syncOptions": { + "initialSyncBehavior": "overwrite-destination", + "keySchema": "INFISICAL_{{secretKey}}" + }, + "destinationConfig": { + "projectId": "my-project-id", + "secretGroupId": "my-secret-group-id" + } + }' + ``` + + ### Sample response + + ```json Response + { + "secretSync": { + "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "name": "my-northflank-sync", + "description": "an example sync", + "isAutoSyncEnabled": true, + "version": 1, + "folderId": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "connectionId": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "createdAt": "2023-11-07T05:31:56Z", + "updatedAt": "2023-11-07T05:31:56Z", + "syncStatus": "succeeded", + "lastSyncJobId": "123", + "lastSyncMessage": null, + "lastSyncedAt": "2023-11-07T05:31:56Z", + "importStatus": null, + "lastImportJobId": null, + "lastImportMessage": null, + "lastImportedAt": null, + "removeStatus": null, + "lastRemoveJobId": null, + "lastRemoveMessage": null, + "lastRemovedAt": null, + "syncOptions": { + "initialSyncBehavior": "overwrite-destination", + "keySchema": "INFISICAL_{{secretKey}}", + "disableSecretDeletion": false + }, + "projectId": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "connection": { + "app": "northflank", + "name": "my-northflank-connection", + "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a" + }, + "environment": { + "slug": "dev", + "name": "Development", + "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a" + }, + "folder": { + "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a", + "path": "/my-secrets" + }, + "destination": "northflank", + "destinationConfig": { + "projectId": "my-project-id", + "secretGroupId": "my-secret-group-id" + } + } + } + ``` + + \ No newline at end of file diff --git a/docs/sdks/languages/python.mdx b/docs/sdks/languages/python.mdx index 066ecc060..670e0975a 100644 --- a/docs/sdks/languages/python.mdx +++ b/docs/sdks/languages/python.mdx @@ -72,6 +72,7 @@ The SDK methods are organized into the following high-level categories: 1. `auth`: Handles authentication methods. 2. `secrets`: Manages CRUD operations for secrets. 3. `kms`: Perform cryptographic operations with Infisical KMS. +4. `folders`: Manages folder-related operations. ### `auth` @@ -415,4 +416,66 @@ decrypted_data = client.kms.decrypt_data( - `ciphertext` (str): The ciphertext returned from the encrypt operation. **Returns:** -- `str`: The base64 encoded plaintext. \ No newline at end of file +- `str`: The base64 encoded plaintext. + +### `folders` + +This sub-class handles operations related to folders: + +#### List Folders + +```python +folders = client.folders.list_folders( + project_id="", + environment_slug="dev", + path="/", + recursive=False, # Optional + last_secret_modified=None # Optional +) +``` + +**Parameters:** +- `project_id` (str): The ID of your project. +- `environment_slug` (str): The environment in which to list folders. +- `path` (str): The path to list folders from. +- `recursive` (bool, optional): Whether to list folders recursively from the specified path and downwards. Defaults to `False`. +- `last_secret_modified` (datetime, optional): The timestamp used to filter folders with secrets modified after the specified date. Defaults to `None`. + +**Returns:** +- `ListFoldersResponse`: The response containing the list of folders. + +#### Create Folder + +```python +new_folder = client.folders.create_folder( + name="my-folder", + environment_slug="dev", + project_id="", + path="/", # Optional + description=None # Optional +) +``` + +**Parameters:** +- `name` (str): The name of the folder to create. +- `environment_slug` (str): The slug of the environment to create the folder in. +- `project_id` (str): The ID of your project to create the folder in. +- `path` (str, optional): The path to create the folder in. Defaults to `/`. +- `description` (str, optional): An optional description label for the folder. Defaults to `None`. + +**Returns:** +- `CreateFolderResponseItem`: The response containing the created folder. + +#### Get Folder by ID + +```python +folder = client.folders.get_folder_by_id( + id="" +) +``` + +**Parameters:** +- `id` (str): The ID of the folder to retrieve. + +**Returns:** +- `SingleFolderResponseItem`: The response containing the folder details. \ No newline at end of file diff --git a/docs/self-hosting/guides/monitoring-telemetry.mdx b/docs/self-hosting/guides/monitoring-telemetry.mdx index 1c2d05702..b23c51b27 100644 --- a/docs/self-hosting/guides/monitoring-telemetry.mdx +++ b/docs/self-hosting/guides/monitoring-telemetry.mdx @@ -319,80 +319,137 @@ helm install otel-collector open-telemetry/opentelemetry-collector \ --set config.exporters.prometheus.endpoint=0.0.0.0:8889 ``` -## Alternative Backends - -Since Infisical exports in OpenTelemetry format, you can easily configure the collector to send metrics to other backends instead of (or in addition to) Prometheus: - -### Cloud-Native Examples - -```yaml -# Add to your otel-collector-config.yaml exporters section -exporters: - # AWS CloudWatch - awsemf: - region: us-west-2 - log_group_name: /aws/emf/infisical - log_stream_name: metrics - - # Google Cloud Monitoring - googlecloud: - project_id: your-project-id - - # Azure Monitor - azuremonitor: - connection_string: "your-connection-string" - - # Datadog - datadog: - api: - key: "your-api-key" - site: "datadoghq.com" - - # New Relic - newrelic: - apikey: "your-api-key" - host_override: "otlp.nr-data.net" -``` - -### Multi-Backend Configuration - -```yaml -service: - pipelines: - metrics: - receivers: [otlp] - processors: [batch] - exporters: [prometheus, awsemf, datadog] # Send to multiple backends -``` - -## Setting Up Grafana - -1. **Access Grafana**: Navigate to your Grafana instance -2. **Login**: Use your configured credentials -3. **Add Prometheus Data Source**: - - Go to Configuration → Data Sources - - Click "Add data source" - - Select "Prometheus" - - Set URL to your Prometheus endpoint - - Click "Save & Test" - ## Available Metrics Infisical exposes the following key metrics in OpenTelemetry format: -### API Performance Metrics +### Core API Metrics -- `API_latency` - API request latency histogram in milliseconds +These metrics track all HTTP API requests to Infisical, including request counts, latency, and errors. Use these to monitor overall API health, identify performance bottlenecks, and track usage patterns across users and machine identities. - - **Labels**: `route`, `method`, `statusCode` - - **Example**: Monitor response times for specific endpoints +#### Total API Requests -- `API_errors` - API error count histogram - - **Labels**: `route`, `method`, `type`, `name` - - **Example**: Track error rates by endpoint and error type +- **Metric Name**: `infisical.http.server.request.count` +- **Type**: Counter +- **Unit**: `{request}` +- **Description**: Total number of API requests to Infisical (covers both human users and machine identities) +- **Attributes**: + - `infisical.organization.id` (string): Organization ID + - `infisical.organization.name` (string): Organization name (e.g., "Platform Engineering Team") + - `infisical.user.id` (string, optional): User ID if human user + - `infisical.user.email` (string, optional): User email (e.g., "jane.doe@cisco.com") + - `infisical.identity.id` (string, optional): Machine identity ID + - `infisical.identity.name` (string, optional): Machine identity name (e.g., "prod-k8s-operator") + - `infisical.auth.method` (string, optional): Auth method used + - `http.request.method` (string): HTTP method (GET, POST, PUT, DELETE) + - `http.route` (string): API endpoint route pattern + - `http.response.status_code` (int): HTTP status code + - `infisical.project.id` (string, optional): Project ID + - `infisical.project.name` (string, optional): Project name + - `user_agent.original` (string, optional): User agent string + - `client.address` (string, optional): IP address + +#### Request Duration + +- **Metric Name**: `infisical.http.server.request.duration` +- **Type**: Histogram +- **Unit**: `s` (seconds) +- **Description**: API request latency +- **Buckets**: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10] +- **Attributes**: + - `infisical.organization.id` (string): Organization ID + - `infisical.organization.name` (string): Organization name + - `infisical.user.id` (string, optional): User ID if human user + - `infisical.user.email` (string, optional): User email + - `infisical.identity.id` (string, optional): Machine identity ID + - `infisical.identity.name` (string, optional): Machine identity name + - `http.request.method` (string): HTTP method + - `http.route` (string): API endpoint route pattern + - `http.response.status_code` (int): HTTP status code + - `infisical.project.id` (string, optional): Project ID + - `infisical.project.name` (string, optional): Project name + +#### API Errors by Actor + +- **Metric Name**: `infisical.http.server.error.count` +- **Type**: Counter +- **Unit**: `{error}` +- **Description**: API errors grouped by actor (for identifying misconfigured services) +- **Attributes**: + - `infisical.organization.id` (string): Organization ID + - `infisical.organization.name` (string): Organization name + - `infisical.user.id` (string, optional): User ID if human + - `infisical.user.email` (string, optional): User email + - `infisical.identity.id` (string, optional): Identity ID if machine + - `infisical.identity.name` (string, optional): Identity name + - `http.route` (string): API endpoint where error occurred + - `http.request.method` (string): HTTP method + - `error.type` (string): Error category/type (client_error, server_error, auth_error, rate_limit_error, etc.) + - `infisical.project.id` (string, optional): Project ID + - `infisical.project.name` (string, optional): Project name + - `client.address` (string, optional): IP address + - `user_agent.original` (string, optional): User agent information + +### Secret Operations Metrics + +These metrics provide visibility into secret access patterns, helping you understand which secrets are being accessed, by whom, and from where. Essential for security auditing and access pattern analysis. + +#### Secret Read Operations + +- **Metric Name**: `infisical.secret.read.count` +- **Type**: Counter +- **Unit**: `{operation}` +- **Description**: Number of secret read operations +- **Attributes**: + - `infisical.organization.id` (string): Organization ID + - `infisical.organization.name` (string): Organization name + - `infisical.project.id` (string): Project ID + - `infisical.project.name` (string): Project name (e.g., "payment-service-secrets") + - `infisical.environment` (string): Environment (dev, staging, prod) + - `infisical.secret.path` (string): Path to secrets (e.g., "/microservice-a/database") + - `infisical.secret.name` (string, optional): Name of secret + - `infisical.user.id` (string, optional): User ID if human + - `infisical.user.email` (string, optional): User email + - `infisical.identity.id` (string, optional): Machine identity ID + - `infisical.identity.name` (string, optional): Machine identity name + - `user_agent.original` (string, optional): User agent/SDK information + - `client.address` (string, optional): IP address + +### Authentication Metrics + +These metrics track authentication attempts and outcomes, enabling you to monitor login success rates, detect potential security threats, and identify authentication issues. + +#### Login Attempts + +- **Metric Name**: `infisical.auth.attempt.count` +- **Type**: Counter +- **Unit**: `{attempt}` +- **Description**: Authentication attempts (both successful and failed) +- **Attributes**: + - `infisical.organization.id` (string): Organization ID + - `infisical.organization.name` (string): Organization name + - `infisical.user.id` (string, optional): User ID if human (if identifiable) + - `infisical.user.email` (string, optional): User email (if identifiable) + - `infisical.identity.id` (string, optional): Identity ID if machine (if identifiable) + - `infisical.identity.name` (string, optional): Identity name (if identifiable) + - `infisical.auth.method` (string): Authentication method attempted + - `infisical.auth.result` (string): success or failure + - `error.type` (string, optional): Reason for failure if failed (invalid_credentials, expired_token, invalid_token, etc.) + - `client.address` (string): IP address + - `user_agent.original` (string, optional): User agent/client information + - `infisical.auth.attempt.username` (string, optional): Attempted username/email (if available) + +### Legacy Metrics + +These metrics are from the previous instrumentation and may be deprecated in future versions. Consider migrating to the new Core API Metrics for more comprehensive observability. + +- `API_latency` - API request latency histogram in milliseconds (Labels: `route`, `method`, `statusCode`) +- `API_errors` - API error count histogram (Labels: `route`, `method`, `type`, `name`) ### Integration & Secret Sync Metrics +These metrics monitor secret synchronization operations between Infisical and external systems, helping you track sync health, identify integration failures, and troubleshoot connectivity issues. + - `integration_secret_sync_errors` - Integration secret sync error count - **Labels**: `version`, `integration`, `integrationId`, `type`, `status`, `name`, `projectId` @@ -414,16 +471,11 @@ Infisical exposes the following key metrics in OpenTelemetry format: ### System Metrics -These metrics are automatically collected by OpenTelemetry's HTTP instrumentation: +These low-level HTTP metrics are automatically collected by OpenTelemetry's instrumentation layer, providing baseline performance data for all HTTP traffic. - `http_server_duration` - HTTP server request duration metrics (histogram buckets, count, sum) - `http_client_duration` - HTTP client request duration metrics (histogram buckets, count, sum) -### Custom Business Metrics - -- `infisical_secret_operations_total` - Total secret operations -- `infisical_secrets_processed_total` - Total secrets processed - ## Troubleshooting ### Common Issues diff --git a/docs/snippets/AppConnectionsBrowser.jsx b/docs/snippets/AppConnectionsBrowser.jsx index cfc65d1fd..dfe574547 100644 --- a/docs/snippets/AppConnectionsBrowser.jsx +++ b/docs/snippets/AppConnectionsBrowser.jsx @@ -47,6 +47,8 @@ export const AppConnectionsBrowser = () => { {"name": "Auth0", "slug": "auth0", "path": "/integrations/app-connections/auth0", "description": "Learn how to connect your Auth0 to pull secrets from Infisical.", "category": "Identity & Auth"}, {"name": "Okta", "slug": "okta", "path": "/integrations/app-connections/okta", "description": "Learn how to connect your Okta to pull secrets from Infisical.", "category": "Identity & Auth"}, {"name": "Laravel Forge", "slug": "laravel-forge", "path": "/integrations/app-connections/laravel-forge", "description": "Learn how to connect your Laravel Forge to pull secrets from Infisical.", "category": "Hosting"}, + {"name": "Chef", "slug": "chef", "path": "/integrations/app-connections/chef", "description": "Learn how to connect your Chef to pull secrets from Infisical.", "category": "DevOps Tools"}, + {"name": "Northflank", "slug": "northflank", "path": "/integrations/app-connections/northflank", "description": "Learn how to connect your Northflank projects to pull secrets from Infisical.", "category": "Hosting"} ].sort(function(a, b) { return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); }); diff --git a/docs/snippets/SecretSyncsBrowser.jsx b/docs/snippets/SecretSyncsBrowser.jsx index 3598bf68e..17ff9e97b 100644 --- a/docs/snippets/SecretSyncsBrowser.jsx +++ b/docs/snippets/SecretSyncsBrowser.jsx @@ -37,7 +37,9 @@ export const SecretSyncsBrowser = () => { {"name": "Humanitec", "slug": "humanitec", "path": "/integrations/secret-syncs/humanitec", "description": "Learn how to sync secrets from Infisical to Humanitec.", "category": "DevOps Tools"}, {"name": "OCI Vault", "slug": "oci-vault", "path": "/integrations/secret-syncs/oci-vault", "description": "Learn how to sync secrets from Infisical to OCI Vault.", "category": "Cloud Providers"}, {"name": "Zabbix", "slug": "zabbix", "path": "/integrations/secret-syncs/zabbix", "description": "Learn how to sync secrets from Infisical to Zabbix.", "category": "Monitoring"}, - {"name": "Laravel Forge", "slug": "laravel-forge", "path": "/integrations/secret-syncs/laravel-forge", "description": "Learn how to sync secrets from Infisical to Laravel Forge.", "category": "Hosting"} + {"name": "Laravel Forge", "slug": "laravel-forge", "path": "/integrations/secret-syncs/laravel-forge", "description": "Learn how to sync secrets from Infisical to Laravel Forge.", "category": "Hosting"}, + {"name": "Chef", "slug": "chef", "path": "/integrations/secret-syncs/chef", "description": "Learn how to sync secrets from Infisical to Chef.", "category": "DevOps Tools"}, + {"name": "Northflank", "slug": "northflank", "path": "/integrations/secret-syncs/northflank", "description": "Learn how to sync secrets from Infisical to Northflank projects.", "category": "Hosting"} ].sort(function(a, b) { return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); }); diff --git a/frontend/.storybook/decorators/DocumentDecorator.tsx b/frontend/.storybook/decorators/DocumentDecorator.tsx index 13f4dc8c7..b0d817c6e 100644 --- a/frontend/.storybook/decorators/DocumentDecorator.tsx +++ b/frontend/.storybook/decorators/DocumentDecorator.tsx @@ -3,7 +3,7 @@ import type { Decorator } from "@storybook/react-vite"; export const DocumentDecorator: Decorator = (Story) => { useEffect(() => { - const root = document.getElementsByTagName("html")[0]; + const root = document.documentElement; root.setAttribute("class", "overflow-visible"); }, []); diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 6e20b6d35..e8fdda096 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -138,10 +138,10 @@ "tailwindcss": "^4.1.14", "typescript": "~5.6.2", "typescript-eslint": "^8.15.0", - "vite": "^5.4.18", - "vite-plugin-node-polyfills": "^0.22.0", + "vite": "^6.2.0", + "vite-plugin-node-polyfills": "^0.23.0", "vite-plugin-top-level-await": "^1.4.4", - "vite-plugin-wasm": "^3.3.0", + "vite-plugin-wasm": "^3.4.0", "vite-tsconfig-paths": "^5.1.4" } }, @@ -717,9 +717,9 @@ "license": "MIT" }, "node_modules/@esbuild/aix-ppc64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", - "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.11.tgz", + "integrity": "sha512-Xt1dOL13m8u0WE8iplx9Ibbm+hFAO0GsU2P34UNoDGvZYkY8ifSiy6Zuc1lYxfG7svWE2fzqCUmFp5HCn51gJg==", "cpu": [ "ppc64" ], @@ -730,13 +730,13 @@ "aix" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/android-arm": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", - "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.11.tgz", + "integrity": "sha512-uoa7dU+Dt3HYsethkJ1k6Z9YdcHjTrSb5NUy66ZfZaSV8hEYGD5ZHbEMXnqLFlbBflLsl89Zke7CAdDJ4JI+Gg==", "cpu": [ "arm" ], @@ -747,13 +747,13 @@ "android" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/android-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", - "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.11.tgz", + "integrity": "sha512-9slpyFBc4FPPz48+f6jyiXOx/Y4v34TUeDDXJpZqAWQn/08lKGeD8aDp9TMn9jDz2CiEuHwfhRmGBvpnd/PWIQ==", "cpu": [ "arm64" ], @@ -764,13 +764,13 @@ "android" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/android-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", - "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.11.tgz", + "integrity": "sha512-Sgiab4xBjPU1QoPEIqS3Xx+R2lezu0LKIEcYe6pftr56PqPygbB7+szVnzoShbx64MUupqoE0KyRlN7gezbl8g==", "cpu": [ "x64" ], @@ -781,13 +781,13 @@ "android" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", - "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.11.tgz", + "integrity": "sha512-VekY0PBCukppoQrycFxUqkCojnTQhdec0vevUL/EDOCnXd9LKWqD/bHwMPzigIJXPhC59Vd1WFIL57SKs2mg4w==", "cpu": [ "arm64" ], @@ -798,13 +798,13 @@ "darwin" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", - "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.11.tgz", + "integrity": "sha512-+hfp3yfBalNEpTGp9loYgbknjR695HkqtY3d3/JjSRUyPg/xd6q+mQqIb5qdywnDxRZykIHs3axEqU6l1+oWEQ==", "cpu": [ "x64" ], @@ -815,13 +815,13 @@ "darwin" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", - "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.11.tgz", + "integrity": "sha512-CmKjrnayyTJF2eVuO//uSjl/K3KsMIeYeyN7FyDBjsR3lnSJHaXlVoAK8DZa7lXWChbuOk7NjAc7ygAwrnPBhA==", "cpu": [ "arm64" ], @@ -832,13 +832,13 @@ "freebsd" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", - "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.11.tgz", + "integrity": "sha512-Dyq+5oscTJvMaYPvW3x3FLpi2+gSZTCE/1ffdwuM6G1ARang/mb3jvjxs0mw6n3Lsw84ocfo9CrNMqc5lTfGOw==", "cpu": [ "x64" ], @@ -849,13 +849,13 @@ "freebsd" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-arm": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", - "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.11.tgz", + "integrity": "sha512-TBMv6B4kCfrGJ8cUPo7vd6NECZH/8hPpBHHlYI3qzoYFvWu2AdTvZNuU/7hsbKWqu/COU7NIK12dHAAqBLLXgw==", "cpu": [ "arm" ], @@ -866,13 +866,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", - "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.11.tgz", + "integrity": "sha512-Qr8AzcplUhGvdyUF08A1kHU3Vr2O88xxP0Tm8GcdVOUm25XYcMPp2YqSVHbLuXzYQMf9Bh/iKx7YPqECs6ffLA==", "cpu": [ "arm64" ], @@ -883,13 +883,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", - "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.11.tgz", + "integrity": "sha512-TmnJg8BMGPehs5JKrCLqyWTVAvielc615jbkOirATQvWWB1NMXY77oLMzsUjRLa0+ngecEmDGqt5jiDC6bfvOw==", "cpu": [ "ia32" ], @@ -900,13 +900,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", - "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.11.tgz", + "integrity": "sha512-DIGXL2+gvDaXlaq8xruNXUJdT5tF+SBbJQKbWy/0J7OhU8gOHOzKmGIlfTTl6nHaCOoipxQbuJi7O++ldrxgMw==", "cpu": [ "loong64" ], @@ -917,13 +917,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", - "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.11.tgz", + "integrity": "sha512-Osx1nALUJu4pU43o9OyjSCXokFkFbyzjXb6VhGIJZQ5JZi8ylCQ9/LFagolPsHtgw6himDSyb5ETSfmp4rpiKQ==", "cpu": [ "mips64el" ], @@ -934,13 +934,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", - "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.11.tgz", + "integrity": "sha512-nbLFgsQQEsBa8XSgSTSlrnBSrpoWh7ioFDUmwo158gIm5NNP+17IYmNWzaIzWmgCxq56vfr34xGkOcZ7jX6CPw==", "cpu": [ "ppc64" ], @@ -951,13 +951,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", - "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.11.tgz", + "integrity": "sha512-HfyAmqZi9uBAbgKYP1yGuI7tSREXwIb438q0nqvlpxAOs3XnZ8RsisRfmVsgV486NdjD7Mw2UrFSw51lzUk1ww==", "cpu": [ "riscv64" ], @@ -968,13 +968,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", - "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.11.tgz", + "integrity": "sha512-HjLqVgSSYnVXRisyfmzsH6mXqyvj0SA7pG5g+9W7ESgwA70AXYNpfKBqh1KbTxmQVaYxpzA/SvlB9oclGPbApw==", "cpu": [ "s390x" ], @@ -985,13 +985,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", - "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.11.tgz", + "integrity": "sha512-HSFAT4+WYjIhrHxKBwGmOOSpphjYkcswF449j6EjsjbinTZbp8PJtjsVK1XFJStdzXdy/jaddAep2FGY+wyFAQ==", "cpu": [ "x64" ], @@ -1002,13 +1002,13 @@ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/netbsd-arm64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.1.tgz", - "integrity": "sha512-O96poM2XGhLtpTh+s4+nP7YCCAfb4tJNRVZHfIE7dgmax+yMP2WgMd2OecBuaATHKTHsLWHQeuaxMRnCsH8+5g==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.11.tgz", + "integrity": "sha512-hr9Oxj1Fa4r04dNpWr3P8QKVVsjQhqrMSUzZzf+LZcYjZNqhA3IAfPQdEh1FLVUJSiu6sgAwp3OmwBfbFgG2Xg==", "cpu": [ "arm64" ], @@ -1023,9 +1023,9 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", - "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.11.tgz", + "integrity": "sha512-u7tKA+qbzBydyj0vgpu+5h5AeudxOAGncb8N6C9Kh1N4n7wU1Xw1JDApsRjpShRpXRQlJLb9wY28ELpwdPcZ7A==", "cpu": [ "x64" ], @@ -1036,13 +1036,13 @@ "netbsd" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/openbsd-arm64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.1.tgz", - "integrity": "sha512-Na9T3szbXezdzM/Kfs3GcRQNjHzM6GzFBeU1/6IV/npKP5ORtp9zbQjvkDJ47s6BCgaAZnnnu/cY1x342+MvZg==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.11.tgz", + "integrity": "sha512-Qq6YHhayieor3DxFOoYM1q0q1uMFYb7cSpLD2qzDSvK1NAvqFi8Xgivv0cFC6J+hWVw2teCYltyy9/m/14ryHg==", "cpu": [ "arm64" ], @@ -1057,9 +1057,9 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", - "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.11.tgz", + "integrity": "sha512-CN+7c++kkbrckTOz5hrehxWN7uIhFFlmS/hqziSFVWpAzpWrQoAG4chH+nN3Be+Kzv/uuo7zhX716x3Sn2Jduw==", "cpu": [ "x64" ], @@ -1070,13 +1070,30 @@ "openbsd" ], "engines": { - "node": ">=12" + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.11.tgz", + "integrity": "sha512-rOREuNIQgaiR+9QuNkbkxubbp8MSO9rONmwP5nKncnWJ9v5jQ4JxFnLu4zDSRPf3x4u+2VN4pM4RdyIzDty/wQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", - "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.11.tgz", + "integrity": "sha512-nq2xdYaWxyg9DcIyXkZhcYulC6pQ2FuCgem3LI92IwMgIZ69KHeY8T4Y88pcwoLIjbed8n36CyKoYRDygNSGhA==", "cpu": [ "x64" ], @@ -1087,13 +1104,13 @@ "sunos" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", - "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.11.tgz", + "integrity": "sha512-3XxECOWJq1qMZ3MN8srCJ/QfoLpL+VaxD/WfNRm1O3B4+AZ/BnLVgFbUV3eiRYDMXetciH16dwPbbHqwe1uU0Q==", "cpu": [ "arm64" ], @@ -1104,13 +1121,13 @@ "win32" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", - "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.11.tgz", + "integrity": "sha512-3ukss6gb9XZ8TlRyJlgLn17ecsK4NSQTmdIXRASVsiS2sQ6zPPZklNJT5GR5tE/MUarymmy8kCEf5xPCNCqVOA==", "cpu": [ "ia32" ], @@ -1121,13 +1138,13 @@ "win32" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/win32-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", - "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.11.tgz", + "integrity": "sha512-D7Hpz6A2L4hzsRpPaCYkQnGOotdUpDzSGRIv9I+1ITdHROSFUWW95ZPZWQmGka1Fg7W3zFJowyn9WGwMJ0+KPA==", "cpu": [ "x64" ], @@ -1138,7 +1155,7 @@ "win32" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@eslint-community/eslint-utils": { @@ -3725,9 +3742,9 @@ } }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.28.1.tgz", - "integrity": "sha512-2aZp8AES04KI2dy3Ss6/MDjXbwBzj+i0GqKtWXgw2/Ma6E4jJvujryO6gJAghIRVz7Vwr9Gtl/8na3nDUKpraQ==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.52.5.tgz", + "integrity": "sha512-8c1vW4ocv3UOMp9K+gToY5zL2XiiVw3k7f1ksf4yO1FlDFQ1C2u72iACFnSOceJFsWskc2WZNqeRhFRPzv+wtQ==", "cpu": [ "arm" ], @@ -3739,9 +3756,9 @@ ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.28.1.tgz", - "integrity": "sha512-EbkK285O+1YMrg57xVA+Dp0tDBRB93/BZKph9XhMjezf6F4TpYjaUSuPt5J0fZXlSag0LmZAsTmdGGqPp4pQFA==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.52.5.tgz", + "integrity": "sha512-mQGfsIEFcu21mvqkEKKu2dYmtuSZOBMmAl5CFlPGLY94Vlcm+zWApK7F/eocsNzp8tKmbeBP8yXyAbx0XHsFNA==", "cpu": [ "arm64" ], @@ -3753,9 +3770,9 @@ ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.28.1.tgz", - "integrity": "sha512-prduvrMKU6NzMq6nxzQw445zXgaDBbMQvmKSJaxpaZ5R1QDM8w+eGxo6Y/jhT/cLoCvnZI42oEqf9KQNYz1fqQ==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.52.5.tgz", + "integrity": "sha512-takF3CR71mCAGA+v794QUZ0b6ZSrgJkArC+gUiG6LB6TQty9T0Mqh3m2ImRBOxS2IeYBo4lKWIieSvnEk2OQWA==", "cpu": [ "arm64" ], @@ -3767,9 +3784,9 @@ ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.28.1.tgz", - "integrity": "sha512-WsvbOunsUk0wccO/TV4o7IKgloJ942hVFK1CLatwv6TJspcCZb9umQkPdvB7FihmdxgaKR5JyxDjWpCOp4uZlQ==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.52.5.tgz", + "integrity": "sha512-W901Pla8Ya95WpxDn//VF9K9u2JbocwV/v75TE0YIHNTbhqUTv9w4VuQ9MaWlNOkkEfFwkdNhXgcLqPSmHy0fA==", "cpu": [ "x64" ], @@ -3781,9 +3798,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.28.1.tgz", - "integrity": "sha512-HTDPdY1caUcU4qK23FeeGxCdJF64cKkqajU0iBnTVxS8F7H/7BewvYoG+va1KPSL63kQ1PGNyiwKOfReavzvNA==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.52.5.tgz", + "integrity": "sha512-QofO7i7JycsYOWxe0GFqhLmF6l1TqBswJMvICnRUjqCx8b47MTo46W8AoeQwiokAx3zVryVnxtBMcGcnX12LvA==", "cpu": [ "arm64" ], @@ -3795,9 +3812,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.28.1.tgz", - "integrity": "sha512-m/uYasxkUevcFTeRSM9TeLyPe2QDuqtjkeoTpP9SW0XxUWfcYrGDMkO/m2tTw+4NMAF9P2fU3Mw4ahNvo7QmsQ==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.52.5.tgz", + "integrity": "sha512-jr21b/99ew8ujZubPo9skbrItHEIE50WdV86cdSoRkKtmWa+DDr6fu2c/xyRT0F/WazZpam6kk7IHBerSL7LDQ==", "cpu": [ "x64" ], @@ -3809,9 +3826,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.28.1.tgz", - "integrity": "sha512-QAg11ZIt6mcmzpNE6JZBpKfJaKkqTm1A9+y9O+frdZJEuhQxiugM05gnCWiANHj4RmbgeVJpTdmKRmH/a+0QbA==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.52.5.tgz", + "integrity": "sha512-PsNAbcyv9CcecAUagQefwX8fQn9LQ4nZkpDboBOttmyffnInRy8R8dSg6hxxl2Re5QhHBf6FYIDhIj5v982ATQ==", "cpu": [ "arm" ], @@ -3823,9 +3840,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.28.1.tgz", - "integrity": "sha512-dRP9PEBfolq1dmMcFqbEPSd9VlRuVWEGSmbxVEfiq2cs2jlZAl0YNxFzAQS2OrQmsLBLAATDMb3Z6MFv5vOcXg==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.52.5.tgz", + "integrity": "sha512-Fw4tysRutyQc/wwkmcyoqFtJhh0u31K+Q6jYjeicsGJJ7bbEq8LwPWV/w0cnzOqR2m694/Af6hpFayLJZkG2VQ==", "cpu": [ "arm" ], @@ -3837,9 +3854,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.28.1.tgz", - "integrity": "sha512-uGr8khxO+CKT4XU8ZUH1TTEUtlktK6Kgtv0+6bIFSeiSlnGJHG1tSFSjm41uQ9sAO/5ULx9mWOz70jYLyv1QkA==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.52.5.tgz", + "integrity": "sha512-a+3wVnAYdQClOTlyapKmyI6BLPAFYs0JM8HRpgYZQO02rMR09ZcV9LbQB+NL6sljzG38869YqThrRnfPMCDtZg==", "cpu": [ "arm64" ], @@ -3851,9 +3868,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.28.1.tgz", - "integrity": "sha512-QF54q8MYGAqMLrX2t7tNpi01nvq5RI59UBNx+3+37zoKX5KViPo/gk2QLhsuqok05sSCRluj0D00LzCwBikb0A==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.52.5.tgz", + "integrity": "sha512-AvttBOMwO9Pcuuf7m9PkC1PUIKsfaAJ4AYhy944qeTJgQOqJYJ9oVl2nYgY7Rk0mkbsuOpCAYSs6wLYB2Xiw0Q==", "cpu": [ "arm64" ], @@ -3864,10 +3881,10 @@ "linux" ] }, - "node_modules/@rollup/rollup-linux-loongarch64-gnu": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.28.1.tgz", - "integrity": "sha512-vPul4uodvWvLhRco2w0GcyZcdyBfpfDRgNKU+p35AWEbJ/HPs1tOUrkSueVbBS0RQHAf/A+nNtDpvw95PeVKOA==", + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.52.5.tgz", + "integrity": "sha512-DkDk8pmXQV2wVrF6oq5tONK6UHLz/XcEVow4JTTerdeV1uqPeHxwcg7aFsfnSm9L+OO8WJsWotKM2JJPMWrQtA==", "cpu": [ "loong64" ], @@ -3878,10 +3895,10 @@ "linux" ] }, - "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.28.1.tgz", - "integrity": "sha512-pTnTdBuC2+pt1Rmm2SV7JWRqzhYpEILML4PKODqLz+C7Ou2apEV52h19CR7es+u04KlqplggmN9sqZlekg3R1A==", + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.52.5.tgz", + "integrity": "sha512-W/b9ZN/U9+hPQVvlGwjzi+Wy4xdoH2I8EjaCkMvzpI7wJUs8sWJ03Rq96jRnHkSrcHTpQe8h5Tg3ZzUPGauvAw==", "cpu": [ "ppc64" ], @@ -3893,9 +3910,23 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.28.1.tgz", - "integrity": "sha512-vWXy1Nfg7TPBSuAncfInmAI/WZDd5vOklyLJDdIRKABcZWojNDY0NJwruY2AcnCLnRJKSaBgf/GiJfauu8cQZA==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.52.5.tgz", + "integrity": "sha512-sjQLr9BW7R/ZiXnQiWPkErNfLMkkWIoCz7YMn27HldKsADEKa5WYdobaa1hmN6slu9oWQbB6/jFpJ+P2IkVrmw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.52.5.tgz", + "integrity": "sha512-hq3jU/kGyjXWTvAh2awn8oHroCbrPm8JqM7RUpKjalIRWWXE01CQOf/tUNWNHjmbMHg/hmNCwc/Pz3k1T/j/Lg==", "cpu": [ "riscv64" ], @@ -3907,9 +3938,9 @@ ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.28.1.tgz", - "integrity": "sha512-/yqC2Y53oZjb0yz8PVuGOQQNOTwxcizudunl/tFs1aLvObTclTwZ0JhXF2XcPT/zuaymemCDSuuUPXJJyqeDOg==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.52.5.tgz", + "integrity": "sha512-gn8kHOrku8D4NGHMK1Y7NA7INQTRdVOntt1OCYypZPRt6skGbddska44K8iocdpxHTMMNui5oH4elPH4QOLrFQ==", "cpu": [ "s390x" ], @@ -3921,9 +3952,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.28.1.tgz", - "integrity": "sha512-fzgeABz7rrAlKYB0y2kSEiURrI0691CSL0+KXwKwhxvj92VULEDQLpBYLHpF49MSiPG4sq5CK3qHMnb9tlCjBw==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.52.5.tgz", + "integrity": "sha512-hXGLYpdhiNElzN770+H2nlx+jRog8TyynpTVzdlc6bndktjKWyZyiCsuDAlpd+j+W+WNqfcyAWz9HxxIGfZm1Q==", "cpu": [ "x64" ], @@ -3935,9 +3966,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.28.1.tgz", - "integrity": "sha512-xQTDVzSGiMlSshpJCtudbWyRfLaNiVPXt1WgdWTwWz9n0U12cI2ZVtWe/Jgwyv/6wjL7b66uu61Vg0POWVfz4g==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.52.5.tgz", + "integrity": "sha512-arCGIcuNKjBoKAXD+y7XomR9gY6Mw7HnFBv5Rw7wQRvwYLR7gBAgV7Mb2QTyjXfTveBNFAtPt46/36vV9STLNg==", "cpu": [ "x64" ], @@ -3948,10 +3979,24 @@ "linux" ] }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.52.5.tgz", + "integrity": "sha512-QoFqB6+/9Rly/RiPjaomPLmR/13cgkIGfA40LHly9zcH1S0bN2HVFYk3a1eAyHQyjs3ZJYlXvIGtcCs5tko9Cw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.28.1.tgz", - "integrity": "sha512-wSXmDRVupJstFP7elGMgv+2HqXelQhuNf+IS4V+nUpNVi/GUiBgDmfwD0UGN3pcAnWsgKG3I52wMOBnk1VHr/A==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.52.5.tgz", + "integrity": "sha512-w0cDWVR6MlTstla1cIfOGyl8+qb93FlAVutcor14Gf5Md5ap5ySfQ7R9S/NjNaMLSFdUnKGEasmVnu3lCMqB7w==", "cpu": [ "arm64" ], @@ -3963,9 +4008,9 @@ ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.28.1.tgz", - "integrity": "sha512-ZkyTJ/9vkgrE/Rk9vhMXhf8l9D+eAhbAVbsGsXKy2ohmJaWg0LPQLnIxRdRp/bKyr8tXuPlXhIoGlEB5XpJnGA==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.52.5.tgz", + "integrity": "sha512-Aufdpzp7DpOTULJCuvzqcItSGDH73pF3ko/f+ckJhxQyHtp67rHw3HMNxoIdDMUITJESNE6a8uh4Lo4SLouOUg==", "cpu": [ "ia32" ], @@ -3976,10 +4021,24 @@ "win32" ] }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.52.5.tgz", + "integrity": "sha512-UGBUGPFp1vkj6p8wCRraqNhqwX/4kNQPS57BCFc8wYh0g94iVIW33wJtQAx3G7vrjjNtRaxiMUylM0ktp/TRSQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.28.1.tgz", - "integrity": "sha512-ZvK2jBafvttJjoIdKm/Q/Bh7IJ1Ose9IBOwpOXcOvW3ikGTQGmKDgxTC6oCAzW6PynbkKP8+um1du81XJHZ0JA==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.52.5.tgz", + "integrity": "sha512-TAcgQh2sSkykPRWLrdyy2AiceMckNf5loITqXxFI5VuQjS5tSuw3WlwdN8qv8vzjLAUTvYaH/mVjSFpbkFbpTg==", "cpu": [ "x64" ], @@ -5406,9 +5465,9 @@ "license": "MIT" }, "node_modules/@types/estree": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", - "integrity": "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", "license": "MIT" }, "node_modules/@types/estree-jsx": { @@ -8148,9 +8207,9 @@ } }, "node_modules/esbuild": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", - "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "version": "0.25.11", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.11.tgz", + "integrity": "sha512-KohQwyzrKTQmhXDW1PjCv3Tyspn9n5GcY2RTDqeORIdIJY8yKIF7sTSopFmn/wpMPW4rdPXI0UE5LJLuq3bx0Q==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -8158,32 +8217,35 @@ "esbuild": "bin/esbuild" }, "engines": { - "node": ">=12" + "node": ">=18" }, "optionalDependencies": { - "@esbuild/aix-ppc64": "0.21.5", - "@esbuild/android-arm": "0.21.5", - "@esbuild/android-arm64": "0.21.5", - "@esbuild/android-x64": "0.21.5", - "@esbuild/darwin-arm64": "0.21.5", - "@esbuild/darwin-x64": "0.21.5", - "@esbuild/freebsd-arm64": "0.21.5", - "@esbuild/freebsd-x64": "0.21.5", - "@esbuild/linux-arm": "0.21.5", - "@esbuild/linux-arm64": "0.21.5", - "@esbuild/linux-ia32": "0.21.5", - "@esbuild/linux-loong64": "0.21.5", - "@esbuild/linux-mips64el": "0.21.5", - "@esbuild/linux-ppc64": "0.21.5", - "@esbuild/linux-riscv64": "0.21.5", - "@esbuild/linux-s390x": "0.21.5", - "@esbuild/linux-x64": "0.21.5", - "@esbuild/netbsd-x64": "0.21.5", - "@esbuild/openbsd-x64": "0.21.5", - "@esbuild/sunos-x64": "0.21.5", - "@esbuild/win32-arm64": "0.21.5", - "@esbuild/win32-ia32": "0.21.5", - "@esbuild/win32-x64": "0.21.5" + "@esbuild/aix-ppc64": "0.25.11", + "@esbuild/android-arm": "0.25.11", + "@esbuild/android-arm64": "0.25.11", + "@esbuild/android-x64": "0.25.11", + "@esbuild/darwin-arm64": "0.25.11", + "@esbuild/darwin-x64": "0.25.11", + "@esbuild/freebsd-arm64": "0.25.11", + "@esbuild/freebsd-x64": "0.25.11", + "@esbuild/linux-arm": "0.25.11", + "@esbuild/linux-arm64": "0.25.11", + "@esbuild/linux-ia32": "0.25.11", + "@esbuild/linux-loong64": "0.25.11", + "@esbuild/linux-mips64el": "0.25.11", + "@esbuild/linux-ppc64": "0.25.11", + "@esbuild/linux-riscv64": "0.25.11", + "@esbuild/linux-s390x": "0.25.11", + "@esbuild/linux-x64": "0.25.11", + "@esbuild/netbsd-arm64": "0.25.11", + "@esbuild/netbsd-x64": "0.25.11", + "@esbuild/openbsd-arm64": "0.25.11", + "@esbuild/openbsd-x64": "0.25.11", + "@esbuild/openharmony-arm64": "0.25.11", + "@esbuild/sunos-x64": "0.25.11", + "@esbuild/win32-arm64": "0.25.11", + "@esbuild/win32-ia32": "0.25.11", + "@esbuild/win32-x64": "0.25.11" } }, "node_modules/esbuild-register": { @@ -9015,6 +9077,24 @@ "reusify": "^1.0.4" } }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, "node_modules/fflate": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", @@ -11926,9 +12006,9 @@ "license": "MIT" }, "node_modules/nanoid": { - "version": "3.3.8", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz", - "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==", + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", "dev": true, "funding": [ { @@ -12498,9 +12578,9 @@ "license": "ISC" }, "node_modules/picomatch": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz", - "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "license": "MIT", "engines": { "node": ">=12" @@ -12541,9 +12621,9 @@ } }, "node_modules/postcss": { - "version": "8.4.49", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.49.tgz", - "integrity": "sha512-OCVPnIObs4N29kxTjzLfUryOkvZEq+pf8jTF0lg8E7uETuWHA+v7j3c/xJmiqpX450191LlmZfUKkXxkTry7nA==", + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", "dev": true, "funding": [ { @@ -12561,7 +12641,7 @@ ], "license": "MIT", "dependencies": { - "nanoid": "^3.3.7", + "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" }, @@ -13638,13 +13718,13 @@ } }, "node_modules/rollup": { - "version": "4.28.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.28.1.tgz", - "integrity": "sha512-61fXYl/qNVinKmGSTHAZ6Yy8I3YIJC/r2m9feHo6SwVAVcLT5MPwOUFe7EuURA/4m0NR8lXG4BBXuo/IZEsjMg==", + "version": "4.52.5", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.52.5.tgz", + "integrity": "sha512-3GuObel8h7Kqdjt0gxkEzaifHTqLVW56Y/bjN7PSQtkKr0w3V/QYSdt6QWYtd7A1xUtYQigtdUfgj1RvWVtorw==", "dev": true, "license": "MIT", "dependencies": { - "@types/estree": "1.0.6" + "@types/estree": "1.0.8" }, "bin": { "rollup": "dist/bin/rollup" @@ -13654,25 +13734,28 @@ "npm": ">=8.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.28.1", - "@rollup/rollup-android-arm64": "4.28.1", - "@rollup/rollup-darwin-arm64": "4.28.1", - "@rollup/rollup-darwin-x64": "4.28.1", - "@rollup/rollup-freebsd-arm64": "4.28.1", - "@rollup/rollup-freebsd-x64": "4.28.1", - "@rollup/rollup-linux-arm-gnueabihf": "4.28.1", - "@rollup/rollup-linux-arm-musleabihf": "4.28.1", - "@rollup/rollup-linux-arm64-gnu": "4.28.1", - "@rollup/rollup-linux-arm64-musl": "4.28.1", - "@rollup/rollup-linux-loongarch64-gnu": "4.28.1", - "@rollup/rollup-linux-powerpc64le-gnu": "4.28.1", - "@rollup/rollup-linux-riscv64-gnu": "4.28.1", - "@rollup/rollup-linux-s390x-gnu": "4.28.1", - "@rollup/rollup-linux-x64-gnu": "4.28.1", - "@rollup/rollup-linux-x64-musl": "4.28.1", - "@rollup/rollup-win32-arm64-msvc": "4.28.1", - "@rollup/rollup-win32-ia32-msvc": "4.28.1", - "@rollup/rollup-win32-x64-msvc": "4.28.1", + "@rollup/rollup-android-arm-eabi": "4.52.5", + "@rollup/rollup-android-arm64": "4.52.5", + "@rollup/rollup-darwin-arm64": "4.52.5", + "@rollup/rollup-darwin-x64": "4.52.5", + "@rollup/rollup-freebsd-arm64": "4.52.5", + "@rollup/rollup-freebsd-x64": "4.52.5", + "@rollup/rollup-linux-arm-gnueabihf": "4.52.5", + "@rollup/rollup-linux-arm-musleabihf": "4.52.5", + "@rollup/rollup-linux-arm64-gnu": "4.52.5", + "@rollup/rollup-linux-arm64-musl": "4.52.5", + "@rollup/rollup-linux-loong64-gnu": "4.52.5", + "@rollup/rollup-linux-ppc64-gnu": "4.52.5", + "@rollup/rollup-linux-riscv64-gnu": "4.52.5", + "@rollup/rollup-linux-riscv64-musl": "4.52.5", + "@rollup/rollup-linux-s390x-gnu": "4.52.5", + "@rollup/rollup-linux-x64-gnu": "4.52.5", + "@rollup/rollup-linux-x64-musl": "4.52.5", + "@rollup/rollup-openharmony-arm64": "4.52.5", + "@rollup/rollup-win32-arm64-msvc": "4.52.5", + "@rollup/rollup-win32-ia32-msvc": "4.52.5", + "@rollup/rollup-win32-x64-gnu": "4.52.5", + "@rollup/rollup-win32-x64-msvc": "4.52.5", "fsevents": "~2.3.2" } }, @@ -14496,6 +14579,23 @@ "integrity": "sha512-lBN9zLN/oAf68o3zNXYrdCt1kP8WsiGW8Oo2ka41b2IM5JL/S1CTyX1rW0mb/zSuJun0ZUrDxx4sqvYS2FWzPA==", "license": "MIT" }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, "node_modules/tinyrainbow": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", @@ -14652,438 +14752,6 @@ "fsevents": "~2.3.3" } }, - "node_modules/tsx/node_modules/@esbuild/aix-ppc64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.1.tgz", - "integrity": "sha512-kfYGy8IdzTGy+z0vFGvExZtxkFlA4zAxgKEahG9KE1ScBjpQnFsNOX8KTU5ojNru5ed5CVoJYXFtoxaq5nFbjQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/android-arm": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.1.tgz", - "integrity": "sha512-dp+MshLYux6j/JjdqVLnMglQlFu+MuVeNrmT5nk6q07wNhCdSnB7QZj+7G8VMUGh1q+vj2Bq8kRsuyA00I/k+Q==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/android-arm64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.1.tgz", - "integrity": "sha512-50tM0zCJW5kGqgG7fQ7IHvQOcAn9TKiVRuQ/lN0xR+T2lzEFvAi1ZcS8DiksFcEpf1t/GYOeOfCAgDHFpkiSmA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/android-x64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.1.tgz", - "integrity": "sha512-GCj6WfUtNldqUzYkN/ITtlhwQqGWu9S45vUXs7EIYf+7rCiiqH9bCloatO9VhxsL0Pji+PF4Lz2XXCES+Q8hDw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/darwin-arm64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.1.tgz", - "integrity": "sha512-5hEZKPf+nQjYoSr/elb62U19/l1mZDdqidGfmFutVUjjUZrOazAtwK+Kr+3y0C/oeJfLlxo9fXb1w7L+P7E4FQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/darwin-x64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.1.tgz", - "integrity": "sha512-hxVnwL2Dqs3fM1IWq8Iezh0cX7ZGdVhbTfnOy5uURtao5OIVCEyj9xIzemDi7sRvKsuSdtCAhMKarxqtlyVyfA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/freebsd-arm64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.1.tgz", - "integrity": "sha512-1MrCZs0fZa2g8E+FUo2ipw6jw5qqQiH+tERoS5fAfKnRx6NXH31tXBKI3VpmLijLH6yriMZsxJtaXUyFt/8Y4A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/freebsd-x64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.1.tgz", - "integrity": "sha512-0IZWLiTyz7nm0xuIs0q1Y3QWJC52R8aSXxe40VUxm6BB1RNmkODtW6LHvWRrGiICulcX7ZvyH6h5fqdLu4gkww==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-arm": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.1.tgz", - "integrity": "sha512-NdKOhS4u7JhDKw9G3cY6sWqFcnLITn6SqivVArbzIaf3cemShqfLGHYMx8Xlm/lBit3/5d7kXvriTUGa5YViuQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-arm64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.1.tgz", - "integrity": "sha512-jaN3dHi0/DDPelk0nLcXRm1q7DNJpjXy7yWaWvbfkPvI+7XNSc/lDOnCLN7gzsyzgu6qSAmgSvP9oXAhP973uQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-ia32": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.1.tgz", - "integrity": "sha512-OJykPaF4v8JidKNGz8c/q1lBO44sQNUQtq1KktJXdBLn1hPod5rE/Hko5ugKKZd+D2+o1a9MFGUEIUwO2YfgkQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-loong64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.1.tgz", - "integrity": "sha512-nGfornQj4dzcq5Vp835oM/o21UMlXzn79KobKlcs3Wz9smwiifknLy4xDCLUU0BWp7b/houtdrgUz7nOGnfIYg==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-mips64el": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.1.tgz", - "integrity": "sha512-1osBbPEFYwIE5IVB/0g2X6i1qInZa1aIoj1TdL4AaAb55xIIgbg8Doq6a5BzYWgr+tEcDzYH67XVnTmUzL+nXg==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-ppc64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.1.tgz", - "integrity": "sha512-/6VBJOwUf3TdTvJZ82qF3tbLuWsscd7/1w+D9LH0W/SqUgM5/JJD0lrJ1fVIfZsqB6RFmLCe0Xz3fmZc3WtyVg==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-riscv64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.1.tgz", - "integrity": "sha512-nSut/Mx5gnilhcq2yIMLMe3Wl4FK5wx/o0QuuCLMtmJn+WeWYoEGDN1ipcN72g1WHsnIbxGXd4i/MF0gTcuAjQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-s390x": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.1.tgz", - "integrity": "sha512-cEECeLlJNfT8kZHqLarDBQso9a27o2Zd2AQ8USAEoGtejOrCYHNtKP8XQhMDJMtthdF4GBmjR2au3x1udADQQQ==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-x64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.1.tgz", - "integrity": "sha512-xbfUhu/gnvSEg+EGovRc+kjBAkrvtk38RlerAzQxvMzlB4fXpCFCeUAYzJvrnhFtdeyVCDANSjJvOvGYoeKzFA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/netbsd-x64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.1.tgz", - "integrity": "sha512-X53z6uXip6KFXBQ+Krbx25XHV/NCbzryM6ehOAeAil7X7oa4XIq+394PWGnwaSQ2WRA0KI6PUO6hTO5zeF5ijA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/openbsd-x64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.1.tgz", - "integrity": "sha512-T3H78X2h1tszfRSf+txbt5aOp/e7TAz3ptVKu9Oyir3IAOFPGV6O9c2naym5TOriy1l0nNf6a4X5UXRZSGX/dw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/sunos-x64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.1.tgz", - "integrity": "sha512-2H3RUvcmULO7dIE5EWJH8eubZAI4xw54H1ilJnRNZdeo8dTADEZ21w6J22XBkXqGJbe0+wnNJtw3UXRoLJnFEg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/win32-arm64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.1.tgz", - "integrity": "sha512-GE7XvrdOzrb+yVKB9KsRMq+7a2U/K5Cf/8grVFRAGJmfADr/e/ODQ134RK2/eeHqYV5eQRFxb1hY7Nr15fv1NQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/win32-ia32": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.1.tgz", - "integrity": "sha512-uOxSJCIcavSiT6UnBhBzE8wy3n0hOkJsBOzy7HDAuTDE++1DJMRRVCPGisULScHL+a/ZwdXPpXD3IyFKjA7K8A==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/win32-x64": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.1.tgz", - "integrity": "sha512-Y1EQdcfwMSeQN/ujR5VayLOJ1BHaK+ssyk0AEzPjC+t1lITgsnccPqFjb6V+LsTp/9Iov4ysfjxLaGJ9RPtkVg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/esbuild": { - "version": "0.25.1", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.1.tgz", - "integrity": "sha512-BGO5LtrGC7vxnqucAe/rmvKdJllfGaYWdyABvyMoXQlfYMb2bbRuReWR5tEGE//4LcNJj9XrkovTqNYRFZHAMQ==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.25.1", - "@esbuild/android-arm": "0.25.1", - "@esbuild/android-arm64": "0.25.1", - "@esbuild/android-x64": "0.25.1", - "@esbuild/darwin-arm64": "0.25.1", - "@esbuild/darwin-x64": "0.25.1", - "@esbuild/freebsd-arm64": "0.25.1", - "@esbuild/freebsd-x64": "0.25.1", - "@esbuild/linux-arm": "0.25.1", - "@esbuild/linux-arm64": "0.25.1", - "@esbuild/linux-ia32": "0.25.1", - "@esbuild/linux-loong64": "0.25.1", - "@esbuild/linux-mips64el": "0.25.1", - "@esbuild/linux-ppc64": "0.25.1", - "@esbuild/linux-riscv64": "0.25.1", - "@esbuild/linux-s390x": "0.25.1", - "@esbuild/linux-x64": "0.25.1", - "@esbuild/netbsd-arm64": "0.25.1", - "@esbuild/netbsd-x64": "0.25.1", - "@esbuild/openbsd-arm64": "0.25.1", - "@esbuild/openbsd-x64": "0.25.1", - "@esbuild/sunos-x64": "0.25.1", - "@esbuild/win32-arm64": "0.25.1", - "@esbuild/win32-ia32": "0.25.1", - "@esbuild/win32-x64": "0.25.1" - } - }, "node_modules/tsyringe": { "version": "4.8.0", "resolved": "https://registry.npmjs.org/tsyringe/-/tsyringe-4.8.0.tgz", @@ -15610,21 +15278,24 @@ } }, "node_modules/vite": { - "version": "5.4.19", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.19.tgz", - "integrity": "sha512-qO3aKv3HoQC8QKiNSTuUM1l9o/XX3+c+VTgLHbJWHZGeTPVAg2XwazI9UWzoxjIJCGCV2zU60uqMzjeLZuULqA==", + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz", + "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", "dev": true, "license": "MIT", "dependencies": { - "esbuild": "^0.21.3", - "postcss": "^8.4.43", - "rollup": "^4.20.0" + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" }, "bin": { "vite": "bin/vite.js" }, "engines": { - "node": "^18.0.0 || >=20.0.0" + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" }, "funding": { "url": "https://github.com/vitejs/vite?sponsor=1" @@ -15633,19 +15304,25 @@ "fsevents": "~2.3.3" }, "peerDependencies": { - "@types/node": "^18.0.0 || >=20.0.0", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", - "terser": "^5.4.0" + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" }, "peerDependenciesMeta": { "@types/node": { "optional": true }, + "jiti": { + "optional": true + }, "less": { "optional": true }, @@ -15666,13 +15343,19 @@ }, "terser": { "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true } } }, "node_modules/vite-plugin-node-polyfills": { - "version": "0.22.0", - "resolved": "https://registry.npmjs.org/vite-plugin-node-polyfills/-/vite-plugin-node-polyfills-0.22.0.tgz", - "integrity": "sha512-F+G3LjiGbG8QpbH9bZ//GSBr9i1InSTkaulfUHFa9jkLqVGORFBoqc2A/Yu5Mmh1kNAbiAeKeK+6aaQUf3x0JA==", + "version": "0.23.0", + "resolved": "https://registry.npmjs.org/vite-plugin-node-polyfills/-/vite-plugin-node-polyfills-0.23.0.tgz", + "integrity": "sha512-4n+Ys+2bKHQohPBKigFlndwWQ5fFKwaGY6muNDMTb0fSQLyBzS+jjUNRZG9sKF0S/Go4ApG6LFnUGopjkILg3w==", "dev": true, "license": "MIT", "dependencies": { @@ -15683,7 +15366,7 @@ "url": "https://github.com/sponsors/davidmyersdev" }, "peerDependencies": { - "vite": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0" + "vite": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0" } }, "node_modules/vite-plugin-top-level-await": { @@ -15702,13 +15385,13 @@ } }, "node_modules/vite-plugin-wasm": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/vite-plugin-wasm/-/vite-plugin-wasm-3.3.0.tgz", - "integrity": "sha512-tVhz6w+W9MVsOCHzxo6SSMSswCeIw4HTrXEi6qL3IRzATl83jl09JVO1djBqPSwfjgnpVHNLYcaMbaDX5WB/pg==", + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/vite-plugin-wasm/-/vite-plugin-wasm-3.5.0.tgz", + "integrity": "sha512-X5VWgCnqiQEGb+omhlBVsvTfxikKtoOgAzQ95+BZ8gQ+VfMHIjSHr0wyvXFQCa0eKQ0fKyaL0kWcEnYqBac4lQ==", "dev": true, "license": "MIT", "peerDependencies": { - "vite": "^2 || ^3 || ^4 || ^5" + "vite": "^2 || ^3 || ^4 || ^5 || ^6 || ^7" } }, "node_modules/vite-tsconfig-paths": { diff --git a/frontend/package.json b/frontend/package.json index 9c375190e..8009c2118 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -147,10 +147,10 @@ "tailwindcss": "^4.1.14", "typescript": "~5.6.2", "typescript-eslint": "^8.15.0", - "vite": "^5.4.18", - "vite-plugin-node-polyfills": "^0.22.0", + "vite": "^6.2.0", + "vite-plugin-node-polyfills": "^0.23.0", "vite-plugin-top-level-await": "^1.4.4", - "vite-plugin-wasm": "^3.3.0", + "vite-plugin-wasm": "^3.4.0", "vite-tsconfig-paths": "^5.1.4" } } diff --git a/frontend/public/images/integrations/Chef.png b/frontend/public/images/integrations/Chef.png new file mode 100644 index 000000000..8d8886c21 Binary files /dev/null and b/frontend/public/images/integrations/Chef.png differ diff --git a/frontend/src/components/app-connections/AppConnectionOption.tsx b/frontend/src/components/app-connections/AppConnectionOption.tsx index 30a37425c..793f9d821 100644 --- a/frontend/src/components/app-connections/AppConnectionOption.tsx +++ b/frontend/src/components/app-connections/AppConnectionOption.tsx @@ -1,9 +1,11 @@ import { components, OptionProps } from "react-select"; import { faCheckCircle } from "@fortawesome/free-regular-svg-icons"; -import { faBuilding, faPlus } from "@fortawesome/free-solid-svg-icons"; +import { faPlus } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { Badge, Tooltip } from "@app/components/v2"; +import { Tooltip } from "@app/components/v2"; +import { Badge, OrgIcon, SubOrgIcon } from "@app/components/v3"; +import { useOrganization } from "@app/context"; import { TAvailableAppConnection } from "@app/hooks/api/appConnections"; export const AppConnectionOption = ({ @@ -13,6 +15,8 @@ export const AppConnectionOption = ({ }: OptionProps) => { const isCreateOption = props.data.id === "_create"; + const { isSubOrganization } = useOrganization(); + return (
@@ -23,15 +27,22 @@ export const AppConnectionOption = ({
) : ( <> -

{children}

+

{children}

{!props.data.projectId && ( - -
- - + + {isSubOrganization ? ( + + + Sub-Organization + + ) : ( + + Organization -
+ )}
)} {isSelected && ( diff --git a/frontend/src/components/pki-syncs/CertificateManagementModal.tsx b/frontend/src/components/pki-syncs/CertificateManagementModal.tsx new file mode 100644 index 000000000..f5fd72309 --- /dev/null +++ b/frontend/src/components/pki-syncs/CertificateManagementModal.tsx @@ -0,0 +1,444 @@ +import React, { useEffect, useState } from "react"; +import { faSearch, faX } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; + +import { createNotification } from "@app/components/notifications"; +import { + Button, + Checkbox, + EmptyState, + Input, + Modal, + ModalContent, + Pagination, + Table, + TableContainer, + TBody, + Td, + Th, + THead, + Tooltip, + Tr +} from "@app/components/v2"; +import { useProject } from "@app/context"; +import { + CertStatus, + useAddCertificatesToPkiSync, + useListPkiSyncCertificates, + useRemoveCertificatesFromPkiSync +} from "@app/hooks/api"; +import { TPkiSync } from "@app/hooks/api/pkiSyncs"; +import { useListWorkspaceCertificates } from "@app/hooks/api/projects"; + +type Props = { + isOpen: boolean; + onClose: () => void; + pkiSync?: TPkiSync; + onCertificatesUpdated?: () => void; + selectedCertificateIds?: string[]; + onCertificateSelectionChange?: (certificateIds: string[]) => void; + title?: string; + subtitle?: string; + saveButtonText?: string; +}; + +export const CertificateManagementModal = ({ + isOpen, + onClose, + pkiSync, + onCertificatesUpdated, + selectedCertificateIds, + onCertificateSelectionChange, + title = "Manage Certificate Sync", + subtitle = "Select which certificates should be synced.", + saveButtonText = "Save Changes" +}: Props) => { + const { currentProject } = useProject(); + const [currentPage, setCurrentPage] = useState(1); + const [searchTerm, setSearchTerm] = useState(""); + const [debouncedSearchTerm, setDebouncedSearchTerm] = useState(""); + const pageSize = 10; + + const isCreateMode = !pkiSync; + + useEffect(() => { + const handler = setTimeout(() => { + setDebouncedSearchTerm(searchTerm); + setCurrentPage(1); + }, 300); + + return () => { + clearTimeout(handler); + }; + }, [searchTerm]); + + const { data } = useListWorkspaceCertificates({ + projectId: currentProject?.id || "", + offset: (currentPage - 1) * pageSize, + limit: pageSize, + commonName: debouncedSearchTerm || undefined, + friendlyName: debouncedSearchTerm || undefined, + forPkiSync: true + }); + + const allCertificates = data?.certificates || []; + const totalCount = data?.totalCount || 0; + + const { data: syncData } = useListPkiSyncCertificates(pkiSync?.id || ""); + const syncCertificates = syncData?.certificates || []; + const addCertificatesToSync = useAddCertificatesToPkiSync(); + const removeCertificatesFromSync = useRemoveCertificatesFromPkiSync(); + + const syncedCertificateIds = isCreateMode + ? selectedCertificateIds || [] + : syncCertificates.map((sc) => sc.certificateId); + + const totalPages = Math.ceil(totalCount / pageSize); + + const [selectedIds, setSelectedIds] = useState([]); + + React.useEffect(() => { + setSelectedIds(syncedCertificateIds); + }, [JSON.stringify(syncedCertificateIds)]); + + const handleToggleSelection = (certId: string) => { + setSelectedIds((prev) => + prev.includes(certId) ? prev.filter((id) => id !== certId) : [...prev, certId] + ); + }; + + const handleSelectAll = () => { + const currentPageIds = allCertificates.map((cert) => cert.id); + const allCurrentPageSelected = currentPageIds.every((id) => selectedIds.includes(id)); + + if (allCurrentPageSelected) { + setSelectedIds((prev) => prev.filter((id) => !currentPageIds.includes(id))); + } else { + setSelectedIds((prev) => [...new Set([...prev, ...currentPageIds])]); + } + }; + + const clearSearch = () => { + setSearchTerm(""); + setCurrentPage(1); + }; + + React.useEffect(() => { + if (isOpen) { + setCurrentPage(1); + setSearchTerm(""); + } + }, [isOpen]); + + const handleSaveCertificates = async () => { + try { + if (isCreateMode) { + if (onCertificateSelectionChange) { + onCertificateSelectionChange(selectedIds); + onClose(); + } + return; + } + + if (!pkiSync) return; + + const certificatesToAdd = selectedIds.filter((id) => !syncedCertificateIds.includes(id)); + const certificatesToRemove = syncedCertificateIds.filter((id) => !selectedIds.includes(id)); + + const invalidCertificates = certificatesToAdd + .map((id) => allCertificates.find((cert) => cert.id === id)) + .filter((cert) => { + if (!cert) return false; + const isExpired = new Date(cert.notAfter) < new Date(); + const isRevoked = cert.status === CertStatus.REVOKED; + return isExpired || isRevoked; + }); + + if (invalidCertificates.length > 0) { + const invalidNames = invalidCertificates.map((cert) => cert?.commonName).join(", "); + createNotification({ + text: `Cannot add expired or revoked certificates: ${invalidNames}`, + type: "error" + }); + return; + } + + const operations = []; + + if (certificatesToAdd.length > 0) { + operations.push( + addCertificatesToSync + .mutateAsync({ + pkiSyncId: pkiSync.id, + certificateIds: certificatesToAdd + }) + .then(() => ({ + type: "add", + count: certificatesToAdd.length, + success: true + })) + .catch((error) => ({ + type: "add", + count: certificatesToAdd.length, + success: false, + error + })) + ); + } + + if (certificatesToRemove.length > 0) { + operations.push( + removeCertificatesFromSync + .mutateAsync({ + pkiSyncId: pkiSync.id, + certificateIds: certificatesToRemove + }) + .then(() => ({ + type: "remove", + count: certificatesToRemove.length, + success: true + })) + .catch((error) => ({ + type: "remove", + count: certificatesToRemove.length, + success: false, + error + })) + ); + } + + if (operations.length === 0) { + createNotification({ + text: "No changes to save", + type: "info" + }); + onClose(); + return; + } + + const results = await Promise.all(operations); + const failures = results.filter((r) => !r.success); + const successes = results.filter((r) => r.success); + + if (failures.length === 0) { + const addCount = successes.find((r) => r.type === "add")?.count || 0; + const removeCount = successes.find((r) => r.type === "remove")?.count || 0; + + let message = "Certificate selection updated successfully"; + if (addCount > 0 && removeCount > 0) { + message = `Added ${addCount} and removed ${removeCount} certificate(s)`; + } else if (addCount > 0) { + message = `Added ${addCount} certificate(s)`; + } else if (removeCount > 0) { + message = `Removed ${removeCount} certificate(s)`; + } + + createNotification({ + text: message, + type: "success" + }); + + if (onCertificatesUpdated) { + onCertificatesUpdated(); + } + onClose(); + } else { + const partialSuccess = successes.length > 0; + console.error("Certificate sync operation failures:", failures); + + createNotification({ + text: partialSuccess + ? "Some certificate changes failed. Check console for details." + : "Failed to update certificate selection", + type: partialSuccess ? "warning" : "error" + }); + + if (partialSuccess && onCertificatesUpdated) { + onCertificatesUpdated(); + } + } + } catch (error) { + console.error("Unexpected error during certificate sync operation:", error); + createNotification({ + text: "An unexpected error occurred while updating certificates", + type: "error" + }); + } + }; + + const isLoading = addCertificatesToSync.isPending || removeCertificatesFromSync.isPending; + + return ( + !open && onClose()}> + +
+
+
+ { + setSearchTerm(e.target.value); + setCurrentPage(1); + }} + className="pl-9" + /> + + {searchTerm && ( + + )} +
+
+ + + + + + + + + + + + + + {allCertificates.map((cert) => { + const isExpired = new Date(cert.notAfter) < new Date(); + const isRevoked = cert.status === CertStatus.REVOKED; + const cannotBeAdded = isExpired || isRevoked; + const isAlreadySynced = syncedCertificateIds.includes(cert.id); + + let originalDisplayName = "—"; + if (cert.altNames && cert.altNames.trim()) { + originalDisplayName = cert.altNames.trim(); + } else if (cert.commonName && cert.commonName.trim()) { + originalDisplayName = cert.commonName.trim(); + } + + let displayName = originalDisplayName; + let isTruncated = false; + if (originalDisplayName.length > 34) { + displayName = `${originalDisplayName.substring(0, 34)}...`; + isTruncated = true; + } + + const truncatedSerial = + cert.serialNumber.length > 8 + ? `${cert.serialNumber.slice(0, 4)}...${cert.serialNumber.slice(-4)}` + : cert.serialNumber; + + return ( + { + if (!cannotBeAdded || isAlreadySynced) { + handleToggleSelection(cert.id); + } + }} + > + + + + + + + ); + })} + +
+ 0 && + allCertificates.every((cert) => selectedIds.includes(cert.id)) + } + onCheckedChange={handleSelectAll} + /> + SAN / CNSerial NumberIssued AtExpires At
e.stopPropagation()}> + { + if (!cannotBeAdded || isAlreadySynced) { + handleToggleSelection(cert.id); + } + }} + isDisabled={cannotBeAdded && !isAlreadySynced} + /> + + {isTruncated ? ( + +
{displayName}
+
+ ) : ( +
{displayName}
+ )} +
+
+ {truncatedSerial} +
+
+ + {new Date(cert.notBefore).toLocaleDateString()} + + + + {new Date(cert.notAfter).toLocaleDateString()} + +
+ {allCertificates.length === 0 && ( + + {searchTerm + ? "No certificates match your search criteria." + : "No certificates available for sync."} + + )} +
+ + {totalPages > 1 && ( +
+ setCurrentPage(page)} + onChangePerPage={() => {}} + /> +
+ )} +
+ +
+ + +
+
+
+ ); +}; diff --git a/frontend/src/components/pki-syncs/CreatePkiSyncModal.tsx b/frontend/src/components/pki-syncs/CreatePkiSyncModal.tsx index 5b5e81ba3..0169b2296 100644 --- a/frontend/src/components/pki-syncs/CreatePkiSyncModal.tsx +++ b/frontend/src/components/pki-syncs/CreatePkiSyncModal.tsx @@ -11,21 +11,24 @@ type Props = { isOpen: boolean; onOpenChange: (isOpen: boolean) => void; selectSync?: PkiSync | null; + initialData?: any; }; type ContentProps = { onComplete: (pkiSync: TPkiSync) => void; selectedSync: PkiSync | null; setSelectedSync: (selectedSync: PkiSync | null) => void; + initialData?: any; }; -const Content = ({ onComplete, setSelectedSync, selectedSync }: ContentProps) => { +const Content = ({ onComplete, setSelectedSync, selectedSync, initialData }: ContentProps) => { if (selectedSync) { return ( setSelectedSync(null)} destination={selectedSync} + initialData={initialData} /> ); } @@ -33,7 +36,12 @@ const Content = ({ onComplete, setSelectedSync, selectedSync }: ContentProps) => return ; }; -export const CreatePkiSyncModal = ({ onOpenChange, selectSync = null, ...props }: Props) => { +export const CreatePkiSyncModal = ({ + onOpenChange, + selectSync = null, + initialData, + ...props +}: Props) => { const [selectedSync, setSelectedSync] = useState(selectSync); useEffect(() => { @@ -69,6 +77,7 @@ export const CreatePkiSyncModal = ({ onOpenChange, selectSync = null, ...props } }} selectedSync={selectedSync} setSelectedSync={setSelectedSync} + initialData={initialData} /> diff --git a/frontend/src/components/pki-syncs/PkiSyncImportStatusBadge.tsx b/frontend/src/components/pki-syncs/PkiSyncImportStatusBadge.tsx index d5b3119d0..2cea3c55b 100644 --- a/frontend/src/components/pki-syncs/PkiSyncImportStatusBadge.tsx +++ b/frontend/src/components/pki-syncs/PkiSyncImportStatusBadge.tsx @@ -1,27 +1,20 @@ import { ReactNode, useEffect, useMemo, useState } from "react"; -import { - faCheck, - faDownload, - faTriangleExclamation, - faXmark, - IconDefinition -} from "@fortawesome/free-solid-svg-icons"; +import { faXmark } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { differenceInSeconds } from "date-fns"; -import { twMerge } from "tailwind-merge"; +import { CheckIcon, DownloadIcon, LucideIcon, TriangleAlertIcon } from "lucide-react"; -import { Badge, Tooltip } from "@app/components/v2"; -import { BadgeProps } from "@app/components/v2/Badge/Badge"; +import { Tooltip } from "@app/components/v2"; +import { Badge, TBadgeProps } from "@app/components/v3"; import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs"; import { PkiSyncStatus, TPkiSync } from "@app/hooks/api/pkiSyncs"; type Props = { pkiSync: TPkiSync; - className?: string; mini?: boolean; }; -export const PkiSyncImportStatusBadge = ({ pkiSync, className, mini }: Props) => { +export const PkiSyncImportStatusBadge = ({ pkiSync, mini }: Props) => { const { importStatus, lastImportMessage, lastImportedAt, destination } = pkiSync; const [hide, setHide] = useState(importStatus === PkiSyncStatus.Succeeded); const destinationName = PKI_SYNC_MAP[destination].name; @@ -50,24 +43,24 @@ export const PkiSyncImportStatusBadge = ({ pkiSync, className, mini }: Props) => if (!importStatus || hide) return null; - let variant: BadgeProps["variant"]; + let variant: TBadgeProps["variant"]; let label: string; - let icon: IconDefinition; + let Icon: LucideIcon; let tooltipContent: ReactNode; switch (importStatus) { case PkiSyncStatus.Pending: case PkiSyncStatus.Running: - variant = "primary"; + variant = "warning"; label = "Importing Certificates..."; tooltipContent = `Importing certificates from ${destinationName}. This may take a moment.`; - icon = faDownload; + Icon = DownloadIcon; break; case PkiSyncStatus.Failed: variant = "danger"; label = "Failed to Import Certificates"; - icon = faTriangleExclamation; + Icon = TriangleAlertIcon; tooltipContent = (
{failureMessage && ( @@ -93,20 +86,15 @@ export const PkiSyncImportStatusBadge = ({ pkiSync, className, mini }: Props) => tooltipContent = "Successfully imported certificates."; variant = "success"; label = "Certificates Imported"; - icon = faCheck; + Icon = CheckIcon; } return ( -
- - - {!mini && {label}} - -
+ + + {!mini && label} +
); }; diff --git a/frontend/src/components/pki-syncs/PkiSyncModalHeader.tsx b/frontend/src/components/pki-syncs/PkiSyncModalHeader.tsx index 0e18959dc..32f84c247 100644 --- a/frontend/src/components/pki-syncs/PkiSyncModalHeader.tsx +++ b/frontend/src/components/pki-syncs/PkiSyncModalHeader.tsx @@ -1,6 +1,4 @@ -import { faArrowUpRightFromSquare, faBookOpen } from "@fortawesome/free-solid-svg-icons"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; - +import { DocumentationLinkBadge } from "@app/components/v3"; import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs"; import { PkiSync } from "@app/hooks/api/pkiSyncs"; @@ -20,23 +18,11 @@ export const PkiSyncModalHeader = ({ destination, isConfigured }: Props) => { className="h-12 w-12 rounded-md bg-bunker-500 p-2" />
-
+
{destinationDetails.name} Certificate Sync - -
- - Docs - -
-
+

{isConfigured diff --git a/frontend/src/components/pki-syncs/PkiSyncRemoveStatusBadge.tsx b/frontend/src/components/pki-syncs/PkiSyncRemoveStatusBadge.tsx index 3e898ba42..968431b84 100644 --- a/frontend/src/components/pki-syncs/PkiSyncRemoveStatusBadge.tsx +++ b/frontend/src/components/pki-syncs/PkiSyncRemoveStatusBadge.tsx @@ -1,27 +1,20 @@ import { ReactNode, useEffect, useMemo, useState } from "react"; -import { - faCheck, - faEraser, - faTriangleExclamation, - faXmark, - IconDefinition -} from "@fortawesome/free-solid-svg-icons"; +import { faXmark } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { differenceInSeconds } from "date-fns"; -import { twMerge } from "tailwind-merge"; +import { AlertTriangleIcon, CheckIcon, EraserIcon, LucideIcon } from "lucide-react"; -import { Badge, Tooltip } from "@app/components/v2"; -import { BadgeProps } from "@app/components/v2/Badge/Badge"; +import { Tooltip } from "@app/components/v2"; +import { Badge, TBadgeProps } from "@app/components/v3"; import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs"; import { PkiSyncStatus, TPkiSync } from "@app/hooks/api/pkiSyncs"; type Props = { pkiSync: TPkiSync; - className?: string; mini?: boolean; }; -export const PkiSyncRemoveStatusBadge = ({ pkiSync, className, mini }: Props) => { +export const PkiSyncRemoveStatusBadge = ({ pkiSync, mini }: Props) => { const { removeStatus, lastRemoveMessage, lastRemovedAt, destination } = pkiSync; const [hide, setHide] = useState(removeStatus === PkiSyncStatus.Succeeded); const destinationName = PKI_SYNC_MAP[destination].name; @@ -50,24 +43,24 @@ export const PkiSyncRemoveStatusBadge = ({ pkiSync, className, mini }: Props) => if (!removeStatus || hide) return null; - let variant: BadgeProps["variant"]; + let variant: TBadgeProps["variant"]; let label: string; - let icon: IconDefinition; + let Icon: LucideIcon; let tooltipContent: ReactNode; switch (removeStatus) { case PkiSyncStatus.Pending: case PkiSyncStatus.Running: - variant = "primary"; + variant = "warning"; label = "Removing Certificates..."; tooltipContent = `Removing certificates from ${destinationName}. This may take a moment.`; - icon = faEraser; + Icon = EraserIcon; break; case PkiSyncStatus.Failed: variant = "danger"; label = "Failed to Remove Certificates"; - icon = faTriangleExclamation; + Icon = AlertTriangleIcon; tooltipContent = (

{failureMessage && ( @@ -93,20 +86,15 @@ export const PkiSyncRemoveStatusBadge = ({ pkiSync, className, mini }: Props) => tooltipContent = "Successfully removed certificates."; variant = "success"; label = "Certificates Removed"; - icon = faCheck; + Icon = CheckIcon; } return ( -
- - - {!mini && {label}} - -
+ + + {!mini && label} +
); }; diff --git a/frontend/src/components/pki-syncs/PkiSyncSelect.tsx b/frontend/src/components/pki-syncs/PkiSyncSelect.tsx index 667332c75..251f88ee2 100644 --- a/frontend/src/components/pki-syncs/PkiSyncSelect.tsx +++ b/frontend/src/components/pki-syncs/PkiSyncSelect.tsx @@ -69,7 +69,10 @@ export const PkiSyncSelect = ({ onSelect }: Props) => { type="button" onClick={() => enterprise && !subscription.enterpriseCertificateSyncs - ? handlePopUpOpen("upgradePlan") + ? handlePopUpOpen("upgradePlan", { + isEnterpriseFeature: true, + text: "All Certificate Syncs can be unlocked if you switch to Infisical Enterprise plan." + }) : onSelect(destination) } className="group relative flex h-28 cursor-pointer flex-col items-center justify-center overflow-hidden rounded-md border border-mineshaft-600 bg-mineshaft-700 p-4 duration-200 hover:bg-mineshaft-600" @@ -148,7 +151,8 @@ export const PkiSyncSelect = ({ onSelect }: Props) => { handlePopUpToggle("upgradePlan", isOpen)} - text="You can use every Certificate Sync if you switch to Infisical's Enterprise plan." + isEnterpriseFeature={popUp.upgradePlan.data?.isEnterpriseFeature} + text={popUp.upgradePlan.data?.text} />
); diff --git a/frontend/src/components/pki-syncs/PkiSyncStatusBadge.tsx b/frontend/src/components/pki-syncs/PkiSyncStatusBadge.tsx index 1fa207202..1c1294280 100644 --- a/frontend/src/components/pki-syncs/PkiSyncStatusBadge.tsx +++ b/frontend/src/components/pki-syncs/PkiSyncStatusBadge.tsx @@ -1,55 +1,51 @@ import { - faCheck, - faExclamationTriangle, - faHourglass, - faRotate, - IconDefinition -} from "@fortawesome/free-solid-svg-icons"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; + AlertTriangleIcon, + CheckIcon, + HourglassIcon, + LucideIcon, + RefreshCwIcon +} from "lucide-react"; -import { Badge, BadgeProps } from "@app/components/v2/Badge/Badge"; +import { Badge, TBadgeProps } from "@app/components/v3"; import { PkiSyncStatus } from "@app/hooks/api/pkiSyncs"; type Props = { status: PkiSyncStatus; -} & Omit; +} & Omit; export const PkiSyncStatusBadge = ({ status }: Props) => { - let variant: BadgeProps["variant"]; + let variant: TBadgeProps["variant"]; let text: string; - let icon: IconDefinition; + let Icon: LucideIcon; switch (status) { case PkiSyncStatus.Failed: variant = "danger"; text = "Failed to Sync"; - icon = faExclamationTriangle; + Icon = AlertTriangleIcon; break; case PkiSyncStatus.Succeeded: variant = "success"; text = "Synced"; - icon = faCheck; + Icon = CheckIcon; break; case PkiSyncStatus.Pending: - variant = "primary"; + variant = "info"; text = "Queued"; - icon = faHourglass; + Icon = HourglassIcon; break; case PkiSyncStatus.Running: default: - variant = "primary"; + variant = "info"; text = "Syncing"; - icon = faRotate; + Icon = RefreshCwIcon; break; } return ( - - - {text} + + + {text} ); }; diff --git a/frontend/src/components/pki-syncs/PkiSyncTable.tsx b/frontend/src/components/pki-syncs/PkiSyncTable.tsx index 983e4687c..4fbc7a16d 100644 --- a/frontend/src/components/pki-syncs/PkiSyncTable.tsx +++ b/frontend/src/components/pki-syncs/PkiSyncTable.tsx @@ -2,7 +2,6 @@ import { faPlug, faRefresh, faTrash } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { - Badge, EmptyState, IconButton, Table, @@ -13,6 +12,7 @@ import { THead, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { TPkiSync } from "@app/hooks/api/pkiSyncs"; type Props = { @@ -29,10 +29,10 @@ const getSyncStatusBadge = (status?: string) => { case "FAILED": return Failed; case "RUNNING": - return Running; + return Running; case "PENDING": default: - return Pending; + return Pending; } }; @@ -71,7 +71,7 @@ export const PkiSyncTable = ({ pkiSyncs, onEdit, onDelete, onTrigger }: Props) = {pkiSync.name}
- {pkiSync.destination} + {pkiSync.destination}
{pkiSync.appConnectionName || "Unknown"} diff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx index 582518bd7..6ffb2f859 100644 --- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx +++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx @@ -13,27 +13,28 @@ import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs"; import { PkiSync, TPkiSync, useCreatePkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs"; import { PkiSyncFormSchema, TPkiSyncForm } from "./schemas/pki-sync-schema"; +import { PkiSyncCertificatesFields } from "./PkiSyncCertificatesFields"; import { PkiSyncDestinationFields } from "./PkiSyncDestinationFields"; import { PkiSyncDetailsFields } from "./PkiSyncDetailsFields"; import { PkiSyncOptionsFields } from "./PkiSyncOptionsFields"; import { PkiSyncReviewFields } from "./PkiSyncReviewFields"; -import { PkiSyncSourceFields } from "./PkiSyncSourceFields"; type Props = { onComplete: (pkiSync: TPkiSync) => void; destination: PkiSync; onCancel: () => void; + initialData?: any; }; const FORM_TABS: { name: string; key: string; fields: (keyof TPkiSyncForm)[] }[] = [ - { name: "Source", key: "source", fields: ["subscriberId"] }, { name: "Destination", key: "destination", fields: ["connection", "destinationConfig"] }, { name: "Sync Options", key: "options", fields: ["syncOptions"] }, { name: "Details", key: "details", fields: ["name", "description"] }, + { name: "Certificates", key: "certificates", fields: ["certificateIds"] }, { name: "Review", key: "review", fields: [] } ]; -export const CreatePkiSyncForm = ({ destination, onComplete, onCancel }: Props) => { +export const CreatePkiSyncForm = ({ destination, onComplete, onCancel, initialData }: Props) => { const createPkiSync = useCreatePkiSync(); const { currentProject } = useProject(); const { name: destinationName } = PKI_SYNC_MAP[destination]; @@ -49,34 +50,47 @@ export const CreatePkiSyncForm = ({ destination, onComplete, onCancel }: Props) defaultValues: { destination, isAutoSyncEnabled: false, + certificateIds: [], syncOptions: { canImportCertificates: false, canRemoveCertificates: false, + preserveArn: true, certificateNameSchema: syncOption?.defaultCertificateNameSchema - } + }, + ...initialData } as Partial, reValidateMode: "onChange" }); - const onSubmit = async ({ connection, destinationConfig, ...formData }: TPkiSyncForm) => { + const onSubmit = async ({ + connection, + destinationConfig, + certificateIds, + ...formData + }: TPkiSyncForm) => { try { const pkiSync = await createPkiSync.mutateAsync({ ...formData, connectionId: connection.id, projectId: currentProject.id, - destinationConfig + destinationConfig, + certificateIds: certificateIds || [] }); createNotification({ - text: `Successfully added ${destinationName} Certificate Sync`, + text: `Successfully created ${destinationName} Certificate Sync${ + certificateIds && certificateIds.length > 0 + ? ` with ${certificateIds.length} certificate(s)` + : "" + }`, type: "success" }); onComplete(pkiSync); } catch (err: Error | unknown) { - console.error(err); + console.error("PKI sync creation failed:", err); setShowConfirmation(false); createNotification({ - title: `Failed to add ${destinationName} Certificate Sync`, + title: `Failed to create ${destinationName} Certificate Sync`, text: err instanceof Error ? err.message : "An unknown error occurred", type: "error" }); @@ -184,9 +198,6 @@ export const CreatePkiSyncForm = ({ destination, onComplete, onCancel }: Props) ))} - - - @@ -200,8 +211,8 @@ export const CreatePkiSyncForm = ({ destination, onComplete, onCancel }: Props) + + + diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx index 73f5bc2bc..137e0d6de 100644 --- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx +++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx @@ -27,12 +27,16 @@ export const EditPkiSyncForm = ({ pkiSync, fields, onComplete }: Props) => { const formMethods = useForm({ resolver: zodResolver(UpdatePkiSyncFormSchema), defaultValues: { - ...pkiSync, + name: pkiSync.name, + destination: pkiSync.destination, description: pkiSync.description ?? "", connection: { id: pkiSync.connectionId, name: pkiSync.appConnectionName - } + }, + syncOptions: pkiSync.syncOptions, + destinationConfig: pkiSync.destinationConfig, + isAutoSyncEnabled: pkiSync.isAutoSyncEnabled } as Partial, reValidateMode: "onChange" }); diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncCertificatesFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncCertificatesFields.tsx new file mode 100644 index 000000000..a5abcb60b --- /dev/null +++ b/frontend/src/components/pki-syncs/forms/PkiSyncCertificatesFields.tsx @@ -0,0 +1,189 @@ +import { useMemo, useState } from "react"; +import { Controller, useFormContext } from "react-hook-form"; +import { faCertificate, faEdit, faTrash } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; + +import { + Button, + EmptyState, + FormControl, + Table, + TableContainer, + TBody, + Td, + Th, + THead, + Tooltip, + Tr +} from "@app/components/v2"; +import { useProject } from "@app/context"; +import { CertStatus } from "@app/hooks/api"; +import { useListWorkspaceCertificates } from "@app/hooks/api/projects"; + +import { CertificateManagementModal } from "../CertificateManagementModal"; +import { TPkiSyncForm } from "./schemas/pki-sync-schema"; + +export const PkiSyncCertificatesFields = () => { + const { control, watch, setValue } = useFormContext(); + const { currentProject } = useProject(); + const [isSelectionModalOpen, setIsSelectionModalOpen] = useState(false); + + const certificateIds = watch("certificateIds") || []; + + const { data, isLoading } = useListWorkspaceCertificates({ + projectId: currentProject?.id || "", + offset: 0, + limit: 100, + forPkiSync: true + }); + + const certificates = data?.certificates || []; + + const activeCertificates = useMemo( + () => certificates.filter((cert) => cert.status === CertStatus.ACTIVE), + [certificates] + ); + + const selectedCertificates = useMemo( + () => activeCertificates.filter((cert) => certificateIds.includes(cert.id)), + [activeCertificates, certificateIds] + ); + + if (isLoading) { + return ( +
+
Loading certificates...
+
+ ); + } + + return ( + <> +

+ Select certificates to sync with this integration. Only active certificates can be synced. + You can modify this selection after creating the sync. +

+ + ( + +
+ +
+ + + + + + + + + + + + + {selectedCertificates.map((cert) => { + let originalDisplayName = "—"; + if (cert.altNames && cert.altNames.trim()) { + originalDisplayName = cert.altNames.trim(); + } else if (cert.commonName && cert.commonName.trim()) { + originalDisplayName = cert.commonName.trim(); + } + + let displayName = originalDisplayName; + let isTruncated = false; + if (originalDisplayName.length > 34) { + displayName = `${originalDisplayName.substring(0, 34)}...`; + isTruncated = true; + } + + const truncatedSerial = + cert.serialNumber.length > 8 + ? `${cert.serialNumber.slice(0, 4)}...${cert.serialNumber.slice(-4)}` + : cert.serialNumber; + + const isExpired = new Date(cert.notAfter) < new Date(); + + return ( + + + + + + + + ); + })} + +
SAN / CNSerial NumberIssued AtExpires AtRemove
+ {isTruncated ? ( + +
{displayName}
+
+ ) : ( +
{displayName}
+ )} +
+
+ {truncatedSerial} +
+
+ + {new Date(cert.notBefore).toLocaleDateString()} + + + + {new Date(cert.notAfter).toLocaleDateString()} + + + +
+ {selectedCertificates.length === 0 && ( + + )} +
+
+
+
+ )} + /> + + setIsSelectionModalOpen(false)} + selectedCertificateIds={certificateIds} + onCertificateSelectionChange={(newCertificateIds) => { + setValue("certificateIds", newCertificateIds); + }} + title="Select Certificates for Sync" + subtitle="Choose which certificates you want to include in this sync. You can modify this selection after creating the sync." + saveButtonText="Update Selection" + /> + + ); +}; diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx index 445f9169d..c8da83aac 100644 --- a/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx +++ b/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx @@ -1,14 +1,18 @@ import { Controller, useFormContext } from "react-hook-form"; +import { SingleValue } from "react-select"; import { faInfoCircle } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { Link } from "@tanstack/react-router"; +import { useRouterState } from "@tanstack/react-router"; +import { AppConnectionOption } from "@app/components/app-connections"; import { FilterableSelect, FormControl } from "@app/components/v2"; import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context"; import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types"; import { APP_CONNECTION_MAP } from "@app/helpers/appConnections"; import { PKI_SYNC_CONNECTION_MAP } from "@app/helpers/pkiSyncs"; +import { usePopUp } from "@app/hooks"; import { useListAvailableAppConnections } from "@app/hooks/api/appConnections"; +import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components"; import { TPkiSyncForm } from "./schemas/pki-sync-schema"; @@ -18,12 +22,30 @@ type Props = { export const PkiSyncConnectionField = ({ onChange: callback }: Props) => { const { permission } = useProjectPermission(); - const { control, watch } = useFormContext(); - const { currentProject } = useProject(); + const { control, watch, setValue } = useFormContext(); + + const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["addConnection"] as const); const destination = watch("destination"); const app = PKI_SYNC_CONNECTION_MAP[destination]; + const { currentProject } = useProject(); + + const { + location: { pathname } + } = useRouterState(); + + const getPkiSyncReturnUrl = () => { + if (pathname.includes("selectedTab=secret-syncs")) { + return pathname.replace("selectedTab=secret-syncs", "selectedTab=pki-syncs"); + } + if (!pathname.includes("selectedTab=")) { + const separator = pathname.includes("?") ? "&" : "?"; + return `${pathname}${separator}selectedTab=pki-syncs`; + } + return pathname; + }; + const { data: availableConnections, isPending } = useListAvailableAppConnections( app, currentProject.id @@ -47,6 +69,7 @@ export const PkiSyncConnectionField = ({ onChange: callback }: Props) => { ( { { + if ((newValue as SingleValue<{ id: string; name: string }>)?.id === "_create") { + handlePopUpOpen("addConnection"); + onChange(null); + const formData = { ...watch(), returnUrl: getPkiSyncReturnUrl() }; + localStorage.setItem("pkiSyncFormData", JSON.stringify(formData)); + if (callback) callback(); + return; + } + onChange(newValue); if (callback) callback(); }} isLoading={isPending} - options={availableConnections} + options={[ + ...(canCreateConnection ? [{ id: "_create", name: "Create Connection" }] : []), + ...(availableConnections ?? []) + ]} placeholder="Select connection..." getOptionLabel={(option) => option.name} getOptionValue={(option) => option.id} + components={{ Option: AppConnectionOption }} /> )} control={control} name="connection" /> - {availableConnections?.length === 0 && ( + {!isPending && !availableConnections?.length && !canCreateConnection && (

- {canCreateConnection ? ( - <> - You do not have access to any {appName} Connections. Create one from the{" "} - - App Connections - {" "} - page. - - ) : ( - `You do not have access to any ${appName} Connections. Contact an admin to create one.` - )} + You do not have access to any {appName} Connections. Contact an admin to create one.

)} + { + localStorage.removeItem("pkiSyncFormData"); + handlePopUpToggle("addConnection", isOpen); + }} + projectType={currentProject.type} + projectId={currentProject.id} + app={app} + onComplete={(connection) => { + if (connection) { + setValue("connection", connection); + } + }} + /> ); }; diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx index ce581bb88..c1313e684 100644 --- a/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx +++ b/frontend/src/components/pki-syncs/forms/PkiSyncOptionsFields/PkiSyncOptionsFields.tsx @@ -71,14 +71,14 @@ export const PkiSyncOptionsFields = ({ destination }: Props) => { isChecked={value} >

- Enable Certificate Removal{" "} + Enable Removal of Expired/Revoked Certificates{" "}

When enabled, Infisical will remove certificates from the destination during - a sync if they are no longer managed by Infisical. + a sync if they are no longer active in Infisical.

Disable this option if you intend to manage some certificates manually @@ -95,6 +95,94 @@ export const PkiSyncOptionsFields = ({ destination }: Props) => { )} /> + {currentDestination === PkiSync.AwsCertificateManager && ( + ( + + +

+ Preserve ARN on Renewal{" "} + +

+ When enabled, Infisical will replace the contents of existing certificates + while preserving the same ARN during certificate renewal syncs. +

+

+ This allows consuming services like load balancers to continue using the + same ARN without requiring manual updates. +

+

+ When disabled, new certificates will be created with new ARNs, and old + certificates will be removed. +

+ + } + > + + +

+ +
+ )} + /> + )} + + {currentDestination === PkiSync.AzureKeyVault && ( + ( + + +

+ Enable Versioning on Renewal{" "} + +

+ When enabled, Infisical will create a new version of the existing + certificate in Azure Key Vault during certificate renewal syncs, + preserving the original certificate name. +

+

+ This allows consuming services to continue using the same certificate name + while automatically using the latest version without requiring manual + updates. +

+

+ When disabled, new certificates will be created with new names, and old + certificates will be removed. +

+ + } + > + + +

+
+
+ )} + /> + )} + { const { watch } = useFormContext(); const { currentProject } = useProject(); - const { data: pkiSubscribers = [] } = useListWorkspacePkiSubscribers(currentProject?.id || ""); + const { data } = useListWorkspaceCertificates({ + projectId: currentProject?.id || "", + offset: 0, + limit: 100 + }); - const getSubscriberName = (subscriberId?: string) => { - const subscriber = pkiSubscribers.find((sub) => sub.id === subscriberId); - return subscriber?.name || "Unknown"; + const certificates = data?.certificates || []; + + const getSelectedCertificates = (certificateIds?: string[]) => { + if (!certificateIds || certificateIds.length === 0) return []; + return certificates.filter((cert) => certificateIds.includes(cert.id)); }; const { name, description, connection, - subscriberId, + certificateIds, syncOptions, destination, destinationConfig, @@ -30,17 +47,79 @@ export const PkiSyncReviewFields = () => { } = watch(); const destinationName = PKI_SYNC_MAP[destination].name; + const selectedCertificates = getSelectedCertificates(certificateIds); return (
- Source + Certificates
-
- - {getSubscriberName(subscriberId)} - +
+ {selectedCertificates.length === 0 ? ( + No certificates selected + ) : ( + + + + + + + + + + + {selectedCertificates.map((cert) => { + let originalDisplayName = "—"; + if (cert.altNames && cert.altNames.trim()) { + originalDisplayName = cert.altNames.trim(); + } else if (cert.commonName && cert.commonName.trim()) { + originalDisplayName = cert.commonName.trim(); + } + + let displayName = originalDisplayName; + let isTruncated = false; + if (originalDisplayName.length > 34) { + displayName = `${originalDisplayName.substring(0, 34)}...`; + isTruncated = true; + } + + const truncatedSerial = + cert.serialNumber.length > 8 + ? `${cert.serialNumber.slice(0, 4)}...${cert.serialNumber.slice(-4)}` + : cert.serialNumber; + + return ( + + + + + + ); + })} + +
SAN / CNSerial NumberExpires At
+ {isTruncated ? ( + +
{displayName}
+
+ ) : ( +
{displayName}
+ )} +
+
+ {truncatedSerial} +
+
+ + {new Date(cert.notAfter).toLocaleDateString()} + +
+
+ )}
@@ -61,11 +140,13 @@ export const PkiSyncReviewFields = () => {
Sync Options
-
+
- - {isAutoSyncEnabled ? "Enabled" : "Disabled"} - +
+ + {isAutoSyncEnabled ? "Enabled" : "Disabled"} + +
{/* Hidden for now - Import certificates functionality disabled {syncOptions?.canImportCertificates !== undefined && ( @@ -78,9 +159,11 @@ export const PkiSyncReviewFields = () => { */} {syncOptions?.canRemoveCertificates !== undefined && ( - - {syncOptions.canRemoveCertificates ? "Enabled" : "Disabled"} - +
+ + {syncOptions.canRemoveCertificates ? "Enabled" : "Disabled"} + +
)}
diff --git a/frontend/src/components/pki-syncs/forms/schemas/aws-certificate-manager-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/aws-certificate-manager-pki-sync-destination-schema.ts index aa522ef7d..4333b6187 100644 --- a/frontend/src/components/pki-syncs/forms/schemas/aws-certificate-manager-pki-sync-destination-schema.ts +++ b/frontend/src/components/pki-syncs/forms/schemas/aws-certificate-manager-pki-sync-destination-schema.ts @@ -7,6 +7,7 @@ import { BasePkiSyncSchema } from "./base-pki-sync-schema"; const AwsCertificateManagerSyncOptionsSchema = z.object({ canImportCertificates: z.boolean().default(false), canRemoveCertificates: z.boolean().default(false), + preserveArn: z.boolean().default(true), certificateNameSchema: z .string() .optional() diff --git a/frontend/src/components/pki-syncs/forms/schemas/azure-key-vault-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/azure-key-vault-pki-sync-destination-schema.ts index e87e7a52c..2a8f3ee53 100644 --- a/frontend/src/components/pki-syncs/forms/schemas/azure-key-vault-pki-sync-destination-schema.ts +++ b/frontend/src/components/pki-syncs/forms/schemas/azure-key-vault-pki-sync-destination-schema.ts @@ -4,7 +4,46 @@ import { PkiSync } from "@app/hooks/api/pkiSyncs"; import { BasePkiSyncSchema } from "./base-pki-sync-schema"; -export const AzureKeyVaultPkiSyncDestinationSchema = BasePkiSyncSchema().merge( +const AzureKeyVaultSyncOptionsSchema = z.object({ + canImportCertificates: z.boolean().default(false), + canRemoveCertificates: z.boolean().default(true), + enableVersioning: z.boolean().default(true), + certificateNameSchema: z + .string() + .optional() + .refine( + (val) => { + if (!val) return true; + + const allowedOptionalPlaceholders = ["{{environment}}"]; + + const allowedPlaceholdersRegexPart = ["{{certificateId}}", ...allowedOptionalPlaceholders] + .map((p) => p.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&")) + .join("|"); + + const allowedContentRegex = new RegExp( + `^([a-zA-Z0-9_\\-/]|${allowedPlaceholdersRegexPart})*$` + ); + const contentIsValid = allowedContentRegex.test(val); + + if (val.trim()) { + const certificateIdRegex = /\{\{certificateId\}\}/; + const certificateIdIsPresent = certificateIdRegex.test(val); + return contentIsValid && certificateIdIsPresent; + } + + return contentIsValid; + }, + { + message: + "Certificate name schema must include exactly one {{certificateId}} placeholder. It can also include {{environment}} placeholders. Only alphanumeric characters (a-z, A-Z, 0-9), dashes (-), underscores (_), and slashes (/) are allowed besides the placeholders." + } + ) +}); + +export const AzureKeyVaultPkiSyncDestinationSchema = BasePkiSyncSchema( + AzureKeyVaultSyncOptionsSchema +).merge( z.object({ destination: z.literal(PkiSync.AzureKeyVault), destinationConfig: z.object({ diff --git a/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts index f8c9d599f..73da1f6af 100644 --- a/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts +++ b/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts @@ -53,7 +53,8 @@ export const BasePkiSyncSchema = ) : ( -
+
Add Secret Rotation - -
- - Docs - -
-
+
) } diff --git a/frontend/src/components/secret-rotations-v2/SecretRotationV2ModalHeader.tsx b/frontend/src/components/secret-rotations-v2/SecretRotationV2ModalHeader.tsx index d44d08046..a834d78dc 100644 --- a/frontend/src/components/secret-rotations-v2/SecretRotationV2ModalHeader.tsx +++ b/frontend/src/components/secret-rotations-v2/SecretRotationV2ModalHeader.tsx @@ -1,6 +1,4 @@ -import { faArrowUpRightFromSquare, faBookOpen } from "@fortawesome/free-solid-svg-icons"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; - +import { DocumentationLinkBadge } from "@app/components/v3"; import { SECRET_ROTATION_MAP } from "@app/helpers/secretRotationsV2"; import { SecretRotation } from "@app/hooks/api/secretRotationsV2"; @@ -20,23 +18,11 @@ export const SecretRotationV2ModalHeader = ({ type, isConfigured }: Props) => { className="h-12 w-12 rounded-md bg-bunker-500 p-2" />
-
+
{destinationDetails.name} Rotation - -
- - Docs - -
-
+ />

{isConfigured diff --git a/frontend/src/components/secret-rotations-v2/SecretRotationV2StatusBadge.tsx b/frontend/src/components/secret-rotations-v2/SecretRotationV2StatusBadge.tsx index c3b38f7a7..edb7cac1b 100644 --- a/frontend/src/components/secret-rotations-v2/SecretRotationV2StatusBadge.tsx +++ b/frontend/src/components/secret-rotations-v2/SecretRotationV2StatusBadge.tsx @@ -1,18 +1,17 @@ -import { faBan, faRotate, faXmark } from "@fortawesome/free-solid-svg-icons"; +import { faXmark } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { format, formatDistanceToNow } from "date-fns"; -import { twMerge } from "tailwind-merge"; +import { BanIcon, RefreshCwIcon, XIcon } from "lucide-react"; import { Tooltip } from "@app/components/v2"; -import { Badge } from "@app/components/v2/Badge/Badge"; +import { Badge } from "@app/components/v3"; import { SecretRotationStatus, TSecretRotationV2 } from "@app/hooks/api/secretRotationsV2"; type Props = { secretRotation: TSecretRotationV2; - className?: string; }; -export const SecretRotationV2StatusBadge = ({ secretRotation, className }: Props) => { +export const SecretRotationV2StatusBadge = ({ secretRotation }: Props) => { const { isAutoRotationEnabled, rotationStatus, nextRotationAt, lastRotationMessage } = secretRotation; @@ -50,28 +49,18 @@ export const SecretRotationV2StatusBadge = ({ secretRotation, className }: Props

} > -
- - - Rotation Failed - -
+ + + Rotation Failed + ); } if (!isAutoRotationEnabled) { return ( - - + + Auto-Rotation Disabled ); @@ -92,20 +81,12 @@ export const SecretRotationV2StatusBadge = ({ secretRotation, className }: Props } > -
- = 7 ? "success" : "primary"} - className={twMerge( - "flex h-5 w-min items-center gap-1.5 whitespace-nowrap capitalize", - className - )} - > - - {daysToRotation < 0 - ? "Rotating" - : `Rotates ${formatDistanceToNow(nextRotationAt, { addSuffix: true })}`} - -
+ = 7 ? "info" : "warning"} className="capitalize"> + + {daysToRotation < 0 + ? "Rotating" + : `Rotates ${formatDistanceToNow(nextRotationAt, { addSuffix: true })}`} + ); }; diff --git a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2SecretsMappingFields/shared/SecretsMappingTable.tsx b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2SecretsMappingFields/shared/SecretsMappingTable.tsx index a012cb392..b5fafe11b 100644 --- a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2SecretsMappingFields/shared/SecretsMappingTable.tsx +++ b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2SecretsMappingFields/shared/SecretsMappingTable.tsx @@ -1,8 +1,10 @@ import { ReactNode } from "react"; -import { faArrowRight, faKey } from "@fortawesome/free-solid-svg-icons"; +import { faArrowRight } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { KeyIcon } from "lucide-react"; -import { Badge, FormLabel } from "@app/components/v2"; +import { FormLabel } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; type Props = { items: { name: string; input: ReactNode }[]; @@ -32,9 +34,10 @@ export const SecretsMappingTable = ({ items }: Props) => {
- - - {name} + {/* TODO(scott): probably shouldn't be a badge */} + + + {name}
diff --git a/frontend/src/components/secret-scanning/CreateSecretScanningDataSourceModal.tsx b/frontend/src/components/secret-scanning/CreateSecretScanningDataSourceModal.tsx index e4390024b..ac8c9dc24 100644 --- a/frontend/src/components/secret-scanning/CreateSecretScanningDataSourceModal.tsx +++ b/frontend/src/components/secret-scanning/CreateSecretScanningDataSourceModal.tsx @@ -1,10 +1,9 @@ import { useEffect, useState } from "react"; -import { faArrowUpRightFromSquare, faBookOpen } from "@fortawesome/free-solid-svg-icons"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { useNavigate, useRouterState } from "@tanstack/react-router"; import { TSecretScanningDataSourceForm } from "@app/components/secret-scanning/forms/schemas"; import { Modal, ModalContent } from "@app/components/v2"; +import { DocumentationLinkBadge } from "@app/components/v3"; import { SecretScanningDataSource, TSecretScanningDataSource @@ -108,23 +107,9 @@ export const CreateSecretScanningDataSourceModal = ({ onOpenChange, isOpen, ...p selectedDataSource ? ( ) : ( -
+
Add Data Source - -
- - Docs - -
-
+
) } diff --git a/frontend/src/components/secret-scanning/SecretScanningDataSourceModalHeader.tsx b/frontend/src/components/secret-scanning/SecretScanningDataSourceModalHeader.tsx index da964d6b6..6ae644fa5 100644 --- a/frontend/src/components/secret-scanning/SecretScanningDataSourceModalHeader.tsx +++ b/frontend/src/components/secret-scanning/SecretScanningDataSourceModalHeader.tsx @@ -1,6 +1,4 @@ -import { faArrowUpRightFromSquare, faBookOpen } from "@fortawesome/free-solid-svg-icons"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; - +import { DocumentationLinkBadge } from "@app/components/v3"; import { SECRET_SCANNING_DATA_SOURCE_MAP } from "@app/helpers/secretScanningV2"; import { SecretScanningDataSource } from "@app/hooks/api/secretScanningV2"; @@ -20,23 +18,11 @@ export const SecretScanningDataSourceModalHeader = ({ type, isConfigured }: Prop className="h-12 rounded-md bg-bunker-500 p-2" />
-
+
{dataSourceDetails.name} Data Source - -
- - Docs - -
-
+ />

{isConfigured ? "Edit" : "Connect a"} {dataSourceDetails.name} Data Source diff --git a/frontend/src/components/secret-scanning/SecretScanningScanStatus.tsx b/frontend/src/components/secret-scanning/SecretScanningScanStatus.tsx index a02e050f0..35913414f 100644 --- a/frontend/src/components/secret-scanning/SecretScanningScanStatus.tsx +++ b/frontend/src/components/secret-scanning/SecretScanningScanStatus.tsx @@ -1,22 +1,23 @@ -import { faArrowRotateForward, faCheck, faXmark } from "@fortawesome/free-solid-svg-icons"; +import { faXmark } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { formatDistance } from "date-fns"; -import { twMerge } from "tailwind-merge"; +import { CheckIcon, RotateCwIcon, XIcon } from "lucide-react"; -import { Badge, Tooltip } from "@app/components/v2"; +import { Tooltip } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { SecretScanningScanStatus } from "@app/hooks/api/secretScanningV2"; type Props = { status: SecretScanningScanStatus; statusMessage?: string | null; - className?: string; + scannedAt?: string | null; }; export const SecretScanningScanStatusBadge = ({ status, statusMessage, - className, + scannedAt }: Props) => { if (status === SecretScanningScanStatus.Failed) { @@ -53,11 +54,8 @@ export const SecretScanningScanStatusBadge = ({ } >

- - + + Scan Error
@@ -67,26 +65,17 @@ export const SecretScanningScanStatusBadge = ({ if (status === SecretScanningScanStatus.Queued || status === SecretScanningScanStatus.Scanning) { return ( - - - Scanning + + + Scanning ); } return ( - - - Complete + + + Complete ); }; diff --git a/frontend/src/components/secret-syncs/SecretSyncImportStatusBadge.tsx b/frontend/src/components/secret-syncs/SecretSyncImportStatusBadge.tsx index 54cfcd588..494528d00 100644 --- a/frontend/src/components/secret-syncs/SecretSyncImportStatusBadge.tsx +++ b/frontend/src/components/secret-syncs/SecretSyncImportStatusBadge.tsx @@ -1,27 +1,20 @@ import { ReactNode, useEffect, useMemo, useState } from "react"; -import { - faCheck, - faDownload, - faTriangleExclamation, - faXmark, - IconDefinition -} from "@fortawesome/free-solid-svg-icons"; +import { faXmark } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { differenceInSeconds } from "date-fns"; -import { twMerge } from "tailwind-merge"; +import { AlertTriangleIcon, CheckIcon, DownloadIcon, LucideIcon } from "lucide-react"; -import { Badge, Tooltip } from "@app/components/v2"; -import { BadgeProps } from "@app/components/v2/Badge/Badge"; +import { Tooltip } from "@app/components/v2"; +import { Badge, TBadgeProps } from "@app/components/v3"; import { SECRET_SYNC_MAP } from "@app/helpers/secretSyncs"; import { SecretSyncStatus, TSecretSync } from "@app/hooks/api/secretSyncs"; type Props = { secretSync: TSecretSync; - className?: string; mini?: boolean; }; -export const SecretSyncImportStatusBadge = ({ secretSync, className, mini }: Props) => { +export const SecretSyncImportStatusBadge = ({ secretSync, mini }: Props) => { const { importStatus, lastImportMessage, lastImportedAt, destination } = secretSync; const [hide, setHide] = useState(importStatus === SecretSyncStatus.Succeeded); const destinationName = SECRET_SYNC_MAP[destination].name; @@ -50,24 +43,24 @@ export const SecretSyncImportStatusBadge = ({ secretSync, className, mini }: Pro if (!importStatus || hide) return null; - let variant: BadgeProps["variant"]; + let variant: TBadgeProps["variant"]; let label: string; - let icon: IconDefinition; + let Icon: LucideIcon; let tooltipContent: ReactNode; switch (importStatus) { case SecretSyncStatus.Pending: case SecretSyncStatus.Running: - variant = "primary"; + variant = "warning"; label = "Importing Secrets..."; tooltipContent = `Importing secrets from ${destinationName}. This may take a moment.`; - icon = faDownload; + Icon = DownloadIcon; break; case SecretSyncStatus.Failed: variant = "danger"; label = "Failed to Import Secrets"; - icon = faTriangleExclamation; + Icon = AlertTriangleIcon; tooltipContent = (
{failureMessage && ( @@ -93,20 +86,15 @@ export const SecretSyncImportStatusBadge = ({ secretSync, className, mini }: Pro tooltipContent = "Successfully imported secrets."; variant = "success"; label = "Secrets Imported"; - icon = faCheck; + Icon = CheckIcon; } return ( -
- - - {!mini && {label}} - -
+ + + {!mini && label} +
); }; diff --git a/frontend/src/components/secret-syncs/SecretSyncModalHeader.tsx b/frontend/src/components/secret-syncs/SecretSyncModalHeader.tsx index ebbe34d75..41cbbcf58 100644 --- a/frontend/src/components/secret-syncs/SecretSyncModalHeader.tsx +++ b/frontend/src/components/secret-syncs/SecretSyncModalHeader.tsx @@ -1,6 +1,4 @@ -import { faArrowUpRightFromSquare, faBookOpen } from "@fortawesome/free-solid-svg-icons"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; - +import { DocumentationLinkBadge } from "@app/components/v3"; import { SECRET_SYNC_MAP } from "@app/helpers/secretSyncs"; import { SecretSync } from "@app/hooks/api/secretSyncs"; @@ -20,23 +18,11 @@ export const SecretSyncModalHeader = ({ destination, isConfigured }: Props) => { className="h-12 w-12 rounded-md bg-bunker-500 object-contain p-2" />
-
+
{destinationDetails.name} Sync - -
- - Docs - -
-
+ />

{isConfigured diff --git a/frontend/src/components/secret-syncs/SecretSyncRemoveStatusBadge.tsx b/frontend/src/components/secret-syncs/SecretSyncRemoveStatusBadge.tsx index abbd78838..917386818 100644 --- a/frontend/src/components/secret-syncs/SecretSyncRemoveStatusBadge.tsx +++ b/frontend/src/components/secret-syncs/SecretSyncRemoveStatusBadge.tsx @@ -1,27 +1,20 @@ import { ReactNode, useEffect, useMemo, useState } from "react"; -import { - faCheck, - faEraser, - faTriangleExclamation, - faXmark, - IconDefinition -} from "@fortawesome/free-solid-svg-icons"; +import { faXmark } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { differenceInSeconds } from "date-fns"; -import { twMerge } from "tailwind-merge"; +import { AlertTriangleIcon, CheckIcon, EraserIcon, LucideIcon } from "lucide-react"; -import { Badge, Tooltip } from "@app/components/v2"; -import { BadgeProps } from "@app/components/v2/Badge/Badge"; +import { Tooltip } from "@app/components/v2"; +import { Badge, TBadgeProps } from "@app/components/v3"; import { SECRET_SYNC_MAP } from "@app/helpers/secretSyncs"; import { SecretSyncStatus, TSecretSync } from "@app/hooks/api/secretSyncs"; type Props = { secretSync: TSecretSync; - className?: string; mini?: boolean; }; -export const SecretSyncRemoveStatusBadge = ({ secretSync, className, mini }: Props) => { +export const SecretSyncRemoveStatusBadge = ({ secretSync, mini }: Props) => { const { removeStatus, lastRemoveMessage, lastRemovedAt, destination } = secretSync; const [hide, setHide] = useState(removeStatus === SecretSyncStatus.Succeeded); const destinationName = SECRET_SYNC_MAP[destination].name; @@ -50,24 +43,24 @@ export const SecretSyncRemoveStatusBadge = ({ secretSync, className, mini }: Pro if (!removeStatus || hide) return null; - let variant: BadgeProps["variant"]; + let variant: TBadgeProps["variant"]; let label: string; - let icon: IconDefinition; + let Icon: LucideIcon; let tooltipContent: ReactNode; switch (removeStatus) { case SecretSyncStatus.Pending: case SecretSyncStatus.Running: - variant = "primary"; + variant = "warning"; label = "Removing Secrets..."; tooltipContent = `Removing secrets from ${destinationName}. This may take a moment.`; - icon = faEraser; + Icon = EraserIcon; break; case SecretSyncStatus.Failed: variant = "danger"; label = "Failed to Remove Secrets"; - icon = faTriangleExclamation; + Icon = AlertTriangleIcon; tooltipContent = (

{failureMessage && ( @@ -93,20 +86,15 @@ export const SecretSyncRemoveStatusBadge = ({ secretSync, className, mini }: Pro tooltipContent = "Successfully removed secrets."; variant = "success"; label = "Secrets Removed"; - icon = faCheck; + Icon = CheckIcon; } return ( -
- - - {!mini && {label}} - -
+ + + {!mini && label} +
); }; diff --git a/frontend/src/components/secret-syncs/SecretSyncSelect.tsx b/frontend/src/components/secret-syncs/SecretSyncSelect.tsx index 0c0fdd67b..881f16610 100644 --- a/frontend/src/components/secret-syncs/SecretSyncSelect.tsx +++ b/frontend/src/components/secret-syncs/SecretSyncSelect.tsx @@ -67,7 +67,10 @@ export const SecretSyncSelect = ({ onSelect }: Props) => { type="button" onClick={() => enterprise && !subscription.enterpriseSecretSyncs - ? handlePopUpOpen("upgradePlan") + ? handlePopUpOpen("upgradePlan", { + isEnterpriseFeature: true, + text: "All Secret Syncs can be unlocked if you switch to Infisical Enterprise plan." + }) : onSelect(destination) } className="group relative flex h-28 cursor-pointer flex-col items-center justify-center overflow-hidden rounded-md border border-mineshaft-600 bg-mineshaft-700 p-4 duration-200 hover:bg-mineshaft-600" @@ -145,8 +148,9 @@ export const SecretSyncSelect = ({ onSelect }: Props) => { )} handlePopUpToggle("upgradePlan", isOpen)} - text="You can use every Secret Sync if you switch to Infisical's Enterprise plan." + text={popUp.upgradePlan.data?.text} />
); diff --git a/frontend/src/components/secret-syncs/SecretSyncStatusBadge.tsx b/frontend/src/components/secret-syncs/SecretSyncStatusBadge.tsx index e0d541138..26ba74d2a 100644 --- a/frontend/src/components/secret-syncs/SecretSyncStatusBadge.tsx +++ b/frontend/src/components/secret-syncs/SecretSyncStatusBadge.tsx @@ -1,55 +1,51 @@ import { - faCheck, - faExclamationTriangle, - faHourglass, - faRotate, - IconDefinition -} from "@fortawesome/free-solid-svg-icons"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; + AlertTriangleIcon, + CheckIcon, + HourglassIcon, + LucideIcon, + RefreshCwIcon +} from "lucide-react"; -import { Badge, BadgeProps } from "@app/components/v2/Badge/Badge"; +import { Badge, TBadgeProps } from "@app/components/v3"; import { SecretSyncStatus } from "@app/hooks/api/secretSyncs"; type Props = { status: SecretSyncStatus; -} & Omit; +} & Omit; export const SecretSyncStatusBadge = ({ status }: Props) => { - let variant: BadgeProps["variant"]; + let variant: TBadgeProps["variant"]; let text: string; - let icon: IconDefinition; + let Icon: LucideIcon; switch (status) { case SecretSyncStatus.Failed: variant = "danger"; text = "Failed to Sync"; - icon = faExclamationTriangle; + Icon = AlertTriangleIcon; break; case SecretSyncStatus.Succeeded: variant = "success"; text = "Synced"; - icon = faCheck; + Icon = CheckIcon; break; case SecretSyncStatus.Pending: - variant = "primary"; + variant = "info"; text = "Queued"; - icon = faHourglass; + Icon = HourglassIcon; break; case SecretSyncStatus.Running: default: - variant = "primary"; + variant = "info"; text = "Syncing"; - icon = faRotate; + Icon = RefreshCwIcon; break; } return ( - - - {text} + + + {text} ); }; diff --git a/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx b/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx index 45e0297bd..ebad86cbd 100644 --- a/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx +++ b/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx @@ -8,13 +8,14 @@ import { twMerge } from "tailwind-merge"; import { createNotification } from "@app/components/notifications"; import { Button, FormControl, Switch } from "@app/components/v2"; -import { useProject } from "@app/context"; +import { useOrganization, useProject } from "@app/context"; import { SECRET_SYNC_MAP } from "@app/helpers/secretSyncs"; import { SecretSync, SecretSyncInitialSyncBehavior, TSecretSync, useCreateSecretSync, + useDuplicateDestinationCheck, useSecretSyncOption } from "@app/hooks/api/secretSyncs"; @@ -48,6 +49,7 @@ export const CreateSecretSyncForm = ({ }: Props) => { const createSecretSync = useCreateSecretSync(); const { currentProject } = useProject(); + const { currentOrg } = useOrganization(); const { name: destinationName } = SECRET_SYNC_MAP[destination]; const [showConfirmation, setShowConfirmation] = useState(false); @@ -106,11 +108,20 @@ export const CreateSecretSyncForm = ({ setSelectedTabIndex((prev) => prev - 1); }; - const { handleSubmit, trigger, control } = formMethods; + const { handleSubmit, trigger, control, watch } = formMethods; + + const { hasDuplicate } = useDuplicateDestinationCheck({ + destination, + projectId: currentProject?.id || "", + enabled: true, + destinationConfig: watch("destinationConfig") + }); const isStepValid = async (index: number) => trigger(FORM_TABS[index].fields); const isFinalStep = selectedTabIndex === FORM_TABS.length - 1; + const isCreateButtonDisabled = + isFinalStep && hasDuplicate && currentOrg?.blockDuplicateSecretSyncDestinations; const handleNext = async () => { if (isFinalStep) { @@ -245,7 +256,7 @@ export const CreateSecretSyncForm = ({
- {selectedTabIndex > 0 && ( diff --git a/frontend/src/components/secret-syncs/forms/DuplicateDestinationConfirmationModal.tsx b/frontend/src/components/secret-syncs/forms/DuplicateDestinationConfirmationModal.tsx index d80dbc640..59871e880 100644 --- a/frontend/src/components/secret-syncs/forms/DuplicateDestinationConfirmationModal.tsx +++ b/frontend/src/components/secret-syncs/forms/DuplicateDestinationConfirmationModal.tsx @@ -6,6 +6,7 @@ type Props = { onConfirm: () => void; isLoading?: boolean; duplicateProjectId?: string; + isDisabled?: boolean; }; export const DuplicateDestinationConfirmationModal = ({ @@ -13,7 +14,8 @@ export const DuplicateDestinationConfirmationModal = ({ onOpenChange, onConfirm, isLoading, - duplicateProjectId + duplicateProjectId, + isDisabled }: Props) => { return ( @@ -21,7 +23,12 @@ export const DuplicateDestinationConfirmationModal = ({

Another secret sync in your organization is already configured with the same - destination. Proceeding may cause conflicts or overwrite existing data. + destination.{" "} + + {isDisabled + ? "Your organization does not allow duplicate destination configurations." + : "Proceeding may cause conflicts or overwrite existing data."} +

{duplicateProjectId && (

@@ -31,26 +38,28 @@ export const DuplicateDestinationConfirmationModal = ({

)} -

Are you sure you want to continue?

+ {!isDisabled &&

Are you sure you want to continue?

}
-
- - - - - - -
+ {!isDisabled && ( +
+ + + + + + +
+ )}
); diff --git a/frontend/src/components/secret-syncs/forms/EditSecretSyncForm.tsx b/frontend/src/components/secret-syncs/forms/EditSecretSyncForm.tsx index 3c0e4ea17..2085afe9c 100644 --- a/frontend/src/components/secret-syncs/forms/EditSecretSyncForm.tsx +++ b/frontend/src/components/secret-syncs/forms/EditSecretSyncForm.tsx @@ -5,6 +5,7 @@ import { zodResolver } from "@hookform/resolvers/zod"; import { createNotification } from "@app/components/notifications"; import { SecretSyncEditFields } from "@app/components/secret-syncs/types"; import { Button, ModalClose } from "@app/components/v2"; +import { useOrganization } from "@app/context"; import { SECRET_SYNC_MAP } from "@app/helpers/secretSyncs"; import { TSecretSync, @@ -30,6 +31,7 @@ export const EditSecretSyncForm = ({ secretSync, fields, onComplete }: Props) => const { name: destinationName } = SECRET_SYNC_MAP[secretSync.destination]; const [showDuplicateConfirmation, setShowDuplicateConfirmation] = useState(false); const [pendingFormData, setPendingFormData] = useState(null); + const { currentOrg } = useOrganization(); const formMethods = useForm({ resolver: zodResolver(UpdateSecretSyncFormSchema), @@ -209,6 +211,7 @@ export const EditSecretSyncForm = ({ secretSync, fields, onComplete }: Props) => onConfirm={handleConfirmDuplicate} isLoading={updateSecretSync.isPending} duplicateProjectId={storedDuplicateProjectId} + isDisabled={currentOrg?.blockDuplicateSecretSyncDestinations} /> ); diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/ChefSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/ChefSyncFields.tsx new file mode 100644 index 000000000..bf5e0908c --- /dev/null +++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/ChefSyncFields.tsx @@ -0,0 +1,93 @@ +import { Controller, useFormContext, useWatch } from "react-hook-form"; +import { SingleValue } from "react-select"; + +import { SecretSyncConnectionField } from "@app/components/secret-syncs/forms/SecretSyncConnectionField"; +import { FilterableSelect, FormControl } from "@app/components/v2"; +import { + TChefDataBag, + TChefDataBagItem, + useChefConnectionListDataBagItems, + useChefConnectionListDataBags +} from "@app/hooks/api/appConnections/chef"; +import { SecretSync } from "@app/hooks/api/secretSyncs"; + +import { TSecretSyncForm } from "../schemas"; + +export const ChefSyncFields = () => { + const { control, setValue } = useFormContext< + TSecretSyncForm & { destination: SecretSync.Chef } + >(); + + const connectionId = useWatch({ name: "connection.id", control }); + const dataBagName = useWatch({ name: "destinationConfig.dataBagName", control }); + + const { data: dataBags, isLoading: isDataBagsLoading } = useChefConnectionListDataBags( + connectionId, + { + enabled: Boolean(connectionId) + } + ); + + const { data: dataBagItems, isLoading: isDataBagItemsLoading } = + useChefConnectionListDataBagItems(connectionId, dataBagName, { + enabled: Boolean(connectionId && dataBagName) + }); + + const handleChangeConnection = () => { + setValue("destinationConfig.dataBagName", ""); + setValue("destinationConfig.dataBagItemName", ""); + }; + + return ( + <> + + + ( + + dataBag.name === value) ?? null} + onChange={(option) => { + const selectedDataBag = option as SingleValue; + onChange(selectedDataBag?.name ?? ""); + setValue("destinationConfig.dataBagItemName", ""); + }} + options={dataBags} + placeholder="Select a data bag..." + getOptionLabel={(option) => option.name} + getOptionValue={(option) => option.name} + /> + + )} + /> + + ( + + dataBagItem.name === value) ?? null} + onChange={(option) => { + const selectedDataBagItem = option as SingleValue; + onChange(selectedDataBagItem?.name ?? ""); + }} + options={dataBagItems} + placeholder="Select a data bag item..." + getOptionLabel={(option) => option.name} + getOptionValue={(option) => option.name} + /> + + )} + /> + + ); +}; diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/GcpSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/GcpSyncFields.tsx index e7d988f46..08414c14e 100644 --- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/GcpSyncFields.tsx +++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/GcpSyncFields.tsx @@ -5,14 +5,8 @@ import { faCircleInfo } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { SecretSyncConnectionField } from "@app/components/secret-syncs/forms/SecretSyncConnectionField"; -import { - Badge, - FilterableSelect, - FormControl, - Select, - SelectItem, - Tooltip -} from "@app/components/v2"; +import { FilterableSelect, FormControl, Select, SelectItem, Tooltip } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { GCP_SYNC_SCOPES } from "@app/helpers/secretSyncs"; import { useGcpConnectionListProjectLocations, @@ -26,10 +20,7 @@ import { TSecretSyncForm } from "../schemas"; const formatOptionLabel = ({ displayName, locationId }: TGcpLocation) => (
- {displayName}{" "} - - {locationId} - + {displayName} {locationId}
); diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/NorthflankSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/NorthflankSyncFields.tsx new file mode 100644 index 000000000..2392e4394 --- /dev/null +++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/NorthflankSyncFields.tsx @@ -0,0 +1,123 @@ +import { Controller, useFormContext, useWatch } from "react-hook-form"; +import { SingleValue } from "react-select"; +import { faCircleInfo } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; + +import { SecretSyncConnectionField } from "@app/components/secret-syncs/forms/SecretSyncConnectionField"; +import { FilterableSelect, FormControl, Tooltip } from "@app/components/v2"; +import { + TNorthflankProject, + TNorthflankSecretGroup, + useNorthflankConnectionListProjects, + useNorthflankConnectionListSecretGroups +} from "@app/hooks/api/appConnections/northflank"; +import { SecretSync } from "@app/hooks/api/secretSyncs"; + +import { TSecretSyncForm } from "../schemas"; + +export const NorthflankSyncFields = () => { + const { control, setValue } = useFormContext< + TSecretSyncForm & { destination: SecretSync.Northflank } + >(); + + const connectionId = useWatch({ name: "connection.id", control }); + const projectId = useWatch({ name: "destinationConfig.projectId", control }); + + const { data: projects = [], isPending: isProjectsLoading } = useNorthflankConnectionListProjects( + connectionId, + { + enabled: Boolean(connectionId) + } + ); + + const { data: secretGroups = [], isPending: isSecretGroupsLoading } = + useNorthflankConnectionListSecretGroups(connectionId, projectId, { + enabled: Boolean(connectionId) && Boolean(projectId) + }); + + return ( + <> + { + setValue("destinationConfig.projectId", ""); + setValue("destinationConfig.projectName", ""); + setValue("destinationConfig.secretGroupId", ""); + setValue("destinationConfig.secretGroupName", ""); + }} + /> + ( + +
+ Don't see the project you're looking for?{" "} + +
+ + } + > + p.id === value) ?? null} + onChange={(option) => { + const v = option as SingleValue; + onChange(v?.id ?? null); + setValue("destinationConfig.projectName", v?.name ?? ""); + setValue("destinationConfig.secretGroupId", ""); + setValue("destinationConfig.secretGroupName", ""); + }} + options={projects} + placeholder="Select a project..." + getOptionLabel={(option) => option.name} + getOptionValue={(option) => option.id} + /> +
+ )} + /> + ( + +
+ Don't see the secret group you're looking for?{" "} + +
+ + } + > + sg.id === value) ?? null} + onChange={(option) => { + const v = option as SingleValue; + onChange(v?.id ?? null); + setValue("destinationConfig.secretGroupName", v?.name ?? ""); + }} + options={secretGroups} + placeholder="Select a secret group..." + getOptionLabel={(option) => option.name} + getOptionValue={(option) => option.id} + /> +
+ )} + /> + + ); +}; diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/SecretSyncDestinationFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/SecretSyncDestinationFields.tsx index 61ba54369..50fee8b9b 100644 --- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/SecretSyncDestinationFields.tsx +++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/SecretSyncDestinationFields.tsx @@ -12,6 +12,7 @@ import { AzureKeyVaultSyncFields } from "./AzureKeyVaultSyncFields"; import { BitbucketSyncFields } from "./BitbucketSyncFields"; import { CamundaSyncFields } from "./CamundaSyncFields"; import { ChecklySyncFields } from "./ChecklySyncFields"; +import { ChefSyncFields } from "./ChefSyncFields"; import { CloudflarePagesSyncFields } from "./CloudflarePagesSyncFields"; import { CloudflareWorkersSyncFields } from "./CloudflareWorkersSyncFields"; import { DatabricksSyncFields } from "./DatabricksSyncFields"; @@ -25,6 +26,7 @@ import { HerokuSyncFields } from "./HerokuSyncFields"; import { HumanitecSyncFields } from "./HumanitecSyncFields"; import { LaravelForgeSyncFields } from "./LaravelForgeSyncFields"; import { NetlifySyncFields } from "./NetlifySyncFields"; +import { NorthflankSyncFields } from "./NorthflankSyncFields"; import { OCIVaultSyncFields } from "./OCIVaultSyncFields"; import { RailwaySyncFields } from "./RailwaySyncFields"; import { RenderSyncFields } from "./RenderSyncFields"; @@ -103,6 +105,10 @@ export const SecretSyncDestinationFields = () => { return ; case SecretSync.LaravelForge: return ; + case SecretSync.Chef: + return ; + case SecretSync.Northflank: + return ; default: throw new Error(`Unhandled Destination Config Field: ${destination}`); } diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect.tsx index 6b1894626..829d7c44f 100644 --- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect.tsx +++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/shared/AwsRegionSelect.tsx @@ -2,7 +2,8 @@ import { components, OptionProps, SingleValue } from "react-select"; import { faCheckCircle } from "@fortawesome/free-regular-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { Badge, FilterableSelect } from "@app/components/v2"; +import { FilterableSelect } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { AWS_REGIONS } from "@app/helpers/appConnections"; const Option = ({ isSelected, children, ...props }: OptionProps<(typeof AWS_REGIONS)[number]>) => { @@ -10,7 +11,7 @@ const Option = ({ isSelected, children, ...props }: OptionProps<(typeof AWS_REGI

{children}

- + {props.data.slug} {isSelected && ( diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncOptionsFields/SecretSyncOptionsFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncOptionsFields/SecretSyncOptionsFields.tsx index f66cadaea..506c81a21 100644 --- a/frontend/src/components/secret-syncs/forms/SecretSyncOptionsFields/SecretSyncOptionsFields.tsx +++ b/frontend/src/components/secret-syncs/forms/SecretSyncOptionsFields/SecretSyncOptionsFields.tsx @@ -68,8 +68,10 @@ export const SecretSyncOptionsFields = ({ hideInitialSync }: Props) => { case SecretSync.Supabase: case SecretSync.DigitalOceanAppPlatform: case SecretSync.Netlify: + case SecretSync.Northflank: case SecretSync.Bitbucket: case SecretSync.LaravelForge: + case SecretSync.Chef: AdditionalSyncOptionsFieldsComponent = null; break; default: diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/AwsParameterStoreSyncReviewFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/AwsParameterStoreSyncReviewFields.tsx index 073cb4175..a70752703 100644 --- a/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/AwsParameterStoreSyncReviewFields.tsx +++ b/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/AwsParameterStoreSyncReviewFields.tsx @@ -1,10 +1,10 @@ import { useFormContext } from "react-hook-form"; -import { faEye } from "@fortawesome/free-solid-svg-icons"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { EyeIcon } from "lucide-react"; import { GenericFieldLabel } from "@app/components/secret-syncs"; import { TSecretSyncForm } from "@app/components/secret-syncs/forms/schemas"; -import { Badge, Table, TBody, Td, Th, THead, Tooltip, Tr } from "@app/components/v2"; +import { Table, TBody, Td, Th, THead, Tooltip, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { AWS_REGIONS } from "@app/helpers/appConnections"; import { SecretSync } from "@app/hooks/api/secretSyncs"; @@ -41,11 +41,9 @@ export const AwsParameterStoreSyncOptionsReviewFields = () => { } >
- - - - {tags.length} Tag{tags.length > 1 ? "s" : ""} - + + + {tags.length} Tag{tags.length > 1 ? "s" : ""}
diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/AwsSecretsManagerSyncReviewFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/AwsSecretsManagerSyncReviewFields.tsx index 90d7d5023..d37cae3f1 100644 --- a/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/AwsSecretsManagerSyncReviewFields.tsx +++ b/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/AwsSecretsManagerSyncReviewFields.tsx @@ -1,10 +1,10 @@ import { useFormContext } from "react-hook-form"; -import { faEye } from "@fortawesome/free-solid-svg-icons"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { EyeIcon } from "lucide-react"; import { GenericFieldLabel } from "@app/components/secret-syncs"; import { TSecretSyncForm } from "@app/components/secret-syncs/forms/schemas"; -import { Badge, Table, TBody, Td, Th, THead, Tooltip, Tr } from "@app/components/v2"; +import { Table, TBody, Td, Th, THead, Tooltip, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { AWS_REGIONS } from "@app/helpers/appConnections"; import { SecretSync } from "@app/hooks/api/secretSyncs"; import { AwsSecretsManagerSyncMappingBehavior } from "@app/hooks/api/secretSyncs/types/aws-secrets-manager-sync"; @@ -26,7 +26,7 @@ export const AwsSecretsManagerSyncReviewFields = () => { <> {awsRegion?.name} - + {awsRegion?.slug}{" "} @@ -73,11 +73,9 @@ export const AwsSecretsManagerSyncOptionsReviewFields = () => { } >
- - - - {tags.length} Tag{tags.length > 1 ? "s" : ""} - + + + {tags.length} Tag{tags.length > 1 ? "s" : ""}
diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/ChefSyncReviewFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/ChefSyncReviewFields.tsx new file mode 100644 index 000000000..95f5310a2 --- /dev/null +++ b/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/ChefSyncReviewFields.tsx @@ -0,0 +1,18 @@ +import { useFormContext } from "react-hook-form"; + +import { TSecretSyncForm } from "@app/components/secret-syncs/forms/schemas"; +import { GenericFieldLabel } from "@app/components/v2"; +import { SecretSync } from "@app/hooks/api/secretSyncs"; + +export const ChefSyncReviewFields = () => { + const { watch } = useFormContext(); + const dataBagName = watch("destinationConfig.dataBagName"); + const dataBagItemName = watch("destinationConfig.dataBagItemName"); + + return ( + <> + {dataBagName} + {dataBagItemName} + + ); +}; diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/NorthflankSyncReviewFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/NorthflankSyncReviewFields.tsx new file mode 100644 index 000000000..a37597722 --- /dev/null +++ b/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/NorthflankSyncReviewFields.tsx @@ -0,0 +1,20 @@ +import { useFormContext } from "react-hook-form"; + +import { TSecretSyncForm } from "@app/components/secret-syncs/forms/schemas"; +import { GenericFieldLabel } from "@app/components/v2"; +import { SecretSync } from "@app/hooks/api/secretSyncs"; + +export const NorthflankSyncReviewFields = () => { + const { watch } = useFormContext(); + const projectName = watch("destinationConfig.projectName"); + const projectId = watch("destinationConfig.projectId"); + const secretGroupName = watch("destinationConfig.secretGroupName"); + const secretGroupId = watch("destinationConfig.secretGroupId"); + + return ( + <> + {projectName || projectId} + {secretGroupName || secretGroupId} + + ); +}; diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/RenderSyncReviewFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/RenderSyncReviewFields.tsx index f195f0e72..313d7eb3d 100644 --- a/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/RenderSyncReviewFields.tsx +++ b/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/RenderSyncReviewFields.tsx @@ -2,7 +2,7 @@ import { useFormContext } from "react-hook-form"; import { GenericFieldLabel } from "@app/components/secret-syncs"; import { TSecretSyncForm } from "@app/components/secret-syncs/forms/schemas"; -import { Badge } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { SecretSync } from "@app/hooks/api/secretSyncs"; import { RenderSyncScope } from "@app/hooks/api/secretSyncs/types/render-sync"; diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/SecretSyncReviewFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/SecretSyncReviewFields.tsx index 44d35cd2c..940b3c173 100644 --- a/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/SecretSyncReviewFields.tsx +++ b/frontend/src/components/secret-syncs/forms/SecretSyncReviewFields/SecretSyncReviewFields.tsx @@ -5,8 +5,8 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { GenericFieldLabel } from "@app/components/secret-syncs"; import { TSecretSyncForm } from "@app/components/secret-syncs/forms/schemas"; -import { Badge } from "@app/components/v2"; -import { useProject } from "@app/context"; +import { Badge } from "@app/components/v3"; +import { useOrganization, useProject } from "@app/context"; import { SECRET_SYNC_INITIAL_SYNC_BEHAVIOR_MAP, SECRET_SYNC_MAP } from "@app/helpers/secretSyncs"; import { SecretSync, useDuplicateDestinationCheck } from "@app/hooks/api/secretSyncs"; @@ -24,6 +24,7 @@ import { AzureKeyVaultSyncReviewFields } from "./AzureKeyVaultSyncReviewFields"; import { BitbucketSyncReviewFields } from "./BitbucketSyncReviewFields"; import { CamundaSyncReviewFields } from "./CamundaSyncReviewFields"; import { ChecklySyncReviewFields } from "./ChecklySyncReviewFields"; +import { ChefSyncReviewFields } from "./ChefSyncReviewFields"; import { CloudflarePagesSyncReviewFields } from "./CloudflarePagesReviewFields"; import { CloudflareWorkersSyncReviewFields } from "./CloudflareWorkersReviewFields"; import { DatabricksSyncReviewFields } from "./DatabricksSyncReviewFields"; @@ -37,6 +38,7 @@ import { HerokuSyncReviewFields } from "./HerokuSyncReviewFields"; import { HumanitecSyncReviewFields } from "./HumanitecSyncReviewFields"; import { LaravelForgeSyncReviewFields } from "./LaravelForgeSyncReviewFields"; import { NetlifySyncReviewFields } from "./NetlifySyncReviewFields"; +import { NorthflankSyncReviewFields } from "./NorthflankSyncReviewFields"; import { OCIVaultSyncReviewFields } from "./OCIVaultSyncReviewFields"; import { OnePassSyncReviewFields } from "./OnePassSyncReviewFields"; import { RailwaySyncReviewFields } from "./RailwaySyncReviewFields"; @@ -51,6 +53,7 @@ import { ZabbixSyncReviewFields } from "./ZabbixSyncReviewFields"; export const SecretSyncReviewFields = () => { const { watch } = useFormContext(); const { currentProject } = useProject(); + const { currentOrg } = useOrganization(); let DestinationFieldsComponent: ReactNode; let AdditionalSyncOptionsFieldsComponent: ReactNode; @@ -166,12 +169,18 @@ export const SecretSyncReviewFields = () => { case SecretSync.Netlify: DestinationFieldsComponent = ; break; + case SecretSync.Northflank: + DestinationFieldsComponent = ; + break; case SecretSync.Bitbucket: DestinationFieldsComponent = ; break; case SecretSync.LaravelForge: DestinationFieldsComponent = ; break; + case SecretSync.Chef: + DestinationFieldsComponent = ; + break; default: throw new Error(`Unhandled Destination Review Fields: ${destination}`); } @@ -193,18 +202,50 @@ export const SecretSyncReviewFields = () => { {isChecking && Checking...}
{hasDuplicate && ( -
-
- +
+
+

- Another secret sync in your organization is already configured with the same - destination. This may lead to conflicts or unexpected behavior. + {currentOrg?.blockDuplicateSecretSyncDestinations + ? "Another secret sync in your organization is already configured with the same destination. Your organization does not allow duplicate destination configurations." + : "Another secret sync in your organization is already configured with the same destination. This may lead to conflicts or unexpected behavior."}

{duplicateProjectId && ( -

+

Duplicate found in project ID:{" "} - + {duplicateProjectId}

@@ -224,7 +265,7 @@ export const SecretSyncReviewFields = () => {
- + {isAutoSyncEnabled ? "Enabled" : "Disabled"} @@ -235,7 +276,7 @@ export const SecretSyncReviewFields = () => { {AdditionalSyncOptionsFieldsComponent} {disableSecretDeletion && ( - Disabled + Disabled )}
diff --git a/frontend/src/components/secret-syncs/forms/schemas/chef-sync-destination-schema.ts b/frontend/src/components/secret-syncs/forms/schemas/chef-sync-destination-schema.ts new file mode 100644 index 000000000..8d27b616f --- /dev/null +++ b/frontend/src/components/secret-syncs/forms/schemas/chef-sync-destination-schema.ts @@ -0,0 +1,14 @@ +import { z } from "zod"; + +import { BaseSecretSyncSchema } from "@app/components/secret-syncs/forms/schemas/base-secret-sync-schema"; +import { SecretSync } from "@app/hooks/api/secretSyncs"; + +export const ChefSyncDestinationSchema = BaseSecretSyncSchema().merge( + z.object({ + destination: z.literal(SecretSync.Chef), + destinationConfig: z.object({ + dataBagName: z.string().trim().min(1, "Data Bag required"), + dataBagItemName: z.string().trim().min(1, "Data Bag Item required") + }) + }) +); diff --git a/frontend/src/components/secret-syncs/forms/schemas/northflank-sync-destination-schema.ts b/frontend/src/components/secret-syncs/forms/schemas/northflank-sync-destination-schema.ts new file mode 100644 index 000000000..1554da63b --- /dev/null +++ b/frontend/src/components/secret-syncs/forms/schemas/northflank-sync-destination-schema.ts @@ -0,0 +1,16 @@ +import { z } from "zod"; + +import { BaseSecretSyncSchema } from "@app/components/secret-syncs/forms/schemas/base-secret-sync-schema"; +import { SecretSync } from "@app/hooks/api/secretSyncs"; + +export const NorthflankSyncDestinationSchema = BaseSecretSyncSchema().merge( + z.object({ + destination: z.literal(SecretSync.Northflank), + destinationConfig: z.object({ + projectId: z.string().trim().min(1, "Project ID is required"), + projectName: z.string().trim().optional(), + secretGroupId: z.string().trim().min(1, "Secret Group ID is required"), + secretGroupName: z.string().trim().optional() + }) + }) +); diff --git a/frontend/src/components/secret-syncs/forms/schemas/secret-sync-schema.ts b/frontend/src/components/secret-syncs/forms/schemas/secret-sync-schema.ts index 5ebc38184..561191da0 100644 --- a/frontend/src/components/secret-syncs/forms/schemas/secret-sync-schema.ts +++ b/frontend/src/components/secret-syncs/forms/schemas/secret-sync-schema.ts @@ -9,6 +9,7 @@ import { AzureKeyVaultSyncDestinationSchema } from "./azure-key-vault-sync-desti import { BitbucketSyncDestinationSchema } from "./bitbucket-sync-destination-schema"; import { CamundaSyncDestinationSchema } from "./camunda-sync-destination-schema"; import { ChecklySyncDestinationSchema } from "./checkly-sync-destination-schema"; +import { ChefSyncDestinationSchema } from "./chef-sync-destination-schema"; import { CloudflarePagesSyncDestinationSchema } from "./cloudflare-pages-sync-destination-schema"; import { CloudflareWorkersSyncDestinationSchema } from "./cloudflare-workers-sync-destination-schema"; import { DatabricksSyncDestinationSchema } from "./databricks-sync-destination-schema"; @@ -22,6 +23,7 @@ import { HerokuSyncDestinationSchema } from "./heroku-sync-destination-schema"; import { HumanitecSyncDestinationSchema } from "./humanitec-sync-destination-schema"; import { LaravelForgeSyncDestinationSchema } from "./laravel-forge-sync-destination-schema"; import { NetlifySyncDestinationSchema } from "./netlify-sync-destination-schema"; +import { NorthflankSyncDestinationSchema } from "./northflank-sync-destination-schema"; import { OCIVaultSyncDestinationSchema } from "./oci-vault-sync-destination-schema"; import { RailwaySyncDestinationSchema } from "./railway-sync-destination-schema"; import { RenderSyncDestinationSchema } from "./render-sync-destination-schema"; @@ -62,8 +64,10 @@ const SecretSyncUnionSchema = z.discriminatedUnion("destination", [ ChecklySyncDestinationSchema, DigitalOceanAppPlatformSyncDestinationSchema, NetlifySyncDestinationSchema, + NorthflankSyncDestinationSchema, BitbucketSyncDestinationSchema, - LaravelForgeSyncDestinationSchema + LaravelForgeSyncDestinationSchema, + ChefSyncDestinationSchema ]); export const SecretSyncFormSchema = SecretSyncUnionSchema; diff --git a/frontend/src/components/utilities/certificateDisplayUtils.tsx b/frontend/src/components/utilities/certificateDisplayUtils.tsx new file mode 100644 index 000000000..4a2b2de26 --- /dev/null +++ b/frontend/src/components/utilities/certificateDisplayUtils.tsx @@ -0,0 +1,100 @@ +import { ReactNode } from "react"; + +import { Tooltip } from "@app/components/v2"; + +interface CertificateNameData { + altNames?: string | null; + commonName?: string | null; + certificateAltNames?: string | null; + certificateCommonName?: string | null; +} + +interface DisplayNameResult { + originalDisplayName: string; + displayName: string; + isTruncated: boolean; +} + +/** + * Extracts and formats the display name for a certificate from SAN/CN data + * @param cert - Certificate object with potential altNames/commonName fields + * @param maxLength - Maximum length before truncating (default: 64) + * @param fallback - Fallback text when no name is found (default: "—") + * @returns Object with original name, truncated name, and truncation flag + */ +export const getCertificateDisplayName = ( + cert: CertificateNameData, + maxLength: number = 64, + fallback: string = "—" +): DisplayNameResult => { + // Extract original display name - prioritize SAN over CN + let originalDisplayName = fallback; + + // Handle different property name variations + const altNames = cert.altNames || cert.certificateAltNames; + const commonName = cert.commonName || cert.certificateCommonName; + + if (altNames && altNames.trim()) { + originalDisplayName = altNames.trim(); + } else if (commonName && commonName.trim()) { + originalDisplayName = commonName.trim(); + } + + // Handle truncation + let displayName = originalDisplayName; + let isTruncated = false; + + if (originalDisplayName.length > maxLength) { + displayName = `${originalDisplayName.substring(0, maxLength)}...`; + isTruncated = true; + } + + return { + originalDisplayName, + displayName, + isTruncated + }; +}; + +/** + * Renders a certificate display name with optional tooltip for truncated names + * @param cert - Certificate object with potential altNames/commonName fields + * @param maxLength - Maximum length before truncating (default: 64) + * @param fallback - Fallback text when no name is found (default: "—") + * @param className - Optional CSS class for the display element + * @param tooltipClassName - Optional CSS class for the tooltip (default: "max-w-lg") + * @returns JSX element with certificate name and optional tooltip + */ +export const CertificateDisplayName = ({ + cert, + maxLength = 64, + fallback = "—", + className = "truncate", + tooltipClassName = "max-w-lg" +}: { + cert: CertificateNameData; + maxLength?: number; + fallback?: string; + className?: string; + tooltipClassName?: string; +}): ReactNode => { + const { originalDisplayName, displayName, isTruncated } = getCertificateDisplayName( + cert, + maxLength, + fallback + ); + + if (isTruncated) { + return ( + +
{displayName}
+
+ ); + } + + return ( +
+ {displayName} +
+ ); +}; diff --git a/frontend/src/components/v2/Badge/Badge.tsx b/frontend/src/components/v2/Badge/Badge.tsx deleted file mode 100644 index 36541a781..000000000 --- a/frontend/src/components/v2/Badge/Badge.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import { forwardRef } from "react"; -import { cva, VariantProps } from "cva"; -import { twMerge } from "tailwind-merge"; - -interface IProps { - children: React.ReactNode; - className?: string; - onClick?: (e: React.MouseEvent) => void; -} - -const badgeVariants = cva( - [ - "inline-block cursor-default rounded-md bg-yellow/20 px-1.5 py-0.5 text-xs text-yellow opacity-80 hover:opacity-100" - ], - { - variants: { - variant: { - primary: "bg-yellow/20 text-yellow", - danger: "bg-red/20 text-red", - success: "bg-green/20 text-green", - org: "bg-org-v1/20 text-org-v1 [&_svg]:text-org-v1 flex items-center opacity-100 hover:bg-org-v1/10 [&_svg]:size-3 gap-x-1 w-min whitespace-nowrap", - namespace: - "bg-namespace-v1/20 text-namespace-v1 [&_svg]:text-namespace-v1 flex opacity-100 hover:bg-namespace-v1/10 items-center [&_svg]:size-3.5 gap-x-1.5 w-min whitespace-nowrap", - project: - "bg-primary/10 text-primary [&_svg]:text-primary opacity-100 hover:bg-primary/10 flex items-center [&_svg]:size-3 w-min gap-x-1.5 whitespace-nowrap", - instance: - "bg-mineshaft-200/20 text-mineshaft-200 [&_svg]:text-mineshaft-200 opacity-100 hover:bg-mineshaft-200/20 flex items-center [&_svg]:size-3 gap-x-1.5 w-min whitespace-nowrap" - } - } - } -); - -export type BadgeProps = VariantProps & IProps; - -export const Badge = forwardRef( - ({ children, className, variant, ...props }, ref) => { - return ( -
- {children} -
- ); - } -); diff --git a/frontend/src/components/v2/Badge/index.tsx b/frontend/src/components/v2/Badge/index.tsx deleted file mode 100644 index 5c7042709..000000000 --- a/frontend/src/components/v2/Badge/index.tsx +++ /dev/null @@ -1 +0,0 @@ -export { Badge } from "./Badge"; diff --git a/frontend/src/components/v2/Modal/Modal.tsx b/frontend/src/components/v2/Modal/Modal.tsx index e7efda4b8..5e8f65788 100644 --- a/frontend/src/components/v2/Modal/Modal.tsx +++ b/frontend/src/components/v2/Modal/Modal.tsx @@ -14,6 +14,7 @@ export type ModalContentProps = Omit void; overlayClassName?: string; + showCloseButton?: boolean; }; export const ModalContent = forwardRef( @@ -27,6 +28,7 @@ export const ModalContent = forwardRef( footerContent, bodyClassName, onClose, + showCloseButton = true, ...props }, forwardedRef @@ -57,15 +59,17 @@ export const ModalContent = forwardRef( {children} {footerContent && {footerContent}} - - - - - + {showCloseButton && ( + + + + + + )} @@ -74,7 +78,9 @@ export const ModalContent = forwardRef( ModalContent.displayName = "ModalContent"; -export type ModalProps = Omit & { isOpen?: boolean }; +export type ModalProps = Omit & { + isOpen?: boolean; +}; export const Modal = ({ isOpen, ...props }: ModalProps) => ( ); diff --git a/frontend/src/components/v2/PageHeader/PageHeader.tsx b/frontend/src/components/v2/PageHeader/PageHeader.tsx index e3f72f61b..f84edfcd2 100644 --- a/frontend/src/components/v2/PageHeader/PageHeader.tsx +++ b/frontend/src/components/v2/PageHeader/PageHeader.tsx @@ -1,11 +1,16 @@ -import { IconDefinition } from "@fortawesome/free-brands-svg-icons"; -import { faCube, faCubes, faGlobe, faServer } from "@fortawesome/free-solid-svg-icons"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { createElement } from "react"; import { ReactNode } from "@tanstack/react-router"; +import { LucideIcon } from "lucide-react"; import { twMerge } from "tailwind-merge"; -import { Badge } from "@app/components/v2"; -import { BadgeProps } from "@app/components/v2/Badge/Badge"; +import { + Badge, + InstanceIcon, + OrgIcon, + ProjectIcon, + SubOrgIcon, + TBadgeProps +} from "@app/components/v3"; import { ProjectType } from "@app/hooks/api/projects/types"; type Props = { @@ -16,19 +21,19 @@ type Props = { scope: "org" | "namespace" | "instance" | ProjectType | null; }; -const SCOPE_NAME: Record, { label: string; icon: IconDefinition }> = { - org: { label: "Organization", icon: faGlobe }, - [ProjectType.SecretManager]: { label: "Project", icon: faCube }, - [ProjectType.CertificateManager]: { label: "Project", icon: faCube }, - [ProjectType.SSH]: { label: "Project", icon: faCube }, - [ProjectType.KMS]: { label: "Project", icon: faCube }, - [ProjectType.PAM]: { label: "Project", icon: faCube }, - [ProjectType.SecretScanning]: { label: "Project", icon: faCube }, - namespace: { label: "Sub-Organization", icon: faCubes }, - instance: { label: "Server", icon: faServer } +const SCOPE_NAME: Record, { label: string; icon: LucideIcon }> = { + org: { label: "Organization", icon: OrgIcon }, + [ProjectType.SecretManager]: { label: "Project", icon: ProjectIcon }, + [ProjectType.CertificateManager]: { label: "Project", icon: ProjectIcon }, + [ProjectType.SSH]: { label: "Project", icon: ProjectIcon }, + [ProjectType.KMS]: { label: "Project", icon: ProjectIcon }, + [ProjectType.PAM]: { label: "Project", icon: ProjectIcon }, + [ProjectType.SecretScanning]: { label: "Project", icon: ProjectIcon }, + namespace: { label: "Sub-Organization", icon: SubOrgIcon }, + instance: { label: "Server", icon: InstanceIcon } }; -const SCOPE_VARIANT: Record, BadgeProps["variant"]> = { +const SCOPE_VARIANT: Record, TBadgeProps["variant"]> = { org: "org", [ProjectType.SecretManager]: "project", [ProjectType.CertificateManager]: "project", @@ -36,8 +41,8 @@ const SCOPE_VARIANT: Record, BadgeProps["variant"]> [ProjectType.KMS]: "project", [ProjectType.PAM]: "project", [ProjectType.SecretScanning]: "project", - namespace: "namespace", - instance: "instance" + namespace: "sub-org", + instance: "neutral" }; export const PageHeader = ({ title, description, children, className, scope }: Props) => ( @@ -47,7 +52,7 @@ export const PageHeader = ({ title, description, children, className, scope }: P

{title}

{scope && ( - + {createElement(SCOPE_NAME[scope].icon)} {SCOPE_NAME[scope].label} )} diff --git a/frontend/src/components/v2/Select/Select.tsx b/frontend/src/components/v2/Select/Select.tsx index 3954b8b20..99e83823e 100644 --- a/frontend/src/components/v2/Select/Select.tsx +++ b/frontend/src/components/v2/Select/Select.tsx @@ -3,6 +3,7 @@ import { IconProp } from "@fortawesome/fontawesome-svg-core"; import { faCaretDown, faCaretUp, faCheck } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import * as SelectPrimitive from "@radix-ui/react-select"; +import { LucideIcon } from "lucide-react"; import { twMerge } from "tailwind-merge"; import { Spinner } from "../Spinner"; @@ -19,6 +20,7 @@ type Props = { icon?: IconProp; isMulti?: boolean; iconClassName?: string; + LucideIcon?: LucideIcon; dropdownContainerStyle?: React.CSSProperties; side?: SelectPrimitive.SelectContentProps["side"]; }; @@ -39,6 +41,7 @@ export const Select = forwardRef( iconClassName, dropdownContainerStyle, side, + LucideIcon: Lucide, ...props }, ref @@ -65,6 +68,7 @@ export const Select = forwardRef( >
{props.icon && } + {Lucide && }
diff --git a/frontend/src/components/v2/index.tsx b/frontend/src/components/v2/index.tsx index 8019c3589..cb4430aa4 100644 --- a/frontend/src/components/v2/index.tsx +++ b/frontend/src/components/v2/index.tsx @@ -2,7 +2,6 @@ export * from "./AccessRestrictedBanner"; export * from "./Accordion"; export * from "./Alert"; -export * from "./Badge"; export * from "./Breadcrumb"; export * from "./Button"; export * from "./Card"; diff --git a/frontend/src/components/v3/generic/Badge/Badge.stories.tsx b/frontend/src/components/v3/generic/Badge/Badge.stories.tsx index da0743a66..4cbf955f9 100644 --- a/frontend/src/components/v3/generic/Badge/Badge.stories.tsx +++ b/frontend/src/components/v3/generic/Badge/Badge.stories.tsx @@ -1,9 +1,9 @@ import type { Meta, StoryObj } from "@storybook/react-vite"; import { Link } from "@tanstack/react-router"; import { + AlertTriangleIcon, + AsteriskIcon, BanIcon, - BoxesIcon, - BoxIcon, CheckIcon, ChevronsUpDownIcon, CircleXIcon, @@ -11,9 +11,11 @@ import { GlobeIcon, InfoIcon, RadarIcon, - TriangleAlertIcon + TriangleAlertIcon, + UserIcon } from "lucide-react"; +import { OrgIcon, ProjectIcon, SubOrgIcon } from "../../platform"; import { Badge } from "./Badge"; /** @@ -69,7 +71,29 @@ export const Neutral: Story = { parameters: { docs: { description: { - story: "Use this variant when indicating neutral or disabled states." + story: + "Use this variant when indicating neutral or disabled states or when linking to external documents." + } + } + } +}; + +export const Ghost: Story = { + name: "Variant: Ghost", + args: { + variant: "ghost", + children: ( + <> + + User + + ) + }, + parameters: { + docs: { + description: { + story: + "Use this variant when indicating a configuration or property value. Avoid using this variant as an interactive element as it is not intuitive to interact with." } } } @@ -109,8 +133,7 @@ export const Info: Story = { parameters: { docs: { description: { - story: - "Use this variant when indicating informational states or linking to external references." + story: "Use this variant when indicating informational states." } } } @@ -162,7 +185,7 @@ export const Organization: Story = { variant: "org", children: ( <> - + Organization ) @@ -182,7 +205,7 @@ export const SubOrganization: Story = { variant: "sub-org", children: ( <> - + Sub-Organization ) @@ -202,7 +225,7 @@ export const Project: Story = { variant: "project", children: ( <> - + Project ) @@ -283,10 +306,11 @@ export const AsButton: Story = { export const IsTruncatable: Story = { name: "Example: isTruncatable", args: { + variant: "org", isTruncatable: true, children: ( <> - + Infisical Infrastructure ) @@ -295,7 +319,7 @@ export const IsTruncatable: Story = { docs: { description: { story: - "Use the `isTruncatable` prop with a `span` tag wrapping the text content to support truncation." + "Use the `isTruncatable` prop with a `span` tag wrapping the text content to support truncation. Parent `div` should have a fixed width and `flex` class." } } }, @@ -305,3 +329,48 @@ export const IsTruncatable: Story = {
) }; + +export const IsSquare: Story = { + name: "Example: isSquare", + args: { + variant: "danger", + isSquare: true, + children: + }, + parameters: { + docs: { + description: { + story: + "Use the `isSquare` prop when displaying a squared badge with 1-2 character text or only an icon." + } + } + } +}; + +export const IsFullWidth: Story = { + name: "Example: isFullWidth", + args: { + variant: "neutral", + isFullWidth: true, + + children: ( + <> + + Secret Value + + ) + }, + parameters: { + docs: { + description: { + story: + "Use the `isFullWidth` prop to expand the badges width to fill it's parent container." + } + } + }, + decorators: (Story) => ( +
+ +
+ ) +}; diff --git a/frontend/src/components/v3/generic/Badge/Badge.tsx b/frontend/src/components/v3/generic/Badge/Badge.tsx index cc66806bc..f94bff5f2 100644 --- a/frontend/src/components/v3/generic/Badge/Badge.tsx +++ b/frontend/src/components/v3/generic/Badge/Badge.tsx @@ -6,30 +6,37 @@ import { cn } from "@app/components/v3/utils"; const badgeVariants = cva( [ - "select-none items-center rounded-sm px-1.5 py-0.5 text-xs", - "gap-x-1 [a&,button&]:cursor-pointer inline-flex", - "[&>svg]:pointer-events-none [&>svg]:shrink-0 [&>svg]:stroke-[2.25] [&>svg]:size-3", + "select-none items-center align-middle rounded-sm h-4.5 px-1.5 text-xs", + "gap-x-1 [a&,button&]:cursor-pointer inline-flex font-normal", + "[&>svg]:pointer-events-none [&>svg]:shrink-0 [&>svg]:stroke-[2.25] [&_svg:not([class*='size-'])]:size-3", "transition duration-200 ease-in-out" ], { variants: { isTruncatable: { true: "[&>span,&>p]:truncate min-w-0", - false: "w-fit shrink-0 whitespace-nowrap overflow-hidden" + false: "w-fit shrink-0 min-w-fit whitespace-nowrap overflow-hidden" + }, + isFullWidth: { + true: "w-full justify-center" + }, + isSquare: { + true: "w-4.5 justify-center px-0.5" }, variant: { - neutral: "bg-neutral/30 text-neutral [a&,button&]:hover:bg-neutral/40", - success: "bg-success/30 text-success [a&,button&]:hover:bg-success/40", - info: "bg-info/30 text-info [a&,button&]:hover:bg-info/40", - warning: "bg-warning/30 text-warning [a&,button&]:hover:bg-warning/40", - danger: "bg-danger/30 text-danger [a&,button&]:hover:bg-danger/40", - project: "bg-project/30 text-project [a&,button&]:hover:bg-project/40", - org: "bg-org/30 text-org [a&,button&]:hover:bg-org/40", - "sub-org": "bg-sub-org/30 text-sub-org [a&,button&]:hover:bg-sub-org/40" + ghost: "text-mineshaft-200 gap-x-2", + neutral: "bg-neutral/25 text-neutral [a&,button&]:hover:bg-neutral/35", + success: "bg-success/25 text-success [a&,button&]:hover:bg-success/35", + info: "bg-info/25 text-info [a&,button&]:hover:bg-info/35", + warning: "bg-warning/25 text-warning [a&,button&]:hover:bg-warning/35", + danger: "bg-danger/25 text-danger [a&,button&]:hover:bg-danger/35", + project: "bg-project/25 text-project [a&,button&]:hover:bg-project/35", + org: "bg-org/25 text-org [a&,button&]:hover:bg-org/35", + "sub-org": "bg-sub-org/25 text-sub-org [a&,button&]:hover:bg-sub-org/35" } }, defaultVariants: { - variant: "success" + variant: "neutral" } } ); @@ -37,16 +44,28 @@ const badgeVariants = cva( type TBadgeProps = VariantProps & React.ComponentProps<"span"> & { asChild?: boolean; + variant: NonNullable["variant"]>; // TODO: REMOVE }; const Badge = forwardRef( - ({ className, variant, asChild = false, isTruncatable = false, ...props }, ref): JSX.Element => { + ( + { + className, + variant, + asChild = false, + isTruncatable = false, + isFullWidth = false, + isSquare = false, + ...props + }, + ref + ): JSX.Element => { const Comp = asChild ? Slot : "span"; return ( ); diff --git a/frontend/src/components/v3/index.ts b/frontend/src/components/v3/index.ts index e69de29bb..1b74c0e26 100644 --- a/frontend/src/components/v3/index.ts +++ b/frontend/src/components/v3/index.ts @@ -0,0 +1,2 @@ +export * from "./generic"; +export * from "./platform"; diff --git a/frontend/src/components/v3/platform/DocumentationLinkBadge/DocumentationLinkBadge.stories.tsx b/frontend/src/components/v3/platform/DocumentationLinkBadge/DocumentationLinkBadge.stories.tsx new file mode 100644 index 000000000..bd746532e --- /dev/null +++ b/frontend/src/components/v3/platform/DocumentationLinkBadge/DocumentationLinkBadge.stories.tsx @@ -0,0 +1,24 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; + +import { DocumentationLinkBadge } from "./DocumentationLinkBadge"; + +/** + * The documentation link badge is a re-usable component to link to Infisical documentation references. + */ +const meta = { + title: "Platform/Documentation Link Badge", + component: DocumentationLinkBadge, + parameters: { + layout: "centered" + }, + tags: ["autodocs"], + argTypes: {}, + args: { href: "https://infisical.com/docs/documentation/getting-started/introduction" } +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Default: Story = { + name: "Example: Default" +}; diff --git a/frontend/src/components/v3/platform/DocumentationLinkBadge/DocumentationLinkBadge.tsx b/frontend/src/components/v3/platform/DocumentationLinkBadge/DocumentationLinkBadge.tsx new file mode 100644 index 000000000..b847f93ae --- /dev/null +++ b/frontend/src/components/v3/platform/DocumentationLinkBadge/DocumentationLinkBadge.tsx @@ -0,0 +1,18 @@ +import { BookOpenIcon } from "lucide-react"; + +import { Badge } from "@app/components/v3"; + +type TDocumentationLinkBadgeProps = { + href: string; +}; + +export function DocumentationLinkBadge({ href }: TDocumentationLinkBadgeProps) { + return ( + + + + Documentation + + + ); +} diff --git a/frontend/src/components/v3/platform/DocumentationLinkBadge/index.ts b/frontend/src/components/v3/platform/DocumentationLinkBadge/index.ts new file mode 100644 index 000000000..aed3c2244 --- /dev/null +++ b/frontend/src/components/v3/platform/DocumentationLinkBadge/index.ts @@ -0,0 +1 @@ +export * from "./DocumentationLinkBadge"; diff --git a/frontend/src/components/v3/platform/ScopeIcons.tsx b/frontend/src/components/v3/platform/ScopeIcons.tsx new file mode 100644 index 000000000..8f8712319 --- /dev/null +++ b/frontend/src/components/v3/platform/ScopeIcons.tsx @@ -0,0 +1,8 @@ +import { BoxesIcon, BoxIcon, Building2Icon, ServerIcon } from "lucide-react"; + +const InstanceIcon = ServerIcon; +const OrgIcon = Building2Icon; +const SubOrgIcon = BoxesIcon; +const ProjectIcon = BoxIcon; + +export { InstanceIcon, OrgIcon, ProjectIcon, SubOrgIcon }; diff --git a/frontend/src/components/v3/platform/index.ts b/frontend/src/components/v3/platform/index.ts new file mode 100644 index 000000000..ab5839618 --- /dev/null +++ b/frontend/src/components/v3/platform/index.ts @@ -0,0 +1,2 @@ +export * from "./DocumentationLinkBadge"; +export * from "./ScopeIcons"; diff --git a/frontend/src/const/routes.ts b/frontend/src/const/routes.ts index c9a6b326d..5f199443d 100644 --- a/frontend/src/const/routes.ts +++ b/frontend/src/const/routes.ts @@ -301,10 +301,6 @@ export const ROUTE_PATHS = Object.freeze({ "/projects/cert-management/$projectId/subscribers", "/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/subscribers" ), - CertificatesPage: setRoute( - "/projects/cert-management/$projectId/certificates", - "/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/certificates" - ), CertificateAuthoritiesPage: setRoute( "/projects/cert-management/$projectId/certificate-authorities", "/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/certificate-authorities" diff --git a/frontend/src/helpers/appConnections.ts b/frontend/src/helpers/appConnections.ts index bdb26c796..1d0d7bec3 100644 --- a/frontend/src/helpers/appConnections.ts +++ b/frontend/src/helpers/appConnections.ts @@ -46,10 +46,12 @@ import { } from "@app/hooks/api/appConnections/types"; import { BitbucketConnectionMethod } from "@app/hooks/api/appConnections/types/bitbucket-connection"; import { ChecklyConnectionMethod } from "@app/hooks/api/appConnections/types/checkly-connection"; +import { ChefConnectionMethod } from "@app/hooks/api/appConnections/types/chef-connection"; import { DigitalOceanConnectionMethod } from "@app/hooks/api/appConnections/types/digital-ocean"; import { HerokuConnectionMethod } from "@app/hooks/api/appConnections/types/heroku-connection"; import { LaravelForgeConnectionMethod } from "@app/hooks/api/appConnections/types/laravel-forge-connection"; import { NetlifyConnectionMethod } from "@app/hooks/api/appConnections/types/netlify-connection"; +import { NorthflankConnectionMethod } from "@app/hooks/api/appConnections/types/northflank-connection"; import { OCIConnectionMethod } from "@app/hooks/api/appConnections/types/oci-connection"; import { RailwayConnectionMethod } from "@app/hooks/api/appConnections/types/railway-connection"; import { RenderConnectionMethod } from "@app/hooks/api/appConnections/types/render-connection"; @@ -121,13 +123,15 @@ export const APP_CONNECTION_MAP: Record< name: "Netlify", image: "Netlify.png" }, + [AppConnection.Northflank]: { name: "Northflank", image: "Northflank.png" }, [AppConnection.Okta]: { name: "Okta", image: "Okta.png" }, [AppConnection.Redis]: { name: "Redis", image: "Redis.png" }, [AppConnection.LaravelForge]: { name: "Laravel Forge", image: "Laravel Forge.png", size: 65 - } + }, + [AppConnection.Chef]: { name: "Chef", image: "Chef.png" } }; export const getAppConnectionMethodDetails = (method: TAppConnection["method"]) => { @@ -135,6 +139,8 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"]) case GitHubConnectionMethod.App: case GitHubRadarConnectionMethod.App: return { name: "GitHub App", icon: faGithub }; + case GitHubConnectionMethod.Pat: + return { name: "Personal Access Token", icon: faKey }; case AzureKeyVaultConnectionMethod.OAuth: case AzureAppConfigurationConnectionMethod.OAuth: case AzureClientSecretsConnectionMethod.OAuth: @@ -162,6 +168,7 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"]) case BitbucketConnectionMethod.ApiToken: case ZabbixConnectionMethod.ApiToken: case DigitalOceanConnectionMethod.ApiToken: + case NorthflankConnectionMethod.ApiToken: case OktaConnectionMethod.ApiToken: case LaravelForgeConnectionMethod.ApiToken: return { name: "API Token", icon: faKey }; @@ -197,6 +204,8 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"]) case RenderConnectionMethod.ApiKey: case ChecklyConnectionMethod.ApiKey: return { name: "API Key", icon: faKey }; + case ChefConnectionMethod.UserKey: + return { name: "User Key", icon: faKey }; case AzureClientSecretsConnectionMethod.ClientSecret: case AzureAppConfigurationConnectionMethod.ClientSecret: case AzureKeyVaultConnectionMethod.ClientSecret: diff --git a/frontend/src/helpers/policies.ts b/frontend/src/helpers/policies.ts index d798d3c10..58feaf703 100644 --- a/frontend/src/helpers/policies.ts +++ b/frontend/src/helpers/policies.ts @@ -1,20 +1,20 @@ -import { IconDefinition } from "@fortawesome/free-brands-svg-icons"; -import { faArrowRightToBracket, faEdit } from "@fortawesome/free-solid-svg-icons"; +import { LucideIcon, UserCheckIcon, UserPenIcon } from "lucide-react"; +import { TBadgeProps } from "@app/components/v3"; import { PolicyType } from "@app/hooks/api/policies/enums"; export const policyDetails: Record< PolicyType, - { name: string; className: string; icon: IconDefinition } + { name: string; variant: TBadgeProps["variant"]; Icon: LucideIcon } > = { [PolicyType.AccessPolicy]: { - className: "bg-green/20 text-green", + variant: "ghost", name: "Access Policy", - icon: faArrowRightToBracket + Icon: UserCheckIcon }, [PolicyType.ChangePolicy]: { - className: "bg-yellow/20 text-yellow", + variant: "ghost", name: "Change Policy", - icon: faEdit + Icon: UserPenIcon } }; diff --git a/frontend/src/helpers/secretScanningV2.ts b/frontend/src/helpers/secretScanningV2.ts index 4e88b8482..ee5226611 100644 --- a/frontend/src/helpers/secretScanningV2.ts +++ b/frontend/src/helpers/secretScanningV2.ts @@ -1,10 +1,6 @@ -import { - faBan, - faCheck, - faMagnifyingGlassMinus, - faWarning -} from "@fortawesome/free-solid-svg-icons"; +import { AlertTriangleIcon, BanIcon, CheckIcon, LucideIcon, SearchSlashIcon } from "lucide-react"; +import { TBadgeProps } from "@app/components/v3"; import { AppConnection } from "@app/hooks/api/appConnections/enums"; import { SecretScanningDataSource, @@ -74,12 +70,28 @@ export const RESOURCE_DESCRIPTION_HELPER: Record< } }; -export const SECRET_SCANNING_FINDING_STATUS_ICON_MAP = { - [SecretScanningFindingStatus.Resolved]: { icon: faCheck, className: "text-green" }, - [SecretScanningFindingStatus.Unresolved]: { icon: faWarning, className: "text-yellow" }, - [SecretScanningFindingStatus.Ignore]: { icon: faBan, className: "text-mineshaft-400" }, +export const SECRET_SCANNING_FINDING_STATUS_MAP: Record< + SecretScanningFindingStatus, + { Icon: LucideIcon; variant: TBadgeProps["variant"]; className: string } +> = { + [SecretScanningFindingStatus.Resolved]: { + Icon: CheckIcon, + variant: "success", + className: "text-success" + }, + [SecretScanningFindingStatus.Unresolved]: { + Icon: AlertTriangleIcon, + variant: "warning", + className: "text-warning" + }, + [SecretScanningFindingStatus.Ignore]: { + Icon: BanIcon, + variant: "neutral", + className: "text-neutral" + }, [SecretScanningFindingStatus.FalsePositive]: { - icon: faMagnifyingGlassMinus, - className: "text-mineshaft-400" + Icon: SearchSlashIcon, + variant: "neutral", + className: "text-neutral" } }; diff --git a/frontend/src/helpers/secretSyncs.ts b/frontend/src/helpers/secretSyncs.ts index 12cae6ea6..393aff644 100644 --- a/frontend/src/helpers/secretSyncs.ts +++ b/frontend/src/helpers/secretSyncs.ts @@ -114,9 +114,17 @@ export const SECRET_SYNC_MAP: Record = { [SecretSync.Checkly]: AppConnection.Checkly, [SecretSync.DigitalOceanAppPlatform]: AppConnection.DigitalOcean, [SecretSync.Netlify]: AppConnection.Netlify, + [SecretSync.Northflank]: AppConnection.Northflank, [SecretSync.Bitbucket]: AppConnection.Bitbucket, - [SecretSync.LaravelForge]: AppConnection.LaravelForge + [SecretSync.LaravelForge]: AppConnection.LaravelForge, + [SecretSync.Chef]: AppConnection.Chef }; export const SECRET_SYNC_INITIAL_SYNC_BEHAVIOR_MAP: Record< diff --git a/frontend/src/hooks/api/appConnections/chef/index.ts b/frontend/src/hooks/api/appConnections/chef/index.ts new file mode 100644 index 000000000..2c1906d36 --- /dev/null +++ b/frontend/src/hooks/api/appConnections/chef/index.ts @@ -0,0 +1,2 @@ +export * from "./queries"; +export * from "./types"; diff --git a/frontend/src/hooks/api/appConnections/chef/queries.tsx b/frontend/src/hooks/api/appConnections/chef/queries.tsx new file mode 100644 index 000000000..f24a39eed --- /dev/null +++ b/frontend/src/hooks/api/appConnections/chef/queries.tsx @@ -0,0 +1,68 @@ +import { useQuery, UseQueryOptions } from "@tanstack/react-query"; + +import { apiRequest } from "@app/config/request"; +import { appConnectionKeys } from "@app/hooks/api/appConnections"; + +import { TChefDataBag, TChefDataBagItem } from "./types"; + +const chefConnectionKeys = { + all: [...appConnectionKeys.all, "chef"] as const, + listDataBags: (connectionId: string) => + [...chefConnectionKeys.all, "data-bags", connectionId] as const, + listDataBagItems: (connectionId: string, dataBagName: string) => + [...chefConnectionKeys.all, "data-bag-items", connectionId, dataBagName] as const +}; + +export const useChefConnectionListDataBags = ( + connectionId: string, + options?: Omit< + UseQueryOptions< + TChefDataBag[], + unknown, + TChefDataBag[], + ReturnType + >, + "queryKey" | "queryFn" + > +) => { + return useQuery({ + queryKey: chefConnectionKeys.listDataBags(connectionId), + queryFn: async () => { + const { data } = await apiRequest.get( + `/api/v1/app-connections/chef/${connectionId}/data-bags` + ); + + return data; + }, + ...options + }); +}; + +export const useChefConnectionListDataBagItems = ( + connectionId: string, + dataBagName: string, + options?: Omit< + UseQueryOptions< + TChefDataBagItem[], + unknown, + TChefDataBagItem[], + ReturnType + >, + "queryKey" | "queryFn" + > +) => { + return useQuery({ + queryKey: chefConnectionKeys.listDataBagItems(connectionId, dataBagName), + queryFn: async () => { + const params = { dataBagName }; + const { data } = await apiRequest.get( + `/api/v1/app-connections/chef/${connectionId}/data-bag-items`, + { params } + ); + + return data; + }, + enabled: Boolean(connectionId && dataBagName), + ...options + }); +}; diff --git a/frontend/src/hooks/api/appConnections/chef/types.ts b/frontend/src/hooks/api/appConnections/chef/types.ts new file mode 100644 index 000000000..fd87d47c7 --- /dev/null +++ b/frontend/src/hooks/api/appConnections/chef/types.ts @@ -0,0 +1,7 @@ +export type TChefDataBag = { + name: string; +}; + +export type TChefDataBagItem = { + name: string; +}; diff --git a/frontend/src/hooks/api/appConnections/enums.ts b/frontend/src/hooks/api/appConnections/enums.ts index 66fed8a5d..fba0cbb4b 100644 --- a/frontend/src/hooks/api/appConnections/enums.ts +++ b/frontend/src/hooks/api/appConnections/enums.ts @@ -36,7 +36,9 @@ export enum AppConnection { Supabase = "supabase", DigitalOcean = "digital-ocean", Netlify = "netlify", + Northflank = "northflank", Okta = "okta", Redis = "redis", - LaravelForge = "laravel-forge" + LaravelForge = "laravel-forge", + Chef = "chef" } diff --git a/frontend/src/hooks/api/appConnections/gitlab/types.ts b/frontend/src/hooks/api/appConnections/gitlab/types.ts index 0d8d9baf0..7d2699c75 100644 --- a/frontend/src/hooks/api/appConnections/gitlab/types.ts +++ b/frontend/src/hooks/api/appConnections/gitlab/types.ts @@ -10,5 +10,6 @@ export type TGitLabGroup = { export enum GitLabAccessTokenType { Personal = "personal", - Project = "project" + Project = "project", + Group = "group" } diff --git a/frontend/src/hooks/api/appConnections/northflank/index.ts b/frontend/src/hooks/api/appConnections/northflank/index.ts new file mode 100644 index 000000000..2c1906d36 --- /dev/null +++ b/frontend/src/hooks/api/appConnections/northflank/index.ts @@ -0,0 +1,2 @@ +export * from "./queries"; +export * from "./types"; diff --git a/frontend/src/hooks/api/appConnections/northflank/queries.tsx b/frontend/src/hooks/api/appConnections/northflank/queries.tsx new file mode 100644 index 000000000..bf63cd976 --- /dev/null +++ b/frontend/src/hooks/api/appConnections/northflank/queries.tsx @@ -0,0 +1,65 @@ +import { useQuery, UseQueryOptions } from "@tanstack/react-query"; + +import { apiRequest } from "@app/config/request"; +import { appConnectionKeys } from "@app/hooks/api/appConnections"; + +import { TNorthflankProject, TNorthflankSecretGroup } from "./types"; + +const northflankConnectionKeys = { + all: [...appConnectionKeys.all, "northflank"] as const, + listProjects: (connectionId: string) => + [...northflankConnectionKeys.all, "projects", connectionId] as const, + listSecretGroups: (connectionId: string, projectId: string) => + [...northflankConnectionKeys.all, "secret-groups", connectionId, projectId] as const +}; + +export const useNorthflankConnectionListProjects = ( + connectionId: string, + options?: Omit< + UseQueryOptions< + TNorthflankProject[], + unknown, + TNorthflankProject[], + ReturnType + >, + "queryKey" | "queryFn" + > +) => { + return useQuery({ + queryKey: northflankConnectionKeys.listProjects(connectionId), + queryFn: async () => { + const { data } = await apiRequest.get<{ projects: TNorthflankProject[] }>( + `/api/v1/app-connections/northflank/${connectionId}/projects` + ); + + return data.projects; + }, + ...options + }); +}; + +export const useNorthflankConnectionListSecretGroups = ( + connectionId: string, + projectId: string, + options?: Omit< + UseQueryOptions< + TNorthflankSecretGroup[], + unknown, + TNorthflankSecretGroup[], + ReturnType + >, + "queryKey" | "queryFn" + > +) => { + return useQuery({ + queryKey: northflankConnectionKeys.listSecretGroups(connectionId, projectId), + queryFn: async () => { + const { data } = await apiRequest.get<{ secretGroups: TNorthflankSecretGroup[] }>( + `/api/v1/app-connections/northflank/${connectionId}/projects/${projectId}/secret-groups` + ); + + return data.secretGroups; + }, + ...options + }); +}; diff --git a/frontend/src/hooks/api/appConnections/northflank/types.ts b/frontend/src/hooks/api/appConnections/northflank/types.ts new file mode 100644 index 000000000..061d2179f --- /dev/null +++ b/frontend/src/hooks/api/appConnections/northflank/types.ts @@ -0,0 +1,9 @@ +export type TNorthflankProject = { + id: string; + name: string; +}; + +export type TNorthflankSecretGroup = { + id: string; + name: string; +}; diff --git a/frontend/src/hooks/api/appConnections/types/app-options.ts b/frontend/src/hooks/api/appConnections/types/app-options.ts index 797e7a7c6..1f553f605 100644 --- a/frontend/src/hooks/api/appConnections/types/app-options.ts +++ b/frontend/src/hooks/api/appConnections/types/app-options.ts @@ -148,6 +148,10 @@ export type TChecklyConnectionOption = TAppConnectionOptionBase & { app: AppConnection.Checkly; }; +export type TChefConnectionOption = TAppConnectionOptionBase & { + app: AppConnection.Chef; +}; + export type TSupabaseConnectionOption = TAppConnectionOptionBase & { app: AppConnection.Supabase; }; @@ -168,6 +172,10 @@ export type TLaravelForgeConnectionOption = TAppConnectionOptionBase & { app: AppConnection.LaravelForge; }; +export type TNorthflankConnectionOption = TAppConnectionOptionBase & { + app: AppConnection.Northflank; +}; + export type TAzureAdCsConnectionOption = TAppConnectionOptionBase & { app: AppConnection.AzureADCS; }; @@ -213,9 +221,11 @@ export type TAppConnectionOption = | TSupabaseConnectionOption | TDigitalOceanConnectionOption | TNetlifyConnectionOption + | TNorthflankConnectionOption | TOktaConnectionOption | TAzureAdCsConnectionOption - | TLaravelForgeConnectionOption; + | TLaravelForgeConnectionOption + | TChefConnectionOption; export type TAppConnectionOptionMap = { [AppConnection.AWS]: TAwsConnectionOption; @@ -254,8 +264,10 @@ export type TAppConnectionOptionMap = { [AppConnection.Supabase]: TSupabaseConnectionOption; [AppConnection.DigitalOcean]: TDigitalOceanConnectionOption; [AppConnection.Netlify]: TNetlifyConnectionOption; + [AppConnection.Northflank]: TNorthflankConnectionOption; [AppConnection.Okta]: TOktaConnectionOption; [AppConnection.AzureADCS]: TAzureAdCsConnectionOption; [AppConnection.Redis]: TRedisConnectionOption; [AppConnection.LaravelForge]: TLaravelForgeConnectionOption; + [AppConnection.Chef]: TChefConnectionOption; }; diff --git a/frontend/src/hooks/api/appConnections/types/chef-connection.ts b/frontend/src/hooks/api/appConnections/types/chef-connection.ts new file mode 100644 index 000000000..371d42199 --- /dev/null +++ b/frontend/src/hooks/api/appConnections/types/chef-connection.ts @@ -0,0 +1,16 @@ +import { AppConnection } from "@app/hooks/api/appConnections/enums"; +import { TRootAppConnection } from "@app/hooks/api/appConnections/types/root-connection"; + +export enum ChefConnectionMethod { + UserKey = "user-key" +} + +export type TChefConnection = TRootAppConnection & { app: AppConnection.Chef } & { + method: ChefConnectionMethod.UserKey; + credentials: { + instanceUrl?: string; + orgName: string; + userName: string; + privateKey: string; + }; +}; diff --git a/frontend/src/hooks/api/appConnections/types/github-connection.ts b/frontend/src/hooks/api/appConnections/types/github-connection.ts index 27bed2dcb..595e5adbb 100644 --- a/frontend/src/hooks/api/appConnections/types/github-connection.ts +++ b/frontend/src/hooks/api/appConnections/types/github-connection.ts @@ -3,7 +3,8 @@ import { TRootAppConnection } from "@app/hooks/api/appConnections/types/root-con export enum GitHubConnectionMethod { App = "github-app", - OAuth = "oauth" + OAuth = "oauth", + Pat = "pat" } export type TGitHubConnection = TRootAppConnection & { app: AppConnection.GitHub } & ( @@ -24,4 +25,12 @@ export type TGitHubConnection = TRootAppConnection & { app: AppConnection.GitHub host?: string; }; } + | { + method: GitHubConnectionMethod.Pat; + credentials: { + personalAccessToken: string; + instanceType?: "cloud" | "server"; + host?: string; + }; + } ); diff --git a/frontend/src/hooks/api/appConnections/types/index.ts b/frontend/src/hooks/api/appConnections/types/index.ts index fd840d5de..3e62031b3 100644 --- a/frontend/src/hooks/api/appConnections/types/index.ts +++ b/frontend/src/hooks/api/appConnections/types/index.ts @@ -11,6 +11,7 @@ import { TAzureKeyVaultConnection } from "./azure-key-vault-connection"; import { TBitbucketConnection } from "./bitbucket-connection"; import { TCamundaConnection } from "./camunda-connection"; import { TChecklyConnection } from "./checkly-connection"; +import { TChefConnection } from "./chef-connection"; import { TCloudflareConnection } from "./cloudflare-connection"; import { TDatabricksConnection } from "./databricks-connection"; import { TDigitalOceanConnection } from "./digital-ocean"; @@ -27,6 +28,7 @@ import { TLdapConnection } from "./ldap-connection"; import { TMsSqlConnection } from "./mssql-connection"; import { TMySqlConnection } from "./mysql-connection"; import { TNetlifyConnection } from "./netlify-connection"; +import { TNorthflankConnection } from "./northflank-connection"; import { TOCIConnection } from "./oci-connection"; import { TOktaConnection } from "./okta-connection"; import { TOracleDBConnection } from "./oracledb-connection"; @@ -52,6 +54,7 @@ export * from "./azure-key-vault-connection"; export * from "./bitbucket-connection"; export * from "./camunda-connection"; export * from "./checkly-connection"; +export * from "./chef-connection"; export * from "./cloudflare-connection"; export * from "./databricks-connection"; export * from "./flyio-connection"; @@ -66,6 +69,8 @@ export * from "./laravel-forge-connection"; export * from "./ldap-connection"; export * from "./mssql-connection"; export * from "./mysql-connection"; +export * from "./netlify-connection"; +export * from "./northflank-connection"; export * from "./oci-connection"; export * from "./okta-connection"; export * from "./oracledb-connection"; @@ -119,8 +124,10 @@ export type TAppConnection = | TSupabaseConnection | TDigitalOceanConnection | TNetlifyConnection + | TNorthflankConnection | TOktaConnection - | TRedisConnection; + | TRedisConnection + | TChefConnection; export type TAvailableAppConnection = Pick; diff --git a/frontend/src/hooks/api/appConnections/types/northflank-connection.ts b/frontend/src/hooks/api/appConnections/types/northflank-connection.ts new file mode 100644 index 000000000..9e29693e4 --- /dev/null +++ b/frontend/src/hooks/api/appConnections/types/northflank-connection.ts @@ -0,0 +1,13 @@ +import { AppConnection } from "@app/hooks/api/appConnections/enums"; +import { TRootAppConnection } from "@app/hooks/api/appConnections/types/root-connection"; + +export enum NorthflankConnectionMethod { + ApiToken = "api-token" +} + +export type TNorthflankConnection = TRootAppConnection & { app: AppConnection.Northflank } & { + method: NorthflankConnectionMethod.ApiToken; + credentials: { + apiToken: string; + }; +}; diff --git a/frontend/src/hooks/api/ca/constants.tsx b/frontend/src/hooks/api/ca/constants.tsx index 778656da4..16a350dbd 100644 --- a/frontend/src/hooks/api/ca/constants.tsx +++ b/frontend/src/hooks/api/ca/constants.tsx @@ -53,6 +53,6 @@ export const getCaStatusBadgeVariant = (status: CaStatus | SshCaStatus | SshCert case CaStatus.DISABLED: return "danger"; default: - return "primary"; + return "warning"; } }; diff --git a/frontend/src/hooks/api/ca/mutations.tsx b/frontend/src/hooks/api/ca/mutations.tsx index fa422054c..49a53dce7 100644 --- a/frontend/src/hooks/api/ca/mutations.tsx +++ b/frontend/src/hooks/api/ca/mutations.tsx @@ -152,7 +152,7 @@ export const useCreateCertificate = () => { }); }; -export const useCreateCertificateV3 = () => { +export const useCreateCertificateV3 = (options?: { projectId?: string }) => { const queryClient = useQueryClient(); return useMutation({ mutationFn: async (body) => { @@ -167,6 +167,12 @@ export const useCreateCertificateV3 = () => { queryKey: projectKeys.forProjectCertificates(projectSlug) }); + if (options?.projectId) { + queryClient.invalidateQueries({ + queryKey: projectKeys.forProjectCertificates(options.projectId) + }); + } + queryClient.invalidateQueries({ queryKey: ["certificate-profiles"] }); diff --git a/frontend/src/hooks/api/certificateProfiles/index.ts b/frontend/src/hooks/api/certificateProfiles/index.ts index dc5c17efa..e12e066c4 100644 --- a/frontend/src/hooks/api/certificateProfiles/index.ts +++ b/frontend/src/hooks/api/certificateProfiles/index.ts @@ -8,7 +8,6 @@ export { useGetCertificateProfileById, useGetCertificateProfileBySlug, useGetProfileCertificates, - useGetProfileMetrics, useListCertificateProfiles } from "./queries"; export type * from "./types"; diff --git a/frontend/src/hooks/api/certificateProfiles/queries.tsx b/frontend/src/hooks/api/certificateProfiles/queries.tsx index abdc93ddb..19859b02f 100644 --- a/frontend/src/hooks/api/certificateProfiles/queries.tsx +++ b/frontend/src/hooks/api/certificateProfiles/queries.tsx @@ -4,7 +4,6 @@ import { apiRequest } from "@app/config/request"; import { TCertificateProfile, - TCertificateProfileMetrics, TCertificateProfileWithDetails, TGetCertificateProfileByIdDTO, TGetCertificateProfileBySlugDTO, @@ -20,7 +19,6 @@ export const certificateProfileKeys = { limit?: number; offset?: number; search?: string; - includeMetrics?: boolean; includeConfigs?: boolean; enrollmentType?: string; expiringDays?: number; @@ -51,10 +49,8 @@ export const useListCertificateProfiles = ({ limit = 20, offset = 0, search, - includeMetrics = false, includeConfigs = false, - enrollmentType, - expiringDays = 7 + enrollmentType }: TListCertificateProfilesDTO) => { return useQuery({ queryKey: certificateProfileKeys.list({ @@ -62,10 +58,8 @@ export const useListCertificateProfiles = ({ limit, offset, search, - includeMetrics, includeConfigs, - enrollmentType, - expiringDays + enrollmentType }), queryFn: async () => { const { data } = await apiRequest.get<{ @@ -77,10 +71,8 @@ export const useListCertificateProfiles = ({ limit, offset, search, - includeMetrics, includeConfigs, - enrollmentType, - expiringDays + enrollmentType } }); return data; @@ -145,18 +137,3 @@ export const useGetProfileCertificates = ({ enabled: Boolean(profileId) }); }; - -export const useGetProfileMetrics = ({ profileId, expiringDays = 7 }: TGetProfileMetricsDTO) => { - return useQuery({ - queryKey: certificateProfileKeys.getMetrics(profileId, { expiringDays }), - queryFn: async () => { - const { data } = await apiRequest.get<{ - metrics: TCertificateProfileMetrics; - }>(`/api/v1/pki/certificate-profiles/${profileId}/metrics`, { - params: { expiringDays } - }); - return data.metrics; - }, - enabled: Boolean(profileId) - }); -}; diff --git a/frontend/src/hooks/api/certificateProfiles/types.ts b/frontend/src/hooks/api/certificateProfiles/types.ts index a9b6b7060..f3584b12d 100644 --- a/frontend/src/hooks/api/certificateProfiles/types.ts +++ b/frontend/src/hooks/api/certificateProfiles/types.ts @@ -10,7 +10,6 @@ export type TCertificateProfile = { apiConfigId?: string; createdAt: string; updatedAt: string; - metrics?: TCertificateProfileMetrics; }; export type TCertificateProfileWithDetails = TCertificateProfile & { @@ -35,7 +34,7 @@ export type TCertificateProfileWithDetails = TCertificateProfile & { apiConfig?: { id: string; autoRenew: boolean; - autoRenewDays?: number; + renewBeforeDays?: number; }; }; @@ -53,7 +52,7 @@ export type TCreateCertificateProfileDTO = { }; apiConfig?: { autoRenew?: boolean; - autoRenewDays?: number; + renewBeforeDays?: number; }; }; @@ -68,7 +67,7 @@ export type TUpdateCertificateProfileDTO = { }; apiConfig?: { autoRenew?: boolean; - autoRenewDays?: number; + renewBeforeDays?: number; }; }; @@ -81,10 +80,8 @@ export type TListCertificateProfilesDTO = { limit?: number; offset?: number; search?: string; - includeMetrics?: boolean; includeConfigs?: boolean; enrollmentType?: "api" | "est"; - expiringDays?: number; }; export type TGetCertificateProfileByIdDTO = { @@ -96,15 +93,6 @@ export type TGetCertificateProfileBySlugDTO = { slug: string; }; -export type TCertificateProfileMetrics = { - profileId: string; - totalCertificates: number; - activeCertificates: number; - expiredCertificates: number; - expiringCertificates: number; - revokedCertificates: number; -}; - export type TProfileCertificate = { id: string; serialNumber: string; @@ -126,5 +114,4 @@ export type TGetProfileCertificatesDTO = { export type TGetProfileMetricsDTO = { profileId: string; - expiringDays?: number; }; diff --git a/frontend/src/hooks/api/certificateTemplates/types.ts b/frontend/src/hooks/api/certificateTemplates/types.ts index 373bbef2a..a6653cbec 100644 --- a/frontend/src/hooks/api/certificateTemplates/types.ts +++ b/frontend/src/hooks/api/certificateTemplates/types.ts @@ -42,8 +42,8 @@ export type TCreateCertificateTemplateDTO = { subjectAlternativeName: string; ttl: string; projectId: string; - keyUsages: CertKeyUsage[]; - extendedKeyUsages: CertExtendedKeyUsage[]; + keyUsages: string[]; + extendedKeyUsages: string[]; }; export type TUpdateCertificateTemplateDTO = { @@ -55,8 +55,8 @@ export type TUpdateCertificateTemplateDTO = { subjectAlternativeName?: string; ttl?: string; projectId: string; - keyUsages?: CertKeyUsage[]; - extendedKeyUsages?: CertExtendedKeyUsage[]; + keyUsages?: string[]; + extendedKeyUsages?: string[]; }; export type TDeleteCertificateTemplateDTO = { @@ -71,8 +71,8 @@ export type TCreateCertificateTemplateV2DTO = { subjectAlternativeName: string; ttl: string; projectId: string; - keyUsages: CertKeyUsage[]; - extendedKeyUsages: CertExtendedKeyUsage[]; + keyUsages: string[]; + extendedKeyUsages: string[]; }; export type TUpdateCertificateTemplateV2DTO = { @@ -83,8 +83,8 @@ export type TUpdateCertificateTemplateV2DTO = { subjectAlternativeName?: string; ttl?: string; projectId: string; - keyUsages?: CertKeyUsage[]; - extendedKeyUsages?: CertExtendedKeyUsage[]; + keyUsages?: string[]; + extendedKeyUsages?: string[]; }; export type TDeleteCertificateTemplateV2DTO = { diff --git a/frontend/src/hooks/api/certificates/index.tsx b/frontend/src/hooks/api/certificates/index.tsx index ddac04730..7d9c5df08 100644 --- a/frontend/src/hooks/api/certificates/index.tsx +++ b/frontend/src/hooks/api/certificates/index.tsx @@ -1,2 +1,9 @@ -export { useDeleteCert, useImportCertificate, useRevokeCert } from "./mutations"; +export { CertStatus } from "./enums"; +export { + useDeleteCert, + useImportCertificate, + useRenewCertificate, + useRevokeCert, + useUpdateRenewalConfig +} from "./mutations"; export { useGetCert, useGetCertBody } from "./queries"; diff --git a/frontend/src/hooks/api/certificates/mutations.tsx b/frontend/src/hooks/api/certificates/mutations.tsx index 388295b0a..eed1d9e5f 100644 --- a/frontend/src/hooks/api/certificates/mutations.tsx +++ b/frontend/src/hooks/api/certificates/mutations.tsx @@ -9,7 +9,10 @@ import { TDeleteCertDTO, TImportCertificateDTO, TImportCertificateResponse, - TRevokeCertDTO + TRenewCertificateDTO, + TRenewCertificateResponse, + TRevokeCertDTO, + TUpdateRenewalConfigDTO } from "./types"; export const useDeleteCert = () => { @@ -77,3 +80,57 @@ export const useImportCertificate = () => { } }); }; + +export const useRenewCertificate = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async ({ certificateId }) => { + const { data } = await apiRequest.post( + `/api/v3/certificates/${certificateId}/renew`, + {} + ); + return data; + }, + onSuccess: (data) => { + queryClient.invalidateQueries({ + queryKey: ["certificate-profiles", "list"] + }); + queryClient.invalidateQueries({ + queryKey: pkiSubscriberKeys.allPkiSubscriberCertificates() + }); + queryClient.invalidateQueries({ + queryKey: projectKeys.allProjectCertificates() + }); + if (data.projectId) { + queryClient.invalidateQueries({ + queryKey: projectKeys.forProjectCertificates(data.projectId) + }); + } + } + }); +}; + +export const useUpdateRenewalConfig = () => { + const queryClient = useQueryClient(); + return useMutation< + { message: string; renewBeforeDays?: number }, + object, + TUpdateRenewalConfigDTO + >({ + mutationFn: async ({ certificateId, renewBeforeDays, enableAutoRenewal }) => { + const { data } = await apiRequest.patch<{ message: string; renewBeforeDays?: number }>( + `/api/v3/certificates/${certificateId}/config`, + { renewBeforeDays, enableAutoRenewal } + ); + return data; + }, + onSuccess: (_, { projectSlug }) => { + queryClient.invalidateQueries({ + queryKey: projectKeys.forProjectCertificates(projectSlug) + }); + queryClient.invalidateQueries({ + queryKey: projectKeys.allProjectCertificates() + }); + } + }); +}; diff --git a/frontend/src/hooks/api/certificates/types.ts b/frontend/src/hooks/api/certificates/types.ts index 1ec3292a3..adfb815a6 100644 --- a/frontend/src/hooks/api/certificates/types.ts +++ b/frontend/src/hooks/api/certificates/types.ts @@ -4,15 +4,23 @@ export type TCertificate = { id: string; caId: string; certificateTemplateId?: string; + profileId?: string; status: CertStatus; friendlyName: string; commonName: string; subjectAltNames: string; + altNames?: string; serialNumber: string; notBefore: string; notAfter: string; keyUsages: CertKeyUsage[]; extendedKeyUsages: CertExtendedKeyUsage[]; + renewBeforeDays?: number; + renewedBy?: string; + renewedFromCertificateId?: string; + renewedByCertificateId?: string; + renewalError?: string; + hasPrivateKey?: boolean; }; export type TDeleteCertDTO = { @@ -43,3 +51,24 @@ export type TImportCertificateResponse = { privateKey: string; serialNumber: string; }; + +export type TRenewCertificateDTO = { + certificateId: string; +}; + +export type TRenewCertificateResponse = { + certificate: string; + issuingCaCertificate: string; + certificateChain: string; + privateKey?: string; + serialNumber: string; + certificateId: string; + projectId: string; +}; + +export type TUpdateRenewalConfigDTO = { + certificateId: string; + renewBeforeDays?: number; + enableAutoRenewal?: boolean; + projectSlug: string; +}; diff --git a/frontend/src/hooks/api/index.tsx b/frontend/src/hooks/api/index.tsx index e9e80feec..0216ae030 100644 --- a/frontend/src/hooks/api/index.tsx +++ b/frontend/src/hooks/api/index.tsx @@ -28,6 +28,7 @@ export * from "./organization"; export * from "./pkiAlerts"; export * from "./pkiCollections"; export * from "./pkiSubscriber"; +export * from "./pkiSyncs"; export * from "./projects"; export * from "./projectUserAdditionalPrivilege"; export * from "./rateLimit"; diff --git a/frontend/src/hooks/api/migration/queries.tsx b/frontend/src/hooks/api/migration/queries.tsx index e4ce6824d..198bf887b 100644 --- a/frontend/src/hooks/api/migration/queries.tsx +++ b/frontend/src/hooks/api/migration/queries.tsx @@ -5,7 +5,8 @@ import { apiRequest } from "@app/config/request"; import { ExternalMigrationProviders, TVaultExternalMigrationConfig, - VaultKubernetesAuthRole + VaultKubernetesAuthRole, + VaultKubernetesRole } from "./types"; export const externalMigrationQueryKeys = { @@ -31,6 +32,11 @@ export const externalMigrationQueryKeys = { "vault-kubernetes-auth-roles", namespace, mountPath + ], + vaultKubernetesRoles: (namespace?: string, mountPath?: string) => [ + "vault-kubernetes-roles", + namespace, + mountPath ] }; @@ -172,3 +178,30 @@ export const useGetVaultKubernetesAuthRoles = ( enabled: enabled && !!namespace && !!mountPath }); }; + +export const useGetVaultKubernetesRoles = ( + enabled = true, + namespace?: string, + mountPath?: string +) => { + return useQuery({ + queryKey: externalMigrationQueryKeys.vaultKubernetesRoles(namespace, mountPath), + queryFn: async () => { + if (!namespace || !mountPath) { + throw new Error("Both namespace and mountPath are required"); + } + + const { data } = await apiRequest.get<{ + roles: VaultKubernetesRole[]; + }>("/api/v3/external-migration/vault/kubernetes-roles", { + params: { + namespace, + mountPath + } + }); + + return data.roles; + }, + enabled: enabled && !!namespace && !!mountPath + }); +}; diff --git a/frontend/src/hooks/api/migration/types.ts b/frontend/src/hooks/api/migration/types.ts index f4303ea26..4c101548c 100644 --- a/frontend/src/hooks/api/migration/types.ts +++ b/frontend/src/hooks/api/migration/types.ts @@ -49,3 +49,24 @@ export type VaultKubernetesAuthRole = { disable_local_ca_jwt?: boolean; }; }; + +export type VaultKubernetesRole = { + name: string; + mountPath: string; + allowed_kubernetes_namespaces?: string[]; + allowed_kubernetes_namespace_selector?: string; + token_max_ttl?: number; + token_default_ttl?: number; + token_default_audiences?: string[]; + service_account_name?: string; + kubernetes_role_name?: string; + kubernetes_role_type?: string; + generated_role_rules?: string; + name_template?: string; + extra_annotations?: Record; + extra_labels?: Record; + config: { + kubernetes_host: string; + kubernetes_ca_cert?: string; + }; +}; diff --git a/frontend/src/hooks/api/organization/queries.tsx b/frontend/src/hooks/api/organization/queries.tsx index bbf73dd25..4340f9718 100644 --- a/frontend/src/hooks/api/organization/queries.tsx +++ b/frontend/src/hooks/api/organization/queries.tsx @@ -125,7 +125,8 @@ export const useUpdateOrg = () => { scannerProductEnabled, shareSecretsProductEnabled, maxSharedSecretLifetime, - maxSharedSecretViewLimit + maxSharedSecretViewLimit, + blockDuplicateSecretSyncDestinations }) => { return apiRequest.patch(`/api/v1/organization/${orgId}`, { name, @@ -146,7 +147,8 @@ export const useUpdateOrg = () => { scannerProductEnabled, shareSecretsProductEnabled, maxSharedSecretLifetime, - maxSharedSecretViewLimit + maxSharedSecretViewLimit, + blockDuplicateSecretSyncDestinations }); }, onSuccess: () => { diff --git a/frontend/src/hooks/api/organization/types.ts b/frontend/src/hooks/api/organization/types.ts index 867450830..b366277f1 100644 --- a/frontend/src/hooks/api/organization/types.ts +++ b/frontend/src/hooks/api/organization/types.ts @@ -29,6 +29,7 @@ export type Organization = { shareSecretsProductEnabled: boolean; maxSharedSecretLifetime: number; maxSharedSecretViewLimit: number | null; + blockDuplicateSecretSyncDestinations: boolean; }; export type UpdateOrgDTO = { @@ -52,6 +53,7 @@ export type UpdateOrgDTO = { shareSecretsProductEnabled?: boolean; maxSharedSecretViewLimit?: number | null; maxSharedSecretLifetime?: number; + blockDuplicateSecretSyncDestinations?: boolean; }; export type BillingDetails = { diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.ts index b6e5ce64c..0684f6073 100644 --- a/frontend/src/hooks/api/pam/enums.ts +++ b/frontend/src/hooks/api/pam/enums.ts @@ -1,5 +1,6 @@ export enum PamResourceType { Postgres = "postgres", + MySQL = "mysql", RDP = "rdp", SSH = "ssh", Kubernetes = "kubernetes" diff --git a/frontend/src/hooks/api/pam/maps.ts b/frontend/src/hooks/api/pam/maps.ts index a27507d7d..c240a12ad 100644 --- a/frontend/src/hooks/api/pam/maps.ts +++ b/frontend/src/hooks/api/pam/maps.ts @@ -5,6 +5,7 @@ export const PAM_RESOURCE_TYPE_MAP: Record< { name: string; image: string; size?: number } > = { [PamResourceType.Postgres]: { name: "PostgreSQL", image: "Postgres.png" }, + [PamResourceType.MySQL]: { name: "MySQL", image: "MySql.png" }, [PamResourceType.RDP]: { name: "RDP", image: "RDP.png" }, [PamResourceType.SSH]: { name: "SSH", image: "SSH.png" }, [PamResourceType.Kubernetes]: { name: "Kubernetes", image: "Kubernetes.png" } diff --git a/frontend/src/hooks/api/pam/types/base-account.ts b/frontend/src/hooks/api/pam/types/base-account.ts index 20cb7aa60..286c9389a 100644 --- a/frontend/src/hooks/api/pam/types/base-account.ts +++ b/frontend/src/hooks/api/pam/types/base-account.ts @@ -16,6 +16,8 @@ export interface TBasePamAccount { rotationEnabled: boolean; rotationIntervalSeconds?: number | null; lastRotatedAt?: string | null; + lastRotationMessage?: string | null; + rotationStatus?: string | null; createdAt: string; updatedAt: string; } diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.ts index 1b4acf6d4..1b1890cbd 100644 --- a/frontend/src/hooks/api/pam/types/index.ts +++ b/frontend/src/hooks/api/pam/types/index.ts @@ -1,11 +1,13 @@ import { PamResourceType, PamSessionStatus } from "../enums"; +import { TMySQLAccount, TMySQLResource } from "./mysql-resource"; import { TPostgresAccount, TPostgresResource } from "./postgres-resource"; +export * from "./mysql-resource"; export * from "./postgres-resource"; -export type TPamResource = TPostgresResource; +export type TPamResource = TPostgresResource | TMySQLResource; -export type TPamAccount = TPostgresAccount; +export type TPamAccount = TPostgresAccount | TMySQLAccount; export type TPamFolder = { id: string; diff --git a/frontend/src/hooks/api/pam/types/mysql-resource.ts b/frontend/src/hooks/api/pam/types/mysql-resource.ts new file mode 100644 index 000000000..f1a7c09c8 --- /dev/null +++ b/frontend/src/hooks/api/pam/types/mysql-resource.ts @@ -0,0 +1,14 @@ +import { PamResourceType } from "../enums"; +import { TBaseSqlConnectionDetails, TBaseSqlCredentials } from "./shared/sql-resource"; +import { TBasePamAccount } from "./base-account"; +import { TBasePamResource } from "./base-resource"; + +// Resources +export type TMySQLResource = TBasePamResource & { resourceType: PamResourceType.MySQL } & { + connectionDetails: TBaseSqlConnectionDetails; +}; + +// Accounts +export type TMySQLAccount = TBasePamAccount & { + credentials: TBaseSqlCredentials; +}; diff --git a/frontend/src/hooks/api/pkiSubscriber/constants.tsx b/frontend/src/hooks/api/pkiSubscriber/constants.tsx index 1de5e9ddb..768df9f52 100644 --- a/frontend/src/hooks/api/pkiSubscriber/constants.tsx +++ b/frontend/src/hooks/api/pkiSubscriber/constants.tsx @@ -15,6 +15,6 @@ export const getPkiSubscriberStatusBadgeVariant = (status: PkiSubscriberStatus) case PkiSubscriberStatus.DISABLED: return "danger"; default: - return "primary"; + return "warning"; } }; diff --git a/frontend/src/hooks/api/pkiSubscriber/types.ts b/frontend/src/hooks/api/pkiSubscriber/types.ts index 23ca6baf3..239d56148 100644 --- a/frontend/src/hooks/api/pkiSubscriber/types.ts +++ b/frontend/src/hooks/api/pkiSubscriber/types.ts @@ -47,8 +47,8 @@ export type TCreatePkiSubscriberDTO = { commonName: string; ttl?: string; subjectAlternativeNames: string[]; - keyUsages: CertKeyUsage[]; - extendedKeyUsages: CertExtendedKeyUsage[]; + keyUsages: string[]; + extendedKeyUsages: string[]; enableAutoRenewal?: boolean; autoRenewalPeriodInDays?: number; properties?: TPkiSubscriberProperties; @@ -63,8 +63,8 @@ export type TUpdatePkiSubscriberDTO = { status?: PkiSubscriberStatus; ttl?: string; subjectAlternativeNames?: string[]; - keyUsages?: CertKeyUsage[]; - extendedKeyUsages?: CertExtendedKeyUsage[]; + keyUsages?: string[]; + extendedKeyUsages?: string[]; enableAutoRenewal?: boolean; autoRenewalPeriodInDays?: number; properties?: TPkiSubscriberProperties; diff --git a/frontend/src/hooks/api/pkiSyncs/enums.ts b/frontend/src/hooks/api/pkiSyncs/enums.ts index 507f3336c..014516230 100644 --- a/frontend/src/hooks/api/pkiSyncs/enums.ts +++ b/frontend/src/hooks/api/pkiSyncs/enums.ts @@ -9,3 +9,10 @@ export enum PkiSyncStatus { Succeeded = "succeeded", Failed = "failed" } + +export enum CertificateSyncStatus { + Pending = "pending", + Syncing = "syncing", + Succeeded = "succeeded", + Failed = "failed" +} diff --git a/frontend/src/hooks/api/pkiSyncs/mutations.tsx b/frontend/src/hooks/api/pkiSyncs/mutations.tsx index 30cf18690..9aff79dd0 100644 --- a/frontend/src/hooks/api/pkiSyncs/mutations.tsx +++ b/frontend/src/hooks/api/pkiSyncs/mutations.tsx @@ -198,3 +198,47 @@ export const useTriggerPkiSyncRemoveCertificates = () => { } }); }; + +export const useAddCertificatesToPkiSync = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async ({ + pkiSyncId, + certificateIds + }: { + pkiSyncId: string; + certificateIds: string[]; + }) => { + const { data } = await apiRequest.post(`/api/v1/pki/syncs/${pkiSyncId}/certificates`, { + certificateIds + }); + + return data; + }, + onSuccess: (_, { pkiSyncId }) => { + queryClient.invalidateQueries({ queryKey: pkiSyncKeys.certificates(pkiSyncId) }); + } + }); +}; + +export const useRemoveCertificatesFromPkiSync = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async ({ + pkiSyncId, + certificateIds + }: { + pkiSyncId: string; + certificateIds: string[]; + }) => { + const { data } = await apiRequest.delete(`/api/v1/pki/syncs/${pkiSyncId}/certificates`, { + data: { certificateIds } + }); + + return data; + }, + onSuccess: (_, { pkiSyncId }) => { + queryClient.invalidateQueries({ queryKey: pkiSyncKeys.certificates(pkiSyncId) }); + } + }); +}; diff --git a/frontend/src/hooks/api/pkiSyncs/queries.tsx b/frontend/src/hooks/api/pkiSyncs/queries.tsx index d0db913bd..6e7aabc42 100644 --- a/frontend/src/hooks/api/pkiSyncs/queries.tsx +++ b/frontend/src/hooks/api/pkiSyncs/queries.tsx @@ -2,14 +2,25 @@ import { useQuery, UseQueryOptions } from "@tanstack/react-query"; import { apiRequest } from "@app/config/request"; import { PkiSync, TPkiSyncOption } from "@app/hooks/api/pkiSyncs"; -import { TListPkiSyncOptions, TListPkiSyncs, TPkiSync } from "@app/hooks/api/pkiSyncs/types"; +import { + TListPkiSyncOptions, + TListPkiSyncs, + TPkiSync, + TPkiSyncCertificate +} from "@app/hooks/api/pkiSyncs/types"; export const pkiSyncKeys = { all: ["pki-sync"] as const, options: () => [...pkiSyncKeys.all, "options"] as const, list: (projectId: string) => [...pkiSyncKeys.all, "list", projectId] as const, + listWithCertificate: (projectId: string, certificateId: string) => + [...pkiSyncKeys.all, "list", projectId, "with-certificate", certificateId] as const, byId: (syncId: string, projectId: string) => - [...pkiSyncKeys.all, "by-id", syncId, projectId] as const + [...pkiSyncKeys.all, "by-id", syncId, projectId] as const, + certificates: (syncId: string, pagination?: { offset: number; limit: number }) => + pagination + ? ([...pkiSyncKeys.all, "certificates", syncId, pagination] as const) + : ([...pkiSyncKeys.all, "certificates", syncId] as const) }; export const usePkiSyncOptions = ( @@ -41,9 +52,14 @@ export const usePkiSyncOption = (destination: PkiSync) => { return { syncOption, isPending }; }; -export const fetchPkiSyncsByProjectId = async (projectId: string) => { +export const fetchPkiSyncsByProjectId = async (projectId: string, certificateId?: string) => { + const params: { projectId: string; certificateId?: string } = { projectId }; + if (certificateId) { + params.certificateId = certificateId; + } + const { data } = await apiRequest.get("/api/v1/pki/syncs", { - params: { projectId } + params }); return data.pkiSyncs; @@ -63,6 +79,27 @@ export const useListPkiSyncs = ( }); }; +export const useListPkiSyncsWithCertificate = ( + projectId: string, + certificateId: string, + options?: Omit< + UseQueryOptions< + TPkiSync[], + unknown, + TPkiSync[], + ReturnType + >, + "queryKey" | "queryFn" + > +) => { + return useQuery({ + queryKey: pkiSyncKeys.listWithCertificate(projectId, certificateId), + queryFn: () => fetchPkiSyncsByProjectId(projectId, certificateId), + enabled: !!projectId && !!certificateId, + ...options + }); +}; + export const useGetPkiSync = ( { syncId, projectId }: { syncId: string; projectId: string }, options?: Omit< @@ -82,3 +119,33 @@ export const useGetPkiSync = ( ...options }); }; + +export const useListPkiSyncCertificates = ( + syncId: string, + pagination?: { offset?: number; limit?: number }, + options?: Omit< + UseQueryOptions< + { certificates: TPkiSyncCertificate[]; totalCount: number }, + unknown, + { certificates: TPkiSyncCertificate[]; totalCount: number }, + ReturnType + >, + "queryKey" | "queryFn" + > +) => { + const { offset = 0, limit = 20 } = pagination || {}; + + return useQuery({ + queryKey: pkiSyncKeys.certificates(syncId, { offset, limit }), + queryFn: async () => { + const { data } = await apiRequest.get(`/api/v1/pki/syncs/${syncId}/certificates`, { + params: { offset, limit } + }); + return { + certificates: data.certificates || [], + totalCount: data.totalCount || 0 + }; + }, + ...options + }); +}; diff --git a/frontend/src/hooks/api/pkiSyncs/types/common.ts b/frontend/src/hooks/api/pkiSyncs/types/common.ts index 8cd1aef96..77dc785ee 100644 --- a/frontend/src/hooks/api/pkiSyncs/types/common.ts +++ b/frontend/src/hooks/api/pkiSyncs/types/common.ts @@ -1,6 +1,6 @@ import { AppConnection } from "@app/hooks/api/appConnections/enums"; -import { PkiSyncStatus } from "../enums"; +import { CertificateSyncStatus, PkiSyncStatus } from "../enums"; export type RootPkiSyncOptions = { canImportCertificates: boolean; @@ -43,4 +43,26 @@ export type TRootPkiSync = { } | null; appConnectionName?: string; appConnectionApp?: string; + hasCertificate?: boolean; +}; + +export type TPkiSyncCertificate = { + id: string; + pkiSyncId: string; + certificateId: string; + syncStatus?: CertificateSyncStatus | null; + lastSyncMessage?: string | null; + lastSyncedAt?: string | null; + createdAt: string; + updatedAt: string; + certificateSerialNumber?: string; + certificateCommonName?: string; + certificateAltNames?: string; + certificateStatus?: string; + certificateNotBefore?: Date; + certificateNotAfter?: Date; + certificateRenewBeforeDays?: number; + certificateRenewalError?: string; + pkiSyncName?: string; + pkiSyncDestination?: string; }; diff --git a/frontend/src/hooks/api/pkiSyncs/types/index.ts b/frontend/src/hooks/api/pkiSyncs/types/index.ts index 899217f52..69ec3ae6f 100644 --- a/frontend/src/hooks/api/pkiSyncs/types/index.ts +++ b/frontend/src/hooks/api/pkiSyncs/types/index.ts @@ -33,7 +33,8 @@ type TCreatePkiSyncDTOBase = { certificateNameSchema?: string; }; isAutoSyncEnabled: boolean; - subscriberId?: string; + subscriberId?: string | null; + certificateIds?: string[]; projectId: string; }; diff --git a/frontend/src/hooks/api/projects/queries.tsx b/frontend/src/hooks/api/projects/queries.tsx index 0445d5984..1613e95a9 100644 --- a/frontend/src/hooks/api/projects/queries.tsx +++ b/frontend/src/hooks/api/projects/queries.tsx @@ -664,17 +664,26 @@ export const useListWorkspaceCas = ({ export const useListWorkspaceCertificates = ({ projectId, offset, - limit + limit, + friendlyName, + commonName, + forPkiSync }: { projectId: string; offset: number; limit: number; + friendlyName?: string; + commonName?: string; + forPkiSync?: boolean; }) => { return useQuery({ queryKey: projectKeys.specificProjectCertificates({ projectId, offset, - limit + limit, + friendlyName, + commonName, + forPkiSync }), queryFn: async () => { const params = new URLSearchParams({ @@ -682,6 +691,16 @@ export const useListWorkspaceCertificates = ({ limit: String(limit) }); + if (friendlyName) { + params.append("friendlyName", friendlyName); + } + if (commonName) { + params.append("commonName", commonName); + } + if (forPkiSync) { + params.append("forPkiSync", "true"); + } + const { data: { certificates, totalCount } } = await apiRequest.get<{ certificates: TCertificate[]; totalCount: number }>( @@ -693,7 +712,8 @@ export const useListWorkspaceCertificates = ({ return { certificates, totalCount }; }, - enabled: Boolean(projectId) + enabled: Boolean(projectId), + placeholderData: (previousData) => previousData }); }; diff --git a/frontend/src/hooks/api/projects/query-keys.tsx b/frontend/src/hooks/api/projects/query-keys.tsx index 51e3db71c..04f14f90d 100644 --- a/frontend/src/hooks/api/projects/query-keys.tsx +++ b/frontend/src/hooks/api/projects/query-keys.tsx @@ -39,12 +39,22 @@ export const projectKeys = { specificProjectCertificates: ({ projectId, offset, - limit + limit, + friendlyName, + commonName, + forPkiSync }: { projectId: string; offset: number; limit: number; - }) => [...projectKeys.forProjectCertificates(projectId), { offset, limit }] as const, + friendlyName?: string; + commonName?: string; + forPkiSync?: boolean; + }) => + [ + ...projectKeys.forProjectCertificates(projectId), + { offset, limit, friendlyName, commonName, forPkiSync } + ] as const, getProjectPkiAlerts: (projectId: string) => [{ projectId }, "project-pki-alerts"] as const, getProjectPkiSubscribers: (projectId: string) => [{ projectId }, "project-pki-subscribers"] as const, diff --git a/frontend/src/hooks/api/secretSyncs/enums.ts b/frontend/src/hooks/api/secretSyncs/enums.ts index efcc04b6d..be51805c8 100644 --- a/frontend/src/hooks/api/secretSyncs/enums.ts +++ b/frontend/src/hooks/api/secretSyncs/enums.ts @@ -28,8 +28,10 @@ export enum SecretSync { Checkly = "checkly", DigitalOceanAppPlatform = "digital-ocean-app-platform", Netlify = "netlify", + Northflank = "northflank", Bitbucket = "bitbucket", - LaravelForge = "laravel-forge" + LaravelForge = "laravel-forge", + Chef = "chef" } export enum SecretSyncStatus { diff --git a/frontend/src/hooks/api/secretSyncs/types/chef-sync.ts b/frontend/src/hooks/api/secretSyncs/types/chef-sync.ts new file mode 100644 index 000000000..6bd3d7ca2 --- /dev/null +++ b/frontend/src/hooks/api/secretSyncs/types/chef-sync.ts @@ -0,0 +1,16 @@ +import { AppConnection } from "@app/hooks/api/appConnections/enums"; +import { SecretSync } from "@app/hooks/api/secretSyncs"; +import { TRootSecretSync } from "@app/hooks/api/secretSyncs/types/root-sync"; + +export type TChefSync = TRootSecretSync & { + destination: SecretSync.Chef; + destinationConfig: { + dataBagName: string; + dataBagItemName: string; + }; + connection: { + app: AppConnection.Chef; + name: string; + id: string; + }; +}; diff --git a/frontend/src/hooks/api/secretSyncs/types/index.ts b/frontend/src/hooks/api/secretSyncs/types/index.ts index 3cab195bd..b4088728b 100644 --- a/frontend/src/hooks/api/secretSyncs/types/index.ts +++ b/frontend/src/hooks/api/secretSyncs/types/index.ts @@ -10,6 +10,7 @@ import { TAzureKeyVaultSync } from "./azure-key-vault-sync"; import { TBitbucketSync } from "./bitbucket-sync"; import { TCamundaSync } from "./camunda-sync"; import { TChecklySync } from "./checkly-sync"; +import { TChefSync } from "./chef-sync"; import { TCloudflarePagesSync } from "./cloudflare-pages-sync"; import { TCloudflareWorkersSync } from "./cloudflare-workers-sync"; import { TDatabricksSync } from "./databricks-sync"; @@ -23,6 +24,7 @@ import { THerokuSync } from "./heroku-sync"; import { THumanitecSync } from "./humanitec-sync"; import { TLaravelForgeSync } from "./laravel-forge-sync"; import { TNetlifySync } from "./netlify-sync"; +import { TNorthflankSync } from "./northflank-sync"; import { TOCIVaultSync } from "./oci-vault-sync"; import { TRailwaySync } from "./railway-sync"; import { TRenderSync } from "./render-sync"; @@ -70,8 +72,10 @@ export type TSecretSync = | TSupabaseSync | TDigitalOceanAppPlatformSync | TNetlifySync + | TNorthflankSync | TBitbucketSync - | TLaravelForgeSync; + | TLaravelForgeSync + | TChefSync; export type TListSecretSyncs = { secretSyncs: TSecretSync[] }; diff --git a/frontend/src/hooks/api/secretSyncs/types/northflank-sync.ts b/frontend/src/hooks/api/secretSyncs/types/northflank-sync.ts new file mode 100644 index 000000000..e1fff68fc --- /dev/null +++ b/frontend/src/hooks/api/secretSyncs/types/northflank-sync.ts @@ -0,0 +1,19 @@ +import { AppConnection } from "@app/hooks/api/appConnections/enums"; +import { SecretSync } from "@app/hooks/api/secretSyncs"; +import { TRootSecretSync } from "@app/hooks/api/secretSyncs/types/root-sync"; + +export type TNorthflankSync = TRootSecretSync & { + destination: SecretSync.Northflank; + destinationConfig: { + projectId: string; + projectName?: string; + secretGroupId: string; + secretGroupName?: string; + }; + + connection: { + app: AppConnection.Northflank; + name: string; + id: string; + }; +}; diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.ts index 98daf3ec1..80bea3db7 100644 --- a/frontend/src/hooks/api/subscriptions/types.ts +++ b/frontend/src/hooks/api/subscriptions/types.ts @@ -59,6 +59,7 @@ export type SubscriptionPlan = { enterpriseAppConnections: boolean; cardDeclined?: boolean; cardDeclinedReason?: string; + cardDeclinedDays?: number; machineIdentityAuthTemplates: boolean; pam: boolean; }; diff --git a/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx b/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx index f9ef51133..3fb909c9b 100644 --- a/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx +++ b/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx @@ -7,15 +7,12 @@ import { faCaretDown, faCheck, faChevronRight, - faCubes, faEnvelope, faExclamationTriangle, - faGlobe, faInfinity, faInfo, faInfoCircle, faPlus, - faServer, faSignOut, faToolbox, faUser, @@ -30,7 +27,6 @@ import { Mfa } from "@app/components/auth/Mfa"; import { createNotification } from "@app/components/notifications"; import SecurityClient from "@app/components/utilities/SecurityClient"; import { - Badge, BreadcrumbContainer, Button, DropdownMenu, @@ -46,6 +42,7 @@ import { TBreadcrumbFormat, Tooltip } from "@app/components/v2"; +import { Badge, InstanceIcon, OrgIcon, SubOrgIcon } from "@app/components/v3"; import { envConfig } from "@app/config/env"; import { useOrganization, useSubscription, useUser } from "@app/context"; import { isInfisicalCloud } from "@app/helpers/platform"; @@ -144,12 +141,10 @@ export const Navbar = () => { enabled: Boolean(subscription.subOrganization) }); - useEffect(() => { - if (subscription?.cardDeclined && !sessionStorage.getItem("paymentFailed")) { - sessionStorage.setItem("paymentFailed", "true"); - setShowCardDeclinedModal(true); - } - }, [subscription]); + const isCardDeclined = Boolean(subscription?.cardDeclined); + const isCardDeclinedMoreThan30Days = Boolean( + isCardDeclined && subscription?.cardDeclinedDays && subscription?.cardDeclinedDays >= 30 + ); const { data: orgs } = useGetOrganizations(); const navigate = useNavigate(); @@ -161,6 +156,23 @@ export const Navbar = () => { const [isOrgSelectOpen, setIsOrgSelectOpen] = useState(false); const location = useLocation(); + const isBillingPage = location.pathname === "/organization/billing"; + + const isModalIntrusive = Boolean(!isBillingPage && isCardDeclinedMoreThan30Days); + + useEffect(() => { + if (isModalIntrusive) { + setShowCardDeclinedModal(true); + sessionStorage.setItem("paymentFailed", "true"); + return; + } + + if (isCardDeclined && !sessionStorage.getItem("paymentFailed")) { + sessionStorage.setItem("paymentFailed", "true"); + setShowCardDeclinedModal(true); + } + }, [subscription, isBillingPage, isModalIntrusive]); + const matches = useRouterState({ select: (s) => s.matches.at(-1)?.context }); const breadcrumbs = matches && "breadcrumbs" in matches ? matches.breadcrumbs : undefined; @@ -271,9 +283,7 @@ export const Navbar = () => { to="/admin" className="group flex cursor-pointer items-center gap-2 text-sm text-white transition-all duration-100 hover:text-primary" > -
- -
+
Server Console

/

@@ -288,24 +298,31 @@ export const Navbar = () => {
{ - navigate({ - to: "/organization/projects", - search: (search) => ({ ...search, subOrganization: undefined }) - }); - if (isSubOrganization) { - await router.invalidate({ sync: true }).catch(() => null); - } - }} + asChild variant="org" + isTruncatable + // TODO(scott): either add badge size/style variant or create designated component for namespace/org nav bar className={twMerge( - "max-w-full min-w-0 cursor-pointer text-sm", + "gap-x-1.5 text-sm", (!isOrgScope || isSubOrganization) && - "bg-transparent text-mineshaft-200 hover:bg-transparent hover:underline" + "bg-transparent text-mineshaft-200 hover:!bg-transparent hover:underline [&>svg]:!text-org" )} > - -

{currentOrg?.name}

+
{getPlan(subscription)} @@ -443,19 +460,22 @@ export const Navbar = () => { <>

/

- - - -

{currentOrg.subOrganization.name}

-
- + svg]:!text-sub-org" + )} + > + + + {currentOrg.subOrganization.name} + +
{ )} {user.superAdmin && !location.pathname.startsWith("/admin") && ( - + Server Console )} @@ -684,7 +704,10 @@ export const Navbar = () => { - + !isModalIntrusive && setShowCardDeclinedModal(false)} + > @@ -692,6 +715,7 @@ export const Navbar = () => { Your payment could not be processed.
} + showCloseButton={!isModalIntrusive} >
@@ -712,15 +736,16 @@ export const Navbar = () => { > Update Payment Method + + {!isModalIntrusive && ( - + )}
diff --git a/frontend/src/layouts/PamLayout/PamLayout.tsx b/frontend/src/layouts/PamLayout/PamLayout.tsx index f34c29d0d..c6e7e067a 100644 --- a/frontend/src/layouts/PamLayout/PamLayout.tsx +++ b/frontend/src/layouts/PamLayout/PamLayout.tsx @@ -18,7 +18,11 @@ export const PamLayout = () => { useEffect(() => { if (subscription && !subscription.pam) { - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + description: + "Your current plan does not provide access to Infisical PAM. To unlock this feature, please upgrade to Infisical Enterprise plan.", + isEnterpriseFeature: true + }); } }, [subscription]); @@ -111,7 +115,8 @@ export const PamLayout = () => { onOpenChange={(isOpen) => { handlePopUpToggle("upgradePlan", isOpen); }} - text="You can use PAM if you switch to a paid Infisical plan." + text={popUp.upgradePlan.data?.description} + isEnterpriseFeature={popUp.upgradePlan.data?.isEnterpriseFeature} /> ); diff --git a/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx b/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx index 2c088c293..7aeb5e1fd 100644 --- a/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx +++ b/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx @@ -52,25 +52,7 @@ export const PkiManagerLayout = () => { projectId: currentProject.id }} > - {({ isActive }) => Policies} - - - {({ isActive }) => ( - - Certificates - - )} + {({ isActive }) => Certificates} {

{currentWorkspace?.name}

- - - - {currentWorkspace.type ? PROJECT_TYPE_NAME[currentWorkspace.type] : "Project"} - + + + {currentWorkspace.type ? PROJECT_TYPE_NAME[currentWorkspace.type] : "Project"} @@ -243,7 +240,7 @@ export const ProjectSelect = () => { handlePopUpToggle("upgradePlan", isOpen)} - text="You have exceeded the number of projects allowed on the free plan." + text="You’ve reached the maximum number of projects available on the Free plan. Upgrade to the Infisical Pro plan to create more projects." /> { {Boolean( secretApprovalReqCount?.open || accessApprovalRequestCount?.pendingCount ) && ( - + {pendingRequestsCount} )} diff --git a/frontend/src/layouts/SecretScanningLayout/SecretScanningLayout.tsx b/frontend/src/layouts/SecretScanningLayout/SecretScanningLayout.tsx index 227f7ae70..0a1fd14f4 100644 --- a/frontend/src/layouts/SecretScanningLayout/SecretScanningLayout.tsx +++ b/frontend/src/layouts/SecretScanningLayout/SecretScanningLayout.tsx @@ -1,7 +1,8 @@ import { Link, Outlet, useLocation } from "@tanstack/react-router"; import { motion } from "framer-motion"; -import { Badge, Tab, TabList, Tabs } from "@app/components/v2"; +import { Tab, TabList, Tabs } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { ProjectPermissionSub, useProject, @@ -66,7 +67,7 @@ export const SecretScanningLayout = () => { Findings {Boolean(unresolvedFindings) && ( - + {unresolvedFindings} )} diff --git a/frontend/src/pages/admin/AccessManagementPage/components/ServerAdminsTable.tsx b/frontend/src/pages/admin/AccessManagementPage/components/ServerAdminsTable.tsx index 5b34aa029..0ec5c9e58 100644 --- a/frontend/src/pages/admin/AccessManagementPage/components/ServerAdminsTable.tsx +++ b/frontend/src/pages/admin/AccessManagementPage/components/ServerAdminsTable.tsx @@ -7,16 +7,15 @@ import { faTrash, faUsers, faUserXmark, - faWarning, faXmark } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { AlertTriangleIcon } from "lucide-react"; import { twMerge } from "tailwind-merge"; import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal"; import { createNotification } from "@app/components/notifications"; import { - Badge, Button, Checkbox, DeleteActionModal, @@ -38,6 +37,7 @@ import { Tooltip, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { useSubscription, useUser } from "@app/context"; import { getUserTablePreference, @@ -432,7 +432,7 @@ export const ServerAdminsTable = () => { handlePopUpToggle("upgradePlan", isOpen)} - text={`${popUp?.upgradePlan?.data?.message} is only available on Infisical's Pro plan and above.`} + text="Your current plan does not allow removing server admins. To unlock this feature, please upgrade to Infisical Pro plan." /> { const email = user.email ?? user.username; return (
  • -
    +

    {user.firstName || user.lastName ? ( <> @@ -464,15 +464,10 @@ export const ServerAdminsTable = () => {

    {userId === user.id && ( -
    - - - Deleting Yourself - -
    + + + Deleting Yourself +
    )}
    diff --git a/frontend/src/pages/admin/CachingPage/components/CachingPageForm.tsx b/frontend/src/pages/admin/CachingPage/components/CachingPageForm.tsx index cac64d135..fbf956b7b 100644 --- a/frontend/src/pages/admin/CachingPage/components/CachingPageForm.tsx +++ b/frontend/src/pages/admin/CachingPage/components/CachingPageForm.tsx @@ -1,9 +1,9 @@ import { useEffect, useState } from "react"; -import { faRotate } from "@fortawesome/free-solid-svg-icons"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { RefreshCwIcon } from "lucide-react"; import { createNotification } from "@app/components/notifications"; -import { Badge, Button, DeleteActionModal } from "@app/components/v2"; +import { Button, DeleteActionModal } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { useUser } from "@app/context"; import { usePopUp } from "@app/hooks"; import { useInvalidateCache } from "@app/hooks/api"; @@ -62,11 +62,8 @@ export const CachingPageForm = () => {
    Secrets Cache {isInvalidating && ( - - + + Invalidating Cache )} diff --git a/frontend/src/pages/admin/EncryptionPage/components/EncryptionPageForm.tsx b/frontend/src/pages/admin/EncryptionPage/components/EncryptionPageForm.tsx index 69f4139a2..aa7fdbdbb 100644 --- a/frontend/src/pages/admin/EncryptionPage/components/EncryptionPageForm.tsx +++ b/frontend/src/pages/admin/EncryptionPage/components/EncryptionPageForm.tsx @@ -1,13 +1,13 @@ import { useCallback } from "react"; import { Controller, useForm } from "react-hook-form"; -import { faInfoCircle } from "@fortawesome/free-solid-svg-icons"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { zodResolver } from "@hookform/resolvers/zod"; +import { InfoIcon } from "lucide-react"; import { z } from "zod"; import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal"; import { createNotification } from "@app/components/notifications"; -import { Badge, Button, FormControl, Select, SelectItem, Tooltip } from "@app/components/v2"; +import { Button, FormControl, Select, SelectItem, Tooltip } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { useServerConfig, useSubscription } from "@app/context"; import { usePopUp } from "@app/hooks"; import { @@ -54,7 +54,8 @@ export const EncryptionPageForm = () => { if (!subscription.hsm) { handlePopUpOpen("upgradePlan", { - description: "Hardware Security Module's (HSM's), are only available on Enterprise plans." + isEnterpriseFeature: true, + text: "Your current plan does not include access to Hardware Security Module (HSM). To unlock this feature, please upgrade to Infisical Enterprise plan." }); return; } @@ -132,12 +133,10 @@ export const EncryptionPageForm = () => { {config.fipsEnabled && ( -
    - - FIPS Mode: Enabled - - -
    + + FIPS Mode: Enabled + +
    )}
    @@ -145,7 +144,8 @@ export const EncryptionPageForm = () => { handlePopUpToggle("upgradePlan", isOpen)} - text={(popUp.upgradePlan?.data as { description: string })?.description} + text={popUp.upgradePlan?.data?.text} + isEnterpriseFeature={popUp.upgradePlan?.data?.isEnterpriseFeature} /> ); diff --git a/frontend/src/pages/admin/EnvironmentPage/components/EnvironmentPageForm.tsx b/frontend/src/pages/admin/EnvironmentPage/components/EnvironmentPageForm.tsx index 59df496af..5f74593a3 100644 --- a/frontend/src/pages/admin/EnvironmentPage/components/EnvironmentPageForm.tsx +++ b/frontend/src/pages/admin/EnvironmentPage/components/EnvironmentPageForm.tsx @@ -1,8 +1,6 @@ import { useCallback, useEffect, useMemo, useState } from "react"; import { Control, Controller, useForm, useWatch } from "react-hook-form"; import { - faArrowUpRightFromSquare, - faBookOpen, faChevronRight, faExclamationTriangle, faMagnifyingGlass @@ -14,6 +12,7 @@ import { z } from "zod"; import { createNotification } from "@app/components/notifications"; import { Button, FormControl, Input, SecretInput, Tooltip } from "@app/components/v2"; import { HighlightText } from "@app/components/v2/HighlightText"; +import { DocumentationLinkBadge } from "@app/components/v3"; import { useGetEnvOverrides, useUpdateServerConfig } from "@app/hooks/api"; type TForm = Record; @@ -213,22 +212,9 @@ export const EnvironmentPageForm = () => { >
    -
    +

    Overrides

    - -
    - - Docs - -
    -
    +

    Override specific environment variables. After saving, it may take up to 5 minutes for diff --git a/frontend/src/pages/admin/ResourceOverviewPage/components/MachineIdentitiesTable.tsx b/frontend/src/pages/admin/ResourceOverviewPage/components/MachineIdentitiesTable.tsx index c493fe24d..9929d7500 100644 --- a/frontend/src/pages/admin/ResourceOverviewPage/components/MachineIdentitiesTable.tsx +++ b/frontend/src/pages/admin/ResourceOverviewPage/components/MachineIdentitiesTable.tsx @@ -7,10 +7,10 @@ import { faXmark } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { ServerCogIcon } from "lucide-react"; import { createNotification } from "@app/components/notifications"; import { - Badge, DeleteActionModal, DropdownMenu, DropdownMenuContent, @@ -29,6 +29,7 @@ import { THead, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { getUserTablePreference, PreferenceKey, @@ -110,7 +111,8 @@ const IdentityPanelTable = ({ {name} {isInstanceAdmin && ( - + + Server Admin )} diff --git a/frontend/src/pages/admin/ResourceOverviewPage/components/OrganizationsTable.tsx b/frontend/src/pages/admin/ResourceOverviewPage/components/OrganizationsTable.tsx index 9405505c8..fbb9462d0 100644 --- a/frontend/src/pages/admin/ResourceOverviewPage/components/OrganizationsTable.tsx +++ b/frontend/src/pages/admin/ResourceOverviewPage/components/OrganizationsTable.tsx @@ -3,7 +3,6 @@ import { faArrowDown, faArrowUp, faBuilding, - faCircleQuestion, faEllipsisV, faEnvelope, faEye, @@ -19,11 +18,11 @@ import { } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { useNavigate } from "@tanstack/react-router"; +import { CircleQuestionMarkIcon } from "lucide-react"; import { twMerge } from "tailwind-merge"; import { createNotification } from "@app/components/notifications"; import { - Badge, Button, DeleteActionModal, DropdownMenu, @@ -46,6 +45,7 @@ import { Tooltip, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { useUser } from "@app/context"; import { OrgMembershipRole } from "@app/helpers/roles"; import { @@ -295,15 +295,17 @@ const ViewMembersModalContent = ({ )}

    - - -

    {member.role.replace("-", " ")}

    - {Boolean(member.roleId) && ( - - - - )} -
    + +
    + + + {member.role.replace("-", " ")} + {Boolean(member.roleId) && } + + +
    diff --git a/frontend/src/pages/admin/ResourceOverviewPage/components/UserIdentitiesTable.tsx b/frontend/src/pages/admin/ResourceOverviewPage/components/UserIdentitiesTable.tsx index 7b5b2c3d5..d61d428af 100644 --- a/frontend/src/pages/admin/ResourceOverviewPage/components/UserIdentitiesTable.tsx +++ b/frontend/src/pages/admin/ResourceOverviewPage/components/UserIdentitiesTable.tsx @@ -9,16 +9,15 @@ import { faUsers, faUserShield, faUserXmark, - faWarning, faXmark } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { AlertTriangleIcon, UserCogIcon } from "lucide-react"; import { twMerge } from "tailwind-merge"; import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal"; import { createNotification } from "@app/components/notifications"; import { - Badge, Button, Checkbox, DeleteActionModal, @@ -41,6 +40,7 @@ import { Tooltip, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { useSubscription, useUser } from "@app/context"; import { getUserTablePreference, @@ -58,9 +58,6 @@ import { import { User } from "@app/hooks/api/users/types"; import { UsePopUpState } from "@app/hooks/usePopUp"; -const addServerAdminUpgradePlanMessage = "Granting another user Server Admin permissions"; -const removeServerAdminUpgradePlanMessage = "Removing Server Admin permissions from user"; - const UserPanelTable = ({ handlePopUpOpen, users, @@ -84,7 +81,7 @@ const UserPanelTable = ({ data?: { username: string; id: string; - message?: string; + text?: string; } ) => void; isPending: boolean; @@ -218,7 +215,8 @@ const UserPanelTable = ({ {name ?? Not Set}

    {superAdmin && ( - + + Server Admin )} @@ -259,7 +257,7 @@ const UserPanelTable = ({ handlePopUpOpen("upgradePlan", { username, id, - message: addServerAdminUpgradePlanMessage + text: "Your current plan does not allow setting additional server admins. To unlock this feature, please upgrade to Infisical Pro plan." }); return; } @@ -287,7 +285,7 @@ const UserPanelTable = ({ handlePopUpOpen("upgradePlan", { username, id, - message: removeServerAdminUpgradePlanMessage + text: "Your current plan does not allow removing server admins. To unlock this feature, please upgrade to Infisical Pro plan." }); return; } @@ -529,7 +527,7 @@ export const UserIdentitiesTable = () => { handlePopUpToggle("upgradePlan", isOpen)} - text={`${popUp?.upgradePlan?.data?.message} is only available on Infisical's Pro plan and above.`} + text={popUp.upgradePlan.data?.text} /> { const email = user.email ?? user.username; return (
  • -
    +

    {user.firstName || user.lastName ? ( <> @@ -561,15 +559,10 @@ export const UserIdentitiesTable = () => {

    {userId === user.id && ( -
    - - - Deleting Yourself - -
    + + + Deleting Yourself +
    )}
    diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaCertificatesSection/CaCertificatesTable.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaCertificatesSection/CaCertificatesTable.tsx index e9f65c4f6..c04b8525a 100644 --- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaCertificatesSection/CaCertificatesTable.tsx +++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaCertificatesSection/CaCertificatesTable.tsx @@ -7,7 +7,6 @@ import { twMerge } from "tailwind-merge"; import { ProjectPermissionCan } from "@app/components/permissions"; import { - Badge, DropdownMenu, DropdownMenuContent, DropdownMenuItem, @@ -22,6 +21,7 @@ import { THead, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context"; import { useGetCaCerts } from "@app/hooks/api"; @@ -60,7 +60,7 @@ export const CaCertificatesTable = ({ caId }: Props) => {
    CA Certificate {caCert.version} {isLastItem && ( - + Current )} diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx index e853dc801..1e264dadc 100644 --- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx +++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx @@ -1,7 +1,6 @@ import { faPlus } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal"; import { createNotification } from "@app/components/notifications"; import { ProjectPermissionCan } from "@app/components/permissions"; import { Button, DeleteActionModal } from "@app/components/v2"; @@ -24,8 +23,7 @@ export const CaSection = () => { "caCert", "installCaCert", "deleteCa", - "caStatus", // enable / disable - "upgradePlan" + "caStatus" // enable / disable ] as const); const onRemoveCaSubmit = async (caName: string) => { @@ -124,11 +122,6 @@ export const CaSection = () => { onUpdateCaStatus(popUp?.caStatus?.data as { caName: string; status: CaStatus }) } /> - handlePopUpToggle("upgradePlan", isOpen)} - text={(popUp.upgradePlan?.data as { description: string })?.description} - />
    ); }; diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaTable.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaTable.tsx index 81fce98c6..b98475bc9 100644 --- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaTable.tsx +++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaTable.tsx @@ -6,7 +6,6 @@ import { twMerge } from "tailwind-merge"; import { ProjectPermissionCan } from "@app/components/permissions"; import { - Badge, DropdownMenu, DropdownMenuContent, DropdownMenuItem, @@ -22,6 +21,7 @@ import { Tooltip, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context"; import { CaStatus, CaType, useListCasByTypeAndProjectId } from "@app/hooks/api"; import { @@ -34,15 +34,12 @@ import { UsePopUpState } from "@app/hooks/usePopUp"; type Props = { handlePopUpOpen: ( - popUpName: keyof UsePopUpState< - ["installCaCert", "caCert", "ca", "deleteCa", "caStatus", "upgradePlan"] - >, + popUpName: keyof UsePopUpState<["installCaCert", "caCert", "ca", "deleteCa", "caStatus"]>, data?: { caId?: string; caName?: string; dn?: string; status?: CaStatus; - description?: string; } ) => void; }; diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx index 121c32e5f..a1fdcfc1f 100644 --- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx +++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx @@ -124,7 +124,7 @@ type Props = { const caTypes = [ { label: "ACME", value: CaType.ACME }, - { label: "Azure AD Certificate Service", value: CaType.AZURE_AD_CS } + { label: "Active Directory Certificate Services (AD CS)", value: CaType.AZURE_AD_CS } ]; export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => { diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx index 14ce122ec..24bfb79ac 100644 --- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx +++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx @@ -1,7 +1,6 @@ import { faPlus } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal"; import { createNotification } from "@app/components/notifications"; import { ProjectPermissionCan } from "@app/components/permissions"; import { Button, DeleteActionModal } from "@app/components/v2"; @@ -20,8 +19,7 @@ export const ExternalCaSection = () => { const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([ "ca", "deleteCa", - "caStatus", // enable / disable - "upgradePlan" + "caStatus" // enable / disable ] as const); const onRemoveCaSubmit = async (caName: string, type: CaType) => { @@ -131,11 +129,6 @@ export const ExternalCaSection = () => { ) } /> - handlePopUpToggle("upgradePlan", isOpen)} - text={(popUp.upgradePlan?.data as { description: string })?.description} - />
    ); }; diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaTable.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaTable.tsx index a948473e8..379a091c7 100644 --- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaTable.tsx +++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaTable.tsx @@ -10,7 +10,6 @@ import { twMerge } from "tailwind-merge"; import { ProjectPermissionCan } from "@app/components/permissions"; import { - Badge, DropdownMenu, DropdownMenuContent, DropdownMenuItem, @@ -26,6 +25,7 @@ import { Tooltip, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context"; import { CaStatus, CaType, useListExternalCasByProjectId } from "@app/hooks/api"; import { caStatusToNameMap, getCaStatusBadgeVariant } from "@app/hooks/api/ca/constants"; @@ -33,12 +33,11 @@ import { UsePopUpState } from "@app/hooks/usePopUp"; type Props = { handlePopUpOpen: ( - popUpName: keyof UsePopUpState<["ca", "deleteCa", "caStatus", "upgradePlan"]>, + popUpName: keyof UsePopUpState<["ca", "deleteCa", "caStatus"]>, data?: { name?: string; type?: CaType; status?: CaStatus; - description?: string; } ) => void; }; diff --git a/frontend/src/pages/cert-manager/CertificatesPage/CertificatesPage.tsx b/frontend/src/pages/cert-manager/CertificatesPage/CertificatesPage.tsx deleted file mode 100644 index 984a3b398..000000000 --- a/frontend/src/pages/cert-manager/CertificatesPage/CertificatesPage.tsx +++ /dev/null @@ -1,61 +0,0 @@ -import { Helmet } from "react-helmet"; -import { useTranslation } from "react-i18next"; - -import { ProjectPermissionCan } from "@app/components/permissions"; -import { PageHeader } from "@app/components/v2"; -import { - ProjectPermissionActions, - ProjectPermissionCertificateActions, - ProjectPermissionSub, - useProjectPermission -} from "@app/context"; -import { ProjectType } from "@app/hooks/api/projects/types"; - -import { PkiCollectionSection } from "../AlertingPage/components"; -import { CertificatesSection } from "./components"; - -export const CertificatesPage = () => { - const { t } = useTranslation(); - const { permission } = useProjectPermission(); - - const canAccessPkiColl = permission.can( - ProjectPermissionActions.Read, - ProjectPermissionSub.PkiCollections - ); - const canAccessCerts = permission.can( - ProjectPermissionCertificateActions.Read, - ProjectPermissionSub.Certificates - ); - - return ( -
    - - {t("common.head-title", { title: "Certificates" })} - -
    - - {/* If both are false, the section does not render. This is to prevent duplicate banners. */} - {(canAccessCerts || canAccessPkiColl) && ( - - - - )} - - - -
    -
    - ); -}; diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx index dc0dffb0d..98ee930d5 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal.tsx @@ -122,11 +122,12 @@ export const CertificateIssuanceModal = ({ popUp, handlePopUpToggle, profileId } const { data: profilesData } = useListCertificateProfiles({ projectId: currentProject?.id || "", - includeMetrics: false, enrollmentType: "api" }); - const { mutateAsync: createCertificate } = useCreateCertificateV3(); + const { mutateAsync: createCertificate } = useCreateCertificateV3({ + projectId: currentProject?.id + }); const formResolver = useMemo(() => { return zodResolver(createSchema(shouldShowSubjectSection)); diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx new file mode 100644 index 000000000..db3e6c197 --- /dev/null +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManagePkiSyncsModal.tsx @@ -0,0 +1,296 @@ +import { useEffect, useMemo, useState } from "react"; +import { faPlus, faSearch } from "@fortawesome/free-solid-svg-icons"; +import { useNavigate } from "@tanstack/react-router"; + +import { createNotification } from "@app/components/notifications"; +import { + Button, + Checkbox, + EmptyState, + Input, + Modal, + ModalContent, + Pagination, + Table, + TableContainer, + TBody, + Td, + Th, + THead, + Tr +} from "@app/components/v2"; +import { ROUTE_PATHS } from "@app/const/routes"; +import { useProject } from "@app/context"; +import { + PkiSync, + useAddCertificatesToPkiSync, + useListPkiSyncsWithCertificate, + useRemoveCertificatesFromPkiSync +} from "@app/hooks/api/pkiSyncs"; +import { IntegrationsListPageTabs } from "@app/types/integrations"; + +type Props = { + popUp: { + isOpen: boolean; + data?: { + certificateId?: string; + commonName?: string; + }; + }; + handlePopUpToggle: (popUpName: "managePkiSyncs", state?: boolean) => void; +}; + +const PER_PAGE = 10; + +export const CertificateManagePkiSyncsModal = ({ popUp, handlePopUpToggle }: Props) => { + const [selectedSyncIds, setSelectedSyncIds] = useState>(new Set()); + const [initialSyncIds, setInitialSyncIds] = useState>(new Set()); + const [isSubmitting, setIsSubmitting] = useState(false); + const [currentPage, setCurrentPage] = useState(1); + const [searchTerm, setSearchTerm] = useState(""); + + const { currentProject } = useProject(); + const navigate = useNavigate(); + const { certificateId, commonName } = popUp.data || {}; + + const { data: pkiSyncs = [], isPending } = useListPkiSyncsWithCertificate( + currentProject?.id || "", + certificateId || "", + { + enabled: !!currentProject?.id && !!certificateId + } + ); + const addCertificatesToSync = useAddCertificatesToPkiSync(); + const removeCertificatesFromSync = useRemoveCertificatesFromPkiSync(); + + const filteredSyncs = useMemo(() => { + if (!searchTerm.trim()) return pkiSyncs; + + const searchLower = searchTerm.toLowerCase(); + return pkiSyncs.filter((sync) => sync.name.toLowerCase().includes(searchLower)); + }, [pkiSyncs, searchTerm]); + + const startIndex = (currentPage - 1) * PER_PAGE; + const endIndex = startIndex + PER_PAGE; + const paginatedSyncs = filteredSyncs.slice(startIndex, endIndex); + + useEffect(() => { + setCurrentPage(1); + }, [searchTerm]); + + const handleClose = () => { + handlePopUpToggle("managePkiSyncs", false); + setSelectedSyncIds(new Set()); + setInitialSyncIds(new Set()); + setSearchTerm(""); + setCurrentPage(1); + }; + + const handleNavigateToPkiSyncs = () => { + if (!currentProject?.id) return; + + navigate({ + to: ROUTE_PATHS.CertManager.IntegrationsListPage.path, + params: { + projectId: currentProject.id + }, + search: { + selectedTab: IntegrationsListPageTabs.PkiSyncs + } + }); + handleClose(); + }; + + const getDestinationDisplayName = (destination: string) => { + switch (destination) { + case PkiSync.AzureKeyVault: + return "Azure Key Vault"; + case PkiSync.AwsCertificateManager: + return "AWS Certificate Manager"; + default: + return destination; + } + }; + + useEffect(() => { + if (!certificateId || !pkiSyncs || pkiSyncs.length === 0) return; + + const currentSyncIds = new Set( + pkiSyncs.filter((sync) => sync.hasCertificate).map((sync) => sync.id) + ); + setSelectedSyncIds(currentSyncIds); + setInitialSyncIds(new Set(currentSyncIds)); + }, [certificateId, pkiSyncs]); + + const handleSyncToggle = (syncId: string) => { + setSelectedSyncIds((prev) => { + const newSet = new Set(prev); + if (newSet.has(syncId)) { + newSet.delete(syncId); + } else { + newSet.add(syncId); + } + return newSet; + }); + }; + + const handleSaveChanges = async () => { + if (!certificateId) return; + + try { + setIsSubmitting(true); + + const syncsToAdd = Array.from(selectedSyncIds).filter((id) => !initialSyncIds.has(id)); + const syncsToRemove = Array.from(initialSyncIds).filter((id) => !selectedSyncIds.has(id)); + + await Promise.all( + syncsToAdd.map((syncId) => + addCertificatesToSync.mutateAsync({ + pkiSyncId: syncId, + certificateIds: [certificateId] + }) + ) + ); + + await Promise.all( + syncsToRemove.map((syncId) => + removeCertificatesFromSync.mutateAsync({ + pkiSyncId: syncId, + certificateIds: [certificateId] + }) + ) + ); + + createNotification({ + text: `PKI sync settings updated for certificate "${commonName}"`, + type: "success" + }); + + handleClose(); + } catch (error) { + console.error(error); + createNotification({ + text: "Failed to update PKI sync settings", + type: "error" + }); + } finally { + setIsSubmitting(false); + } + }; + + return ( + + +
    + setSearchTerm(e.target.value)} + placeholder="Search PKI syncs by name..." + /> +
    +
    + {isPending && ( +
    +
    Loading PKI syncs...
    +
    + )} + {!isPending && pkiSyncs.length === 0 && ( + +
    + Create a{" "} + {" "} + first to manage certificate syncing. +
    +
    + )} + {!isPending && pkiSyncs.length > 0 && filteredSyncs.length === 0 && searchTerm && ( + +
    + No PKI syncs match your search criteria. Try a different search term. +
    +
    + )} + {!isPending && filteredSyncs.length > 0 && ( + + + + + + + + + + {paginatedSyncs.map((sync) => ( + handleSyncToggle(sync.id)} + > + + + + + ))} + +
    + NameDestination
    + handleSyncToggle(sync.id)} + id={`sync-${sync.id}`} + /> + +
    + {sync.name} +
    +
    +
    + {getDestinationDisplayName(sync.destination)} +
    +
    +
    + )} + {!isPending && filteredSyncs.length > PER_PAGE && ( +
    + {}} + /> +
    + )} +
    + +
    + + +
    +
    +
    + ); +}; diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManageRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManageRenewalModal.tsx new file mode 100644 index 000000000..d6199678a --- /dev/null +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateManageRenewalModal.tsx @@ -0,0 +1,265 @@ +import { useEffect, useMemo } from "react"; +import { Controller, useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { z } from "zod"; + +import { createNotification } from "@app/components/notifications"; +import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2"; +import { useProject } from "@app/context"; +import { useUpdateRenewalConfig } from "@app/hooks/api"; +import { useGetCertificateProfileById } from "@app/hooks/api/certificateProfiles"; +import { UsePopUpState } from "@app/hooks/usePopUp"; + +const DEFAULT_RENEWAL_BEFORE_DAYS = 20; +const MIN_RENEWAL_BEFORE_DAYS = 1; +const MAX_RENEWAL_BEFORE_DAYS = 30; + +const createFormSchema = (ttlDays: number, notAfter: string) => + z.object({ + renewBeforeDays: z + .number() + .min(MIN_RENEWAL_BEFORE_DAYS, `Renewal days must be at least ${MIN_RENEWAL_BEFORE_DAYS}`) + .max(MAX_RENEWAL_BEFORE_DAYS, `Renewal days cannot exceed ${MAX_RENEWAL_BEFORE_DAYS}`) + .refine( + (value) => value < ttlDays, + (value) => ({ + message: `Renewal days (${value}) must be less than certificate TTL (${ttlDays} days)` + }) + ) + .refine( + (value) => { + const expiryDate = new Date(notAfter); + const renewalDate = new Date(expiryDate.getTime() - value * 24 * 60 * 60 * 1000); + const tomorrow = new Date(); + tomorrow.setDate(tomorrow.getDate() + 1); + tomorrow.setHours(0, 0, 0, 0); + return renewalDate >= tomorrow; + }, + () => ({ + message: "Renewals can only be scheduled from tomorrow onwards." + }) + ) + }); + +type FormData = z.infer>; + +type Props = { + popUp: UsePopUpState<["manageRenewal"]>; + handlePopUpToggle: (popUpName: keyof UsePopUpState<["manageRenewal"]>, state?: boolean) => void; +}; + +const RenewalConfigForm = ({ + control, + errors, + onSubmit, + isLoading, + buttonText, + onCancel +}: { + control: any; + errors: { renewBeforeDays?: { message?: string } }; + onSubmit: (e?: React.BaseSyntheticEvent) => Promise; + isLoading: boolean; + buttonText: string; + onCancel: () => void; +}) => ( +
    + + ( + { + const value = parseInt(e.target.value, 10); + field.onChange(value); + }} + placeholder="Enter days before expiration" + /> + )} + /> + + +
    + + +
    +
    +); + +export const CertificateManageRenewalModal = ({ popUp, handlePopUpToggle }: Props) => { + const { currentProject } = useProject(); + const { mutateAsync: updateRenewalConfig, isPending: isUpdatingConfig } = + useUpdateRenewalConfig(); + + const certificateData = popUp.manageRenewal.data as { + certificateId: string; + commonName: string; + profileId: string; + renewBeforeDays?: number; + ttlDays?: number; + notAfter: string; + renewalError?: string; + renewedFromCertificateId?: string; + renewedByCertificateId?: string; + }; + + const { data: profileData } = useGetCertificateProfileById({ + profileId: certificateData?.profileId || "" + }); + + const defaultRenewalDays = useMemo(() => { + if (certificateData?.renewBeforeDays) { + return certificateData.renewBeforeDays; + } + if (profileData?.apiConfig?.renewBeforeDays) { + return profileData.apiConfig.renewBeforeDays; + } + return DEFAULT_RENEWAL_BEFORE_DAYS; + }, [certificateData?.renewBeforeDays, profileData?.apiConfig?.renewBeforeDays]); + + const isAutoRenewalEnabled = Boolean( + certificateData?.renewBeforeDays && certificateData.renewBeforeDays > 0 + ); + + const hasRenewalError = Boolean(certificateData?.renewalError); + + const formSchema = createFormSchema( + certificateData?.ttlDays || 365, + certificateData?.notAfter || "" + ); + + const { + control, + handleSubmit, + formState: { errors }, + reset + } = useForm({ + resolver: zodResolver(formSchema), + defaultValues: { + renewBeforeDays: defaultRenewalDays + } + }); + + useEffect(() => { + if (popUp.manageRenewal.isOpen) { + reset({ + renewBeforeDays: defaultRenewalDays + }); + } + }, [popUp.manageRenewal.isOpen, defaultRenewalDays, reset]); + + const onUpdateRenewal = async (data: FormData) => { + try { + if (!currentProject?.slug) { + createNotification({ + text: "Unable to update auto-renewal: Project not found. Please refresh the page and try again.", + type: "error" + }); + return; + } + + await updateRenewalConfig({ + certificateId: certificateData.certificateId, + renewBeforeDays: data.renewBeforeDays, + projectSlug: currentProject.slug + }); + + createNotification({ + text: isAutoRenewalEnabled + ? "Auto-renewal configuration updated successfully" + : "Auto-renewal enabled successfully", + type: "success" + }); + + handlePopUpToggle("manageRenewal", false); + } catch (err) { + console.error(err); + createNotification({ + text: isAutoRenewalEnabled + ? "Failed to update auto-renewal configuration. Please check your inputs and try again." + : "Failed to enable auto-renewal. Please check your inputs and try again.", + type: "error" + }); + } + }; + + const getModalTitle = () => { + if (hasRenewalError) { + return `Fix Auto-Renewal: ${certificateData?.commonName || ""}`; + } + if (isAutoRenewalEnabled) { + return `Manage Auto-Renewal for ${certificateData?.commonName || ""}`; + } + return `Enable Auto-Renewal for ${certificateData?.commonName || ""}`; + }; + + if (!certificateData) { + return null; + } + + return ( + { + handlePopUpToggle("manageRenewal", isOpen); + }} + > + + {hasRenewalError && ( +
    +
    +
    + ! +
    +
    +

    Automatic Renewal Failed

    +

    + The last automatic renewal attempt failed: {certificateData.renewalError} +

    +

    + You can reconfigure auto-renewal below or disable it completely. +

    +
    +
    +
    + )} + + {(!isAutoRenewalEnabled || hasRenewalError) && ( + handlePopUpToggle("manageRenewal", false)} + /> + )} + + {isAutoRenewalEnabled && !hasRenewalError && ( + handlePopUpToggle("manageRenewal", false)} + /> + )} +
    +
    + ); +}; diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalConfigModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalConfigModal.tsx new file mode 100644 index 000000000..c952f1e54 --- /dev/null +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalConfigModal.tsx @@ -0,0 +1,178 @@ +import { Controller, useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { z } from "zod"; + +import { createNotification } from "@app/components/notifications"; +import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2"; +import { useProject } from "@app/context"; +import { useUpdateRenewalConfig } from "@app/hooks/api"; +import { UsePopUpState } from "@app/hooks/usePopUp"; + +const createFormSchema = (ttlDays: number) => + z.object({ + renewBeforeDays: z + .number() + .min(1, "Renewal days must be at least 1") + .max(365, "Renewal days cannot exceed 365") + .refine( + (value) => value < ttlDays, + (value) => ({ + message: `Renewal days (${value}) must be less than certificate TTL (${ttlDays} days)` + }) + ) + }); + +type FormData = z.infer>; + +type Props = { + popUp: UsePopUpState<["configureRenewal"]>; + handlePopUpToggle: ( + popUpName: keyof UsePopUpState<["configureRenewal"]>, + state?: boolean + ) => void; +}; + +export const CertificateRenewalConfigModal = ({ popUp, handlePopUpToggle }: Props) => { + const { currentProject } = useProject(); + const { mutateAsync: updateRenewalConfig, isPending: isSubmitting } = useUpdateRenewalConfig(); + + const certificateData = popUp.configureRenewal.data as { + certificateId: string; + commonName: string; + profileId: string; + renewBeforeDays?: number; + ttlDays: number; + }; + + const formSchema = createFormSchema(certificateData.ttlDays); + + const { + control, + handleSubmit, + formState: { errors }, + watch + } = useForm({ + resolver: zodResolver(formSchema), + defaultValues: { + renewBeforeDays: certificateData?.renewBeforeDays || 1 + } + }); + + const renewBeforeDays = watch("renewBeforeDays"); + + const onSubmit = async (data: FormData) => { + try { + if (!currentProject?.slug) { + createNotification({ + text: "Project not found", + type: "error" + }); + return; + } + + await updateRenewalConfig({ + certificateId: certificateData.certificateId, + renewBeforeDays: data.renewBeforeDays, + projectSlug: currentProject.slug + }); + + createNotification({ + text: "Successfully updated auto-renewal configuration", + type: "success" + }); + + handlePopUpToggle("configureRenewal", false); + } catch (err) { + console.error(err); + createNotification({ + text: "Failed to update auto-renewal configuration", + type: "error" + }); + } + }; + + return ( + { + handlePopUpToggle("configureRenewal", isOpen); + }} + > + +
    +
    +

    + Configure when this certificate should be automatically renewed. The certificate will + be renewed when it has the specified number of days remaining before expiration. +

    + +
    +

    + Certificate TTL: {certificateData?.ttlDays} days +

    +

    + Current Setting:{" "} + {certificateData?.renewBeforeDays + ? `${certificateData.renewBeforeDays} days before expiration` + : "Disabled"} +

    +
    + + ( + + { + const value = parseInt(e.target.value, 10); + field.onChange(Number.isNaN(value) ? 0 : value); + }} + /> + + )} + /> + + {renewBeforeDays && certificateData?.ttlDays && ( +
    +

    + {renewBeforeDays >= certificateData.ttlDays + ? "⚠️ Renewal days must be less than certificate TTL" + : `✓ Certificate will be renewed ${renewBeforeDays} days before expiration`} +

    +
    + )} +
    + +
    + + +
    +
    +
    +
    + ); +}; diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalDisableModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalDisableModal.tsx new file mode 100644 index 000000000..613080cd7 --- /dev/null +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalDisableModal.tsx @@ -0,0 +1,94 @@ +import { createNotification } from "@app/components/notifications"; +import { Button, Modal, ModalContent } from "@app/components/v2"; +import { useProject } from "@app/context"; +import { useUpdateRenewalConfig } from "@app/hooks/api"; +import { UsePopUpState } from "@app/hooks/usePopUp"; + +type Props = { + popUp: UsePopUpState<["disableRenewal"]>; + handlePopUpToggle: (popUpName: keyof UsePopUpState<["disableRenewal"]>, state?: boolean) => void; +}; + +export const CertificateRenewalDisableModal = ({ popUp, handlePopUpToggle }: Props) => { + const { currentProject } = useProject(); + const { mutateAsync: updateRenewalConfig, isPending: isSubmitting } = useUpdateRenewalConfig(); + + const certificateData = popUp.disableRenewal.data as { + certificateId: string; + commonName: string; + }; + + const onDisableConfirm = async () => { + try { + if (!currentProject?.slug) { + createNotification({ + text: "Project not found", + type: "error" + }); + return; + } + + await updateRenewalConfig({ + certificateId: certificateData.certificateId, + projectSlug: currentProject.slug, + enableAutoRenewal: false + }); + + createNotification({ + text: "Successfully disabled auto-renewal", + type: "success" + }); + + handlePopUpToggle("disableRenewal", false); + } catch (err) { + console.error(err); + createNotification({ + text: "Failed to disable auto-renewal", + type: "error" + }); + } + }; + + return ( + { + handlePopUpToggle("disableRenewal", isOpen); + }} + > + +
    +

    + Are you sure you want to disable auto-renewal for this certificate? +

    +
    +

    + Warning: Once disabled, this certificate will not be automatically + renewed and may expire without notice. You can re-enable auto-renewal at any time. +

    +
    +
    + +
    + + +
    +
    +
    + ); +}; diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx new file mode 100644 index 000000000..0e2b1c17d --- /dev/null +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRenewalModal.tsx @@ -0,0 +1,80 @@ +import { faRedo } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; + +import { createNotification } from "@app/components/notifications"; +import { Button, Modal, ModalContent } from "@app/components/v2"; +import { useRenewCertificate } from "@app/hooks/api"; +import { UsePopUpState } from "@app/hooks/usePopUp"; + +type Props = { + popUp: UsePopUpState<["renewCertificate"]>; + handlePopUpToggle: ( + popUpName: keyof UsePopUpState<["renewCertificate"]>, + state?: boolean + ) => void; +}; + +export const CertificateRenewalModal = ({ popUp, handlePopUpToggle }: Props) => { + const { mutateAsync: renewCertificate, isPending: isRenewing } = useRenewCertificate(); + + const onRenewConfirm = async () => { + try { + const { certificateId } = popUp.renewCertificate.data as { certificateId: string }; + + await renewCertificate({ + certificateId + }); + + createNotification({ + text: "Certificate renewed successfully", + type: "success" + }); + + handlePopUpToggle("renewCertificate", false); + } catch (err) { + console.error(err); + } + }; + + const certificateData = popUp.renewCertificate.data as { + certificateId: string; + commonName: string; + profileId: string; + }; + + return ( + { + handlePopUpToggle("renewCertificate", isOpen); + }} + > + +
    +

    + Are you sure you want to renew this certificate now? +

    +
    + +
    + + +
    +
    +
    + ); +}; diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplateModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplateModal.tsx index 9d5d9355f..86f75f149 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplateModal.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplateModal.tsx @@ -172,10 +172,14 @@ export const CertificateTemplateModal = ({ popUp, handlePopUpToggle, caId }: Pro ttl, keyUsages: Object.entries(keyUsages) .filter(([, value]) => value) - .map(([key]) => key as CertKeyUsage), + .map(([key]) => + key === CertKeyUsage.CRL_SIGN + ? "cRLSign" + : key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()) + ), extendedKeyUsages: Object.entries(extendedKeyUsages) .filter(([, value]) => value) - .map(([key]) => key as CertExtendedKeyUsage) + .map(([key]) => key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())) }); createNotification({ @@ -193,10 +197,14 @@ export const CertificateTemplateModal = ({ popUp, handlePopUpToggle, caId }: Pro ttl, keyUsages: Object.entries(keyUsages) .filter(([, value]) => value) - .map(([key]) => key as CertKeyUsage), + .map(([key]) => + key === CertKeyUsage.CRL_SIGN + ? "cRLSign" + : key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()) + ), extendedKeyUsages: Object.entries(extendedKeyUsages) .filter(([, value]) => value) - .map(([key]) => key as CertExtendedKeyUsage) + .map(([key]) => key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())) }); createNotification({ diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesSection.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesSection.tsx index c4d25a6ad..4871eb5c1 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesSection.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesSection.tsx @@ -104,7 +104,8 @@ export const CertificateTemplatesSection = ({ caId }: Props) => { handlePopUpToggle("upgradePlan", isOpen)} - text="Managing template enrollment options for EST is only available on Infisical's Enterprise plan." + isEnterpriseFeature={popUp.upgradePlan.data?.isEnterpriseFeature} + text="Your current plan does not include access to managing template enrollment options for EST. To unlock this feature, please upgrade to Infisical Enterprise plan." />
  • ); diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesTable.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesTable.tsx index e7d137807..c36618309 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesTable.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesTable.tsx @@ -36,6 +36,7 @@ type Props = { data?: { id?: string; name?: string; + isEnterpriseFeature?: boolean; } ) => void; }; @@ -90,7 +91,9 @@ export const CertificateTemplatesTable = ({ handlePopUpOpen, caId }: Props) => { { if (!subscription?.pkiEst) { - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + isEnterpriseFeature: true + }); return; } diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx index bce21123b..4d7f57172 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx @@ -7,8 +7,7 @@ import { Button, DeleteActionModal } from "@app/components/v2"; import { ProjectPermissionCertificateActions, ProjectPermissionSub, - useProject, - useSubscription + useProject } from "@app/context"; import { useDeleteCert } from "@app/hooks/api"; import { usePopUp } from "@app/hooks/usePopUp"; @@ -16,16 +15,19 @@ import { usePopUp } from "@app/hooks/usePopUp"; import { CertificateCertModal } from "./CertificateCertModal"; import { CertificateImportModal } from "./CertificateImportModal"; import { CertificateIssuanceModal } from "./CertificateIssuanceModal"; +import { CertificateManagePkiSyncsModal } from "./CertificateManagePkiSyncsModal"; +import { CertificateManageRenewalModal } from "./CertificateManageRenewalModal"; import { CertificateModal } from "./CertificateModal"; +import { CertificateRenewalModal } from "./CertificateRenewalModal"; import { CertificateRevocationModal } from "./CertificateRevocationModal"; import { CertificatesTable } from "./CertificatesTable"; export const CertificatesSection = () => { const { currentProject } = useProject(); - const { subscription } = useSubscription(); const { mutateAsync: deleteCert } = useDeleteCert(); - const isLegacyTemplatesEnabled = subscription.pkiLegacyTemplates; + // TODO: Use subscription.pkiLegacyTemplates to block legacy templates creation + const isLegacyTemplatesEnabled = true; const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([ "certificateIssuance", @@ -33,7 +35,10 @@ export const CertificatesSection = () => { "certificateImport", "certificateCert", "deleteCertificate", - "revokeCertificate" + "revokeCertificate", + "manageRenewal", + "renewCertificate", + "managePkiSyncs" ] as const); const onRemoveCertificateSubmit = async (serialNumber: string) => { @@ -98,7 +103,13 @@ export const CertificatesSection = () => { )} + + + { + const expiryDate = new Date(notAfter); + const now = new Date(); + const oneDayFromNow = new Date(now.getTime() + 24 * 60 * 60 * 1000); + return expiryDate <= oneDayFromNow; +}; + type Props = { handlePopUpOpen: ( popUpName: keyof UsePopUpState< - ["certificate", "deleteCertificate", "revokeCertificate", "certificateCert"] + [ + "certificate", + "deleteCertificate", + "revokeCertificate", + "certificateCert", + "manageRenewal", + "renewCertificate", + "managePkiSyncs" + ] >, data?: { serialNumber?: string; commonName?: string; + certificateId?: string; + profileId?: string; + renewBeforeDays?: number; + ttlDays?: number; + notAfter?: string; + renewalError?: string; + renewedFromCertificateId?: string; + renewedByCertificateId?: string; } ) => void; }; @@ -69,10 +101,12 @@ export const CertificatesTable = ({ handlePopUpOpen }: Props) => { limit: perPage }); - // Fetch CA data to determine capabilities + const { mutateAsync: updateRenewalConfig } = useUpdateRenewalConfig(); + // TODO: Use subscription.pkiLegacyTemplates to block legacy templates creation + const isLegacyTemplatesEnabled = true; + const { data: caData } = useListCasByProjectId(currentProject?.id ?? ""); - // Create mapping from caId to CA type for capability checking const caCapabilityMap = useMemo(() => { if (!caData) return {}; @@ -83,26 +117,78 @@ export const CertificatesTable = ({ handlePopUpOpen }: Props) => { return map; }, [caData]); + const handleDisableAutoRenewal = async (certificateId: string, commonName: string) => { + try { + if (!currentProject?.slug) { + createNotification({ + text: "Unable to disable auto-renewal: Project not found. Please refresh the page and try again.", + type: "error" + }); + return; + } + + await updateRenewalConfig({ + certificateId, + projectSlug: currentProject.slug, + enableAutoRenewal: false + }); + + createNotification({ + text: `Auto-renewal disabled for ${commonName}`, + type: "success" + }); + } catch (err) { + console.error(err); + createNotification({ + text: "Failed to disable auto-renewal. Please try again or contact support if the issue persists.", + type: "error" + }); + } + }; + return ( - - - - - + + + + - {isPending && } + {isPending && } {!isPending && data?.certificates.map((certificate) => { const { variant, label } = getCertValidUntilBadgeDetails(certificate.notAfter); + + const isRevoked = certificate.status === CertStatus.REVOKED; + const isExpired = new Date(certificate.notAfter) < new Date(); + const isExpiringWithinDay = isExpiringWithinOneDay(certificate.notAfter); + const hasFailed = Boolean(certificate.renewalError); + const isAutoRenewalEnabled = Boolean( + certificate.renewBeforeDays && certificate.renewBeforeDays > 0 + ); + + const canShowAutoRenewalIcon = Boolean( + certificate.profileId && + certificate.hasPrivateKey !== false && + !certificate.renewedByCertificateId && + !isRevoked && + !isExpired && + !isExpiringWithinDay + ); + + // Still need originalDisplayName for other uses in the component + const { originalDisplayName } = getCertificateDisplayName(certificate, 64, "—"); + return ( - - + + - - {subscriberId ? ( - - ) : ( - - )} - - -
    Common NameStatusNot BeforeNot After + SAN / CNStatusNot BeforeNot After
    {certificate.commonName}
    + + {certificate.status === CertStatus.REVOKED ? ( Revoked @@ -120,7 +206,64 @@ export const CertificatesTable = ({ handlePopUpOpen }: Props) => { ? format(new Date(certificate.notAfter), "yyyy-MM-dd") : "-"} + +
    { + if (!canShowAutoRenewalIcon) return ""; + if (isAutoRenewalEnabled) return "opacity-100"; + return "opacity-0 group-hover:opacity-100"; + })()}`} + > + {canShowAutoRenewalIcon && ( + { + if (hasFailed && certificate.renewalError) { + return `Auto-renewal failed: ${certificate.renewalError}`; + } + if (isAutoRenewalEnabled) { + const expiryDate = new Date(certificate.notAfter); + const now = new Date(); + const daysUntilExpiry = Math.ceil( + (expiryDate.getTime() - now.getTime()) / (24 * 60 * 60 * 1000) + ); + const daysUntilRenewal = Math.max( + 0, + daysUntilExpiry - (certificate.renewBeforeDays || 0) + ); + return `Auto-renews in ${daysUntilRenewal}d`; + } + return "Set auto renewal"; + })()} + > + + + )} +
    @@ -151,31 +294,199 @@ export const CertificatesTable = ({ handlePopUpOpen }: Props) => { )} - - {(isAllowed) => ( - - handlePopUpOpen("certificate", { - serialNumber: certificate.serialNumber - }) - } - disabled={!isAllowed} - icon={} + {isLegacyTemplatesEnabled && ( + + {(isAllowed) => ( + + handlePopUpOpen("certificate", { + serialNumber: certificate.serialNumber + }) + } + disabled={!isAllowed} + icon={} + > + View Details + + )} + + )} + {/* Manage auto renewal option - not shown for failed renewals */} + {(() => { + const canManageRenewal = + certificate.profileId && + certificate.hasPrivateKey !== false && + !certificate.renewedByCertificateId && + !isRevoked && + !isExpired && + !hasFailed && + !isExpiringWithinDay; + + if (!canManageRenewal) return null; + + return ( + - View Details - + {(isAllowed) => { + return ( + { + const notAfterDate = new Date(certificate.notAfter); + const notBeforeDate = certificate.notBefore + ? new Date(certificate.notBefore) + : new Date( + notAfterDate.getTime() - 365 * 24 * 60 * 60 * 1000 + ); + const ttlDays = Math.max( + 1, + Math.ceil( + (notAfterDate.getTime() - notBeforeDate.getTime()) / + (24 * 60 * 60 * 1000) + ) + ); + handlePopUpOpen("manageRenewal", { + certificateId: certificate.id, + commonName: certificate.commonName, + profileId: certificate.profileId, + renewBeforeDays: certificate.renewBeforeDays, + ttlDays, + notAfter: certificate.notAfter, + renewalError: certificate.renewalError, + renewedFromCertificateId: + certificate.renewedFromCertificateId, + renewedByCertificateId: certificate.renewedByCertificateId + }); + }} + disabled={!isAllowed} + icon={} + > + {isAutoRenewalEnabled + ? "Manage auto renewal" + : "Enable auto renewal"} + + ); + }} + + ); + })()} + {/* Disable auto renewal option - only shown when auto renewal is active */} + {(() => { + const canDisableRenewal = + certificate.profileId && + certificate.hasPrivateKey !== false && + !certificate.renewedByCertificateId && + !isRevoked && + !isExpired && + !isExpiringWithinDay && + isAutoRenewalEnabled; + + if (!canDisableRenewal) return null; + + return ( + + {(isAllowed) => ( + { + await handleDisableAutoRenewal( + certificate.id, + certificate.commonName + ); + }} + disabled={!isAllowed} + icon={} + > + Disable auto renewal + + )} + + ); + })()} + {/* Manual renewal action for profile-issued certificates that are not revoked/expired (including failed ones) */} + {(() => { + const canRenew = + certificate.profileId && + certificate.hasPrivateKey !== false && + !certificate.renewedByCertificateId && + !isRevoked && + !isExpired; + + if (!canRenew) return null; + + return ( + + {(isAllowed) => ( + { + handlePopUpOpen("renewCertificate", { + certificateId: certificate.id, + commonName: certificate.commonName + }); + }} + disabled={!isAllowed} + icon={} + > + Renew Now + + )} + + ); + })()} + {/* PKI Sync management - only for active certificates that are not renewed */} + {certificate.status === CertStatus.ACTIVE && + !certificate.renewedByCertificateId && ( + + {(isAllowed) => ( + + handlePopUpOpen("managePkiSyncs", { + certificateId: certificate.id, + commonName: certificate.commonName + }) + } + disabled={!isAllowed} + icon={} + > + Manage PKI Syncs + + )} + )} - {/* Only show revoke button if CA supports revocation */} {(() => { const caType = caCapabilityMap[certificate.caId]; - // If caId not found in map, assume CA supports revocation to avoid hiding revoke option const supportsRevocation = !caType || caSupportsCapability(caType, CaCapability.REVOKE_CERTIFICATES); diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts index 93b408bbe..2ac7ec9ce 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.utils.ts @@ -5,13 +5,13 @@ export const getCertValidUntilBadgeDetails = (notAfter: string) => { const notAfterDate = new Date(notAfter).getTime(); const diffInMs = notAfterDate - currentDate; - let variant: "success" | "primary" | "danger" = "success"; + let variant: "success" | "warning" | "danger" = "success"; let label = "Healthy"; if (diffInMs > ms("60d")) { variant = "success"; } else if (diffInMs > ms("30d")) { - variant = "primary"; + variant = "warning"; } else { variant = "danger"; } diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateTemplate.ts b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateTemplate.ts index 871ad00a4..5499a2762 100644 --- a/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateTemplate.ts +++ b/frontend/src/pages/cert-manager/CertificatesPage/components/useCertificateTemplate.ts @@ -11,6 +11,26 @@ import { mapTemplateSignatureAlgorithmToApi } from "@app/pages/cert-manager/PoliciesPage/components/CertificateTemplatesV2Tab/shared/certificate-constants"; +const convertTemplateTtlToCertificateTtl = (templateTtl: string): string => { + const match = templateTtl.match(/^(\d+)([dmyh])$/); + if (!match) return templateTtl; + + const [, value, unit] = match; + const numValue = parseInt(value, 10); + + switch (unit) { + case "m": + return `${numValue * 30}d`; + case "y": + return `${numValue * 365}d`; + case "d": + case "h": + return templateTtl; + default: + return templateTtl; + } +}; + export type TemplateConstraints = { allowedKeyUsages: string[]; allowedExtendedKeyUsages: string[]; @@ -118,7 +138,7 @@ export const useCertificateTemplate = ( // Set TTL if available if (templateData.validity?.max) { - setValue("ttl", templateData.validity.max); + setValue("ttl", convertTemplateTtlToCertificateTtl(templateData.validity.max)); } // Handle SAN types diff --git a/frontend/src/pages/cert-manager/CertificatesPage/route.tsx b/frontend/src/pages/cert-manager/CertificatesPage/route.tsx deleted file mode 100644 index 68deb41b9..000000000 --- a/frontend/src/pages/cert-manager/CertificatesPage/route.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import { createFileRoute } from "@tanstack/react-router"; - -import { CertificatesPage } from "./CertificatesPage"; - -export const Route = createFileRoute( - "/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/certificates" -)({ - component: CertificatesPage, - beforeLoad: ({ context }) => { - return { - breadcrumbs: [ - ...context.breadcrumbs, - { - label: "Certificates" - } - ] - }; - } -}); diff --git a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncRow.tsx b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncRow.tsx index eb16166fc..0b2ce65c1 100644 --- a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncRow.tsx +++ b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncRow.tsx @@ -1,7 +1,6 @@ import { useCallback, useMemo } from "react"; import { subject } from "@casl/ability"; import { - faBan, faCalendarCheck, faCheck, faCopy, @@ -13,12 +12,12 @@ import { faToggleOff, faToggleOn, faTrash, - faTriangleExclamation, faXmark } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { useNavigate } from "@tanstack/react-router"; import { format } from "date-fns"; +import { BanIcon } from "lucide-react"; import { twMerge } from "tailwind-merge"; import { createNotification } from "@app/components/notifications"; @@ -29,7 +28,6 @@ import { PkiSyncStatusBadge } from "@app/components/pki-syncs"; import { - Badge, DropdownMenu, DropdownMenuContent, DropdownMenuItem, @@ -39,6 +37,7 @@ import { Tooltip, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { ROUTE_PATHS } from "@app/const/routes"; import { ProjectPermissionSub } from "@app/context"; import { ProjectPermissionPkiSyncActions } from "@app/context/ProjectPermissionContext/types"; @@ -47,7 +46,6 @@ import { useToggle } from "@app/hooks"; import { PkiSyncStatus, TPkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs"; import { PkiSyncDestinationCol } from "./PkiSyncDestinationCol"; -import { PkiSyncTableCell } from "./PkiSyncTableCell"; type Props = { pkiSync: TPkiSync; @@ -163,26 +161,6 @@ export const PkiSyncRow = ({

    {destinationDetails.name}

    - -
    - - - Source Deleted - -
    -
    -
    @@ -234,12 +212,10 @@ export const PkiSyncRow = ({ className="text-xs" content="Auto-Sync is disabled. Certificate changes in the PKI subscriber will not be automatically synced to the destination." > -
    - - - {!syncStatus && "Auto-Sync Disabled"} - -
    + + + {!syncStatus && "Auto-Sync Disabled"} + )} {syncOption?.canImportCertificates && } diff --git a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncsTable.tsx b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncsTable.tsx index ca4aa7473..178d07e0d 100644 --- a/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncsTable.tsx +++ b/frontend/src/pages/cert-manager/IntegrationsListPage/components/PkiSyncsTab/PkiSyncTable/PkiSyncsTable.tsx @@ -57,7 +57,6 @@ import { PkiSyncRow } from "./PkiSyncRow"; enum PkiSyncsOrderBy { Destination = "destination", - Source = "source", Name = "name", Status = "status" } @@ -160,14 +159,6 @@ export const PkiSyncsTable = ({ pkiSyncs }: Props) => { const [syncOne, syncTwo] = orderDirection === OrderByDirection.ASC ? [a, b] : [b, a]; switch (orderBy) { - case PkiSyncsOrderBy.Source: - return (syncOne.subscriber?.name ?? syncOne.subscriberId ?? "") - .toLowerCase() - .localeCompare( - syncTwo.subscriber?.name?.toLowerCase() ?? - syncTwo.subscriberId?.toLowerCase() ?? - "" - ); case PkiSyncsOrderBy.Destination: return getPkiSyncDestinationColValues(syncOne) .primaryText.toLowerCase() @@ -370,7 +361,7 @@ export const PkiSyncsTable = ({ pkiSyncs }: Props) => {
    - +
    Name {
    -
    - Source - handleSort(PkiSyncsOrderBy.Source)} - > - - -
    -
    +
    Destination {
    +
    Status { const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["addSync"] as const); - const { addSync, ...search } = useSearch({ + const { addSync, connectionId, connectionName, ...search } = useSearch({ from: ROUTE_PATHS.CertManager.IntegrationsListPage.id }); @@ -44,6 +46,42 @@ export const PkiSyncsTab = () => { navigateToBase(); }, [addSync, handlePopUpOpen, navigateToBase]); + useEffect(() => { + const storedFormData = localStorage.getItem("pkiSyncFormData"); + if (storedFormData && !popUp.addSync.isOpen) { + try { + const parsedData = JSON.parse(storedFormData); + if (connectionId && connectionName) { + const initialData = { + ...parsedData, + connection: { id: connectionId, name: connectionName } + }; + handlePopUpOpen("addSync", { destination: parsedData.destination, initialData }); + navigate({ + to: ROUTE_PATHS.CertManager.IntegrationsListPage.path, + params: { projectId: currentProject?.id }, + search: { selectedTab: IntegrationsListPageTabs.PkiSyncs }, + replace: true + }); + } else { + handlePopUpOpen("addSync", { destination: parsedData.destination }); + } + localStorage.removeItem("pkiSyncFormData"); + } catch (error) { + console.error("Failed to parse stored PKI sync form data:", error); + localStorage.removeItem("pkiSyncFormData"); + handlePopUpOpen("addSync"); + } + } + }, [ + handlePopUpOpen, + popUp.addSync.isOpen, + connectionId, + connectionName, + navigate, + currentProject?.id + ]); + const { data: pkiSyncs = [], isPending: isPkiSyncsPending } = useListPkiSyncs( currentProject?.id || "", { @@ -64,21 +102,10 @@ export const PkiSyncsTab = () => {
    -

    Certificate Syncs

    - -
    - - Docs - -
    -
    +
    +

    Certificate Syncs

    + +

    Use App Connections to sync certificates to third-party services. @@ -104,7 +131,8 @@ export const PkiSyncsTab = () => {

    handlePopUpToggle("addSync", isOpen)} /> diff --git a/frontend/src/pages/cert-manager/IntegrationsListPage/route.tsx b/frontend/src/pages/cert-manager/IntegrationsListPage/route.tsx index 0a0868a07..a996a23b5 100644 --- a/frontend/src/pages/cert-manager/IntegrationsListPage/route.tsx +++ b/frontend/src/pages/cert-manager/IntegrationsListPage/route.tsx @@ -9,7 +9,9 @@ import { IntegrationsListPage } from "./IntegrationsListPage"; const IntegrationsListPageQuerySchema = z.object({ selectedTab: z.nativeEnum(IntegrationsListPageTabs).optional(), - addSync: z.nativeEnum(PkiSync).optional() + addSync: z.nativeEnum(PkiSync).optional(), + connectionId: z.string().optional(), + connectionName: z.string().optional() }); export const Route = createFileRoute( diff --git a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx index b8235f488..063cab35d 100644 --- a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx +++ b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx @@ -59,9 +59,9 @@ export const PkiCollectionPage = () => { }); handlePopUpClose("deletePkiCollection"); navigate({ - to: "/projects/cert-management/$projectId/certificates", + to: "/projects/cert-management/$projectId/policies", params: { - projectId + projectId: params.projectId } }); } catch { @@ -77,9 +77,9 @@ export const PkiCollectionPage = () => { {data && (
    diff --git a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/components/AddPkiCollectionItemModal.tsx b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/components/AddPkiCollectionItemModal.tsx index 3bcc3dc31..1fd4d7d99 100644 --- a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/components/AddPkiCollectionItemModal.tsx +++ b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/components/AddPkiCollectionItemModal.tsx @@ -5,13 +5,9 @@ import { z } from "zod"; import { createNotification } from "@app/components/notifications"; import { Button, FormControl, Modal, ModalContent, Select, SelectItem } from "@app/components/v2"; import { useProject } from "@app/context"; -import { - CaStatus, - useAddItemToPkiCollection, - useListWorkspaceCas, - useListWorkspaceCertificates -} from "@app/hooks/api"; +import { CaStatus, useAddItemToPkiCollection, useListWorkspaceCas } from "@app/hooks/api"; import { PkiItemType, pkiItemTypeToNameMap } from "@app/hooks/api/pkiCollections/constants"; +import { useListWorkspaceCertificates } from "@app/hooks/api/projects"; import { UsePopUpState } from "@app/hooks/usePopUp"; const schema = z diff --git a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/routes.tsx b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/routes.tsx index 7fef38221..712f3dedf 100644 --- a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/routes.tsx +++ b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/routes.tsx @@ -13,7 +13,7 @@ export const Route = createFileRoute( { label: "Certificate Collections", link: linkOptions({ - to: "/projects/cert-management/$projectId/certificates", + to: "/projects/cert-management/$projectId/policies", params: { projectId: params.projectId } diff --git a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberCertificatesTable.tsx b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberCertificatesTable.tsx index d3533d71d..129af29d3 100644 --- a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberCertificatesTable.tsx +++ b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberCertificatesTable.tsx @@ -7,7 +7,6 @@ import { twMerge } from "tailwind-merge"; import { ProjectPermissionCan } from "@app/components/permissions"; import { - Badge, DropdownMenu, DropdownMenuContent, DropdownMenuItem, @@ -24,6 +23,7 @@ import { Tooltip, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { ProjectPermissionPkiSubscriberActions, ProjectPermissionSub, @@ -93,7 +93,7 @@ export const PkiSubscriberCertificatesTable = ({ subscriberName, handlePopUpOpen } if (daysUntilExpiry < 30) { - return Expiring Soon; + return Expiring Soon; } return Valid; diff --git a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx index 4bc427e48..52104ed1f 100644 --- a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx +++ b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx @@ -351,8 +351,14 @@ export const PkiSubscriberModal = ({ popUp, handlePopUpToggle }: Props) => { commonName, subjectAlternativeNames: subjectAlternativeNamesList, ttl, - keyUsages: keyUsagesList, - extendedKeyUsages: extendedKeyUsagesList, + keyUsages: keyUsagesList.map((key) => + key === CertKeyUsage.CRL_SIGN + ? "cRLSign" + : key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()) + ), + extendedKeyUsages: extendedKeyUsagesList.map((key) => + key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()) + ), enableAutoRenewal, autoRenewalPeriodInDays, properties: Object.keys(properties).length > 0 ? properties : undefined @@ -365,8 +371,14 @@ export const PkiSubscriberModal = ({ popUp, handlePopUpToggle }: Props) => { commonName, subjectAlternativeNames: subjectAlternativeNamesList, ttl, - keyUsages: keyUsagesList, - extendedKeyUsages: extendedKeyUsagesList, + keyUsages: keyUsagesList.map((key) => + key === CertKeyUsage.CRL_SIGN + ? "cRLSign" + : key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()) + ), + extendedKeyUsages: extendedKeyUsagesList.map((key) => + key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()) + ), enableAutoRenewal, autoRenewalPeriodInDays, properties: Object.keys(properties).length > 0 ? properties : undefined diff --git a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx index cb4b9ef39..8c9196dc9 100644 --- a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx +++ b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx @@ -7,8 +7,7 @@ import { Button, DeleteActionModal } from "@app/components/v2"; import { ProjectPermissionPkiSubscriberActions, ProjectPermissionSub, - useProject, - useSubscription + useProject } from "@app/context"; import { useDeletePkiSubscriber, useUpdatePkiSubscriber } from "@app/hooks/api"; import { PkiSubscriberStatus } from "@app/hooks/api/pkiSubscriber/types"; @@ -19,10 +18,10 @@ import { PkiSubscribersTable } from "./PkiSubscribersTable"; export const PkiSubscriberSection = () => { const { currentProject } = useProject(); - const { subscription } = useSubscription(); const projectId = currentProject.id; - const canCreateLegacySubscribers = subscription.pkiLegacyTemplates; + // TODO: Use subscription.pkiLegacyTemplates to block legacy templates creation + const canCreateLegacySubscribers = true; const { mutateAsync: deletePkiSubscriber } = useDeletePkiSubscriber(); const { mutateAsync: updatePkiSubscriber } = useUpdatePkiSubscriber(); diff --git a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscribersTable.tsx b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscribersTable.tsx index d28c2d3a2..89dfd5f02 100644 --- a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscribersTable.tsx +++ b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscribersTable.tsx @@ -11,7 +11,6 @@ import { twMerge } from "tailwind-merge"; import { ProjectPermissionCan } from "@app/components/permissions"; import { - Badge, DropdownMenu, DropdownMenuContent, DropdownMenuItem, @@ -27,6 +26,7 @@ import { Tooltip, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { ProjectPermissionPkiSubscriberActions, ProjectPermissionSub, diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx index 76cc0ec7b..b1b1b2836 100644 --- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/PkiSyncDetailsByIDPage.tsx @@ -18,10 +18,10 @@ import { IntegrationsListPageTabs } from "@app/types/integrations"; import { PkiSyncActionTriggers, PkiSyncAuditLogsSection, + PkiSyncCertificatesSection, PkiSyncDestinationSection, PkiSyncDetailsSection, - PkiSyncOptionsSection, - PkiSyncSourceSection + PkiSyncOptionsSection } from "./components"; const PageContent = () => { @@ -62,7 +62,6 @@ const PageContent = () => { const destinationDetails = PKI_SYNC_MAP[pkiSync.destination]; const handleEditDetails = () => handlePopUpOpen("editSync", PkiSyncEditFields.Details); - const handleEditSource = () => handlePopUpOpen("editSync", PkiSyncEditFields.Source); const handleEditOptions = () => handlePopUpOpen("editSync", PkiSyncEditFields.Options); const handleEditDestination = () => handlePopUpOpen("editSync", PkiSyncEditFields.Destination); @@ -103,7 +102,6 @@ const PageContent = () => {
    -
    @@ -111,6 +109,7 @@ const PageContent = () => { pkiSync={pkiSync} onEditDestination={handleEditDestination} /> +
    diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx index 462678280..bb8e9d02a 100644 --- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncActionTriggers.tsx @@ -1,7 +1,6 @@ import { useCallback } from "react"; import { subject } from "@casl/ability"; import { - faBan, faCheck, faCopy, faDownload, @@ -15,6 +14,7 @@ import { } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { useNavigate } from "@tanstack/react-router"; +import { BanIcon, RefreshCwIcon } from "lucide-react"; import { createNotification } from "@app/components/notifications"; import { ProjectPermissionCan } from "@app/components/permissions"; @@ -26,7 +26,6 @@ import { PkiSyncRemoveStatusBadge } from "@app/components/pki-syncs"; import { - Badge, Button, DropdownMenu, DropdownMenuContent, @@ -35,6 +34,7 @@ import { IconButton, Tooltip } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { ROUTE_PATHS } from "@app/const/routes"; import { ProjectPermissionSub } from "@app/context"; import { ProjectPermissionPkiSyncActions } from "@app/context/ProjectPermissionContext/types"; @@ -136,24 +136,19 @@ export const PkiSyncActionTriggers = ({ pkiSync }: Props) => { {syncOption?.canImportCertificates && } {pkiSync.isAutoSyncEnabled ? ( - - - Auto-Sync Enabled + + + Auto-Sync Enabled ) : ( -
    - - - Auto-Sync Disabled - -
    + + + Auto-Sync Disabled +
    )}
    diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncAuditLogsSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncAuditLogsSection.tsx index 0f9f4a90c..6ef633091 100644 --- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncAuditLogsSection.tsx +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncAuditLogsSection.tsx @@ -26,7 +26,7 @@ export const PkiSyncAuditLogsSection = ({ pkiSync }: Props) => { return (
    -

    Sync Logs

    +

    Sync Logs

    {subscription.auditLogs && (

    Displaying audit logs from the last {Math.min(auditLogsRetentionDays, 60)} days diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx new file mode 100644 index 000000000..aafff85cd --- /dev/null +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncCertificatesSection.tsx @@ -0,0 +1,328 @@ +import { useState } from "react"; +import { subject } from "@casl/ability"; +import { + faCertificate, + faClockRotateLeft, + faEdit, + faTrash +} from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; + +import { createNotification } from "@app/components/notifications"; +import { ProjectPermissionCan } from "@app/components/permissions"; +import { CertificateManagementModal } from "@app/components/pki-syncs/CertificateManagementModal"; +import { + CertificateDisplayName, + getCertificateDisplayName +} from "@app/components/utilities/certificateDisplayUtils"; +import { + DeleteActionModal, + EmptyState, + IconButton, + Pagination, + Table, + TableContainer, + TBody, + Td, + Th, + THead, + Tooltip, + Tr +} from "@app/components/v2"; +import { Badge } from "@app/components/v3"; +import { ProjectPermissionSub } from "@app/context"; +import { ProjectPermissionPkiSyncActions } from "@app/context/ProjectPermissionContext/types"; +import { useListPkiSyncCertificates, useRemoveCertificatesFromPkiSync } from "@app/hooks/api"; +import { CertificateSyncStatus, TPkiSync } from "@app/hooks/api/pkiSyncs"; + +type Props = { + pkiSync: TPkiSync; +}; + +const getSyncStatusVariant = (status?: CertificateSyncStatus | null) => { + if (status === CertificateSyncStatus.Succeeded) return "success"; + if (status === CertificateSyncStatus.Failed) return "danger"; + if (status === CertificateSyncStatus.Syncing) return "neutral"; + return "project"; +}; + +const getSyncStatusText = (status?: CertificateSyncStatus | null) => { + if (status === CertificateSyncStatus.Succeeded) return "Synced"; + if (status === CertificateSyncStatus.Failed) return "Failed"; + if (status === CertificateSyncStatus.Syncing) return "Syncing"; + if (status === CertificateSyncStatus.Pending) return "Pending"; + return "Unknown"; +}; + +const getCertificateStatusVariant = (isExpired: boolean, isRevoked: boolean) => { + if (isRevoked) return "danger"; + if (isExpired) return "danger"; + return "success"; +}; + +const getCertificateStatusText = (isExpired: boolean, isRevoked: boolean) => { + if (isRevoked) return "Revoked"; + if (isExpired) return "Expired"; + return "Active"; +}; + +export const PkiSyncCertificatesSection = ({ pkiSync }: Props) => { + const [isManageModalOpen, setIsManageModalOpen] = useState(false); + const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); + const [certificateToDelete, setCertificateToDelete] = useState<{ + id: string; + displayName: string; + } | null>(null); + const [currentPage, setCurrentPage] = useState(1); + const pageSize = 10; + + const { data, refetch: refetchSyncCertificates } = useListPkiSyncCertificates(pkiSync.id, { + offset: (currentPage - 1) * pageSize, + limit: pageSize + }); + const syncCertificates = data?.certificates || []; + const totalCount = data?.totalCount || 0; + const removeCertificatesFromSync = useRemoveCertificatesFromPkiSync(); + + const permissionSubject = subject(ProjectPermissionSub.PkiSyncs, { + subscriberId: pkiSync.subscriberId || "" + }); + + const handleRemoveCertificate = async (certificateId: string) => { + try { + await removeCertificatesFromSync.mutateAsync({ + pkiSyncId: pkiSync.id, + certificateIds: [certificateId] + }); + + await refetchSyncCertificates(); + + createNotification({ + text: "Certificate removed from sync", + type: "success" + }); + + setIsDeleteModalOpen(false); + setCertificateToDelete(null); + } catch { + createNotification({ + text: "Failed to remove certificate from sync", + type: "error" + }); + } + }; + + const handleDeleteClick = (certificateId: string, displayName: string) => { + setCertificateToDelete({ id: certificateId, displayName }); + setIsDeleteModalOpen(true); + }; + + const totalPages = Math.ceil(totalCount / pageSize); + + return ( +

    +
    +
    +

    Certificates

    + + {(isAllowed) => ( + setIsManageModalOpen(true)} + > + + + )} + +
    + +
    +
    + + + + + + + + + + + + + {syncCertificates.map((syncCert) => { + const isExpired = syncCert.certificateNotAfter + ? new Date(syncCert.certificateNotAfter) < new Date() + : false; + const isRevoked = syncCert.certificateStatus === "revoked"; + + // Calculate auto-renewal timeline + const hasAutoRenewal = Boolean( + syncCert.certificateRenewBeforeDays && + syncCert.certificateRenewBeforeDays > 0 && + !syncCert.certificateRenewalError && + syncCert.certificateNotAfter + ); + + const daysUntilRenewal = + hasAutoRenewal && syncCert.certificateNotAfter + ? (() => { + const expiryDate = new Date(syncCert.certificateNotAfter); + const renewalDate = new Date( + expiryDate.getTime() - + syncCert.certificateRenewBeforeDays! * 24 * 60 * 60 * 1000 + ); + const now = new Date(); + const diffInMs = renewalDate.getTime() - now.getTime(); + return Math.max(0, Math.ceil(diffInMs / (24 * 60 * 60 * 1000))); + })() + : null; + + const { originalDisplayName } = getCertificateDisplayName( + { + altNames: syncCert.certificateAltNames, + commonName: syncCert.certificateCommonName + }, + 34, + "Unknown" + ); + + return ( + + + + + + + + + ); + })} + +
    SAN / CNCertificate StatusSerial NumberSync StatusExpires At +
    + + + + {getCertificateStatusText(isExpired, isRevoked)} + + +
    + {(() => { + const serial = syncCert.certificateSerialNumber; + if (!serial || serial === "Unknown") return "Unknown"; + if (serial.length <= 8) return serial; + return `${serial.substring(0, 4)}...${serial.substring(serial.length - 4)}`; + })()} +
    +
    + {syncCert.lastSyncMessage && + syncCert.syncStatus === CertificateSyncStatus.Failed ? ( + + Failed + + ) : ( + + {getSyncStatusText(syncCert.syncStatus)} + + )} + + + {syncCert.certificateNotAfter + ? new Date(syncCert.certificateNotAfter).toLocaleDateString() + : "Unknown"} + + + {hasAutoRenewal && daysUntilRenewal !== null && ( + +
    + +
    +
    + )} + + {(isAllowed) => ( + + handleDeleteClick(syncCert.certificateId, originalDisplayName) + } + > + + + )} + +
    + {syncCertificates.length === 0 && ( + + )} +
    + {/* Pagination */} + {totalPages > 1 && ( +
    + setCurrentPage(page)} + onChangePerPage={() => {}} + /> +
    + )} +
    +
    +
    + + setIsManageModalOpen(false)} + onCertificatesUpdated={() => { + refetchSyncCertificates(); + }} + /> + + { + setIsDeleteModalOpen(false); + setCertificateToDelete(null); + }} + title="Remove Certificate from Sync" + subTitle={`Are you sure you want to remove "${certificateToDelete?.displayName}" from this PKI sync?`} + deleteKey="confirm" + onDeleteApproved={async () => { + if (certificateToDelete) { + await handleRemoveCertificate(certificateToDelete.id); + } + }} + buttonText="Remove Certificate" + /> +
    + ); +}; diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx index af16fbffd..1c6bb8a04 100644 --- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection.tsx @@ -11,12 +11,15 @@ import { ProjectPermissionPkiSyncActions } from "@app/context/ProjectPermissionC import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs"; import { PkiSync, TPkiSync } from "@app/hooks/api/pkiSyncs"; -import { AzureKeyVaultPkiSyncDestinationSection } from "./PkiSyncDestinationSection/index"; +import { + AwsCertificateManagerPkiSyncDestinationSection, + AzureKeyVaultPkiSyncDestinationSection +} from "./PkiSyncDestinationSection/index"; const GenericFieldLabel = ({ label, children }: { label: string; children: React.ReactNode }) => ( -
    - -
    {children}
    +
    +

    {label}

    +
    {children}
    ); @@ -32,6 +35,9 @@ export const PkiSyncDestinationSection = ({ pkiSync, onEditDestination }: Props) let DestinationComponents: ReactNode; switch (destination) { + case PkiSync.AwsCertificateManager: + DestinationComponents = ; + break; case PkiSync.AzureKeyVault: DestinationComponents = ; break; @@ -47,7 +53,7 @@ export const PkiSyncDestinationSection = ({ pkiSync, onEditDestination }: Props) return (
    -

    Destination Configuration

    +

    Destination Configuration

    {(isAllowed) => (
    -
    +
    {pkiSync.appConnectionName || "Default Connection"} diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/AwsCertificateManagerPkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/AwsCertificateManagerPkiSyncDestinationSection.tsx new file mode 100644 index 000000000..88ffbbb93 --- /dev/null +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/AwsCertificateManagerPkiSyncDestinationSection.tsx @@ -0,0 +1,21 @@ +import { TPkiSync } from "@app/hooks/api/pkiSyncs"; + +const GenericFieldLabel = ({ label, children }: { label: string; children: React.ReactNode }) => ( +
    +

    {label}

    +
    {children}
    +
    +); + +type Props = { + pkiSync: TPkiSync; +}; + +export const AwsCertificateManagerPkiSyncDestinationSection = ({ pkiSync }: Props) => { + const region = + pkiSync.destinationConfig && "region" in pkiSync.destinationConfig + ? pkiSync.destinationConfig.region + : undefined; + + return {region || "Not specified"}; +}; diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/AzureKeyVaultPkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/AzureKeyVaultPkiSyncDestinationSection.tsx index 7c1cc8b14..b9bc7462c 100644 --- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/AzureKeyVaultPkiSyncDestinationSection.tsx +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/AzureKeyVaultPkiSyncDestinationSection.tsx @@ -2,9 +2,9 @@ import { TAzureKeyVaultPkiSync } from "@app/hooks/api/pkiSyncs/types/azure-key-vault-sync"; const GenericFieldLabel = ({ label, children }: { label: string; children: React.ReactNode }) => ( -
    - -
    {children}
    +
    +

    {label}

    +
    {children}
    ); diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts index 5c8823388..4a1728f42 100644 --- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/index.ts @@ -1 +1,2 @@ +export { AwsCertificateManagerPkiSyncDestinationSection } from "./AwsCertificateManagerPkiSyncDestinationSection"; export { AzureKeyVaultPkiSyncDestinationSection } from "./AzureKeyVaultPkiSyncDestinationSection"; diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDetailsSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDetailsSection.tsx index 7514bab50..a3d95d5c3 100644 --- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDetailsSection.tsx +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDetailsSection.tsx @@ -21,9 +21,9 @@ const GenericFieldLabel = ({ children: React.ReactNode; labelClassName?: string; }) => ( -
    - -
    {children}
    +
    +

    {label}

    +
    {children}
    ); @@ -57,7 +57,7 @@ export const PkiSyncDetailsSection = ({ pkiSync, onEditDetails }: Props) => { return (
    -

    Details

    +

    Details

    {(isAllowed) => ( { )}
    -
    -
    - {name} - {description || "None"} - - {subscriber ? subscriber.name : "Subscriber deleted"} +
    + {name} + {description || "None"} + {subscriber && ( + {subscriber.name} + )} + {syncStatus && ( + + - {syncStatus && ( - - - - )} - {lastSyncedAt && ( - - {format(new Date(lastSyncedAt), "yyyy-MM-dd, h:mm aaa")} - - )} - {syncStatus === PkiSyncStatus.Failed && failureMessage && ( - -

    - {failureMessage} -

    -
    - )} -
    + )} + {lastSyncedAt && ( + + {format(new Date(lastSyncedAt), "yyyy-MM-dd, h:mm aaa")} + + )} + {syncStatus === PkiSyncStatus.Failed && failureMessage && ( + +

    {failureMessage}

    +
    + )}
    ); diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncOptionsSection/PkiSyncOptionsSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncOptionsSection/PkiSyncOptionsSection.tsx index 3af7bf189..e9a509ebb 100644 --- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncOptionsSection/PkiSyncOptionsSection.tsx +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncOptionsSection/PkiSyncOptionsSection.tsx @@ -3,12 +3,27 @@ import { faEdit } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { ProjectPermissionCan } from "@app/components/permissions"; -import { GenericFieldLabel } from "@app/components/secret-syncs"; -import { Badge, IconButton } from "@app/components/v2"; +import { IconButton } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { ProjectPermissionSub } from "@app/context"; import { ProjectPermissionPkiSyncActions } from "@app/context/ProjectPermissionContext/types"; import { TPkiSync } from "@app/hooks/api/pkiSyncs"; +const GenericFieldLabel = ({ + label, + children, + labelClassName +}: { + label: string; + children: React.ReactNode; + labelClassName?: string; +}) => ( +
    +

    {label}

    +
    {children}
    +
    +); + type Props = { pkiSync: TPkiSync; onEditOptions: VoidFunction; @@ -27,7 +42,7 @@ export const PkiSyncOptionsSection = ({ pkiSync, onEditOptions }: Props) => {
    -

    Sync Options

    +

    Sync Options

    {(isAllowed) => ( { )}
    -
    -
    - {/* Hidden for now - Import certificates functionality disabled +
    + {/* Hidden for now - Import certificates functionality disabled {canImportCertificates ? "Enabled" : "Disabled"} */} - - - {canRemoveCertificates ? "Enabled" : "Disabled"} - - -
    + + + {canRemoveCertificates ? "Enabled" : "Disabled"} + +
    diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncSourceSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncSourceSection.tsx index 5885795e2..c9dc041df 100644 --- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncSourceSection.tsx +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncSourceSection.tsx @@ -1,10 +1,12 @@ /* eslint-disable jsx-a11y/label-has-associated-control */ import { subject } from "@casl/ability"; -import { faEdit, faTriangleExclamation } from "@fortawesome/free-solid-svg-icons"; +import { faEdit } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { AlertTriangleIcon } from "lucide-react"; import { ProjectPermissionCan } from "@app/components/permissions"; -import { Badge, IconButton, Tooltip } from "@app/components/v2"; +import { IconButton, Tooltip } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { ProjectPermissionSub } from "@app/context"; import { ProjectPermissionPkiSyncActions } from "@app/context/ProjectPermissionContext/types"; import { TPkiSync } from "@app/hooks/api/pkiSyncs"; @@ -36,15 +38,10 @@ export const PkiSyncSourceSection = ({ pkiSync, onEditSource }: Props) => {
    {!subscriberId && ( -
    - - - Source Deleted - -
    + + + Source Deleted +
    )} diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts index 06fe5181e..55a877bff 100644 --- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts +++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/index.ts @@ -1,5 +1,6 @@ export { PkiSyncActionTriggers } from "./PkiSyncActionTriggers"; export { PkiSyncAuditLogsSection } from "./PkiSyncAuditLogsSection"; +export { PkiSyncCertificatesSection } from "./PkiSyncCertificatesSection"; export { PkiSyncDestinationSection } from "./PkiSyncDestinationSection"; export { PkiSyncDetailsSection } from "./PkiSyncDetailsSection"; export { PkiSyncOptionsSection } from "./PkiSyncOptionsSection"; diff --git a/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx b/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx index 440ebb481..558e29a2b 100644 --- a/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx +++ b/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx @@ -114,30 +114,29 @@ export const PkiTemplateListPage = () => { />
    - {subscription?.pkiLegacyTemplates && ( -
    -

    Templates

    -
    - - {(isAllowed) => ( - - )} - -
    + {/* TODO: Use subscription.pkiLegacyTemplates to block legacy templates creation */} +
    +

    Templates

    +
    + + {(isAllowed) => ( + + )} +
    - )} +
    @@ -203,7 +202,9 @@ export const PkiTemplateListPage = () => { onClick={(e) => { e.stopPropagation(); if (!subscription.pkiEst) { - handlePopUpOpen("estUpgradePlan"); + handlePopUpOpen("estUpgradePlan", { + isEnterpriseFeature: true + }); return; } handlePopUpOpen("enrollmentOptions", { @@ -295,7 +296,8 @@ export const PkiTemplateListPage = () => { handlePopUpToggle("estUpgradePlan", isOpen)} - text="You can only configure template enrollment methods if you switch to Infisical's Enterprise plan." + text="Your current plan does not include access to configuring template enrollment methods. To unlock this feature, please upgrade to Infisical Enterprise plan." + isEnterpriseFeature={popUp.estUpgradePlan.data?.isEnterpriseFeature} /> ); diff --git a/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx b/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx index 093a2fcc1..94cf66ff8 100644 --- a/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx +++ b/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx @@ -140,10 +140,14 @@ export const PkiTemplateForm = ({ certTemplate, handlePopUpToggle }: Props) => { ttl, keyUsages: Object.entries(keyUsages) .filter(([, value]) => value) - .map(([key]) => key as CertKeyUsage), + .map(([key]) => + key === CertKeyUsage.CRL_SIGN + ? "cRLSign" + : key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()) + ), extendedKeyUsages: Object.entries(extendedKeyUsages) .filter(([, value]) => value) - .map(([key]) => key as CertExtendedKeyUsage) + .map(([key]) => key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())) }); createNotification({ @@ -160,10 +164,14 @@ export const PkiTemplateForm = ({ certTemplate, handlePopUpToggle }: Props) => { ttl, keyUsages: Object.entries(keyUsages) .filter(([, value]) => value) - .map(([key]) => key as CertKeyUsage), + .map(([key]) => + key === CertKeyUsage.CRL_SIGN + ? "cRLSign" + : key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()) + ), extendedKeyUsages: Object.entries(extendedKeyUsages) .filter(([, value]) => value) - .map(([key]) => key as CertExtendedKeyUsage) + .map(([key]) => key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())) }); createNotification({ diff --git a/frontend/src/pages/cert-manager/PoliciesPage/PoliciesPage.tsx b/frontend/src/pages/cert-manager/PoliciesPage/PoliciesPage.tsx index f6bc792fe..5b2988775 100644 --- a/frontend/src/pages/cert-manager/PoliciesPage/PoliciesPage.tsx +++ b/frontend/src/pages/cert-manager/PoliciesPage/PoliciesPage.tsx @@ -2,17 +2,20 @@ import { useState } from "react"; import { Helmet } from "react-helmet"; import { useTranslation } from "react-i18next"; -import { ProjectPermissionCan } from "@app/components/permissions"; import { ContentLoader, PageHeader, Tab, TabList, TabPanel, Tabs } from "@app/components/v2"; -import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context"; +import { useProject } from "@app/context"; import { ProjectType } from "@app/hooks/api/projects/types"; import { CertificateProfilesTab } from "./components/CertificateProfilesTab"; +import { CertificatesTab } from "./components/CertificatesTab"; import { CertificateTemplatesV2Tab } from "./components/CertificateTemplatesV2Tab"; +import { PkiCollectionsTab } from "./components/PkiCollectionsTab"; enum TabSections { CertificateProfiles = "profiles", - CertificateTemplatesV2 = "templates-v2" + CertificateTemplatesV2 = "templates-v2", + Certificates = "certificates", + PkiCollections = "pki-collections" } export const PoliciesPage = () => { @@ -25,59 +28,54 @@ export const PoliciesPage = () => { } return ( - - {(isAllowed) => { - if (!isAllowed) { - return ( -
    -
    -

    You don't have permission to access certificate policies.

    -
    -
    - ); - } +
    + + {t("common.head-title", { title: "Certificate Management" })} + +
    + - return ( -
    - - {t("common.head-title", { title: "Certificate Policies" })} - -
    - + setActiveTab(value as TabSections)} + > + + + Certificate Profiles + + + Certificate Templates + + + Certificates + + + Certificate Collections + + - setActiveTab(value as TabSections)} - > - - - Certificate Profiles - - - Certificate Templates - - + + + - - - + + + - - - - -
    -
    - ); - }} - + + + + + + + + +
    +
    ); }; diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx index 3f7553f83..cbd6f9ada 100644 --- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx +++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx @@ -1,5 +1,7 @@ import { useEffect } from "react"; import { Controller, useForm } from "react-hook-form"; +import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; @@ -13,7 +15,8 @@ import { ModalContent, Select, SelectItem, - TextArea + TextArea, + Tooltip } from "@app/components/v2"; import { useProject } from "@app/context"; import { useListCasByProjectId } from "@app/hooks/api/ca/queries"; @@ -67,7 +70,7 @@ const createSchema = z apiConfig: z .object({ autoRenew: z.boolean().optional(), - autoRenewDays: z.number().min(1).max(365).optional() + renewBeforeDays: z.number().min(1).max(365).optional() }) .optional() }) @@ -115,7 +118,7 @@ const editSchema = z apiConfig: z .object({ autoRenew: z.boolean().optional(), - autoRenewDays: z.number().min(1).max(365).optional() + renewBeforeDays: z.number().min(1).max(365).optional() }) .optional() }) @@ -183,7 +186,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" } profile.enrollmentType === "api" ? { autoRenew: profile.apiConfig?.autoRenew || false, - autoRenewDays: profile.apiConfig?.autoRenewDays || 30 + renewBeforeDays: profile.apiConfig?.renewBeforeDays || 30 } : undefined } @@ -195,7 +198,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" } certificateTemplateId: "", apiConfig: { autoRenew: false, - autoRenewDays: 30 + renewBeforeDays: 30 } } }); @@ -225,7 +228,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" } profile.enrollmentType === "api" ? { autoRenew: profile.apiConfig?.autoRenew || false, - autoRenewDays: profile.apiConfig?.autoRenewDays || 30 + renewBeforeDays: profile.apiConfig?.renewBeforeDays || 30 } : undefined }); @@ -389,7 +392,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" } } else { setValue("apiConfig", { autoRenew: false, - autoRenewDays: 30 + renewBeforeDays: 30 }); setValue("estConfig", undefined); } @@ -415,7 +418,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" } name="enrollmentType" render={({ field: { onChange, ...field }, fieldState: { error } }) => ( ( - - Enable Auto-Renewal - +
    + + Enable Auto-Renewal By Default + + + + +
    )} /> @@ -548,10 +560,10 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
    ( diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileList.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileList.tsx index 2d6f601b6..b3fc0e22f 100644 --- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileList.tsx +++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileList.tsx @@ -29,8 +29,7 @@ export const ProfileList = ({ onEditProfile, onDeleteProfile }: Props) => { projectId: currentProject?.id || "", limit: 100, offset: 0, - includeConfigs: true, - includeMetrics: true + includeConfigs: true }); const profiles = data?.certificateProfiles || []; @@ -42,10 +41,9 @@ export const ProfileList = ({ onEditProfile, onDeleteProfile }: Props) => {
    - + - @@ -67,10 +65,9 @@ export const ProfileList = ({ onEditProfile, onDeleteProfile }: Props) => { - + - diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileRow.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileRow.tsx index 27a1e7cd1..e3bdea3c4 100644 --- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileRow.tsx +++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ProfileRow.tsx @@ -12,7 +12,6 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { createNotification } from "@app/components/notifications"; import { - Badge, DropdownMenu, DropdownMenuContent, DropdownMenuItem, @@ -21,6 +20,7 @@ import { Tooltip, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { useProjectPermission } from "@app/context"; import { ProjectPermissionActions, @@ -33,59 +33,6 @@ import { TCertificateProfile } from "@app/hooks/api/certificateProfiles"; import { useGetCertificateTemplateV2ById } from "@app/hooks/api/certificateTemplates/queries"; import { CertificateIssuanceModal } from "@app/pages/cert-manager/CertificatesPage/components/CertificateIssuanceModal"; -const MetricsBadges = ({ - metrics -}: { - metrics?: { - totalCertificates: number; - activeCertificates: number; - expiringCertificates: number; - expiredCertificates: number; - revokedCertificates: number; - }; -}) => { - if (!metrics) { - return ( - - No metrics - - ); - } - - if (metrics.totalCertificates === 0) { - return ( - - No certificates - - ); - } - - return ( - <> - {metrics.activeCertificates > 0 && ( - - {metrics.activeCertificates} active - - )} - {metrics.expiringCertificates > 0 && ( - - {metrics.expiringCertificates} expiring - - )} - {metrics.expiredCertificates > 0 && ( - - {metrics.expiredCertificates} expired - - )} - {metrics.revokedCertificates > 0 && ( - - {metrics.revokedCertificates} revoked - - )} - - ); -}; - interface Props { profile: TCertificateProfile; onEditProfile: (profile: TCertificateProfile) => void; @@ -134,8 +81,8 @@ export const ProfileRow = ({ profile, onEditProfile, onDeleteProfile }: Props) = const getEnrollmentTypeBadge = (enrollmentType: string) => { const config = { - api: { variant: "success" as const, label: "API" }, - est: { variant: "primary" as const, label: "EST" } + api: { variant: "ghost" as const, label: "API" }, + est: { variant: "ghost" as const, label: "EST" } } as const; const configKey = Object.keys(config).includes(enrollmentType) @@ -169,11 +116,6 @@ export const ProfileRow = ({ profile, onEditProfile, onDeleteProfile }: Props) = {templateData?.name || profile.certificateTemplateId} - diff --git a/frontend/src/pages/organization/SecretSharingPage/components/ShareSecret/ShareSecretsRow.tsx b/frontend/src/pages/organization/SecretSharingPage/components/ShareSecret/ShareSecretsRow.tsx index 2394253e7..d4b40723b 100644 --- a/frontend/src/pages/organization/SecretSharingPage/components/ShareSecret/ShareSecretsRow.tsx +++ b/frontend/src/pages/organization/SecretSharingPage/components/ShareSecret/ShareSecretsRow.tsx @@ -3,7 +3,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { format } from "date-fns"; import { IconButton, Td, Tooltip, Tr } from "@app/components/v2"; -import { Badge } from "@app/components/v2/Badge"; +import { Badge } from "@app/components/v3"; import { TSharedSecret } from "@app/hooks/api/secretSharing"; import { UsePopUpState } from "@app/hooks/usePopUp"; diff --git a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamTab.tsx b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamTab.tsx index f4f7932a4..d8dca7401 100644 --- a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamTab.tsx +++ b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamTab.tsx @@ -29,7 +29,9 @@ export const AuditLogStreamsTab = withPermission( + + + + + + + ); +}; diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx index 8b553e656..b9599be2d 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PamAccountForm.tsx @@ -8,6 +8,7 @@ import { import { DiscriminativePick } from "@app/types"; import { PamAccountHeader } from "../PamAccountHeader"; +import { MySQLAccountForm } from "./MySQLAccountForm"; import { PostgresAccountForm } from "./PostgresAccountForm"; type FormProps = { @@ -35,10 +36,7 @@ const CreateForm = ({ const createPamAccount = useCreatePamAccount(); const onSubmit = async ( - formData: DiscriminativePick< - TPamAccount, - "name" | "description" | "credentials" | "rotationEnabled" | "rotationIntervalSeconds" - > + formData: DiscriminativePick ) => { try { const account = await createPamAccount.mutateAsync({ @@ -72,6 +70,10 @@ const CreateForm = ({ resourceType={resourceType} /> ); + case PamResourceType.MySQL: + return ( + + ); default: throw new Error(`Unhandled resource: ${resourceType}`); } @@ -81,10 +83,7 @@ const UpdateForm = ({ account, onComplete }: UpdateFormProps) => { const updatePamAccount = useUpdatePamAccount(); const onSubmit = async ( - formData: DiscriminativePick< - TPamAccount, - "name" | "description" | "credentials" | "rotationEnabled" | "rotationIntervalSeconds" - > + formData: DiscriminativePick ) => { try { const updatedAccount = await updatePamAccount.mutateAsync({ @@ -110,6 +109,8 @@ const UpdateForm = ({ account, onComplete }: UpdateFormProps) => { switch (account.resource.resourceType) { case PamResourceType.Postgres: return ; + case PamResourceType.MySQL: + return ; default: throw new Error(`Unhandled resource: ${account.resource.resourceType}`); } diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PostgresAccountForm.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PostgresAccountForm.tsx index 3e5994344..e7d2d902b 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PostgresAccountForm.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountForm/PostgresAccountForm.tsx @@ -4,7 +4,12 @@ import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { Button, ModalClose } from "@app/components/v2"; -import { PamResourceType, TPostgresAccount, useGetPamResourceById } from "@app/hooks/api/pam"; +import { + PamResourceType, + TPostgresAccount, + TPostgresResource, + useGetPamResourceById +} from "@app/hooks/api/pam"; import { UNCHANGED_PASSWORD_SENTINEL } from "@app/hooks/api/pam/constants"; import { BaseSqlAccountSchema } from "./shared/sql-account-schemas"; @@ -56,7 +61,9 @@ export const PostgresAccountForm = ({ account, resourceId, resourceType, onSubmi if (account) { setRotationCredentialsConfigured(account.resource.rotationCredentialsConfigured); } else { - setRotationCredentialsConfigured(!!resource?.rotationAccountCredentials); + setRotationCredentialsConfigured( + !!(resource as TPostgresResource)?.rotationAccountCredentials + ); } }, [account, resource]); diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountRow.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountRow.tsx index 8e7507ac9..f9ce8f33b 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccountRow.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccountRow.tsx @@ -1,23 +1,21 @@ import { useCallback } from "react"; import { - faBoxOpen, faCheck, faCopy, faEdit, faEllipsisV, - faFolder, faRightToBracket, faRotate, faTrash } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { formatDistance } from "date-fns"; +import { FolderIcon, PackageOpenIcon } from "lucide-react"; import { twMerge } from "tailwind-merge"; import { createNotification } from "@app/components/notifications"; import { ProjectPermissionCan } from "@app/components/permissions"; import { - Badge, Button, DropdownMenu, DropdownMenuContent, @@ -29,6 +27,7 @@ import { Tr } from "@app/components/v2"; import { HighlightText } from "@app/components/v2/HighlightText"; +import { Badge } from "@app/components/v3"; import { ProjectPermissionSub } from "@app/context"; import { ProjectPermissionPamAccountActions } from "@app/context/ProjectPermissionContext/types"; import { useToggle } from "@app/hooks"; @@ -88,25 +87,31 @@ export const PamAccountRow = ({ - - + + {isFlatView && accountPath && ( - - + + )} {account.lastRotatedAt && ( - - - Rotated {formatDistance(new Date(), account.lastRotatedAt)} ago - + + + + Rotated {formatDistance(new Date(), account.lastRotatedAt)} ago + + )} diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamResourceOption.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamResourceOption.tsx index 06c04e019..278ac3a62 100644 --- a/frontend/src/pages/pam/PamAccountsPage/components/PamResourceOption.tsx +++ b/frontend/src/pages/pam/PamAccountsPage/components/PamResourceOption.tsx @@ -3,7 +3,7 @@ import { faCheckCircle } from "@fortawesome/free-regular-svg-icons"; import { faPlus } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { Badge } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { PAM_RESOURCE_TYPE_MAP, PamResourceType } from "@app/hooks/api/pam"; export const PamResourceOption = ({ @@ -27,7 +27,7 @@ export const PamResourceOption = ({ <>

    {children}

    - + {`${name} Promise; +}; + +const formSchema = genericResourceFieldsSchema.extend({ + resourceType: z.literal(PamResourceType.MySQL), + connectionDetails: BaseSqlResourceSchema.extend({ + database: z.string().trim().optional().default("") + }) +}); + +type FormData = z.infer; + +export const MySQLResourceForm = ({ resource, onSubmit }: Props) => { + const isUpdate = Boolean(resource); + const [selectedTabIndex, setSelectedTabIndex] = useState(0); + + const form = useForm({ + resolver: zodResolver(formSchema), + defaultValues: resource ?? { + resourceType: PamResourceType.MySQL, + connectionDetails: { + host: "", + port: 3306, + database: "", + sslEnabled: true, + sslRejectUnauthorized: true, + sslCertificate: undefined + } + } + }); + + const { + handleSubmit, + formState: { isSubmitting, isDirty } + } = form; + + return ( + +
    { + setSelectedTabIndex(0); + handleSubmit(onSubmit)(e); + }} + > + + +
    + + + + +
    + +
    + ); +}; diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PamResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PamResourceForm.tsx index 8cfdc8582..2bc54e7cd 100644 --- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PamResourceForm.tsx +++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PamResourceForm.tsx @@ -9,6 +9,7 @@ import { import { DiscriminativePick } from "@app/types"; import { PamResourceHeader } from "../PamResourceHeader"; +import { MySQLResourceForm } from "./MySQLResourceForm"; import { PostgresResourceForm } from "./PostgresResourceForm"; type FormProps = { @@ -57,6 +58,8 @@ const CreateForm = ({ resourceType, onComplete, projectId }: CreateFormProps) => switch (resourceType) { case PamResourceType.Postgres: return ; + case PamResourceType.MySQL: + return ; default: throw new Error(`Unhandled resource: ${resourceType}`); } @@ -92,8 +95,10 @@ const UpdateForm = ({ resource, onComplete }: UpdateFormProps) => { switch (resource.resourceType) { case PamResourceType.Postgres: return ; + case PamResourceType.MySQL: + return ; default: - throw new Error(`Unhandled resource: ${resource.resourceType}`); + throw new Error(`Unhandled resource: ${(resource as any).resourceType}`); } }; diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/shared/SqlResourceFields.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/shared/SqlResourceFields.tsx index 888b62984..c3f3982ec 100644 --- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/shared/SqlResourceFields.tsx +++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/shared/SqlResourceFields.tsx @@ -110,7 +110,7 @@ export const SqlResourceFields = ({ setSelectedTabIndex, selectedTabIndex }: Pro errorText={error?.message} isError={Boolean(error?.message)} className={sslEnabled ? "" : "opacity-50"} - label="SSL Certificate" + label="Trusted CA SSL Certificate" isOptional >
    NameEnrollment TypeEnrollment Method Issuing CA Certificate TemplateCertificates
    NameEnrollment TypeEnrollment Method Issuing CA Certificate TemplateCertificates
    -
    - -
    -
    diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatesTab/CertificatesTab.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatesTab/CertificatesTab.tsx new file mode 100644 index 000000000..caf9cdb2f --- /dev/null +++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatesTab/CertificatesTab.tsx @@ -0,0 +1,5 @@ +import { CertificatesSection } from "../../../CertificatesPage/components/CertificatesSection"; + +export const CertificatesTab = () => { + return ; +}; diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatesTab/index.ts b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatesTab/index.ts new file mode 100644 index 000000000..277134d56 --- /dev/null +++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificatesTab/index.ts @@ -0,0 +1 @@ +export { CertificatesTab } from "./CertificatesTab"; diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/PkiCollectionsTab/PkiCollectionsTab.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/PkiCollectionsTab/PkiCollectionsTab.tsx new file mode 100644 index 000000000..29bd82559 --- /dev/null +++ b/frontend/src/pages/cert-manager/PoliciesPage/components/PkiCollectionsTab/PkiCollectionsTab.tsx @@ -0,0 +1,5 @@ +import { PkiCollectionSection } from "../../../AlertingPage/components/PkiCollectionSection"; + +export const PkiCollectionsTab = () => { + return ; +}; diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/PkiCollectionsTab/index.ts b/frontend/src/pages/cert-manager/PoliciesPage/components/PkiCollectionsTab/index.ts new file mode 100644 index 000000000..4297b3d5e --- /dev/null +++ b/frontend/src/pages/cert-manager/PoliciesPage/components/PkiCollectionsTab/index.ts @@ -0,0 +1 @@ +export { PkiCollectionsTab } from "./PkiCollectionsTab"; diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/index.ts b/frontend/src/pages/cert-manager/PoliciesPage/components/index.ts index 62809f571..a9b24b1db 100644 --- a/frontend/src/pages/cert-manager/PoliciesPage/components/index.ts +++ b/frontend/src/pages/cert-manager/PoliciesPage/components/index.ts @@ -1,2 +1,4 @@ export { CertificateProfilesTab } from "./CertificateProfilesTab"; +export { CertificatesTab } from "./CertificatesTab"; export { CertificateTemplatesV2Tab } from "./CertificateTemplatesV2Tab"; +export { PkiCollectionsTab } from "./PkiCollectionsTab"; diff --git a/frontend/src/pages/kms/KmipPage/components/KmipClientTable.tsx b/frontend/src/pages/kms/KmipPage/components/KmipClientTable.tsx index 9ba85beef..e3cdafbc2 100644 --- a/frontend/src/pages/kms/KmipPage/components/KmipClientTable.tsx +++ b/frontend/src/pages/kms/KmipPage/components/KmipClientTable.tsx @@ -170,7 +170,9 @@ export const KmipClientTable = () => { leftIcon={} onClick={() => { if (subscription && !subscription.kmip) { - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + isEnterpriseFeature: true + }); return; } @@ -342,7 +344,8 @@ export const KmipClientTable = () => { handlePopUpToggle("upgradePlan", isOpen)} - text="KMIP requires an enterprise plan." + text="Your current plan does not include access to KMIP. To unlock this feature, please upgrade to Infisical Enterprise plan." + isEnterpriseFeature={popUp.upgradePlan.data?.isEnterpriseFeature} /> diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx index bf721edfb..a6675ea88 100644 --- a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx +++ b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx @@ -23,7 +23,6 @@ import { motion } from "framer-motion"; import { createNotification } from "@app/components/notifications"; import { ProjectPermissionCan } from "@app/components/permissions"; import { - Badge, Button, DropdownMenu, DropdownMenuContent, @@ -44,7 +43,7 @@ import { Tooltip, Tr } from "@app/components/v2"; -import { BadgeProps } from "@app/components/v2/Badge/Badge"; +import { Badge, TBadgeProps } from "@app/components/v3"; import { ProjectPermissionActions, ProjectPermissionCmekActions, @@ -72,7 +71,7 @@ import { DeleteCmekModal } from "./DeleteCmekModal"; const getStatusBadgeProps = ( isDisabled: boolean -): { variant: BadgeProps["variant"]; label: string } => { +): { variant: TBadgeProps["variant"]; label: string } => { if (isDisabled) { return { variant: "danger", diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekVerifyModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekVerifyModal.tsx index 4163beb5a..5c9eac072 100644 --- a/frontend/src/pages/kms/OverviewPage/components/CmekVerifyModal.tsx +++ b/frontend/src/pages/kms/OverviewPage/components/CmekVerifyModal.tsx @@ -7,7 +7,6 @@ import { z } from "zod"; import { createNotification } from "@app/components/notifications"; import { decodeBase64 } from "@app/components/utilities/cryptography/crypto"; import { - Badge, Button, FormControl, Modal, @@ -19,6 +18,7 @@ import { TextArea, Tooltip } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { SigningAlgorithm, TCmek, useCmekVerify } from "@app/hooks/api/cmeks"; import { isBase64 } from "@app/lib/fn/base64"; @@ -112,30 +112,22 @@ const VerifyForm = ({ cmek }: FormProps) => {
    Signature Status: - - - {signatureValid ? ( -
    -

    Valid

    -
    - ) : ( -
    -

    Invalid

    -
    - )} -
    -
    + + + {signatureValid ? "Valid" : "Invalid"} + +
    Signing Algorithm: - {signingAlgorithm} + {signingAlgorithm}
    Signature:{" "} diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupsSection.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupsSection.tsx index 753ebd93c..416b3c191 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupsSection.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgGroupsTab/components/OrgGroupsSection/OrgGroupsSection.tsx @@ -5,6 +5,7 @@ import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal"; import { createNotification } from "@app/components/notifications"; import { OrgPermissionCan } from "@app/components/permissions"; import { Button, DeleteActionModal } from "@app/components/v2"; +import { DocumentationLinkBadge } from "@app/components/v3"; import { OrgPermissionGroupActions, OrgPermissionSubjects, useSubscription } from "@app/context"; import { useDeleteGroup } from "@app/hooks/api"; import { usePopUp } from "@app/hooks/usePopUp"; @@ -26,8 +27,8 @@ export const OrgGroupsSection = () => { const handleAddGroupModal = () => { if (!subscription?.groups) { handlePopUpOpen("upgradePlan", { - description: - "You can manage users more efficiently with groups if you upgrade your Infisical plan to an Enterprise license." + text: "Your current plan does not allow adding groups. To unlock this feature, please upgrade to Infisical Enterprise plan.", + isEnterpriseFeature: true }); } else { handlePopUpOpen("group"); @@ -57,7 +58,10 @@ export const OrgGroupsSection = () => { return (
    -

    Groups

    +
    +

    Groups

    + +
    {(isAllowed) => (
    ); diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm.tsx index 4ddcf964e..74850b475 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAliCloudAuthForm.tsx @@ -55,7 +55,10 @@ const schema = z export type FormData = z.infer; type Props = { - handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["upgradePlan"]>, + data?: { featureName?: string } + ) => void; handlePopUpToggle: ( popUpName: keyof UsePopUpState<["identityAuthMethod"]>, state?: boolean @@ -277,7 +280,9 @@ export const IdentityAliCloudAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -292,7 +297,9 @@ export const IdentityAliCloudAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -315,7 +322,9 @@ export const IdentityAliCloudAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModalContent.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModalContent.tsx index 57663f441..1bfb904a5 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModalContent.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAuthMethodModalContent.tsx @@ -4,7 +4,8 @@ import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal"; -import { Badge, FormControl, Select, SelectItem, Tooltip } from "@app/components/v2"; +import { FormControl, Select, SelectItem, Tooltip } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { IdentityAuthMethod } from "@app/hooks/api/identities"; import { UsePopUpState } from "@app/hooks/usePopUp"; @@ -277,7 +278,7 @@ export const IdentityAuthMethodModalContent = ({ > {label}{" "} {alreadyConfigured && !isSelectedAuthAlreadyConfigured && ( - Configured + Configured )} @@ -291,7 +292,8 @@ export const IdentityAuthMethodModalContent = ({ handlePopUpToggle("upgradePlan", isOpen)} - text="You can use IP allowlisting if you switch to Infisical's Pro plan." + text={`Your current plan does not include access to ${popUp.upgradePlan.data?.featureName}. To unlock this feature, please upgrade to Infisical ${popUp.upgradePlan.data?.isEnterpriseFeature ? "Enterprise" : "Pro"} plan.`} + isEnterpriseFeature={popUp.upgradePlan.data?.isEnterpriseFeature} /> ); diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm.tsx index 7e3292c18..43b86e1b0 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAwsAuthForm.tsx @@ -57,7 +57,10 @@ const schema = z export type FormData = z.infer; type Props = { - handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["upgradePlan"]>, + data?: { featureName?: string } + ) => void; handlePopUpToggle: ( popUpName: keyof UsePopUpState<["identityAuthMethod"]>, state?: boolean @@ -315,7 +318,9 @@ export const IdentityAwsAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -330,7 +335,9 @@ export const IdentityAwsAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -353,7 +360,9 @@ export const IdentityAwsAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAzureAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAzureAuthForm.tsx index 518d97e7b..c99151c8a 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAzureAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityAzureAuthForm.tsx @@ -52,7 +52,10 @@ const schema = z export type FormData = z.infer; type Props = { - handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["upgradePlan"]>, + data?: { featureName?: string } + ) => void; handlePopUpToggle: ( popUpName: keyof UsePopUpState<["identityAuthMethod"]>, state?: boolean @@ -311,7 +314,9 @@ export const IdentityAzureAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -326,7 +331,9 @@ export const IdentityAzureAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -349,7 +356,9 @@ export const IdentityAzureAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm.tsx index 7175e8b62..f99cfb235 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityGcpAuthForm.tsx @@ -55,7 +55,10 @@ const schema = z export type FormData = z.infer; type Props = { - handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["upgradePlan"]>, + data?: { featureName?: string } + ) => void; handlePopUpToggle: ( popUpName: keyof UsePopUpState<["identityAuthMethod"]>, state?: boolean @@ -350,7 +353,9 @@ export const IdentityGcpAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -365,7 +370,9 @@ export const IdentityGcpAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -388,7 +395,9 @@ export const IdentityGcpAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm.tsx index f62045810..96f4af954 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityJwtAuthForm.tsx @@ -88,7 +88,10 @@ const schema = z.discriminatedUnion("configurationType", [ export type FormData = z.infer; type Props = { - handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["upgradePlan"]>, + data?: { featureName?: string } + ) => void; handlePopUpToggle: ( popUpName: keyof UsePopUpState<["identityAuthMethod"]>, state?: boolean @@ -619,7 +622,9 @@ export const IdentityJwtAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -634,7 +639,9 @@ export const IdentityJwtAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -657,7 +664,9 @@ export const IdentityJwtAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx index 3cfe1c355..921e62a7a 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityKubernetesAuthForm.tsx @@ -22,11 +22,12 @@ import { TextArea, Tooltip } from "@app/components/v2"; -import { useOrganization, useSubscription } from "@app/context"; +import { useOrganization, useOrgPermission, useSubscription } from "@app/context"; import { OrgGatewayPermissionActions, OrgPermissionSubjects } from "@app/context/OrgPermissionContext/types"; +import { OrgMembershipRole } from "@app/helpers/roles"; import { gatewaysQueryKeys, useAddIdentityKubernetesAuth, @@ -95,7 +96,10 @@ const schema = z export type FormData = z.infer; type Props = { - handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["upgradePlan"]>, + data?: { featureName?: string } + ) => void; handlePopUpToggle: ( popUpName: keyof UsePopUpState<["identityAuthMethod"]>, state?: boolean @@ -129,6 +133,8 @@ export const IdentityKubernetesAuthForm = ({ ] as const); const { data: vaultConfigs = [] } = useGetVaultExternalMigrationConfigs(); const hasVaultConnection = vaultConfigs.some((config) => config.connectionId); + const { hasOrgRole } = useOrgPermission(); + const isOrgAdmin = hasOrgRole(OrgMembershipRole.Admin); const { control, @@ -409,20 +415,29 @@ export const IdentityKubernetesAuthForm = ({ Load values from HashiCorp Vault
    - + +
    )}
    @@ -695,7 +710,9 @@ export const IdentityKubernetesAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -710,7 +727,9 @@ export const IdentityKubernetesAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -733,7 +752,9 @@ export const IdentityKubernetesAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx index 878e65cfc..86da3abe4 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx @@ -147,7 +147,10 @@ const schema = z export type FormData = z.infer; type Props = { - handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["upgradePlan"]>, + data?: { isEnterpriseFeature?: boolean; featureName?: string } + ) => void; handlePopUpToggle: ( popUpName: keyof UsePopUpState<["identityAuthMethod"]>, state?: boolean @@ -304,7 +307,10 @@ export const IdentityLdapAuthForm = ({ useEffect(() => { if (!subscription?.ldap) { - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + isEnterpriseFeature: true, + featureName: "LDAP authentication" + }); handlePopUpToggle("identityAuthMethod", false); } }, [subscription, handlePopUpOpen, handlePopUpToggle]); @@ -831,7 +837,9 @@ export const IdentityLdapAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -846,7 +854,9 @@ export const IdentityLdapAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -869,7 +879,9 @@ export const IdentityLdapAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm.tsx index 5e33c71bb..0fd7b45a0 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOciAuthForm.tsx @@ -63,7 +63,10 @@ const schema = z export type FormData = z.infer; type Props = { - handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["upgradePlan"]>, + data?: { featureName?: string } + ) => void; handlePopUpToggle: ( popUpName: keyof UsePopUpState<["identityAuthMethod"]>, state?: boolean @@ -297,7 +300,9 @@ export const IdentityOciAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -312,7 +317,9 @@ export const IdentityOciAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -335,7 +342,9 @@ export const IdentityOciAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm.tsx index 15fbc4b72..87ab18eb6 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityOidcAuthForm.tsx @@ -75,7 +75,10 @@ const schema = z.object({ export type FormData = z.infer; type Props = { - handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["upgradePlan"]>, + data?: { featureName?: string } + ) => void; handlePopUpToggle: ( popUpName: keyof UsePopUpState<["identityAuthMethod"]>, state?: boolean @@ -606,7 +609,9 @@ export const IdentityOidcAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -621,7 +626,9 @@ export const IdentityOidcAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -644,7 +651,9 @@ export const IdentityOidcAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySection.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySection.tsx index 5c15a0cdd..93f4084b3 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySection.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySection.tsx @@ -1,15 +1,11 @@ -import { - faArrowUpRightFromSquare, - faBookOpen, - faLink, - faPlus -} from "@fortawesome/free-solid-svg-icons"; +import { faLink, faPlus } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal"; import { createNotification } from "@app/components/notifications"; import { OrgPermissionCan } from "@app/components/permissions"; import { Button, DeleteActionModal, Modal, ModalContent } from "@app/components/v2"; +import { DocumentationLinkBadge } from "@app/components/v3"; import { OrgPermissionIdentityActions, OrgPermissionSubjects, @@ -113,22 +109,9 @@ export const IdentitySection = withPermission(
    -
    +

    Identities

    - -
    - - Docs - -
    -
    +
    {isSubOrganization && ( { if (!isMoreIdentitiesAllowed && !isEnterprise) { handlePopUpOpen("upgradePlan", { - description: - "You can add more identities if you upgrade your Infisical plan." + text: "You have reached the maximum number of identities allowed on your current plan. Upgrade to Infisical Pro plan to add more identities." }); return; } @@ -181,22 +163,9 @@ export const IdentitySection = withPermission( {/* Identity Auth Templates Section */}
    -
    +

    Identity Auth Templates

    - -
    - - Docs - -
    -
    +
    } onClick={() => { if (subscription && !subscription.machineIdentityAuthTemplates) { - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + isEnterpriseFeature: true, + text: "Your current plan does not include access to creating Identity Auth Templates. To unlock this feature, please upgrade to Infisical Enterprise plan." + }); return; } handlePopUpOpen("createTemplate"); @@ -279,7 +251,8 @@ export const IdentitySection = withPermission( handlePopUpToggle("upgradePlan", isOpen)} - text="You can use Identity Auth Templates if you switch to Infisical's Enterprise plan." + text={popUp.upgradePlan.data?.text} + isEnterpriseFeature={popUp.upgradePlan.data?.isEnterpriseFeature} />
    ); diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm.tsx index 19a0499fc..fc79035b1 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTlsCertAuthForm.tsx @@ -50,7 +50,10 @@ const schema = z.object({ export type FormData = z.infer; type Props = { - handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["upgradePlan"]>, + data?: { featureName?: string } + ) => void; handlePopUpToggle: ( popUpName: keyof UsePopUpState<["identityAuthMethod"]>, state?: boolean @@ -286,7 +289,9 @@ export const IdentityTlsCertAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -301,7 +306,9 @@ export const IdentityTlsCertAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -324,7 +331,9 @@ export const IdentityTlsCertAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm.tsx index b819202fc..502580c9d 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityTokenAuthForm.tsx @@ -49,7 +49,10 @@ const schema = z export type FormData = z.infer; type Props = { - handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["upgradePlan"]>, + data?: { featureName?: string } + ) => void; handlePopUpToggle: ( popUpName: keyof UsePopUpState<["identityAuthMethod"]>, state?: boolean @@ -248,7 +251,9 @@ export const IdentityTokenAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -263,7 +268,9 @@ export const IdentityTokenAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -286,7 +293,9 @@ export const IdentityTokenAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx index d43d84c86..dbaeff687 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx @@ -87,7 +87,10 @@ const schema = z export type FormData = z.infer; type Props = { - handlePopUpOpen: (popUpName: keyof UsePopUpState<["upgradePlan"]>) => void; + handlePopUpOpen: ( + popUpName: keyof UsePopUpState<["upgradePlan"]>, + data?: { featureName?: string } + ) => void; handlePopUpToggle: ( popUpName: keyof UsePopUpState<["identityAuthMethod"]>, state?: boolean @@ -409,7 +412,9 @@ export const IdentityUniversalAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -424,7 +429,9 @@ export const IdentityUniversalAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -447,7 +454,9 @@ export const IdentityUniversalAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" @@ -477,7 +486,9 @@ export const IdentityUniversalAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} placeholder="123.456.789.0" /> @@ -492,7 +503,9 @@ export const IdentityUniversalAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} size="lg" colorSchema="danger" @@ -515,7 +528,9 @@ export const IdentityUniversalAuthForm = ({ return; } - handlePopUpOpen("upgradePlan"); + handlePopUpOpen("upgradePlan", { + featureName: "IP allowlisting" + }); }} leftIcon={} size="xs" diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrgMembersSection.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrgMembersSection.tsx index a8f5ea059..ed9c66b3c 100644 --- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrgMembersSection.tsx +++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/OrgMembersSection.tsx @@ -1,13 +1,13 @@ import { useState } from "react"; -import { faBan, faPlus, faTrash } from "@fortawesome/free-solid-svg-icons"; +import { faPlus, faTrash } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { BanIcon } from "lucide-react"; import { twMerge } from "tailwind-merge"; import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal"; import { createNotification } from "@app/components/notifications"; import { OrgPermissionCan } from "@app/components/permissions"; import { - Badge, Button, DeleteActionModal, EmailServiceSetupModal, @@ -15,6 +15,7 @@ import { ModalContent, Tooltip } from "@app/components/v2"; +import { Badge, DocumentationLinkBadge } from "@app/components/v3"; import { OrgPermissionActions, OrgPermissionSubjects, @@ -75,7 +76,7 @@ export const OrgMembersSection = () => { if (!isMoreIdentitiesAllowed && !isEnterprise) { handlePopUpOpen("upgradePlan", { - description: "You can add more members if you upgrade your Infisical plan." + text: "You have reached the maximum number of members allowed on your current plan. Upgrade to Infisical Pro plan to add more members." }); return; } @@ -207,7 +208,10 @@ export const OrgMembersSection = () => {
    -

    Users

    +
    +

    Users

    + +
    {(isAllowed) => (
    @@ -324,7 +323,7 @@ export const OrgMembersSection = () => { handlePopUpToggle("upgradePlan", isOpen)} - text={(popUp.upgradePlan?.data as { description: string })?.description} + text={popUp.upgradePlan?.data?.text} /> void; @@ -133,7 +133,7 @@ export const OrgMembersTable = ({ if (isCustomRole && subscription && !subscription?.rbac) { handlePopUpOpen("upgradePlan", { - description: "You can assign custom roles to members if you upgrade your Infisical plan." + text: "Your current plan does not include access to assigning custom roles to members. To unlock this feature, please upgrade to Infisical Pro plan." }); return; } @@ -519,17 +519,17 @@ export const OrgMembersTable = ({
    -
    +

    {name ?? Not Set}

    {u.superAdmin && ( - - Server Admin - - - - + + + + Server Admin + + )} {lastLoginAuthMethod && lastLoginTime && ( { if (isCustomRole && subscription && !subscription?.rbac) { handlePopUpOpen("upgradePlan", { - description: - "You can set the default org role to a custom role if you upgrade your Infisical plan." + text: "Your current plan does not include access to set a custom default organization role. To unlock this feature, please upgrade to Infisical Pro plan." }); return; } @@ -200,9 +200,12 @@ export const OrgRoleTable = () => { return (
    -

    - {isSubOrganization ? "Sub-" : ""}Organization Roles -

    +
    +

    + {isSubOrganization ? "Sub-" : ""}Organization Roles +

    + +
    {(isAllowed) => (
    -
    +

    {name}

    {isDefaultOrgRole && ( -
    - - Default - -
    + Default
    )}
    @@ -314,8 +313,18 @@ export const OrgRoleTable = () => { {slug}
    - - {isCustomProjectRole(slug) ? "Custom" : "Default"} + + {isCustomOrgRole(slug) ? ( + <> + + Custom + + ) : ( + <> + + Platform + + )} @@ -461,7 +470,7 @@ export const OrgRoleTable = () => { handlePopUpToggle("upgradePlan", isOpen)} - text={(popUp.upgradePlan?.data as { description: string })?.description} + text={popUp.upgradePlan?.data?.text} /> { case AppConnection.AWS: return ; case AppConnection.GitHub: - return ; + return ; case AppConnection.GitHubRadar: return ; case AppConnection.GCP: @@ -163,12 +165,16 @@ const CreateForm = ({ app, onComplete, projectId }: CreateFormProps) => { return ; case AppConnection.Checkly: return ; + case AppConnection.Chef: + return ; case AppConnection.Supabase: return ; case AppConnection.DigitalOcean: return ; case AppConnection.Netlify: return ; + case AppConnection.Northflank: + return ; case AppConnection.Okta: return ; case AppConnection.Redis: @@ -213,7 +219,11 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => { return ; case AppConnection.GitHub: return ( - + ); case AppConnection.GitHubRadar: return ( @@ -322,10 +332,14 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => { return ; case AppConnection.Checkly: return ; + case AppConnection.Chef: + return ; case AppConnection.Supabase: return ; case AppConnection.DigitalOcean: return ; + case AppConnection.Northflank: + return ; case AppConnection.Okta: return ; case AppConnection.Redis: diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ChefConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ChefConnectionForm.tsx new file mode 100644 index 000000000..862b4e2bd --- /dev/null +++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ChefConnectionForm.tsx @@ -0,0 +1,195 @@ +import { Controller, FormProvider, useForm } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; +import { z } from "zod"; + +import { + Button, + FormControl, + Input, + ModalClose, + SecretInput, + Select, + SelectItem +} from "@app/components/v2"; +import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections"; +import { ChefConnectionMethod, TChefConnection } from "@app/hooks/api/appConnections"; +import { AppConnection } from "@app/hooks/api/appConnections/enums"; + +import { + genericAppConnectionFieldsSchema, + GenericAppConnectionsFields +} from "./GenericAppConnectionFields"; + +type Props = { + appConnection?: TChefConnection; + onSubmit: (formData: FormData) => Promise; +}; + +const rootSchema = genericAppConnectionFieldsSchema.extend({ + app: z.literal(AppConnection.Chef) +}); + +const formSchema = z.discriminatedUnion("method", [ + rootSchema.extend({ + method: z.literal(ChefConnectionMethod.UserKey), + credentials: z.object({ + serverUrl: z.string().trim().url("Valid Chef Server URL required").optional(), + orgName: z.string().trim().min(1, "Organization name required"), + userName: z.string().trim().min(1, "User name required"), + privateKey: z.string().trim().min(1, "Private key required") + }) + }) +]); + +type FormData = z.infer; + +export const ChefConnectionForm = ({ appConnection, onSubmit }: Props) => { + const isUpdate = Boolean(appConnection); + + const form = useForm({ + resolver: zodResolver(formSchema), + defaultValues: appConnection ?? { + app: AppConnection.Chef, + method: ChefConnectionMethod.UserKey + } + }); + + const { + handleSubmit, + control, + formState: { isSubmitting, isDirty } + } = form; + + return ( + +
    + {!isUpdate && } + ( + + onChange(e.target.value)} + /> + + )} + /> + ( + + + + )} + /> + + ( + + onChange(e.target.value)} + /> + + )} + /> + ( + + onChange(e.target.value)} + /> + + )} + /> + ( + + onChange(e.target.value)} + /> + + )} + /> +
    + + + + +
    + +
    + ); +}; diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx index 5faa7d5b0..5d7092c03 100644 --- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx +++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx @@ -16,6 +16,7 @@ import { FormControl, Input, ModalClose, + SecretInput, Select, SelectItem, Tooltip @@ -48,28 +49,58 @@ import { type Props = { appConnection?: TGitHubConnection; projectId: string | undefined | null; + onSubmit: (formData: PatSchemaForm) => Promise; }; -const formSchema = genericAppConnectionFieldsSchema.extend({ +const rootSchema = genericAppConnectionFieldsSchema.extend({ app: z.literal(AppConnection.GitHub), - method: z.nativeEnum(GitHubConnectionMethod), - credentials: z - .union([ - z.object({ - instanceType: z.literal("cloud").optional(), - host: z.string().optional() - }), - z.object({ - instanceType: z.literal("server"), - host: z.string().min(1, "Required") - }) - ]) - .optional() + method: z.nativeEnum(GitHubConnectionMethod) }); +const baseCredentialsSchema = z.union([ + z.object({ + instanceType: z.literal("server"), + host: z.string().min(1, "Host is required for server instance type") + }), + z.object({ + instanceType: z.literal("cloud").optional(), + host: z.string().optional() + }) +]); + +const appSchema = rootSchema.extend({ + method: z.literal(GitHubConnectionMethod.App), + credentials: baseCredentialsSchema +}); + +const oauthSchema = rootSchema.extend({ + method: z.literal(GitHubConnectionMethod.OAuth), + credentials: baseCredentialsSchema +}); + +const patSchema = rootSchema.extend({ + method: z.literal(GitHubConnectionMethod.Pat), + credentials: z.union([ + z.object({ + instanceType: z.literal("server"), + host: z.string().min(1, "Host is required for server instance type"), + personalAccessToken: z.string().min(1, "Personal Access Token is required") + }), + z.object({ + instanceType: z.literal("cloud").optional(), + host: z.string().optional(), + personalAccessToken: z.string().min(1, "Personal Access Token is required") + }) + ]) +}); + +type PatSchemaForm = z.infer; + +const formSchema = z.discriminatedUnion("method", [appSchema, oauthSchema, patSchema]); + type FormData = z.infer; -export const GitHubConnectionForm = ({ appConnection, projectId }: Props) => { +export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Props) => { const isUpdate = Boolean(appConnection); const [isRedirecting, setIsRedirecting] = useState(false); @@ -106,7 +137,12 @@ export const GitHubConnectionForm = ({ appConnection, projectId }: Props) => { const returnUrl = useGetAppConnectionOauthReturnUrl(); - const onSubmit = (formData: FormData) => { + const submitHandler = async (formData: FormData) => { + if (formData.method === GitHubConnectionMethod.Pat) { + await onSubmit(formData); + return; + } + setIsRedirecting(true); const state = crypto.randomBytes(16).toString("hex"); localStorage.setItem("latestCSRFToken", state); @@ -151,15 +187,26 @@ export const GitHubConnectionForm = ({ appConnection, projectId }: Props) => { case GitHubConnectionMethod.App: isMissingConfig = !appClientSlug; break; + case GitHubConnectionMethod.Pat: + isMissingConfig = false; + break; default: throw new Error(`Unhandled GitHub Connection method: ${selectedMethod}`); } const methodDetails = getAppConnectionMethodDetails(selectedMethod); + const getButtonText = () => { + if (selectedMethod === GitHubConnectionMethod.Pat) { + return isUpdate ? "Update Connection" : "Create Connection"; + } + + return isUpdate ? "Reconnect to GitHub" : "Connect to GitHub"; + }; + return ( -
    + {!isUpdate && } { )} /> + {selectedMethod === GitHubConnectionMethod.Pat && ( + ( + + onChange(e.target.value)} + /> + + )} + /> + )} @@ -310,7 +377,7 @@ export const GitHubConnectionForm = ({ appConnection, projectId }: Props) => { isLoading={isSubmitting || isRedirecting} isDisabled={isSubmitting || (!isUpdate && !isDirty) || isMissingConfig || isRedirecting} > - {isUpdate ? "Reconnect to GitHub" : "Connect to GitHub"} + {getButtonText()} + + + + + +
    + ); +}; diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionHeader.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionHeader.tsx index f77157945..6c4e0bed0 100644 --- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionHeader.tsx +++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionHeader.tsx @@ -1,6 +1,6 @@ -import { faArrowUpRightFromSquare, faBookOpen } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { DocumentationLinkBadge } from "@app/components/v3"; import { APP_CONNECTION_MAP } from "@app/helpers/appConnections"; import { AppConnection } from "@app/hooks/api/appConnections/enums"; @@ -29,23 +29,11 @@ export const AppConnectionHeader = ({ app, isConnected, onBack }: Props) => { )}
    -
    +
    {appDetails.name} - -
    - - Docs - -
    -
    + />

    {isConnected ? `${appDetails.name} Connection` : `Connect to ${appDetails.name}`} diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionList.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionList.tsx index 8cd28ea91..bdea10d7a 100644 --- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionList.tsx +++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionList.tsx @@ -72,10 +72,13 @@ export const AppConnectionsSelect = ({ onSelect, projectType }: Props) => { return (

    ); diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx index 514900ee0..8a9f1f775 100644 --- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx +++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx @@ -8,18 +8,17 @@ import { faEdit, faEllipsisV, faInfoCircle, - faServer, faTable, faTrash } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { Link } from "@tanstack/react-router"; +import { ServerIcon } from "lucide-react"; import { twMerge } from "tailwind-merge"; import { createNotification } from "@app/components/notifications"; import { VariablePermissionCan } from "@app/components/permissions"; import { - Badge, DropdownMenu, DropdownMenuContent, DropdownMenuItem, @@ -29,6 +28,7 @@ import { Tooltip, Tr } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { OrgPermissionSubjects, ProjectPermissionSub } from "@app/context"; import { OrgPermissionAppConnectionActions } from "@app/context/OrgPermissionContext/types"; import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types"; @@ -157,9 +157,9 @@ export const AppConnectionRow = ({ {isPlatformManagedCredentials && (
    - - - Platform Managed Credentials + + + Platform Managed Credentials
    diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionsTable.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionsTable.tsx index 491a4d7d7..635377f2e 100644 --- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionsTable.tsx +++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionsTable.tsx @@ -2,8 +2,6 @@ import { useMemo, useState } from "react"; import { faArrowDown, faArrowUp, - faArrowUpRightFromSquare, - faBookOpen, faCheckCircle, faFilter, faMagnifyingGlass, @@ -34,6 +32,7 @@ import { THead, Tr } from "@app/components/v2"; +import { DocumentationLinkBadge } from "@app/components/v3"; import { OrgPermissionSubjects, ProjectPermissionSub } from "@app/context"; import { OrgPermissionAppConnectionActions } from "@app/context/OrgPermissionContext/types"; import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types"; @@ -212,22 +211,9 @@ export const AppConnectionsTable = ({ projectId, projectType }: Props) => {
    -
    +

    App Connections

    - -
    - - Docs - -
    -
    +

    Create and configure connections with third-party apps for re-use across your project diff --git a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx index df3d1327a..71e14e026 100644 --- a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx +++ b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx @@ -633,7 +633,9 @@ export const OAuthCallbackPage = () => { connectionName: data.connection.name, ...(data.returnUrl.includes("integrations") ? { - selectedTab: IntegrationsListPageTabs.SecretSyncs + selectedTab: localStorage.getItem("pkiSyncFormData") + ? IntegrationsListPageTabs.PkiSyncs + : IntegrationsListPageTabs.SecretSyncs } : {}) } diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx index c53c38984..72561b90d 100644 --- a/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx +++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx @@ -8,7 +8,6 @@ import { AnimatePresence, motion } from "framer-motion"; import { twMerge } from "tailwind-merge"; import { - Badge, Button, DropdownMenu, DropdownMenuContent, @@ -20,6 +19,7 @@ import { Select, SelectItem } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { useOrganization } from "@app/context"; import { useGetUserProjects } from "@app/hooks/api"; import { @@ -124,7 +124,7 @@ export const LogsFilter = ({ presets, setFilter, filter, project }: Props) => {

    ); diff --git a/frontend/src/pages/organization/ProjectsPage/components/AllProjectView.tsx b/frontend/src/pages/organization/ProjectsPage/components/AllProjectView.tsx index d7dcfcb3e..cf60ffa59 100644 --- a/frontend/src/pages/organization/ProjectsPage/components/AllProjectView.tsx +++ b/frontend/src/pages/organization/ProjectsPage/components/AllProjectView.tsx @@ -2,7 +2,6 @@ import { useState } from "react"; import { faArrowDownAZ, faBorderAll, - faCheck, faCheckCircle, faFolderOpen, faList, @@ -11,13 +10,13 @@ import { } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { useNavigate } from "@tanstack/react-router"; +import { CheckIcon } from "lucide-react"; import { twMerge } from "tailwind-merge"; import { createNotification } from "@app/components/notifications"; import { OrgPermissionCan } from "@app/components/permissions"; import { RequestProjectAccessModal } from "@app/components/projects/RequestProjectAccessModal"; import { - Badge, Button, DropdownMenu, DropdownMenuContent, @@ -31,6 +30,7 @@ import { Skeleton, Tooltip } from "@app/components/v2"; +import { Badge } from "@app/components/v3"; import { OrgPermissionActions, OrgPermissionSubjects } from "@app/context"; import { OrgPermissionAdminConsoleAction } from "@app/context/OrgPermissionContext/types"; import { getProjectHomePage, getProjectLottieIcon, getProjectTitle } from "@app/helpers/project"; @@ -308,9 +308,9 @@ export const AllProjectView = ({
    {workspace.isMember ? ( - - - Joined + + + Joined ) : ( Expired ) : ( - + {row.encryptedSecret ? "Secret Provided" : "Pending Secret"} )}
    - - -
    - {row.accessType === SecretSharingAccessType.Anyone - ? "Anyone" - : "Organization Members"} -
    -
    -
    + + + {row.accessType === SecretSharingAccessType.Anyone ? "Anyone" : "Organization Members"} + +
    {`${format(new Date(row.createdAt), "yyyy-MM-dd - HH:mm a")}`} {row.expiresAt ? format(new Date(row.expiresAt), "yyyy-MM-dd - HH:mm a") : "-"}