Core Concepts

Understanding these fundamental concepts will help you effectively integrate with AS2aaS and build robust AS2 messaging solutions.

Table of Contents

AS2 Protocol Overview

What is AS2?

AS2 (Applicability Statement 2) is a specification for the secure and reliable transport of business data over the internet. It's widely used in industries like healthcare, retail, and manufacturing for exchanging EDI documents and other business-critical information.

Key AS2 Features

FeaturePurposeImplementation
Message EncryptionProtect sensitive business dataUses partner's public key to encrypt payloads
Digital SignaturesEnsure message authenticity and integrityUses sender's private key to sign messages
Message CompressionReduce transmission time and bandwidthZLIB compression before encryption
Delivery ConfirmationVerify successful message deliveryMDN (Message Disposition Notification) responses
Non-repudiationLegal proof of message exchangeCryptographic signatures and audit trails

AS2 Message Flow

Loading diagram...

Account-Based Architecture

Hierarchical Structure

AS2aaS uses an account-based architecture that provides operational efficiency and centralized management:

Account (Billing Entity)
├── Master Partners (Shared Resources)
│   ├── McKesson Corporation
│   ├── Cardinal Health  
│   └── AmerisourceBergen
├── Master Certificates (Shared Security)
│   ├── Account Identity Certificate
│   └── Master Partner Certificates
├── Tenants (Operational Units)
│   ├── East Coast Division
│   │   ├── Inherited Master Partners
│   │   ├── Tenant-Specific Partners
│   │   └── Configuration Overrides
│   ├── West Coast Division
│   └── Manufacturing Division
└── Users (Access Control)
    ├── Account Owners
    ├── Tenant Administrators
    └── Tenant Members

Key Benefits

BenefitDescriptionImpact
Operational EfficiencySingle partner configuration shared across tenants80% reduction in partner management overhead
Cost SavingsShared certificates and consolidated billingSignificant cost reduction for multi-tenant organizations
Centralized ControlAccount-level policies and governanceConsistent security and compliance across all tenants
ScalabilityEasy addition of new tenants with instant partner accessRapid expansion capabilities

Account vs Tenant Operations

OperationAccount LevelTenant Level
BillingConsolidated invoicingUsage attribution
PartnersMaster partner creationPartner inheritance and overrides
CertificatesShared certificate managementTenant-specific certificates
API KeysAccount-wide accessTenant-scoped access
UsersAccount user managementTenant role assignments

Trading Partners

Partner Types

AS2aaS supports two types of trading partners that work together in the account-based architecture:

Master Partners (Account-Level)

Shared trading partners managed at the account level:

  • Scope: Available to all tenants in the account
  • Management: Created via /v1/accounts/{account}/partners
  • Use Case: Common industry partners (McKesson, Cardinal Health, etc.)
  • Benefits: Single configuration, shared certificates, reduced operational overhead

Tenant Partners

Tenant-specific trading partners:

  • Scope: Limited to individual tenant
  • Management: Created via /v1/partners
  • Use Case: Tenant-specific suppliers, regional partners, testing partners
  • Benefits: Tenant isolation, specialized configurations

Partner Resolution and Inheritance

When tenants access partners, they receive both types:

graph TD
    A[Tenant Request] --> B{Partner Resolution}
    B --> C[Tenant-Specific Partners]
    B --> D[Inherited Master Partners]
    C --> E[Combined Partner List]
    D --> E
    E --> F[Partner with Override Capability]

Partner Configuration Elements

ElementDescriptionMaster PartnersTenant Partners
NameHuman-readable identifier"McKesson Corporation""Regional Supplier"
AS2 IDUnique AS2 protocol identifier"MCKESSON""REGIONAL-001"
Endpoint URLPartner's AS2 receiving endpointShared across tenantsTenant-specific
Security SettingsEncryption, signing, compressionCentrally managedTenant controlled
AlgorithmsCryptographic preferencesAccount standardTenant customizable
MDN ModeDelivery confirmation methodConsistent policyTenant preference
CertificatesX.509 certificatesShared certificatesTenant certificates

