---
# System prepended metadata

title: Implementing RabbitMQ to AUSF part 1

---

# Implementing RabbitMQ to AUSF part 1
## Understanding Every File in the Code Repo
I need to understand every file in the repository in order to know how to implement RabbitMQ when doing the authentication.
* ```go.sum``` and ```go.mod```: These files are used to manage the dependencies of the Go modules used in free5GC. They specify the required packages and versions for building and running the AUSF module.
* `cmd/main.go`: This file is the entry point of the AUSF module. It initializes the AUSF context, logger, configuration, service and routers. It also registers the AUSF to the Network Repository Function (NRF) and starts the HTTP server for handling SBI requests.
* `internal/context/ausf_context_init.go`: This file defines the functions for initializing the AUSF context. The AUSF context is a global variable that stores the information and state of the AUSF module, such as configuration, NF profile, UE contexts, etc.
* `internal/context/context.go`: This file defines the data structures and methods for the AUSF context. It also provides some helper functions for accessing and manipulating the context data.
* `internal/logger/logger.go`: This file defines the logger for the AUSF module. It uses logrus as the underlying logging library and provides some wrapper functions for logging different levels of messages.
* `internal/sbi/consumer/nf_discovery.go`: This file defines the functions for discovering other NFs using the NRF. It implements the Nnrf_NFDiscovery service defined in 3GPP TS 29.510. It allows the AUSF to query the NRF for available NF instances that provide certain services or capabilities.
* `internal/sbi/consumer/nf_management.go`: This file defines the functions for managing the AUSF’s NF profile using the NRF. It implements the Nnrf_NFManagement service defined in 3GPP TS 29.510. It allows the AUSF to register, update, deregister and retrieve its own NF profile to/from the NRF.
* `internal/sbi/producer/eapAkaPrimeKeyGen_test.go`: This file defines some unit tests for generating EAP-AKA’ keys used in authentication procedures. It uses testify as the testing framework and compares the generated keys with some expected values.
* `internal/sbi/producer/functions.go`: This file defines some common functions used by different SBI producers in the AUSF module. For example, it defines a function for generating a correlation ID for each SBI request.
* `internal/sbi/producer/ue_authentication.go`: This file defines the functions for handling SBI requests related to UE authentication procedures. It implements the Nausf_UEAuthentication service defined in 3GPP TS 29.503. It allows the AUSF to receive authentication requests from the AMF, generate authentication vectors, perform EAP-AKA’ authentication, and generate security keys.
* `internal/sbi/sorprotection/routers.go`: This file defines the routers for handling SBI requests related to security orchestration and protection. It implements the Nausf_SecurityOrchestrationProtection service defined in 3GPP TS 29.503. It allows the AUSF to receive requests from the NEF for applying security policies and rules to the UE contexts.
* `internal/sbi/sorprotection/api_default.go`: This file defines the default handlers for the SBI requests related to security orchestration and protection. It parses the request parameters and calls the corresponding functions in the context package.
* `internal/sbi/ueauthentication/api_default.go`: This file defines the default handlers for the SBI requests related to UE authentication procedures. It parses the request parameters and calls the corresponding functions in the context package.
* `internal/sbi/ueauthentication/routers.go`: This file defines the routers for handling SBI requests related to UE authentication procedures. It registers the default handlers for each SBI operation defined in the Nausf_UEAuthentication service.
* `internal/sbi/upuprotection/api_default.go`: This file defines the default handlers for the SBI requests related to user plane protection. It implements the Nausf_UserPlaneProtection service defined in 3GPP TS 29.503. It allows the AUSF to receive requests from the SMF for applying user plane protection policies and rules to the UE sessions.
* `internal/sbi/upuprotection/routers.go`: This file defines the routers for handling SBI requests related to user plane protection. It registers the default handlers for each SBI operation defined in the Nausf_UserPlaneProtection service.
* `pkg/factory/config.go`: This file defines the data structures and methods for parsing and validating the configuration file of the AUSF module. It uses viper as the configuration library and provides some helper functions for accessing and setting configuration values.
* `pkg/factory/factory.go`: This file defines some common functions for initializing and validating different components of free5GC, such as logger, configuration, NF profile, etc. It also provides some constants and variables for common paths and names used in free5GC.
* `pkg/service/init.go`: This file defines some common functions for initializing and running different services of free5GC, such as HTTP server, NF discovery, NF management, etc. It also provides some constants and variables for common service names and URIs used in free5GC.

## Files that are responsible for communication between AUSF and UDM&AMF
The files that are responsible for communication between AUSF and AMF in the free5gc source code for AUSF are:
* The file **routers.go in the upuprotection** folder defines the HTTP router for handling requests related to User Plane Integrity Protection. This feature ensures that the data sent between the user equipment (UE) and the network is not tampered with or modified.

* The file **routers.go in the ueauthentication** folder defines the HTTP router for handling requests related to UE Authentication. This feature verifies the identity and credentials of the UE before allowing it to access the network services.

