mtls

package
v0.0.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 4, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

README ΒΆ

Certificate-Based Authentication (mTLS) Plugin

Enterprise-grade mutual TLS (mTLS) authentication plugin for AuthSome, providing X.509 certificate validation, PIV/CAC smart card support, Hardware Security Module (HSM) integration, and comprehensive certificate lifecycle management.

🎯 Overview

The mTLS plugin enables secure authentication using client certificates, designed for high-security environments including:

  • Government & Defense: PIV/CAC card authentication for federal employees and military personnel
  • IoT & Machine-to-Machine: Device authentication with certificate-based identity
  • Enterprise Applications: Strong authentication for APIs and services
  • Banking & Finance: Hardware-backed certificate authentication with HSM
  • Healthcare: HIPAA-compliant authentication with audit trails

✨ Features

Core Features
  • βœ… X.509 Certificate Validation

    • Full chain validation with configurable trust anchors
    • Signature verification and cryptographic validation
    • Key usage and extended key usage validation
    • Certificate expiration and validity checks
    • Configurable key size and algorithm requirements
  • βœ… Revocation Checking

    • CRL (Certificate Revocation List) support with caching
    • OCSP (Online Certificate Status Protocol) with stapling
    • Automatic revocation status caching
    • Configurable fail-open/fail-closed behavior
  • βœ… PIV/CAC Smart Card Support

    • Personal Identity Verification (PIV) cards
    • Common Access Card (CAC) authentication
    • Multi-slot certificate support (9A, 9C, 9D, 9E)
    • Smart card PIN handling
    • Card reader integration
  • βœ… Hardware Security Module (HSM) Integration

    • PKCS#11 standard support
    • AWS CloudHSM integration
    • Azure Key Vault integration
    • GCP Cloud HSM integration
    • Hardware-backed key operations
  • βœ… Certificate Lifecycle Management

    • Certificate registration and tracking
    • Expiration monitoring and alerts
    • Certificate pinning support
    • Revocation management
    • Usage statistics and audit logs
  • βœ… Policy-Based Validation

    • Organization-specific certificate policies
    • Configurable validation rules
    • Trust anchor management
    • Certificate type restrictions
    • Compliance enforcement

πŸ“¦ Installation

1. Add Plugin to Your Application
import (
    "github.com/xraph/authsome"
    "github.com/xraph/authsome/plugins/enterprise/mtls"
)

func main() {
    // Create AuthSome instance
    auth := authsome.New()
    
    // Register mTLS plugin
    auth.Use(mtls.NewPlugin())
    
    // Mount on Forge app
    app := forge.New()
    auth.Mount(app)
    
    app.Run(":8080")
}
2. Configure in YAML

Create config.yaml:

auth:
  mtls:
    enabled: true
    
    # Certificate Validation
    validation:
      checkExpiration: true
      checkNotBefore: true
      checkSignature: true
      checkKeyUsage: true
      validateChain: true
      maxChainLength: 5
      allowSelfSigned: false
      minKeySize: 2048
      allowedKeyAlgorithms:
        - RSA
        - ECDSA
        - Ed25519
      maxCertificateAge: 365
      minRemainingValidity: 30
      requiredKeyUsage:
        - digitalSignature
        - keyEncipherment
      requiredEku:
        - clientAuth
    
    # Revocation Checking
    revocation:
      enableCrl: true
      crlCacheDuration: 24h
      autoFetchCrl: true
      enableOcsp: true
      ocspCacheDuration: 1h
      ocspStapling: true
      failOpen: false  # Fail closed for security
      preferOcsp: true
    
    # Smart Card Support
    smartCard:
      enabled: true
      enablePiv: true
      pivAuthCertOnly: true
      enableCac: true
      requirePin: false
      maxPinAttempts: 3
    
    # HSM Integration (optional)
    hsm:
      enabled: false
      provider: pkcs11  # pkcs11, cloudhsm, azure, gcp
      # pkcs11Library: /usr/lib/softhsm/libsofthsm2.so
      # pkcs11SlotId: 0
      # pkcs11Pin: "1234"
    
    # API Configuration
    api:
      basePath: /auth/mtls
      enableManagement: true
      enableValidation: true
      enableMetrics: true
    
    # Security
    security:
      rateLimitEnabled: true
      maxAttemptsPerMinute: 10
      auditAllAttempts: true
      storeCertificates: true
      notifyOnExpiration: true
      expirationWarning: 30

πŸš€ Quick Start

Standard Certificate Authentication
package main

import (
    "crypto/tls"
    "log"
    
    "github.com/xraph/authsome"
    "github.com/xraph/authsome/plugins/enterprise/mtls"
    "github.com/xraph/forge"
)

func main() {
    // Create AuthSome with mTLS plugin
    auth := authsome.New(authsome.WithConfig("config.yaml"))
    auth.Use(mtls.NewPlugin())
    
    // Create Forge app with TLS
    app := forge.New()
    
    // Configure TLS with client certificate requirement
    tlsConfig := &tls.Config{
        ClientAuth: tls.RequireAndVerifyClientCert,
        MinVersion: tls.VersionTLS12,
    }
    
    // Mount AuthSome
    auth.Mount(app)
    
    // Protected route requiring certificate
    app.POST("/api/secure", func(c *forge.Context) error {
        // Certificate authentication happens automatically
        userID := c.GetString("userId")
        certID := c.GetString("certificateId")
        
        return c.JSON(200, forge.Map{
            "message": "Authenticated via certificate",
            "userId": userID,
            "certificateId": certID,
        })
    })
    
    // Start with TLS
    log.Fatal(app.RunTLS(":8443", "server.crt", "server.key", tlsConfig))
}
Register a Certificate
curl -X POST https://api.example.com/auth/mtls/certificates \
  -H "Content-Type: application/json" \
  -d '{
    "organizationId": "org_123",
    "userId": "user_456",
    "certificatePem": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----",
    "certificateType": "user",
    "certificateClass": "standard"
  }'
Authenticate with Certificate
curl -X POST https://api.example.com/auth/mtls/authenticate \
  --cert client.crt \
  --key client.key \
  --cacert ca.crt \
  -H "Content-Type: application/json" \
  -d '{
    "organizationId": "org_123"
  }'

πŸ“š Use Cases

1. PIV Card Authentication (Government)
auth:
  mtls:
    enabled: true
    smartCard:
      enabled: true
      enablePiv: true
      pivAuthCertOnly: true  # Only accept PIV auth certificates (slot 9A)
      pivRequiredOids:
        - "2.16.840.1.101.3.2.1.3.7"  # PIV Authentication OID
    
    validation:
      minKeySize: 2048
      requiredEku:
        - clientAuth

Usage:

// Register PIV certificate
req := &mtls.RegisterCertificateRequest{
    OrganizationID: "gov_agency",
    UserID: "john.doe",
    CertificatePEM: pivCertPEM,
    CertificateType: "user",
    CertificateClass: "piv",
    PIVCardID: "card_12345",
}

cert, err := mtlsPlugin.Service().RegisterCertificate(ctx, req)
2. CAC Authentication (Military/DoD)
auth:
  mtls:
    smartCard:
      enabled: true
      enableCac: true
      cacRequiredOids:
        - "2.16.840.1.101.2.1.11.42"  # CAC Authentication OID
3. IoT Device Authentication
auth:
  mtls:
    enabled: true
    validation:
      allowSelfSigned: false
      maxCertificateAge: 365
    
    revocation:
      enableOcsp: true
      enableCrl: true
      failOpen: false  # Strict revocation checking

Register IoT Device:

curl -X POST https://api.example.com/auth/mtls/certificates \
  -H "Content-Type: application/json" \
  -d '{
    "organizationId": "org_123",
    "deviceId": "device_sensor_001",
    "certificatePem": "-----BEGIN CERTIFICATE-----\n...",
    "certificateType": "device",
    "certificateClass": "standard",
    "metadata": {
      "deviceType": "temperature_sensor",
      "location": "warehouse_a"
    }
  }'
4. HSM-Backed Authentication (Banking)
auth:
  mtls:
    hsm:
      enabled: true
      provider: pkcs11
      pkcs11Library: /usr/lib/libpkcs11.so
      pkcs11SlotId: 0
      requireHsm: true  # Only accept HSM-backed certificates

AWS CloudHSM Example:

auth:
  mtls:
    hsm:
      enabled: true
      provider: cloudhsm
      cloudHsmClusterId: cluster-abc123
      cloudHsmRegion: us-east-1
      requireHsm: true
5. API Machine-to-Machine Authentication
// Service-to-service authentication
app.Use(func(c *forge.Context) error {
    // Verify client certificate
    if c.Request().TLS == nil || len(c.Request().TLS.PeerCertificates) == 0 {
        return c.JSON(401, forge.Map{"error": "certificate required"})
    }
    
    cert := c.Request().TLS.PeerCertificates[0]
    
    // Validate certificate through mTLS plugin
    result, err := mtlsPlugin.Service().AuthenticateWithCertificate(
        c.Context(),
        certToPEM(cert.Raw),
        "org_123",
    )
    
    if err != nil || !result.Success {
        return c.JSON(401, forge.Map{"error": "authentication failed"})
    }
    
    // Set context for downstream handlers
    c.Set("userId", result.UserID)
    c.Set("certificateId", result.CertificateID)
    
    return c.Next()
})

πŸ”§ Advanced Configuration

Certificate Policies

Create organization-specific certificate policies:

curl -X POST https://api.example.com/auth/mtls/policies \
  -H "Content-Type: application/json" \
  -d '{
    "organizationId": "org_123",
    "name": "High Security Policy",
    "description": "Policy for sensitive operations",
    "requirePinning": true,
    "requireCrlCheck": true,
    "requireOcspCheck": true,
    "minKeySize": 4096,
    "allowedKeyAlgorithms": ["RSA", "ECDSA"],
    "maxCertificateAge": 180,
    "minRemainingValidity": 60,
    "requirePiv": true,
    "isDefault": true
  }'
Trust Anchor Management

Add custom CA certificates:

curl -X POST https://api.example.com/auth/mtls/trust-anchors \
  -H "Content-Type: application/json" \
  -d '{
    "organizationId": "org_123",
    "name": "Corporate Root CA",
    "certificatePem": "-----BEGIN CERTIFICATE-----\n...",
    "trustLevel": "root"
  }'
Certificate Pinning
// Register certificate with pinning
req := &mtls.RegisterCertificateRequest{
    OrganizationID: "org_123",
    UserID: "user_456",
    CertificatePEM: certPEM,
    IsPinned: true,  // Enable pinning
}

