Skip to content

RPC GO Developer's Guide

shaoboon edited this page Jan 29, 2026 · 2 revisions

RPC-Go Developer Guide

Table of Contents

  1. Overview
  2. Architecture
  3. Project Structure
  4. Core Components
  5. Development Setup
  6. Implementation Details
  7. Testing
  8. Contributing
  9. API Reference

Overview

RPC-Go is a Remote Provisioning Client for Intel® Active Management Technology (AMT). It provides functionality for:

  • Activation: Enable AMT in CCM (Client Control Mode) or ACM (Admin Control Mode)
  • Deactivation: Disable or unprovision AMT devices
  • Configuration: Configure AMT features, networking, TLS, and other settings
  • Management: Query AMT status, version information, and device details

Key Features

  • Cross-platform support (Windows, Linux)
  • Local and remote activation modes
  • Profile-based configuration management
  • JSON and text output formats
  • Library integration support (C-shared library)
  • Comprehensive CLI interface

Deployment Scenarios & Execution Flow

RPC-Go supports two primary deployment patterns with distinct execution flows:

🖥️ Console Mode - Local Direct Execution

Command Example:

# Local activation with YAML profile and encryption key
sudo ./rpc activate --profile acmProfile.yaml --key AsfQcldDxDuFocYjT0ZUZhEFi6lGxbQX

# Simple local CCM activation
sudo ./rpc activate --ccm --password admin123

# Simple local ACM activation  
sudo ./rpc activate --acm --provisioning-cert <cert-file> --password admin123

Execution Flow:

CLI Input → Kong Parsing → Local Hardware Detection → 
Profile Loading (if specified) → HECI/PTHI Communication → 
AMT Activation → Configuration Application → Text/JSON Output

Characteristics:

  • Direct hardware access via HECI/PTHI drivers
  • Local profile configuration from YAML files (with optional encryption)
  • Interactive AMT management with immediate feedback
  • Administrator/IT technician workflows on individual devices
  • Development and testing scenarios

☁️ Cloud Mode - Remote Provisioning Server

Command Example:

# Remote activation via RPS with WebSocket connection
sudo ./rpc activate --url wss://<IP>/activate --profile ccm --verbose

Execution Flow:

CLI Input → Kong Parsing → RPS WebSocket Connection → 
Profile Fetch from Server → Remote Authentication → 
Cloud-Based Activation → JSON Response Processing → Automated Integration

Characteristics:

  • Remote activation via RPS (Remote Provisioning Server) over WebSocket
  • Cloud-hosted profile management fetched from server
  • Automated AMT provisioning at scale
  • JSON output optimized for parsing and automation
  • Enterprise management system integration
  • C-shared library support for platform embedding

Architecture

RPC-Go follows a modular, layered architecture with clear separation of concerns and multiple communication paths:

┌─────────────────────────────────────────────────────────────────────────────────────┐
│                                CLI Layer                                            │
│  ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ ┌─────────────────────────┐  │
│  │   Kong CLI  │ │   Globals   │ │ Command Parsing │ │   Config File Support   │  │
│  │  Framework  │ │   & Flags   │ │   & Routing     │ │   (YAML + Env Vars)     │  │
│  └─────────────┘ └─────────────┘ └─────────────────┘ └─────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────────────┘
                                          │
┌─────────────────────────────────────────────────────────────────────────────────────┐
│                              Command Layer                                          │
│  ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────────────────────────┐  │
│  │  Activate   │ │ Deactivate  │ │              Configure                      │  │
│  │  (CCM/ACM)  │ │ (Full/Part) │ │  ┌─────────┐ ┌─────────┐ ┌──────────────┐  │  │
│  │             │ │             │ │  │ Network │ │Features │ │ Security/TLS │  │  │
│  │  AmtInfo    │ │   Version   │ │  │Settings │ │& Access │ │ & Certificates│  │  │
│  │(Status/Info)│ │             │ │  └─────────┘ └─────────┘ └──────────────┘  │  │
│  └─────────────┘ └─────────────┘ └─────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────────────┘
                                          │
