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 }