Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added ip manipulations #26

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/devopstest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:

devopstest:
runs-on: ubuntu-latest
container: golang:1.17
container: golang:1.18

services:
postgres:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/statictest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:

statictest:
runs-on: ubuntu-latest
container: golang:1.17
container: golang:1.18
steps:
- name: Checkout code
uses: actions/checkout@v2
Expand Down
1 change: 1 addition & 0 deletions cmd/agent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ catchQuitORerror:
for {
select {
case <-quit:
cancel()
break catchQuitORerror
case err = <-er:
return err
Expand Down
3 changes: 2 additions & 1 deletion cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ func main() {
quit := make(chan os.Signal)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)

//See example here: https://pkg.go.dev/net/http#example-Server.Shutdown
// See example here: https://pkg.go.dev/net/http#example-Server.Shutdown
// Gracefully Shutdown
go func() {
sig := <-quit
logger.Info(fmt.Sprintf("caught sig: %+v", sig))
Expand Down
17 changes: 17 additions & 0 deletions internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"runtime"
Expand Down Expand Up @@ -114,6 +115,8 @@ func sendJSONData(ctx context.Context, cfg config.Config, client *http.Client, m
request, err := http.NewRequest(http.MethodPost, url, &buf)
request.Header.Add("Content-Type", "application/json")
request.Header.Add("Content-Encoding", "gzip")
request.Header.Add("X-Real-IP", GetOutboundIP().String())

if cfg.CryptoKey.E != 0 {
request.Header.Add("Content-Encoding", "64base")
}
Expand Down Expand Up @@ -249,3 +252,17 @@ func StartProfiling(ctx chan int, file string, what string) {
}
fmt.Println("collecting memory really done")
}

// Get preferred outbound ip of this machine
// https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go
func GetOutboundIP() net.IP {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()

localAddr := conn.LocalAddr().(*net.UDPAddr)

return localAddr.IP
}
4 changes: 3 additions & 1 deletion internal/handlers/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ func MetricRouter(db storage.Repositories, cfg *config.Config, logger *zap.Logge
r := chi.NewRouter()
mh := NewMetricHandler(db, logger)
rsaMW := NewRsaMW(rsa.PrivateKey(cfg.CryptoKey))
mu := newMetricUtils(cfg)

// use inbuild middleware
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(mu.checkTrusted)

r.Route("/update/", func(r chi.Router) {
r.Post("/gauge/*", Conveyor(mh.PostHandlerGouge(dbUpdated), checkForPost, checkForLength, unpackGZIP))
Expand All @@ -39,7 +41,7 @@ func MetricRouter(db storage.Repositories, cfg *config.Config, logger *zap.Logge
})

r.Route("/value/", func(r chi.Router) {
r.Get("/{type}/{name}", mh.GetHandlerValue())
r.Get("/{type}/{name}", Conveyor(mh.GetHandlerValue(), checkForGet))
r.Post("/", Conveyor(mh.PostHandlerReturn(&cfg.Key), checkForJSON, checkForPost, packGZIP, unpackGZIP))
})

Expand Down
57 changes: 57 additions & 0 deletions internal/handlers/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@ import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/netip"
"strings"

"github.com/maffka123/metricCollector/internal/server/config"
)

type Middleware func(http.Handler) http.HandlerFunc
Expand All @@ -18,6 +22,14 @@ type gzipWriter struct {
Writer io.Writer
}

type metricUtils struct {
cfg *config.Config
}

func newMetricUtils(cfg *config.Config) metricUtils {
return metricUtils{cfg: cfg}
}

func (w gzipWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
Expand All @@ -43,6 +55,16 @@ func checkForPost(next http.Handler) http.HandlerFunc {
})
}

func checkForGet(next http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Only GET requests are allowed!", http.StatusMethodNotAllowed)
return
}
next.ServeHTTP(w, r)
})
}

func checkForJSON(next http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") != "application/json" {
Expand Down Expand Up @@ -142,3 +164,38 @@ func Conveyor(h http.HandlerFunc, middlewares ...Middleware) http.HandlerFunc {
}
return h
}

func (mu *metricUtils) checkTrusted(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if mu.cfg.TrustedSubnet != "" {
b, err := ifIPinCIDR(mu.cfg.TrustedSubnet, r.Header.Get("X-Real-IP"))
if err != nil {
http.Error(w, fmt.Sprintf("IP address could not be parsed: %s", err), http.StatusForbidden)
return
}

if !*b {
http.Error(w, "IP address is not inside relible network", http.StatusForbidden)
return
}
}
next.ServeHTTP(w, r)
}

