Skip to content

AMF Integration test cases #8

@pranav-kumar-hex

Description

@pranav-kumar-hex

Issue Description

Create comprehensive integration test cases for the AMF (Access and Mobility Management Function) in Rust, building upon the integration testing infrastructure established in PR #5 (Integration Testing).

Background

PR #5 introduced a complete integration testing framework with:

  • Docker Compose orchestration of 5G Core Network Functions
  • Packet capture and analysis system with HTTP/2 decoder
  • MongoDB integration for storing network traffic analysis
  • OMEC gnbsim integration for realistic gNB simulation

This issue focuses on creating AMF-specific integration tests that leverage the existing infrastructure to validate AMF functionality through real network transactions.

Objectives

Primary Goals

  1. AMF Transaction Testing: Create integration tests that validate AMF behavior by analyzing real network transactions between AMF and other Network Functions
  2. MongoDB Change Stream Integration: Implement real-time test validation using MongoDB Change Streams to monitor transaction flows
  3. End-to-End Validation: Test complete AMF workflows from initial UE attachment to service establishment

Secondary Goals

  • Performance benchmarking under various load conditions
  • Protocol compliance validation against 3GPP specifications
  • Network slice selection testing with NSSF integration
  • Security validation with mutual TLS authentication

Technical Requirements

1. MongoDB Integration

  • Database: Connect to MongoDB running on localhost:27017 (default port)
  • Collection: Use the existing packet_analysis collection from the packet capture system
  • Change Streams: Implement MongoDB Change Streams to monitor real-time transaction insertions
  • Data Structure: Leverage the existing packet analysis data structure with HTTP/2 decoded payloads

2. Network Function Interactions

The AMF integration tests should validate interactions with the following NFs:

Core Interactions

  • NRF (Network Repository Function):
    • NF Registration/Discovery procedures
    • Service authorization and profile management
  • AUSF (Authentication Server Function):
    • 5G-AKA authentication procedures
    • Nausf_UEAuthentication service operations
  • UDM (Unified Data Management):
    • Subscriber data retrieval via Nudm_UECM
    • Registration management procedures

Session Management

  • SMF (Session Management Function):
    • PDU Session establishment procedures
    • Namf_Communication service interactions
  • PCF (Policy Control Function):
    • Policy association establishment
    • Access and mobility policy enforcement

Network Slicing

  • NSSF (Network Slice Selection Function):
    • Network slice selection procedures
    • S-NSSAI validation and authorization

3. Test Architecture

// Example test structure
#[cfg(test)]
mod amf_integration_tests {
    use super::*;
    use mongodb::{Client, options::ClientOptions, change_stream::event::ChangeStreamEvent};
    use tokio_stream::StreamExt;
    
    struct AMFTestFramework {
        mongo_client: mongodb::Client,
        change_stream: mongodb::change_stream::ChangeStream<Document>,
        test_context: AMFTestContext,
    }
    
    #[tokio::test]
    async fn test_ue_registration_flow() {
        // Implementation details below
    }
    
    #[tokio::test]
    async fn test_pdu_session_establishment() {
        // Implementation details below
    }
}

4. Test Cases to Implement

A. UE Registration Tests

#[tokio::test]
async fn test_ue_initial_registration() {
    // 1. Start change stream monitoring
    // 2. Trigger UE registration via gnbsim
    // 3. Monitor MongoDB for AMF ↔ AUSF authentication flow
    // 4. Validate AMF ↔ UDM subscriber data retrieval
    // 5. Verify AMF ↔ NRF service discovery transactions
    // 6. Assert successful registration completion
}

#[tokio::test]
async fn test_ue_mobility_registration_update() {
    // Test TAU (Tracking Area Update) procedures
    // Monitor AMF ↔ UDM location update transactions
}

#[tokio::test]
async fn test_ue_deregistration() {
    // Test explicit and implicit deregistration flows
    // Validate cleanup transactions with all involved NFs
}

B. Authentication and Security Tests

#[tokio::test]
async fn test_5g_aka_authentication_success() {
    // Monitor AMF ↔ AUSF authentication vector exchange
    // Validate proper NAS security mode establishment
}

#[tokio::test]
async fn test_authentication_failure_scenarios() {
    // Test authentication sync failure
    // Test authentication reject scenarios
}

#[tokio::test]
async fn test_mutual_tls_validation() {
    // Validate TLS handshake between AMF and other NFs
    // Monitor certificate validation in packet capture
}

C. Session Management Tests

