IPWorks EDI 2020 Python Edition

Questions / Feedback?

AS2Receiver Class

Properties   Methods   Events   Configuration Settings   Errors  

The AS2Receiver class is used to process EDI messages and generate receipts.

Syntax

class ipworksedi.AS2Receiver

Remarks

The AS2Receiver implements server-side processing of EDI messages, as specified in [AS2] and RFC 3335. It can be used to decrypt and verify incoming messages and to generate receipts including Message Disposition Notifications (MDNs). The class is designed to be easily incorporated into an HTTP server, and features custom functionality for server environments such as ASP.NET.

BASIC OPERATION

When an AS2 request comes in, you should first invoke read_request. This will populate as2_from and as2_to, and based on this information, you may then set the appropriate certificates. You may specify your certificate with the certificate property, and your trading partner's (signing) certificate with the signer_cert property.

Then, invoke process_request to process the request and generate the MDN receipt as specified in [AS2] and RFC 3335. If the request was processed successfully, edi_data will contain the transmitted EDI data. If a problem occurred, edi_data will not be populated and an exception will be thrown. In either case mdn_receipt will contain the RFC-compliant receipt, which should be returned to the client.

The mdn_receipt may be returned by invoking send_response. The receipt will be returned either synchronously in the HTTP reply, or asynchronously over a separate HTTP, HTTPS, or SMTP connection, as requested by the client.

To create log files, set log_directory prior to invoking process_request. This will log all incoming and outgoing data.

The following example illustrates how to use the class from an ASP.NET page. Note that in Java it will be necessary to provide an HTTPServletRequest as an argument to read_request before processing the request.

EXAMPLE

AS2Receiver1.ReadRequest();
// At this point, you should check the values of AS2From and AS2To.
AS2Receiver1.Certificate = new Certificate(CertStoreTypes.cstPFXFile, "c:\\my_server_directory\\my_pfx_file.pfx", "my password", "CN=Me");
AS2Receiver1.SignerCert = new Certificate("c:\\my_server_directory\\my_partner_cer_file.cer");
AS2Receiver1.LogDirectory = "c:\\my_server_directory\\my_log_directory";
AS2Receiver1.ProcessRequest();
AS2Receiver1.SendResponse();
Additional functionality allows the user to examine details of the client's request, to permit certain types of errors, or to customize the outgoing MDN.

ADVANCED FUNCTIONALITY

Advanced functionality is provided to allow the user to break down the AS2 process, and to allow finer control over the operation of the server. Where process_request automates the entire process, additional methods are also provided to handle each step separately.

Parsing Incoming Data

To process an EDI message, invoke read_request to process the headers from the server, or alternatively, manually set request to the contents of the HTTP request. It may contain both headers and body, or the headers may be specified separately in request_headers. This will provide more information about the client's request, without attempting to read the underlying EDI data.

After invoking read_request, the as2_from, as2_to, and message_id properties will contain the appropriate values. mdn_to will contain a nonempty string if an MDN is requested; RequestedSignatureProtocol, RequestedMICAlgorithms, and receipt_delivery_option provide more information about the client's request. Finally, request_headers contains the complete list of HTTP/AS2 headers.

Next, invoke parse_request. The certificate used to decrypt and sign should be specified with the certificate property, and your partner's signing certificate should be specified with signer_cert. This will process the headers, decompress and/or decrypt the message (if applicable), and verify the signature (if present). EncryptionType, SignatureType, and compression_format describe whether and how the data was encrypted, signed, and compressed, respectively.

parse_request will populate edi_type and edi_data.

Error Handling

If any errors occur an exception will be thrown and edi_data will not be populated. Information about the exception will be provided through the exception's error code and message and also through scan_result. An MDN receipt reporting the error may still be generated; it is recommended that server software trap the error and invoke create_mdn_receipt to report the error to the client.

The ErrorProcessingFlags property may be configured to allow predetermined types of errors. If ErrorProcessingFlags is set when parse_request (or process_request) is invoked, the errors specified will be allowed, an exception will not be thrown, and edi_data will still be determined. However, scan_result will still report the error, as will the receipt generated by create_mdn_receipt. To avoid reporting the errors in the receipt, set the ErrorReportingFlags property.

Creating an MDN-based Receipt

An MDN-based receipt may be created by invoking create_mdn_receipt. Regardless of the success or failure of process_request, the receipt may be created as specified in RFCs 3335 and 2298. If no errors occurred when process_request was invoked, the receipt will report success and will be suitable for non-repudiation of receipt (NRR) if signed. If errors occurred, the MDN will report that an error occurred and that the EDI data was not processed. It is strongly recommended that server software trap any errors thrown by process_request and return the receipt in this case as well.