πŸ“Š Monitoring & Statistics

Get Authentication Statistics
curl -X GET "https://api.example.com/auth/mtls/stats/auth?organizationId=org_123&since=2025-01-01T00:00:00Z"

Response:

{
  "totalAttempts": 1523,
  "successfulAuths": 1487,
  "failedAuths": 36,
  "validationErrors": 12,
  "uniqueUsers": 145,
  "uniqueCerts": 203
}
Get Expiring Certificates
curl -X GET "https://api.example.com/auth/mtls/certificates/expiring?organizationId=org_123&days=30"

πŸ”’ Security Best Practices

1. Always Use Strong Keys
validation:
  minKeySize: 2048  # Minimum 2048 bits for RSA
  allowedKeyAlgorithms:
    - RSA
    - ECDSA  # Prefer ECDSA for better performance
2. Enable Revocation Checking
revocation:
  enableCrl: true
  enableOcsp: true
  failOpen: false  # Fail closed - reject if revocation unavailable
3. Implement Certificate Rotation
  • Set reasonable certificate lifetimes (e.g., 1 year)
  • Monitor expiring certificates
  • Implement automated renewal processes
4. Audit Everything
security:
  auditAllAttempts: true
  auditFailures: true
  auditValidation: true
5. Use Certificate Pinning for High Security
req.IsPinned = true  // Bind session to specific certificate

πŸ§ͺ Testing

Generate Test Certificates
# Generate CA
openssl req -x509 -new -nodes -keyout ca.key -sha256 -days 365 -out ca.crt -subj "/CN=Test CA"

# Generate client key and CSR
openssl req -new -nodes -keyout client.key -out client.csr -subj "/CN=Test Client"

# Sign client certificate
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365 -sha256
Test Authentication
package main

import (
    "testing"
    "crypto/x509"
    "encoding/pem"
)

func TestCertificateAuth(t *testing.T) {
    // Load test certificate
    certPEM := loadTestCertificate()
    
    // Authenticate
    result, err := service.AuthenticateWithCertificate(
        context.Background(),
        certPEM,
        "test_org",
    )
    
    if err != nil {
        t.Fatalf("Authentication failed: %v", err)
    }
    
    if !result.Success {
        t.Fatalf("Expected successful authentication")
    }
}

πŸ“– API Reference

Endpoints
Method Path Description
POST /auth/mtls/certificates Register a certificate
GET /auth/mtls/certificates List certificates
GET /auth/mtls/certificates/:id Get certificate details
POST /auth/mtls/certificates/:id/revoke Revoke a certificate
GET /auth/mtls/certificates/expiring Get expiring certificates
POST /auth/mtls/authenticate Authenticate with certificate
POST /auth/mtls/trust-anchors Add trust anchor
GET /auth/mtls/trust-anchors List trust anchors
POST /auth/mtls/policies Create certificate policy
GET /auth/mtls/policies/:id Get policy
POST /auth/mtls/validate Validate certificate
GET /auth/mtls/stats/auth Get authentication statistics

🀝 Integration Examples

With Kubernetes
apiVersion: v1
kind: Secret
metadata:
  name: client-cert
type: kubernetes.io/tls
data:
  tls.crt: <base64-encoded-cert>
  tls.key: <base64-encoded-key>
---
apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
      - name: app
        volumeMounts:
        - name: client-cert
          mountPath: /etc/certs
          readOnly: true
      volumes:
      - name: client-cert
        secret:
          secretName: client-cert
With NGINX
server {
    listen 443 ssl;
    ssl_certificate /path/to/server.crt;
    ssl_certificate_key /path/to/server.key;
    
    # Client certificate verification
    ssl_client_certificate /path/to/ca.crt;
    ssl_verify_client on;
    ssl_verify_depth 2;
    
    location /api {
        proxy_pass http://backend;
        proxy_set_header X-SSL-Client-Cert $ssl_client_cert;
        proxy_set_header X-SSL-Client-Verify $ssl_client_verify;
    }
}

πŸ› Troubleshooting

Certificate Validation Fails
# Test certificate validation
curl -X POST https://api.example.com/auth/mtls/validate \
  -H "Content-Type: application/json" \
  -d '{
    "certificatePem": "-----BEGIN CERTIFICATE-----\n...",
    "organizationId": "org_123"
  }'
Check Certificate Chain
openssl verify -CAfile ca.crt -untrusted intermediate.crt client.crt
Debug OCSP
openssl ocsp -issuer ca.crt -cert client.crt -url http://ocsp.example.com -text

πŸ“ License

Part of AuthSome - Enterprise Authentication Framework

🀝 Support

For issues, questions, or contributions, please visit the AuthSome repository.

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var (
	// Certificate Errors
	ErrCertificateNotFound    = errors.New("certificate not found")
	ErrCertificateExpired     = errors.New("certificate has expired")
	ErrCertificateRevoked     = errors.New("certificate has been revoked")
	ErrCertificateInvalid     = errors.New("certificate is invalid")
	ErrCertificateNotYetValid = errors.New("certificate is not yet valid")
	ErrCertificateSuspended   = errors.New("certificate is suspended")

	// Validation Errors
	ErrInvalidSignature        = errors.New("invalid certificate signature")
	ErrUntrustedCA             = errors.New("certificate issued by untrusted CA")
	ErrInvalidKeyUsage         = errors.New("invalid key usage for authentication")
	ErrKeyTooWeak              = errors.New("certificate key size too weak")
	ErrUnsupportedAlgorithm    = errors.New("unsupported key or signature algorithm")
	ErrCertificateChainInvalid = errors.New("certificate chain validation failed")

	// Pinning Errors
	ErrCertificateNotPinned = errors.New("certificate not pinned (required by policy)")
	ErrPinExpired           = errors.New("certificate pin has expired")
	ErrPinMismatch          = errors.New("certificate does not match pinned fingerprint")

	// Revocation Errors
	ErrCRLCheckFailed        = errors.New("CRL check failed")
	ErrOCSPCheckFailed       = errors.New("OCSP check failed")
	ErrRevocationUnavailable = errors.New("revocation status unavailable")

	// PIV/CAC Errors
	ErrNotPIVCertificate   = errors.New("certificate is not a PIV certificate")
	ErrNotCACCertificate   = errors.New("certificate is not a CAC certificate")
	ErrSmartCardNotPresent = errors.New("smart card not present")
	ErrSmartCardLocked     = errors.New("smart card is locked")
	ErrPINRequired         = errors.New("smart card PIN required")
	ErrInvalidPIN          = errors.New("invalid smart card PIN")

	// HSM Errors
	ErrHSMNotConfigured       = errors.New("HSM not configured")
	ErrHSMConnectionFailed    = errors.New("HSM connection failed")
	ErrHSMKeyNotFound         = errors.New("HSM key not found")
	ErrHSMOperationFailed     = errors.New("HSM operation failed")
	ErrHSMProviderUnsupported = errors.New("HSM provider not supported")

	// Policy Errors
	ErrPolicyNotFound  = errors.New("certificate policy not found")
	ErrPolicyViolation = errors.New("certificate policy violation")
	ErrPolicyRequired  = errors.New("certificate policy required but not found")

	// Trust Anchor Errors
	ErrTrustAnchorNotFound = errors.New("trust anchor not found")
	ErrTrustAnchorExpired  = errors.New("trust anchor has expired")
	ErrNoTrustAnchors      = errors.New("no trust anchors configured")

	// General Errors
	ErrCertificateParseFailed = errors.New("failed to parse certificate")
	ErrCRLParseFailed         = errors.New("failed to parse CRL")
	ErrOCSPParseFailed        = errors.New("failed to parse OCSP response")
	ErrInvalidPEM             = errors.New("invalid PEM format")
	ErrMissingClientCert      = errors.New("client certificate not provided")
)
View Source
var (
	// PIV OIDs
	OID_PIV_Authentication   = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 2, 1, 3, 7}
	OID_PIV_CardAuth         = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 2, 1, 3, 13}
	OID_PIV_DigitalSignature = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 2, 1, 3, 2}
	OID_PIV_KeyManagement    = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 2, 1, 3, 4}

	// CAC OIDs
	OID_CAC_PKI            = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 2, 1, 11, 39}
	OID_CAC_Authentication = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 2, 1, 11, 42}
	OID_CAC_Email          = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 2, 1, 11, 17}
)

PIV/CAC OID Constants

Functions ΒΆ

func GetCACCertificateTypes ΒΆ

func GetCACCertificateTypes() []string

GetCACCertificateTypes returns CAC certificate types

func GetPIVSlotNames ΒΆ

func GetPIVSlotNames() map[string]string

GetPIVSlotNames returns human-readable PIV slot names

Types ΒΆ

type APIConfig ΒΆ

type APIConfig struct {
	BasePath         string `json:"basePath" yaml:"basePath"`
	EnableManagement bool   `json:"enableManagement" yaml:"enableManagement"` // Certificate management APIs
	EnableValidation bool   `json:"enableValidation" yaml:"enableValidation"` // Validation endpoint
	EnableMetrics    bool   `json:"enableMetrics" yaml:"enableMetrics"`
}

APIConfig configures mTLS API endpoints

type AddTrustAnchorRequest ΒΆ

type AddTrustAnchorRequest struct {
	OrganizationID string                 `json:"organizationId"`
	Name           string                 `json:"name"`
	CertificatePEM string                 `json:"certificatePem"`
	TrustLevel     string                 `json:"trustLevel"` // root, intermediate, self_signed
	Metadata       map[string]interface{} `json:"metadata,omitempty"`
}

type AuthEventFilters ΒΆ

type AuthEventFilters struct {
	OrganizationID string
	CertificateID  string
	UserID         string
	EventType      string
	Status         string
	Since          time.Time
	Until          time.Time
	Limit          int
	Offset         int
}

AuthEventFilters for filtering auth event queries

type AuthEventStats ΒΆ

type AuthEventStats struct {
	TotalAttempts    int
	SuccessfulAuths  int
	FailedAuths      int
	ValidationErrors int
	UniqueUsers      int
	UniqueCerts      int
}

AuthEventStats contains authentication event statistics

type AuthenticationResult ΒΆ

type AuthenticationResult struct {
	Success          bool              `json:"success"`
	UserID           string            `json:"userId,omitempty"`
	CertificateID    string            `json:"certificateId,omitempty"`
	Certificate      *Certificate      `json:"certificate,omitempty"`
	ValidationResult *ValidationResult `json:"validationResult,omitempty"`
	Errors           []error           `json:"errors,omitempty"`
}

type AzureKeyVaultProvider ΒΆ

type AzureKeyVaultProvider struct {
	// contains filtered or unexported fields
}

AzureKeyVaultProvider implements HSM provider for Azure Key Vault

func NewAzureKeyVaultProvider ΒΆ

func NewAzureKeyVaultProvider(config *Config) *AzureKeyVaultProvider

NewAzureKeyVaultProvider creates a new Azure Key Vault provider

func (*AzureKeyVaultProvider) Connect ΒΆ

func (p *AzureKeyVaultProvider) Connect(ctx context.Context) error

func (*AzureKeyVaultProvider) Disconnect ΒΆ

func (p *AzureKeyVaultProvider) Disconnect() error

func (*AzureKeyVaultProvider) GetCertificate ΒΆ

func (p *AzureKeyVaultProvider) GetCertificate(ctx context.Context, keyID string) (*x509.Certificate, error)

func (*AzureKeyVaultProvider) GetKey ΒΆ

func (*AzureKeyVaultProvider) GetProviderInfo ΒΆ

func (p *AzureKeyVaultProvider) GetProviderInfo() *HSMProviderInfo

func (*AzureKeyVaultProvider) ListKeys ΒΆ

func (p *AzureKeyVaultProvider) ListKeys(ctx context.Context) ([]HSMKeyInfo, error)

func (*AzureKeyVaultProvider) Sign ΒΆ

func (p *AzureKeyVaultProvider) Sign(ctx context.Context, keyID string, digest []byte) ([]byte, error)

func (*AzureKeyVaultProvider) ValidateKey ΒΆ

func (p *AzureKeyVaultProvider) ValidateKey(ctx context.Context, keyID string) error

type BunRepository ΒΆ

type BunRepository struct {
	// contains filtered or unexported fields
}

BunRepository implements Repository using Bun ORM

func NewBunRepository ΒΆ

func NewBunRepository(db *bun.DB) *BunRepository

NewBunRepository creates a new Bun repository

func (*BunRepository) CreateAuthEvent ΒΆ

func (r *BunRepository) CreateAuthEvent(ctx context.Context, event *CertificateAuthEvent) error

func (*BunRepository) CreateCRL ΒΆ

func (*BunRepository) CreateCertificate ΒΆ

func (r *BunRepository) CreateCertificate(ctx context.Context, cert *Certificate) error

func (*BunRepository) CreateOCSPResponse ΒΆ

func (r *BunRepository) CreateOCSPResponse(ctx context.Context, resp *OCSPResponse) error

func (*BunRepository) CreatePolicy ΒΆ

func (r *BunRepository) CreatePolicy(ctx context.Context, policy *CertificatePolicy) error

func (*BunRepository) CreateTrustAnchor ΒΆ

func (r *BunRepository) CreateTrustAnchor(ctx context.Context, anchor *TrustAnchor) error

func (*BunRepository) DeleteCRL ΒΆ

func (r *BunRepository) DeleteCRL(ctx context.Context, id string) error

func (*BunRepository) DeleteCertificate ΒΆ

func (r *BunRepository) DeleteCertificate(ctx context.Context, id string) error

func (*BunRepository) DeleteExpiredOCSPResponses ΒΆ

func (r *BunRepository) DeleteExpiredOCSPResponses(ctx context.Context) error

func (*BunRepository) DeletePolicy ΒΆ

func (r *BunRepository) DeletePolicy(ctx context.Context, id string) error

func (*BunRepository) DeleteTrustAnchor ΒΆ

func (r *BunRepository) DeleteTrustAnchor(ctx context.Context, id string) error

func (*BunRepository) GetAuthEventStats ΒΆ

func (r *BunRepository) GetAuthEventStats(ctx context.Context, orgID string, since time.Time) (*AuthEventStats, error)

func (*BunRepository) GetCRL ΒΆ

func (*BunRepository) GetCRLByIssuer ΒΆ

func (r *BunRepository) GetCRLByIssuer(ctx context.Context, issuer string) (*CertificateRevocationList, error)

func (*BunRepository) GetCertificate ΒΆ

func (r *BunRepository) GetCertificate(ctx context.Context, id string) (*Certificate, error)

func (*BunRepository) GetCertificateByFingerprint ΒΆ

func (r *BunRepository) GetCertificateByFingerprint(ctx context.Context, fingerprint string) (*Certificate, error)

func (*BunRepository) GetCertificateBySerialNumber ΒΆ

func (r *BunRepository) GetCertificateBySerialNumber(ctx context.Context, serialNumber string) (*Certificate, error)

func (*BunRepository) GetDefaultPolicy ΒΆ

func (r *BunRepository) GetDefaultPolicy(ctx context.Context, orgID string) (*CertificatePolicy, error)

func (*BunRepository) GetDeviceCertificates ΒΆ

func (r *BunRepository) GetDeviceCertificates(ctx context.Context, deviceID string) ([]*Certificate, error)

func (*BunRepository) GetExpiringCertificates ΒΆ

func (r *BunRepository) GetExpiringCertificates(ctx context.Context, orgID string, days int) ([]*Certificate, error)

func (*BunRepository) GetOCSPResponse ΒΆ

func (r *BunRepository) GetOCSPResponse(ctx context.Context, certificateID string) (*OCSPResponse, error)

func (*BunRepository) GetPolicy ΒΆ

func (r *BunRepository) GetPolicy(ctx context.Context, id string) (*CertificatePolicy, error)

func (*BunRepository) GetTrustAnchor ΒΆ

func (r *BunRepository) GetTrustAnchor(ctx context.Context, id string) (*TrustAnchor, error)

func (*BunRepository) GetTrustAnchorByFingerprint ΒΆ

func (r *BunRepository) GetTrustAnchorByFingerprint(ctx context.Context, fingerprint string) (*TrustAnchor, error)

func (*BunRepository) GetUserCertificates ΒΆ

func (r *BunRepository) GetUserCertificates(ctx context.Context, userID string) ([]*Certificate, error)

func (*BunRepository) ListAuthEvents ΒΆ

func (r *BunRepository) ListAuthEvents(ctx context.Context, filters AuthEventFilters) ([]*CertificateAuthEvent, error)

func (*BunRepository) ListCRLs ΒΆ

func (r *BunRepository) ListCRLs(ctx context.Context, trustAnchorID string) ([]*CertificateRevocationList, error)

func (*BunRepository) ListCertificates ΒΆ

func (r *BunRepository) ListCertificates(ctx context.Context, filters CertificateFilters) ([]*Certificate, error)

func (*BunRepository) ListPolicies ΒΆ

func (r *BunRepository) ListPolicies(ctx context.Context, orgID string) ([]*CertificatePolicy, error)

func (*BunRepository) ListTrustAnchors ΒΆ

func (r *BunRepository) ListTrustAnchors(ctx context.Context, orgID string) ([]*TrustAnchor, error)

func (*BunRepository) RevokeCertificate ΒΆ

func (r *BunRepository) RevokeCertificate(ctx context.Context, id string, reason string) error

func (*BunRepository) UpdateCRL ΒΆ

func (*BunRepository) UpdateCertificate ΒΆ

func (r *BunRepository) UpdateCertificate(ctx context.Context, cert *Certificate) error

func (*BunRepository) UpdateOCSPResponse ΒΆ

func (r *BunRepository) UpdateOCSPResponse(ctx context.Context, resp *OCSPResponse) error

func (*BunRepository) UpdatePolicy ΒΆ

func (r *BunRepository) UpdatePolicy(ctx context.Context, policy *CertificatePolicy) error

func (*BunRepository) UpdateTrustAnchor ΒΆ

func (r *BunRepository) UpdateTrustAnchor(ctx context.Context, anchor *TrustAnchor) error

type CACCardInfo ΒΆ

type CACCardInfo struct {
	CardID         string           `json:"cardId"`
	CACNumber      string           `json:"cacNumber"`
	PersonDN       string           `json:"personDn,omitempty"`
	Certificates   []CACCertificate `json:"certificates"`
	IssueDate      *time.Time       `json:"issueDate,omitempty"`
	ExpirationDate *time.Time       `json:"expirationDate,omitempty"`
	ReaderName     string           `json:"readerName,omitempty"`
}

CACCardInfo contains CAC card information

type CACCertificate ΒΆ

type CACCertificate struct {
	CertificateType string            `json:"certificateType"` // ID, Email, Signature, Encryption
	Certificate     *x509.Certificate `json:"-"`
	Fingerprint     string            `json:"fingerprint"`
}

CACCertificate represents a certificate on a CAC

type Certificate ΒΆ

type Certificate struct {
	bun.BaseModel `bun:"table:mtls_certificates,alias:cert"`

	ID             string `bun:"id,pk,type:varchar(36)" json:"id"`
	OrganizationID string `bun:"organization_id,notnull,type:varchar(36)" json:"organizationId"`
	UserID         string `bun:"user_id,nullzero,type:varchar(36)" json:"userId,omitempty"` // null for device/machine certs
	DeviceID       string `bun:"device_id,nullzero,type:varchar(36)" json:"deviceId,omitempty"`

	// Certificate Info
	Subject         string `bun:"subject,notnull" json:"subject"`
	Issuer          string `bun:"issuer,notnull" json:"issuer"`
	SerialNumber    string `bun:"serial_number,notnull,unique" json:"serialNumber"`
	Fingerprint     string `bun:"fingerprint,notnull,unique" json:"fingerprint"` // SHA-256
	FingerprintSHA1 string `bun:"fingerprint_sha1,notnull" json:"fingerprintSha1"`

	// Certificate Data
	CertificatePEM string `bun:"certificate_pem,notnull,type:text" json:"-"` // Don't expose in JSON
	PublicKeyPEM   string `bun:"public_key_pem,notnull,type:text" json:"-"`

	// Validity
	NotBefore time.Time `bun:"not_before,notnull" json:"notBefore"`
	NotAfter  time.Time `bun:"not_after,notnull" json:"notAfter"`

	// Certificate Type
	CertificateType  string `bun:"certificate_type,notnull" json:"certificateType"`   // user, device, service
	CertificateClass string `bun:"certificate_class,notnull" json:"certificateClass"` // standard, piv, cac, smartcard

	// Status
	Status        string     `bun:"status,notnull,default:'active'" json:"status"` // active, revoked, expired, suspended
	RevokedAt     *time.Time `bun:"revoked_at,nullzero" json:"revokedAt,omitempty"`
	RevokedReason string     `bun:"revoked_reason,nullzero" json:"revokedReason,omitempty"`

	// PIV/CAC Specific
	PIVCardID string `bun:"piv_card_id,nullzero" json:"pivCardId,omitempty"`
	CACNumber string `bun:"cac_number,nullzero" json:"cacNumber,omitempty"`

	// HSM Integration
	HSMKeyID    string `bun:"hsm_key_id,nullzero" json:"hsmKeyId,omitempty"`
	HSMProvider string `bun:"hsm_provider,nullzero" json:"hsmProvider,omitempty"`

	// Pinning
	IsPinned     bool       `bun:"is_pinned,notnull,default:false" json:"isPinned"`
	PinExpiresAt *time.Time `bun:"pin_expires_at,nullzero" json:"pinExpiresAt,omitempty"`

	// Extensions
	KeyUsage         []string    `bun:"key_usage,array,type:text[]" json:"keyUsage"`
	ExtendedKeyUsage []string    `bun:"extended_key_usage,array,type:text[]" json:"extendedKeyUsage"`
	SubjectAltNames  StringArray `bun:"subject_alt_names,type:jsonb" json:"subjectAltNames,omitempty"`

	// Metadata
	Metadata map[string]interface{} `bun:"metadata,type:jsonb" json:"metadata,omitempty"`

	// Audit
	CreatedAt  time.Time  `bun:"created_at,notnull,default:current_timestamp" json:"createdAt"`
	UpdatedAt  time.Time  `bun:"updated_at,notnull,default:current_timestamp" json:"updatedAt"`
	LastUsedAt *time.Time `bun:"last_used_at,nullzero" json:"lastUsedAt,omitempty"`
	UseCount   int        `bun:"use_count,notnull,default:0" json:"useCount"`
}

