Contents · Forum Home · StreamSec Tools 4.1.5.365 documentation

Make an HTTPS request with Synapse and the StreamSec TLS adapter

Use Synapse's THTTPSend to GET a URL and StreamSec to authenticate the server. This example loads a CA certificate from a file and returns the HTTP status code and the response bytes.

The components on this page are normally placed on a form or a data module at design time and set up in the Object Inspector. The sample creates them in code instead, because code shows at a glance which properties are changed from their default values.

Add the StreamSec adapter to the Synapse project

Add the Ararat Synapse source directory to the project's search path. Add SSL_StreamSec4.pas from the Delphi 13 TLS\Synapse demo to the project. Link that adapter as the project's Synapse SSL implementation. Its initialization registers TSSLStreamSec4 for new Synapse sockets. If another SSL plug-in is linked, it can replace that registration.

uses
  System.Classes, System.SysUtils, System.Net.URLClient,
  httpsend, SSL_StreamSec4,
  StreamSec.Mobile.StreamSecII, StreamSec.Mobile.TlsInternalServer;
type
  ESynapseHttpsError = class(Exception);

Set up the client trust and name checks

function NewSynapseClientEngine(const aCAFile: string): TsmSimpleTLSInternalServer;
begin
  Result := TsmSimpleTLSInternalServer.Create(nil);
  try
    Result.ClientOrServer := cosClientSide;
    Result.LocalExplicitTrustByDefault := True;
    if Result.LoadRootCertsFromFile(aCAFile) = 0 then
      raise ESynapseHttpsError.CreateFmt('No trust anchors in %s', [aCAFile]);
    Result.Options.VerifyServerName := [vsnDNS];
    Result.Options.SessionResumption := False;
    Result.TLSSetupClient;
  except
    Result.Free;
    raise;
  end;
end;

Supply a CA file you trust for the destination. TLSSetupClient applies the options before the socket connects. This example accepts a CA file on each call. It disables TLS session resumption so a new request verifies the certificate chain against that call's anchors. The adapter shares its TLS 1.3 ticket cache across sockets for the same host and port.

Use the DNS name covered by the server certificate. Passing an IP address as the expected DNS name fails the name check even when the certificate chain is trusted.

For Synapse, the host comes from the HTTPS URL. THTTPSend passes it to the socket as SNIHost and the StreamSec adapter uses it for the DNS name check. For a certificate issued to localhost, request https://localhost/. A request to https://127.0.0.1/ reaches the same machine but fails this check.

Send the GET and read the response

The adapter reads TLS records directly from the socket. Apply the HTTP client's timeout to socket sends and receives as soon as Synapse opens the socket. The value in this example is 10,000 milliseconds.

type
  TSynapseRequest = class(THTTPSend)
  public
    procedure SocketCreated(Sender: TObject);
  end;

procedure TSynapseRequest.SocketCreated(Sender: TObject);
begin
  Sock.SetTimeout(Timeout);
end;
function SynapseGet(const aURL, aCAFile: string; aBody: TStream): Integer;
var
  lHTTP: TSynapseRequest;
  lEngine: TsmSimpleTLSInternalServer;
begin
  if not aURL.StartsWith('https://', True) or (TURI.Create(aURL).Host = '') then
    raise EArgumentException.Create('An HTTPS URL with a host name is required');
  lEngine := NewSynapseClientEngine(aCAFile);
  try
    lHTTP := TSynapseRequest.Create;
    try
      (lHTTP.Sock.SSL as TSSLStreamSec4).TLSServer := lEngine;
      lHTTP.Protocol := '1.1';
      lHTTP.Timeout := 10000;
      lHTTP.Sock.OnCreateSocket := lHTTP.SocketCreated;
      if not lHTTP.HTTPMethod('GET', aURL) then
        raise ESynapseHttpsError.CreateFmt('HTTPS GET failed (%d): %s',
          [lHTTP.Sock.LastError, lHTTP.Sock.LastErrorDesc]);
      Result := lHTTP.ResultCode;
      lHTTP.Document.Position := 0;
      aBody.CopyFrom(lHTTP.Document, lHTTP.Document.Size);
    finally
      lHTTP.Free;
    end;
  finally
    lEngine.Free;
  end;
end;

Pass the HTTPS URL, the CA file name and a writable stream to SynapseGet. It writes the response at the stream's current position. On a completed HTTP exchange the return value is the server's status code, including a redirect or a 404. Inspect that code before treating the body as a successful result. If Synapse reports a transport error, the helper raises ESynapseHttpsError. A TLS alert from the StreamSec engine propagates directly. For example, an untrusted CA or a host name mismatch raises EOutgoingTLSAlert. No HTTP response is available in either case.

THTTPSend.Document holds the reply in memory, so use this pattern for responses of known, modest size. Free the HTTP client before freeing the TLS engine because the socket uses the engine during shutdown.

Reference

TsmSimpleTLSInternalServer · StreamSec.Mobile.StreamSecII · StreamSec.Mobile.TlsInternalServer

Related tasks