TrustPinErrors
public enum TrustPinErrors : Error
extension TrustPinErrors: LocalizedError
Represents possible errors thrown by the TrustPin library.
TrustPin provides detailed error information to help with debugging certificate pinning issues and implementing appropriate error handling strategies. Each error case represents a specific failure scenario with distinct security implications.
Error Categories
- Configuration errors: Issues with setup parameters or credentials
- Network errors: Problems fetching pinning configurations
- Certificate errors: Invalid or malformed certificates
- Validation errors: Certificate doesn’t match configured pins
- Security errors: Potential security threats or policy violations
Example Error Handling
do {
try await TrustPin.verify(domain: "api.example.com", certificate: cert)
} catch TrustPinErrors.domainNotRegistered {
// Handle unregistered domain (strict mode only)
logger.warning("Unregistered domain accessed")
} catch TrustPinErrors.pinsMismatch {
// Critical security issue - possible MITM attack
logger.critical("Certificate pinning failed")
throw SecurityError.potentialMITMAttack
} catch TrustPinErrors.invalidServerCert {
// Certificate format issue
logger.error("Invalid certificate format")
} catch TrustPinErrors.errorFetchingPinningInfo {
// Network connectivity issue
logger.error("Unable to fetch pinning configuration")
}
Security Response Guidelines
pinsMismatch: Treat as potential MITM attack, do not retrydomainNotRegistered: Log for security monitoring, handle per modeallPinsExpired: Update pins urgently, consider emergency bypassinvalidServerCert: Investigate certificate source and formaterrorFetchingPinningInfo: Retry with exponential backoffconfigurationValidationFailed: Check credentials and network integrityinvalidProjectConfig: Verify credentials and configuration
Topics
Configuration Errors
invalidProjectConfig
Network Errors
errorFetchingPinningInfoconfigurationValidationFailed
Certificate Errors
invalidServerCert
Validation Errors
pinsMismatchallPinsExpired
Security Errors
domainNotRegistered
-
The project configuration is invalid or incomplete.
This error occurs when the setup parameters provided to
setup(_:autoRegisterURLProtocol:)are invalid, missing, or incorrectly formatted.Common Causes
- Empty or whitespace-only organization ID, project ID, or public key
- Invalid base64 encoding in the public key
- Incorrect credential format or structure
- Network connectivity issues during credential validation
Resolution Steps
- Verify credentials: Check organization ID and project ID in TrustPin dashboard
- Validate public key: Ensure proper base64 encoding without extra characters
- Check formatting: Remove any whitespace, newlines, or special characters
- Test connectivity: Verify network access to TrustPin service
Example
do { let config = TrustPinConfiguration( organizationId: "org-123", projectId: "project-456", publicKey: "LS0tLS1CRUdJTi..." ) try await TrustPin.setup(config) } catch TrustPinErrors.invalidProjectConfig { print("Invalid credentials - check TrustPin dashboard") }Important
This error indicates a fundamental configuration issue that must be resolved before TrustPin can function.Declaration
Swift
case invalidProjectConfig -
Failed to fetch or parse the pinning configuration after exhausting all sources.
TrustPin attempts to download the JWS configuration from a prioritised chain of sources:
- Custom
configurationURL(if set) - TrustPin CDNs
The full chain is attempted twice. If all attempts fail and no valid stale cache is available, this error is thrown.
Common Causes
- Network connectivity issues affecting all CDN endpoints
- DNS resolution failures
- Firewall or proxy blocking HTTPS requests to TrustPin CDNs
- Simultaneous service downtime across all CDNs
- Invalid response format from all servers
Resolution Steps
- Check connectivity: Verify internet connection and DNS resolution
- Review firewall: Ensure HTTPS traffic to all TrustPin CDN hostnames is allowed
- Check service status: Verify TrustPin service availability
- Inspect logs: Enable
.debuglog level to see which CDN failed and why
Note
The SDK retries the full CDN chain twice and falls back to a 24-hour stale cache before throwing this error. Persistent failures indicate a systemic network issue.Declaration
Swift
case errorFetchingPinningInfo - Custom
-
The server certificate is invalid, corrupted, or could not be parsed.
This error occurs when the certificate provided to
verify(domain:certificate:)is malformed, corrupted, or not in the expected PEM format.Common Causes
- Invalid PEM format (missing BEGIN/END markers)
- Corrupted certificate data
- Incorrect encoding (not base64)
- Truncated or incomplete certificate
- Wrong certificate type (not X.509)
Certificate Format Requirements
Certificates must be in PEM format with proper markers:
-----BEGIN CERTIFICATE----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA... -----END CERTIFICATE-----Resolution Steps
- Verify format: Ensure certificate includes BEGIN/END markers
- Check encoding: Validate base64 encoding within markers
- Test parsing: Use OpenSSL or similar tool to validate certificate
- Source validation: Verify certificate source and extraction method
Example
do { try await TrustPin.verify(domain: "api.example.com", certificate: pemCert) } catch TrustPinErrors.invalidServerCert { print("Certificate format is invalid - check PEM encoding") }Important
This error indicates a problem with the certificate format, not the pinning validation.Declaration
Swift
case invalidServerCert -
No matching pins were found for the provided certificate.
This error occurs when the certificate’s public key hash doesn’t match any of the configured pins for the domain. This is a critical security error that may indicate a man-in-the-middle (MITM) attack or certificate rotation without pin updates.
Security Implications
- High severity: Potential security threat detected
- MITM attack: Certificate may be compromised or intercepted
- Service disruption: Legitimate certificate rotation without pin updates
- Configuration drift: Pins may be outdated or incorrect
Immediate Actions
- Do not retry: This is not a transient error
- Log security event: Record details for security monitoring
- Alert administrators: Notify security team of potential threat
- Block connection: Prevent potentially compromised connection
Investigation Steps
- Verify certificate: Check if server certificate changed legitimately
- Update pins: If legitimate change, update pins in TrustPin dashboard
- Check network: Investigate for network-level interference
- Review logs: Look for patterns indicating broader compromise
Example Handling
do { try await TrustPin.verify(domain: "api.example.com", certificate: cert) } catch TrustPinErrors.pinsMismatch { // Critical security issue - do not retry logger.critical("Certificate pinning failed for \(domain)") securityMonitor.alert("Potential MITM attack detected") throw SecurityError.potentialMITMAttack }Important
This error should be treated as a potential security threat and investigated immediately.Warning
Never ignore this error or implement automatic retries.Declaration
Swift
case pinsMismatch -
All configured pins for the domain have expired.
This error occurs when all the certificate pins configured for a domain have passed their expiration date. This indicates a maintenance issue that requires immediate attention to restore service availability.
Common Causes
- Expired certificates that weren’t renewed in time
- Outdated pin configuration in TrustPin dashboard
- Certificate rotation without pin updates
- Maintenance oversight or process failure
Immediate Actions
- Check certificate validity: Verify if server certificate is still valid
- Update pins: Generate new pins for current certificates
- Emergency bypass: Consider temporary permissive mode if critical
- Notify administrators: Alert operations team of expiration
Resolution Steps
- TrustPin dashboard: Update expired pins with current certificate hashes
- Certificate renewal: Renew certificates if they’re also expired
- Process review: Improve pin management and renewal processes
- Monitoring: Set up alerts for upcoming pin expirations
Emergency Bypass
If immediate service restoration is critical:
// Temporary permissive mode for emergency access try await TrustPin.setup(TrustPinConfiguration( organizationId: orgId, projectId: projectId, publicKey: publicKey, mode: .permissive // Temporary bypass ))Prevention
- Monitoring: Set up alerts 30 days before pin expiration
- Automation: Implement automated pin renewal processes
- Staging testing: Test pin updates in staging environment first
Documentation: Maintain clear pin management procedures
Important
This error requires immediate attention to restore secure connectivity.
Warning
Consider service impact before implementing emergency bypass procedures.
Declaration
Swift
case allPinsExpired -
The payload failed validation (e.g., signature mismatch or invalid structure).
This error occurs when the validation fails for the downloaded pinning configuration. This indicates either a security issue or a configuration problem with the credentials.
Common Causes
- Credential mismatch: Public key doesn’t match the signature
- Corrupted payload: Network issues corrupted the downloaded configuration
- Tampering: Potential man-in-the-middle attack on configuration
- Service issues: Problems with TrustPin service signing
- Clock skew: Timestamp validation failures due to incorrect system time
Security Implications
- High severity: Configuration integrity compromised
- Potential attack: Configuration may have been tampered with
- Service disruption: Cannot proceed with pinning validation
- Trust breakdown: Fundamental security validation failed
Resolution Steps
- Verify credentials: Ensure public key matches TrustPin dashboard
- Check system time: Verify device clock is accurate
- Test connectivity: Ensure clean network path to TrustPin service
- Retry operation: Attempt fresh configuration download
- Contact support: If persistent, contact TrustPin support
Diagnostic Information
do { try await TrustPin.setup(/* credentials */) } catch TrustPinErrors.configurationValidationFailed { print("configuration validation failed - check credentials and network") // Log additional context: // - System time // - Network conditions // - Credential sources }Prevention
- Credential management: Securely store and manage public keys
- Time synchronization: Ensure accurate system time via NTP
- Network monitoring: Monitor for network interference
Validation testing: Regularly test credential validation
Important
This error may indicate a security issue and should be investigated thoroughly.
Warning
Do not ignore this error as it may indicate configuration tampering.
Declaration
Swift
case configurationValidationFailed -
The domain is not registered for pinning and enforcement is enabled.
This error occurs only in
strictmode when attempting to verify a certificate for a domain that is not configured in your TrustPin pinning configuration. This enforces the security policy that all connections must be explicitly validated.When This Occurs
- Strict mode only: This error is not thrown in
permissivemode - Unregistered domains: Domain not found in TrustPin dashboard configuration
- Typos in domain: Incorrect domain name or subdomain
- New services: Recently added services not yet registered
Resolution Steps
- Register domain: Add domain to TrustPin dashboard with appropriate pins
- Verify domain name: Check for typos or incorrect subdomain
- Update configuration: Refresh TrustPin configuration if recently added
- Consider mode: Evaluate if
permissiveis appropriate
Domain Registration
To register a domain in TrustPin:
- TrustPin Dashboard: Log into your TrustPin account
- Add Domain: Configure domain with certificate pins
- Generate Pins: Create SHA-256 or SHA-512 hashes of certificates
- Set Expiration: Configure appropriate expiration dates
- Test Configuration: Verify in staging environment
Example Handling
do { try await TrustPin.verify(domain: "new-api.example.com", certificate: cert) } catch TrustPinErrors.domainNotRegistered { // Domain not configured for pinning logger.warning("Unregistered domain accessed: \(domain)") // Options: // 1. Register domain in TrustPin dashboard // 2. Switch to permissive mode temporarily // 3. Update application to handle unregistered domains }Security Considerations
- Intentional restriction: This error enforces your security policy
- Audit trail: Log these events for security monitoring
- Process improvement: May indicate need for better domain management
- Compliance: Helps maintain strict security compliance
Migration Strategy
When implementing strict mode:
// Phase 1: Discovery with permissive mode TrustPin.set(logLevel: .info) try await TrustPin.setup(TrustPinConfiguration( organizationId: orgId, projectId: projectId, publicKey: publicKey, mode: .permissive )) // Phase 2: Register discovered domains // (Use logs to identify all accessed domains) // Phase 3: Enable strict mode try await TrustPin.setup(TrustPinConfiguration( organizationId: orgId, projectId: projectId, publicKey: publicKey // mode defaults to .strict ))Note
This error only occurs in strict mode and is part of the security enforcement.Important
Use this error as feedback to improve your domain registration process.Declaration
Swift
case domainNotRegistered - Strict mode only: This error is not thrown in
-
Declaration
Swift
public var errorDescription: String? { get }
View on GitHub
Install in Dash