Certificate represents a client certificate in the system

func (*Certificate) BeforeInsert ΒΆ

func (c *Certificate) BeforeInsert() error

BeforeInsert hook for Certificate

func (*Certificate) BeforeUpdate ΒΆ

func (c *Certificate) BeforeUpdate() error

BeforeUpdate hook for Certificate

type CertificateAuthEvent ΒΆ

type CertificateAuthEvent struct {
	bun.BaseModel `bun:"table:mtls_auth_events,alias:cae"`

	ID             string `bun:"id,pk,type:varchar(36)" json:"id"`
	CertificateID  string `bun:"certificate_id,notnull,type:varchar(36)" json:"certificateId"`
	OrganizationID string `bun:"organization_id,notnull,type:varchar(36)" json:"organizationId"`
	UserID         string `bun:"user_id,nullzero,type:varchar(36)" json:"userId,omitempty"`

	// Event Details
	EventType string `bun:"event_type,notnull" json:"eventType"` // auth_success, auth_failure, validation_error
	Status    string `bun:"status,notnull" json:"status"`        // success, failed, error

	// Validation Details
	ValidationSteps map[string]interface{} `bun:"validation_steps,type:jsonb" json:"validationSteps,omitempty"`
	FailureReason   string                 `bun:"failure_reason,nullzero" json:"failureReason,omitempty"`
	ErrorCode       string                 `bun:"error_code,nullzero" json:"errorCode,omitempty"`

	// Request Context
	IPAddress string `bun:"ip_address,nullzero" json:"ipAddress,omitempty"`
	UserAgent string `bun:"user_agent,nullzero" json:"userAgent,omitempty"`
	RequestID string `bun:"request_id,nullzero" json:"requestId,omitempty"`

	// Smart Card Info (if applicable)
	SmartCardID    string `bun:"smart_card_id,nullzero" json:"smartCardId,omitempty"`
	CardReaderName string `bun:"card_reader_name,nullzero" json:"cardReaderName,omitempty"`

	// Metadata
	Metadata map[string]interface{} `bun:"metadata,type:jsonb" json:"metadata,omitempty"`

	// Timestamp
	CreatedAt time.Time `bun:"created_at,notnull,default:current_timestamp" json:"createdAt"`
}

CertificateAuthEvent tracks authentication events using certificates

type CertificateFilters ΒΆ

type CertificateFilters struct {
	OrganizationID string
	UserID         string
	DeviceID       string
	Status         string
	CertType       string
	Limit          int
	Offset         int
}

CertificateFilters for filtering certificate queries

type CertificatePolicy ΒΆ

type CertificatePolicy struct {
	bun.BaseModel `bun:"table:mtls_policies,alias:cp"`

	ID             string `bun:"id,pk,type:varchar(36)" json:"id"`
	OrganizationID string `bun:"organization_id,notnull,type:varchar(36)" json:"organizationId"`

	// Policy Info
	Name        string `bun:"name,notnull" json:"name"`
	Description string `bun:"description,nullzero" json:"description,omitempty"`

	// Validation Rules
	RequirePinning   bool `bun:"require_pinning,notnull,default:false" json:"requirePinning"`
	AllowSelfSigned  bool `bun:"allow_self_signed,notnull,default:false" json:"allowSelfSigned"`
	RequireCRLCheck  bool `bun:"require_crl_check,notnull,default:true" json:"requireCrlCheck"`
	RequireOCSPCheck bool `bun:"require_ocsp_check,notnull,default:true" json:"requireOcspCheck"`
	OCSPStapling     bool `bun:"ocsp_stapling,notnull,default:false" json:"ocspStapling"`

	// Certificate Requirements
	MinKeySize           int         `bun:"min_key_size,notnull,default:2048" json:"minKeySize"`
	AllowedKeyAlgorithms StringArray `bun:"allowed_key_algorithms,type:jsonb" json:"allowedKeyAlgorithms"`
	AllowedSignatureAlgs StringArray `bun:"allowed_signature_algs,type:jsonb" json:"allowedSignatureAlgs"`
	RequiredKeyUsage     StringArray `bun:"required_key_usage,type:jsonb" json:"requiredKeyUsage,omitempty"`
	RequiredEKU          StringArray `bun:"required_eku,type:jsonb" json:"requiredEku,omitempty"`

	// Validity Requirements
	MaxCertificateAge    int `bun:"max_certificate_age,notnull,default:365" json:"maxCertificateAge"`      // days
	MinRemainingValidity int `bun:"min_remaining_validity,notnull,default:30" json:"minRemainingValidity"` // days

	// Trust Requirements
	AllowedCAs         StringArray `bun:"allowed_cas,type:jsonb" json:"allowedCas,omitempty"` // fingerprints
	RequiredTrustLevel string      `bun:"required_trust_level,notnull,default:'root'" json:"requiredTrustLevel"`

	// Smart Card/PIV/CAC
	RequirePIV      bool `bun:"require_piv,notnull,default:false" json:"requirePiv"`
	RequireCAC      bool `bun:"require_cac,notnull,default:false" json:"requireCac"`
	PIVAuthCertOnly bool `bun:"piv_auth_cert_only,notnull,default:true" json:"pivAuthCertOnly"`

	// HSM Requirements
	RequireHSM          bool        `bun:"require_hsm,notnull,default:false" json:"requireHsm"`
	AllowedHSMProviders StringArray `bun:"allowed_hsm_providers,type:jsonb" json:"allowedHsmProviders,omitempty"`

	// Status
	Status    string `bun:"status,notnull,default:'active'" json:"status"` // active, inactive
	IsDefault bool   `bun:"is_default,notnull,default:false" json:"isDefault"`

	// Metadata
	Metadata map[string]interface{} `bun:"metadata,type:jsonb" json:"metadata,omitempty"`

	// Audit
	CreatedAt time.Time `bun:"created_at,notnull,default:current_timestamp" json:"createdAt"`
	UpdatedAt time.Time `bun:"updated_at,notnull,default:current_timestamp" json:"updatedAt"`
}

CertificatePolicy defines certificate validation policies

type CertificateResponse ΒΆ

type CertificateResponse struct {
	Certificate interface{} `json:"certificate"`
}

type CertificateRevocationList ΒΆ

type CertificateRevocationList struct {
	bun.BaseModel `bun:"table:mtls_crls,alias:crl"`

	ID             string `bun:"id,pk,type:varchar(36)" json:"id"`
	OrganizationID string `bun:"organization_id,notnull,type:varchar(36)" json:"organizationId"`
	TrustAnchorID  string `bun:"trust_anchor_id,notnull,type:varchar(36)" json:"trustAnchorId"`

	// CRL Info
	Issuer     string    `bun:"issuer,notnull" json:"issuer"`
	ThisUpdate time.Time `bun:"this_update,notnull" json:"thisUpdate"`
	NextUpdate time.Time `bun:"next_update,notnull" json:"nextUpdate"`

	// CRL Data
	CRLPEM    string `bun:"crl_pem,notnull,type:text" json:"-"`
	CRLNumber string `bun:"crl_number,nullzero" json:"crlNumber,omitempty"`

	// Distribution
	DistributionPoint string `bun:"distribution_point,nullzero" json:"distributionPoint,omitempty"`

	// Status
	Status string `bun:"status,notnull,default:'valid'" json:"status"` // valid, expired, superseded

	// Stats
	RevokedCertCount int `bun:"revoked_cert_count,notnull,default:0" json:"revokedCertCount"`

	// Audit
	CreatedAt     time.Time `bun:"created_at,notnull,default:current_timestamp" json:"createdAt"`
	UpdatedAt     time.Time `bun:"updated_at,notnull,default:current_timestamp" json:"updatedAt"`
	LastFetchedAt time.Time `bun:"last_fetched_at,notnull,default:current_timestamp" json:"lastFetchedAt"`
}

CertificateRevocationList stores CRL data

type CertificateValidator ΒΆ

type CertificateValidator struct {
	// contains filtered or unexported fields
}

CertificateValidator handles X.509 certificate validation

func NewCertificateValidator ΒΆ

func NewCertificateValidator(config *Config, repo Repository, revChecker *RevocationChecker) *CertificateValidator

NewCertificateValidator creates a new certificate validator

func (*CertificateValidator) ValidateCertificate ΒΆ

func (v *CertificateValidator) ValidateCertificate(ctx context.Context, certPEM []byte, orgID string) (*ValidationResult, error)

ValidateCertificate performs comprehensive certificate validation

type CertificatesResponse ΒΆ

type CertificatesResponse struct {
	Certificates interface{} `json:"certificates"`
	Count        int         `json:"count"`
}

type CloudHSMProvider ΒΆ

type CloudHSMProvider struct {
	// contains filtered or unexported fields
}

CloudHSMProvider implements HSM provider for AWS CloudHSM

func NewCloudHSMProvider ΒΆ

func NewCloudHSMProvider(config *Config) *CloudHSMProvider

NewCloudHSMProvider creates a new AWS CloudHSM provider

func (*CloudHSMProvider) Connect ΒΆ

