Sunday, July 18, 2021

 One of the most interesting aspects of using keyvault services is that the client application can treat it merely as a resource with little or no maintenance for the scope and lifetime of that resource. This enables it to integrate with existing applications as a pipeline:

For example:

public class KeyVaultProxy : HttpPipelinePolicy, IDisposable

    {

        private readonly Cache _cache;

        public KeyVaultProxy()
        {
            _cache = new Cache();
        }

        public void Clear() => _cache.Clear();

       public override async ValueTask ProcessAsync(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline) =>
            await ProcessAsync(true, message, pipeline).ConfigureAwait(false);

        private async ValueTask ProcessAsync(bool isAsync, HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline)
        {
            Request request = message.Request;
            if (request.Method == RequestMethod.Get)
            {
                string uri = request.Uri.ToUri().GetLeftPart(UriPartial.Path);
                if (IsSupported(uri))
                {
                    message.Response = await _cache.GetOrAddAsync(isAsync, uri, null, async () =>
                    {
                        await ProcessNextAsync(isAsync, message, pipeline).ConfigureAwait(false);
                        return message.Response;
                    }).ConfigureAwait(false);

                    return;
                }
            }

            await ProcessNextAsync(isAsync, message, pipeline).ConfigureAwait(false);
        }

        private static async ValueTask ProcessNextAsync(bool isAsync, HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline)
        {
            if (isAsync)
            {
                await ProcessNextAsync(message, pipeline).ConfigureAwait(false);
            }
            else
            {
                ProcessNext(message, pipeline);
            }
        }

        /// <inheritdoc/>
        void IDisposable.Dispose()
        {
            _cache.Dispose();
            GC.SuppressFinalize(this);
        }
    }

An HttpPipelinePolicy is one that can mutate the request and the received response enabling it to work just like an Nginx handler. It is called pipelining because multiple HTTP requests can be sent in the same TCP connection. In a pipeline, there is no limitation of a response right after a request in a sequence. The resources that KeyVault supports, are part of "/secrets/", "/keys/", or "/certificates/" path qualifiers which allows policies specific to those.

No comments:

Post a Comment