The mdn_receipt will consist of the MDN itself, a human-readable message, MIME headers and footers, and a signature if applicable. The receipt may be generated by invoking create_mdn_receipt and customized further by setting the parameters to create_mdn_receipt.

The Message parameter to CreateMDNReceipt may be used to customize the human-readable message in the receipt. If it is set to an empty string, an appropriate message will automatically be written whenever mdn_receipt is regenerated.

The receipt will be signed using the protocol specified by ReceiptSigningProtocol, if any. The certificate used to sign the receipt is specified by certificate. By default the receipt will be signed if explicitly requested by the client, and unsigned otherwise.

Error reporting may be controlled by configuring ErrorReportingFlags. By default, any errors will cause mdn_receipt to report a failure to process the message (either "failed/Failure" or "processed/Error" will be reported, according to the specification and the type of error). Setting ErrorReportingFlags will cause the mdn_receipt to overlook the chosen types of errors. If all errors are overlooked, the mdn_receipt will report success and calculate a MIC on the original message as usual. A warning may be reported by setting the MDNWarning configuration setting.

Additional Server-Side Functionality

When used in a server environment such as ASP.NET, the class may be used to interface directly with the underlying HTTP context. If request is not set by the user, parse_request and process_request will first get the request from the underlying HTTP environment, if possible. send_response will send the reply in this environment if able; otherwise the reply will be directed to standard out.

ASP.NET Core Notes

The class may be used within any .NET Standard compatible platform, including .NET Core and ASP.NET Core. When using AS2Receiver within an ASP.NET Core MVC application the class can be configured to automatically read from the request context, and send using the response context. To do so pass the HttpContext to the constructor of the AS2Receiver class. For instance:


//Inside HomeController.cs
As2receiver as2 = new As2receiver(HttpContext);

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