Configuration Override Capability

Tenants can override master partner settings when needed:

Override TypeUse CaseExample
Endpoint URLTenant-specific endpointDifferent EDI gateway
Security SettingsCustom security requirementsDifferent encryption level
MDN ModeOperational preferencesSync vs async MDN
Custom HeadersIntegration requirementsTenant-specific routing

Partner Relationship Types

RelationshipMaster Partner UsageTenant Partner Usage
Major SuppliersMcKesson, Cardinal Health as master partnersRegional suppliers as tenant partners
Industry StandardsStandard EDI partners shared across tenantsCustom integration partners per tenant
Corporate PartnersParent company relationshipsDivision-specific relationships

Messages and Payloads

Message Structure

AS2 messages consist of multiple layers:

Loading diagram...

Message Components

ComponentPurposeContents
Business PayloadThe actual business documentEDI transaction, XML document, JSON data
AS2 HeadersProtocol-level metadataAS2-From, AS2-To, Message-ID
Security EnvelopeCryptographic protectionEncryption and signature wrappers
Transport HeadersHTTP-level informationContent-Type, Content-Length

Content Types

CategoryMIME TypesUse Cases
EDI Documentsapplication/edi-x12, application/edifactPurchase orders, invoices, shipping notices
XML Documentsapplication/xmlCustom business documents, SOAP messages
Structured Dataapplication/jsonModern API-style data exchange
Text Filestext/plain, text/csvSimple data files, reports
Binary Filesapplication/pdf, application/zipDocuments, compressed archives

Message Lifecycle

StatusDescriptionDurationNext Steps
queuedMessage accepted for processingSecondsSystem prepares message
processingMessage being prepared and securedSeconds to minutesTransmission to partner
sentSuccessfully transmitted to partnerImmediateAwait delivery confirmation
deliveredDelivery confirmed via MDNMinutes to hoursProcess complete
failedTransmission or processing failedImmediateReview error and retry

X.509 Certificates

Certificate Architecture

AS2aaS implements a hierarchical certificate management system aligned with the account-based architecture:

Master Certificates (Account-Level)

  • Scope: Shared across all tenants in the account
  • Management: Via /v1/accounts/{account}/certificates
  • Benefits: Single certificate renewal, consistent security policies
  • Use Case: Account identity certificates, master partner certificates

Tenant Certificates

  • Scope: Limited to specific tenant
  • Management: Via /v1/certificates
  • Benefits: Tenant-specific security requirements
  • Use Case: Tenant identity certificates, tenant-specific partner certificates

Certificate Types and Scoping

TypeAccount-LevelTenant-LevelPurpose
Identity CertificateMaster identity for all tenantsTenant-specific identityOrganization's signing/decryption certificate
Partner CertificateMaster partner certificatesTenant partner certificatesTrading partner's public certificates

Certificate Resolution Priority

When processing AS2 messages, certificates are resolved in this order:

  1. Tenant-specific certificate (highest priority)
  2. Account master certificate (inherited)
  3. System default certificate (fallback)

Certificate Usage by Scope

OperationMaster Certificate UsageTenant Certificate Usage
Sign outbound messagesAccount identity shared by all tenantsTenant-specific signing identity
Decrypt inbound messagesAccount identity for all tenantsTenant-specific decryption
Encrypt outbound messagesMaster partner certificatesTenant partner certificates
Verify inbound signaturesMaster partner certificatesTenant partner certificates

Certificate Inheritance Benefits

BenefitDescriptionImpact
Cost EfficiencySingle certificate purchase for multiple tenants70-80% cost reduction
Operational SimplicityOne renewal process instead of per-tenantReduced administrative overhead
ConsistencyUniform security policies across tenantsBetter compliance management
ScalabilityNew tenants instantly inherit certificatesRapid tenant onboarding

Certificate Lifecycle

Loading diagram...

Message Disposition Notifications (MDN)

