From 293235bcfee930e089dec894327bf90448bd683a Mon Sep 17 00:00:00 2001 From: pf-lin Date: Sat, 13 Jan 2024 13:14:40 +0800 Subject: [PATCH 1/8] Add OAuth2 on SMF --- internal/context/context.go | 11 +++++++++ .../sbi/consumer/nsmf_pdusession_callback.go | 9 ++++++-- internal/sbi/consumer/sm_policy.go | 23 +++++++++++++++---- internal/sbi/eventexposure/api_default.go | 20 ++++++++++++++++ internal/sbi/eventexposure/routers.go | 6 +++++ .../api_individual_pdu_session_hsmf.go | 10 ++++++++ .../pdusession/api_individual_sm_context.go | 17 ++++++++++++++ .../pdusession/api_pdu_sessions_collection.go | 5 ++++ .../pdusession/api_sm_contexts_collection.go | 6 +++++ internal/sbi/pdusession/routers.go | 6 +++++ 10 files changed, 107 insertions(+), 6 deletions(-) diff --git a/internal/context/context.go b/internal/context/context.go index 0282cfb8..1cee3ffc 100644 --- a/internal/context/context.go +++ b/internal/context/context.go @@ -297,3 +297,14 @@ func (c *SMFContext) GetTokenCtx(scope, targetNF string) ( return oauth.GetTokenCtx(models.NfType_SMF, c.NfInstanceID, c.NrfUri, scope, targetNF) } + +func (context *SMFContext) AuthorizationCheck(token, serviceName string) error { + if !context.OAuth2Required { + return nil + } + err := oauth.VerifyOAuth(token, serviceName, context.NrfCertPem) + if err != nil { + return err + } + return nil +} diff --git a/internal/sbi/consumer/nsmf_pdusession_callback.go b/internal/sbi/consumer/nsmf_pdusession_callback.go index 22751c64..b7942e07 100644 --- a/internal/sbi/consumer/nsmf_pdusession_callback.go +++ b/internal/sbi/consumer/nsmf_pdusession_callback.go @@ -1,12 +1,12 @@ package consumer import ( - "context" "net/http" "github.com/free5gc/openapi" "github.com/free5gc/openapi/Nsmf_PDUSession" "github.com/free5gc/openapi/models" + smf_context "github.com/free5gc/smf/internal/context" "github.com/free5gc/smf/internal/logger" ) @@ -19,10 +19,15 @@ func SendSMContextStatusNotification(uri string) (*models.ProblemDetails, error) configuration := Nsmf_PDUSession.NewConfiguration() client := Nsmf_PDUSession.NewAPIClient(configuration) + ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nsmf-pdusession", "SMF") + if err != nil { + return pd, err + } + logger.CtxLog.Infoln("[SMF] Send SMContext Status Notification") httpResp, localErr := client. IndividualSMContextNotificationApi. - SMContextNotification(context.Background(), uri, request) + SMContextNotification(ctx, uri, request) if localErr == nil { if httpResp.StatusCode != http.StatusNoContent { diff --git a/internal/sbi/consumer/sm_policy.go b/internal/sbi/consumer/sm_policy.go index 830a159c..15d6370b 100644 --- a/internal/sbi/consumer/sm_policy.go +++ b/internal/sbi/consumer/sm_policy.go @@ -1,7 +1,6 @@ package consumer import ( - "context" "fmt" "net" "regexp" @@ -48,10 +47,15 @@ func SendSMPolicyAssociationCreate(smContext *smf_context.SMContext) (string, *m } smPolicyData.SuppFeat = "F" + ctx, _, err := smf_context.GetSelf().GetTokenCtx("npcf-smpolicycontrol", "PCF") + if err != nil { + return "", nil, err + } + var smPolicyID string var smPolicyDecision *models.SmPolicyDecision smPolicyDecisionFromPCF, httpRsp, err := smContext.SMPolicyClient.DefaultApi. - SmPoliciesPost(context.Background(), smPolicyData) + SmPoliciesPost(ctx, smPolicyData) defer func() { if httpRsp != nil { if closeErr := httpRsp.Body.Close(); closeErr != nil { @@ -143,9 +147,15 @@ func SendSMPolicyAssociationUpdateByUERequestModification( updateSMPolicy.UeInitResReq.PackFiltInfo = append(updateSMPolicy.UeInitResReq.PackFiltInfo, *PackFiltInfo) } } + + ctx, _, err := smf_context.GetSelf().GetTokenCtx("npcf-smpolicycontrol", "PCF") + if err != nil { + return nil, err + } + var smPolicyDecision *models.SmPolicyDecision smPolicyDecisionFromPCF, rsp, err := smContext.SMPolicyClient. - DefaultApi.SmPoliciesSmPolicyIdUpdatePost(context.TODO(), smContext.SMPolicyID, updateSMPolicy) + DefaultApi.SmPoliciesSmPolicyIdUpdatePost(ctx, smContext.SMPolicyID, updateSMPolicy) defer func() { if rsp != nil { if closeErr := rsp.Body.Close(); closeErr != nil { @@ -364,8 +374,13 @@ func SendSMPolicyAssociationTermination(smContext *smf_context.SMContext) error return errors.Errorf("smContext not selected PCF") } + ctx, _, err := smf_context.GetSelf().GetTokenCtx("npcf-smpolicycontrol", "PCF") + if err != nil { + return err + } + rsp, err := smContext.SMPolicyClient.DefaultApi.SmPoliciesSmPolicyIdDeletePost( - context.Background(), smContext.SMPolicyID, models.SmPolicyDeleteData{}) + ctx, smContext.SMPolicyID, models.SmPolicyDeleteData{}) defer func() { if rsp != nil { if closeErr := rsp.Body.Close(); closeErr != nil { diff --git a/internal/sbi/eventexposure/api_default.go b/internal/sbi/eventexposure/api_default.go index 60b90b6d..7dacdca7 100644 --- a/internal/sbi/eventexposure/api_default.go +++ b/internal/sbi/eventexposure/api_default.go @@ -17,20 +17,40 @@ import ( // SubscriptionsPost - func SubscriptionsPost(c *gin.Context) { + auth_err := authorizationCheck(c) + if auth_err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) + return + } c.JSON(http.StatusOK, gin.H{}) } // SubscriptionsSubIdDelete - func SubscriptionsSubIdDelete(c *gin.Context) { + auth_err := authorizationCheck(c) + if auth_err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) + return + } c.JSON(http.StatusOK, gin.H{}) } // SubscriptionsSubIdGet - func SubscriptionsSubIdGet(c *gin.Context) { + auth_err := authorizationCheck(c) + if auth_err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) + return + } c.JSON(http.StatusOK, gin.H{}) } // SubscriptionsSubIdPut - func SubscriptionsSubIdPut(c *gin.Context) { + auth_err := authorizationCheck(c) + if auth_err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) + return + } c.JSON(http.StatusOK, gin.H{}) } diff --git a/internal/sbi/eventexposure/routers.go b/internal/sbi/eventexposure/routers.go index cbf67c07..cc9b53d5 100644 --- a/internal/sbi/eventexposure/routers.go +++ b/internal/sbi/eventexposure/routers.go @@ -15,6 +15,7 @@ import ( "github.com/gin-gonic/gin" + smf_context "github.com/free5gc/smf/internal/context" "github.com/free5gc/smf/internal/logger" "github.com/free5gc/smf/pkg/factory" logger_util "github.com/free5gc/util/logger" @@ -42,6 +43,11 @@ func NewRouter() *gin.Engine { return router } +func authorizationCheck(c *gin.Context) error { + token := c.Request.Header.Get("Authorization") + return smf_context.GetSelf().AuthorizationCheck(token, "nsmf-event-exposure") +} + func AddService(engine *gin.Engine) *gin.RouterGroup { group := engine.Group(factory.SmfEventExposureResUriPrefix) diff --git a/internal/sbi/pdusession/api_individual_pdu_session_hsmf.go b/internal/sbi/pdusession/api_individual_pdu_session_hsmf.go index b3a920e4..542d09ed 100644 --- a/internal/sbi/pdusession/api_individual_pdu_session_hsmf.go +++ b/internal/sbi/pdusession/api_individual_pdu_session_hsmf.go @@ -17,10 +17,20 @@ import ( // ReleasePduSession - Release func ReleasePduSession(c *gin.Context) { + auth_err := authorizationCheck(c) + if auth_err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) + return + } c.JSON(http.StatusOK, gin.H{}) } // UpdatePduSession - Update (initiated by V-SMF) func UpdatePduSession(c *gin.Context) { + auth_err := authorizationCheck(c) + if auth_err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) + return + } c.JSON(http.StatusOK, gin.H{}) } diff --git a/internal/sbi/pdusession/api_individual_sm_context.go b/internal/sbi/pdusession/api_individual_sm_context.go index 0987c839..722ab739 100644 --- a/internal/sbi/pdusession/api_individual_sm_context.go +++ b/internal/sbi/pdusession/api_individual_sm_context.go @@ -25,6 +25,12 @@ import ( // HTTPReleaseSmContext - Release SM Context func HTTPReleaseSmContext(c *gin.Context) { + auth_err := authorizationCheck(c) + if auth_err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) + return + } + logger.PduSessLog.Info("Receive Release SM Context Request") var request models.ReleaseSmContextRequest request.JsonData = new(models.SmContextReleaseData) @@ -54,11 +60,22 @@ func HTTPReleaseSmContext(c *gin.Context) { // RetrieveSmContext - Retrieve SM Context func RetrieveSmContext(c *gin.Context) { + auth_err := authorizationCheck(c) + if auth_err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) + return + } c.JSON(http.StatusOK, gin.H{}) } // HTTPUpdateSmContext - Update SM Context func HTTPUpdateSmContext(c *gin.Context) { + auth_err := authorizationCheck(c) + if auth_err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) + return + } + logger.PduSessLog.Info("Receive Update SM Context Request") var request models.UpdateSmContextRequest request.JsonData = new(models.SmContextUpdateData) diff --git a/internal/sbi/pdusession/api_pdu_sessions_collection.go b/internal/sbi/pdusession/api_pdu_sessions_collection.go index cf08d4c1..38f11b37 100644 --- a/internal/sbi/pdusession/api_pdu_sessions_collection.go +++ b/internal/sbi/pdusession/api_pdu_sessions_collection.go @@ -17,5 +17,10 @@ import ( // PostPduSessions - Create func PostPduSessions(c *gin.Context) { + auth_err := authorizationCheck(c) + if auth_err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) + return + } c.JSON(http.StatusOK, gin.H{}) } diff --git a/internal/sbi/pdusession/api_sm_contexts_collection.go b/internal/sbi/pdusession/api_sm_contexts_collection.go index 4f378b11..65852f46 100644 --- a/internal/sbi/pdusession/api_sm_contexts_collection.go +++ b/internal/sbi/pdusession/api_sm_contexts_collection.go @@ -24,6 +24,12 @@ import ( // HTTPPostSmContexts - Create SM Context func HTTPPostSmContexts(c *gin.Context) { + auth_err := authorizationCheck(c) + if auth_err != nil { + c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) + return + } + logger.PduSessLog.Info("Receive Create SM Context Request") var request models.PostSmContextsRequest diff --git a/internal/sbi/pdusession/routers.go b/internal/sbi/pdusession/routers.go index 61c5b226..5a0e578a 100644 --- a/internal/sbi/pdusession/routers.go +++ b/internal/sbi/pdusession/routers.go @@ -15,6 +15,7 @@ import ( "github.com/gin-gonic/gin" + smf_context "github.com/free5gc/smf/internal/context" "github.com/free5gc/smf/internal/logger" "github.com/free5gc/smf/pkg/factory" logger_util "github.com/free5gc/util/logger" @@ -42,6 +43,11 @@ func NewRouter() *gin.Engine { return router } +func authorizationCheck(c *gin.Context) error { + token := c.Request.Header.Get("Authorization") + return smf_context.GetSelf().AuthorizationCheck(token, "nsmf-pdusession") +} + func AddService(engine *gin.Engine) *gin.RouterGroup { group := engine.Group(factory.SmfPdusessionResUriPrefix) From 9b92113f7c5a7456ad38c7f31fc7e0e2e3423e2c Mon Sep 17 00:00:00 2001 From: pf-lin Date: Fri, 19 Jan 2024 14:39:27 +0000 Subject: [PATCH 2/8] Add util/oauth --- internal/util/oauth/router_auth_check.go | 33 +++++++ internal/util/oauth/router_auth_check_test.go | 91 +++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 internal/util/oauth/router_auth_check.go create mode 100644 internal/util/oauth/router_auth_check_test.go diff --git a/internal/util/oauth/router_auth_check.go b/internal/util/oauth/router_auth_check.go new file mode 100644 index 00000000..15a090b5 --- /dev/null +++ b/internal/util/oauth/router_auth_check.go @@ -0,0 +1,33 @@ +package util_oauth + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + smf_context "github.com/free5gc/smf/internal/context" + "github.com/free5gc/smf/internal/logger" +) + +type RouterAuthorizationCheck struct { + serviceName string +} + +func NewRouterAuthorizationCheck(serviceName string) *RouterAuthorizationCheck { + return &RouterAuthorizationCheck{ + serviceName: serviceName, + } +} + +func (rac *RouterAuthorizationCheck) Check(c *gin.Context, smfContext smf_context.NFContext) { + token := c.Request.Header.Get("Authorization") + err := smfContext.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/oauth/router_auth_check_test.go b/internal/util/oauth/router_auth_check_test.go new file mode 100644 index 00000000..9874386f --- /dev/null +++ b/internal/util/oauth/router_auth_check_test.go @@ -0,0 +1,91 @@ +package util_oauth + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/pkg/errors" +) + +const ( + Valid = "valid" + Invalid = "invalid" +) + +type mockSMFContext struct{} + +func newMockSMFContext() *mockSMFContext { + return &mockSMFContext{} +} + +func (m *mockSMFContext) 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, newMockSMFContext()) + 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 3af89521db0dd11d26dbbfe4ebc66a1c664e7475 Mon Sep 17 00:00:00 2001 From: pf-lin Date: Fri, 19 Jan 2024 14:42:52 +0000 Subject: [PATCH 3/8] Add feature of OAuth2: consumer & producer (Event Exposure and PDU Session) --- go.mod | 2 +- go.sum | 4 ++-- internal/context/context.go | 22 ++++++++++--------- internal/logger/logger.go | 2 ++ internal/sbi/consumer/nf_discovery.go | 6 ++--- internal/sbi/consumer/nf_management.go | 4 ++-- .../sbi/consumer/nsmf_pdusession_callback.go | 9 ++------ internal/sbi/consumer/sm_policy.go | 6 ++--- internal/sbi/eventexposure/api_default.go | 20 ----------------- internal/sbi/eventexposure/routers.go | 14 +++++++----- .../api_individual_pdu_session_hsmf.go | 10 --------- .../pdusession/api_individual_sm_context.go | 17 -------------- .../pdusession/api_pdu_sessions_collection.go | 5 ----- .../pdusession/api_sm_contexts_collection.go | 6 ----- internal/sbi/pdusession/routers.go | 14 +++++++----- 15 files changed, 45 insertions(+), 96 deletions(-) diff --git a/go.mod b/go.mod index 74f91498..11a5ce0a 100644 --- a/go.mod +++ b/go.mod @@ -9,7 +9,7 @@ require ( github.com/free5gc/aper v1.0.4 github.com/free5gc/nas v1.1.0 github.com/free5gc/ngap v1.0.6 - github.com/free5gc/openapi v1.0.7-0.20231216094313-e15a4ff046f6 + github.com/free5gc/openapi v1.0.7-0.20240117084712-52ad99299693 github.com/free5gc/pfcp v1.0.6 github.com/free5gc/util v1.0.5-0.20231001095115-433858e5be94 github.com/gin-gonic/gin v1.9.1 diff --git a/go.sum b/go.sum index ed905f46..4cd40b00 100644 --- a/go.sum +++ b/go.sum @@ -70,8 +70,8 @@ github.com/free5gc/ngap v1.0.6 h1:f9sKqHMNrFZVo9Kp8hAyrCXSoI8l746N5O+DFn7vKHA= github.com/free5gc/ngap v1.0.6/go.mod h1:TG1kwwU/EyIlJ3bxY591rdxpD5ZeYnLZTzoWjcfvrBM= github.com/free5gc/openapi v1.0.4/go.mod h1:KRCnnp0GeK0Bl4gnrX79cQAidKXNENf8VRdG0y9R0Fc= github.com/free5gc/openapi v1.0.6/go.mod h1:iw/N0E+FlX44EEx24IBi2EdZW8v+bkj3ETWPGnlK9DI= -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/pfcp v1.0.6 h1:dKEVyZWozF1G+yk1JXw/1ggtIRI0v362say/Q6VDZTE= github.com/free5gc/pfcp v1.0.6/go.mod h1:WzpW7Zxhx5WONMumNKRWbPn7pl/iTYp2FqRLNiOWUjs= github.com/free5gc/tlv v1.0.2-0.20230131124215-8b6ebd69bf93 h1:QPSSI5zw4goiIfxem9doVyMqTO8iKLQ536pzpET5Y+Q= diff --git a/internal/context/context.go b/internal/context/context.go index 1cee3ffc..d692d788 100644 --- a/internal/context/context.go +++ b/internal/context/context.go @@ -24,6 +24,12 @@ func Init() { smfContext.NfInstanceID = uuid.New().String() } +type NFContext interface { + AuthorizationCheck(token, serviceName string) error +} + +var _ NFContext = &SMFContext{} + var smfContext SMFContext type SMFContext struct { @@ -288,23 +294,19 @@ func GetUEDefaultPathPool(groupName string) *UEDefaultPaths { return smfContext.UEDefaultPathPool[groupName] } -func (c *SMFContext) GetTokenCtx(scope, targetNF string) ( +func (c *SMFContext) GetTokenCtx(scope string, targetNF models.NfType) ( context.Context, *models.ProblemDetails, error, ) { if !c.OAuth2Required { return context.TODO(), nil, nil } - return oauth.GetTokenCtx(models.NfType_SMF, - c.NfInstanceID, c.NrfUri, scope, targetNF) + return oauth.GetTokenCtx(models.NfType_SMF, targetNF, + c.NfInstanceID, c.NrfUri, scope) } -func (context *SMFContext) AuthorizationCheck(token, serviceName string) error { - if !context.OAuth2Required { +func (c *SMFContext) AuthorizationCheck(token, serviceName string) error { + if !c.OAuth2Required { return nil } - err := oauth.VerifyOAuth(token, serviceName, context.NrfCertPem) - if err != nil { - return err - } - return nil + return oauth.VerifyOAuth(token, serviceName, c.NrfCertPem) } diff --git a/internal/logger/logger.go b/internal/logger/logger.go index 81936e74..2acaf1e8 100644 --- a/internal/logger/logger.go +++ b/internal/logger/logger.go @@ -23,6 +23,7 @@ var ( GsmLog *logrus.Entry PfcpLog *logrus.Entry PduSessLog *logrus.Entry + UtilLog *logrus.Entry ) func init() { @@ -42,4 +43,5 @@ func init() { GsmLog = NfLog.WithField(logger_util.FieldCategory, "GSM") PfcpLog = NfLog.WithField(logger_util.FieldCategory, "PFCP") PduSessLog = NfLog.WithField(logger_util.FieldCategory, "PduSess") + UtilLog = NfLog.WithField(logger_util.FieldCategory, "Util") } diff --git a/internal/sbi/consumer/nf_discovery.go b/internal/sbi/consumer/nf_discovery.go index c671d534..fd5fea3a 100644 --- a/internal/sbi/consumer/nf_discovery.go +++ b/internal/sbi/consumer/nf_discovery.go @@ -15,7 +15,7 @@ import ( ) func SendNFDiscoveryUDM() (*models.ProblemDetails, error) { - ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nnrf-disc", "NRF") + ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nnrf-disc", models.NfType_NRF) if err != nil { return pd, err } @@ -61,7 +61,7 @@ func SendNFDiscoveryUDM() (*models.ProblemDetails, error) { } func SendNFDiscoveryPCF() (problemDetails *models.ProblemDetails, err error) { - ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nnrf-disc", "NRF") + ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nnrf-disc", models.NfType_NRF) if err != nil { return pd, err } @@ -101,7 +101,7 @@ func SendNFDiscoveryPCF() (problemDetails *models.ProblemDetails, err error) { } func SendNFDiscoveryServingAMF(smContext *smf_context.SMContext) (*models.ProblemDetails, error) { - ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nnrf-disc", "NRF") + ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nnrf-disc", models.NfType_NRF) if err != nil { return pd, err } diff --git a/internal/sbi/consumer/nf_management.go b/internal/sbi/consumer/nf_management.go index 7f85b37a..d0d417c5 100644 --- a/internal/sbi/consumer/nf_management.go +++ b/internal/sbi/consumer/nf_management.go @@ -106,7 +106,7 @@ func RetrySendNFRegistration(MaxRetry int) error { func SendNFDeregistration() error { // Check data (Use RESTful DELETE) - ctx, _, err := smf_context.GetSelf().GetTokenCtx("nnrf-nfm", "NRF") + ctx, _, err := smf_context.GetSelf().GetTokenCtx("nnrf-nfm", models.NfType_NRF) if err != nil { return err } @@ -136,7 +136,7 @@ func SendNFDeregistration() error { func SendDeregisterNFInstance() (*models.ProblemDetails, error) { logger.ConsumerLog.Infof("Send Deregister NFInstance") - ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nnrf-nfm", "NRF") + ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nnrf-nfm", models.NfType_NRF) if err != nil { return pd, err } diff --git a/internal/sbi/consumer/nsmf_pdusession_callback.go b/internal/sbi/consumer/nsmf_pdusession_callback.go index b7942e07..22751c64 100644 --- a/internal/sbi/consumer/nsmf_pdusession_callback.go +++ b/internal/sbi/consumer/nsmf_pdusession_callback.go @@ -1,12 +1,12 @@ package consumer import ( + "context" "net/http" "github.com/free5gc/openapi" "github.com/free5gc/openapi/Nsmf_PDUSession" "github.com/free5gc/openapi/models" - smf_context "github.com/free5gc/smf/internal/context" "github.com/free5gc/smf/internal/logger" ) @@ -19,15 +19,10 @@ func SendSMContextStatusNotification(uri string) (*models.ProblemDetails, error) configuration := Nsmf_PDUSession.NewConfiguration() client := Nsmf_PDUSession.NewAPIClient(configuration) - ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nsmf-pdusession", "SMF") - if err != nil { - return pd, err - } - logger.CtxLog.Infoln("[SMF] Send SMContext Status Notification") httpResp, localErr := client. IndividualSMContextNotificationApi. - SMContextNotification(ctx, uri, request) + SMContextNotification(context.Background(), uri, request) if localErr == nil { if httpResp.StatusCode != http.StatusNoContent { diff --git a/internal/sbi/consumer/sm_policy.go b/internal/sbi/consumer/sm_policy.go index 15d6370b..cde88bb9 100644 --- a/internal/sbi/consumer/sm_policy.go +++ b/internal/sbi/consumer/sm_policy.go @@ -47,7 +47,7 @@ func SendSMPolicyAssociationCreate(smContext *smf_context.SMContext) (string, *m } smPolicyData.SuppFeat = "F" - ctx, _, err := smf_context.GetSelf().GetTokenCtx("npcf-smpolicycontrol", "PCF") + ctx, _, err := smf_context.GetSelf().GetTokenCtx("npcf-smpolicycontrol", models.NfType_PCF) if err != nil { return "", nil, err } @@ -148,7 +148,7 @@ func SendSMPolicyAssociationUpdateByUERequestModification( } } - ctx, _, err := smf_context.GetSelf().GetTokenCtx("npcf-smpolicycontrol", "PCF") + ctx, _, err := smf_context.GetSelf().GetTokenCtx("npcf-smpolicycontrol", models.NfType_PCF) if err != nil { return nil, err } @@ -374,7 +374,7 @@ func SendSMPolicyAssociationTermination(smContext *smf_context.SMContext) error return errors.Errorf("smContext not selected PCF") } - ctx, _, err := smf_context.GetSelf().GetTokenCtx("npcf-smpolicycontrol", "PCF") + ctx, _, err := smf_context.GetSelf().GetTokenCtx("npcf-smpolicycontrol", models.NfType_PCF) if err != nil { return err } diff --git a/internal/sbi/eventexposure/api_default.go b/internal/sbi/eventexposure/api_default.go index 7dacdca7..60b90b6d 100644 --- a/internal/sbi/eventexposure/api_default.go +++ b/internal/sbi/eventexposure/api_default.go @@ -17,40 +17,20 @@ import ( // SubscriptionsPost - func SubscriptionsPost(c *gin.Context) { - auth_err := authorizationCheck(c) - if auth_err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) - return - } c.JSON(http.StatusOK, gin.H{}) } // SubscriptionsSubIdDelete - func SubscriptionsSubIdDelete(c *gin.Context) { - auth_err := authorizationCheck(c) - if auth_err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) - return - } c.JSON(http.StatusOK, gin.H{}) } // SubscriptionsSubIdGet - func SubscriptionsSubIdGet(c *gin.Context) { - auth_err := authorizationCheck(c) - if auth_err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) - return - } c.JSON(http.StatusOK, gin.H{}) } // SubscriptionsSubIdPut - func SubscriptionsSubIdPut(c *gin.Context) { - auth_err := authorizationCheck(c) - if auth_err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) - return - } c.JSON(http.StatusOK, gin.H{}) } diff --git a/internal/sbi/eventexposure/routers.go b/internal/sbi/eventexposure/routers.go index cc9b53d5..db460336 100644 --- a/internal/sbi/eventexposure/routers.go +++ b/internal/sbi/eventexposure/routers.go @@ -17,7 +17,9 @@ import ( smf_context "github.com/free5gc/smf/internal/context" "github.com/free5gc/smf/internal/logger" + "github.com/free5gc/smf/internal/util/oauth" "github.com/free5gc/smf/pkg/factory" + "github.com/free5gc/openapi/models" logger_util "github.com/free5gc/util/logger" ) @@ -33,6 +35,8 @@ type Route struct { HandlerFunc gin.HandlerFunc } +const serviceName string = string(models.ServiceName_NSMF_EVENT_EXPOSURE) + // Routes is the list of the generated Route. type Routes []Route @@ -43,14 +47,14 @@ func NewRouter() *gin.Engine { return router } -func authorizationCheck(c *gin.Context) error { - token := c.Request.Header.Get("Authorization") - return smf_context.GetSelf().AuthorizationCheck(token, "nsmf-event-exposure") -} - func AddService(engine *gin.Engine) *gin.RouterGroup { group := engine.Group(factory.SmfEventExposureResUriPrefix) + routerAuthorizationCheck := util_oauth.NewRouterAuthorizationCheck(serviceName) + group.Use(func(c *gin.Context) { + routerAuthorizationCheck.Check(c, smf_context.GetSelf()) + }) + for _, route := range routes { switch route.Method { case "GET": diff --git a/internal/sbi/pdusession/api_individual_pdu_session_hsmf.go b/internal/sbi/pdusession/api_individual_pdu_session_hsmf.go index 542d09ed..b3a920e4 100644 --- a/internal/sbi/pdusession/api_individual_pdu_session_hsmf.go +++ b/internal/sbi/pdusession/api_individual_pdu_session_hsmf.go @@ -17,20 +17,10 @@ import ( // ReleasePduSession - Release func ReleasePduSession(c *gin.Context) { - auth_err := authorizationCheck(c) - if auth_err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) - return - } c.JSON(http.StatusOK, gin.H{}) } // UpdatePduSession - Update (initiated by V-SMF) func UpdatePduSession(c *gin.Context) { - auth_err := authorizationCheck(c) - if auth_err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) - return - } c.JSON(http.StatusOK, gin.H{}) } diff --git a/internal/sbi/pdusession/api_individual_sm_context.go b/internal/sbi/pdusession/api_individual_sm_context.go index 722ab739..0987c839 100644 --- a/internal/sbi/pdusession/api_individual_sm_context.go +++ b/internal/sbi/pdusession/api_individual_sm_context.go @@ -25,12 +25,6 @@ import ( // HTTPReleaseSmContext - Release SM Context func HTTPReleaseSmContext(c *gin.Context) { - auth_err := authorizationCheck(c) - if auth_err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) - return - } - logger.PduSessLog.Info("Receive Release SM Context Request") var request models.ReleaseSmContextRequest request.JsonData = new(models.SmContextReleaseData) @@ -60,22 +54,11 @@ func HTTPReleaseSmContext(c *gin.Context) { // RetrieveSmContext - Retrieve SM Context func RetrieveSmContext(c *gin.Context) { - auth_err := authorizationCheck(c) - if auth_err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) - return - } c.JSON(http.StatusOK, gin.H{}) } // HTTPUpdateSmContext - Update SM Context func HTTPUpdateSmContext(c *gin.Context) { - auth_err := authorizationCheck(c) - if auth_err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) - return - } - logger.PduSessLog.Info("Receive Update SM Context Request") var request models.UpdateSmContextRequest request.JsonData = new(models.SmContextUpdateData) diff --git a/internal/sbi/pdusession/api_pdu_sessions_collection.go b/internal/sbi/pdusession/api_pdu_sessions_collection.go index 38f11b37..cf08d4c1 100644 --- a/internal/sbi/pdusession/api_pdu_sessions_collection.go +++ b/internal/sbi/pdusession/api_pdu_sessions_collection.go @@ -17,10 +17,5 @@ import ( // PostPduSessions - Create func PostPduSessions(c *gin.Context) { - auth_err := authorizationCheck(c) - if auth_err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) - return - } c.JSON(http.StatusOK, gin.H{}) } diff --git a/internal/sbi/pdusession/api_sm_contexts_collection.go b/internal/sbi/pdusession/api_sm_contexts_collection.go index 65852f46..4f378b11 100644 --- a/internal/sbi/pdusession/api_sm_contexts_collection.go +++ b/internal/sbi/pdusession/api_sm_contexts_collection.go @@ -24,12 +24,6 @@ import ( // HTTPPostSmContexts - Create SM Context func HTTPPostSmContexts(c *gin.Context) { - auth_err := authorizationCheck(c) - if auth_err != nil { - c.JSON(http.StatusUnauthorized, gin.H{"error": auth_err.Error()}) - return - } - logger.PduSessLog.Info("Receive Create SM Context Request") var request models.PostSmContextsRequest diff --git a/internal/sbi/pdusession/routers.go b/internal/sbi/pdusession/routers.go index 5a0e578a..97747dc3 100644 --- a/internal/sbi/pdusession/routers.go +++ b/internal/sbi/pdusession/routers.go @@ -17,7 +17,9 @@ import ( smf_context "github.com/free5gc/smf/internal/context" "github.com/free5gc/smf/internal/logger" + "github.com/free5gc/smf/internal/util/oauth" "github.com/free5gc/smf/pkg/factory" + "github.com/free5gc/openapi/models" logger_util "github.com/free5gc/util/logger" ) @@ -33,6 +35,8 @@ type Route struct { HandlerFunc gin.HandlerFunc } +const serviceName string = string(models.ServiceName_NSMF_PDUSESSION) + // Routes is the list of the generated Route. type Routes []Route @@ -43,14 +47,14 @@ func NewRouter() *gin.Engine { return router } -func authorizationCheck(c *gin.Context) error { - token := c.Request.Header.Get("Authorization") - return smf_context.GetSelf().AuthorizationCheck(token, "nsmf-pdusession") -} - func AddService(engine *gin.Engine) *gin.RouterGroup { group := engine.Group(factory.SmfPdusessionResUriPrefix) + routerAuthorizationCheck := util_oauth.NewRouterAuthorizationCheck(serviceName) + group.Use(func(c *gin.Context) { + routerAuthorizationCheck.Check(c, smf_context.GetSelf()) + }) + for _, route := range routes { switch route.Method { case "GET": From cbcd8a44451436b9c6969f547e1b13803d09dd78 Mon Sep 17 00:00:00 2001 From: pf-lin Date: Mon, 22 Jan 2024 12:00:43 +0000 Subject: [PATCH 4/8] Fix linter problem Co-authored-by: ming-hsien Co-authored-by: ian60509 --- internal/sbi/eventexposure/routers.go | 2 +- internal/sbi/pdusession/routers.go | 2 +- internal/util/oauth/router_auth_check.go | 2 +- internal/util/oauth/router_auth_check_test.go | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/sbi/eventexposure/routers.go b/internal/sbi/eventexposure/routers.go index db460336..717c06d2 100644 --- a/internal/sbi/eventexposure/routers.go +++ b/internal/sbi/eventexposure/routers.go @@ -15,11 +15,11 @@ import ( "github.com/gin-gonic/gin" + "github.com/free5gc/openapi/models" smf_context "github.com/free5gc/smf/internal/context" "github.com/free5gc/smf/internal/logger" "github.com/free5gc/smf/internal/util/oauth" "github.com/free5gc/smf/pkg/factory" - "github.com/free5gc/openapi/models" logger_util "github.com/free5gc/util/logger" ) diff --git a/internal/sbi/pdusession/routers.go b/internal/sbi/pdusession/routers.go index 97747dc3..2e3a16f7 100644 --- a/internal/sbi/pdusession/routers.go +++ b/internal/sbi/pdusession/routers.go @@ -15,11 +15,11 @@ import ( "github.com/gin-gonic/gin" + "github.com/free5gc/openapi/models" smf_context "github.com/free5gc/smf/internal/context" "github.com/free5gc/smf/internal/logger" "github.com/free5gc/smf/internal/util/oauth" "github.com/free5gc/smf/pkg/factory" - "github.com/free5gc/openapi/models" logger_util "github.com/free5gc/util/logger" ) diff --git a/internal/util/oauth/router_auth_check.go b/internal/util/oauth/router_auth_check.go index 15a090b5..37b111ac 100644 --- a/internal/util/oauth/router_auth_check.go +++ b/internal/util/oauth/router_auth_check.go @@ -30,4 +30,4 @@ func (rac *RouterAuthorizationCheck) Check(c *gin.Context, smfContext smf_contex } logger.UtilLog.Debugf("RouterAuthorizationCheck: Check Authorized") -} \ No newline at end of file +} diff --git a/internal/util/oauth/router_auth_check_test.go b/internal/util/oauth/router_auth_check_test.go index 9874386f..cb225844 100644 --- a/internal/util/oauth/router_auth_check_test.go +++ b/internal/util/oauth/router_auth_check_test.go @@ -88,4 +88,4 @@ func TestRouterAuthorizationCheck_Check(t *testing.T) { } }) } -} \ No newline at end of file +} From fbd6deb1a06e73be2efcb951c3f8c8009224d522 Mon Sep 17 00:00:00 2001 From: pf-lin Date: Wed, 24 Jan 2024 10:47:14 +0000 Subject: [PATCH 5/8] Modify missing consumers Co-authored-by: ming-hsien Co-authored-by: ian60509 --- internal/pfcp/handler/handler.go | 9 +++++-- .../sbi/consumer/ue_context_management.go | 16 +++++++++--- internal/sbi/producer/datapath.go | 17 ++++++++++--- internal/sbi/producer/pdu_session.go | 25 ++++++++++++++++--- pkg/association/association.go | 7 +++++- 5 files changed, 60 insertions(+), 14 deletions(-) diff --git a/internal/pfcp/handler/handler.go b/internal/pfcp/handler/handler.go index 926f8025..88b32519 100644 --- a/internal/pfcp/handler/handler.go +++ b/internal/pfcp/handler/handler.go @@ -1,7 +1,6 @@ package handler import ( - "context" "fmt" "github.com/free5gc/openapi/models" @@ -173,9 +172,15 @@ func HandlePfcpSessionReportRequest(msg *pfcpUdp.Message) { }, } + ctx, _, err := smf_context.GetSelf().GetTokenCtx("namf-comm", models.NfType_AMF) + if err != nil { + logger.PfcpLog.Warnf("Get NAMF_COMM context failed: %s", err) + return + } + rspData, _, err := smContext.CommunicationClient. N1N2MessageCollectionDocumentApi. - N1N2MessageTransfer(context.Background(), smContext.Supi, n1n2Request) + N1N2MessageTransfer(ctx, smContext.Supi, n1n2Request) if err != nil { logger.PfcpLog.Warnf("Send N1N2Transfer failed: %s", err) } diff --git a/internal/sbi/consumer/ue_context_management.go b/internal/sbi/consumer/ue_context_management.go index a9263fa6..3196315e 100644 --- a/internal/sbi/consumer/ue_context_management.go +++ b/internal/sbi/consumer/ue_context_management.go @@ -1,8 +1,6 @@ package consumer import ( - "context" - "github.com/pkg/errors" "github.com/free5gc/openapi" @@ -42,7 +40,12 @@ func UeCmRegistration(smCtx *smf_context.SMContext) ( " PduSessionId:", registrationData.PduSessionId, " SNssai:", registrationData.SingleNssai, " Dnn:", registrationData.Dnn, " PlmnId:", registrationData.PlmnId) - _, httpResp, localErr := client.SMFRegistrationApi.SmfRegistrationsPduSessionId(context.Background(), + ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nudm-uecm", models.NfType_UDM) + if err != nil { + return pd, err + } + + _, httpResp, localErr := client.SMFRegistrationApi.SmfRegistrationsPduSessionId(ctx, smCtx.Supi, smCtx.PduSessionId, registrationData) defer func() { if httpResp != nil { @@ -78,7 +81,12 @@ func UeCmDeregistration(smCtx *smf_context.SMContext) (*models.ProblemDetails, e configuration.SetBasePath(uecmUri) client := Nudm_UEContextManagement.NewAPIClient(configuration) - httpResp, localErr := client.SMFDeregistrationApi.Deregistration(context.Background(), + ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nudm-uecm", models.NfType_UDM) + if err != nil { + return pd, err + } + + httpResp, localErr := client.SMFDeregistrationApi.Deregistration(ctx, smCtx.Supi, smCtx.PduSessionId) defer func() { if httpResp != nil { diff --git a/internal/sbi/producer/datapath.go b/internal/sbi/producer/datapath.go index 4604cab6..c2149d35 100644 --- a/internal/sbi/producer/datapath.go +++ b/internal/sbi/producer/datapath.go @@ -1,7 +1,6 @@ package producer import ( - "context" "fmt" "github.com/free5gc/nas/nasMessage" @@ -239,10 +238,16 @@ func sendPDUSessionEstablishmentReject( }, } + ctx, _, err := smf_context.GetSelf().GetTokenCtx("namf-comm", models.NfType_AMF) + if err != nil { + logger.PduSessLog.Warnf("Get NAMF_COMM context failed: %s", err) + return + } + rspData, rsp, err := smContext. CommunicationClient. N1N2MessageCollectionDocumentApi. - N1N2MessageTransfer(context.Background(), smContext.Supi, n1n2Request) + N1N2MessageTransfer(ctx, smContext.Supi, n1n2Request) defer func() { if rsp != nil { if resCloseErr := rsp.Body.Close(); resCloseErr != nil { @@ -301,10 +306,16 @@ func sendPDUSessionEstablishmentAccept( }, } + ctx, _, err := smf_context.GetSelf().GetTokenCtx("namf-comm", models.NfType_AMF) + if err != nil { + logger.PduSessLog.Warnf("Get NAMF_COMM context failed: %s", err) + return + } + rspData, rsp, err := smContext. CommunicationClient. N1N2MessageCollectionDocumentApi. - N1N2MessageTransfer(context.Background(), smContext.Supi, n1n2Request) + N1N2MessageTransfer(ctx, smContext.Supi, n1n2Request) defer func() { if rsp != nil { if resCloseErr := rsp.Body.Close(); resCloseErr != nil { diff --git a/internal/sbi/producer/pdu_session.go b/internal/sbi/producer/pdu_session.go index 05610f60..84249f59 100644 --- a/internal/sbi/producer/pdu_session.go +++ b/internal/sbi/producer/pdu_session.go @@ -1,7 +1,6 @@ package producer import ( - "context" "encoding/hex" "errors" "net" @@ -101,9 +100,15 @@ func HandlePDUSessionSMContextCreate(isDone <-chan struct{}, SubscriberDataManagementClient := smf_context.GetSelf().SubscriberDataManagementClient + ctx, _, oauthErr := smf_context.GetSelf().GetTokenCtx("nudm-sdm", models.NfType_UDM) + if oauthErr != nil { + smContext.Log.Errorf("Get Token Context Error[%v]", oauthErr) + return nil + } + if sessSubData, rsp, err := SubscriberDataManagementClient. SessionManagementSubscriptionDataRetrievalApi. - GetSmData(context.Background(), smContext.Supi, smDataParams); err != nil { + GetSmData(ctx, smContext.Supi, smDataParams); err != nil { smContext.Log.Errorln("Get SessionManagementSubscriptionData error:", err) } else { defer func() { @@ -1093,12 +1098,18 @@ func sendGSMPDUSessionReleaseCommand(smContext *smf_context.SMContext, nasPdu [] // Start T3592 t3592 := factory.SmfConfig.Configuration.T3592 if t3592.Enable { + ctx, _, err := smf_context.GetSelf().GetTokenCtx("namf-comm", models.NfType_AMF) + if err != nil { + smContext.Log.Warnf("Get namf-comm token failed: %+v", err) + return + } + smContext.T3592 = smf_context.NewTimer(t3592.ExpireTime, t3592.MaxRetryTimes, func(expireTimes int32) { smContext.SMLock.Lock() rspData, rsp, err := smContext. CommunicationClient. N1N2MessageCollectionDocumentApi. - N1N2MessageTransfer(context.Background(), smContext.Supi, n1n2Request) + N1N2MessageTransfer(ctx, smContext.Supi, n1n2Request) if err != nil { smContext.Log.Warnf("Send N1N2Transfer for GSMPDUSessionReleaseCommand failed: %s", err) } @@ -1138,13 +1149,19 @@ func sendGSMPDUSessionModificationCommand(smContext *smf_context.SMContext, nasP // Start T3591 t3591 := factory.SmfConfig.Configuration.T3591 if t3591.Enable { + ctx, _, err := smf_context.GetSelf().GetTokenCtx("namf-comm", models.NfType_AMF) + if err != nil { + smContext.Log.Warnf("Get namf-comm token failed: %+v", err) + return + } + smContext.T3591 = smf_context.NewTimer(t3591.ExpireTime, t3591.MaxRetryTimes, func(expireTimes int32) { smContext.SMLock.Lock() defer smContext.SMLock.Unlock() rspData, rsp, err := smContext. CommunicationClient. N1N2MessageCollectionDocumentApi. - N1N2MessageTransfer(context.Background(), smContext.Supi, n1n2Request) + N1N2MessageTransfer(ctx, smContext.Supi, n1n2Request) if err != nil { smContext.Log.Warnf("Send N1N2Transfer for GSMPDUSessionModificationCommand failed: %s", err) } diff --git a/pkg/association/association.go b/pkg/association/association.go index 7e7e2fa2..389d488f 100644 --- a/pkg/association/association.go +++ b/pkg/association/association.go @@ -245,9 +245,14 @@ func requestAMFToReleasePDUResources(smContext *smf_context.SMContext) (sendNoti } } + ctx, _, err := smf_context.GetSelf().GetTokenCtx("namf-comm", models.NfType_AMF) + if err != nil { + return false, false + } + rspData, res, err := smContext.CommunicationClient. N1N2MessageCollectionDocumentApi. - N1N2MessageTransfer(context.Background(), smContext.Supi, n1n2Request) + N1N2MessageTransfer(ctx, smContext.Supi, n1n2Request) if err != nil { logger.MainLog.Warnf("Send N1N2Transfer failed: %+v", err) } From 6f8f9a686ae26417f3e40e9b0a074a107c64663b Mon Sep 17 00:00:00 2001 From: CTFang Date: Tue, 6 Feb 2024 13:10:06 +0000 Subject: [PATCH 6/8] Fix: use models in serviceName when authorization --- internal/context/context.go | 10 +++++----- internal/sbi/eventexposure/routers.go | 6 ++---- internal/sbi/pdusession/routers.go | 6 ++---- internal/util/oauth/router_auth_check.go | 5 +++-- internal/util/oauth/router_auth_check_test.go | 5 +++-- 5 files changed, 15 insertions(+), 17 deletions(-) diff --git a/internal/context/context.go b/internal/context/context.go index d692d788..ce342f1b 100644 --- a/internal/context/context.go +++ b/internal/context/context.go @@ -25,7 +25,7 @@ func Init() { } type NFContext interface { - AuthorizationCheck(token, serviceName string) error + AuthorizationCheck(token string, serviceName models.ServiceName) error } var _ NFContext = &SMFContext{} @@ -294,19 +294,19 @@ func GetUEDefaultPathPool(groupName string) *UEDefaultPaths { return smfContext.UEDefaultPathPool[groupName] } -func (c *SMFContext) GetTokenCtx(scope string, targetNF models.NfType) ( +func (c *SMFContext) 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_SMF, targetNF, - c.NfInstanceID, c.NrfUri, scope) + c.NfInstanceID, c.NrfUri, string(serviceName)) } -func (c *SMFContext) AuthorizationCheck(token, serviceName string) error { +func (c *SMFContext) AuthorizationCheck(token string, serviceName models.ServiceName) error { if !c.OAuth2Required { return nil } - return oauth.VerifyOAuth(token, serviceName, c.NrfCertPem) + return oauth.VerifyOAuth(token, string(serviceName), c.NrfCertPem) } diff --git a/internal/sbi/eventexposure/routers.go b/internal/sbi/eventexposure/routers.go index 717c06d2..26e3319e 100644 --- a/internal/sbi/eventexposure/routers.go +++ b/internal/sbi/eventexposure/routers.go @@ -18,7 +18,7 @@ import ( "github.com/free5gc/openapi/models" smf_context "github.com/free5gc/smf/internal/context" "github.com/free5gc/smf/internal/logger" - "github.com/free5gc/smf/internal/util/oauth" + util_oauth "github.com/free5gc/smf/internal/util/oauth" "github.com/free5gc/smf/pkg/factory" logger_util "github.com/free5gc/util/logger" ) @@ -35,8 +35,6 @@ type Route struct { HandlerFunc gin.HandlerFunc } -const serviceName string = string(models.ServiceName_NSMF_EVENT_EXPOSURE) - // Routes is the list of the generated Route. type Routes []Route @@ -50,7 +48,7 @@ func NewRouter() *gin.Engine { func AddService(engine *gin.Engine) *gin.RouterGroup { group := engine.Group(factory.SmfEventExposureResUriPrefix) - routerAuthorizationCheck := util_oauth.NewRouterAuthorizationCheck(serviceName) + routerAuthorizationCheck := util_oauth.NewRouterAuthorizationCheck(models.ServiceName_NSMF_EVENT_EXPOSURE) group.Use(func(c *gin.Context) { routerAuthorizationCheck.Check(c, smf_context.GetSelf()) }) diff --git a/internal/sbi/pdusession/routers.go b/internal/sbi/pdusession/routers.go index 2e3a16f7..c9f753f0 100644 --- a/internal/sbi/pdusession/routers.go +++ b/internal/sbi/pdusession/routers.go @@ -18,7 +18,7 @@ import ( "github.com/free5gc/openapi/models" smf_context "github.com/free5gc/smf/internal/context" "github.com/free5gc/smf/internal/logger" - "github.com/free5gc/smf/internal/util/oauth" + util_oauth "github.com/free5gc/smf/internal/util/oauth" "github.com/free5gc/smf/pkg/factory" logger_util "github.com/free5gc/util/logger" ) @@ -35,8 +35,6 @@ type Route struct { HandlerFunc gin.HandlerFunc } -const serviceName string = string(models.ServiceName_NSMF_PDUSESSION) - // Routes is the list of the generated Route. type Routes []Route @@ -50,7 +48,7 @@ func NewRouter() *gin.Engine { func AddService(engine *gin.Engine) *gin.RouterGroup { group := engine.Group(factory.SmfPdusessionResUriPrefix) - routerAuthorizationCheck := util_oauth.NewRouterAuthorizationCheck(serviceName) + routerAuthorizationCheck := util_oauth.NewRouterAuthorizationCheck(models.ServiceName_NSMF_PDUSESSION) group.Use(func(c *gin.Context) { routerAuthorizationCheck.Check(c, smf_context.GetSelf()) }) diff --git a/internal/util/oauth/router_auth_check.go b/internal/util/oauth/router_auth_check.go index 37b111ac..d9db11f6 100644 --- a/internal/util/oauth/router_auth_check.go +++ b/internal/util/oauth/router_auth_check.go @@ -5,15 +5,16 @@ import ( "github.com/gin-gonic/gin" + "github.com/free5gc/openapi/models" smf_context "github.com/free5gc/smf/internal/context" "github.com/free5gc/smf/internal/logger" ) 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/oauth/router_auth_check_test.go b/internal/util/oauth/router_auth_check_test.go index cb225844..4af6a756 100644 --- a/internal/util/oauth/router_auth_check_test.go +++ b/internal/util/oauth/router_auth_check_test.go @@ -5,6 +5,7 @@ import ( "net/http/httptest" "testing" + "github.com/free5gc/openapi/models" "github.com/gin-gonic/gin" "github.com/pkg/errors" ) @@ -20,7 +21,7 @@ func newMockSMFContext() *mockSMFContext { return &mockSMFContext{} } -func (m *mockSMFContext) AuthorizationCheck(token string, serviceName string) error { +func (m *mockSMFContext) AuthorizationCheck(token string, serviceName models.ServiceName) error { if token == Valid { return nil } @@ -81,7 +82,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, newMockSMFContext()) if w.Code != tt.want.statusCode { t.Errorf("StatusCode should be %d, but got %d", tt.want.statusCode, w.Code) From 1877d4a51a3816ceb910c00cd3ebe327d4fe7506 Mon Sep 17 00:00:00 2001 From: CTFang Date: Tue, 6 Feb 2024 13:17:01 +0000 Subject: [PATCH 7/8] Fix: use models serviceName in GetTokenCtx --- internal/context/sm_context.go | 2 +- internal/pfcp/handler/handler.go | 2 +- internal/sbi/consumer/nf_discovery.go | 6 +++--- internal/sbi/consumer/nf_management.go | 4 ++-- internal/sbi/consumer/sm_policy.go | 6 +++--- internal/sbi/consumer/ue_context_management.go | 4 ++-- internal/sbi/producer/datapath.go | 4 ++-- internal/sbi/producer/pdu_session.go | 6 +++--- pkg/association/association.go | 2 +- 9 files changed, 18 insertions(+), 18 deletions(-) diff --git a/internal/context/sm_context.go b/internal/context/sm_context.go index 714ab250..0215a504 100644 --- a/internal/context/sm_context.go +++ b/internal/context/sm_context.go @@ -411,7 +411,7 @@ func (smContext *SMContext) PDUAddressToNAS() ([12]byte, uint8) { // PCFSelection will select PCF for this SM Context func (smContext *SMContext) PCFSelection() error { - ctx, _, err := GetSelf().GetTokenCtx("nnrf-disc", "NRF") + ctx, _, err := GetSelf().GetTokenCtx(models.ServiceName_NNRF_DISC, "NRF") if err != nil { return err } diff --git a/internal/pfcp/handler/handler.go b/internal/pfcp/handler/handler.go index 88b32519..109a1208 100644 --- a/internal/pfcp/handler/handler.go +++ b/internal/pfcp/handler/handler.go @@ -172,7 +172,7 @@ func HandlePfcpSessionReportRequest(msg *pfcpUdp.Message) { }, } - ctx, _, err := smf_context.GetSelf().GetTokenCtx("namf-comm", models.NfType_AMF) + ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NAMF_COMM, models.NfType_AMF) if err != nil { logger.PfcpLog.Warnf("Get NAMF_COMM context failed: %s", err) return diff --git a/internal/sbi/consumer/nf_discovery.go b/internal/sbi/consumer/nf_discovery.go index fd5fea3a..1b236a9f 100644 --- a/internal/sbi/consumer/nf_discovery.go +++ b/internal/sbi/consumer/nf_discovery.go @@ -15,7 +15,7 @@ import ( ) func SendNFDiscoveryUDM() (*models.ProblemDetails, error) { - ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nnrf-disc", models.NfType_NRF) + ctx, pd, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NNRF_DISC, models.NfType_NRF) if err != nil { return pd, err } @@ -61,7 +61,7 @@ func SendNFDiscoveryUDM() (*models.ProblemDetails, error) { } func SendNFDiscoveryPCF() (problemDetails *models.ProblemDetails, err error) { - ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nnrf-disc", models.NfType_NRF) + ctx, pd, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NNRF_DISC, models.NfType_NRF) if err != nil { return pd, err } @@ -101,7 +101,7 @@ func SendNFDiscoveryPCF() (problemDetails *models.ProblemDetails, err error) { } func SendNFDiscoveryServingAMF(smContext *smf_context.SMContext) (*models.ProblemDetails, error) { - ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nnrf-disc", models.NfType_NRF) + ctx, pd, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NNRF_DISC, models.NfType_NRF) if err != nil { return pd, err } diff --git a/internal/sbi/consumer/nf_management.go b/internal/sbi/consumer/nf_management.go index d0d417c5..c1fa418e 100644 --- a/internal/sbi/consumer/nf_management.go +++ b/internal/sbi/consumer/nf_management.go @@ -106,7 +106,7 @@ func RetrySendNFRegistration(MaxRetry int) error { func SendNFDeregistration() error { // Check data (Use RESTful DELETE) - ctx, _, err := smf_context.GetSelf().GetTokenCtx("nnrf-nfm", models.NfType_NRF) + ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NNRF_NFM, models.NfType_NRF) if err != nil { return err } @@ -136,7 +136,7 @@ func SendNFDeregistration() error { func SendDeregisterNFInstance() (*models.ProblemDetails, error) { logger.ConsumerLog.Infof("Send Deregister NFInstance") - ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nnrf-nfm", models.NfType_NRF) + ctx, pd, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NNRF_NFM, models.NfType_NRF) if err != nil { return pd, err } diff --git a/internal/sbi/consumer/sm_policy.go b/internal/sbi/consumer/sm_policy.go index cde88bb9..79a0491e 100644 --- a/internal/sbi/consumer/sm_policy.go +++ b/internal/sbi/consumer/sm_policy.go @@ -47,7 +47,7 @@ func SendSMPolicyAssociationCreate(smContext *smf_context.SMContext) (string, *m } smPolicyData.SuppFeat = "F" - ctx, _, err := smf_context.GetSelf().GetTokenCtx("npcf-smpolicycontrol", models.NfType_PCF) + ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NPCF_SMPOLICYCONTROL, models.NfType_PCF) if err != nil { return "", nil, err } @@ -148,7 +148,7 @@ func SendSMPolicyAssociationUpdateByUERequestModification( } } - ctx, _, err := smf_context.GetSelf().GetTokenCtx("npcf-smpolicycontrol", models.NfType_PCF) + ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NPCF_SMPOLICYCONTROL, models.NfType_PCF) if err != nil { return nil, err } @@ -374,7 +374,7 @@ func SendSMPolicyAssociationTermination(smContext *smf_context.SMContext) error return errors.Errorf("smContext not selected PCF") } - ctx, _, err := smf_context.GetSelf().GetTokenCtx("npcf-smpolicycontrol", models.NfType_PCF) + ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NPCF_SMPOLICYCONTROL, models.NfType_PCF) if err != nil { return err } diff --git a/internal/sbi/consumer/ue_context_management.go b/internal/sbi/consumer/ue_context_management.go index 3196315e..b07b57cf 100644 --- a/internal/sbi/consumer/ue_context_management.go +++ b/internal/sbi/consumer/ue_context_management.go @@ -40,7 +40,7 @@ func UeCmRegistration(smCtx *smf_context.SMContext) ( " PduSessionId:", registrationData.PduSessionId, " SNssai:", registrationData.SingleNssai, " Dnn:", registrationData.Dnn, " PlmnId:", registrationData.PlmnId) - ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nudm-uecm", models.NfType_UDM) + ctx, pd, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NUDM_UECM, models.NfType_UDM) if err != nil { return pd, err } @@ -81,7 +81,7 @@ func UeCmDeregistration(smCtx *smf_context.SMContext) (*models.ProblemDetails, e configuration.SetBasePath(uecmUri) client := Nudm_UEContextManagement.NewAPIClient(configuration) - ctx, pd, err := smf_context.GetSelf().GetTokenCtx("nudm-uecm", models.NfType_UDM) + ctx, pd, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NUDM_UECM, models.NfType_UDM) if err != nil { return pd, err } diff --git a/internal/sbi/producer/datapath.go b/internal/sbi/producer/datapath.go index c2149d35..167229b6 100644 --- a/internal/sbi/producer/datapath.go +++ b/internal/sbi/producer/datapath.go @@ -238,7 +238,7 @@ func sendPDUSessionEstablishmentReject( }, } - ctx, _, err := smf_context.GetSelf().GetTokenCtx("namf-comm", models.NfType_AMF) + ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NAMF_COMM, models.NfType_AMF) if err != nil { logger.PduSessLog.Warnf("Get NAMF_COMM context failed: %s", err) return @@ -306,7 +306,7 @@ func sendPDUSessionEstablishmentAccept( }, } - ctx, _, err := smf_context.GetSelf().GetTokenCtx("namf-comm", models.NfType_AMF) + ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NAMF_COMM, models.NfType_AMF) if err != nil { logger.PduSessLog.Warnf("Get NAMF_COMM context failed: %s", err) return diff --git a/internal/sbi/producer/pdu_session.go b/internal/sbi/producer/pdu_session.go index 84249f59..cd0ad298 100644 --- a/internal/sbi/producer/pdu_session.go +++ b/internal/sbi/producer/pdu_session.go @@ -100,7 +100,7 @@ func HandlePDUSessionSMContextCreate(isDone <-chan struct{}, SubscriberDataManagementClient := smf_context.GetSelf().SubscriberDataManagementClient - ctx, _, oauthErr := smf_context.GetSelf().GetTokenCtx("nudm-sdm", models.NfType_UDM) + ctx, _, oauthErr := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NUDM_SDM, models.NfType_UDM) if oauthErr != nil { smContext.Log.Errorf("Get Token Context Error[%v]", oauthErr) return nil @@ -1098,7 +1098,7 @@ func sendGSMPDUSessionReleaseCommand(smContext *smf_context.SMContext, nasPdu [] // Start T3592 t3592 := factory.SmfConfig.Configuration.T3592 if t3592.Enable { - ctx, _, err := smf_context.GetSelf().GetTokenCtx("namf-comm", models.NfType_AMF) + ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NAMF_COMM, models.NfType_AMF) if err != nil { smContext.Log.Warnf("Get namf-comm token failed: %+v", err) return @@ -1149,7 +1149,7 @@ func sendGSMPDUSessionModificationCommand(smContext *smf_context.SMContext, nasP // Start T3591 t3591 := factory.SmfConfig.Configuration.T3591 if t3591.Enable { - ctx, _, err := smf_context.GetSelf().GetTokenCtx("namf-comm", models.NfType_AMF) + ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NAMF_COMM, models.NfType_AMF) if err != nil { smContext.Log.Warnf("Get namf-comm token failed: %+v", err) return diff --git a/pkg/association/association.go b/pkg/association/association.go index 389d488f..0e834190 100644 --- a/pkg/association/association.go +++ b/pkg/association/association.go @@ -245,7 +245,7 @@ func requestAMFToReleasePDUResources(smContext *smf_context.SMContext) (sendNoti } } - ctx, _, err := smf_context.GetSelf().GetTokenCtx("namf-comm", models.NfType_AMF) + ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NAMF_COMM, models.NfType_AMF) if err != nil { return false, false } From c6294e9ba336cf0aa132a64e037660fd1505dfd7 Mon Sep 17 00:00:00 2001 From: CTFang Date: Tue, 6 Feb 2024 13:18:49 +0000 Subject: [PATCH 8/8] fix linter error --- internal/util/oauth/router_auth_check_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/util/oauth/router_auth_check_test.go b/internal/util/oauth/router_auth_check_test.go index 4af6a756..2bc78fb0 100644 --- a/internal/util/oauth/router_auth_check_test.go +++ b/internal/util/oauth/router_auth_check_test.go @@ -5,9 +5,10 @@ import ( "net/http/httptest" "testing" - "github.com/free5gc/openapi/models" "github.com/gin-gonic/gin" "github.com/pkg/errors" + + "github.com/free5gc/openapi/models" ) const (