┌─────────────────────────────────────────────────────────────────────────────────────┐
│                          Business Logic Layer                                      │
│  ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ ┌───────────────────────┐  │
│  │Orchestrator │ │   Profile   │ │   Activation    │ │    Configuration      │  │
│  │  Service    │ │   Fetcher   │ │   Services      │ │     Services          │  │
│  │(Multi-step) │ │(HTTP/Local) │ │  (Local/Remote) │ │  (Feature/Network)    │  │
│  │             │ │             │ │                 │ │                       │  │
│  │  ┌─────────┐ │ │  ┌─────────┐ │ │  ┌─────────┐  │ │  ┌─────────────────┐  │  │
│  │  │  RPS    │ │ │  │  Cert   │ │ │  │Local    │  │ │  │   Certificate   │  │  │
│  │  │ Client  │ │ │  │ Manager │ │ │  │Service  │  │ │  │    Manager      │  │  │
│  │  └─────────┘ │ │  └─────────┘ │ │  └─────────┘  │ │  └─────────────────┘  │  │
│  └─────────────┘ └─────────────┘ └─────────────────┘ └───────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────────────┘
                                          │
┌─────────────────────────────────────────────────────────────────────────────────────┐
│                        Hardware Interface Layer                                    │
│  ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│  │   Local AMT     │ │     WSMAN       │ │      HECI       │ │    Network      │ │
│  │   Interface     │ │    Client       │ │     Driver      │ │   Utilities     │ │
│  │  (PTHI/HECI)    │ │   (HTTP/TLS)    │ │  (Platform-     │ │ (DHCP/WiFi/     │ │
│  │                 │ │                 │ │   specific)     │ │  Ethernet)      │ │
│  │  ┌───────────┐  │ │  ┌───────────┐  │ │  ┌───────────┐  │ │  ┌───────────┐ │ │
│  │  │Intel ME   │  │ │  │TLS Client │  │ │  │Linux HECI│  │ │  │OS Network │ │ │
│  │  │Interface  │  │ │  │for AMT    │  │ │  │Windows   │  │ │  │Interface  │ │ │
│  │  └───────────┘  │ │  └───────────┘  │ │  │ HECI     │  │ │  └───────────┘ │ │
│  └─────────────────┘ └─────────────────┘ │  └───────────┘  │ └─────────────────┘ │
└─────────────────────────────────────────┘─────────────────┘─────────────────────────┘
                                          │
┌─────────────────────────────────────────────────────────────────────────────────────┐
│                          Hardware/Firmware Layer                                   │
│  ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│  │   Intel AMT     │ │   Intel ME      │ │   Network       │ │   Platform      │ │
│  │   Firmware      │ │   Firmware      │ │   Hardware      │ │   Hardware      │ │
│  │   (Management   │ │   (Security     │ │   (Ethernet/    │ │   (CPU/BIOS/    │ │
│  │    Features)    │ │    Engine)      │ │    WiFi)        │ │    UEFI)        │ │
│  └─────────────────┘ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────────────┘

Architectural Principles

1. Layered Separation

  • CLI Layer: User interface, argument parsing, and global configuration
  • Command Layer: Command-specific logic and validation
  • Business Logic: Core application services and orchestration
  • Hardware Interface: Platform abstraction and communication protocols
  • Hardware/Firmware: Intel AMT/ME hardware and firmware

2. Multiple Communication Paths

  • Direct Hardware Access: HECI/PTHI for low-level AMT operations
  • Network-based Management: WSMAN over HTTP/TLS for configuration
  • Remote Provisioning: RPS client for cloud-based activation
  • Profile-based Configuration: Orchestrated multi-command execution

3. Cross-Platform Support

  • Windows: Uses Windows HECI driver and Windows-specific APIs
  • Linux: Uses Linux MEI driver and Linux-specific network interfaces
  • Common Interface: Unified Go interfaces abstract platform differences

Communication Flow & Patterns

1. Command Execution Flow 🖥️ Console | ☁️ Cloud

User Input → CLI Parsing → Command Validation → Context Building → 
Service Execution → Hardware Communication → Response Processing → Output

2. Authentication & Security Flow 🖥️ Console | ☁️ Cloud

Password Collection (CLI/ENV/Config/Prompt) → AMT Connection Setup →
TLS Certificate Validation → WSMAN Client Creation → 
Authenticated Command Execution

3. Activation Flow

🖥️ Console (Local Activation):