MDN Purpose

MDNs provide cryptographic proof that a message was successfully received and processed by the intended recipient. They serve both technical and legal purposes in business communications.

MDN Modes

ModeTimingUse CaseImplementation
SynchronousImmediate responseReal-time confirmation neededMDN returned in HTTP response
AsynchronousDelayed responseStandard business messagingMDN sent as separate message
NoneNo confirmationFire-and-forget messagingNo delivery confirmation

MDN Content

FieldDescriptionExample
DispositionProcessing result"automatic-action/MDN-sent-automatically; processed"
Received Content MICMessage integrity checkCryptographic hash of received content
Reporting UAReceiving system identifier"Partner AS2 System/2.1"
Original Message IDReference to original messageLinks MDN to original message

API Keys and Authentication

Authentication Model

AS2aaS uses API key-based authentication with Bearer token format. API keys can be scoped to either account-level or tenant-level access, supporting the account-based architecture.

Key Types and Scoping

Key TypeScopeAccess LevelUse Case
Account KeysAccount-wideAll tenants within accountEnterprise management, multi-tenant operations
Tenant KeysSingle tenantSpecific tenant onlyApplication integrations, tenant-specific workflows

Account-Scoped Keys (pk_live_..., pk_test_...)

  • Access: All tenants within the account
  • Master Partners: Can manage account-level master partners
  • Billing: Account-level usage tracking
  • Use Case: Administrative operations, cross-tenant management

Tenant-Scoped Keys (tk_live_..., tk_test_...)

  • Access: Single tenant only
  • Master Partners: Can view inherited master partners (read-only)
  • Billing: Tenant-level usage attribution
  • Use Case: Application integrations, tenant-isolated operations

Key Environments

EnvironmentKey PrefixBehaviorBilling
Testpk_test_, tk_test_Messages simulated, no real transmissionNo charges
Livepk_live_, tk_live_Real AS2 messages sent to partnersBillable usage

Permission Scopes

Account-Level Scopes

ScopeAccess LevelOperations
*Full account accessAll operations across all tenants
accounts:readAccount informationView account details and settings
accounts:writeAccount managementModify account settings
tenants:readTenant informationView tenant details
tenants:writeTenant managementCreate and modify tenants
users:readUser informationView account users
users:writeUser managementManage account users

Tenant-Level Scopes

ScopeAccess LevelOperations
*Full tenant accessAll operations within tenant
messages:readRead-only messagesView message status and history
messages:writeMessage operationsSend messages, modify message data
partners:readRead-only partnersView partner configurations
partners:writePartner managementCreate and modify tenant partners
certificates:readRead-only certificatesView certificate information
certificates:writeCertificate managementUpload and manage certificates

Webhooks and Events

Event-Driven Architecture

AS2aaS uses webhooks to provide real-time notifications about message status changes, partner events, and system events. This eliminates the need for constant API polling.

Event Categories

CategoryEventsPurpose
Message Eventsmessage.queued, message.sent, message.delivered, message.failed, message.receivedTrack message lifecycle
Partner Eventspartner.created, partner.updated, partner.deletedMonitor partner changes
Certificate Eventscertificate.uploaded, certificate.expiring, certificate.expiredCertificate lifecycle management
Account Eventsaccount.created, account.updatedAccount-level changes
Tenant Eventstenant.created, tenant.updatedTenant management
Billing Eventsbilling.usage_threshold, billing.limit_exceededUsage monitoring

Webhook Security

Security FeatureImplementationPurpose
HMAC SignaturesSHA-256 with secret keyVerify webhook authenticity
HTTPS OnlyTLS encryption requiredSecure transmission
Retry LogicExponential backoffReliable delivery
Timeout Handling30-second limitPrevent hanging requests

Multi-tenant Architecture

Account-Tenant Relationship

AS2aaS implements a hierarchical multi-tenant architecture where tenants exist within accounts:

Account (acme-corp)
├── Tenant: East Coast Division (tnt_east)
├── Tenant: West Coast Division (tnt_west)  
├── Tenant: Manufacturing Division (tnt_mfg)
└── Tenant: European Operations (tnt_eu)

Tenant Concept

A tenant represents an operational unit or business division within an account. Tenants provide operational isolation while benefiting from shared account-level resources.

Resource Sharing and Isolation

ResourceAccount-LevelTenant-LevelSharing Model
MessagesUsage aggregationComplete isolationNo sharing
PartnersMaster partners (shared)Tenant partners (isolated)Inheritance with overrides
CertificatesMaster certificates (shared)Tenant certificates (isolated)Inheritance with overrides
API KeysAccount-scopedTenant-scopedHierarchical access
WebhooksAccount eventsTenant eventsScoped notifications
BillingConsolidated invoicingUsage attributionAccount-level billing

Tenant Benefits from Account Architecture

BenefitDescriptionImpact
Instant Partner AccessNew tenants inherit all master partnersImmediate operational capability
Shared Certificate CostsMaster certificates used by all tenantsReduced certificate expenses
Consistent SecurityAccount-level security policiesUniform compliance
Simplified OnboardingPre-configured master resourcesRapid tenant deployment

Tenant Context and Switching

Using Account-Scoped Keys

GET /v1/partners HTTP/1.1
Authorization: Bearer pk_live_account_key
X-Tenant-ID: tnt_000002

Using Tenant-Scoped Keys

GET /v1/partners HTTP/1.1
Authorization: Bearer tk_live_tenant_key
# Automatically scoped to tenant

Tenant Management Operations

OperationEndpointScopePurpose
List TenantsGET /v1/tenantsAccountView all account tenants
Create TenantPOST /v1/tenantsAccountAdd new operational unit
Switch ContextPOST /v1/tenants/{id}/switchAccountChange active tenant
Inherit Master PartnerPOST /v1/tenants/{id}/partners/inheritAccountAdd master partner to tenant

Data Flow Concepts

Outbound Message Flow

Loading diagram...

Inbound Message Flow

Loading diagram...

Security Concepts

Defense in Depth

AS2aaS implements multiple security layers:

LayerProtectionImplementation
Transport SecurityEncryption in transitTLS 1.3 for all communications
Application SecurityAuthentication and authorizationAPI key-based access control
Message SecurityAS2 protocol securityEncryption, signing, compression
Data SecurityEncryption at restAES-256 for stored data
Network SecurityInfrastructure protectionDDoS protection, firewall rules

Certificate Management

AspectConsiderationBest Practice
Key SizeCryptographic strength2048-bit minimum, 4096-bit recommended
Algorithm SelectionSecurity vs compatibilitySHA256withRSA for signing, AES256-CBC for encryption
Certificate RotationRegular renewalAnnual rotation recommended
Key StorageSecure key managementHardware security modules for high-security environments

Integration Patterns

Common Integration Approaches

PatternDescriptionUse Case
Direct IntegrationAPI calls from your applicationReal-time message sending
Batch ProcessingScheduled bulk operationsHigh-volume daily processing
Event-DrivenWebhook-triggered processingResponsive message handling
Middleware IntegrationThrough integration platformsEnterprise system integration

Error Handling Strategies

StrategyImplementationBenefit
Retry LogicExponential backoff for transient failuresImproved reliability
Circuit BreakerStop requests after repeated failuresSystem protection
Dead Letter QueueStore failed messages for reviewNo message loss
MonitoringTrack error rates and patternsProactive issue resolution

Performance Considerations

Message Processing Performance

FactorImpactOptimization
Message SizeLinear processing timeEnable compression for large messages
EncryptionModerate overheadChoose efficient algorithms
Partner Response TimeAffects delivery confirmationMonitor partner performance
Network LatencyGeographic distanceConsider regional deployment

API Performance

AspectConsiderationBest Practice
Request RatePlan-based limitsImplement request queuing
PaginationLarge result setsUse appropriate page sizes
FilteringReduce data transferApply specific filters
CachingReduce API callsCache stable data locally

