Skip to content

Commit 972845d

Browse files
committed
fix: add the Authorization header to the cache key to avoid reading cache data without a valid netbox token that was used to read the data from netbox.
1 parent a064ce8 commit 972845d

2 files changed

Lines changed: 8 additions & 10 deletions

File tree

README.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,7 @@ and the parser will be used to parse the data into a format that can be used by
7070
The web_proxy_cache can be used with http based service discovery in Prometheus. The service discovery can in principle
7171
be used for any api call for the netbox api, but the exporter is designed to work with the
7272
`/dcim/devices/` endpoint where the filter return a hugh amount of entries.
73-
To format the output for service discovery use the `X-Forwarded-For` header with the value
74-
`service_discovery`.
73+
To format the output for service discovery use the `X-Forwarded-For` header with the value `service-discovery`.
7574
> The reason for this implementation is that it has been observed that the netbox plugin
7675
> [netbox-plugin-prometheus-sd](https://github.com/FlxPeters/netbox-plugin-prometheus-sd)
7776
> will take a vary long time to return the result or even return 500 or 504 (probobly proxy timeout)

provider/netbox/proxy.go

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,7 @@ func Endpoint(w http.ResponseWriter, r *http.Request) {
8787
func cacheHandling(w http.ResponseWriter, r *http.Request) {
8888
r.URL.Path = strings.TrimPrefix(r.URL.Path, fmt.Sprintf("/%s", Netbox))
8989

90-
key := fmt.Sprintf("%s%s?%s", r.Header.Get("X-Forwarded-Host"), r.URL.Path, r.URL.RawQuery)
91-
90+
key := getCacheKey(r)
9291
var cacheData interface{}
9392
var ok bool
9493
cacheData, ok = cache[Netbox].Get(key)
@@ -165,11 +164,6 @@ func serviceDiscovery(cacheData interface{}) ([]map[string]interface{}, error) {
165164
}
166165

167166
results := raw.Results
168-
/*
169-
if !ok {
170-
return nil, fmt.Errorf("missing or malformed 'results' field in JSON data")
171-
}
172-
*/
173167

174168
var sd []map[string]interface{}
175169
for _, entry := range results {
@@ -411,6 +405,11 @@ func getForwardContentData(r *http.Request) (string, int, error) {
411405
Data: result,
412406
}
413407

414-
cache[Netbox].Set(fmt.Sprintf("%s%s?%s", r.Header.Get("X-Forwarded-Host"), r.URL.Path, r.URL.RawQuery), cacheData)
408+
cache[Netbox].Set(getCacheKey(r), cacheData)
415409
return "Success", http.StatusOK, nil
416410
}
411+
412+
// getCacheKey generates a unique cache key based on the request URL and relevant headers
413+
func getCacheKey(r *http.Request) string {
414+
return fmt.Sprintf("%s%s?%s-%s", r.Header.Get("X-Forwarded-Host"), r.URL.Path, r.URL.RawQuery, r.Header.Get("Authorization"))
415+
}

0 commit comments

Comments
 (0)