AMT State Validation → Hardware Enablement → Mode Selection (CCM/ACM) →
Certificate Processing (ACM only) → Activation Execution → 
Configuration Application → Verification

☁️ Cloud (Remote Activation):

WebSocket Connection → RPS Authentication → Profile Request →
Server-side Activation → Response Processing → Status Verification

4. Profile Orchestration Flow 🖥️ Console | ☁️ Cloud

Profile Fetch/Load → Profile Validation → Multi-step Execution:
(Activation → MEBx Config → Features → Networking → TLS → CIRA) →
Verification & Reporting

5. Configuration Command Flow 🖥️ Console | ☁️ Cloud

Runtime Initialization → Password Validation → WSMAN Client Setup →
Device State Verification → Configuration Application → 
AMT Reboot/Restart (if needed) → Verification

Key Architectural Components

Context System

The Context struct carries shared state and dependencies:

type Context struct {
    AMTCommand       amt.Interface      // Hardware interface
    ControlMode      int               // Current AMT mode (CCM/ACM)
    AMTPassword      string            // Centralized password
    JsonOutput       bool              // Output formatting
    SkipCertCheck    bool             // TLS validation flags
    WSMANClient      interfaces.WSMANer // Network client
    // ... other shared state
}

Interface Abstraction

All hardware interactions go through well-defined interfaces:

  • amt.Interface - Core AMT operations (activation, status, etc.)
  • interfaces.WSMANer - WSMAN-based configuration operations
  • heci.Interface - Low-level hardware communication
  • pthi.Interface - Platform Trust Hardware Interface

Command Pattern

All commands implement consistent interfaces:

type Command interface {
    Validate() error                    // Input validation
    Run(ctx *Context) error            // Command execution
}

type PasswordRequirer interface {
    RequiresAMTPassword() bool         // Password requirement indication
}

Architecture Deep Dive

Design Philosophy

RPC-Go follows a layered architecture with clear separation of concerns. Each layer has specific responsibilities and communicates through well-defined interfaces. This design enables:

  • Modularity: Each component can be developed and tested independently
  • Cross-platform support: Platform differences are abstracted at the right layers
  • Testability: Interfaces allow for easy mocking and unit testing
  • Extensibility: New commands and features can be added without affecting existing code

Layer-by-Layer Analysis

Layer 1: CLI Layer - The User Interface

This is where user interaction begins, handling command-line parsing and configuration complexity.

Components & Responsibilities:

// Global flags affecting all commands
type Globals struct {
    LogLevel         string `help:"Set log level" default:"info"`
    JsonOutput       bool   `help:"Output in JSON format"`
    AMTPassword      string `help:"AMT admin password" env:"AMT_PASSWORD"`
    SkipCertCheck    bool   `help:"Skip certificate verification"`
}

Processing Flow:

  1. User input: sudo ./rpc activate -u wss://<IP>/activate --profile=acmProfile
  2. Kong parses into structured command + flags
  3. Global settings (logging, output format) applied
  4. Password collected from CLI, config file, or environment
  5. Control passes to Command Layer

Layer 2: Command Layer - Business Logic Coordinators

Each command type implements specific business logic with inherited common functionality.

Base Command Structure:

type AMTBaseCmd struct {
    LocalTLSEnforced bool
    ControlMode      int                    // Cached current AMT control mode (0=pre-provision, 1=CCM, 2=ACM)
    WSMan           interfaces.WSMANer     // WSMAN client
}

Command Categories:

Activation Commands:

type ActivateCmd struct {
    AMTBaseCmd
    Local bool   // Force local activation
    URL   string // RPS server URL for remote
    CCM   bool   // Client Control Mode
    ACM   bool   // Admin Control Mode
}

Configuration Commands:

  • Network: wired, wireless, wifisync - Ethernet, WiFi, and sync settings
  • Features: amtfeatures - KVM, SOL, IDER redirection capabilities
  • Security: tls - Certificate management and TLS configuration
  • System: syncclock, synchostname - System synchronization
  • Remote: cira, proxy - Remote access and proxy configuration

Information Commands:

type AmtInfoCmd struct {
    Ver      bool // AMT Version
    UUID     bool // Unique Identifier  
    Mode     bool // Control Mode
    Lan      bool // LAN Settings
    Cert     bool // Certificate Information
}