return http.HandlerFunc(fn)
}

func ifIPinCIDR(cidr string, ipStr string) (*bool, error) {
network, err := netip.ParsePrefix(cidr)
if err != nil {
return nil, err
}

ip, err := netip.ParseAddr(ipStr)
if err != nil {
return nil, err
}

b := network.Contains(ip)
return &b, nil
}
108 changes: 108 additions & 0 deletions internal/handlers/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"os"
"testing"

"github.com/maffka123/metricCollector/internal/server/config"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -117,6 +118,113 @@ func Test_checkForPost(t *testing.T) {
}
}

func Test_checkForGet(t *testing.T) {
type args struct {
next http.Handler
}
type want struct {
status int
body string
}
tests := []struct {
name string
args args
want want
request *http.Request
}{
{name: "no post", args: args{
next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }),
},
want: want{status: 405, body: "Only GET requests are allowed!\n"},
request: httptest.NewRequest(http.MethodPost, "/update/", nil)},
{name: "post", args: args{
next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }),
},
want: want{status: 200, body: ""},
request: httptest.NewRequest(http.MethodGet, "/update/", nil)},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
request := tt.request
w := httptest.NewRecorder()
h := http.HandlerFunc(checkForGet(tt.args.next))
h.ServeHTTP(w, request)
result := w.Result()
defer result.Body.Close()

bodyBytes, err := io.ReadAll(result.Body)
if err != nil {
fmt.Println(err)
}
bodyString := string(bodyBytes)

assert.Equal(t, tt.want.status, result.StatusCode)
assert.Equal(t, tt.want.body, bodyString)
})
}
}

func Test_checkTrusted(t *testing.T) {
type args struct {
next http.Handler
mu metricUtils
header string
}
type want struct {
status int
body string
}
tests := []struct {
name string
args args
want want
request *http.Request
}{
{name: "success", args: args{
next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }),
mu: metricUtils{cfg: &config.Config{TrustedSubnet: "172.17.0.0/16"}},
header: "172.17.0.2",
},
want: want{status: 200, body: ""},
request: httptest.NewRequest(http.MethodPost, "/update/", nil)},

{name: "forbidden", args: args{
next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }),
mu: metricUtils{cfg: &config.Config{TrustedSubnet: "172.17.0.0/16"}},
header: "172.16.0.2",
},
want: want{status: 403, body: "IP address is not inside relible network\n"},
request: httptest.NewRequest(http.MethodPost, "/update/", nil)},
{name: "ignore", args: args{
next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }),
mu: metricUtils{cfg: &config.Config{}},
header: "172.16.0.2",
},
want: want{status: 200, body: ""},
request: httptest.NewRequest(http.MethodPost, "/update/", nil)},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
request := tt.request
request.Header.Add("X-Real-IP", tt.args.header)
w := httptest.NewRecorder()
h := tt.args.mu.checkTrusted(tt.args.next)
h.ServeHTTP(w, request)
result := w.Result()
defer result.Body.Close()

bodyBytes, err := io.ReadAll(result.Body)
if err != nil {
fmt.Println(err)
}
bodyString := string(bodyBytes)

assert.Equal(t, tt.want.status, result.StatusCode)
assert.Equal(t, tt.want.body, bodyString)
})
}
}

func Test_unpackGZIP(t *testing.T) {
type args struct {
next http.Handler
Expand Down
2 changes: 2 additions & 0 deletions internal/server/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ type Config struct {
Debug bool `env:"METRIC_SERVER_DEBUG"`
CryptoKey rsaPrivKey `env:"CRYPTO_KEY" json:"crypto_key"`
configFile string `env:"CONFIG"`
TrustedSubnet string `env:"TRUSTED_SUBNET" json:"trusted_subnet"`
}

func (v rsaPrivKey) String() string {
Expand Down Expand Up @@ -67,6 +68,7 @@ func InitConfig() (Config, error) {
flag.Var(&cfg.CryptoKey, "ck", "crypto key for asymmetric encoding")
flag.BoolVar(&cfg.Debug, "debug", true, "key for hash function")
flag.StringVar(&cfg.configFile, "c", "", "location of config.json file")
flag.StringVar(&cfg.configFile, "t", "", "ip of a trusted agent")

// find full options link here: https://github.com/jackc/pgx/blob/master/pgxpool/pool.go
flag.StringVar(&cfg.DBpath, "d", "", "path for connection with pg: postgres://postgres:pass@localhost:5432/test?pool_max_conns=10")
Expand Down