github.com/crowdsecurity/crowdsec@v1.6.1/cmd/notification-slack/main.go (about) 1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "os" 7 8 "github.com/crowdsecurity/crowdsec/pkg/protobufs" 9 "github.com/hashicorp/go-hclog" 10 plugin "github.com/hashicorp/go-plugin" 11 12 "github.com/slack-go/slack" 13 "gopkg.in/yaml.v2" 14 ) 15 16 type PluginConfig struct { 17 Name string `yaml:"name"` 18 Webhook string `yaml:"webhook"` 19 LogLevel *string `yaml:"log_level"` 20 } 21 type Notify struct { 22 ConfigByName map[string]PluginConfig 23 } 24 25 var logger hclog.Logger = hclog.New(&hclog.LoggerOptions{ 26 Name: "slack-plugin", 27 Level: hclog.LevelFromString("INFO"), 28 Output: os.Stderr, 29 JSONFormat: true, 30 }) 31 32 func (n *Notify) Notify(ctx context.Context, notification *protobufs.Notification) (*protobufs.Empty, error) { 33 if _, ok := n.ConfigByName[notification.Name]; !ok { 34 return nil, fmt.Errorf("invalid plugin config name %s", notification.Name) 35 } 36 cfg := n.ConfigByName[notification.Name] 37 38 if cfg.LogLevel != nil && *cfg.LogLevel != "" { 39 logger.SetLevel(hclog.LevelFromString(*cfg.LogLevel)) 40 } 41 logger.Info(fmt.Sprintf("found notify signal for %s config", notification.Name)) 42 logger.Debug(fmt.Sprintf("posting to %s webhook, message %s", cfg.Webhook, notification.Text)) 43 err := slack.PostWebhookContext(ctx, n.ConfigByName[notification.Name].Webhook, &slack.WebhookMessage{ 44 Text: notification.Text, 45 }) 46 if err != nil { 47 logger.Error(err.Error()) 48 } 49 50 return &protobufs.Empty{}, err 51 } 52 53 func (n *Notify) Configure(ctx context.Context, config *protobufs.Config) (*protobufs.Empty, error) { 54 d := PluginConfig{} 55 if err := yaml.Unmarshal(config.Config, &d); err != nil { 56 return nil, err 57 } 58 n.ConfigByName[d.Name] = d 59 logger.Debug(fmt.Sprintf("Slack plugin '%s' use URL '%s'", d.Name, d.Webhook)) 60 return &protobufs.Empty{}, nil 61 } 62 63 func main() { 64 var handshake = plugin.HandshakeConfig{ 65 ProtocolVersion: 1, 66 MagicCookieKey: "CROWDSEC_PLUGIN_KEY", 67 MagicCookieValue: os.Getenv("CROWDSEC_PLUGIN_KEY"), 68 } 69 70 plugin.Serve(&plugin.ServeConfig{ 71 HandshakeConfig: handshake, 72 Plugins: map[string]plugin.Plugin{ 73 "slack": &protobufs.NotifierPlugin{ 74 Impl: &Notify{ConfigByName: make(map[string]PluginConfig)}, 75 }, 76 }, 77 GRPCServer: plugin.DefaultGRPCServer, 78 Logger: logger, 79 }) 80 }