Layer 3: Business Logic Layer - Service Orchestrators

Core business services implementing AMT management logic.

1. Profile Orchestrator - Multi-step Operations

type ProfileOrchestrator struct {
    profile        *profile.Profile
    globalPassword string
    executor       CommandExecutor
}

Orchestration Flow:

1. Activation (CCM/ACM mode setup)
2. MEBx Password Configuration (ACM only)  
3. AMT Features Setup (KVM, SOL, IDER)
4. Network Configuration (Wired settings)
5. WiFi Port Enablement
6. Wireless Profile Creation
7. TLS Certificate Configuration
8. CIRA Remote Access Setup
9. Verification & Cleanup

2. Activation Services - Local/Remote Provisioning

type LocalActivationService struct {
    wsman            interfaces.WSMANer
    amtCommand       amt.Interface
    config           LocalActivationConfig
    localTLSEnforced bool
}

Activation Process:

validateAMTState() → validateConfiguration() → enableAMT() → 
activateCCM()/activateACM() → postActivationConfig()

3. Configuration Services - Feature & Network Management

  • Certificate Manager: X.509 certificates, Enterprise Assistant integration
  • Network Services: Ethernet (DHCP/static), WiFi profiles, 802.1X authentication
  • Security Services: TLS configuration, proxy settings

Layer 4: Hardware Interface Layer - Platform Abstraction

Abstracts different communication methods with Intel AMT hardware.

1. Local AMT Interface (PTHI/HECI)

type AMTCommand struct {
    PTHI pthi.Interface
}

type Interface interface {
    Initialize() error
    GetControlMode() (int, error)
    EnableAMT() error
    GetVersionDataFromME(key string, timeout time.Duration) (string, error)
    Unprovision() (mode int, err error)
    // 20+ more hardware interface methods
}

Used for: Device activation/deactivation, status queries, hardware enablement

2. WSMAN Client (HTTP/TLS Network)

type GoWSMANMessages struct {
    wsmanMessages *messages.Messages
    client        *wsman.Client
}

Used for: Advanced configuration, certificate management, network settings

3. Platform-Specific HECI Drivers

  • Linux: Uses MEI driver (/dev/mei* devices)
  • Windows: Uses Windows HECI driver APIs
  • Common Interface: Platform differences abstracted through Go interfaces

Layer 5: Hardware/Firmware Layer - Intel Hardware Stack

  • Intel AMT Firmware: Management features (KVM, SOL, IDER, power management)
  • Intel ME Firmware: Security engine (secure boot, crypto, hardware security)
  • Network Hardware: Ethernet/WiFi interfaces, Wake-on-LAN
  • Platform Hardware: CPU, BIOS/UEFI integration

Communication Paths & Data Flow

1. Direct Hardware Access (HECI/PTHI)

CLI Command → AMT Interface → PTHI → HECI Driver → Intel ME → AMT Firmware

Use Cases: Activation, status queries, basic operations

2. Network Management (WSMAN)

CLI Command → WSMAN Client → HTTP/TLS → AMT Network Stack → Configuration

Use Cases: Advanced configuration, certificates, network settings

3. Remote Provisioning (RPS)

RPC Client → RPS Server → Cloud Management → Device Configuration

Use Cases: Cloud-based activation, centralized management

4. Profile Orchestration (Multi-step)

Profile → Orchestrator → Sequential Commands → Multiple Interfaces → Complete Setup

Key Design Patterns

Interface-Based Architecture

// Hardware abstraction
type Interface interface {
    Initialize() error
    GetControlMode() (int, error)
}

// Network management abstraction  
type WSMANer interface {
    GetGeneralSettings() (general.Response, error)
    PutGeneralSettings(request general.GeneralSettingsRequest) (general.Response, error)
}

Benefits: Testing with mocks, platform flexibility, interface evolution

Context Pattern

type Context struct {
    AMTCommand       amt.Interface          // Hardware interface
    ControlMode      int                   // Current AMT state
    AMTPassword      string                // Centralized password
    JsonOutput       bool                  // Output formatting
    WSMANClient      interfaces.WSMANer    // Network client
    SkipCertCheck    bool                 // TLS validation flags
}

Purpose: Shared state and dependency injection across command execution

Factory Pattern

// Component creation through factories
amtCommand := amt.NewAMTCommand()
wsmanClient := localamt.NewGoWSMANMessages(utils.LMSAddress)
orchestrator := orchestrator.NewProfileOrchestrator(profile, password)

Error Handling Architecture

Typed Errors

type CustomError struct {
    Message string
    Code    int
}

var (
    AMTConnectionFailed = CustomError{"Failed to connect to AMT", 1}
    DeviceNotActivated = CustomError{"Device not activated", 2}
)

Error Propagation

// Layer 4: Hardware error
err := heci.SendMessage(buffer)

// Layer 3: Service error with context
return fmt.Errorf("failed to communicate with AMT: %w", err)

// Layer 2: Command error with business context
return fmt.Errorf("activation failed: %w", err)

// Layer 1: User-friendly logging
log.Error("AMT activation failed. Check hardware and permissions.")

Security Architecture

Authentication Flow

Password Collection → AMT Connection → TLS Validation → 
Authentication → Secure Command Execution

Certificate Management

type CertificateHandles struct {
    RootCertHandle   string  // CA certificate
    ClientCertHandle string  // Client certificate  
    KeyPairHandle    string  // Public/private key pair
    PrivateKeyHandle string  // Private key only
}

Certificate Lifecycle: Generate/Load → Install → Configure → Verify → Cleanup

Platform Abstraction

Windows Implementation

  • Windows HECI driver APIs
  • Windows-specific network detection
  • Windows certificate store integration
  • Windows service capabilities

Linux Implementation

  • Linux MEI driver (/dev/mei*)
  • Linux network utilities
  • Root privilege requirements
  • systemd integration

Common Interface

type Interface interface {
    Init(useLME, useWD bool) error
    SendMessage(buffer []byte, done *uint32) (int, error)
    ReceiveMessage(buffer []byte, done *uint32) (int, error) 
    Close()
}

Implementation Files: heci_linux.go, heci_windows.go

Concurrency & Performance Considerations

Synchronous Design

Most operations are blocking by design because:

  • Hardware operations have inherent latency
  • AMT firmware expects sequential operations
  • Simplified error handling and state management
  • Typical use cases don't require high concurrency

Background Operations

// Long-running operations with timeouts
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

// Profile orchestration with progress reporting
go orchestrator.ExecuteProfile()

Testing Architecture

Interface Mocking

// Mock AMT interface for testing
type MockAMTCommand struct {
    controlMode   int
    shouldError   bool
}

func (m *MockAMTCommand) GetControlMode() (int, error) {
    if m.shouldError {
        return 0, errors.New("mock error")
    }
    return m.controlMode, nil
}

Test Categories

  • Unit Tests: Individual component testing with mocks
  • Integration Tests: Real hardware interaction (when available)
  • Command Tests: End-to-end command validation
  • Profile Tests: Multi-step orchestration validation

This layered architecture provides RPC-Go with robust cross-platform AMT management capabilities while maintaining clean separation of concerns, excellent testability, and clear extension points for future development.

Project Structure

rpc-go/
├── cmd/rpc/                    # Main entry points
│   ├── main.go                 # Executable entry point
│   └── lib.go                  # C library exports
├── internal/                   # Internal packages
│   ├── cli/                    # CLI parsing and setup
│   ├── commands/               # Command implementations
│   │   ├── activate/           # Activation commands
│   │   ├── configure/          # Configuration sub-commands
│   │   ├── base.go             # Shared command functionality
│   │   ├── amtinfo.go          # AMT information command
│   │   ├── deactivate.go       # Deactivation command
│   │   └── version.go          # Version command
│   ├── certs/                  # Certificate management
│   ├── interfaces/             # Internal interfaces
│   ├── lm/                     # Local Management service
│   ├── local/amt/              # Local AMT interface
│   ├── mocks/                  # Test mocks
│   ├── orchestrator/           # Profile orchestration
│   ├── profile/                # Profile handling
│   └── rps/                    # Remote Provisioning Server client
├── pkg/                        # Public packages
│   ├── amt/                    # AMT command interface
│   ├── heci/                   # Hardware Event Channel Interface
│   ├── network/                # Network utilities
│   ├── pthi/                   # Platform Trust Hardware Interface
│   ├── smb/                    # SMB/Samba utilities
│   ├── utils/                  # Common utilities
│   └── windows/                # Windows-specific code
└── samples/                    # Usage examples

Package Categories

Internal Packages (internal/):

  • Implementation details not exposed to external users
  • Command implementations, business logic, and internal services

Public Packages (pkg/):

  • Reusable components that can be imported by other Go projects
  • Hardware interfaces, utilities, and AMT communication layers

Entry Points (cmd/):

  • Main executable and library builds
  • Minimal logic, delegates to internal packages

Core Components

1. CLI System (internal/cli/)

The CLI system uses the Kong library for command parsing:

// CLI structure with nested commands
type CLI struct {
    Globals
    commands.ServerAuthFlags
    
    AmtInfo    commands.AmtInfoCmd    `cmd:"" name:"amtinfo"`
    Version    commands.VersionCmd    `cmd:"version"`
    Activate   activate.ActivateCmd   `cmd:"activate"`
    Deactivate commands.DeactivateCmd `cmd:"deactivate"`
    Configure  configure.ConfigureCmd `cmd:"configure"`
}

Key Features:

  • Global flags (password, logging, output format)
  • Automatic help generation
  • YAML configuration file support
  • Environment variable integration

2. Command System (internal/commands/)

Base Command (commands/base.go)

type AMTBaseCmd struct {
    LocalTLSEnforced bool `help:"Require TLS for local connections"`
    ControlMode      int  // Cached current AMT control mode (0=pre-provision, 1=CCM, 2=ACM)
}

All commands embed AMTBaseCmd for common functionality:

  • AMT password management
  • Control mode detection
  • WSMAN client setup

Command Interface

Commands implement these interfaces as needed:

type PasswordRequirer interface {
    RequiresAMTPassword() bool
}

3. AMT Interface (pkg/amt/)

The AMT package provides the primary interface for hardware communication:

type Interface interface {
    Initialize() error
    GetChangeEnabled() (ChangeEnabledResponse, error)
    EnableAMT() error
    DisableAMT() error
    GetVersionDataFromME(key string, timeout time.Duration) (string, error)
    GetUUID() (string, error)
    GetControlMode() (int, error)
    // ... many more methods
}

Implementation: AMTCommand struct uses PTHI (Platform Trust Hardware Interface) for communication with Intel ME.

4. Hardware Communication

HECI Driver (pkg/heci/)

  • Hardware Event Channel Interface for Intel ME communication
  • Platform-specific implementations (Linux/Windows)
  • Low-level message passing

PTHI Layer (pkg/pthi/)

  • Platform Trust Hardware Interface
  • High-level commands built on HECI
  • Structured request/response handling

5. Activation System (internal/commands/activate/)

Activation Modes

type ActivationMode int

const (
    ModeCCM ActivationMode = iota + 1  // Client Control Mode
    ModeACM                            // Admin Control Mode
)

Local Activation Service

type LocalActivationService struct {
    wsman            interfaces.WSMANer
    amtCommand       amt.Interface
    config           LocalActivationConfig
    context          *commands.Context
    localTLSEnforced bool
    isUpgrade        bool
}

Activation Flow:

  1. Validate AMT State: Check if AMT is ready for activation
  2. Validate Configuration: Ensure all required parameters are present
  3. Enable AMT: Enable hardware if needed
  4. Perform Activation: Execute CCM or ACM activation
  5. Configure Features: Apply additional settings

6. Profile System (internal/profile/ & internal/orchestrator/)

Profile Structure

Profiles define complete AMT configurations:

configuration:
  amt_specific:
    control_mode: "ccmactivate"  # or "acmactivate"
    admin_password: "admin123"
    provisioning_cert: "base64-cert-data"
  redirection:
    services:
      kvm: true
      sol: true
      ider: false

Orchestrator

The orchestrator executes multi-step profiles:

  1. Activation: Set up AMT in specified mode
  2. Configuration: Apply network, TLS, and feature settings
  3. Validation: Verify configuration applied correctly

Development Setup

Prerequisites

  • Go 1.25 or later
  • GCC (for C library builds)
  • Intel AMT-capable hardware (for testing)
  • Admin/root privileges (required for HECI access)

Building

Standard Executable

go build -o rpc ./cmd/rpc/main.go

C Shared Library

# Windows
go build -buildmode=c-shared -o rpc.dll ./cmd/rpc

# Linux
CGO_ENABLED=1 go build -buildmode=c-shared -o librpc.so ./cmd/rpc

Docker Image

docker build -t rpc-go:latest .

Development Commands

Code Quality

# Format code
gofumpt -l -w -extra ./

# Run tests
go test ./...

# Lint code (requires Docker)
docker run --rm -v ${PWD}:/app -w /app golangci/golangci-lint:latest golangci-lint run -v

# Generate mocks
make mock

Running Locally

# Check AMT access
sudo ./rpc amtinfo

# Test local activation (CCM mode)
sudo ./rpc activate --ccm --password admin123

# Configure AMT features
sudo ./rpc configure amtfeatures --kvm --sol

Implementation Details

Error Handling

RPC-Go uses a custom error system with typed error codes:

type CustomError struct {
    Message string
    Code    int
}

var (
    AMTConnectionFailed = CustomError{
        Message: "Failed to connect to AMT",
        Code:    1,
    }
    // ... more error types
)

Password Management

Passwords are handled through multiple sources with precedence:

  1. Command-line flags (--password)
  2. Environment variables (AMT_PASSWORD)
  3. Configuration files
  4. Interactive prompts

Configuration System

YAML Configuration

# Global AMT password
amt-password: "admin123"

# Command-specific settings
activate:
  ccm: true
  dns: "example.com"
  
configure:
  sync-clock:
    password: "override-password"  # Optional override

Environment Variables

export AMT_PASSWORD="admin123"
export TENANT_ID="tenant-1"

Logging

Structured logging with multiple levels:

log.SetLevel(log.TraceLevel)  // trace, debug, info, warn, error
log.SetFormatter(&log.JSONFormatter{})  // JSON or text format

Testing Strategy

Unit Tests

  • Mock AMT interfaces for isolated testing
  • Test command validation and configuration
  • Verify error handling paths

Integration Tests

  • Test with real AMT hardware (when available)
  • Validate end-to-end activation flows
  • Check profile orchestration

Fuzz Tests

  • Mock AMT interfaces for cli input fuzz testing
  • Validate rpc-go arguments parser
  • Ensure robustness against unexpected or malicious inputs

Mock Generation

mockgen -source ./internal/interfaces/wsman.go -destination ./internal/mocks/wsman_mock.go

Testing

Running Tests

All Tests

go test ./...

Specific Package

go test ./internal/commands/activate

Fuzz Tests

# Run fuzz tests with custom duration
go test -fuzz=FuzzDeactivate -fuzztime=10m ./internal/cli

# Run regression tests with existing corpus
go test ./internal/cli -fuzz=FuzzDeactivate -fuzztime=1x

# Run all fuzz tests sequentially
for fuzz in FuzzDeactivate FuzzDeactivateURL FuzzDeactivatePassword FuzzDeactivateFlagCombinations; do
  go test -fuzz=$fuzz -fuzztime=5m ./internal/cli
done

Coverage Report

go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

Test Organization

Tests are organized alongside source code:

  • *_test.go files in same directory as implementation
  • *_fuzz_test.go files for fuzz testing (uses Go 1.18+ native fuzzing)
  • testdata/ directories for test fixtures
  • Mock interfaces in internal/mocks/

Writing Tests

Command Tests

func TestActivateCmd_Validate(t *testing.T) {
    tests := []struct {
        name    string
        cmd     ActivateCmd
        wantErr bool
    }{
        {
            name: "valid CCM activation",
            cmd: ActivateCmd{CCM: true},
            wantErr: false,
        },
        // ... more test cases
    }
    
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            err := tt.cmd.Validate()
            if (err != nil) != tt.wantErr {
                t.Errorf("ActivateCmd.Validate() error = %v, wantErr %v", err, tt.wantErr)
            }
        })
    }
}

Fuzz Tests

