Skip to content

Commit

Permalink
feat: block by ip
Browse files Browse the repository at this point in the history
  • Loading branch information
leomotors committed Dec 23, 2023
1 parent 55ffbe9 commit 23a4a76
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

Previous changelog before 1.7 will not be noted here.

## [2.3.0] - 2023-12-23

- feat: only allow local ip in some path for system that don't use nginx

## [2.2.1] - 2023-12-21

- feat: add arm64 docker image
Expand Down
4 changes: 2 additions & 2 deletions server/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ func main() {
})

mux.Handle("/data", routes.DataGetHandler)
mux.Handle("/metrics", routes.MetricsHandler)
mux.Handle("/update", routes.UpdatePostHandler)
mux.Handle("/metrics", middlewares.LocalOnly(routes.MetricsHandler))
mux.Handle("/update", middlewares.LocalOnly(routes.UpdatePostHandler))

wrappedMux := middlewares.Logger(mux)

Expand Down
41 changes: 41 additions & 0 deletions server/middlewares/localonly.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package middlewares

import (
"net/http"
"strconv"
"strings"
)

func isLocalIP(ip string) bool {
if ip[0:7] == "192.168" || ip[0:3] == "10." {
return true
}

if ip[0:4] != "172." {
return false
}

tokens := strings.Split(ip, ".")

if len(tokens) != 4 {
return false
}

i, _ := strconv.Atoi(tokens[1])

return i >= 16 && i <= 31
}

func LocalOnly(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := getIP(r)

// Start with 172 or 192 only
if !isLocalIP(ip) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}

next.ServeHTTP(w, r)
})
}
25 changes: 25 additions & 0 deletions server/middlewares/localonly_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package middlewares

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestIsLocalIP(t *testing.T) {
assert.True(t, isLocalIP("192.168.1.112"))
assert.True(t, isLocalIP("192.168.10.123"))

assert.False(t, isLocalIP("48.123.45.67"))
assert.False(t, isLocalIP("192.166.69.420"))

assert.True(t, isLocalIP("172.24.0.1"))
assert.True(t, isLocalIP("172.18.0.1"))

assert.False(t, isLocalIP("172.32.0.0"))
assert.False(t, isLocalIP("172.15.0.0"))

assert.False(t, isLocalIP("invalid string"))
assert.False(t, isLocalIP("1234:5678:abcd:efgh:ijkl:mnop:qrst:uvwx"))
assert.False(t, isLocalIP("172.24.0"))
}

0 comments on commit 23a4a76

Please sign in to comment.