* The file **routers.go in the sorprotection** folder defines the HTTP router for handling requests related to SOR Protection. SOR stands for Security Anchor of Registration, which is a mechanism to protect the UE’s registration status and subscription data from being compromised by malicious actors.

* The file **ue_authentication.go in the producer** folder defines the business logic for handling UE Authentication requests. It implements various functions such as HandleUeAuthPostRequest, HandleAuth5gAkaComfirmRequest, HandleEapAuthComfirmRequest, etc. that perform different steps of the authentication process, such as generating authentication vectors, verifying authentication responses, generating security keys, etc.

## Trying to edit api_default.go in ueauthentication folder
from this
```go!
// HTTPUeAuthenticationsPost -
func HTTPUeAuthenticationsPost(ctx *gin.Context) {
	var authInfo models.AuthenticationInfo

	requestBody, err := ctx.GetRawData()
	if err != nil {
		problemDetail := models.ProblemDetails{
			Title:  "System failure",
			Status: http.StatusInternalServerError,
			Detail: err.Error(),
			Cause:  "SYSTEM_FAILURE",
		}
		logger.UeAuthLog.Errorf("Get Request Body error: %+v", err)
		ctx.JSON(http.StatusInternalServerError, problemDetail)
		return
	}

	err = openapi.Deserialize(&authInfo, requestBody, "application/json")
	if err != nil {
		problemDetail := "[Request Body] " + err.Error()
		rsp := models.ProblemDetails{
			Title:  "Malformed request syntax",
			Status: http.StatusBadRequest,
			Detail: problemDetail,
		}
		logger.UeAuthLog.Errorln(problemDetail)
		ctx.JSON(http.StatusBadRequest, rsp)
		return
	}

	req := httpwrapper.NewRequest(ctx.Request, authInfo)

	rsp := producer.HandleUeAuthPostRequest(req)

	for key, value := range rsp.Header {
		ctx.Header(key, value[0])
	}
	responseBody, err := openapi.Serialize(rsp.Body, "application/json")
	if err != nil {
		logger.UeAuthLog.Errorln(err)
		problemDetails := models.ProblemDetails{
			Status: http.StatusInternalServerError,
			Cause:  "SYSTEM_FAILURE",
			Detail: err.Error(),
		}
		ctx.JSON(http.StatusInternalServerError, problemDetails)
	} else {
		ctx.Data(rsp.Status, "application/json", responseBody)
	}
}
```
to this
```go!
// Import the amqp package
import (
    "log"
    "github.com/streadway/amqp"
)

// Create a global variable for the connection
var conn *amqp.Connection

// Modify the HTTPUeAuthenticationsPost function
func HTTPUeAuthenticationsPost(ctx *gin.Context) {
    var authInfo models.AuthenticationInfo
    requestBody, err := ctx.GetRawData()
    if err != nil {
        log.Fatalf("Failed to get request body: %v", err)
    }
    err = openapi.Deserialize(&authInfo, requestBody, "application/json")
    if err != nil {
        log.Fatalf("Failed to deserialize request body: %v", err)
    }
    // Create a channel
    ch, err := conn.Channel()
    if err != nil {
        log.Fatalf("Failed to open a channel: %v", err)
    }
    defer ch.Close()

    // Declare a queue
    q, err := ch.QueueDeclare(
        "auth_queue", // name of the queue
        false,        // durable
        false,        // delete when unused
        false,        // exclusive
        false,        // no-wait
        nil,          // arguments
    )
    if err != nil {
        log.Fatalf("Failed to declare a queue: %v", err)
    }

    // Publish a message to the queue
    err = ch.Publish(
        "",     // exchange
        q.Name, // routing key
        false,  // mandatory
        false,  // immediate
        amqp.Publishing{
            ContentType: "application/json",
            Body:        requestBody,
        })
    if err != nil {
        log.Fatalf("Failed to publish a message: %v", err)
    }

    // Send a response to the client
    ctx.JSON(http.StatusOK, gin.H{
        "message": "Authentication request sent to the queue",
    })
}
```
I also need to create a new file for the RabbitMQ
```go!
import (
    "log"
    "github.com/streadway/amqp"
)

func main() {
    // Connect to the RabbitMQ server
    conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
    if err != nil {
        log.Fatalf("Failed to connect to RabbitMQ: %v", err)
    }
    defer conn.Close()

    // Create a channel
    ch, err := conn.Channel()
    if err != nil {
        log.Fatalf("Failed to open a channel: %v", err)
    }
    defer ch.Close()

    // Declare a queue
    q, err := ch.QueueDeclare(
        "test_queue", // name of the queue
        false,        // durable
        false,        // delete when unused
        false,        // exclusive
        false,        // no-wait
        nil,          // arguments
    )
    if err != nil {
        log.Fatalf("Failed to declare a queue: %v", err)
    }
}
```