@@ -2,8 +2,12 @@ package plugin
2
2
3
3
import (
4
4
"context"
5
+ "crypto/tls"
6
+ "crypto/x509"
5
7
"encoding/json"
8
+ "errors"
6
9
"fmt"
10
+ "os"
7
11
"strings"
8
12
"time"
9
13
@@ -44,6 +48,16 @@ func NewDatasource(ctx context.Context, source backend.DataSourceInstanceSetting
44
48
45
49
opts := options .Client ().ApplyURI (uri )
46
50
51
+ if config .AuthMethod == "auth-tls" {
52
+ // TLS setup
53
+ tlsConfig , err := tlsSetup (config )
54
+ if err != nil {
55
+ backend .Logger .Error ("Failed to setup TLS" , "error" , err )
56
+ return nil , err
57
+ }
58
+ opts .SetTLSConfig (tlsConfig )
59
+ }
60
+
47
61
client , err := mongo .Connect (ctx , opts )
48
62
if err != nil {
49
63
backend .Logger .Error (fmt .Sprintf ("Failed to connect to db: %s" , err .Error ()))
@@ -63,6 +77,39 @@ func (d *Datasource) Dispose() {
63
77
d .client .Disconnect (context .TODO ())
64
78
}
65
79
80
+ func tlsSetup (config * models.PluginSettings ) (* tls.Config , error ) {
81
+ caFile := config .CaCertPath
82
+ certFile := config .ClientCertPath
83
+ keyFile := config .ClientKeyPath
84
+
85
+ if caFile == "" || certFile == "" || keyFile == "" {
86
+ return nil , errors .New ("CA certificate, client certificate or client key file path is missing" )
87
+ }
88
+
89
+ // Loads CA certificate file
90
+ caCert , err := os .ReadFile (caFile )
91
+ if err != nil {
92
+ return nil , err
93
+ }
94
+ caCertPool := x509 .NewCertPool ()
95
+ if ok := caCertPool .AppendCertsFromPEM (caCert ); ! ok {
96
+ return nil , errors .New ("CA file must be in PEM format" )
97
+ }
98
+ // Loads client certificate files
99
+ cert , err := tls .LoadX509KeyPair (certFile , keyFile )
100
+
101
+ if err != nil {
102
+ return nil , err
103
+ }
104
+
105
+ tlsConfig := & tls.Config {
106
+ RootCAs : caCertPool ,
107
+ Certificates : []tls.Certificate {cert },
108
+ }
109
+
110
+ return tlsConfig , nil
111
+ }
112
+
66
113
// QueryData handles multiple queries and returns multiple responses.
67
114
// req contains the queries []DataQuery (where each query contains RefID as a unique identifier).
68
115
// The QueryDataResponse contains a map of RefID to the response for each query, and each response
@@ -206,6 +253,20 @@ func (d *Datasource) CheckHealth(ctx context.Context, req *backend.CheckHealthRe
206
253
}
207
254
208
255
opts := options .Client ().ApplyURI (uri ).SetTimeout (5 * time .Second )
256
+
257
+ if config .AuthMethod == "auth-tls" {
258
+ // TLS setup
259
+ tlsConfig , err := tlsSetup (config )
260
+ if err != nil {
261
+ backend .Logger .Error ("Failed to setup TLS" , "error" , err )
262
+
263
+ res .Status = backend .HealthStatusError
264
+ res .Message = err .Error ()
265
+ return res , nil
266
+ }
267
+ opts .SetTLSConfig (tlsConfig )
268
+ }
269
+
209
270
client , err := mongo .Connect (ctx , opts )
210
271
if err != nil {
211
272
res .Status = backend .HealthStatusError
0 commit comments