From ea17cf126790d7c4ac70696fc884dabb0e020449 Mon Sep 17 00:00:00 2001 From: TYuan0816 Date: Tue, 23 Jan 2024 01:17:47 +0800 Subject: [PATCH 1/5] Add OAuth2 on AUSF --- go.mod | 1 + go.sum | 4 ++-- internal/context/context.go | 23 ++++++++++++++++++++--- internal/logger/logger.go | 2 ++ internal/sbi/consumer/nf_discovery.go | 2 +- internal/sbi/consumer/nf_management.go | 2 +- internal/util/router_auth_check.go | 0 internal/util/router_auth_check_test.go | 0 8 files changed, 27 insertions(+), 7 deletions(-) create mode 100644 internal/util/router_auth_check.go create mode 100644 internal/util/router_auth_check_test.go diff --git a/go.mod b/go.mod index e9e59a9..69002dd 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d github.com/bronze1man/radius v0.0.0-20190516032554-afd8baec892d github.com/free5gc/openapi v1.0.7-0.20231216094313-e15a4ff046f6 + github.com/free5gc/openapi v1.0.7-0.20240117084712-52ad99299693 github.com/free5gc/util v1.0.5-0.20231205080047-308f623d6808 github.com/gin-gonic/gin v1.9.1 github.com/google/gopacket v1.1.19 diff --git a/go.sum b/go.sum index 1b3bda3..82fdce1 100644 --- a/go.sum +++ b/go.sum @@ -61,8 +61,8 @@ github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.m github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/evanphx/json-patch v0.5.2/go.mod h1:ZWS5hhDbVDyob71nXKNL0+PWn6ToqBHMikGIFbs31qQ= -github.com/free5gc/openapi v1.0.7-0.20231216094313-e15a4ff046f6 h1:8P/wOkTAQMgZJe9pUUNSTE5PWeAdlMrsU9kLsI+VAVE= -github.com/free5gc/openapi v1.0.7-0.20231216094313-e15a4ff046f6/go.mod h1:qv9KqEucoZSeENPRFGxfTe+33ZWYyiYFx1Rj+H0DoWA= +github.com/free5gc/openapi v1.0.7-0.20240117084712-52ad99299693 h1:gFyYBsErQAkx4OVHXYqjO0efO9gPWydQavQcjU0CkHY= +github.com/free5gc/openapi v1.0.7-0.20240117084712-52ad99299693/go.mod h1:qv9KqEucoZSeENPRFGxfTe+33ZWYyiYFx1Rj+H0DoWA= github.com/free5gc/util v1.0.5-0.20231205080047-308f623d6808 h1:8/IoWEgcO2DLlLCqbsxwduD7CzXdKe/BFJU2tcAqnxo= github.com/free5gc/util v1.0.5-0.20231205080047-308f623d6808/go.mod h1:d+79g84a3YHhzvjJ2IhurrBOavOA8xWIQ/GCywPXqQk= github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= diff --git a/internal/context/context.go b/internal/context/context.go index 53c3b03..b0c226c 100644 --- a/internal/context/context.go +++ b/internal/context/context.go @@ -104,6 +104,13 @@ func Init() { InitAusfContext(&ausfContext) } + +type NFContext interface { + AuthorizationCheck(token, serviceName string) error +} + +var _ NFContext = &AUSFContext{} + func NewAusfUeContext(identifier string) (ausfUeContext *AusfUeContext) { ausfUeContext = new(AusfUeContext) ausfUeContext.Supi = identifier // supi @@ -160,12 +167,22 @@ func (a *AUSFContext) GetSelfID() string { return a.NfId } -func (c *AUSFContext) GetTokenCtx(scope, targetNF string) ( +func (c *AUSFContext) GetTokenCtx(scope string, targetNF model.NfType) ( context.Context, *models.ProblemDetails, error, ) { if !c.OAuth2Required { return context.TODO(), nil, nil } - return oauth.GetTokenCtx(models.NfType_AUSF, - c.NfId, c.NrfUri, scope, targetNF) + return oauth.GetTokenCtx(models.NfType_AUSF, targetNF, + c.NfID, c.NrfUri, scope) } + +func (c *AUSFContext) AuthorizationCheck(token, serviceName string) error { + if !c.OAuth2Required { + logger.UtilLog.Debugf("AUSFContext::AuthorizationCheck: OAuth2 not required\n") + return nil + } + + logger.UtilLog.Debugf("AUSFContext::AuthorizationCheck: token[%s] serviceName[%s]\n", token, serviceName) + return oauth.VerifyOAuth(token, serviceName, c.NrfCertPem) +} \ No newline at end of file diff --git a/internal/logger/logger.go b/internal/logger/logger.go index c715cad..b2d3ce3 100644 --- a/internal/logger/logger.go +++ b/internal/logger/logger.go @@ -18,6 +18,7 @@ var ( UeAuthLog *logrus.Entry Auth5gAkaLog *logrus.Entry AuthELog *logrus.Entry + UtilLog *logrus.Entry ) func init() { @@ -37,4 +38,5 @@ func init() { UeAuthLog = NfLog.WithField(logger_util.FieldCategory, "UeAuth") Auth5gAkaLog = NfLog.WithField(logger_util.FieldCategory, "5gAka") AuthELog = NfLog.WithField(logger_util.FieldCategory, "Eap") + UtilLog = NfLog.WithField(logger_util.FieldCategory, "Util") } diff --git a/internal/sbi/consumer/nf_discovery.go b/internal/sbi/consumer/nf_discovery.go index 6278fde..0c40e25 100644 --- a/internal/sbi/consumer/nf_discovery.go +++ b/internal/sbi/consumer/nf_discovery.go @@ -13,7 +13,7 @@ import ( func SendSearchNFInstances(nrfUri string, targetNfType, requestNfType models.NfType, param Nnrf_NFDiscovery.SearchNFInstancesParamOpts, ) (*models.SearchResult, error) { - ctx, _, err := ausf_context.GetSelf().GetTokenCtx("nnrf-disc", "NRF") + ctx, _, err := ausf_context.GetSelf().GetTokenCtx("nnrf-disc", models.NfType_NRF) if err != nil { return nil, err } diff --git a/internal/sbi/consumer/nf_management.go b/internal/sbi/consumer/nf_management.go index 3a156c4..588b27d 100644 --- a/internal/sbi/consumer/nf_management.go +++ b/internal/sbi/consumer/nf_management.go @@ -90,7 +90,7 @@ func SendRegisterNFInstance(nrfUri, nfInstanceId string, profile models.NfProfil func SendDeregisterNFInstance() (*models.ProblemDetails, error) { logger.ConsumerLog.Infof("Send Deregister NFInstance") - ctx, pd, err := ausf_context.GetSelf().GetTokenCtx("nnrf-nfm", "NRF") + ctx, pd, err := ausf_context.GetSelf().GetTokenCtx("nnrf-nfm", models.NfType_NRF) if err != nil { return pd, err } diff --git a/internal/util/router_auth_check.go b/internal/util/router_auth_check.go new file mode 100644 index 0000000..e69de29 diff --git a/internal/util/router_auth_check_test.go b/internal/util/router_auth_check_test.go new file mode 100644 index 0000000..e69de29 From f8269549603e4ea835bc3dde54367515690d9dfc Mon Sep 17 00:00:00 2001 From: TYuan0816 Date: Wed, 24 Jan 2024 20:50:10 +0800 Subject: [PATCH 2/5] Debug After Golangci-Lint Run on AUSF --- go.mod | 1 - internal/context/context.go | 4 +- internal/sbi/consumer/nf_discovery.go | 4 +- internal/sbi/consumer/nf_management.go | 7 +- internal/sbi/producer/functions.go | 8 +- internal/sbi/producer/ue_authentication.go | 8 +- internal/sbi/sorprotection/routers.go | 12 ++- internal/sbi/ueauthentication/routers.go | 10 +++ internal/sbi/upuprotection/routers.go | 10 +++ internal/util/router_auth_check.go | 33 ++++++++ internal/util/router_auth_check_test.go | 91 ++++++++++++++++++++++ 11 files changed, 179 insertions(+), 9 deletions(-) diff --git a/go.mod b/go.mod index 69002dd..c252fdc 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,6 @@ require ( github.com/antihax/optional v1.0.0 github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d github.com/bronze1man/radius v0.0.0-20190516032554-afd8baec892d - github.com/free5gc/openapi v1.0.7-0.20231216094313-e15a4ff046f6 github.com/free5gc/openapi v1.0.7-0.20240117084712-52ad99299693 github.com/free5gc/util v1.0.5-0.20231205080047-308f623d6808 github.com/gin-gonic/gin v1.9.1 diff --git a/internal/context/context.go b/internal/context/context.go index b0c226c..347222b 100644 --- a/internal/context/context.go +++ b/internal/context/context.go @@ -167,14 +167,14 @@ func (a *AUSFContext) GetSelfID() string { return a.NfId } -func (c *AUSFContext) GetTokenCtx(scope string, targetNF model.NfType) ( +func (c *AUSFContext) GetTokenCtx(scope string, targetNF models.NfType) ( context.Context, *models.ProblemDetails, error, ) { if !c.OAuth2Required { return context.TODO(), nil, nil } return oauth.GetTokenCtx(models.NfType_AUSF, targetNF, - c.NfID, c.NrfUri, scope) + c.NfId, c.NrfUri, scope) } func (c *AUSFContext) AuthorizationCheck(token, serviceName string) error { diff --git a/internal/sbi/consumer/nf_discovery.go b/internal/sbi/consumer/nf_discovery.go index 0c40e25..cbd2f45 100644 --- a/internal/sbi/consumer/nf_discovery.go +++ b/internal/sbi/consumer/nf_discovery.go @@ -22,8 +22,8 @@ func SendSearchNFInstances(nrfUri string, targetNfType, requestNfType models.NfT configuration.SetBasePath(nrfUri) client := Nnrf_NFDiscovery.NewAPIClient(configuration) - result, rsp, rspErr := client.NFInstancesStoreApi.SearchNFInstances(ctx, - targetNfType, requestNfType, ¶m) + result, rsp, rspErr := client.NFInstancesStoreApi.SearchNFInstances(ctx, targetNfType, requestNfType, ¶m) + if rspErr != nil { return nil, fmt.Errorf("NFInstancesStoreApi Response error: %+w", rspErr) } diff --git a/internal/sbi/consumer/nf_management.go b/internal/sbi/consumer/nf_management.go index 588b27d..ff32506 100644 --- a/internal/sbi/consumer/nf_management.go +++ b/internal/sbi/consumer/nf_management.go @@ -40,9 +40,14 @@ func SendRegisterNFInstance(nrfUri, nfInstanceId string, profile models.NfProfil configuration.SetBasePath(nrfUri) client := Nnrf_NFManagement.NewAPIClient(configuration) + ctx, _, err := ausf_context.GetSelf().GetTokenCtx("nnrf-nfm", models.NfType_NRF) + if err != nil { + return "", "", err + } + var res *http.Response for { - nf, resTmp, err := client.NFInstanceIDDocumentApi.RegisterNFInstance(context.TODO(), nfInstanceId, profile) + nf, resTmp, err := client.NFInstanceIDDocumentApi.RegisterNFInstance(ctx, nfInstanceId, profile) if err != nil || resTmp == nil { logger.ConsumerLog.Errorf("AUSF register to NRF Error[%v]", err) time.Sleep(2 * time.Second) diff --git a/internal/sbi/producer/functions.go b/internal/sbi/producer/functions.go index 2999659..03ed8a6 100644 --- a/internal/sbi/producer/functions.go +++ b/internal/sbi/producer/functions.go @@ -372,7 +372,13 @@ func sendAuthResultToUDM(id string, authType models.AuthType, success bool, serv authEvent.NfInstanceId = self.GetSelfID() client := createClientToUdmUeau(udmUrl) - _, rsp, confirmAuthErr := client.ConfirmAuthApi.ConfirmAuth(context.Background(), id, authEvent) + + ctx, _, err := ausf_context.GetSelf().GetTokenCtx("nudm-ueau", models.NfType_UDM) + if err != nil { + return err + } + + _, rsp, confirmAuthErr := client.ConfirmAuthApi.ConfirmAuth(ctx, id, authEvent) defer func() { if rspCloseErr := rsp.Body.Close(); rspCloseErr != nil { logger.ConsumerLog.Errorf("ConfirmAuth Response cannot close: %v", rspCloseErr) diff --git a/internal/sbi/producer/ue_authentication.go b/internal/sbi/producer/ue_authentication.go index 0fbf190..d3837a0 100644 --- a/internal/sbi/producer/ue_authentication.go +++ b/internal/sbi/producer/ue_authentication.go @@ -124,7 +124,13 @@ func UeAuthPostRequestProcedure(updateAuthenticationInfo models.AuthenticationIn udmUrl := getUdmUrl(self.NrfUri) client := createClientToUdmUeau(udmUrl) - authInfoResult, rsp, err := client.GenerateAuthDataApi.GenerateAuthData(context.Background(), supiOrSuci, authInfoReq) + + ctx, _, err := ausf_context.GetSelf().GetTokenCtx("nudm-ueau", models.NfType_UDM) + if err != nil { + return nil, "", nil + } + + authInfoResult, rsp, err := client.GenerateAuthDataApi.GenerateAuthData(ctx, supiOrSuci, authInfoReq) if err != nil { logger.UeAuthLog.Infoln(err.Error()) var problemDetails models.ProblemDetails diff --git a/internal/sbi/sorprotection/routers.go b/internal/sbi/sorprotection/routers.go index 88f63ae..18640b9 100644 --- a/internal/sbi/sorprotection/routers.go +++ b/internal/sbi/sorprotection/routers.go @@ -12,14 +12,19 @@ package sorprotection import ( "net/http" "strings" - + "github.com/gin-gonic/gin" + ausf_context "github.com/free5gc/ausf/internal/context" "github.com/free5gc/ausf/internal/logger" + "github.com/free5gc/ausf/internal/util" "github.com/free5gc/ausf/pkg/factory" + "github.com/free5gc/openapi/models" logger_util "github.com/free5gc/util/logger" ) +const serviceName string = string(models.ServiceName_NAUSF_SORPROTECTION) + // Route is the information for every URI. type Route struct { // Name is the name of this Route. @@ -45,6 +50,11 @@ func NewRouter() *gin.Engine { func AddService(engine *gin.Engine) *gin.RouterGroup { group := engine.Group(factory.AusfSorprotectionResUriPrefix) + routerAuthorizationCheck := util.NewRouterAuthorizationCheck(serviceName) + group.Use(func(c *gin.Context) { + routerAuthorizationCheck.Check(c, ausf_context.GetSelf()) + }) + for _, route := range routes { switch route.Method { case "GET": diff --git a/internal/sbi/ueauthentication/routers.go b/internal/sbi/ueauthentication/routers.go index cbf572e..845ac7d 100644 --- a/internal/sbi/ueauthentication/routers.go +++ b/internal/sbi/ueauthentication/routers.go @@ -15,11 +15,16 @@ import ( "github.com/gin-gonic/gin" + ausf_context "github.com/free5gc/ausf/internal/context" "github.com/free5gc/ausf/internal/logger" + "github.com/free5gc/ausf/internal/util" "github.com/free5gc/ausf/pkg/factory" + "github.com/free5gc/openapi/models" logger_util "github.com/free5gc/util/logger" ) +const serviceName string = string(models.ServiceName_NAUSF_AUTH) + // Route is the information for every URI. type Route struct { // Name is the name of this Route. @@ -45,6 +50,11 @@ func NewRouter() *gin.Engine { func AddService(engine *gin.Engine) *gin.RouterGroup { group := engine.Group(factory.AusfAuthResUriPrefix) + routerAuthorizationCheck := util.NewRouterAuthorizationCheck(serviceName) + group.Use(func(c *gin.Context) { + routerAuthorizationCheck.Check(c, ausf_context.GetSelf()) + }) + for _, route := range routes { switch route.Method { case "GET": diff --git a/internal/sbi/upuprotection/routers.go b/internal/sbi/upuprotection/routers.go index f439c84..ad9461e 100644 --- a/internal/sbi/upuprotection/routers.go +++ b/internal/sbi/upuprotection/routers.go @@ -15,11 +15,16 @@ import ( "github.com/gin-gonic/gin" + ausf_context "github.com/free5gc/ausf/internal/context" "github.com/free5gc/ausf/internal/logger" + "github.com/free5gc/ausf/internal/util" "github.com/free5gc/ausf/pkg/factory" + "github.com/free5gc/openapi/models" logger_util "github.com/free5gc/util/logger" ) +const serviceName string = string(models.ServiceName_NAUSF_UPUPROTECTION) + // Route is the information for every URI. type Route struct { // Name is the name of this Route. @@ -45,6 +50,11 @@ func NewRouter() *gin.Engine { func AddService(engine *gin.Engine) *gin.RouterGroup { group := engine.Group(factory.AusfAuthResUriPrefix) + routerAuthorizationCheck := util.NewRouterAuthorizationCheck(serviceName) + group.Use(func(c *gin.Context) { + routerAuthorizationCheck.Check(c, ausf_context.GetSelf()) + }) + for _, route := range routes { switch route.Method { case "GET": diff --git a/internal/util/router_auth_check.go b/internal/util/router_auth_check.go index e69de29..88ea59a 100644 --- a/internal/util/router_auth_check.go +++ b/internal/util/router_auth_check.go @@ -0,0 +1,33 @@ +package util + +import ( + "net/http" + + "github.com/gin-gonic/gin" + +ausf_context "github.com/free5gc/ausf/internal/context" + "github.com/free5gc/ausf/internal/logger" +) + +type RouterAuthorizationCheck struct { + serviceName string +} + +func NewRouterAuthorizationCheck(serviceName string) *RouterAuthorizationCheck { + return &RouterAuthorizationCheck{ + serviceName: serviceName, + } +} + +func (rac *RouterAuthorizationCheck) Check(c *gin.Context, ausfContext ausf_context.NFContext) { + token := c.Request.Header.Get("Authorization") + err := ausfContext.AuthorizationCheck(token, rac.serviceName) + if err != nil { + logger.UtilLog.Debugf("RouterAuthorizationCheck: Check Unauthorized: %s", err.Error()) + c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()}) + c.Abort() + return + } + + logger.UtilLog.Debugf("RouterAuthorizationCheck: Check Authorized") +} \ No newline at end of file diff --git a/internal/util/router_auth_check_test.go b/internal/util/router_auth_check_test.go index e69de29..bc0de90 100644 --- a/internal/util/router_auth_check_test.go +++ b/internal/util/router_auth_check_test.go @@ -0,0 +1,91 @@ +package util + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/pkg/errors" +) + +const ( + Valid = "valid" + Invalid = "invalid" +) + +type mockAUSFContext struct{} + +func newMockAUSFContext() *mockAUSFContext { + return &mockAUSFContext{} +} + +func (m *mockAUSFContext) AuthorizationCheck(token string, serviceName string) error { + if token == Valid { + return nil + } + + return errors.New("invalid token") +} + +func TestRouterAuthorizationCheck_Check(t *testing.T) { + // Mock gin.Context + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + + var err error + c.Request, err = http.NewRequest("GET", "/", nil) + if err != nil { + t.Errorf("error on http request: %+v", err) + } + + type Args struct { + token string + } + type Want struct { + statusCode int + } + + tests := []struct { + name string + args Args + want Want + }{ + { + name: "Valid Token", + args: Args{ + token: Valid, + }, + want: Want{ + statusCode: http.StatusOK, + }, + }, + { + name: "Invalid Token", + args: Args{ + token: Invalid, + }, + want: Want{ + statusCode: http.StatusUnauthorized, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w = httptest.NewRecorder() + c, _ = gin.CreateTestContext(w) + c.Request, err = http.NewRequest("GET", "/", nil) + if err != nil { + t.Errorf("error on http request: %+v", err) + } + c.Request.Header.Set("Authorization", tt.args.token) + + rac := NewRouterAuthorizationCheck("testService") + rac.Check(c, newMockAUSFContext()) + if w.Code != tt.want.statusCode { + t.Errorf("StatusCode should be %d, but got %d", tt.want.statusCode, w.Code) + } + }) + } +} \ No newline at end of file From e9ba65059f5c09355b9fcabbd2a557d37b641666 Mon Sep 17 00:00:00 2001 From: TYuan0816 Date: Fri, 26 Jan 2024 10:53:32 +0800 Subject: [PATCH 3/5] Debug Linter Error --- internal/sbi/consumer/nf_discovery.go | 3 ++- internal/sbi/consumer/nf_management.go | 2 +- internal/sbi/producer/functions.go | 2 +- internal/sbi/producer/ue_authentication.go | 2 +- pkg/factory/config.go | 28 +++++++++++----------- 5 files changed, 19 insertions(+), 18 deletions(-) diff --git a/internal/sbi/consumer/nf_discovery.go b/internal/sbi/consumer/nf_discovery.go index cbd2f45..1126c4f 100644 --- a/internal/sbi/consumer/nf_discovery.go +++ b/internal/sbi/consumer/nf_discovery.go @@ -22,7 +22,8 @@ func SendSearchNFInstances(nrfUri string, targetNfType, requestNfType models.NfT configuration.SetBasePath(nrfUri) client := Nnrf_NFDiscovery.NewAPIClient(configuration) - result, rsp, rspErr := client.NFInstancesStoreApi.SearchNFInstances(ctx, targetNfType, requestNfType, ¶m) + result, rsp, rspErr := client.NFInstancesStoreApi.SearchNFInstances(ctx, + targetNfType, requestNfType, ¶m) if rspErr != nil { return nil, fmt.Errorf("NFInstancesStoreApi Response error: %+w", rspErr) diff --git a/internal/sbi/consumer/nf_management.go b/internal/sbi/consumer/nf_management.go index ff32506..3d3d6e3 100644 --- a/internal/sbi/consumer/nf_management.go +++ b/internal/sbi/consumer/nf_management.go @@ -1,7 +1,7 @@ package consumer import ( - "context" + "fmt" "net/http" "strings" diff --git a/internal/sbi/producer/functions.go b/internal/sbi/producer/functions.go index 03ed8a6..59498a1 100644 --- a/internal/sbi/producer/functions.go +++ b/internal/sbi/producer/functions.go @@ -1,7 +1,7 @@ package producer import ( - "context" + "crypto/hmac" "crypto/sha256" "encoding/base64" diff --git a/internal/sbi/producer/ue_authentication.go b/internal/sbi/producer/ue_authentication.go index d3837a0..dd2a01c 100644 --- a/internal/sbi/producer/ue_authentication.go +++ b/internal/sbi/producer/ue_authentication.go @@ -2,7 +2,7 @@ package producer import ( "bytes" - "context" + "crypto/sha256" "encoding/base64" "encoding/hex" diff --git a/pkg/factory/config.go b/pkg/factory/config.go index 2545100..983da78 100644 --- a/pkg/factory/config.go +++ b/pkg/factory/config.go @@ -153,8 +153,8 @@ func appendInvalid(err error) error { } func (c *Config) GetVersion() string { - c.RLock() - defer c.RUnlock() + c.RWMutex.RLock() + defer c.RWMutex.RUnlock() if c.Info.Version != "" { return c.Info.Version @@ -163,8 +163,8 @@ func (c *Config) GetVersion() string { } func (c *Config) SetLogEnable(enable bool) { - c.Lock() - defer c.Unlock() + c.RWMutex.Lock() + defer c.RWMutex.Unlock() if c.Logger == nil { logger.CfgLog.Warnf("Logger should not be nil") @@ -178,8 +178,8 @@ func (c *Config) SetLogEnable(enable bool) { } func (c *Config) SetLogLevel(level string) { - c.Lock() - defer c.Unlock() + c.RWMutex.Lock() + defer c.RWMutex.Unlock() if c.Logger == nil { logger.CfgLog.Warnf("Logger should not be nil") @@ -192,8 +192,8 @@ func (c *Config) SetLogLevel(level string) { } func (c *Config) SetLogReportCaller(reportCaller bool) { - c.Lock() - defer c.Unlock() + c.RWMutex.Lock() + defer c.RWMutex.Unlock() if c.Logger == nil { logger.CfgLog.Warnf("Logger should not be nil") @@ -207,8 +207,8 @@ func (c *Config) SetLogReportCaller(reportCaller bool) { } func (c *Config) GetLogEnable() bool { - c.RLock() - defer c.RUnlock() + c.RWMutex.RLock() + defer c.RWMutex.RUnlock() if c.Logger == nil { logger.CfgLog.Warnf("Logger should not be nil") return false @@ -217,8 +217,8 @@ func (c *Config) GetLogEnable() bool { } func (c *Config) GetLogLevel() string { - c.RLock() - defer c.RUnlock() + c.RWMutex.RLock() + defer c.RWMutex.RUnlock() if c.Logger == nil { logger.CfgLog.Warnf("Logger should not be nil") return "info" @@ -227,8 +227,8 @@ func (c *Config) GetLogLevel() string { } func (c *Config) GetLogReportCaller() bool { - c.RLock() - defer c.RUnlock() + c.RWMutex.RLock() + defer c.RWMutex.RUnlock() if c.Logger == nil { logger.CfgLog.Warnf("Logger should not be nil") return false From ae0a72438c7195027e7252ea3a5f6df7f6038964 Mon Sep 17 00:00:00 2001 From: TYuan0816 Date: Sat, 27 Jan 2024 14:25:38 +0800 Subject: [PATCH 4/5] Fix: fix linter error --- go.mod | 2 +- internal/context/context.go | 3 +-- internal/logger/logger.go | 2 +- internal/sbi/consumer/nf_management.go | 1 - internal/sbi/producer/functions.go | 1 - internal/sbi/producer/ue_authentication.go | 1 - internal/sbi/sorprotection/routers.go | 2 +- internal/util/router_auth_check.go | 4 ++-- internal/util/router_auth_check_test.go | 2 +- 9 files changed, 7 insertions(+), 11 deletions(-) diff --git a/go.mod b/go.mod index c252fdc..23b08a7 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/gin-gonic/gin v1.9.1 github.com/google/gopacket v1.1.19 github.com/google/uuid v1.3.0 + github.com/pkg/errors v0.9.1 github.com/sirupsen/logrus v1.8.1 github.com/stretchr/testify v1.8.3 github.com/urfave/cli v1.22.5 @@ -39,7 +40,6 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.0.8 // indirect - github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/russross/blackfriday/v2 v2.0.1 // indirect github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect diff --git a/internal/context/context.go b/internal/context/context.go index 347222b..cafb81b 100644 --- a/internal/context/context.go +++ b/internal/context/context.go @@ -104,7 +104,6 @@ func Init() { InitAusfContext(&ausfContext) } - type NFContext interface { AuthorizationCheck(token, serviceName string) error } @@ -185,4 +184,4 @@ func (c *AUSFContext) AuthorizationCheck(token, serviceName string) error { logger.UtilLog.Debugf("AUSFContext::AuthorizationCheck: token[%s] serviceName[%s]\n", token, serviceName) return oauth.VerifyOAuth(token, serviceName, c.NrfCertPem) -} \ No newline at end of file +} diff --git a/internal/logger/logger.go b/internal/logger/logger.go index b2d3ce3..90993e0 100644 --- a/internal/logger/logger.go +++ b/internal/logger/logger.go @@ -18,7 +18,7 @@ var ( UeAuthLog *logrus.Entry Auth5gAkaLog *logrus.Entry AuthELog *logrus.Entry - UtilLog *logrus.Entry + UtilLog *logrus.Entry ) func init() { diff --git a/internal/sbi/consumer/nf_management.go b/internal/sbi/consumer/nf_management.go index 3d3d6e3..5f3e8d4 100644 --- a/internal/sbi/consumer/nf_management.go +++ b/internal/sbi/consumer/nf_management.go @@ -1,7 +1,6 @@ package consumer import ( - "fmt" "net/http" "strings" diff --git a/internal/sbi/producer/functions.go b/internal/sbi/producer/functions.go index 59498a1..35d5a2c 100644 --- a/internal/sbi/producer/functions.go +++ b/internal/sbi/producer/functions.go @@ -1,7 +1,6 @@ package producer import ( - "crypto/hmac" "crypto/sha256" "encoding/base64" diff --git a/internal/sbi/producer/ue_authentication.go b/internal/sbi/producer/ue_authentication.go index dd2a01c..36831f1 100644 --- a/internal/sbi/producer/ue_authentication.go +++ b/internal/sbi/producer/ue_authentication.go @@ -2,7 +2,6 @@ package producer import ( "bytes" - "crypto/sha256" "encoding/base64" "encoding/hex" diff --git a/internal/sbi/sorprotection/routers.go b/internal/sbi/sorprotection/routers.go index 18640b9..a62cf6d 100644 --- a/internal/sbi/sorprotection/routers.go +++ b/internal/sbi/sorprotection/routers.go @@ -12,7 +12,7 @@ package sorprotection import ( "net/http" "strings" - + "github.com/gin-gonic/gin" ausf_context "github.com/free5gc/ausf/internal/context" diff --git a/internal/util/router_auth_check.go b/internal/util/router_auth_check.go index 88ea59a..37c571b 100644 --- a/internal/util/router_auth_check.go +++ b/internal/util/router_auth_check.go @@ -5,7 +5,7 @@ import ( "github.com/gin-gonic/gin" -ausf_context "github.com/free5gc/ausf/internal/context" + ausf_context "github.com/free5gc/ausf/internal/context" "github.com/free5gc/ausf/internal/logger" ) @@ -30,4 +30,4 @@ func (rac *RouterAuthorizationCheck) Check(c *gin.Context, ausfContext ausf_cont } logger.UtilLog.Debugf("RouterAuthorizationCheck: Check Authorized") -} \ No newline at end of file +} diff --git a/internal/util/router_auth_check_test.go b/internal/util/router_auth_check_test.go index bc0de90..cd98841 100644 --- a/internal/util/router_auth_check_test.go +++ b/internal/util/router_auth_check_test.go @@ -88,4 +88,4 @@ func TestRouterAuthorizationCheck_Check(t *testing.T) { } }) } -} \ No newline at end of file +} From b68ecce7efda567e900d5e99ab9e21246400abb6 Mon Sep 17 00:00:00 2001 From: CTFang Date: Tue, 6 Feb 2024 13:34:37 +0000 Subject: [PATCH 5/5] Fix: use models serviceName --- internal/context/context.go | 10 +++++----- internal/sbi/consumer/nf_discovery.go | 2 +- internal/sbi/consumer/nf_management.go | 4 ++-- internal/sbi/producer/functions.go | 2 +- internal/sbi/producer/ue_authentication.go | 2 +- internal/sbi/sorprotection/routers.go | 4 +--- internal/sbi/ueauthentication/routers.go | 4 +--- internal/sbi/upuprotection/routers.go | 4 +--- internal/util/router_auth_check.go | 5 +++-- internal/util/router_auth_check_test.go | 6 ++++-- 10 files changed, 20 insertions(+), 23 deletions(-) diff --git a/internal/context/context.go b/internal/context/context.go index cafb81b..017ac74 100644 --- a/internal/context/context.go +++ b/internal/context/context.go @@ -105,7 +105,7 @@ func Init() { } type NFContext interface { - AuthorizationCheck(token, serviceName string) error + AuthorizationCheck(token string, serviceName models.ServiceName) error } var _ NFContext = &AUSFContext{} @@ -166,22 +166,22 @@ func (a *AUSFContext) GetSelfID() string { return a.NfId } -func (c *AUSFContext) GetTokenCtx(scope string, targetNF models.NfType) ( +func (c *AUSFContext) GetTokenCtx(serviceName models.ServiceName, targetNF models.NfType) ( context.Context, *models.ProblemDetails, error, ) { if !c.OAuth2Required { return context.TODO(), nil, nil } return oauth.GetTokenCtx(models.NfType_AUSF, targetNF, - c.NfId, c.NrfUri, scope) + c.NfId, c.NrfUri, string(serviceName)) } -func (c *AUSFContext) AuthorizationCheck(token, serviceName string) error { +func (c *AUSFContext) AuthorizationCheck(token string, serviceName models.ServiceName) error { if !c.OAuth2Required { logger.UtilLog.Debugf("AUSFContext::AuthorizationCheck: OAuth2 not required\n") return nil } logger.UtilLog.Debugf("AUSFContext::AuthorizationCheck: token[%s] serviceName[%s]\n", token, serviceName) - return oauth.VerifyOAuth(token, serviceName, c.NrfCertPem) + return oauth.VerifyOAuth(token, string(serviceName), c.NrfCertPem) } diff --git a/internal/sbi/consumer/nf_discovery.go b/internal/sbi/consumer/nf_discovery.go index 1126c4f..3c97013 100644 --- a/internal/sbi/consumer/nf_discovery.go +++ b/internal/sbi/consumer/nf_discovery.go @@ -13,7 +13,7 @@ import ( func SendSearchNFInstances(nrfUri string, targetNfType, requestNfType models.NfType, param Nnrf_NFDiscovery.SearchNFInstancesParamOpts, ) (*models.SearchResult, error) { - ctx, _, err := ausf_context.GetSelf().GetTokenCtx("nnrf-disc", models.NfType_NRF) + ctx, _, err := ausf_context.GetSelf().GetTokenCtx(models.ServiceName_NNRF_DISC, models.NfType_NRF) if err != nil { return nil, err } diff --git a/internal/sbi/consumer/nf_management.go b/internal/sbi/consumer/nf_management.go index 5f3e8d4..816ae73 100644 --- a/internal/sbi/consumer/nf_management.go +++ b/internal/sbi/consumer/nf_management.go @@ -39,7 +39,7 @@ func SendRegisterNFInstance(nrfUri, nfInstanceId string, profile models.NfProfil configuration.SetBasePath(nrfUri) client := Nnrf_NFManagement.NewAPIClient(configuration) - ctx, _, err := ausf_context.GetSelf().GetTokenCtx("nnrf-nfm", models.NfType_NRF) + ctx, _, err := ausf_context.GetSelf().GetTokenCtx(models.ServiceName_NNRF_NFM, models.NfType_NRF) if err != nil { return "", "", err } @@ -94,7 +94,7 @@ func SendRegisterNFInstance(nrfUri, nfInstanceId string, profile models.NfProfil func SendDeregisterNFInstance() (*models.ProblemDetails, error) { logger.ConsumerLog.Infof("Send Deregister NFInstance") - ctx, pd, err := ausf_context.GetSelf().GetTokenCtx("nnrf-nfm", models.NfType_NRF) + ctx, pd, err := ausf_context.GetSelf().GetTokenCtx(models.ServiceName_NNRF_NFM, models.NfType_NRF) if err != nil { return pd, err } diff --git a/internal/sbi/producer/functions.go b/internal/sbi/producer/functions.go index 35d5a2c..00aba64 100644 --- a/internal/sbi/producer/functions.go +++ b/internal/sbi/producer/functions.go @@ -372,7 +372,7 @@ func sendAuthResultToUDM(id string, authType models.AuthType, success bool, serv client := createClientToUdmUeau(udmUrl) - ctx, _, err := ausf_context.GetSelf().GetTokenCtx("nudm-ueau", models.NfType_UDM) + ctx, _, err := ausf_context.GetSelf().GetTokenCtx(models.ServiceName_NUDM_UEAU, models.NfType_UDM) if err != nil { return err } diff --git a/internal/sbi/producer/ue_authentication.go b/internal/sbi/producer/ue_authentication.go index 36831f1..29291c7 100644 --- a/internal/sbi/producer/ue_authentication.go +++ b/internal/sbi/producer/ue_authentication.go @@ -124,7 +124,7 @@ func UeAuthPostRequestProcedure(updateAuthenticationInfo models.AuthenticationIn udmUrl := getUdmUrl(self.NrfUri) client := createClientToUdmUeau(udmUrl) - ctx, _, err := ausf_context.GetSelf().GetTokenCtx("nudm-ueau", models.NfType_UDM) + ctx, _, err := ausf_context.GetSelf().GetTokenCtx(models.ServiceName_NUDM_UEAU, models.NfType_UDM) if err != nil { return nil, "", nil } diff --git a/internal/sbi/sorprotection/routers.go b/internal/sbi/sorprotection/routers.go index a62cf6d..45264b2 100644 --- a/internal/sbi/sorprotection/routers.go +++ b/internal/sbi/sorprotection/routers.go @@ -23,8 +23,6 @@ import ( logger_util "github.com/free5gc/util/logger" ) -const serviceName string = string(models.ServiceName_NAUSF_SORPROTECTION) - // Route is the information for every URI. type Route struct { // Name is the name of this Route. @@ -50,7 +48,7 @@ func NewRouter() *gin.Engine { func AddService(engine *gin.Engine) *gin.RouterGroup { group := engine.Group(factory.AusfSorprotectionResUriPrefix) - routerAuthorizationCheck := util.NewRouterAuthorizationCheck(serviceName) + routerAuthorizationCheck := util.NewRouterAuthorizationCheck(models.ServiceName_NAUSF_SORPROTECTION) group.Use(func(c *gin.Context) { routerAuthorizationCheck.Check(c, ausf_context.GetSelf()) }) diff --git a/internal/sbi/ueauthentication/routers.go b/internal/sbi/ueauthentication/routers.go index 845ac7d..948f8db 100644 --- a/internal/sbi/ueauthentication/routers.go +++ b/internal/sbi/ueauthentication/routers.go @@ -23,8 +23,6 @@ import ( logger_util "github.com/free5gc/util/logger" ) -const serviceName string = string(models.ServiceName_NAUSF_AUTH) - // Route is the information for every URI. type Route struct { // Name is the name of this Route. @@ -50,7 +48,7 @@ func NewRouter() *gin.Engine { func AddService(engine *gin.Engine) *gin.RouterGroup { group := engine.Group(factory.AusfAuthResUriPrefix) - routerAuthorizationCheck := util.NewRouterAuthorizationCheck(serviceName) + routerAuthorizationCheck := util.NewRouterAuthorizationCheck(models.ServiceName_NAUSF_AUTH) group.Use(func(c *gin.Context) { routerAuthorizationCheck.Check(c, ausf_context.GetSelf()) }) diff --git a/internal/sbi/upuprotection/routers.go b/internal/sbi/upuprotection/routers.go index ad9461e..f3affde 100644 --- a/internal/sbi/upuprotection/routers.go +++ b/internal/sbi/upuprotection/routers.go @@ -23,8 +23,6 @@ import ( logger_util "github.com/free5gc/util/logger" ) -const serviceName string = string(models.ServiceName_NAUSF_UPUPROTECTION) - // Route is the information for every URI. type Route struct { // Name is the name of this Route. @@ -50,7 +48,7 @@ func NewRouter() *gin.Engine { func AddService(engine *gin.Engine) *gin.RouterGroup { group := engine.Group(factory.AusfAuthResUriPrefix) - routerAuthorizationCheck := util.NewRouterAuthorizationCheck(serviceName) + routerAuthorizationCheck := util.NewRouterAuthorizationCheck(models.ServiceName_NAUSF_UPUPROTECTION) group.Use(func(c *gin.Context) { routerAuthorizationCheck.Check(c, ausf_context.GetSelf()) }) diff --git a/internal/util/router_auth_check.go b/internal/util/router_auth_check.go index 37c571b..754fc83 100644 --- a/internal/util/router_auth_check.go +++ b/internal/util/router_auth_check.go @@ -7,13 +7,14 @@ import ( ausf_context "github.com/free5gc/ausf/internal/context" "github.com/free5gc/ausf/internal/logger" + "github.com/free5gc/openapi/models" ) type RouterAuthorizationCheck struct { - serviceName string + serviceName models.ServiceName } -func NewRouterAuthorizationCheck(serviceName string) *RouterAuthorizationCheck { +func NewRouterAuthorizationCheck(serviceName models.ServiceName) *RouterAuthorizationCheck { return &RouterAuthorizationCheck{ serviceName: serviceName, } diff --git a/internal/util/router_auth_check_test.go b/internal/util/router_auth_check_test.go index cd98841..df1612c 100644 --- a/internal/util/router_auth_check_test.go +++ b/internal/util/router_auth_check_test.go @@ -7,6 +7,8 @@ import ( "github.com/gin-gonic/gin" "github.com/pkg/errors" + + "github.com/free5gc/openapi/models" ) const ( @@ -20,7 +22,7 @@ func newMockAUSFContext() *mockAUSFContext { return &mockAUSFContext{} } -func (m *mockAUSFContext) AuthorizationCheck(token string, serviceName string) error { +func (m *mockAUSFContext) AuthorizationCheck(token string, serviceName models.ServiceName) error { if token == Valid { return nil } @@ -81,7 +83,7 @@ func TestRouterAuthorizationCheck_Check(t *testing.T) { } c.Request.Header.Set("Authorization", tt.args.token) - rac := NewRouterAuthorizationCheck("testService") + rac := NewRouterAuthorizationCheck(models.ServiceName("testService")) rac.Check(c, newMockAUSFContext()) if w.Code != tt.want.statusCode { t.Errorf("StatusCode should be %d, but got %d", tt.want.statusCode, w.Code)