Skip to content

Commit

Permalink
replace context.Background with log.Logger
Browse files Browse the repository at this point in the history
  • Loading branch information
karinamzalez committed Jan 29, 2024
1 parent 4f5d4e5 commit e720a6d
Show file tree
Hide file tree
Showing 12 changed files with 35 additions and 40 deletions.
3 changes: 1 addition & 2 deletions ssas/connection.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package ssas

import (
"context"
"database/sql"
"os"
"time"
Expand All @@ -20,7 +19,7 @@ func init() {
Connection, err = createDB()

if err != nil {
log.GetCtxLogger(context.Background()).Fatalf("Failed to create db %s", err.Error())
log.Logger.Fatalf("Failed to create db %s", err.Error())
}
}

Expand Down
3 changes: 1 addition & 2 deletions ssas/hash.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package ssas

import (
"context"
"crypto/rand"
"crypto/sha512"
"encoding/base64"
Expand Down Expand Up @@ -65,7 +64,7 @@ func NewHash(source string) (Hash, error) {
start := time.Now()
h := pbkdf2.Key([]byte(source), salt, hashIter, hashKeyLen, sha512.New)
hashCreationTime := time.Since(start)
log.GetCtxLogger(context.Background()).Info(logrus.Fields{"Elapsed": hashCreationTime, "Event": "SecureHashTime"})
log.Logger.Info(logrus.Fields{"Elapsed": hashCreationTime, "Event": "SecureHashTime"})

hashValue := fmt.Sprintf("%s:%s:%d", base64.StdEncoding.EncodeToString(salt), base64.StdEncoding.EncodeToString(h), hashIter)
return Hash(hashValue), nil
Expand Down
3 changes: 1 addition & 2 deletions ssas/monitoring/monitoring.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package monitoring

import (
"context"
"fmt"
"net/http"
"os"
Expand All @@ -17,7 +16,7 @@ type apm struct {
}

func GetMonitor() *apm {
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if a == nil {
target := os.Getenv("DEPLOYMENT_TARGET")
if target == "" {
Expand Down
5 changes: 2 additions & 3 deletions ssas/service/admin/router.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package admin

import (
"context"
"fmt"
"net/http"
"os"
Expand Down Expand Up @@ -35,7 +34,7 @@ func Server() *service.Server {
useMTLS := os.Getenv("ADMIN_USE_MTLS") == "true"

signingKey, err := service.ChooseSigningKey(adminSigningKeyPath, adminSigningKey)
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if err != nil {
msg := fmt.Sprintf("Unable to get admin server signing key %v", err)
logger.Error(msg)
Expand Down Expand Up @@ -84,7 +83,7 @@ func routes() *chi.Mux {
})

swaggerPath := "./swaggerui"
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if _, err := os.Stat(swaggerPath); os.IsNotExist(err) {
logger.Info("swagger path not found: " + swaggerPath)
swaggerPath = "../swaggerui"
Expand Down
20 changes: 10 additions & 10 deletions ssas/service/main/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func init() {
newrelic.ConfigAppName(appName),
newrelic.ConfigLicense(licenseKey),
)
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if nil != err {
logger.Warnf("New Relic integration is disabled: %s", err)
}
Expand All @@ -86,7 +86,7 @@ func init() {

// We provide some simple commands for bootstrapping the system into place. Commands cannot be combined.
func main() {
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
logger.Info("Home of the System-to-System Authentication Service")
var config = parseConfig()
handleFlags(config)
Expand Down Expand Up @@ -124,7 +124,7 @@ func parseConfig() Flags {
}

func handleFlags(flags Flags) {
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if flags.doAddFixtureData {
addFixtureData()
return
Expand Down Expand Up @@ -164,7 +164,7 @@ func handleFlags(flags Flags) {
}

func createServers() (*service.Server, *service.Server, *http.Server) {
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
ps := public.Server()
if ps == nil {
logger.Error("unable to create public server")
Expand Down Expand Up @@ -192,7 +192,7 @@ func createServers() (*service.Server, *service.Server, *http.Server) {
}

func start(ps *service.Server, as *service.Server, forwarder *http.Server) {
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
logger.Infof("%s", "Starting ssas...")

ps.Serve()
Expand All @@ -205,7 +205,7 @@ func newForwardingRouter() http.Handler {
r := chi.NewRouter()
r.Use(gcmw.RequestID, service.NewAPILogger(), service.ConnectionClose, service.NewCtxLogger)
r.Get("/*", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
// TODO only forward requests for paths in our own host or resource server
url := "https://" + req.Host + req.URL.String()
logger.Infof("forwarding from %s to %s", req.Host+req.URL.String(), url)
Expand Down Expand Up @@ -245,7 +245,7 @@ func makeSystem(db *gorm.DB, groupID, clientID, clientName, scope, hash string)
-----END PUBLIC KEY-----`

g, err := ssas.GetGroupByGroupID(context.Background(), groupID)
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if err != nil {
logger.Warn(err)
}
Expand Down Expand Up @@ -278,7 +278,7 @@ func resetSecret(clientID string) {
s ssas.System
c ssas.Credentials
)
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if s, err = ssas.GetSystemByClientID(context.Background(), clientID); err != nil {
logger.Warn(err)
}
Expand All @@ -297,7 +297,7 @@ func newAdminSystem(name string) {
c ssas.Credentials
u uint64
)
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if pk, _, _, err = ssas.GeneratePublicKey(2048); err != nil {
logger.Errorf("no public key; %s", err)
return
Expand Down Expand Up @@ -326,7 +326,7 @@ func newAdminSystem(name string) {

func listIPs() {
ips, err := ssas.GetAllIPs()
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if err != nil {
logger.Fatalf("unable to get registered IPs: %s", err)
}
Expand Down
13 changes: 7 additions & 6 deletions ssas/service/public/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"time"

"github.com/CMSgov/bcda-ssas-app/log"
"github.com/CMSgov/bcda-ssas-app/ssas/constants"
"github.com/CMSgov/bcda-ssas-app/ssas/monitoring"
"github.com/CMSgov/bcda-ssas-app/ssas/service"
Expand All @@ -21,23 +22,23 @@ var server *service.Server

func init() {
infoMap = make(map[string][]string)
// logger := log.GetCtxLogger(context.Background())
logger := log.Logger
publicSigningKeyPath = os.Getenv("SSAS_PUBLIC_SIGNING_KEY_PATH")
publicSigningKey = os.Getenv("SSAS_PUBLIC_SIGNING_KEY")
// logger.Info("public signing key sourced from ", publicSigningKeyPath)
logger.Info("public signing key sourced from ", publicSigningKeyPath)
clientAssertAud = os.Getenv("SSAS_CLIENT_ASSERTION_AUD")
// logger.Info("aud value required in client assertion tokens:", clientAssertAud)
logger.Info("aud value required in client assertion tokens:", clientAssertAud)
}

func Server() *service.Server {
unsafeMode := os.Getenv("HTTP_ONLY") == "true"
useMTLS := os.Getenv("PUBLIC_USE_MTLS") == "true"

signingKey, err := service.ChooseSigningKey(publicSigningKeyPath, publicSigningKey)
// logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if err != nil {
// msg := fmt.Sprintf("Unable to get public server signing key: %v", err)
// logger.Error(msg)
msg := fmt.Sprintf("Unable to get public server signing key: %v", err)
logger.Error(msg)
return nil
}

Expand Down
3 changes: 1 addition & 2 deletions ssas/service/public/tokens.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package public

import (
"context"
"fmt"
"time"

Expand Down Expand Up @@ -93,7 +92,7 @@ func empty(arr []string) bool {

func tokenValidity(tokenString string, requiredTokenType string) error {
event := logrus.Fields{"Op": "tokenValidity"}
logger := log.GetCtxLogger(context.Background()).WithFields(event)
logger := log.Logger.WithFields(event)
logger.Info(logrus.Fields{"Event": "OperationStarted"})
errLog := logger.WithField("Event", "OperationFailed")

Expand Down
14 changes: 7 additions & 7 deletions ssas/service/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func ChooseSigningKey(signingKeyPath, signingKey string) (*rsa.PrivateKey, error

// NewServer correctly initializes an instance of the Server type.
func NewServer(name, port, version string, info interface{}, routes *chi.Mux, notSecure bool, useMTLS bool, signingKey *rsa.PrivateKey, ttl time.Duration, clientAssertAud string) *Server {
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if signingKey == nil {
logger.Error("Private Key is nil")
return nil
Expand Down Expand Up @@ -156,7 +156,7 @@ func (s *Server) ListRoutes() ([]string, error) {
func (s *Server) LogRoutes() {
banner := fmt.Sprintf("Routes for %s at port %s: ", s.name, s.port)
routes, err := s.ListRoutes()
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if err != nil {
logger.Errorf("%s routing error: %v", banner, err)
return
Expand All @@ -166,7 +166,7 @@ func (s *Server) LogRoutes() {

// Serve starts the server listening for and responding to requests.
func (s *Server) Serve() {
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if s.notSecure {
logger.Infof("starting %s server running UNSAFE http only mode; do not do this in production environments", s.name)
go func() { logger.Fatal(s.server.ListenAndServe()) }()
Expand All @@ -192,7 +192,7 @@ func (s *Server) Serve() {

func getServerCertificates() (*x509.CertPool, tls.Certificate, error) {
crtB, err := b64.StdEncoding.DecodeString(os.Getenv("BCDA_TLS_CERT_B64"))
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if err != nil {
logger.Error(err)
return nil, tls.Certificate{}, errors.New("could not base64 decode BCDA_TLS_CERT_B64")
Expand Down Expand Up @@ -230,7 +230,7 @@ func getServerCertificates() (*x509.CertPool, tls.Certificate, error) {

// Stops the server listening for and responding to requests.
func (s *Server) Stop() {
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
logger.Infof("closing server %s; %+v", s.name, s.server.Close())
}

Expand Down Expand Up @@ -278,7 +278,7 @@ func (s *Server) getHealthCheck(w http.ResponseWriter, r *http.Request) {
// since this ping will be run against all servers, isn't this excessive?
func doHealthCheck(ctx context.Context) bool {
db, err := ssas.Connection.WithContext(ctx).DB()
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if err != nil {
// TODO health check failed event
logger.Error("health check: database connection error: ", err.Error())
Expand Down Expand Up @@ -378,7 +378,7 @@ func (s *Server) mintToken(claims *CommonClaims, issuedAt int64, expiresAt int64
claims.Issuer = "ssas"
token.Claims = claims
var signedString, err = token.SignedString(s.tokenSigningKey)
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if err != nil {
logger.Error(logrus.Fields{"Event": "TokenMintingFailure", "TokenID": tokenID})
logger.Errorf("token signing error %s", err)
Expand Down
3 changes: 1 addition & 2 deletions ssas/service/test_utils.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package service

import (
"context"
"errors"
"time"

Expand Down Expand Up @@ -61,7 +60,7 @@ func BadToken(claims *CommonClaims, flaw TokenFlaw, keyPath string) (token *jwt.
token.Claims = claims
signedString, err = token.SignedString(signingKey)
if err != nil {
log.GetCtxLogger(context.Background()).Error(logrus.Fields{"TokenID": tokenID, "Help": "token signing error " + err.Error(), "Event": "TokenMintingFailure"})
log.Logger.Error(logrus.Fields{"TokenID": tokenID, "Help": "token signing error " + err.Error(), "Event": "TokenMintingFailure"})
}
return
}
4 changes: 2 additions & 2 deletions ssas/service/tokenblacklist.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func (t *Blacklist) IsTokenBlacklisted(tokenID string) bool {
defer t.RUnlock()

bEvent := logrus.Fields{"Op": "TokenVerification", "TrackingID": t.ID, "TokenID": tokenID}
logger := log.GetCtxLogger(context.Background()).WithFields(bEvent)
logger := log.Logger.WithFields(bEvent)
if _, found := t.c.Get(tokenID); found {
logger.Info(logrus.Fields{"Event": "BlacklistedTokenPresented"})
return true
Expand Down Expand Up @@ -136,7 +136,7 @@ func (t *Blacklist) LoadFromDatabase() error {
}

func (t *Blacklist) startCacheRefreshTicker(refreshFreq time.Duration) (*time.Ticker, context.CancelFunc) {
log.GetCtxLogger(context.Background()).Info(logrus.Fields{"Event": "ServiceStarted", "Op": "CacheRefreshTicker", "TrackingID": t.ID})
log.Logger.Info(logrus.Fields{"Event": "ServiceStarted", "Op": "CacheRefreshTicker", "TrackingID": t.ID})

ticker := time.NewTicker(refreshFreq)

Expand Down
2 changes: 1 addition & 1 deletion ssas/systems.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func getEnvVars() {
err := godotenv.Load(envPath)

if err != nil {
log.GetCtxLogger(context.Background()).Info(logrus.Fields{"Event": "ServiceHalted", "Help": fmt.Sprintf("Unable to load environment variables in env %s; message: %s", env, err.Error())})
log.Logger.Info(logrus.Fields{"Event": "ServiceHalted", "Help": fmt.Sprintf("Unable to load environment variables in env %s; message: %s", env, err.Error())})
panic("Unable to start application without loading environment variables.")
}
DefaultScope = os.Getenv("SSAS_DEFAULT_SYSTEM_SCOPE")
Expand Down
2 changes: 1 addition & 1 deletion ssas/testutils.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ func CleanDatabase(group Group) error {
}

err = Connection.Table("systems").Where("g_id = ?", group.ID).Pluck("id", &systemIds).Error
logger := log.GetCtxLogger(context.Background())
logger := log.Logger
if err != nil {
logger.Errorf("unable to find associated systems: %s", err.Error())
} else {
Expand Down

0 comments on commit e720a6d

Please sign in to comment.