#[tokio::test]
async fn test_pdu_session_establishment() {
    // 1. Monitor change stream for session-related transactions
    // 2. Trigger PDU session establishment via UE
    // 3. Validate AMF ↔ SMF Nsmf_PDUSession service calls
    // 4. Monitor AMF ↔ PCF policy association establishment
    // 5. Assert successful session activation
}

#[tokio::test]
async fn test_pdu_session_modification() {
    // Test QoS parameter updates
    // Monitor policy enforcement transactions
}

#[tokio::test]
async fn test_pdu_session_release() {
    // Test session teardown procedures
    // Validate resource cleanup across NFs
}

D. Network Slicing Tests

#[tokio::test]
async fn test_network_slice_selection() {
    // 1. Configure multiple network slices in test environment
    // 2. Monitor AMF ↔ NSSF slice selection transactions
    // 3. Validate S-NSSAI selection based on subscriber profile
    // 4. Assert proper slice-specific SMF selection
}

#[tokio::test]
async fn test_slice_admission_control() {
    // Test slice resource availability checks
    // Validate slice rejection scenarios
}

E. Error Handling and Resilience Tests

#[tokio::test]
async fn test_nf_service_unavailable() {
    // Simulate NF failures (AUSF, UDM, SMF down scenarios)
    // Monitor AMF retry mechanisms and error handling
    // Validate proper error responses to UE/gNB
}

#[tokio::test]
async fn test_network_congestion_handling() {
    // Test AMF behavior under high load conditions
    // Monitor transaction timeouts and queue management
}

#[tokio::test]
async fn test_configuration_update_scenarios() {
    // Test dynamic configuration updates
    // Validate AMF adaptation to configuration changes
}

Implementation Details

1. MongoDB Change Stream Setup

use mongodb::{
    bson::{doc, Document},
    change_stream::event::ChangeStreamEvent,
    options::{ChangeStreamOptions, FullDocumentType},
    Client, Collection,
};
use tokio_stream::StreamExt;

async fn setup_change_stream(collection: &Collection<Document>) -> mongodb::error::Result<mongodb::change_stream::ChangeStream<Document>> {
    let pipeline = vec![
        doc! {
            "$match": {
                "operationType": "insert",
                "fullDocument.source_ip": {
                    "$in": ["10.0.0.2"] // AMF IP from docker-compose
                }
            }
        }
    ];
    
    let options = ChangeStreamOptions::builder()
        .full_document(Some(FullDocumentType::UpdateLookup))
        .build();
    
    collection.watch(pipeline, options).await
}

2. Transaction Analysis Framework

#[derive(Debug, Clone)]
struct AMFTransaction {
    pub timestamp: DateTime<Utc>,
    pub source_nf: String,
    pub target_nf: String,
    pub http_method: String,
    pub uri_path: String,
    pub headers: HashMap<String, String>,
    pub request_body: Option<Document>,
    pub response_body: Option<Document>,
    pub status_code: u16,
    pub transaction_id: String,
}

impl AMFTransaction {
    fn from_mongodb_document(doc: &Document) -> Result<Self, Error> {
        // Parse packet analysis document into structured transaction
        // Extract HTTP/2 decoded payloads from the existing packet capture system
    }
    
    fn is_registration_related(&self) -> bool {
        self.uri_path.contains("/ue-contexts") || 
        self.uri_path.contains("/registrations")
    }
    
    fn is_authentication_related(&self) -> bool {
        self.uri_path.contains("/authenticate") ||
        self.target_nf == "AUSF"
    }
}

3. Test Assertion Framework

struct TransactionMatcher {
    expected_sequence: Vec<TransactionPattern>,
    timeout: Duration,
}

#[derive(Debug)]
struct TransactionPattern {
    source_nf: String,
    target_nf: String,
    uri_pattern: Regex,
    method: String,
    expected_status: u16,
}

impl TransactionMatcher {
    async fn wait_for_sequence(&self, change_stream: &mut ChangeStream<Document>) -> Result<Vec<AMFTransaction>, TestError> {
        let mut matched_transactions = Vec::new();
        let start_time = Instant::now();
        
        while start_time.elapsed() < self.timeout {
            if let Some(event) = change_stream.next().await {
                match event {
                    Ok(ChangeStreamEvent::Insert { full_document: Some(doc), .. }) => {
                        if let Ok(transaction) = AMFTransaction::from_mongodb_document(&doc) {
                            if self.matches_pattern(&transaction) {
                                matched_transactions.push(transaction);
                            }
                        }
                    }
                    _ => continue,
                }
                
                if self.sequence_complete(&matched_transactions) {
                    break;
                }
            }
        }
        
        if self.sequence_complete(&matched_transactions) {
            Ok(matched_transactions)
        } else {
            Err(TestError::SequenceIncomplete(matched_transactions))
        }
    }
}