Compliance and Auditing

Audit Trail

AS2aaS maintains comprehensive audit logs for compliance requirements:

Event TypeInformation LoggedRetention Period
Message EventsTransmission details, status changes7 years
AuthenticationAPI access, user actions7 years
Configuration ChangesPartner and certificate modifications7 years
System EventsPlatform operations, maintenance7 years

Compliance Features

RequirementAS2aaS Implementation
SOC 2 Type IIIndependently audited security controls
GDPR ComplianceData protection and privacy controls
HIPAA ReadyHealthcare data protection (Enterprise plans)
AS2 RFC 4130Full protocol compliance

Business Use Cases

Healthcare and Pharmaceuticals

Use CaseAS2 Implementation
DSCSA ComplianceTrack and trace document exchange
Prescription ProcessingSecure pharmacy communications
Clinical Data ExchangePatient information sharing
Supply Chain VisibilityPharmaceutical distribution tracking

Retail and Supply Chain

Use CaseAS2 Implementation
EDI TransactionsPurchase orders, invoices, ASNs
Inventory ManagementStock level synchronization
Drop-ship OperationsMulti-party fulfillment coordination
Vendor OnboardingAutomated partner setup

Manufacturing

Use CaseAS2 Implementation
Production SchedulingManufacturing order coordination
Quality CertificationsCertificate of analysis exchange
Supplier IntegrationSupply chain coordination
Compliance ReportingRegulatory document submission

Error Handling Concepts

Error Categories

CategoryScopeExamples
Authentication ErrorsAPI accessInvalid API key, expired token
Validation ErrorsRequest formatMissing required fields, invalid data
Transmission ErrorsAS2 protocolPartner unreachable, certificate issues
Business Logic ErrorsApplication logicPartner limits exceeded, invalid configurations

Recovery Strategies

Error TypeRecovery ApproachImplementation
Transient FailuresAutomatic retry with backoffBuilt into AS2aaS platform
Configuration IssuesManual intervention requiredUpdate partner or certificate configuration
Partner ProblemsCoordination requiredContact partner to resolve endpoint issues
Capacity LimitsPlan upgrade or optimizationMonitor usage and upgrade as needed

Monitoring and Observability

Key Metrics

MetricPurposeMonitoring Method
Message Success RateOverall system healthDashboard analytics
Delivery TimePerformance monitoringMessage status tracking
Partner AvailabilityRelationship healthConnection testing
Certificate ExpirySecurity maintenanceAutomated alerts
Usage PatternsCapacity planningBilling and usage reports

Alerting Strategy

Alert TypeTriggerResponse
Message FailuresHigh failure rate for specific partnerInvestigate partner connectivity
Certificate Expiry30 days before expirationInitiate renewal process
Usage ThresholdsApproaching plan limitsConsider plan upgrade
System IssuesPlatform-wide problemsCheck status page, contact support

Development Best Practices

Environment Management

EnvironmentPurposeConfiguration
DevelopmentInitial integration workTest API keys, sandbox partners
TestingIntegration testingTest API keys, real partner configurations
ProductionLive business operationsLive API keys, production certificates

Testing Strategy

Test TypeScopeTools
Unit TestsIndividual API callsSDK test suites
Integration TestsEnd-to-end message flowAS2aaS testing tools
Partner TestsReal partner connectivityConnection testing features
Load TestsHigh-volume scenariosBatch processing simulation

Code Organization

ComponentResponsibilityImplementation
AS2 ClientAPI communicationCentralized AS2aaS SDK usage
Message HandlerBusiness logicProcess incoming and outgoing messages
Webhook ProcessorEvent handlingProcess real-time notifications
Error HandlerException managementCentralized error processing and recovery

Next Steps

After understanding these core concepts, proceed to:

  1. Quick Start Guide - Hands-on tutorial
  2. Authentication - API key setup
  3. Messages API - Detailed API reference
  4. Partners API - Partner management
  5. Webhooks - Event notifications