diff --git a/actions/serve.go b/actions/serve.go index afb6f9c..8a91599 100644 --- a/actions/serve.go +++ b/actions/serve.go @@ -5,7 +5,6 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "log" "net" "net/http" "os" @@ -19,6 +18,7 @@ import ( "gitea.benny.dog/torjus/ezshare/store" "github.com/google/uuid" "github.com/urfave/cli/v2" + "go.uber.org/zap" "golang.org/x/crypto/bcrypt" "google.golang.org/grpc" "google.golang.org/grpc/credentials" @@ -29,6 +29,10 @@ func ActionServe(c *cli.Context) error { if err != nil { return err } + logger := cfg.Server.GetLogger() + serverLogger := logger.Named("SERV") + authLogger := logger.Named("AUTH") + httpLogger := logger.Named("HTTP") // Read certificates srvCertBytes, err := cfg.Server.GRPC.Certs.GetCertBytes() @@ -63,7 +67,7 @@ func ActionServe(c *cli.Context) error { defer userCloseFunc() // Create initial admin-user if neccessary - if err := initializeUsers(userStore); err != nil { + if err := initializeUsers(userStore, serverLogger); err != nil { return fmt.Errorf("error initializing store: %w", err) } @@ -99,26 +103,28 @@ func ActionServe(c *cli.Context) error { // Setup file-service grpcFileServer := server.NewGRPCFileServiceServer(s) grpcFileServer.Hostname = cfg.Server.Hostname + grpcFileServer.Logger = logger.Named("FILE") if c.IsSet("hostname") { grpcFileServer.Hostname = c.String("hostname") } // Setup user-service grpcUserServer := server.NewGRPCUserServiceServer(userStore, certSvc) + grpcUserServer.Logger = logger.Named("USER") lis, err := net.Listen("tcp", grpcAddr) if err != nil { - log.Printf("Unable to setup grpc listener: %s\n", err) + serverLogger.Errorw("Unable to setup GRPC listener.", "error", err) rootCancel() } srvCert, err := tls.X509KeyPair(srvCertBytes, srvKeyBytes) if err != nil { - log.Printf("Unable load server certs: %s\n", err) + serverLogger.Errorw("Unable to load server certs.", "error", err) rootCancel() } certPool := x509.NewCertPool() if !certPool.AppendCertsFromPEM(caCertBytes) { - log.Println("Unable to load CA cert") + serverLogger.Errorw("Unable to load CA certs.") rootCancel() } tlsConfig := &tls.Config{ @@ -130,7 +136,7 @@ func ActionServe(c *cli.Context) error { grpcServer := grpc.NewServer( grpc.Creds(creds), - grpc.ChainUnaryInterceptor(interceptors.NewAuthInterceptor(userStore)), + grpc.ChainUnaryInterceptor(interceptors.NewAuthInterceptor(userStore, authLogger)), ) pb.RegisterFileServiceServer(grpcServer, grpcFileServer) pb.RegisterUserServiceServer(grpcServer, grpcUserServer) @@ -141,12 +147,12 @@ func ActionServe(c *cli.Context) error { grpcServer.GracefulStop() }() - log.Printf("Starting grpc server") + serverLogger.Info("Starting GRPC server.") if err = grpcServer.Serve(lis); err != nil { - log.Printf("GRPC Shutdown with error: %s\n", err) + serverLogger.Warnw("GRPC shutdown with error", "error", err) rootCancel() } - log.Println("GRPC Shutdown") + serverLogger.Info("GRPC shutdown.") grpcShutdownCancel() }() @@ -162,6 +168,7 @@ func ActionServe(c *cli.Context) error { httpAddr = c.String("http-addr") } httpServer := server.NewHTTPSever(s, srvCertBytes, cfg.Server.GRPCEndpoint) + httpServer.Logger = httpLogger httpServer.Addr = httpAddr // wait for cancel @@ -173,12 +180,12 @@ func ActionServe(c *cli.Context) error { httpServer.Shutdown(timeoutCtx) }() - log.Printf("Starting http server") + serverLogger.Info("Starting HTTP server.") if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed { - log.Printf("HTTP Server shutdown with error: %s\n", err) + serverLogger.Warnw("HTTP server shutdown with error.", "error", err) rootCancel() } - log.Println("HTTP Shutdown") + serverLogger.Info("HTTP server shutdown.") httpShutdownCancel() }() @@ -187,7 +194,7 @@ func ActionServe(c *cli.Context) error { return nil } -func initializeUsers(us store.UserStore) error { +func initializeUsers(us store.UserStore, logger *zap.SugaredLogger) error { // TODO: Logging userIDs, err := us.ListUsers() if err != nil { @@ -199,7 +206,6 @@ func initializeUsers(us store.UserStore) error { } // no users, create initial admin-user - log.Printf("No users in store. Creating admin-user.") password := uuid.Must(uuid.NewRandom()).String() hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { @@ -216,7 +222,7 @@ func initializeUsers(us store.UserStore) error { if err := us.StoreUser(admin); err != nil { return err } - log.Printf("user created with id %s:%s", admin.Username, password) + logger.Infow("Created admin user.", "username", admin.Username, "password", password) return nil } diff --git a/config/config.go b/config/config.go index 3dc8035..0caff72 100644 --- a/config/config.go +++ b/config/config.go @@ -14,6 +14,8 @@ import ( "gitea.benny.dog/torjus/ezshare/store" "github.com/pelletier/go-toml" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" "google.golang.org/grpc/credentials" ) @@ -310,3 +312,39 @@ func (sc *ServerUserStoreConfig) GetStore() (store.UserStore, func() error, erro return nil, nil, fmt.Errorf("invalid store config") } + +func (c *ServerConfig) GetLogger() *zap.SugaredLogger { + logEncoderConfig := zap.NewProductionEncoderConfig() + logEncoderConfig.EncodeCaller = zapcore.ShortCallerEncoder + logEncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder + logEncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder + logEncoderConfig.EncodeDuration = zapcore.StringDurationEncoder + + rootLoggerConfig := &zap.Config{ + Level: zap.NewAtomicLevelAt(zap.DebugLevel), + OutputPaths: []string{"stdout"}, + ErrorOutputPaths: []string{"stdout"}, + Encoding: "console", + EncoderConfig: logEncoderConfig, + DisableCaller: true, + } + + switch strings.ToUpper(c.LogLevel) { + case "DEBUG": + rootLoggerConfig.DisableCaller = false + rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.DebugLevel) + case "INFO": + rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.InfoLevel) + case "WARN", "WARNING": + rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.WarnLevel) + case "ERR", "ERROR": + rootLoggerConfig.Level = zap.NewAtomicLevelAt(zap.ErrorLevel) + } + + rootLogger, err := rootLoggerConfig.Build() + if err != nil { + panic(err) + } + + return rootLogger.Sugar() +} diff --git a/go.mod b/go.mod index f9f86e0..77ba7fd 100644 --- a/go.mod +++ b/go.mod @@ -3,12 +3,14 @@ module gitea.benny.dog/torjus/ezshare go 1.17 require ( + github.com/dustin/go-humanize v1.0.0 github.com/go-chi/chi/v5 v5.0.7 github.com/google/go-cmp v0.5.6 github.com/google/uuid v1.3.0 github.com/pelletier/go-toml v1.9.4 github.com/urfave/cli/v2 v2.3.0 go.etcd.io/bbolt v1.3.6 + go.uber.org/zap v1.19.1 golang.org/x/crypto v0.0.0-20211202192323-5770296d904e golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 google.golang.org/grpc v1.42.0 @@ -19,6 +21,8 @@ require ( github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect + go.uber.org/atomic v1.9.0 // indirect + go.uber.org/multierr v1.7.0 // indirect golang.org/x/net v0.0.0-20211203184738-4852103109b8 // indirect golang.org/x/sys v0.0.0-20211205182925-97ca703d548d // indirect golang.org/x/text v0.3.7 // indirect diff --git a/go.sum b/go.sum index 082ef6c..441a953 100644 --- a/go.sum +++ b/go.sum @@ -3,6 +3,8 @@ cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= @@ -18,6 +20,10 @@ github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:ma github.com/cpuguy83/go-md2man/v2 v2.0.1 h1:r/myEWzV9lfsM1tFLgDyu0atFtJ1fXn261LKYj/3DxU= github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= @@ -56,8 +62,14 @@ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/pelletier/go-toml v1.9.4 h1:tjENF6MfZAg8e4ZmZTeWaWiT2vXtsoO6+iuOjFhECwM= github.com/pelletier/go-toml v1.9.4/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= @@ -67,14 +79,28 @@ github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M= github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.etcd.io/bbolt v1.3.6 h1:/ecaJf0sk1l4l6V4awd65v2C3ILy7MSj+s/x1ADCIMU= go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.11-0.20210813005559-691160354723 h1:sHOAIxRGBp443oHZIPB+HsUGaksVCXVQENPxwTfQdH4= +go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= +go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/multierr v1.7.0 h1:zaiO/rmgFjbmCXdSYJWQcdvOCsthmdaHfr3Gm2Kx4Ec= +go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= +go.uber.org/zap v1.19.1 h1:ue41HOKd1vGURxrmeKIgELGb3jPW9DMUDGtsinblHwI= +go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20211202192323-5770296d904e h1:MUP6MR3rJ7Gk9LEia0LP2ytiH6MuCfs7qYz+47jGdD8= golang.org/x/crypto v0.0.0-20211202192323-5770296d904e/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= @@ -82,12 +108,15 @@ golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= @@ -99,6 +128,7 @@ golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -125,6 +155,10 @@ golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -159,8 +193,13 @@ google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/server/fileservice.go b/server/fileservice.go index ba56fa7..2dd0817 100644 --- a/server/fileservice.go +++ b/server/fileservice.go @@ -6,16 +6,19 @@ import ( "gitea.benny.dog/torjus/ezshare/pb" "gitea.benny.dog/torjus/ezshare/store" + "github.com/dustin/go-humanize" + "go.uber.org/zap" ) type GRPCFileServiceServer struct { + Logger *zap.SugaredLogger Hostname string store store.FileStore pb.UnimplementedFileServiceServer } func NewGRPCFileServiceServer(store store.FileStore) *GRPCFileServiceServer { - return &GRPCFileServiceServer{Hostname: "localhost:8051", store: store} + return &GRPCFileServiceServer{Hostname: "localhost:8051", store: store, Logger: zap.NewNop().Sugar()} } func (s *GRPCFileServiceServer) UploadFile(ctx context.Context, req *pb.UploadFileRequest) (*pb.UploadFileResponse, error) { @@ -24,8 +27,10 @@ func (s *GRPCFileServiceServer) UploadFile(ctx context.Context, req *pb.UploadFi id, err := s.store.StoreFile(&f) if err != nil { + s.Logger.Warnw("Error storing file.", "error", err) return nil, err } + s.Logger.Infow("Received file.", "id", id, "size", humanize.Bytes(uint64(len(f.Data)))) return &pb.UploadFileResponse{Id: id, FileUrl: fmt.Sprintf("%s/files/%s", s.Hostname, id)}, nil } @@ -34,13 +39,18 @@ func (s *GRPCFileServiceServer) GetFile(ctx context.Context, req *pb.GetFileRequ if err != nil { return nil, err } + s.Logger.Infow("Sending file to client.", "id", f.FileId, "size", humanize.Bytes(uint64(len(f.Data)))) return &pb.GetFileResponse{File: f}, nil } func (s *GRPCFileServiceServer) DeleteFile(ctx context.Context, req *pb.DeleteFileRequest) (*pb.DeleteFileResponse, error) { - err := s.store.DeleteFile(req.Id) - return &pb.DeleteFileResponse{}, err + if err := s.store.DeleteFile(req.Id); err != nil { + s.Logger.Warnw("Error deleting file.", "error", err) + return nil, err + } + s.Logger.Infow("Deleted file.", "id", req.Id) + return &pb.DeleteFileResponse{}, nil } func (s *GRPCFileServiceServer) ListFiles(ctx context.Context, req *pb.ListFilesRequest) (*pb.ListFilesResponse, error) { diff --git a/server/http.go b/server/http.go index 29eb47c..7055b12 100644 --- a/server/http.go +++ b/server/http.go @@ -7,9 +7,11 @@ import ( "gitea.benny.dog/torjus/ezshare/store" "github.com/go-chi/chi/v5" + "go.uber.org/zap" ) type HTTPServer struct { + Logger *zap.SugaredLogger store store.FileStore serverGRPCCert []byte grpcEndpoint string @@ -23,6 +25,7 @@ type MetadataResponse struct { func NewHTTPSever(store store.FileStore, certBytes []byte, grpcEndpoint string) *HTTPServer { srv := &HTTPServer{ + Logger: zap.NewNop().Sugar(), store: store, serverGRPCCert: certBytes, grpcEndpoint: grpcEndpoint, @@ -38,14 +41,21 @@ func NewHTTPSever(store store.FileStore, certBytes []byte, grpcEndpoint string) } func (s *HTTPServer) ServerCertHandler(w http.ResponseWriter, r *http.Request) { - w.Write(s.serverGRPCCert) + if _, err := w.Write(s.serverGRPCCert); err != nil { + s.Logger.Warnw("Error sending server certificate.", "error", err, "remote_addr", r.RemoteAddr) + + } + s.Logger.Infow("Sent server certificate.", "remote_addr", r.RemoteAddr) } func (s *HTTPServer) MetadataHandler(w http.ResponseWriter, r *http.Request) { md := &MetadataResponse{ GRPCEndpoint: s.grpcEndpoint, } encoder := json.NewEncoder(w) - encoder.Encode(md) + if err := encoder.Encode(md); err != nil { + s.Logger.Warnw("Error encoding or sending metadata.", "error", err, "remote_addr", r.RemoteAddr) + } + s.Logger.Infow("Wrote server cert.", "remote_addr", r.RemoteAddr) } func (s *HTTPServer) FileHandler(w http.ResponseWriter, r *http.Request) { @@ -53,15 +63,20 @@ func (s *HTTPServer) FileHandler(w http.ResponseWriter, r *http.Request) { f, err := s.store.GetFile(id) if err != nil { if err == store.ErrNoSuchItem { + s.Logger.Debugw("Tried to get non-existing file.", "remote_addr", r.RemoteAddr) WriteErrorResponse(w, http.StatusNotFound, "file not found") return } + s.Logger.Warnw("Error getting file from store.", "error", err, "remote_addr", r.RemoteAddr) WriteErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("error: %s", err)) return } w.Header().Add("Content-Type", http.DetectContentType(f.Data)) - w.Write(f.Data) + if _, err := w.Write(f.Data); err != nil { + s.Logger.Warnw("Error sending file.", "error", err, "remote_addr", r.RemoteAddr) + } + s.Logger.Infow("Sent file.", "remote_addr", r.RemoteAddr) } func WriteErrorResponse(w http.ResponseWriter, status int, message string) { diff --git a/server/interceptors/auth.go b/server/interceptors/auth.go index d8f3fab..6270c28 100644 --- a/server/interceptors/auth.go +++ b/server/interceptors/auth.go @@ -5,6 +5,7 @@ import ( "gitea.benny.dog/torjus/ezshare/pb" "gitea.benny.dog/torjus/ezshare/store" + "go.uber.org/zap" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/peer" @@ -15,7 +16,7 @@ type ContextKey string var ContextKeyRole ContextKey = "role" var ContextKeyUserID ContextKey = "userid" -func NewAuthInterceptor(s store.UserStore) grpc.UnaryServerInterceptor { +func NewAuthInterceptor(s store.UserStore, logger *zap.SugaredLogger) grpc.UnaryServerInterceptor { // TODO: Verify that cert is signed by our ca return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { p, ok := peer.FromContext(ctx) @@ -31,6 +32,7 @@ func NewAuthInterceptor(s store.UserStore) grpc.UnaryServerInterceptor { if err == nil { newCtx := context.WithValue(ctx, ContextKeyRole, user.UserRole) newCtx = context.WithValue(newCtx, ContextKeyUserID, user.Id) + logger.Debugw("Authenticated user.", "username", user.Username, "role", user.UserRole.String()) return handler(newCtx, req) } } diff --git a/server/userservice.go b/server/userservice.go index c8d1f29..63ce258 100644 --- a/server/userservice.go +++ b/server/userservice.go @@ -9,19 +9,21 @@ import ( "gitea.benny.dog/torjus/ezshare/server/interceptors" "gitea.benny.dog/torjus/ezshare/store" "github.com/google/uuid" + "go.uber.org/zap" "golang.org/x/crypto/bcrypt" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type GRPCUserServiceServer struct { + Logger *zap.SugaredLogger store store.UserStore certService *certs.CertService pb.UnimplementedUserServiceServer } func NewGRPCUserServiceServer(store store.UserStore, certSvc *certs.CertService) *GRPCUserServiceServer { - return &GRPCUserServiceServer{store: store, certService: certSvc} + return &GRPCUserServiceServer{store: store, certService: certSvc, Logger: zap.NewNop().Sugar()} } func (s *GRPCUserServiceServer) Register(ctx context.Context, req *pb.RegisterUserRequest) (*pb.RegisterUserResponse, error) { // Check if user already exists @@ -42,9 +44,12 @@ func (s *GRPCUserServiceServer) Register(ctx context.Context, req *pb.RegisterUs } if err := s.store.StoreUser(user); err != nil { + s.Logger.Warnw("Error storing registered user.", "error", err) return nil, status.Error(codes.Internal, fmt.Sprintf("unable to store user: %s", err)) } + s.Logger.Infow("Registered new user.", "username", user.Username) + return &pb.RegisterUserResponse{Id: user.Id, Token: ""}, nil } @@ -54,6 +59,7 @@ func (s *GRPCUserServiceServer) Login(_ context.Context, req *pb.LoginUserReques if err == store.ErrNoSuchItem { return nil, status.Error(codes.NotFound, "no such user") } + s.Logger.Warnw("Error retrieving user from store.", "error", err) return nil, status.Error(codes.Internal, "error getting user from store") } @@ -63,6 +69,7 @@ func (s *GRPCUserServiceServer) Login(_ context.Context, req *pb.LoginUserReques cert, key, err := s.certService.NewClient(user.Id) if err != nil { + s.Logger.Warnw("Error generating client certificate.", "error", err) return nil, status.Error(codes.Internal, "unable to generate client certificate") } @@ -71,6 +78,7 @@ func (s *GRPCUserServiceServer) Login(_ context.Context, req *pb.LoginUserReques ClientKey: key, } + s.Logger.Infow("Logged in user.", "username", user.Username) return resp, nil } @@ -102,8 +110,10 @@ func (s *GRPCUserServiceServer) ChangePassword(ctx context.Context, req *pb.Chan } user.HashedPassword = newPasswordHash if err := s.store.StoreUser(user); err != nil { + s.Logger.Warnw("Error storing user with new password.", "error", err) return nil, status.Error(codes.Internal, "unable to store new password") } + s.Logger.Infow("Set new password for user.", "username", user.Username) return &pb.Empty{}, nil }