4. Test Data Setup

#[derive(Debug)]
struct AMFTestContext {
    pub test_ue_imsi: String,
    pub test_plmn: String,
    pub test_slice_info: Vec<SNSSAI>,
    pub gnbsim_config: GnbSimConfig,
}

impl AMFTestContext {
    async fn setup_test_subscriber(&self) -> Result<(), Error> {
        // Use the existing user-init service to create test subscriber
        // Configure subscriber in UDM with specific test parameters
    }
    
    async fn trigger_ue_registration(&self) -> Result<(), Error> {
        // Trigger registration via gnbsim API
        // Return after initial NAS message is sent
    }
    
    async fn cleanup(&self) -> Result<(), Error> {
        // Clean up test data from all NFs
        // Reset gnbsim state
    }
}

Success Criteria

Functional Validation

  • All UE registration flows complete successfully with proper transaction sequences
  • Authentication procedures validate against 3GPP TS 33.501 specifications
  • PDU session establishment follows proper AMF ↔ SMF interactions
  • Network slice selection operates correctly with NSSF integration
  • Error scenarios are handled gracefully with appropriate NAS responses

Performance Validation

  • Tests complete within defined timeout thresholds (default: 30 seconds per test)
  • AMF handles concurrent registrations (target: 100 concurrent UEs)
  • Transaction latencies remain within acceptable bounds (<2 seconds per procedure)

Integration Validation

  • MongoDB Change Streams capture all relevant AMF transactions
  • Packet capture system successfully decodes all HTTP/2 SBI messages
  • Test framework properly correlates multi-NF transaction flows
  • Cleanup procedures restore system to clean state between tests

Dependencies

Infrastructure Dependencies

  • Docker Compose environment from PR Integration Testing #5
  • MongoDB instance running on localhost:27017
  • Packet capture system with HTTP/2 decoder
  • OMEC gnbsim for UE/gNB simulation

Rust Dependencies

[dev-dependencies]
tokio = { version = "1.0", features = ["full"] }
mongodb = "2.8"
tokio-stream = "0.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1.0", features = ["v4"] }
regex = "1.0"
anyhow = "1.0"
tracing = "0.1"
tracing-subscriber = "0.3"

5G Core Dependencies

  • All Network Functions must be operational and discoverable via NRF
  • TLS certificates properly configured for mutual authentication
  • Network slice configurations loaded in NSSF
  • Subscriber profiles configured in UDM/UDR

Timeline

Phase 1 (Week 1-2): Foundation

  • Setup MongoDB Change Stream integration
  • Implement basic transaction parsing from packet capture
  • Create AMF test context and cleanup mechanisms

Phase 2 (Week 3-4): Core Tests

  • Implement UE registration test cases
  • Add authentication and security validation tests
  • Create session management test suite

Phase 3 (Week 5-6): Advanced Features

  • Network slicing integration tests
  • Error handling and resilience tests
  • Performance benchmarking integration

Phase 4 (Week 7): Documentation and CI

  • Comprehensive test documentation
  • CI/CD pipeline integration
  • Performance baseline establishment

Acceptance Criteria

  1. Test Coverage: Minimum 80% coverage of AMF core procedures (registration, authentication, session management)
  2. Reliability: Tests pass consistently (>95% success rate) in clean environment
  3. Performance: Test suite completes within 10 minutes for full regression
  4. Maintainability: Clear test structure with proper error reporting and debugging capabilities
  5. Integration: Seamless integration with existing CI/CD pipeline and development workflow

Additional Considerations

Monitoring and Observability

  • Integrate with existing logging infrastructure
  • Provide detailed transaction traces for debugging failed tests
  • Export test metrics for performance trend analysis

Security Testing

  • Validate TLS certificate handling and mutual authentication
  • Test AMF behavior with malformed or malicious NAS messages
  • Verify proper access control and authorization mechanisms

Scalability Testing

  • Test AMF performance under various load conditions
  • Validate resource usage and memory management
  • Test concurrent multi-UE scenarios with different slice requirements

This comprehensive integration testing framework will provide robust validation of AMF functionality while leveraging the existing infrastructure established in PR #5, ensuring reliable and maintainable test coverage for the UnifyAir 5G core network implementation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions