From a62ffb43dee6bf78aa252dbdef6bbb5054e46551 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 16:17:08 +0100 Subject: [PATCH] feat(check): PostgreSQL, MySQL/MariaDB, SQL Server, MongoDB and Redis checks Each connects to host:port with the configured credentials and TLS mode, signs in and runs a query (a ping for MongoDB and Redis), optionally comparing the first value. Connections go through the network guard, and errors never repeat the password. Tested against real servers. Refs #93 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- go.mod | 13 +- go.sum | 64 ++++++++ internal/check/check.go | 7 +- internal/check/db.go | 318 ++++++++++++++++++++++++++++++++++++++ internal/check/db_test.go | 122 +++++++++++++++ 5 files changed, 522 insertions(+), 2 deletions(-) create mode 100644 internal/check/db.go create mode 100644 internal/check/db_test.go diff --git a/go.mod b/go.mod index dfa1bcf..647b68a 100644 --- a/go.mod +++ b/go.mod @@ -10,13 +10,16 @@ require ( github.com/gin-gonic/gin v1.12.0 github.com/go-jose/go-jose/v4 v4.1.4 github.com/go-playground/validator/v10 v10.30.6 + github.com/go-sql-driver/mysql v1.10.2 github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.13.0 + github.com/microsoft/go-mssqldb v1.12.0 github.com/nicksnyder/go-i18n/v2 v2.7.0 github.com/pquerna/otp v1.5.0 github.com/pressly/goose/v3 v3.30.1 github.com/redis/go-redis/v9 v9.23.0 github.com/yuin/goldmark v1.7.13 + go.mongodb.org/mongo-driver/v2 v2.5.0 go.uber.org/zap v1.28.0 golang.org/x/crypto v0.59.0 golang.org/x/net v0.63.0 @@ -25,6 +28,7 @@ require ( ) require ( + filippo.io/edwards25519 v1.2.0 // indirect github.com/a-h/parse v0.0.42 // indirect github.com/andybalholm/brotli v1.3.0 // indirect github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect @@ -44,10 +48,13 @@ require ( github.com/go-playground/universal-translator v0.18.2 // indirect github.com/goccy/go-json v0.10.5 // indirect github.com/goccy/go-yaml v1.19.2 // indirect + github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect + github.com/golang-sql/sqlexp v0.1.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.3 // indirect github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/compress v1.20.4 // indirect github.com/klauspost/cpuid/v2 v2.4.0 // indirect github.com/leodido/go-urn v1.5.0 // indirect github.com/libdns/libdns v1.1.1 // indirect @@ -63,10 +70,14 @@ require ( github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/quic-go v0.59.0 // indirect github.com/sethvargo/go-retry v0.5.0 // indirect + github.com/shopspring/decimal v1.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.1 // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.2.0 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect + github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect github.com/zeebo/blake3 v0.2.4 // indirect - go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect go.uber.org/atomic v1.12.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap/exp v0.3.0 // indirect diff --git a/go.sum b/go.sum index ab7f07d..1fadc96 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,19 @@ code.pfad.fr/check v1.1.0 h1:GWvjdzhSEgHvEHe2uJujDcpmZoySKuHQNrZMfzfO0bE= code.pfad.fr/check v1.1.0/go.mod h1:NiUH13DtYsb7xp5wll0U4SXx7KhXQVCtRgdC96IPfoM= +filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= +filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0 h1:5H6YRLGMoC8z5aXpxqcD6FfswI8mwoVNHSecvIoazt4= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.24.0/go.mod h1:Sk63W6X/TElfcE2BknMYg0Q9JuCpebgjnHcbs5md4NM= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.15.0 h1:w3gDUJlJ0BfBsHH02DCBDwbkmMSXJqBj6nBOCo9iocY= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.15.0/go.mod h1:7scl8mG/IFLVjJ9ef/ltdND2T1z0CkgVSaQoUxLvmeU= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 h1:Terj1CMW4+NY5CpWjSRkqLoxh2DkYDdv/FH2z0897Uc= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0/go.mod h1:7Ut2Qw9vcwpLW5Q4MBy43uSxXS7tK2yjs94OJ6j5thE= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.5.0 h1:MaKvxE6D0KkjOg6Wd9M00iqP5PR0kUxCfiezes4JweM= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.5.0/go.mod h1:i2h9fsTFKZorh8RdV2IcSUf/Qj98GlTkrTvUbX/s8as= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 h1:nCYfgcSyHZXJI8J0IWE5MsCGlb2xp9fJiXyxWgmOFg4= +github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0/go.mod h1:ucUjca2JtSZboY8IoUqyQyuuXvwbMBVwFOm0vdQPNhA= +github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1 h1:0O6j18nQDoIff6/mtosT5LNU2WehEwp+LqfX6699oqY= +github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1/go.mod h1:xdYAf5bjkOpsd3auA8riiJW4vneBubt9caavL7626jQ= github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/a-h/parse v0.0.42 h1:OUb8soeTG5+mRWieRyS/OyNU7Xl0+4wr4kPKKPa/WUQ= @@ -61,10 +75,18 @@ github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dm github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= github.com/go-playground/validator/v10 v10.30.6 h1:E+mymlPNRzAMNz1FShrRvLeGWcprF5w305eLLgWieuo= github.com/go-playground/validator/v10 v10.30.6/go.mod h1:jPLL8SKCXGe/g87QmEyNw3NO28nmGt5GCnZnufm7rj4= +github.com/go-sql-driver/mysql v1.10.2 h1:5TRvGvczDohUMOCRA5aCAXgfSZOo/oNDSFD/2RrChS0= +github.com/go-sql-driver/mysql v1.10.2/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA= +github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= +github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A= +github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -80,8 +102,12 @@ github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= +github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= github.com/letsencrypt/challtestsrv v1.4.2 h1:0ON3ldMhZyWlfVNYYpFuWRTmZNnyfiL9Hh5YzC3JVwU= @@ -98,6 +124,8 @@ github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48 github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q= github.com/mholt/acmez/v3 v3.1.7 h1:XTqpuUcRdRoIBuDoI+M4mCnRnPTPN4rqH3Mb723Rg4U= github.com/mholt/acmez/v3 v3.1.7/go.mod h1:Lwv6P/czh/AOq+c99tAzP68/VP92s+8y+hDs4FCgxvo= +github.com/microsoft/go-mssqldb v1.12.0 h1:Jwg/8jz2MKlFOYf4Oj7wMOQuTpCLrP4PIx0aINasMfw= +github.com/microsoft/go-mssqldb v1.12.0/go.mod h1:iYsISdcqI4Tf8x/JwwkHfBu5pxtSD6lSJB8tCrOoo6E= github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE= github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -113,6 +141,8 @@ github.com/nicksnyder/go-i18n/v2 v2.7.0 h1:oiVQUmuCeNggvm/fUVb6/R0aP82BDVphZnmVH github.com/nicksnyder/go-i18n/v2 v2.7.0/go.mod h1:ZMYiWg8ndQSGNk4zbzbyJjrrVjQjuQ8pERFrnBik+c8= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs= github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg= @@ -128,6 +158,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= +github.com/shopspring/decimal v1.6.0 h1:DcTwjCj4tJPLuGZYsR9W0hyX9pQwMIkdo26Ig1T9xX4= +github.com/shopspring/decimal v1.6.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -144,8 +176,17 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.2.0 h1:bYKF2AEwG5rqd1BumT4gAnvwU/M9nBp2pTSxeZw7Wvs= +github.com/xdg-go/scram v1.2.0/go.mod h1:3dlrS0iBaWKYVt2ZfA4cj48umJZ+cAEbR6/SjLA88I8= +github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA= github.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY= @@ -174,22 +215,45 @@ go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg= golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI= golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/internal/check/check.go b/internal/check/check.go index d34c349..5201c9b 100644 --- a/internal/check/check.go +++ b/internal/check/check.go @@ -34,7 +34,7 @@ const ( ) // Types lists every check type. -var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Prometheus, Heartbeat, Alertmanager} +var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Prometheus, Postgres, MySQL, MSSQL, MongoDB, Redis, Heartbeat, Alertmanager} // Passive reports whether t is reported to us rather than run by checkers. func Passive(t Type) bool { return t == Heartbeat || t == Alertmanager } @@ -97,6 +97,11 @@ var impls = map[Type]impl{ JSON: jsonCheck{}, Prometheus: prometheusCheck{}, + Postgres: dbCheck{Postgres}, + MySQL: dbCheck{MySQL}, + MSSQL: dbCheck{MSSQL}, + MongoDB: dbCheck{MongoDB}, + Redis: dbCheck{Redis}, Heartbeat: heartbeatCheck{}, Alertmanager: alertmanagerCheck{}, } diff --git a/internal/check/db.go b/internal/check/db.go new file mode 100644 index 0000000..2da2c78 --- /dev/null +++ b/internal/check/db.go @@ -0,0 +1,318 @@ +package check + +import ( + "context" + "crypto/tls" + "database/sql" + "encoding/json" + "fmt" + "net" + "net/url" + "strconv" + "strings" + "sync" + "time" + + "github.com/go-sql-driver/mysql" + "github.com/jackc/pgx/v5" + mssql "github.com/microsoft/go-mssqldb" + "github.com/microsoft/go-mssqldb/msdsn" + "github.com/redis/go-redis/v9" + "go.mongodb.org/mongo-driver/v2/mongo" + "go.mongodb.org/mongo-driver/v2/mongo/options" + "go.mongodb.org/mongo-driver/v2/mongo/readpref" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/netguard" +) + +// Database checks connect to host:port with the configured credentials and +// run a query. Every connection goes through the network guard. +const ( + Postgres Type = "postgres" + MySQL Type = "mysql" + MSSQL Type = "mssql" + MongoDB Type = "mongodb" + Redis Type = "redis" +) + +// DBConfig configures database checks. Password is a secret: the API +// stores it sealed and hands it only to checkers. +type DBConfig struct { + User string `json:"user,omitempty"` + Password string `json:"password,omitempty"` + Database string `json:"database,omitempty"` + // TLS is "disable", "require" (encrypt without verifying) or "verify". + TLS string `json:"tls"` + // Query runs after connecting; it must succeed. Empty uses a ping. + // Not used for MongoDB and Redis. + Query string `json:"query,omitempty"` + // Expect, when set, must equal the first column of the first row. + Expect string `json:"expect,omitempty"` +} + +// SecretFields lists the settings of t the API stores sealed. +func SecretFields(t Type) []string { + switch t { + case Postgres, MySQL, MSSQL, MongoDB, Redis: + return []string{"password"} + } + return nil +} + +type dbCheck struct{ typ Type } + +func (d dbCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) { + host, port, err := net.SplitHostPort(target) + if n, perr := strconv.Atoi(port); err != nil || host == "" || perr != nil || n < 1 || n > 65535 { + return nil, invalid("invalid_target") + } + c := DBConfig{TLS: "require"} + if err := json.Unmarshal(config, &c); err != nil { + return nil, invalid("invalid_config") + } + if c.TLS == "" { + c.TLS = "require" + } + if c.TLS != "disable" && c.TLS != "require" && c.TLS != "verify" { + return nil, invalid("invalid_config") + } + if len(c.User) > 200 || len(c.Password) > 500 || len(c.Database) > 200 || len(c.Query) > 2000 || len(c.Expect) > 500 { + return nil, invalid("invalid_config") + } + if (d.typ == MongoDB || d.typ == Redis) && (c.Query != "" || c.Expect != "") { + return nil, invalid("invalid_config") + } + if d.typ == Redis && c.Database != "" { + if n, err := strconv.Atoi(c.Database); err != nil || n < 0 || n > 15 { + return nil, invalid("invalid_config") + } + } + return encode(c), nil +} + +func (d dbCheck) run(ctx context.Context, s Spec) Outcome { + c, err := decode[DBConfig](s.Config) + if err != nil { + return Outcome{Error: "invalid configuration"} + } + dialer := netguard.Dialer(s.AllowPrivate, s.Timeout) + host, _, _ := net.SplitHostPort(s.Target) + var tlsConfig *tls.Config + if c.TLS != "disable" { + tlsConfig = &tls.Config{ServerName: host, InsecureSkipVerify: c.TLS == "require"} //nolint:gosec // "require" encrypts without verifying, as chosen per monitor + } + var got string + switch d.typ { + case Postgres: + got, err = queryPostgres(ctx, s.Target, c, dialer, tlsConfig) + case MySQL: + got, err = queryMySQL(ctx, s.Target, c, s.AllowPrivate, tlsConfig) + case MSSQL: + got, err = queryMSSQL(ctx, s.Target, c, dialer) + case MongoDB: + err = pingMongo(ctx, s.Target, c, dialer, tlsConfig) + case Redis: + err = pingRedis(ctx, s.Target, c, dialer, tlsConfig) + } + if err != nil { + return Outcome{Error: describeDBErr(err, c.Password)} + } + if c.Expect != "" && got != c.Expect { + return Outcome{Error: fmt.Sprintf("query returned %q, expected %q", truncate(got, 100), truncate(c.Expect, 100))} + } + return Outcome{OK: true} +} + +// describeDBErr shortens driver errors and makes sure they never repeat the +// password, which some drivers include in connection errors. +func describeDBErr(err error, password string) string { + msg := err.Error() + if password != "" { + msg = strings.ReplaceAll(msg, password, "***") + } + return truncate(msg, 300) +} + +func queryPostgres(ctx context.Context, target string, c DBConfig, d *net.Dialer, tlsConfig *tls.Config) (string, error) { + u := url.URL{Scheme: "postgres", Host: target, Path: "/" + c.Database} + if c.User != "" { + u.User = url.UserPassword(c.User, c.Password) + } + cfg, err := pgx.ParseConfig(u.String()) + if err != nil { + return "", err + } + cfg.TLSConfig = tlsConfig + cfg.Fallbacks = nil + cfg.DialFunc = d.DialContext + conn, err := pgx.ConnectConfig(ctx, cfg) + if err != nil { + return "", err + } + defer func() { _ = conn.Close(context.WithoutCancel(ctx)) }() + q := c.Query + if q == "" { + q = "SELECT 1" + } + rows, err := conn.Query(ctx, q) + if err != nil { + return "", err + } + defer rows.Close() + var first string + if rows.Next() { + if vals, err := rows.Values(); err == nil && len(vals) > 0 { + first = fmt.Sprint(vals[0]) + } + } + return first, rows.Err() +} + +var registerMySQLDial sync.Once + +// mysqlNetwork names a dial function registered with the MySQL driver, +// which only accepts dialers by name. +func mysqlNetwork(allowPrivate bool) string { + registerMySQLDial.Do(func() { + for _, private := range []bool{false, true} { + d := netguard.Dialer(private, 0) + mysql.RegisterDialContext(mysqlNetworkName(private), func(ctx context.Context, addr string) (net.Conn, error) { + return d.DialContext(ctx, "tcp", addr) + }) + } + }) + return mysqlNetworkName(allowPrivate) +} + +func mysqlNetworkName(private bool) string { + if private { + return "guard-private" + } + return "guard-public" +} + +var mysqlTLS sync.Map + +func queryMySQL(ctx context.Context, target string, c DBConfig, allowPrivate bool, tlsConfig *tls.Config) (string, error) { + cfg := mysql.NewConfig() + cfg.User, cfg.Passwd, cfg.DBName = c.User, c.Password, c.Database + cfg.Net, cfg.Addr = mysqlNetwork(allowPrivate), target + if tlsConfig != nil { + // The driver takes TLS settings by registered name. + name := "uptimesebi-" + strconv.FormatBool(tlsConfig.InsecureSkipVerify) + "-" + tlsConfig.ServerName + if _, done := mysqlTLS.LoadOrStore(name, true); !done { + if err := mysql.RegisterTLSConfig(name, tlsConfig); err != nil { + return "", err + } + } + cfg.TLSConfig = name + } + connector, err := mysql.NewConnector(cfg) + if err != nil { + return "", err + } + return querySQL(ctx, sql.OpenDB(connector), c, "SELECT 1") +} + +func queryMSSQL(ctx context.Context, target string, c DBConfig, d *net.Dialer) (string, error) { + host, port, _ := net.SplitHostPort(target) + q := url.Values{"database": {c.Database}} + switch c.TLS { + case "disable": + q.Set("encrypt", "disable") + case "require": + q.Set("encrypt", "true") + q.Set("TrustServerCertificate", "true") + default: + q.Set("encrypt", "true") + } + u := url.URL{Scheme: "sqlserver", User: url.UserPassword(c.User, c.Password), Host: net.JoinHostPort(host, port), RawQuery: q.Encode()} + cfg, err := msdsn.Parse(u.String()) + if err != nil { + return "", err + } + connector := mssql.NewConnectorConfig(cfg) + connector.Dialer = dialer{d} + return querySQL(ctx, sql.OpenDB(connector), c, "SELECT 1") +} + +// dialer adapts net.Dialer to the SQL Server driver's interface. +type dialer struct{ d *net.Dialer } + +// DialContext implements the driver's Dialer. +func (d dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { + return d.d.DialContext(ctx, network, addr) +} + +func querySQL(ctx context.Context, db *sql.DB, c DBConfig, ping string) (string, error) { + defer func() { _ = db.Close() }() + db.SetMaxOpenConns(1) + q := c.Query + if q == "" { + q = ping + } + rows, err := db.QueryContext(ctx, q) + if err != nil { + return "", err + } + defer func() { _ = rows.Close() }() + var first sql.NullString + if rows.Next() { + cols, _ := rows.Columns() + dest := make([]any, len(cols)) + for i := range dest { + dest[i] = new(any) + } + if len(cols) > 0 { + dest[0] = &first + } + if err := rows.Scan(dest...); err != nil { + return "", err + } + } + return first.String, rows.Err() +} + +func pingMongo(ctx context.Context, target string, c DBConfig, d *net.Dialer, tlsConfig *tls.Config) error { + opts := options.Client().SetHosts([]string{target}).SetDialer(d).SetTLSConfig(tlsConfig). + SetDirect(true).SetServerSelectionTimeout(timeoutOf(ctx)).SetConnectTimeout(timeoutOf(ctx)) + if c.User != "" { + cred := options.Credential{Username: c.User, Password: c.Password} + if c.Database != "" { + cred.AuthSource = c.Database + } + opts.SetAuth(cred) + } + client, err := mongo.Connect(opts) + if err != nil { + return err + } + defer func() { _ = client.Disconnect(context.WithoutCancel(ctx)) }() + return client.Ping(ctx, readpref.Primary()) +} + +func pingRedis(ctx context.Context, target string, c DBConfig, d *net.Dialer, tlsConfig *tls.Config) error { + db, _ := strconv.Atoi(c.Database) + client := redis.NewClient(&redis.Options{ + Addr: target, Username: c.User, Password: c.Password, DB: db, + Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) { + conn, err := d.DialContext(ctx, network, addr) + if err != nil || tlsConfig == nil { + return conn, err + } + return tls.Client(conn, tlsConfig), nil + }, + MaxRetries: -1, PoolSize: 1, DisableIdentity: true, + }) + defer func() { _ = client.Close() }() + return client.Ping(ctx).Err() +} + +// timeoutOf is the time left until ctx's deadline, for drivers that take a +// timeout instead of a context. +func timeoutOf(ctx context.Context) time.Duration { + if dl, ok := ctx.Deadline(); ok { + return max(time.Until(dl), time.Millisecond) + } + return 10 * time.Second +} diff --git a/internal/check/db_test.go b/internal/check/db_test.go new file mode 100644 index 0000000..d39ed0c --- /dev/null +++ b/internal/check/db_test.go @@ -0,0 +1,122 @@ +package check + +import ( + "context" + "encoding/json" + "net/url" + "os" + "strings" + "testing" + "time" +) + +// dbTarget returns the address of a test database or skips. +func dbTarget(t *testing.T, env string) string { + t.Helper() + v := os.Getenv(env) + if v == "" { + t.Skip(env + " is not set") + } + return v +} + +func runDB(t *testing.T, typ Type, target string, cfg map[string]any, allowPrivate bool) Outcome { + t.Helper() + raw, _ := json.Marshal(cfg) + c, err := Validate(typ, target, raw) + if err != nil { + t.Fatalf("Validate(%s) = %v", raw, err) + } + timeout := 15 * time.Second + if !allowPrivate { + // MongoDB retries a refused server until the timeout. + timeout = 3 * time.Second + } + return Run(context.Background(), Spec{Type: typ, Target: target, Timeout: timeout, Config: c, AllowPrivate: allowPrivate}) +} + +func TestDatabaseChecks(t *testing.T) { + pgTarget := func() string { + u, err := url.Parse(os.Getenv("UPTIME_TEST_DATABASE_URL")) + if err != nil || u.Host == "" { + t.Skip("UPTIME_TEST_DATABASE_URL is not set") + } + return u.Host + } + redisTarget := func() string { + u, err := url.Parse(os.Getenv("UPTIME_TEST_REDIS_URL")) + if err != nil || u.Host == "" { + t.Skip("UPTIME_TEST_REDIS_URL is not set") + } + return u.Host + } + tests := []struct { + name string + typ Type + target func() string + good map[string]any + bad map[string]any + }{ + {"postgres", Postgres, pgTarget, + map[string]any{"user": "uptime", "password": "uptime", "database": "uptime_test", "tls": "disable", "query": "SELECT 41 + 1", "expect": "42"}, + map[string]any{"user": "uptime", "password": "wrong-pw-123", "database": "uptime_test", "tls": "disable"}}, + {"mariadb", MySQL, func() string { return dbTarget(t, "UPTIME_TEST_MYSQL_ADDR") }, + map[string]any{"user": "root", "password": "checkpw", "database": "shop", "tls": "disable", "query": "SELECT 41 + 1", "expect": "42"}, + map[string]any{"user": "root", "password": "wrong-pw-123", "tls": "disable"}}, + {"mssql", MSSQL, func() string { return dbTarget(t, "UPTIME_TEST_MSSQL_ADDR") }, + map[string]any{"user": "sa", "password": "Check-pw-2026", "database": "master", "tls": "require", "query": "SELECT 41 + 1", "expect": "42"}, + map[string]any{"user": "sa", "password": "wrong-pw-123", "tls": "require"}}, + {"mongodb", MongoDB, func() string { return dbTarget(t, "UPTIME_TEST_MONGO_ADDR") }, + map[string]any{"user": "root", "password": "checkpw", "database": "admin", "tls": "disable"}, + map[string]any{"user": "root", "password": "wrong-pw-123", "database": "admin", "tls": "disable"}}, + {"redis", Redis, redisTarget, + map[string]any{"database": "15", "tls": "disable"}, + map[string]any{"user": "nobody", "password": "wrong-pw-123", "tls": "disable"}}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + target := tc.target() + if o := runDB(t, tc.typ, target, tc.good, true); !o.OK { + t.Fatalf("good credentials: %+v", o) + } + o := runDB(t, tc.typ, target, tc.bad, true) + if o.OK { + t.Fatal("wrong password accepted") + } + if strings.Contains(o.Error, "wrong-pw-123") { + t.Errorf("error repeats the password: %s", o.Error) + } + // Shared checkers must not reach private networks. + if o := runDB(t, tc.typ, target, tc.good, false); o.OK || !strings.Contains(o.Error, "non-public") && !strings.Contains(o.Error, "timeout") { + t.Errorf("private address reached without permission: %+v", o) + } + }) + } + t.Run("unexpected result", func(t *testing.T) { + o := runDB(t, Postgres, pgTarget(), map[string]any{"user": "uptime", "password": "uptime", "database": "uptime_test", "tls": "disable", "query": "SELECT 'degraded'", "expect": "ok"}, true) + if o.OK || !strings.Contains(o.Error, `"degraded"`) { + t.Errorf("Run() = %+v", o) + } + }) +} + +func TestDatabaseValidate(t *testing.T) { + for _, tc := range []struct { + typ Type + target string + cfg string + }{ + {Postgres, "db.example.com", `{}`}, + {Postgres, "db.example.com:99999", `{}`}, + {Postgres, "db.example.com:5432", `{"tls":"maybe"}`}, + {Redis, "cache:6379", `{"query":"INFO"}`}, + {Redis, "cache:6379", `{"database":"16"}`}, + } { + if _, err := Validate(tc.typ, tc.target, json.RawMessage(tc.cfg)); err == nil { + t.Errorf("Validate(%s, %s, %s) accepted", tc.typ, tc.target, tc.cfg) + } + } + if got := SecretFields(MySQL); len(got) != 1 || got[0] != "password" { + t.Errorf("SecretFields(mysql) = %v", got) + } +}