From 58cb9ee92f5c7cd314d75c39efaef38c1399dfa8 Mon Sep 17 00:00:00 2001
From: Zakhar Bessarab <z.bessarab@victoriametrics.com>
Date: Thu, 30 Mar 2023 14:18:00 +0300
Subject: [PATCH] lib/fs: verify response code when reading configuration over
 HTTP (#4036)

Verifying status code helps to avoid misleading errors caused by attempt to parse unsuccessful response.

Related issue: #4034

Signed-off-by: Zakhar Bessarab <z.bessarab@victoriametrics.com>
---
 docs/CHANGELOG.md | 2 ++
 lib/fs/fs.go      | 6 ++++++
 2 files changed, 8 insertions(+)

diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 3c07380209..fc39822fd8 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -15,6 +15,8 @@ The following tip changes can be tested by building VictoriaMetrics components f
 
 ## v1.79.x long-time support release (LTS)
 
+* BUGFIX: verify response code when fetching configuration files via HTTP. See [this issue](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/4034).
+
 ## [v1.79.11](https://github.com/VictoriaMetrics/VictoriaMetrics/releases/tag/v1.79.11)
 
 Released at 2023-03-12
diff --git a/lib/fs/fs.go b/lib/fs/fs.go
index c4d23254a5..cf07628828 100644
--- a/lib/fs/fs.go
+++ b/lib/fs/fs.go
@@ -385,6 +385,12 @@ func ReadFileOrHTTP(path string) ([]byte, error) {
 		}
 		data, err := ioutil.ReadAll(resp.Body)
 		_ = resp.Body.Close()
+		if resp.StatusCode != http.StatusOK {
+			if len(data) > 4192 {
+				data = data[:4192]
+			}
+			return nil, fmt.Errorf("unexpected status code when fetching %q: %d, expecting %d; response: %q", path, resp.StatusCode, http.StatusOK, data)
+		}
 		if err != nil {
 			return nil, fmt.Errorf("cannot read %q: %s", path, err)
 		}