func (p *CloudHSMProvider) Connect(ctx context.Context) error

func (*CloudHSMProvider) Disconnect ΒΆ

func (p *CloudHSMProvider) Disconnect() error

func (*CloudHSMProvider) GetCertificate ΒΆ

func (p *CloudHSMProvider) GetCertificate(ctx context.Context, keyID string) (*x509.Certificate, error)

func (*CloudHSMProvider) GetKey ΒΆ

func (p *CloudHSMProvider) GetKey(ctx context.Context, keyID string) (crypto.PrivateKey, error)

func (*CloudHSMProvider) GetProviderInfo ΒΆ

func (p *CloudHSMProvider) GetProviderInfo() *HSMProviderInfo

func (*CloudHSMProvider) ListKeys ΒΆ

func (p *CloudHSMProvider) ListKeys(ctx context.Context) ([]HSMKeyInfo, error)

func (*CloudHSMProvider) Sign ΒΆ

func (p *CloudHSMProvider) Sign(ctx context.Context, keyID string, digest []byte) ([]byte, error)

func (*CloudHSMProvider) ValidateKey ΒΆ

func (p *CloudHSMProvider) ValidateKey(ctx context.Context, keyID string) error

type Config ΒΆ

type Config struct {
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Certificate Validation
	Validation ValidationConfig `json:"validation" yaml:"validation"`

	// Revocation Checking
	Revocation RevocationConfig `json:"revocation" yaml:"revocation"`

	// PIV/CAC Smart Card Support
	SmartCard SmartCardConfig `json:"smartCard" yaml:"smartCard"`

	// HSM Integration
	HSM HSMConfig `json:"hsm" yaml:"hsm"`

	// Certificate Pinning
	Pinning PinningConfig `json:"pinning" yaml:"pinning"`

	// Trust Anchors
	TrustAnchors TrustAnchorsConfig `json:"trustAnchors" yaml:"trustAnchors"`

	// Session Management
	Session SessionConfig `json:"session" yaml:"session"`

	// API Endpoints
	API APIConfig `json:"api" yaml:"api"`

	// Security
	Security SecurityConfig `json:"security" yaml:"security"`
}

Config holds the mTLS plugin configuration

func DefaultConfig ΒΆ

func DefaultConfig() *Config

DefaultConfig returns the default mTLS configuration

func (*Config) Validate ΒΆ

func (c *Config) Validate() error

Validate validates the configuration

type CreatePolicyRequest ΒΆ

type CreatePolicyRequest struct {
	OrganizationID       string                 `json:"organizationId"`
	Name                 string                 `json:"name"`
	Description          string                 `json:"description,omitempty"`
	RequirePinning       bool                   `json:"requirePinning"`
	AllowSelfSigned      bool                   `json:"allowSelfSigned"`
	RequireCRLCheck      bool                   `json:"requireCrlCheck"`
	RequireOCSPCheck     bool                   `json:"requireOcspCheck"`
	MinKeySize           int                    `json:"minKeySize"`
	AllowedKeyAlgorithms StringArray            `json:"allowedKeyAlgorithms,omitempty"`
	AllowedSignatureAlgs StringArray            `json:"allowedSignatureAlgs,omitempty"`
	MaxCertificateAge    int                    `json:"maxCertificateAge"`
	MinRemainingValidity int                    `json:"minRemainingValidity"`
	RequirePIV           bool                   `json:"requirePiv"`
	RequireCAC           bool                   `json:"requireCac"`
	RequireHSM           bool                   `json:"requireHsm"`
	IsDefault            bool                   `json:"isDefault"`
	Metadata             map[string]interface{} `json:"metadata,omitempty"`
}

type ErrorResponse ΒΆ

type ErrorResponse = responses.ErrorResponse

Response types - use shared responses from core

type GCPCloudHSMProvider ΒΆ

type GCPCloudHSMProvider struct {
	// contains filtered or unexported fields
}

GCPCloudHSMProvider implements HSM provider for GCP Cloud HSM

func NewGCPCloudHSMProvider ΒΆ

func NewGCPCloudHSMProvider(config *Config) *GCPCloudHSMProvider

NewGCPCloudHSMProvider creates a new GCP Cloud HSM provider

func (*GCPCloudHSMProvider) Connect ΒΆ

func (p *GCPCloudHSMProvider) Connect(ctx context.Context) error

func (*GCPCloudHSMProvider) Disconnect ΒΆ

func (p *GCPCloudHSMProvider) Disconnect() error

func (*GCPCloudHSMProvider) GetCertificate ΒΆ

func (p *GCPCloudHSMProvider) GetCertificate(ctx context.Context, keyID string) (*x509.Certificate, error)

func (*GCPCloudHSMProvider) GetKey ΒΆ

func (p *GCPCloudHSMProvider) GetKey(ctx context.Context, keyID string) (crypto.PrivateKey, error)

func (*GCPCloudHSMProvider) GetProviderInfo ΒΆ

func (p *GCPCloudHSMProvider) GetProviderInfo() *HSMProviderInfo

func (*GCPCloudHSMProvider) ListKeys ΒΆ

func (p *GCPCloudHSMProvider) ListKeys(ctx context.Context) ([]HSMKeyInfo, error)

func (*GCPCloudHSMProvider) Sign ΒΆ

func (p *GCPCloudHSMProvider) Sign(ctx context.Context, keyID string, digest []byte) ([]byte, error)

func (*GCPCloudHSMProvider) ValidateKey ΒΆ

func (p *GCPCloudHSMProvider) ValidateKey(ctx context.Context, keyID string) error

type HSMConfig ΒΆ

type HSMConfig struct {
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Provider Configuration
	Provider       string            `json:"provider" yaml:"provider"` // pkcs11, cloudhsm, yubihsm, etc.
	ProviderConfig map[string]string `json:"providerConfig" yaml:"providerConfig"`

	// PKCS#11 Configuration
	PKCS11Library string `json:"pkcs11Library" yaml:"pkcs11Library"`
	PKCS11SlotID  int    `json:"pkcs11SlotId" yaml:"pkcs11SlotId"`
	PKCS11PIN     string `json:"pkcs11Pin" yaml:"pkcs11Pin"`

	// AWS CloudHSM
	CloudHSMClusterID string `json:"cloudHsmClusterId" yaml:"cloudHsmClusterId"`
	CloudHSMRegion    string `json:"cloudHsmRegion" yaml:"cloudHsmRegion"`

	// Azure Key Vault
	AzureVaultURL string `json:"azureVaultUrl" yaml:"azureVaultUrl"`
	AzureTenantID string `json:"azureTenantId" yaml:"azureTenantId"`

	// GCP Cloud HSM
	GCPProjectID string `json:"gcpProjectId" yaml:"gcpProjectId"`
	GCPLocation  string `json:"gcpLocation" yaml:"gcpLocation"`
	GCPKeyRing   string `json:"gcpKeyRing" yaml:"gcpKeyRing"`

	// Connection
	ConnectionTimeout time.Duration `json:"connectionTimeout" yaml:"connectionTimeout"`
	MaxConnections    int           `json:"maxConnections" yaml:"maxConnections"`

	// Security
	RequireHSM       bool     `json:"requireHsm" yaml:"requireHsm"` // Reject certs not backed by HSM
	AllowedProviders []string `json:"allowedProviders" yaml:"allowedProviders"`
}

HSMConfig configures Hardware Security Module integration

type HSMKeyInfo ΒΆ