func FuzzYourCommand(f *testing.F) {
    // Add seed corpus
    f.Add("valid-input-1")
    f.Add("edge-case-2")
    
    f.Fuzz(func(t *testing.T, input string) {
        // Skip extremely long inputs
        if len(input) > 10000 {
            t.Skip("Input too long")
        }
        
        // Setup mocks
        ctrl := gomock.NewController(t)
        defer ctrl.Finish()
        mockAMT := setupMockAMT(ctrl)
        
        // Build arguments
        args := []string{"rpc", input}

        // Protect against panics
        defer recoverPanic(t, input)
        
        // Test your function - should not panic
        _, _, err := Parse(args, mockAMTCommand)
        _ = err // Error is OK, panic is not
    })
}

Using Mocks

func TestActivationService(t *testing.T) {
    ctrl := gomock.NewController(t)
    defer ctrl.Finish()
    
    mockAMT := mock.NewMockInterface(ctrl)
    mockAMT.EXPECT().GetControlMode().Return(0, nil)
    
    service := NewLocalActivationService(mockAMT, config, ctx)
    err := service.Activate()
    assert.NoError(t, err)
}

API Reference

Command-Line Interface 🖥️ Console

Global Flags

  • --password: AMT admin password 🖥️ Console | ☁️ Cloud
  • --json: JSON output format ☁️ Cloud (recommended for automation)
  • --verbose: Enable verbose logging 🖥️ Console
  • --log-level: Set log level (trace, debug, info, warn, error) 🖥️ Console | ☁️ Cloud
  • --skip-cert-check: Skip TLS verification for remote connections 🖥️ Console | ☁️ Cloud
  • --skip-amt-cert-check: Skip TLS verification for AMT connections 🖥️ Console | ☁️ Cloud

Commands

amtinfo

Display AMT status and configuration information.

rpc amtinfo [--password <password>]
activate

Activate AMT on the local device.

# Local activation (🖥️ Console - local hardware access)
sudo ./rpc activate --local --profile acmProfile.yaml --key "AsfQcldDxDuFocYjT0ZUZhEFi6lGxbQX" --skip-amt-cert-check -v --log-level=trace

# Remote activation via RPS (☁️ Cloud - scalable deployment)
sudo ./rpc -u wss://<IP>/activate -n -profile dmt_ccm_profile
deactivate

Deactivate or unprovision AMT. 🖥️ Console | ☁️ Cloud

sudo ./rpc deactivate -u wss://<IP>/deactivate
configure

Configure AMT features and settings. All configure subcommands require an activated AMT device and AMT admin password.

System Synchronization:

# Synchronize system clock with AMT
rpc configure syncclock

# Synchronize hostname and DNS suffix
rpc configure synchostname

Library Interface ☁️ Cloud Integration

When built as a C shared library, RPC-Go exports these functions for integration into cloud management platforms:

// Check if AMT hardware is accessible
int rpcCheckAccess();

// Execute RPC command and return results
int rpcExec(char* input, char** output, char** errorOutput);

Usage Example

#include "rpc.h"

int main() {
    // Check access
    if (rpcCheckAccess() != 0) {
        printf("AMT not accessible\n");
        return 1;
    }
    
    // Execute command
    char* output;
    char* errorOutput;
    int result = rpcExec("amtinfo --json", &output, &errorOutput);
    
    if (result == 0) {
        printf("Output: %s\n", output);
    } else {
        printf("Error: %s\n", errorOutput);
    }
    
    return result;
}

Go Package Interface

AMT Package (pkg/amt)

import "github.com/device-management-toolkit/rpc-go/v2/pkg/amt"

// Create AMT command interface
amtCmd := amt.NewAMTCommand()
err := amtCmd.Initialize()

// Get AMT information
uuid, err := amtCmd.GetUUID()
controlMode, err := amtCmd.GetControlMode()
versions, err := amtCmd.GetVersionDataFromME("AMT", 5*time.Second)

Utilities Package (pkg/utils)

import "github.com/device-management-toolkit/rpc-go/v2/pkg/utils"

// Constants
fmt.Println(utils.ProjectName)    // "rpc"
fmt.Println(utils.ProjectVersion) // Version string

// Error handling
if err == utils.AMTConnectionFailed {
    // Handle specific error
}

This guide covers the essential aspects of RPC-Go development

Clone this wiki locally