Skip to content

Commit

Permalink
Merge pull request #93 from pf-lin/feature/oauth2
Browse files Browse the repository at this point in the history
Add OAuth2 (Token Retrieve & Authorization Check)
  • Loading branch information
ianchen0119 authored Feb 7, 2024
2 parents 05c55bb + c6294e9 commit 3da558b
Show file tree
Hide file tree
Showing 17 changed files with 249 additions and 30 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
19 changes: 16 additions & 3 deletions internal/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ func Init() {
smfContext.NfInstanceID = uuid.New().String()
}

type NFContext interface {
AuthorizationCheck(token string, serviceName models.ServiceName) error
}

var _ NFContext = &SMFContext{}

var smfContext SMFContext

type SMFContext struct {
Expand Down Expand Up @@ -288,12 +294,19 @@ func GetUEDefaultPathPool(groupName string) *UEDefaultPaths {
return smfContext.UEDefaultPathPool[groupName]
}

func (c *SMFContext) GetTokenCtx(scope, targetNF string) (
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,
c.NfInstanceID, c.NrfUri, scope, targetNF)
return oauth.GetTokenCtx(models.NfType_SMF, targetNF,
c.NfInstanceID, c.NrfUri, string(serviceName))
}

func (c *SMFContext) AuthorizationCheck(token string, serviceName models.ServiceName) error {
if !c.OAuth2Required {
return nil
}
return oauth.VerifyOAuth(token, string(serviceName), c.NrfCertPem)
}
2 changes: 1 addition & 1 deletion internal/context/sm_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
2 changes: 2 additions & 0 deletions internal/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ var (
GsmLog *logrus.Entry
PfcpLog *logrus.Entry
PduSessLog *logrus.Entry
UtilLog *logrus.Entry
)

func init() {
Expand All @@ -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")
}
9 changes: 7 additions & 2 deletions internal/pfcp/handler/handler.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package handler

import (
"context"
"fmt"

"github.com/free5gc/openapi/models"
Expand Down Expand Up @@ -173,9 +172,15 @@ func HandlePfcpSessionReportRequest(msg *pfcpUdp.Message) {
},
}

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
}

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)
}
Expand Down
6 changes: 3 additions & 3 deletions internal/sbi/consumer/nf_discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(models.ServiceName_NNRF_DISC, models.NfType_NRF)
if err != nil {
return pd, err
}
Expand Down Expand Up @@ -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(models.ServiceName_NNRF_DISC, models.NfType_NRF)
if err != nil {
return pd, err
}
Expand Down Expand Up @@ -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(models.ServiceName_NNRF_DISC, models.NfType_NRF)
if err != nil {
return pd, err
}
Expand Down
4 changes: 2 additions & 2 deletions internal/sbi/consumer/nf_management.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(models.ServiceName_NNRF_NFM, models.NfType_NRF)
if err != nil {
return err
}
Expand Down Expand Up @@ -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(models.ServiceName_NNRF_NFM, models.NfType_NRF)
if err != nil {
return pd, err
}
Expand Down
23 changes: 19 additions & 4 deletions internal/sbi/consumer/sm_policy.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package consumer

import (
"context"
"fmt"
"net"
"regexp"
Expand Down Expand Up @@ -48,10 +47,15 @@ func SendSMPolicyAssociationCreate(smContext *smf_context.SMContext) (string, *m
}
smPolicyData.SuppFeat = "F"

ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NPCF_SMPOLICYCONTROL, models.NfType_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 {
Expand Down Expand Up @@ -143,9 +147,15 @@ func SendSMPolicyAssociationUpdateByUERequestModification(
updateSMPolicy.UeInitResReq.PackFiltInfo = append(updateSMPolicy.UeInitResReq.PackFiltInfo, *PackFiltInfo)
}
}

ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NPCF_SMPOLICYCONTROL, models.NfType_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 {
Expand Down Expand Up @@ -364,8 +374,13 @@ func SendSMPolicyAssociationTermination(smContext *smf_context.SMContext) error
return errors.Errorf("smContext not selected PCF")
}

ctx, _, err := smf_context.GetSelf().GetTokenCtx(models.ServiceName_NPCF_SMPOLICYCONTROL, models.NfType_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 {
Expand Down
16 changes: 12 additions & 4 deletions internal/sbi/consumer/ue_context_management.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package consumer

import (
"context"

"github.com/pkg/errors"

"github.com/free5gc/openapi"
Expand Down Expand Up @@ -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(models.ServiceName_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 {
Expand Down Expand Up @@ -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(models.ServiceName_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 {
Expand Down
8 changes: 8 additions & 0 deletions internal/sbi/eventexposure/routers.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ 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"
util_oauth "github.com/free5gc/smf/internal/util/oauth"
"github.com/free5gc/smf/pkg/factory"
logger_util "github.com/free5gc/util/logger"
)
Expand Down Expand Up @@ -45,6 +48,11 @@ func NewRouter() *gin.Engine {
func AddService(engine *gin.Engine) *gin.RouterGroup {
group := engine.Group(factory.SmfEventExposureResUriPrefix)

routerAuthorizationCheck := util_oauth.NewRouterAuthorizationCheck(models.ServiceName_NSMF_EVENT_EXPOSURE)
group.Use(func(c *gin.Context) {
routerAuthorizationCheck.Check(c, smf_context.GetSelf())
})

for _, route := range routes {
switch route.Method {
case "GET":
Expand Down
8 changes: 8 additions & 0 deletions internal/sbi/pdusession/routers.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ 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"
util_oauth "github.com/free5gc/smf/internal/util/oauth"
"github.com/free5gc/smf/pkg/factory"
logger_util "github.com/free5gc/util/logger"
)
Expand Down Expand Up @@ -45,6 +48,11 @@ func NewRouter() *gin.Engine {
func AddService(engine *gin.Engine) *gin.RouterGroup {
group := engine.Group(factory.SmfPdusessionResUriPrefix)

routerAuthorizationCheck := util_oauth.NewRouterAuthorizationCheck(models.ServiceName_NSMF_PDUSESSION)
group.Use(func(c *gin.Context) {
routerAuthorizationCheck.Check(c, smf_context.GetSelf())
})

for _, route := range routes {
switch route.Method {
case "GET":
Expand Down
17 changes: 14 additions & 3 deletions internal/sbi/producer/datapath.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package producer

import (
"context"
"fmt"

"github.com/free5gc/nas/nasMessage"
Expand Down Expand Up @@ -239,10 +238,16 @@ func sendPDUSessionEstablishmentReject(
},
}

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
}

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 {
Expand Down Expand Up @@ -301,10 +306,16 @@ func sendPDUSessionEstablishmentAccept(
},
}

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
}

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 {
Expand Down
25 changes: 21 additions & 4 deletions internal/sbi/producer/pdu_session.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package producer

import (
"context"
"encoding/hex"
"errors"
"net"
Expand Down Expand Up @@ -101,9 +100,15 @@ func HandlePDUSessionSMContextCreate(isDone <-chan struct{},

SubscriberDataManagementClient := smf_context.GetSelf().SubscriberDataManagementClient

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
}

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() {
Expand Down Expand Up @@ -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(models.ServiceName_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)
}
Expand Down Expand Up @@ -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(models.ServiceName_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)
}
Expand Down
Loading

0 comments on commit 3da558b

Please sign in to comment.