Files
grafana-zabbix/pkg/datasource/resource_handler.go
ismail simsek 04fca562b0 feat(backend): Add query guardrails to prevent potential issues (#2149)
## Summary

Implements query guardrails in the backend to prevent execution of
expensive or malformed queries that could impact customer environments.

Part of https://github.com/grafana/oss-big-tent-squad/issues/127

## Changes

### New guardrails added:

1. **Item ID validation** (`queryItemIdData`)
   - Validates that item IDs are non-empty
   - Validates that item IDs contain only numeric values

2. **Time range validation** (`QueryData`)
   - Validates that `From` timestamp is before `To` timestamp

3. **API method allowlist** (`ZabbixAPIHandler`)
- Only allows Zabbix API methods defined in the frontend type
`zabbixMethodName`
   - Blocks any write/delete/update operations not in the allowlist

### New files:
- `pkg/datasource/guardrails.go` - Validation functions and error
definitions
- `pkg/datasource/guardrails_test.go` - Unit tests for all validation
functions

### Modified files:
- `pkg/datasource/datasource.go` - Added time range validation
- `pkg/datasource/zabbix.go` - Added item ID validation  
- `pkg/datasource/resource_handler.go` - Added API method validation

## Reasoning
- Allowed functions might be unnecessary as we've already prevent using
those in
[types.ts](https://github.com/grafana/grafana-zabbix/blob/main/src/datasource/zabbix/types.ts#L1-L23)
but it's nice to be cautious.
- itemid and time validation is just for sanity. 
- Time range validation will be necessary in the future to warn user
agains running expensive queries.
2025-12-29 18:57:17 +01:00

173 lines
4.5 KiB
Go

package datasource
import (
"encoding/json"
"io"
"net/http"
"time"
"github.com/alexanderzobnin/grafana-zabbix/pkg/zabbix"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/backend/log"
)
// Resource handler describes handlers for the resources populated by plugin in plugin.go, like:
// mux.HandleFunc("/", ds.RootHandler)
// mux.HandleFunc("/zabbix-api", ds.ZabbixAPIHandler)
func (ds *ZabbixDatasource) RootHandler(rw http.ResponseWriter, req *http.Request) {
ds.logger.Debug("Received resource call", "url", req.URL.String(), "method", req.Method)
_, err := rw.Write([]byte("Hello from Zabbix data source!"))
if err != nil {
ds.logger.Warn("Error writing response")
}
rw.WriteHeader(http.StatusOK)
}
func (ds *ZabbixDatasource) ZabbixAPIHandler(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
return
}
body, err := io.ReadAll(req.Body)
defer func() {
if err := req.Body.Close(); err != nil {
log.DefaultLogger.Warn("Error closing request body", "error", err)
}
}()
if err != nil || len(body) == 0 {
writeError(rw, http.StatusBadRequest, err)
return
}
var reqData ZabbixAPIResourceRequest
err = json.Unmarshal(body, &reqData)
if err != nil {
ds.logger.Error("Cannot unmarshal request", "error", err.Error())
writeError(rw, http.StatusInternalServerError, err)
return
}
// Validate API method is allowed (guardrail)
if err := ValidateAPIMethod(reqData.Method); err != nil {
ds.logger.Warn("Blocked API method", "method", reqData.Method)
writeError(rw, http.StatusForbidden, err)
return
}
ctx := req.Context()
pluginCxt := backend.PluginConfigFromContext(ctx)
dsInstance, err := ds.getDSInstance(ctx, pluginCxt)
if err != nil {
ds.logger.Error("Error loading datasource", "error", err)
writeError(rw, http.StatusInternalServerError, err)
return
}
apiReq := &zabbix.ZabbixAPIRequest{Method: reqData.Method, Params: reqData.Params}
result, err := dsInstance.ZabbixAPIQuery(req.Context(), apiReq)
if err != nil {
ds.logger.Error("Zabbix API request error", "error", err)
writeError(rw, http.StatusInternalServerError, err)
return
}
writeResponse(rw, result)
}
func (ds *ZabbixDatasource) DBConnectionPostProcessingHandler(rw http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodPost {
return
}
body, err := io.ReadAll(req.Body)
defer func() {
if err := req.Body.Close(); err != nil {
log.DefaultLogger.Warn("Error closing request body", "error", err)
}
}()
if err != nil || len(body) == 0 {
writeError(rw, http.StatusBadRequest, err)
return
}
var reqData DBConnectionPostProcessingRequest
err = json.Unmarshal(body, &reqData)
if err != nil {
ds.logger.Error("Cannot unmarshal request", "error", err.Error())
writeError(rw, http.StatusInternalServerError, err)
return
}
ctx := req.Context()
pluginCxt := backend.PluginConfigFromContext(ctx)
dsInstance, err := ds.getDSInstance(ctx, pluginCxt)
if err != nil {
ds.logger.Error("Error loading datasource", "error", err)
writeError(rw, http.StatusInternalServerError, err)
return
}
reqData.Query.TimeRange.From = time.Unix(reqData.TimeRange.From, 0)
reqData.Query.TimeRange.To = time.Unix(reqData.TimeRange.To, 0)
frames, err := dsInstance.applyDataProcessing(req.Context(), &reqData.Query, reqData.Series, true)
if err != nil {
writeError(rw, http.StatusInternalServerError, err)
}
resultJson, err := json.Marshal(frames)
if err != nil {
writeError(rw, http.StatusInternalServerError, err)
}
rw.Header().Add("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
_, err = rw.Write(resultJson)
if err != nil {
ds.logger.Warn("Error writing response")
}
}
func writeResponse(rw http.ResponseWriter, result *ZabbixAPIResourceResponse) {
resultJson, err := json.Marshal(*result)
if err != nil {
writeError(rw, http.StatusInternalServerError, err)
}
rw.Header().Add("Content-Type", "application/json")
rw.WriteHeader(http.StatusOK)
_, err = rw.Write(resultJson)
if err != nil {
log.DefaultLogger.Warn("Error writing response")
}
}
func writeError(rw http.ResponseWriter, statusCode int, err error) {
data := make(map[string]interface{})
data["error"] = "Internal Server Error"
data["message"] = err.Error()
var b []byte
if b, err = json.Marshal(data); err != nil {
rw.WriteHeader(statusCode)
return
}
rw.Header().Add("Content-Type", "application/json")
rw.WriteHeader(http.StatusInternalServerError)
_, err = rw.Write(b)
if err != nil {
log.DefaultLogger.Warn("Error writing response")
}
}