as2_fromThe AS2 Identifier of the sending system.
as2_toThe AS2 Identifier of the receiving system.
attachment_countThe number of records in the Attachment arrays.
attachment_content_typeThe MIME content-type of this ediattachment .
attachment_dataThis property contains the attachment data.
attachment_filenameThe file name of the attachment.
attachment_headersThe class fills out Headers each time any of the other properties for that ediattachment are changed.
attachment_nameName is the final name to be associated with the contents of either the Data or Filename properties.
cem_countThe number of records in the CEM arrays.
cem_acceptedWhether the CEM request is accepted.
cem_cert_idA user defined identifier for the certificate.
cem_cert_issuerThis property holds the issuer of the certificate.
cem_cert_serial_numberThis property holds the serial number of the certificate.
cem_cert_storeThe name of the certificate store for the certificate.
cem_cert_store_passwordIf the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store.
cem_cert_store_typeThe type of certificate store for this certificate.
cem_cert_subjectThe subject of the certificate.
cem_cert_usageThis property defines which usages are applicable to the certificate.
cem_rejection_reasonIf Accepted is False this property specifies the reason a request was rejected.
cem_respond_by_dateThis property specifies the date by which the other party should respond.
cem_response_urlThis property defines the URL to which the response should be sent.
cert_encodedThe certificate (PEM/base64 encoded).
cert_storeThe name of the certificate store for the client certificate.
cert_store_passwordIf the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store.
cert_store_typeThe type of certificate store for this certificate.
cert_subjectThe subject of the certificate used for client authentication.
compression_formatThe compression format used on the incoming message.
edi_dataThis property contains the EDI payload of the transmission.
edi_typeThe Content-Type of the EDI message.
edi_filenameIn a sender, if Filename is specified, the file specified will be used for the EDI payload of the transmission.
edi_nameName is the final name to be associated with the contents of either the Data or FileName properties.
firewall_auto_detectThis property tells the class whether or not to automatically detect and use firewall system settings, if available.
firewall_typeThis property determines the type of firewall to connect through.
firewall_hostThis property contains the name or IP address of firewall (optional).
firewall_passwordThis property contains a password if authentication is to be used when connecting through the firewall.
firewall_portThis property contains the TCP port for the firewall Host .
firewall_userThis property contains a user name if authentication is to be used connecting through a firewall.
incoming_directoryThe directory to be used to store incoming messages.
local_hostThe name of the local host or user-assigned IP interface through which connections are initiated or accepted.
log_directoryThe path to a directory for logging.
log_fileThe log file written.
mdn_receipt_contentThis contains the entire content of the MDN Receipt.
mdn_receipt_header_countThe number of headers in the MDN.
mdn_receipt_header_fieldThe property name of the MDN header currently selected by HeaderIndex .
mdn_receipt_header_indexWhich MDN header is currently selected to populate HeaderField and HeaderValue .
mdn_receipt_headersHeaders contains all of the headers of the AS2 MDN Receipt as a single string.
mdn_receipt_header_valueThe value of the MDN header currently selected by HeaderIndex .
mdn_receipt_mdnMDN will contain the entire machine readable text of the Message Disposition Notification in the receipt.
mdn_receipt_messageThe human-readable portion of the MDN receipt.
mdn_receipt_mic_valueThe Message Integrity Check(s) (one-way hash) of the original EDI message.
mdn_receipt_signing_protocolThis property contains the MIME type of the signature used, if any (i.
mdn_toThe recipient for the Message Disposition Notification (MDN).
message_idThe message ID of the incoming message.
receipt_delivery_optionA URL indicating how the receipt is to be delivered.
requestThe HTTP request to be processed.
request_header_countThe number of records in the RequestHeader arrays.
request_header_fieldThis property contains the name of the HTTP header (same case as it is delivered).
request_header_valueThis property contains the header contents.
request_headers_stringThe HTTP headers in the AS2 request.
restart_directoryThe directory to log cached files when using AS2 restart functionality.
rollover_cert_encodedThe certificate (PEM/base64 encoded).
rollover_cert_storeThe name of the certificate store for the client certificate.
rollover_cert_store_passwordIf the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store.
rollover_cert_store_typeThe type of certificate store for this certificate.
rollover_cert_subjectThe subject of the certificate used for client authentication.
scan_resultThe result of invoking ParseRequest .
signer_cert_encodedThe certificate (PEM/base64 encoded).
signer_cert_storeThe name of the certificate store for the client certificate.
signer_cert_store_passwordIf the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store.
signer_cert_store_typeThe type of certificate store for this certificate.
signer_cert_subjectThe subject of the certificate used for client authentication.
ssl_accept_server_cert_encodedThe certificate (PEM/base64 encoded).
ssl_accept_server_cert_storeThe name of the certificate store for the client certificate.
ssl_accept_server_cert_store_passwordIf the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store.
ssl_accept_server_cert_store_typeThe type of certificate store for this certificate.
ssl_accept_server_cert_subjectThe subject of the certificate used for client authentication.
ssl_cert_encodedThe certificate (PEM/base64 encoded).
ssl_cert_storeThe name of the certificate store for the client certificate.
ssl_cert_store_passwordIf the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store.
ssl_cert_store_typeThe type of certificate store for this certificate.
ssl_cert_subjectThe subject of the certificate used for client authentication.
use_pssWhether to use RSA-PSS during signing and verification.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

ack_requestOptional. Acknowledges the incoming request.
configSets or retrieves a configuration setting.
create_mdn_receiptCreates MDNReceipt .
parse_requestParses the EDI message and determines the EDIData .
process_requestProcesses the EDI data, and generates the receipt.
process_restart_requestProcesses the AS2 restart request, and sends a response to the client.
read_requestReads the AS2 request from the HTTP session.
resetResets the state of the control.
send_async_mdnSends the MDNReceipt to the RemoteURL specified.
send_responseIn a server environment, responds to the requesting client with MDNReceipt .
set_tp_infoA convenient way to set AS2 communication parameters using XML strings.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

on_cem_requestFired when a Certificate Exchange Messaging (CEM) request is received.
on_cem_responseFired when a Certificate Exchange Messaging (CEM) response is received.
on_edi_data_infoFired when processing an incoming message.
on_errorInformation about errors during data delivery.
on_logFired with log information while processing a message.
on_recipient_infoFired for each recipient certificate of the encrypted message.
on_signer_cert_infoFired during verification of the signed message.
on_ssl_server_authenticationFor asynchronous HTTPS MDNs, fired after the server presents its certificate.
on_ssl_statusShows the progress of the secure connection.

Configuration Settings


The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.

AcceptAnySignerCertUsed to accept trust any signing certificate unconditionally.
AS2VersionIncomingThe version of AS2 that was used in the incoming message.
AS2VersionOutgoingThe version of AS2 to be used in the outgoing message.
AuthorizationThe Authorization string to be sent to the server.
AuthSchemeThe authorization scheme to be used when server authorization is to be performed.
CEMCertDirSpecifies the directory where certificates are saved when receiving a CEM request.
CloseStreamAfterProcessingSpecifies whether or not the OutputStream should be closed after processing.
DecodeTempDirectoryThe temp directory the class will use to decode messages.
DetectDuplicatesWhether to detect duplicate messages.
EncryptionAlgorithmThe encryption algorithm used to encrypt the incoming data.
EncryptionPaddingSchemeThe encryption padding scheme used when encrypting the incoming data.
EncryptionTypeThe MIME type of the encrypted data.
ErrorProcessingFlagsFlags controlling how errors affect ProcessRequest.
ErrorReportingFlagsFlags controlling how errors affect the MDNReceipt.
FilenameSourceThe location from which to read the filename.
InvalidFilenameMDNActionInstructs MDN disposition on invalid and duplicate filenames.
LogDebugWhether to log debug data.
LogFilenameThe base name of the log file.
LogOptionsThe information to be written to log files.
MaxPartsThe maximum number of MIME parts to process.
MDNDispositionOverrides the automatically calculated MDN disposition.
MDNMICAlgorithmThe algorithm used to sign the outgoing MDN.
MDNReportingUAThe name of the user agent performing the disposition.
MDNSendingModeThe level of end user interaction involved in sending the MDN.
MDNWarningA warning to appear in the MDN.
NormalizeMICWhether to normalize line endings before calculating the MIC.
OverwriteCEMCertsWhether existing CEM certificates are overwritten when a duplicate is received.
PasswordA password if authentication is to be used.
ProcessingErrorA processing error occurred in the received EDI message.
ProxyAuthorizationThe authorization string to be sent to the proxy server.
ProxyPasswordA password if Basic authentication is to be used for the proxy.
ProxyPortPort for the proxy server (default 80).
ProxyServerName or IP address of a proxy server (optional).
ProxyUserA user name if Basic authentication is to be used for the proxy.
ReceiptSigningProtocolThe protocol used to sign the outgoing MDN receipt.
RequestedMICAlgorithmsThe Message Integrity Check algorithm(s) requested by the client, if any.
RequestedSignatureProtocolThe signing protocol requested by the client, if any.
RequestFileReads the AS2 message from disk.
RequireAS2ToEnsure that the received message is intended for the given AS2 identifier.
RequiredSignatureAlgorithmsSpecifies a list of acceptable signature algorithms.
RequireEncryptEnsure that the received message is encrypted.
RequireOAEPEnsure that the encryption padding mode is RSAES-OAEP.
RequirePSSEnsure that the signature scheme in the received message is RSASSA-PSS.
RequireSignEnsure that the received message is signed.
ResponseSubjectThe subject to be used for the MDN response.
SenderSignatureAlgorithmThe algorithm used by the sender to sign the message.
SenderSignatureSchemeThe signature scheme used by the sender to sign the message.
SignatureTypeThe MIME type of the signature (if any).
SignerCACertCA certificate used to verify signed messages.
SMTPFromThe email address of the sender of the message.
SMTPServerThe SMTP server to be used.
UserA user name if authentication is to be used.
WarnOnMDNFailureWhether to log a .wrn file instead of a .err file when MDN delivery fails.
AcceptEncodingUsed to tell the server which types of content encodings the client supports.
AllowHTTPCompressionThis property enables HTTP compression for receiving data.
AllowHTTPFallbackWhether HTTP/2 connections are permitted to fallback to HTTP/1.1.
AppendWhether to append data to LocalFile.
AuthorizationThe Authorization string to be sent to the server.
BytesTransferredContains the number of bytes transferred in the response data.
ChunkSizeSpecifies the chunk size in bytes when using chunked encoding.
CompressHTTPRequestSet to true to compress the body of a PUT or POST request.
EncodeURLIf set to true the URL will be encoded by the class.
FollowRedirectsDetermines what happens when the server issues a redirect.
GetOn302RedirectIf set to true the class will perform a GET on the new location.
HTTP2HeadersWithoutIndexingHTTP2 headers that should not update the dynamic header table with incremental indexing.
HTTPVersionThe version of HTTP used by the class.
IfModifiedSinceA date determining the maximum age of the desired document.
KeepAliveDetermines whether the HTTP connection is closed after completion of the request.
KerberosSPNThe Service Principal Name for the Kerberos Domain Controller.
LogLevelThe level of detail that is logged.
MaxRedirectAttemptsLimits the number of redirects that are followed in a request.
NegotiatedHTTPVersionThe negotiated HTTP version.
OtherHeadersOther headers as determined by the user (optional).
ProxyAuthorizationThe authorization string to be sent to the proxy server.
ProxyAuthSchemeThe authorization scheme to be used for the proxy.
ProxyPasswordA password if authentication is to be used for the proxy.
ProxyPortPort for the proxy server (default 80).
ProxyServerName or IP address of a proxy server (optional).
ProxyUserA user name if authentication is to be used for the proxy.
SentHeadersThe full set of headers as sent by the client.
StatusLineThe first line of the last response from the server.
TransferredDataThe contents of the last response from the server.
TransferredDataLimitThe maximum number of incoming bytes to be stored by the class.
TransferredHeadersThe full set of headers as received from the server.
TransferredRequestThe full request as sent by the client.
UseChunkedEncodingEnables or Disables HTTP chunked encoding for transfers.
UseIDNsWhether to encode hostnames to internationalized domain names.
UsePlatformHTTPClientWhether or not to use the platform HTTP client.
UserAgentInformation about the user agent (browser).
ConnectionTimeoutSets a separate timeout value for establishing a connection.
FirewallAutoDetectTells the class whether or not to automatically detect and use firewall system settings, if available.
FirewallHostName or IP address of firewall (optional).
FirewallPasswordPassword to be used if authentication is to be used when connecting through the firewall.
FirewallPortThe TCP port for the FirewallHost;.
FirewallTypeDetermines the type of firewall to connect through.
FirewallUserA user name if authentication is to be used connecting through a firewall.
KeepAliveIntervalThe retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received.
KeepAliveTimeThe inactivity time in milliseconds before a TCP keep-alive packet is sent.
LingerWhen set to True, connections are terminated gracefully.
LingerTimeTime in seconds to have the connection linger.
LocalHostThe name of the local host through which connections are initiated or accepted.
LocalPortThe port in the local host where the class binds.
MaxLineLengthThe maximum amount of data to accumulate when no EOL is found.
MaxTransferRateThe transfer rate limit in bytes per second.
ProxyExceptionsListA semicolon separated list of hosts and IPs to bypass when using a proxy.
TCPKeepAliveDetermines whether or not the keep alive socket option is enabled.
TcpNoDelayWhether or not to delay when sending packets.
UseIPv6Whether to use IPv6.
LogSSLPacketsControls whether SSL packets are logged when using the internal security API.
OpenSSLCADirThe path to a directory containing CA certificates.
OpenSSLCAFileName of the file containing the list of CA's trusted by your application.
OpenSSLCipherListA string that controls the ciphers to be used by SSL.
OpenSSLPrngSeedDataThe data to seed the pseudo random number generator (PRNG).
ReuseSSLSessionDetermines if the SSL session is reused.
SSLCACertFilePathsThe paths to CA certificate files on Unix/Linux.
SSLCACertsA newline separated list of CA certificate to use during SSL client authentication.
SSLCheckCRLWhether to check the Certificate Revocation List for the server certificate.
SSLCipherStrengthThe minimum cipher strength used for bulk encryption.
SSLEnabledCipherSuitesThe cipher suite to be used in an SSL negotiation.
SSLEnabledProtocolsUsed to enable/disable the supported security protocols.
SSLEnableRenegotiationWhether the renegotiation_info SSL extension is supported.
SSLIncludeCertChainWhether the entire certificate chain is included in the SSLServerAuthentication event.
SSLNegotiatedCipherReturns the negotiated ciphersuite.
SSLNegotiatedCipherStrengthReturns the negotiated ciphersuite strength.
SSLNegotiatedCipherSuiteReturns the negotiated ciphersuite.
SSLNegotiatedKeyExchangeReturns the negotiated key exchange algorithm.
SSLNegotiatedKeyExchangeStrengthReturns the negotiated key exchange algorithm strength.
SSLNegotiatedVersionReturns the negotiated protocol version.
SSLProviderThe name of the security provider to use.
SSLSecurityFlagsFlags that control certificate verification.
SSLServerCACertsA newline separated list of CA certificate to use during SSL server certificate validation.
TLS12SignatureAlgorithmsDefines the allowed TLS 1.2 signature algorithms when UseInternalSecurityAPI is True.
TLS12SupportedGroupsThe supported groups for ECC.
TLS13KeyShareGroupsThe groups for which to pregenerate key shares.
TLS13SignatureAlgorithmsThe allowed certificate signature algorithms.
TLS13SupportedGroupsThe supported groups for (EC)DHE key exchange.
AbsoluteTimeoutDetermines whether timeouts are inactivity timeouts or absolute timeouts.
FirewallDataUsed to send extra data to the firewall.
InBufferSizeThe size in bytes of the incoming queue of the socket.
OutBufferSizeThe size in bytes of the outgoing queue of the socket.
BuildInfoInformation about the product's build.
CodePageThe system code page used for Unicode to Multibyte translations.
LicenseInfoInformation about the current license.
ProcessIdleEventsWhether the class uses its internal event loop to process events when the main thread is idle.
SelectWaitMillisThe length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks EDI 2020 Python Edition - Version 20.0 [Build 8203]