diff --git a/go.mod b/go.mod index 647b68a..1ff549b 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/caarlos0/env/v11 v11.4.2 github.com/caddyserver/certmagic v0.25.6 github.com/coreos/go-oidc/v3 v3.21.0 + github.com/eclipse/paho.mqtt.golang v1.5.1 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 @@ -14,10 +15,14 @@ require ( 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/mochi-mqtt/server/v2 v2.7.9 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/rabbitmq/amqp091-go v1.17.0 github.com/redis/go-redis/v9 v9.23.0 + github.com/twmb/franz-go v1.22.3 + github.com/twmb/franz-go/pkg/kmsg v1.15.1 github.com/yuin/goldmark v1.7.13 go.mongodb.org/mongo-driver/v2 v2.5.0 go.uber.org/zap v1.28.0 @@ -50,6 +55,7 @@ require ( 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/gorilla/websocket v1.5.3 // 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 @@ -67,8 +73,10 @@ require ( github.com/modern-go/reflect2 v1.0.2 // indirect github.com/natefinch/atomic v1.0.1 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/pierrec/lz4/v4 v4.1.33 // indirect github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/quic-go v0.59.0 // indirect + github.com/rs/xid v1.4.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 @@ -87,6 +95,7 @@ require ( golang.org/x/sys v0.50.0 // indirect golang.org/x/tools v0.52.0 // indirect google.golang.org/protobuf v1.36.12 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) tool github.com/a-h/templ/cmd/templ diff --git a/go.sum b/go.sum index 1fadc96..b0ba41c 100644 --- a/go.sum +++ b/go.sum @@ -55,6 +55,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= +github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2ISgCl2W7nE= +github.com/eclipse/paho.mqtt.golang v1.5.1/go.mod h1:1/yJCneuyOoCOzKSsOTUc0AJfpsItBGWvYpBLimhArU= github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w= github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE= github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= @@ -92,6 +94,8 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= @@ -100,12 +104,18 @@ github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4= github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= 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/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg= +github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= 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/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 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= @@ -128,6 +138,8 @@ github.com/microsoft/go-mssqldb v1.12.0 h1:Jwg/8jz2MKlFOYf4Oj7wMOQuTpCLrP4PIx0aI 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/mochi-mqtt/server/v2 v2.7.9 h1:y0g4vrSLAag7T07l2oCzOa/+nKVLoazKEWAArwqBNYI= +github.com/mochi-mqtt/server/v2 v2.7.9/go.mod h1:lZD3j35AVNqJL5cezlnSkuG05c0FCHSsfAKSPBOSbqc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -141,6 +153,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/pierrec/lz4/v4 v4.1.33 h1:GjG1TJ1V4IzKP8L96muuuDNpTwd7D+l2ccXrjAbe014= +github.com/pierrec/lz4/v4 v4.1.33/go.mod h1:7SE9MC2STkNtL4PIwGhjmyVwvILaGI9/COYQNBhKM/c= 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= @@ -152,10 +166,16 @@ github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= +github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ= +github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s= github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/rs/xid v1.4.0 h1:qd7wPTDkN6KQx2VmMBLrpHkiyQwgFXRnkOLacUiaSNY= +github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= 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= @@ -174,6 +194,10 @@ github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWD github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/twmb/franz-go v1.22.3 h1:RHe35s34pKefMLyL+ZYJ6mQVtfFZz4zHDHVkTyACur0= +github.com/twmb/franz-go v1.22.3/go.mod h1:OhbFLkvp6GLcN5daC7I4Q2z0W/rFP16HG+gTbe9CDC4= +github.com/twmb/franz-go/pkg/kmsg v1.15.1 h1:3sj7ekbH33t73nsBcHS0wtp/PyMIViHLNItZrE8V9zM= +github.com/twmb/franz-go/pkg/kmsg v1.15.1/go.mod h1:sGkGxKexpRLBThFHJLjjywcyfkK09qB/g+X+wFWZQ/A= 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= @@ -257,7 +281,10 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T 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= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A= modernc.org/libc v1.80.2/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g= diff --git a/internal/check/check.go b/internal/check/check.go index 5201c9b..b018177 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, Postgres, MySQL, MSSQL, MongoDB, Redis, Heartbeat, Alertmanager} +var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Prometheus, Postgres, MySQL, MSSQL, MongoDB, Redis, MQTT, Kafka, RabbitMQ, 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 } @@ -102,6 +102,9 @@ var impls = map[Type]impl{ MSSQL: dbCheck{MSSQL}, MongoDB: dbCheck{MongoDB}, Redis: dbCheck{Redis}, + MQTT: brokerCheck{MQTT}, + Kafka: brokerCheck{Kafka}, + RabbitMQ: brokerCheck{RabbitMQ}, Heartbeat: heartbeatCheck{}, Alertmanager: alertmanagerCheck{}, } diff --git a/internal/check/db.go b/internal/check/db.go index 2da2c78..6192772 100644 --- a/internal/check/db.go +++ b/internal/check/db.go @@ -9,7 +9,6 @@ import ( "net" "net/url" "strconv" - "strings" "sync" "time" @@ -53,7 +52,7 @@ type DBConfig struct { // SecretFields lists the settings of t the API stores sealed. func SecretFields(t Type) []string { switch t { - case Postgres, MySQL, MSSQL, MongoDB, Redis: + case Postgres, MySQL, MSSQL, MongoDB, Redis, MQTT, Kafka, RabbitMQ: return []string{"password"} } return nil @@ -73,7 +72,7 @@ func (d dbCheck) validate(target string, config json.RawMessage) (json.RawMessag if c.TLS == "" { c.TLS = "require" } - if c.TLS != "disable" && c.TLS != "require" && c.TLS != "verify" { + if !validTLSMode(c.TLS) { 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 { @@ -96,11 +95,7 @@ func (d dbCheck) run(ctx context.Context, s Spec) Outcome { 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 - } + tlsConfig := tlsFor(c.TLS, s.Target) var got string switch d.typ { case Postgres: @@ -115,7 +110,7 @@ func (d dbCheck) run(ctx context.Context, s Spec) Outcome { err = pingRedis(ctx, s.Target, c, dialer, tlsConfig) } if err != nil { - return Outcome{Error: describeDBErr(err, c.Password)} + return Outcome{Error: redact(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))} @@ -123,16 +118,6 @@ func (d dbCheck) run(ctx context.Context, s Spec) Outcome { 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 != "" { diff --git a/internal/check/db_test.go b/internal/check/db_test.go index 64dfc60..0828ed5 100644 --- a/internal/check/db_test.go +++ b/internal/check/db_test.go @@ -120,3 +120,13 @@ func TestDatabaseValidate(t *testing.T) { t.Errorf("SecretFields(mysql) = %v", got) } } + +// runShort runs a check whose failure ends in a timeout with a short one. +func runShort(t *testing.T, typ Type, target, cfg string) Outcome { + t.Helper() + c, err := Validate(typ, target, json.RawMessage(cfg)) + if err != nil { + t.Fatalf("Validate(%s) = %v", cfg, err) + } + return Run(context.Background(), Spec{Type: typ, Target: target, Timeout: 3 * time.Second, Config: c, AllowPrivate: true}) +} diff --git a/internal/check/messaging.go b/internal/check/messaging.go new file mode 100644 index 0000000..530ba33 --- /dev/null +++ b/internal/check/messaging.go @@ -0,0 +1,301 @@ +package check + +import ( + "context" + "crypto/rand" + "crypto/tls" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net" + "net/url" + "strings" + "time" + + mqtt "github.com/eclipse/paho.mqtt.golang" + amqp "github.com/rabbitmq/amqp091-go" + "github.com/twmb/franz-go/pkg/kerr" + "github.com/twmb/franz-go/pkg/kgo" + "github.com/twmb/franz-go/pkg/kmsg" + "github.com/twmb/franz-go/pkg/sasl" + "github.com/twmb/franz-go/pkg/sasl/plain" + "github.com/twmb/franz-go/pkg/sasl/scram" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/netguard" +) + +// Message broker checks sign in to the broker; optionally they look at a +// topic or queue. +const ( + MQTT Type = "mqtt" + Kafka Type = "kafka" + RabbitMQ Type = "rabbitmq" +) + +// BrokerConfig configures message broker checks. Password is a secret. +type BrokerConfig struct { + User string `json:"user,omitempty"` + Password string `json:"password,omitempty"` + // TLS is "disable", "require" (encrypt without verifying) or "verify". + TLS string `json:"tls"` + // Topic is, for MQTT, subscribed to: a message must arrive (retained + // messages count) and contain Expect if set. For Kafka it must exist + // with a leader for every partition. + Topic string `json:"topic,omitempty"` + Expect string `json:"expect,omitempty"` + // Message is produced to the Kafka topic when set. + Message string `json:"message,omitempty"` + // SASL is the Kafka mechanism: "plain", "scram-sha-256" or + // "scram-sha-512"; used when User is set. + SASL string `json:"sasl,omitempty"` + // Vhost and Queue are for RabbitMQ; the queue must exist. + Vhost string `json:"vhost,omitempty"` + Queue string `json:"queue,omitempty"` +} + +type brokerCheck struct{ typ Type } + +func (b brokerCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) { + targets := strings.Split(target, ",") + if len(targets) > 1 && b.typ != Kafka || len(targets) > 5 { + return nil, invalid("invalid_target") + } + for _, t := range targets { + if !validHostPort(strings.TrimSpace(t)) { + return nil, invalid("invalid_target") + } + } + c := BrokerConfig{TLS: "disable"} + if err := json.Unmarshal(config, &c); err != nil { + return nil, invalid("invalid_config") + } + if c.TLS == "" { + c.TLS = "disable" + } + if !validTLSMode(c.TLS) || len(c.User) > 200 || len(c.Password) > 500 || len(c.Topic) > 250 || + len(c.Expect) > 500 || len(c.Message) > 1000 || len(c.Vhost) > 200 || len(c.Queue) > 250 { + return nil, invalid("invalid_config") + } + only := func(ok bool, fields ...string) bool { + for _, f := range fields { + if f != "" && !ok { + return false + } + } + return true + } + valid := only(b.typ == MQTT || b.typ == Kafka, c.Topic) && + only(b.typ == MQTT, c.Expect) && + only(b.typ == Kafka, c.Message, c.SASL) && + only(b.typ == RabbitMQ, c.Vhost, c.Queue) + if !valid || c.Expect != "" && c.Topic == "" || c.Message != "" && c.Topic == "" { + return nil, invalid("invalid_config") + } + if b.typ == MQTT && strings.ContainsAny(c.Topic, "+#") { + return nil, invalid("invalid_config") + } + if b.typ == Kafka && c.User != "" { + if c.SASL == "" { + c.SASL = "plain" + } + if c.SASL != "plain" && c.SASL != "scram-sha-256" && c.SASL != "scram-sha-512" { + return nil, invalid("invalid_config") + } + } + return encode(c), nil +} + +func (b brokerCheck) run(ctx context.Context, s Spec) Outcome { + c, err := decode[BrokerConfig](s.Config) + if err != nil { + return Outcome{Error: "invalid configuration"} + } + d := netguard.Dialer(s.AllowPrivate, s.Timeout) + dial := func(ctx context.Context, addr string) (net.Conn, error) { + conn, err := d.DialContext(ctx, "tcp", addr) + if err != nil || c.TLS == "disable" { + return conn, err + } + tc := tls.Client(conn, tlsFor(c.TLS, addr)) + if err := tc.HandshakeContext(ctx); err != nil { + _ = conn.Close() + return nil, err + } + return tc, nil + } + switch b.typ { + case MQTT: + err = checkMQTT(ctx, s.Target, c, dial) + case Kafka: + err = checkKafka(ctx, s.Target, c, dial) + case RabbitMQ: + err = checkRabbitMQ(ctx, s.Target, c, dial) + } + if err != nil { + return Outcome{Error: redact(err, c.Password)} + } + return Outcome{OK: true} +} + +type dialFunc func(ctx context.Context, addr string) (net.Conn, error) + +func checkMQTT(ctx context.Context, target string, c BrokerConfig, dial dialFunc) error { + id := make([]byte, 6) + _, _ = rand.Read(id) + opts := mqtt.NewClientOptions().AddBroker("tcp://" + target). + SetClientID("uptimesebi-" + hex.EncodeToString(id)). + SetUsername(c.User).SetPassword(c.Password). + SetCleanSession(true).SetAutoReconnect(false).SetConnectRetry(false). + SetConnectTimeout(timeoutOf(ctx)). + SetCustomOpenConnectionFn(func(uri *url.URL, _ mqtt.ClientOptions) (net.Conn, error) { + return dial(ctx, uri.Host) + }) + client := mqtt.NewClient(opts) + if err := wait(ctx, client.Connect()); err != nil { + return err + } + defer client.Disconnect(0) + if c.Topic == "" { + return nil + } + got := make(chan string, 16) + sub := client.Subscribe(c.Topic, 0, func(_ mqtt.Client, m mqtt.Message) { + select { + case got <- string(m.Payload()): + default: + } + }) + if err := wait(ctx, sub); err != nil { + return err + } + // Stop waiting before the check's deadline, so the result says what + // was missing instead of a bare timeout. + ctx, cancel := context.WithTimeout(ctx, timeoutOf(ctx)*4/5) + defer cancel() + var last string + for { + select { + case msg := <-got: + if c.Expect == "" || strings.Contains(msg, c.Expect) { + return nil + } + last = msg + case <-ctx.Done(): + if last != "" { + return fmt.Errorf("message %q does not contain %q", truncate(last, 100), truncate(c.Expect, 100)) + } + return fmt.Errorf("no message on %s", c.Topic) + } + } +} + +// wait waits for an MQTT operation until ctx ends. +func wait(ctx context.Context, t mqtt.Token) error { + select { + case <-t.Done(): + return t.Error() + case <-ctx.Done(): + return errors.New("broker did not answer in time") + } +} + +func checkKafka(ctx context.Context, target string, c BrokerConfig, dial dialFunc) error { + seeds := strings.Split(target, ",") + for i := range seeds { + seeds[i] = strings.TrimSpace(seeds[i]) + } + opts := []kgo.Opt{ + kgo.SeedBrokers(seeds...), + kgo.Dialer(func(ctx context.Context, _, host string) (net.Conn, error) { return dial(ctx, host) }), + kgo.RequestRetries(0), + kgo.ProducerLinger(0), + kgo.RecordDeliveryTimeout(timeoutOf(ctx)), + } + if c.User != "" { + var m sasl.Mechanism + switch c.SASL { + case "scram-sha-256": + m = scram.Auth{User: c.User, Pass: c.Password}.AsSha256Mechanism() + case "scram-sha-512": + m = scram.Auth{User: c.User, Pass: c.Password}.AsSha512Mechanism() + default: + m = plain.Auth{User: c.User, Pass: c.Password}.AsMechanism() + } + opts = append(opts, kgo.SASL(m)) + } + client, err := kgo.NewClient(opts...) + if err != nil { + return err + } + defer client.Close() + + req := kmsg.NewPtrMetadataRequest() + if c.Topic != "" { + t := kmsg.NewMetadataRequestTopic() + t.Topic = kmsg.StringPtr(c.Topic) + req.Topics = append(req.Topics, t) + } + resp, err := req.RequestWith(ctx, client) + if err != nil { + return err + } + if len(resp.Brokers) == 0 { + return errors.New("cluster reports no brokers") + } + if c.Topic == "" { + return nil + } + if len(resp.Topics) == 0 { + return fmt.Errorf("topic %s not found", c.Topic) + } + topic := resp.Topics[0] + if err := kerr.ErrorForCode(topic.ErrorCode); err != nil { + return fmt.Errorf("topic %s: %w", c.Topic, err) + } + for _, p := range topic.Partitions { + if p.Leader < 0 { + return fmt.Errorf("topic %s: partition %d has no leader", c.Topic, p.Partition) + } + } + if c.Message != "" { + rec := &kgo.Record{Topic: c.Topic, Value: []byte(c.Message), Timestamp: time.Now()} + if err := client.ProduceSync(ctx, rec).FirstErr(); err != nil { + return fmt.Errorf("producing to %s: %w", c.Topic, err) + } + } + return nil +} + +func checkRabbitMQ(ctx context.Context, target string, c BrokerConfig, dial dialFunc) error { + vhost := c.Vhost + if vhost == "" { + vhost = "/" + } + user, password := c.User, c.Password + if user == "" { + user, password = "guest", "guest" + } + // TLS is done by dial, so the URL always names plain AMQP. + conn, err := amqp.DialConfig("amqp://"+target+"/", amqp.Config{ + SASL: []amqp.Authentication{&amqp.PlainAuth{Username: user, Password: password}}, + Vhost: vhost, + Heartbeat: 10 * time.Second, + Dial: func(_, addr string) (net.Conn, error) { return dial(ctx, addr) }, + }) + if err != nil { + return err + } + defer func() { _ = conn.Close() }() + ch, err := conn.Channel() + if err != nil { + return err + } + defer func() { _ = ch.Close() }() + if c.Queue != "" { + if _, err := ch.QueueDeclarePassive(c.Queue, false, false, false, false, nil); err != nil { + return fmt.Errorf("queue %s: %w", c.Queue, err) + } + } + return nil +} diff --git a/internal/check/messaging_test.go b/internal/check/messaging_test.go new file mode 100644 index 0000000..5e848bb --- /dev/null +++ b/internal/check/messaging_test.go @@ -0,0 +1,158 @@ +package check + +import ( + "context" + "errors" + "io" + "log/slog" + "net" + "strings" + "testing" + + mqttserver "github.com/mochi-mqtt/server/v2" + "github.com/mochi-mqtt/server/v2/hooks/auth" + "github.com/mochi-mqtt/server/v2/listeners" + "github.com/twmb/franz-go/pkg/kerr" + "github.com/twmb/franz-go/pkg/kgo" + "github.com/twmb/franz-go/pkg/kmsg" +) + +// mqttBroker starts an in-process broker that accepts check/checkpw and +// holds a retained status message. +func mqttBroker(t *testing.T) string { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().String() + _ = l.Close() + srv := mqttserver.New(&mqttserver.Options{InlineClient: true, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}) + ledger := &auth.Ledger{ + Auth: auth.AuthRules{{Username: "check", Password: "checkpw", Allow: true}}, + ACL: auth.ACLRules{{Filters: auth.Filters{"#": auth.ReadWrite}}}, + } + if err := srv.AddHook(new(auth.Hook), &auth.Options{Ledger: ledger}); err != nil { + t.Fatal(err) + } + if err := srv.AddListener(listeners.NewTCP(listeners.Config{ID: "t", Address: addr})); err != nil { + t.Fatal(err) + } + if err := srv.Serve(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = srv.Close() }) + if err := srv.Publish("plant/pump", []byte(`{"state":"running"}`), true, 0); err != nil { + t.Fatal(err) + } + return addr +} + +func TestBrokerChecks(t *testing.T) { + tests := []struct { + name string + typ Type + target func(*testing.T) string + good []map[string]any + bad map[string]any + // fails are working credentials with a failing condition. + fails map[string]string + }{ + {"mqtt", MQTT, mqttBroker, + []map[string]any{ + {"user": "check", "password": "checkpw"}, + {"user": "check", "password": "checkpw", "topic": "plant/pump", "expect": "running"}, + }, + map[string]any{"user": "check", "password": "wrong-pw-123"}, + map[string]string{ + `{"user":"check","password":"checkpw","topic":"plant/pump","expect":"stopped"}`: `does not contain "stopped"`, + `{"user":"check","password":"checkpw","topic":"plant/silent"}`: "no message on plant/silent", + }}, + {"rabbitmq", RabbitMQ, func(t *testing.T) string { return dbTarget(t, "UPTIME_TEST_RABBITMQ_ADDR") }, + []map[string]any{{"user": "check", "password": "checkpw"}}, + map[string]any{"user": "check", "password": "wrong-pw-123"}, + map[string]string{ + `{"user":"check","password":"checkpw","queue":"no-such-queue"}`: "queue no-such-queue", + `{"user":"check","password":"checkpw","vhost":"nope"}`: "vhost nope not found", + }}, + {"kafka", Kafka, kafkaWithTopic, + []map[string]any{ + {}, + {"topic": "uptimesebi-check", "message": "probe"}, + {"topic": "uptimesebi-check"}, + }, + nil, + map[string]string{ + `{"topic":"no-such-topic-for-sure"}`: "no-such-topic-for-sure", + }}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + target := tc.target(t) + for _, cfg := range tc.good { + if o := runDB(t, tc.typ, target, cfg, true); !o.OK { + t.Errorf("%v: %+v", cfg, o) + } + } + if tc.bad != nil { + o := runDB(t, tc.typ, target, tc.bad, true) + if o.OK || strings.Contains(o.Error, "wrong-pw-123") { + t.Errorf("wrong password: %+v", o) + } + } + for cfg, want := range tc.fails { + o := runShort(t, tc.typ, target, cfg) + if o.OK || !strings.Contains(o.Error, want) { + t.Errorf("%s: %+v, want error containing %q", cfg, o, want) + } + } + if o := runDB(t, tc.typ, target, tc.good[0], false); o.OK || !strings.Contains(o.Error, "non-public") && !strings.Contains(o.Error, "timeout") && !strings.Contains(o.Error, "in time") { + t.Errorf("private address reached without permission: %+v", o) + } + }) + } +} + +// kafkaWithTopic returns the test Kafka with the topic uptimesebi-check. +func kafkaWithTopic(t *testing.T) string { + addr := dbTarget(t, "UPTIME_TEST_KAFKA_ADDR") + client, err := kgo.NewClient(kgo.SeedBrokers(addr)) + if err != nil { + t.Fatal(err) + } + defer client.Close() + req := kmsg.NewPtrCreateTopicsRequest() + topic := kmsg.NewCreateTopicsRequestTopic() + topic.Topic, topic.NumPartitions, topic.ReplicationFactor = "uptimesebi-check", 1, 1 + req.Topics = append(req.Topics, topic) + resp, err := req.RequestWith(context.Background(), client) + if err != nil { + t.Fatal(err) + } + if err := kerr.ErrorForCode(resp.Topics[0].ErrorCode); err != nil && !errors.Is(err, kerr.TopicAlreadyExists) { + t.Fatal(err) + } + return addr +} + +func TestBrokerValidate(t *testing.T) { + for _, tc := range []struct { + typ Type + target, cfg string + }{ + {MQTT, "a:1883,b:1883", `{}`}, + {MQTT, "broker:1883", `{"topic":"plant/#"}`}, + {MQTT, "broker:1883", `{"expect":"ok"}`}, + {MQTT, "broker:1883", `{"queue":"q"}`}, + {Kafka, "a:9092", `{"user":"u","sasl":"gssapi"}`}, + {Kafka, "a:9092", `{"message":"m"}`}, + {RabbitMQ, "mq:5672", `{"topic":"t"}`}, + } { + if _, err := Validate(tc.typ, tc.target, []byte(tc.cfg)); err == nil { + t.Errorf("Validate(%s, %s, %s) accepted", tc.typ, tc.target, tc.cfg) + } + } + if _, err := Validate(Kafka, "a:9092, b:9092", []byte(`{"user":"u","password":"p"}`)); err != nil { + t.Errorf("Kafka with two brokers: %v", err) + } +} diff --git a/internal/check/secure.go b/internal/check/secure.go new file mode 100644 index 0000000..fc877e4 --- /dev/null +++ b/internal/check/secure.go @@ -0,0 +1,32 @@ +package check + +import ( + "crypto/tls" + "net" + "strings" +) + +// TLS modes of services with optional encryption: "require" encrypts +// without verifying the certificate, "verify" also verifies it. +func validTLSMode(m string) bool { return m == "disable" || m == "require" || m == "verify" } + +// tlsFor returns the client TLS settings for mode, or nil for "disable". +func tlsFor(mode, target string) *tls.Config { + if mode == "disable" { + return nil + } + host, _, _ := net.SplitHostPort(target) + return &tls.Config{ServerName: host, InsecureSkipVerify: mode == "require"} //nolint:gosec // "require" encrypts without verifying, as chosen per monitor +} + +// redact shortens err for customers and removes secrets some clients +// repeat in their errors. +func redact(err error, secrets ...string) string { + msg := err.Error() + for _, s := range secrets { + if s != "" { + msg = strings.ReplaceAll(msg, s, "***") + } + } + return truncate(msg, 300) +}