type HSMKeyInfo struct {
	KeyID       string                 `json:"keyId"`
	Label       string                 `json:"label"`
	Algorithm   string                 `json:"algorithm"`
	KeySize     int                    `json:"keySize"`
	Certificate *x509.Certificate      `json:"-"`
	CreatedAt   time.Time              `json:"createdAt"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

HSMKeyInfo contains information about an HSM key

type HSMManager ΒΆ

type HSMManager struct {
	// contains filtered or unexported fields
}

HSMManager manages HSM connections and operations

func NewHSMManager ΒΆ

func NewHSMManager(config *Config, repo Repository) *HSMManager

NewHSMManager creates a new HSM manager

func (*HSMManager) GetProvider ΒΆ

func (m *HSMManager) GetProvider(name string) (HSMProvider, error)

GetProvider returns an HSM provider by name

func (*HSMManager) Init ΒΆ

func (m *HSMManager) Init(ctx context.Context) error

Init initializes HSM providers based on configuration

func (*HSMManager) Shutdown ΒΆ

func (m *HSMManager) Shutdown() error

Shutdown closes all HSM connections

func (*HSMManager) ValidateCertificateHSMBinding ΒΆ

func (m *HSMManager) ValidateCertificateHSMBinding(ctx context.Context, cert *Certificate) error

ValidateCertificateHSMBinding validates that a certificate is backed by HSM key

type HSMProvider ΒΆ

type HSMProvider interface {
	// Connect establishes connection to HSM
	Connect(ctx context.Context) error

	// Disconnect closes HSM connection
	Disconnect() error

	// GetKey retrieves a key from HSM
	GetKey(ctx context.Context, keyID string) (crypto.PrivateKey, error)

	// Sign performs a signing operation using HSM key
	Sign(ctx context.Context, keyID string, digest []byte) ([]byte, error)

	// GetCertificate retrieves a certificate from HSM
	GetCertificate(ctx context.Context, keyID string) (*x509.Certificate, error)

	// ListKeys lists available keys in HSM
	ListKeys(ctx context.Context) ([]HSMKeyInfo, error)

	// ValidateKey validates that a key exists and is accessible
	ValidateKey(ctx context.Context, keyID string) error

	// GetProviderInfo returns HSM provider information
	GetProviderInfo() *HSMProviderInfo
}

HSMProvider defines the interface for HSM providers

type HSMProviderInfo ΒΆ

type HSMProviderInfo struct {
	Provider     string            `json:"provider"`
	Version      string            `json:"version"`
	Model        string            `json:"model,omitempty"`
	SerialNumber string            `json:"serialNumber,omitempty"`
	Capabilities []string          `json:"capabilities"`
	Connected    bool              `json:"connected"`
	Metadata     map[string]string `json:"metadata,omitempty"`
}

HSMProviderInfo contains HSM provider information

type Handler ΒΆ

type Handler struct {
	// contains filtered or unexported fields
}

Handler handles HTTP requests for mTLS operations

func NewHandler ΒΆ

func NewHandler(service *Service) *Handler

NewHandler creates a new mTLS handler

func (*Handler) AddTrustAnchor ΒΆ

func (h *Handler) AddTrustAnchor(c forge.Context) error

AddTrustAnchor adds a new trust anchor POST /auth/mtls/trust-anchors

func (*Handler) AuthenticateWithCertificate ΒΆ

func (h *Handler) AuthenticateWithCertificate(c forge.Context) error

AuthenticateWithCertificate authenticates using client certificate POST /auth/mtls/authenticate

func (*Handler) CreatePolicy ΒΆ

func (h *Handler) CreatePolicy(c forge.Context) error

CreatePolicy creates a certificate policy POST /auth/mtls/policies

func (*Handler) GetAuthStats ΒΆ

func (h *Handler) GetAuthStats(c forge.Context) error

GetAuthStats retrieves authentication statistics GET /auth/mtls/stats/auth

func (*Handler) GetCertificate ΒΆ

func (h *Handler) GetCertificate(c forge.Context) error

GetCertificate retrieves a certificate by ID GET /auth/mtls/certificates/:id

func (*Handler) GetExpiringCertificates ΒΆ

func (h *Handler) GetExpiringCertificates(c forge.Context) error

GetExpiringCertificates retrieves certificates expiring soon GET /auth/mtls/certificates/expiring

func (*Handler) GetPolicy ΒΆ

func (h *Handler) GetPolicy(c forge.Context) error

GetPolicy retrieves a policy by ID GET /auth/mtls/policies/:id

func (*Handler) GetTrustAnchors ΒΆ

func (h *Handler) GetTrustAnchors(c forge.Context) error

GetTrustAnchors lists trust anchors for an organization GET /auth/mtls/trust-anchors

func (*Handler) ListCertificates ΒΆ

func (h *Handler) ListCertificates(c forge.Context) error

ListCertificates lists certificates with filters GET /auth/mtls/certificates

func (*Handler) RegisterCertificate ΒΆ

func (h *Handler) RegisterCertificate(c forge.Context) error

RegisterCertificate registers a new certificate POST /auth/mtls/certificates

func (*Handler) RevokeCertificate ΒΆ

func (h *Handler) RevokeCertificate(c forge.Context) error

RevokeCertificate revokes a certificate POST /auth/mtls/certificates/:id/revoke

func (*Handler) ValidateCertificate ΒΆ

func (h *Handler) ValidateCertificate(c forge.Context) error

ValidateCertificate validates a certificate without authentication POST /auth/mtls/validate

type MTLSCertificateListResponse ΒΆ

type MTLSCertificateListResponse struct {
	Certificates []interface{} `json:"certificates"`
}

type MTLSCertificateResponse ΒΆ

type MTLSCertificateResponse struct {
	Certificate interface{} `json:"certificate"`
}

type MessageResponse ΒΆ

type MessageResponse = responses.MessageResponse

type OCSPResponse ΒΆ

type OCSPResponse struct {
	bun.BaseModel `bun:"table:mtls_ocsp_responses,alias:ocsp"`

	ID            string `bun:"id,pk,type:varchar(36)" json:"id"`
	CertificateID string `bun:"certificate_id,notnull,type:varchar(36)" json:"certificateId"`

	// OCSP Response
	Status     string     `bun:"status,notnull" json:"status"` // good, revoked, unknown
	ProducedAt time.Time  `bun:"produced_at,notnull" json:"producedAt"`
	ThisUpdate time.Time  `bun:"this_update,notnull" json:"thisUpdate"`
	NextUpdate *time.Time `bun:"next_update,nullzero" json:"nextUpdate,omitempty"`

	// Response Data
	ResponseData string `bun:"response_data,type:text" json:"-"`
	ResponderID  string `bun:"responder_id,nullzero" json:"responderId,omitempty"`

	// Revocation Info (if revoked)
	RevokedAt        *time.Time `bun:"revoked_at,nullzero" json:"revokedAt,omitempty"`
	RevocationReason string     `bun:"revocation_reason,nullzero" json:"revocationReason,omitempty"`

	// Cache
	ExpiresAt time.Time `bun:"expires_at,notnull" json:"expiresAt"`

	// Audit
	CreatedAt time.Time `bun:"created_at,notnull,default:current_timestamp" json:"createdAt"`
	UpdatedAt time.Time `bun:"updated_at,notnull,default:current_timestamp" json:"updatedAt"`
}

OCSPResponse stores OCSP response cache

type PIVCardInfo ΒΆ

type PIVCardInfo struct {
	CardID         string           `json:"cardId"`
	CardholderUUID string           `json:"cardholderUuid,omitempty"`
	ExpirationDate *time.Time       `json:"expirationDate,omitempty"`
	Certificates   []PIVCertificate `json:"certificates"`
	PINPolicy      PIVPINPolicy     `json:"pinPolicy"`
	ReaderName     string           `json:"readerName,omitempty"`
}

PIVCardInfo contains PIV card information

type PIVCertificate ΒΆ

type PIVCertificate struct {
	SlotID      string            `json:"slotId"`   // 9A, 9C, 9D, 9E
	SlotName    string            `json:"slotName"` // Authentication, Digital Signature, Key Management, Card Authentication
	Certificate *x509.Certificate `json:"-"`
	Fingerprint string            `json:"fingerprint"`
}

PIVCertificate represents a certificate slot on a PIV card

type PIVPINPolicy ΒΆ

type PIVPINPolicy struct {
	PINRequired  bool `json:"pinRequired"`
	PINMinLength int  `json:"pinMinLength"`
	PINMaxLength int  `json:"pinMaxLength"`
	Retries      int  `json:"retries"`
	PINVerified  bool `json:"pinVerified"`
}

PIVPINPolicy defines PIN requirements

type PKCS11Provider ΒΆ

type PKCS11Provider struct {
	// contains filtered or unexported fields
}

PKCS11Provider implements HSM provider for PKCS#11 devices

func NewPKCS11Provider ΒΆ

func NewPKCS11Provider(config *Config) *PKCS11Provider

NewPKCS11Provider creates a new PKCS#11 provider

func (*PKCS11Provider) Connect ΒΆ

func (p *PKCS11Provider) Connect(ctx context.Context) error

func (*PKCS11Provider) Disconnect ΒΆ

func (p *PKCS11Provider) Disconnect() error

func (*PKCS11Provider) GetCertificate ΒΆ

func (p *PKCS11Provider) GetCertificate(ctx context.Context, keyID string) (*x509.Certificate, error)

func (*PKCS11Provider) GetKey ΒΆ

func (p *PKCS11Provider) GetKey(ctx context.Context, keyID string) (crypto.PrivateKey, error)

func (*PKCS11Provider) GetProviderInfo ΒΆ

func (p *PKCS11Provider) GetProviderInfo() *HSMProviderInfo

func (*PKCS11Provider) ListKeys ΒΆ

func (p *PKCS11Provider) ListKeys(ctx context.Context) ([]HSMKeyInfo, error)

func (*PKCS11Provider) Sign ΒΆ

func (p *PKCS11Provider) Sign(ctx context.Context, keyID string, digest []byte) ([]byte, error)

func (*PKCS11Provider) ValidateKey ΒΆ

func (p *PKCS11Provider) ValidateKey(ctx context.Context, keyID string) error

type PinningConfig ΒΆ

type PinningConfig struct {
	Enabled            bool          `json:"enabled" yaml:"enabled"`
	Required           bool          `json:"required" yaml:"required"` // Reject unpinned certs
	PinExpiration      time.Duration `json:"pinExpiration" yaml:"pinExpiration"`
	AutoPin            bool          `json:"autoPin" yaml:"autoPin"` // Auto-pin on first use
	PinRotationWarning time.Duration `json:"pinRotationWarning" yaml:"pinRotationWarning"`
}

PinningConfig configures certificate pinning

type Plugin ΒΆ

type Plugin struct {
	// contains filtered or unexported fields
}

Plugin implements the AuthSome plugin interface for mTLS

func NewPlugin ΒΆ

func NewPlugin() *Plugin

NewPlugin creates a new mTLS plugin

func (*Plugin) Description ΒΆ

func (p *Plugin) Description() string

Description returns the plugin description

func (*Plugin) HSMManager ΒΆ

func (p *Plugin) HSMManager() *HSMManager

HSMManager returns the HSM manager for direct access (optional public method)

func (*Plugin) ID ΒΆ

func (p *Plugin) ID() string

ID returns the plugin identifier

func (*Plugin) Init ΒΆ

func (p *Plugin) Init(auth interface{}) error

Init initializes the plugin with AuthSome dependencies

func (*Plugin) Migrate ΒΆ

func (p *Plugin) Migrate() error

Migrate performs database migrations

func (*Plugin) Name ΒΆ

func (p *Plugin) Name() string

Name returns the plugin name

func (*Plugin) RegisterHooks ΒΆ

func (p *Plugin) RegisterHooks(hookRegistry *hooks.HookRegistry) error

RegisterHooks registers plugin hooks with the hook registry (implements Plugin interface)

func (*Plugin) RegisterRoutes ΒΆ

func (p *Plugin) RegisterRoutes(router forge.Router) error

RegisterRoutes registers HTTP routes for the plugin

func (*Plugin) RegisterServiceDecorators ΒΆ

func (p *Plugin) RegisterServiceDecorators(services *registry.ServiceRegistry) error

RegisterServiceDecorators allows plugins to replace core services with decorated versions

func (*Plugin) Service ΒΆ

func (p *Plugin) Service() *Service

Service returns the mTLS service for direct access (optional public method)

func (*Plugin) Shutdown ΒΆ

func (p *Plugin) Shutdown() error

Shutdown cleanly shuts down the plugin

func (*Plugin) SmartCardProvider ΒΆ

func (p *Plugin) SmartCardProvider() *SmartCardProvider

SmartCardProvider returns the smart card provider for direct access (optional public method)

func (*Plugin) Validator ΒΆ

func (p *Plugin) Validator() *CertificateValidator

Validator returns the certificate validator for direct access (optional public method)

func (*Plugin) Version ΒΆ

func (p *Plugin) Version() string

Version returns the plugin version

type RegisterCertificateRequest ΒΆ

type RegisterCertificateRequest struct {
	OrganizationID   string                 `json:"organizationId"`
	UserID           string                 `json:"userId,omitempty"`
	DeviceID         string                 `json:"deviceId,omitempty"`
	CertificatePEM   string                 `json:"certificatePem"`
	CertificateType  string                 `json:"certificateType"`  // user, device, service
	CertificateClass string                 `json:"certificateClass"` // standard, piv, cac, smartcard
	PIVCardID        string                 `json:"pivCardId,omitempty"`
	CACNumber        string                 `json:"cacNumber,omitempty"`
	HSMKeyID         string                 `json:"hsmKeyId,omitempty"`
	HSMProvider      string                 `json:"hsmProvider,omitempty"`
	IsPinned         bool                   `json:"isPinned"`
	Metadata         map[string]interface{} `json:"metadata,omitempty"`
}

type Repository ΒΆ

type Repository interface {
	// Certificates
	CreateCertificate(ctx context.Context, cert *Certificate) error
	GetCertificate(ctx context.Context, id string) (*Certificate, error)
	GetCertificateByFingerprint(ctx context.Context, fingerprint string) (*Certificate, error)
	GetCertificateBySerialNumber(ctx context.Context, serialNumber string) (*Certificate, error)
	ListCertificates(ctx context.Context, filters CertificateFilters) ([]*Certificate, error)
	UpdateCertificate(ctx context.Context, cert *Certificate) error
	RevokeCertificate(ctx context.Context, id string, reason string) error
	DeleteCertificate(ctx context.Context, id string) error

	// Certificate queries
	GetUserCertificates(ctx context.Context, userID string) ([]*Certificate, error)
	GetDeviceCertificates(ctx context.Context, deviceID string) ([]*Certificate, error)
	GetExpiringCertificates(ctx context.Context, orgID string, days int) ([]*Certificate, error)

	// Trust Anchors
	CreateTrustAnchor(ctx context.Context, anchor *TrustAnchor) error
	GetTrustAnchor(ctx context.Context, id string) (*TrustAnchor, error)
	GetTrustAnchorByFingerprint(ctx context.Context, fingerprint string) (*TrustAnchor, error)
	ListTrustAnchors(ctx context.Context, orgID string) ([]*TrustAnchor, error)
	UpdateTrustAnchor(ctx context.Context, anchor *TrustAnchor) error
	DeleteTrustAnchor(ctx context.Context, id string) error

	// CRLs
	CreateCRL(ctx context.Context, crl *CertificateRevocationList) error
	GetCRL(ctx context.Context, id string) (*CertificateRevocationList, error)
	GetCRLByIssuer(ctx context.Context, issuer string) (*CertificateRevocationList, error)
	ListCRLs(ctx context.Context, trustAnchorID string) ([]*CertificateRevocationList, error)
	UpdateCRL(ctx context.Context, crl *CertificateRevocationList) error
	DeleteCRL(ctx context.Context, id string) error

	// OCSP Responses
	CreateOCSPResponse(ctx context.Context, resp *OCSPResponse) error
	GetOCSPResponse(ctx context.Context, certificateID string) (*OCSPResponse, error)
	UpdateOCSPResponse(ctx context.Context, resp *OCSPResponse) error
	DeleteExpiredOCSPResponses(ctx context.Context) error

	// Auth Events
	CreateAuthEvent(ctx context.Context, event *CertificateAuthEvent) error
	ListAuthEvents(ctx context.Context, filters AuthEventFilters) ([]*CertificateAuthEvent, error)
	GetAuthEventStats(ctx context.Context, orgID string, since time.Time) (*AuthEventStats, error)

	// Policies
	CreatePolicy(ctx context.Context, policy *CertificatePolicy) error
	GetPolicy(ctx context.Context, id string) (*CertificatePolicy, error)
	GetDefaultPolicy(ctx context.Context, orgID string) (*CertificatePolicy, error)
	ListPolicies(ctx context.Context, orgID string) ([]*CertificatePolicy, error)
	UpdatePolicy(ctx context.Context, policy *CertificatePolicy) error
	DeletePolicy(ctx context.Context, id string) error
}

Repository defines the data access interface for mTLS

type RevocationChecker ΒΆ

type RevocationChecker struct {
	// contains filtered or unexported fields
}

RevocationChecker handles certificate revocation checking via CRL and OCSP

func NewRevocationChecker ΒΆ

func NewRevocationChecker(config *Config, repo Repository) *RevocationChecker

NewRevocationChecker creates a new revocation checker

func (*RevocationChecker) CheckRevocation ΒΆ

func (r *RevocationChecker) CheckRevocation(ctx context.Context, cert *x509.Certificate) (string, error)

CheckRevocation checks if a certificate has been revoked

func (*RevocationChecker) CleanupExpiredCache ΒΆ

func (r *RevocationChecker) CleanupExpiredCache(ctx context.Context) error

CleanupExpiredCache removes expired OCSP responses from cache

type RevocationConfig ΒΆ

type RevocationConfig struct {
	// CRL Configuration
	EnableCRL        bool          `json:"enableCrl" yaml:"enableCrl"`
	CRLCacheDuration time.Duration `json:"crlCacheDuration" yaml:"crlCacheDuration"`
	CRLFetchTimeout  time.Duration `json:"crlFetchTimeout" yaml:"crlFetchTimeout"`
	CRLMaxSize       int64         `json:"crlMaxSize" yaml:"crlMaxSize"` // bytes
	AutoFetchCRL     bool          `json:"autoFetchCrl" yaml:"autoFetchCrl"`

	// OCSP Configuration
	EnableOCSP        bool          `json:"enableOcsp" yaml:"enableOcsp"`
	OCSPCacheDuration time.Duration `json:"ocspCacheDuration" yaml:"ocspCacheDuration"`
	OCSPTimeout       time.Duration `json:"ocspTimeout" yaml:"ocspTimeout"`
	OCSPStapling      bool          `json:"ocspStapling" yaml:"ocspStapling"`

	// Fallback Behavior
	FailOpen   bool `json:"failOpen" yaml:"failOpen"` // Allow auth if revocation unavailable
	PreferOCSP bool `json:"preferOcsp" yaml:"preferOcsp"`
}

RevocationConfig configures certificate revocation checking

type SecurityConfig ΒΆ

type SecurityConfig struct {
	// Rate Limiting
	RateLimitEnabled     bool `json:"rateLimitEnabled" yaml:"rateLimitEnabled"`
	MaxAttemptsPerMinute int  `json:"maxAttemptsPerMinute" yaml:"maxAttemptsPerMinute"`
	MaxAttemptsPerHour   int  `json:"maxAttemptsPerHour" yaml:"maxAttemptsPerHour"`

	// Audit Logging
	AuditAllAttempts bool `json:"auditAllAttempts" yaml:"auditAllAttempts"`
	AuditFailures    bool `json:"auditFailures" yaml:"auditFailures"`
	AuditValidation  bool `json:"auditValidation" yaml:"auditValidation"`

	// Certificate Storage
	StoreCertificates bool `json:"storeCertificates" yaml:"storeCertificates"`
	StorePrivateKeys  bool `json:"storePrivateKeys" yaml:"storePrivateKeys"` // Usually false
	EncryptStorage    bool `json:"encryptStorage" yaml:"encryptStorage"`

	// Notifications
	NotifyOnRevocation bool `json:"notifyOnRevocation" yaml:"notifyOnRevocation"`
	NotifyOnExpiration bool `json:"notifyOnExpiration" yaml:"notifyOnExpiration"`
	ExpirationWarning  int  `json:"expirationWarning" yaml:"expirationWarning"` // days
}

SecurityConfig configures security settings

type Service ΒΆ

type Service struct {
	// contains filtered or unexported fields
}

Service handles mTLS business logic

func NewService ΒΆ

func NewService(
	config *Config,
	repo Repository,
	validator *CertificateValidator,
	revChecker *RevocationChecker,
	smartCard *SmartCardProvider,
	hsmManager *HSMManager,
) *Service

NewService creates a new mTLS service

func (*Service) AddTrustAnchor ΒΆ

func (s *Service) AddTrustAnchor(ctx context.Context, req *AddTrustAnchorRequest) (*TrustAnchor, error)

AddTrustAnchor adds a new trusted CA certificate

func (*Service) AuthenticateWithCertificate ΒΆ

func (s *Service) AuthenticateWithCertificate(ctx context.Context, certPEM []byte, orgID string) (*AuthenticationResult, error)

AuthenticateWithCertificate authenticates a user with a client certificate

func (*Service) CreatePolicy ΒΆ

func (s *Service) CreatePolicy(ctx context.Context, req *CreatePolicyRequest) (*CertificatePolicy, error)

CreatePolicy creates a certificate policy

func (*Service) GetAuthEventStats ΒΆ

func (s *Service) GetAuthEventStats(ctx context.Context, orgID string, since time.Time) (*AuthEventStats, error)

GetAuthEventStats retrieves authentication statistics

func (*Service) GetCertificate ΒΆ

func (s *Service) GetCertificate(ctx context.Context, id string) (*Certificate, error)

GetCertificate retrieves a certificate by ID

func (*Service) GetExpiringCertificates ΒΆ

func (s *Service) GetExpiringCertificates(ctx context.Context, orgID string, days int) ([]*Certificate, error)

GetExpiringCertificates retrieves certificates expiring soon

func (*Service) GetPolicy ΒΆ

func (s *Service) GetPolicy(ctx context.Context, id string) (*CertificatePolicy, error)

GetPolicy retrieves a policy by ID

func (*Service) GetTrustAnchors ΒΆ

func (s *Service) GetTrustAnchors(ctx context.Context, orgID string) ([]*TrustAnchor, error)

GetTrustAnchors lists trust anchors for an organization

func (*Service) ListCertificates ΒΆ

func (s *Service) ListCertificates(ctx context.Context, filters CertificateFilters) ([]*Certificate, error)

ListCertificates lists certificates with filters

func (*Service) RegisterCertificate ΒΆ

func (s *Service) RegisterCertificate(ctx context.Context, req *RegisterCertificateRequest) (*Certificate, error)

RegisterCertificate registers a new client certificate

func (*Service) RevokeCertificate ΒΆ

func (s *Service) RevokeCertificate(ctx context.Context, id string, reason string) error

RevokeCertificate revokes a certificate

type SessionConfig ΒΆ

type SessionConfig struct {
	// Session Creation
	CreateSession   bool          `json:"createSession" yaml:"createSession"`
	SessionDuration time.Duration `json:"sessionDuration" yaml:"sessionDuration"`

	// Certificate Binding
	BindToFingerprint bool `json:"bindToFingerprint" yaml:"bindToFingerprint"` // Bind session to cert
	RequireSameCert   bool `json:"requireSameCert" yaml:"requireSameCert"`     // Require same cert for session

	// Re-validation
	RevalidateOnUse    bool          `json:"revalidateOnUse" yaml:"revalidateOnUse"`
	RevalidateInterval time.Duration `json:"revalidateInterval" yaml:"revalidateInterval"`
}

SessionConfig configures mTLS session management

type SmartCardAuthRequest ΒΆ

type SmartCardAuthRequest struct {
	OrganizationID  string                 `json:"organizationId"`
	CardType        string                 `json:"cardType"` // piv, cac
	ReaderName      string                 `json:"readerName,omitempty"`
	PIN             string                 `json:"pin,omitempty"`
	CertificateSlot string                 `json:"certificateSlot,omitempty"`
	Metadata        map[string]interface{} `json:"metadata,omitempty"`
}

SmartCardAuthRequest contains authentication request data

type SmartCardAuthResponse ΒΆ

type SmartCardAuthResponse struct {
	Success          bool              `json:"success"`
	UserID           string            `json:"userId,omitempty"`
	CertificateID    string            `json:"certificateId,omitempty"`
	CardInfo         interface{}       `json:"cardInfo,omitempty"`
	ValidationResult *ValidationResult `json:"validationResult,omitempty"`
	Error            string            `json:"error,omitempty"`
}

SmartCardAuthResponse contains authentication response

type SmartCardConfig ΒΆ

type SmartCardConfig struct {
	Enabled bool `json:"enabled" yaml:"enabled"`

	// PIV (Personal Identity Verification)
	EnablePIV       bool     `json:"enablePiv" yaml:"enablePiv"`
	PIVAuthCertOnly bool     `json:"pivAuthCertOnly" yaml:"pivAuthCertOnly"` // Only accept PIV auth certificate
	PIVRequiredOIDs []string `json:"pivRequiredOids" yaml:"pivRequiredOids"`

	// CAC (Common Access Card)
	EnableCAC       bool     `json:"enableCac" yaml:"enableCac"`
	CACRequiredOIDs []string `json:"cacRequiredOids" yaml:"cacRequiredOids"`

	// Card Reader Configuration
	Readers       []string      `json:"readers" yaml:"readers"` // Specific readers to use (empty = all)
	ReaderTimeout time.Duration `json:"readerTimeout" yaml:"readerTimeout"`

	// PIN Configuration
	RequirePIN     bool `json:"requirePin" yaml:"requirePin"`
	MaxPINAttempts int  `json:"maxPinAttempts" yaml:"maxPinAttempts"`
	PINMinLength   int  `json:"pinMinLength" yaml:"pinMinLength"`
	PINMaxLength   int  `json:"pinMaxLength" yaml:"pinMaxLength"`

	// Security
	LockCardOnFailure bool          `json:"lockCardOnFailure" yaml:"lockCardOnFailure"`
	CardTimeout       time.Duration `json:"cardTimeout" yaml:"cardTimeout"`
}

SmartCardConfig configures PIV/CAC smart card support

type SmartCardProvider ΒΆ

type SmartCardProvider struct {
	// contains filtered or unexported fields
}

SmartCardProvider handles PIV/CAC smart card authentication

func NewSmartCardProvider ΒΆ

func NewSmartCardProvider(config *Config, repo Repository) *SmartCardProvider

NewSmartCardProvider creates a new smart card provider

func (*SmartCardProvider) AuthenticateWithCAC ΒΆ

func (s *SmartCardProvider) AuthenticateWithCAC(ctx context.Context, cert *x509.Certificate, orgID string) (*SmartCardAuthResponse, error)

AuthenticateWithCAC authenticates a user with CAC certificate

func (*SmartCardProvider) AuthenticateWithPIV ΒΆ

func (s *SmartCardProvider) AuthenticateWithPIV(ctx context.Context, cert *x509.Certificate, orgID string) (*SmartCardAuthResponse, error)

AuthenticateWithPIV authenticates a user with PIV certificate

func (*SmartCardProvider) ValidateCACCard ΒΆ

func (s *SmartCardProvider) ValidateCACCard(ctx context.Context, cert *x509.Certificate) (*CACCardInfo, error)

ValidateCACCard validates a CAC card and extracts certificate

func (*SmartCardProvider) ValidatePIVCard ΒΆ

func (s *SmartCardProvider) ValidatePIVCard(ctx context.Context, cert *x509.Certificate) (*PIVCardInfo, error)

ValidatePIVCard validates a PIV card and extracts certificate

type StatusResponse ΒΆ

type StatusResponse = responses.StatusResponse

type StringArray ΒΆ

type StringArray []string

StringArray is a custom type for string arrays stored as JSONB

func (*StringArray) Scan ΒΆ

func (s *StringArray) Scan(value interface{}) error

Scan implements the sql.Scanner interface

func (StringArray) Value ΒΆ

func (s StringArray) Value() (driver.Value, error)

Value implements the driver.Valuer interface

type SuccessResponse ΒΆ

type SuccessResponse = responses.SuccessResponse

type TrustAnchor ΒΆ

type TrustAnchor struct {
	bun.BaseModel `bun:"table:mtls_trust_anchors,alias:ta"`

	ID             string `bun:"id,pk,type:varchar(36)" json:"id"`
	OrganizationID string `bun:"organization_id,notnull,type:varchar(36)" json:"organizationId"`

	// CA Info
	Name         string `bun:"name,notnull" json:"name"`
	Subject      string `bun:"subject,notnull" json:"subject"`
	Issuer       string `bun:"issuer,notnull" json:"issuer"`
	SerialNumber string `bun:"serial_number,notnull" json:"serialNumber"`
	Fingerprint  string `bun:"fingerprint,notnull,unique" json:"fingerprint"`

	// Certificate
	CertificatePEM string `bun:"certificate_pem,notnull,type:text" json:"-"`

	// Validity
	NotBefore time.Time `bun:"not_before,notnull" json:"notBefore"`
	NotAfter  time.Time `bun:"not_after,notnull" json:"notAfter"`

	// Trust Level
	TrustLevel string `bun:"trust_level,notnull" json:"trustLevel"` // root, intermediate, self_signed
	IsRootCA   bool   `bun:"is_root_ca,notnull,default:false" json:"isRootCA"`

	// Revocation Checking
	CRLEndpoints  StringArray `bun:"crl_endpoints,type:jsonb" json:"crlEndpoints,omitempty"`
	OCSPEndpoints StringArray `bun:"ocsp_endpoints,type:jsonb" json:"ocspEndpoints,omitempty"`

	// Status
	Status string `bun:"status,notnull,default:'active'" json:"status"` // active, revoked, expired

	// Metadata
	Metadata map[string]interface{} `bun:"metadata,type:jsonb" json:"metadata,omitempty"`

	// Audit
	CreatedAt time.Time `bun:"created_at,notnull,default:current_timestamp" json:"createdAt"`
	UpdatedAt time.Time `bun:"updated_at,notnull,default:current_timestamp" json:"updatedAt"`
}

TrustAnchor represents a trusted CA certificate

type TrustAnchorsConfig ΒΆ

type TrustAnchorsConfig struct {
	// System Trust Store
	UseSystemStore  bool   `json:"useSystemStore" yaml:"useSystemStore"`
	SystemStorePath string `json:"systemStorePath" yaml:"systemStorePath"`

	// Custom Trust Anchors
	CustomAnchors []string `json:"customAnchors" yaml:"customAnchors"` // Paths to CA certs

	// Auto-Update
	AutoUpdate     bool          `json:"autoUpdate" yaml:"autoUpdate"`
	UpdateInterval time.Duration `json:"updateInterval" yaml:"updateInterval"`

	// Validation
	ValidateAnchors bool `json:"validateAnchors" yaml:"validateAnchors"`
	RejectExpired   bool `json:"rejectExpired" yaml:"rejectExpired"`
}

TrustAnchorsConfig configures trust anchor management

type TrustStoresResponse ΒΆ

type TrustStoresResponse struct {
	TrustStores interface{} `json:"trust_stores"`
	Count       int         `json:"count"`
}

type ValidationConfig ΒΆ

type ValidationConfig struct {
	// Basic Validation
	CheckExpiration       bool `json:"checkExpiration" yaml:"checkExpiration"`
	CheckNotBefore        bool `json:"checkNotBefore" yaml:"checkNotBefore"`
	CheckSignature        bool `json:"checkSignature" yaml:"checkSignature"`
	CheckKeyUsage         bool `json:"checkKeyUsage" yaml:"checkKeyUsage"`
	CheckExtendedKeyUsage bool `json:"checkExtendedKeyUsage" yaml:"checkExtendedKeyUsage"`

	// Chain Validation
	ValidateChain   bool `json:"validateChain" yaml:"validateChain"`
	MaxChainLength  int  `json:"maxChainLength" yaml:"maxChainLength"`
	AllowSelfSigned bool `json:"allowSelfSigned" yaml:"allowSelfSigned"`

	// Key Requirements
	MinKeySize           int      `json:"minKeySize" yaml:"minKeySize"` // bits
	AllowedKeyAlgorithms []string `json:"allowedKeyAlgorithms" yaml:"allowedKeyAlgorithms"`
	AllowedSignatureAlgs []string `json:"allowedSignatureAlgs" yaml:"allowedSignatureAlgs"`

	// Validity Requirements
	MaxCertificateAge    int `json:"maxCertificateAge" yaml:"maxCertificateAge"`       // days
	MinRemainingValidity int `json:"minRemainingValidity" yaml:"minRemainingValidity"` // days

	// Required Extensions
	RequiredKeyUsage []string `json:"requiredKeyUsage" yaml:"requiredKeyUsage"`
	RequiredEKU      []string `json:"requiredEku" yaml:"requiredEku"`
}

ValidationConfig configures certificate validation

type ValidationError ΒΆ

type ValidationError struct {
	Code       string
	Message    string
	Field      string
	Details    map[string]interface{}
	Underlying error
}

ValidationError provides detailed validation failure information

func NewValidationError ΒΆ

func NewValidationError(code, message, field string, underlying error) *ValidationError

NewValidationError creates a new validation error

func (*ValidationError) Error ΒΆ

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap ΒΆ

func (e *ValidationError) Unwrap() error

func (*ValidationError) WithDetail ΒΆ

func (e *ValidationError) WithDetail(key string, value interface{}) *ValidationError

WithDetail adds a detail to the validation error

type ValidationResult ΒΆ

type ValidationResult struct {
	Valid            bool                   `json:"valid"`
	Certificate      *x509.Certificate      `json:"-"`
	Chain            []*x509.Certificate    `json:"-"`
	Errors           []error                `json:"errors,omitempty"`
	Warnings         []string               `json:"warnings,omitempty"`
	ValidationSteps  map[string]interface{} `json:"validationSteps"`
	TrustAnchor      *TrustAnchor           `json:"trustAnchor,omitempty"`
	RevocationStatus string                 `json:"revocationStatus,omitempty"`
}

ValidationResult contains the result of certificate validation

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL