<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nicolas Duminil on Medium]]></title>
        <description><![CDATA[Stories by Nicolas Duminil on Medium]]></description>
        <link>https://medium.com/@nicolasduminil?source=rss-dbb8e0d51f2e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KhxejbQMNJw0KwLw</url>
            <title>Stories by Nicolas Duminil on Medium</title>
            <link>https://medium.com/@nicolasduminil?source=rss-dbb8e0d51f2e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:43:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nicolasduminil/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reactive vs Virtual Threads on Quarkus]]></title>
            <link>https://medium.com/@nicolasduminil/reactive-vs-virtual-threads-on-quarkus-c126caf7b4de?source=rss-dbb8e0d51f2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c126caf7b4de</guid>
            <dc:creator><![CDATA[Nicolas Duminil]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 16:00:04 GMT</pubDate>
            <atom:updated>2026-11-16T16:00:04.597Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract</h3><p>This article compares the reactive style, as provided by Mutiny, with virtual threads, on one on demand HTTP operation. It explains how the two relate, shows the sequence diagram and code of each example, and analyzes the tests together with a load measurement. The most instructive results of this article contradict the expectations that I might have had before. The reader will therefore find here a full report on what was measured.</p><h3>1. Introduction</h3><p>The arrival of virtual threads in Java 21 has produced a debate more abundant in convictions than in figures. One party regards reactive pipelines as the only respectable way of waiting for a network, and another announces that they have lost their reason to exist. This article prefers a measurement, and it makes one modest request of the reader, namely to be critical against these measurement as well.</p><p>The operation under study is the retrieval of a stock quote from the <a href="https://finnhub.io/">Finnhub</a> REST API. It originates from a project concerning <a href="https://github.com/nicolasduminil/reactive-messaging">Reactive Messaging</a>, whose <a href="https://github.com/nicolasduminil/reactive-messaging">companion article</a> applies virtual threads to the consumers of a Kafka topic. The present service is independent of it, and it uses no channel and no broker.</p><p>The software versions used throughout are Java 21.0.3, Quarkus 3.40.1.1 and Mutiny 3.3.0. The full source code of the project can be found <a href="https://github.com/nicolasduminil/mutiny-virtual-threads">here</a>.</p><h3>2. The reactive style and the virtual thread style</h3><p>Both styles answer the same question, which is how a server can serve many concurrent requests that spend most of their time waiting for the network, while a platform thread remains an expensive resource.</p><p>The reactive answer avoids waiting altogether. Quarkus builds its network layer on Eclipse Vert.x, a toolkit for event driven applications on the JVM. Vert.x supplies the HTTP server that receives every request and the HTTP client that carries every call of the REST client. A small number of Vert.x event loop threads, which are ordinary platform threads, execute short callbacks, and the code is expressed as a pipeline of transformations. The answer of virtual threads, finalized in Java 21 by JEP 444, renders the waiting inexpensive. The code blocks in the most traditional manner, but what blocks is a lightweight thread that the JVM parks, not the carrier one, which is released for other work.</p><p>The two styles are alternatives, and they do not form a progression in which the second supersedes the first. The project presents both, side by side, in a single service.</p><p>The resource exposing the blocking method requires a single annotation, @RunOnVirtualThread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJozJO3K2YAh_rJaQiBuNw.png" /></figure><p>Two remarks qualify this table. First, the listing above contains one step only, and at this scale neither style exhibits a worthy readability advantage. But as soon as branching, loops and error handling appear in the code, the difference becomes perceptible. Second, the pinning hazard depends on the Java version. JEP 491, delivered in JDK 24, allows virtual threads to hold monitors independently of their carriers, which removes pinning caused by synchronized. The pinning through native code remains however possible. As this project runs on Java 21, the hazard applies in full and section 4 tests it accordingly.</p><h3>3. The service, one operation in five forms</h3><p>Virtual threads appear in this project beside Mutiny, so a precise distinction is required before going further. Section 2 presented the two styles as alternative solutions to the same problem. While this is true from the point of view of the manner in which a request spends its waiting time, as mechanisms, however, they belong to different categories. Mutiny is a library for composing asynchronous operations. A Uni is a lazy description of what must happen, it executes nothing before a subscriber appears, and its steps run on whichever thread subscribes to it or delivers its item. A virtual thread, by contrast, is a unit of execution provided by the JVM, and it knows nothing of the operations it carries. The first concerns the composition of the work, and the second concerns what executes it. This explains why the two can be combined at all.</p><p>The use case is deliberately elementary. A client performs an HTTP request to obtain the current quote of a given stock and remains connected until the response arrives. The following request illustrates this exchange.</p><pre>curl http://localhost:8080/api/v1/quote/reactive/AAPL</pre><p>The service answers with the corresponding Quote, serialized as JSON.</p><pre>{&quot;previousClose&quot;:259.71,&quot;price&quot;:261.74,&quot;symbol&quot;:&quot;AAPL&quot;}</pre><p>Serving such a request requires three successive operations:</p><ol><li>the validation of the symbol against the pattern [A-Z0-9.:-]{1,20}</li><li>a call to the /quote operation of Finnhub, which carries the symbol and the API token</li><li>the conversion of the answer into a Quote, a price of zero denoting an unknown symbol</li></ol><p>The first and the third operations consume a negligible amount of processor time, and the second one consumes nearly the entire duration of the request, which is spent waiting for the remote service. A large number of concurrent requests waiting for the network is precisely the situation that both the reactive style and virtual threads were designed to address. With so little business logic, any difference between the implementations can only originate in the manner of waiting for the result.</p><p>The service exposes this single operation through five endpoints, which differ only in one segment of their path and return the same JSON payload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDZ4q2wixyih_q_QlQOlTg.png" /></figure><p>The first two endpoints implement the alternatives shown in the sequence diagram below, and the remaining three combine them, as explained further on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*AvxMPYnFH6vcB2hqosZCoA.png" /></figure><p>The two endpoints, /api/v1/quote/reactive and respectively /api/v1/quote/virtual are served by the following REST services.</p><pre>@Path(&quot;/api/v1/quote/reactive&quot;)<br>public class ReactiveQuoteResource<br>{<br>  ...<br>  @GET<br>  @Path(&quot;/{symbol}&quot;)<br>  public Uni&lt;Quote&gt; quote(<br>    @PathParam(&quot;symbol&quot;) @Pattern(regexp = QuoteSymbol.PATTERN) String symbol)<br>  {<br>    return service.fetchReactive(symbol);<br>  }<br>}</pre><pre>...</pre><pre>@Path(&quot;/api/v1/quote/virtual&quot;)<br>public class VirtualThreadQuoteResource<br>{<br>  ...<br>  @GET<br>  @Path(&quot;/{symbol}&quot;)<br>  @RunOnVirtualThread<br>  public Quote quote(<br>    @PathParam(&quot;symbol&quot;) @Pattern(regexp = QuoteSymbol.PATTERN) String symbol)<br>  {<br>    return service.fetchBlocking(symbol);<br>  }<br>}</pre><p>A method returning a Uni is considered non-blocking, and it runs on a Vert.x event loop thread. A method returning a plain object is considered blocking, and it would normally run on a thread of the worker pool, which is a platform thread as well, unless the @RunOnVirtualThread annotation directs it to a virtual thread created for this request. The return type plays the same role as far as the REST clients are concerned. FinnhubClient declares:</p><pre>@RegisterRestClient(configKey = &quot;finnhub&quot;)<br>public interface FinnhubClient<br>{<br>  @GET<br>  @Path(&quot;/quote&quot;)<br>  Uni&lt;FinnhubQuote&gt; quote(@QueryParam(&quot;symbol&quot;) String symbol,<br>      @QueryParam(&quot;token&quot;) String token);<br>}</pre><p>while its counterpart, FinnhubBlockingClient, has different signatures:</p><pre>@RegisterRestClient(configKey = &quot;finnhub&quot;)<br>public interface FinnhubBlockingClient<br>{<br>  @GET<br>  @Path(&quot;/quote&quot;)<br>  FinnhubQuote quote(@QueryParam(&quot;symbol&quot;) String symbol,<br>      @QueryParam(&quot;token&quot;) String token);<br>}</pre><p>The two interfaces thus describe one remote operation, and they differ only in the behavior they impose upon the calling thread.</p><p>The upper part of the diagram shows the reactive path. A Vert.x event loop thread invokes the resource method, which merely constructs the pipeline and returns it. An event loop thread is an ordinary platform thread, belonging to a pool whose default size equals the number of processors. Quarkus then subscribes to this pipeline, the client sends its request without blocking, and the event loop thread proceeds to other requests. During the interval that separates the request from its answer, no thread is waiting for Finnhub. When the answer arrives, a callback executes the map step on the same event loop thread and the response is written. A small number of event loop threads can consequently serve a large number of requests, on the strict condition that each step remains brief. A blocking call on this thread would stall every request sharing the event loop, and Quarkus therefore refuses it by raising a BlockingNotAllowedException.</p><p>The lower part of the diagram shows the virtual thread path. Quarkus dispatches the request to a new virtual thread, whose code executes sequentially and calls the blocking client in the most traditional manner. While this call waits for the answer, the JVM parks the virtual thread, which means that it preserves its stack on the heap and unmounts it from its carrier. A carrier is an ordinary platform thread, belonging to a scheduler whose default size equals the number of processors, and once released it may execute another virtual thread. When the answer arrives, the virtual thread is scheduled again, possibly on a different carrier, and it resumes at the following statement, with its local variables and its enclosing try blocks intact. It remains unaware of having been absent, a privilege rarely granted to those who sleep during working hours.</p><p>Such a thread is inexpensive because its stack grows on the heap according to need, whereas a platform thread reserves its stack in advance, by default one megabyte on common 64 bit platforms. Each request can therefore receive its own virtual thread, and pooling them would defeat their purpose. Two conditions qualify this apparent gratuity. The first is that the thread must be able to unmount, and on Java 21 a virtual thread blocking inside a synchronized block remains pinned to its carrier. The tests accordingly apply the annotation @ShouldNotPin to the virtual thread endpoints. The second is that inexpensive waiting removes a limit which was also serving as a protection, a subject to which section 5.1 returns.</p><p>The measurements of section 4 show both paths reaching the same theoretical ceiling, so the choice between them rests on the style of the code and on the hazards listed in section 2, rather than on throughput.</p><p>The service then addresses the narrower question of combining these two styles. The realistic scenario is a reactive pipeline that calls an endpoint that offers only a blocking client. Quarkus rejects such a call on the event loop platform thread with an exception, so the call must move elsewhere, and the choice of its destination is what the two offloading endpoints compare.</p><p>The class QuoteService exposes two methods, offloadToWorkerPool(...) and offloadToVirtualThread(...), which move the blocking call away from the event loop platform thread. The first moves it to another thread of the worker pool, which is a platform thread as well. This transfer between two platform threads keeps the cost of the wait unchanged, because the waiting thread remains a platform thread. What it changes is the obligation attached to the thread. An event loop thread serves the requests of many connections and must remain free at every instant, whereas a worker pool thread serves one call at a time and may block while delaying that call alone. The worker pool thread nevertheless remains occupied during the entire wait, so the size of the pool bounds the number of concurrent calls. The second method moves the call to a virtual thread, which obtains the same permission to block, while the wait occupies a parked virtual thread instead of a platform thread.</p><p>The class QuoteService also exposes the method awaitOnVirtualThread(...) which does the reverse of offload(...) and calls the non-blocking reactive client from sequential code, and waits for the result by blocking the current virtual thread.</p><pre>@ApplicationScoped<br>public class QuoteService<br>{<br>   private final FinnhubClient reactiveClient;<br>   private final FinnhubBlockingClient blockingClient;<br>   private final FinnhubConfig config;<br>   private final ExecutorService virtualThreads;</pre><pre>   public QuoteService(@RestClient FinnhubClient reactiveClient,<br>                       @RestClient FinnhubBlockingClient blockingClient,<br>                       FinnhubConfig config,<br>                       @VirtualThreads ExecutorService virtualThreads)<br>   {<br>      this.reactiveClient = reactiveClient;<br>      this.blockingClient = blockingClient;<br>      this.config = config;<br>      this.virtualThreads = virtualThreads;<br>   }</pre><pre>   public Uni&lt;Quote&gt; fetchReactive(String symbol)<br>   {<br>      return reactiveClient.quote(symbol, token())<br>          .map(quote -&gt; toQuote(symbol, quote));<br>   }</pre><pre>   public Quote fetchBlocking(String symbol)<br>   {<br>      return toQuote(symbol, blockingClient.quote(symbol, token()));<br>   }</pre><pre>   public Uni&lt;Quote&gt; offloadToWorkerPool(String symbol)<br>   {<br>      return offload(symbol, Infrastructure.getDefaultWorkerPool());<br>   }</pre><pre>   public Uni&lt;Quote&gt; offloadToVirtualThread(String symbol)<br>   {<br>      return offload(symbol, virtualThreads);<br>   }</pre><pre>   public Quote awaitOnVirtualThread(String symbol)<br>   {<br>      return fetchReactive(symbol).await().indefinitely();<br>   }</pre><pre>   private Uni&lt;Quote&gt; offload(String symbol, Executor executor)<br>   {<br>      return Uni.createFrom().item(() -&gt; fetchBlocking(symbol))<br>          .runSubscriptionOn(executor);<br>   }</pre><pre>   private String token()<br>   {<br>      return config.token().orElse(&quot;&quot;);<br>   }</pre><pre>   private static Quote toQuote(String symbol, FinnhubQuote quote)<br>   {<br>      if (quote.current().signum() == 0)<br>         throw new QuoteNotFoundException(symbol);<br>      return new Quote(symbol, quote.current(), quote.previousClose());<br>   }<br>}</pre><p>The method offload deserves a careful reading, because it expresses the essence of the combination. The call Uni.createFrom().item(...) wraps the blocking operation in a lazy Uni, whose supplier executes at the moment of subscription. The operator runSubscriptionOn determines the thread on which this subscription occurs, and consequently the thread on which the blocking call runs. The resource method returns its Uni immediately, so the event loop remains free, and the signature declares a non-blocking operation. The operator emitOn would be an unfortunate substitute, since it only displaces the steps located downstream and it would leave the blocking call on the event loop.</p><p>The two offloading endpoints differ in one argument only, namely the executor. The first receives the default worker pool, whose threads are limited in number and each of which remains occupied during the entire call. The second receives an ExecutorService injected with the qualifier @VirtualThreads, which starts a virtual thread for each task. This annotated executor is preferred to Executors.newVirtualThreadPerTaskExecutor() because Quarkus propagates the context through it and governs its lifecycle. In both cases the method returns a Uni, so the caller may continue to compose it with the operators of Mutiny, for instance in order to retry the call or to recover from a failure. The two differ solely in the resource consumed during the wait, namely a platform thread that remains occupied in the first case, and a virtual thread that is parked while its carrier is released in the second.</p><p>The await endpoint performs the inverse operation. Its resource method carries @RunOnVirtualThread, and it calls the reactive client through await().indefinitely(), which subscribes to the Uni and blocks the caller until an item or a failure arrives. The HTTP exchange remains non-blocking, and the only thread that waits is the virtual thread, as the lower part of the following diagram shows. This call is possible only on a thread permitted to block. On an event loop, Mutiny raises an IllegalStateException with the message &quot;The current thread cannot be blocked&quot;. The adverb indefinitely should alarm no reader, since the read timeout of 5 seconds concludes the wait with status 504, and the tests verify it. This form is useful when sequential code must exploit a library offering only a reactive interface.</p><p>One might wish to shorten the journey by annotating a method that returns a Uni with @RunOnVirtualThread. Quarkus 3.40 logs an error stating that the method was &quot;both @NonBlocking and @RunOnVirtualThread&quot;, then starts normally and runs the method on a virtual thread, a form of protest followed by immediate compliance. The project avoids this combination, and it keeps these models in separate resources.</p><p>The presented combination of the two styles is by no means a general improvement. It serves a reactive pipeline obliged to call a blocking producer under a load capable of exhausting the worker pool. It also serves a sequential code obliged to call a reactive client. A pipeline containing no blocking call gains nothing from it, and section 4 shows that the two offloading strategies are indistinguishable at 100 connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*TGb2lv8dbPNlst2-C2Njlg.png" /></figure><p>All endpoints honor one error contract, expressed as RFC 9457 Problem Details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDQfjOIisitPsGZiYLdjSQ.png" /></figure><p>The details are fixed strings, as the URL of the upstream call carries the API token, and the text of an exception raised by a client library lies beyond the control of the application.</p><h3>4. Running the application and the tests</h3><p>The project requires JDK 21 and Maven 3.9 or later. The tests require nothing more, since they replace Finnhub with a WireMock server started within the test process. A call to the real service requires a free API key, obtained from the <a href="https://finnhub.io/">Finnhub</a> site, and the load comparison requires the HTTP benchmarking tool wrk.</p><p>The following commands clone the repository and execute the complete build, which compiles the code and runs the 59 tests analyzed in the next section.</p><pre>git clone https://github.com/nicolasduminil/mutiny-virtual-threads.git<br>cd mutiny-virtual-threads<br>mvn verify</pre><p>A single test class runs with the option -Dtest, for instance mvn test -Dtest=QuoteResourceTest. The application reads the API key from the environment variable FINNHUB_TOKEN, through the property finnhub.token. Once packaged, it starts on port 8080 and answers on the five endpoints, which share the prefix /api/v1/quote/ and differ in the path segment listed in Section 3.</p><pre>mvn package -DskipTests<br>FINNHUB_TOKEN=&lt;your-key&gt; java -jar target/quarkus-app/quarkus-run.jar &amp;<br>curl http://localhost:8080/api/v1/quote/reactive/AAPL<br>curl http://localhost:8080/api/v1/quote/virtual/AAPL</pre><p>Each endpoint returns the same JSON document, for instance {&quot;previousClose&quot;:259.71,&quot;price&quot;:261.74,&quot;symbol&quot;:&quot;AAPL&quot;}. In the absence of a valid key, Finnhub rejects the call and every endpoint answers with the status 502 defined by the error contract.</p><p>The load comparison executes the packaged application against a local stub, so it consumes no request of the Finnhub quota. The script load/compare.sh starts the stub and the application, measures each endpoint with wrk, and prints a summary grouped by number of connections. Its environment variables adjust the run, namely DELAY_MS for the latency of the stub, 200 ms by default, DURATION for the length of each measurement, 20 seconds by default, CONNECTIONS for the list of connection counts, and MODELS for the list of endpoints.</p><pre>mvn package -DskipTests<br>load/compare.sh<br>DELAY_MS=50 DURATION=30s load/compare.sh</pre><h3>5. Analysis of the test results</h3><p>The complete build executes 59 tests, all of which pass, with no test skipped. The durations below come from a single run and include the startup of the application and of the instrumentation for pinning detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3goa_6CLWtlOkIZqixamcQ.png" /></figure><p>The class QuoteResourceTest accounts for most of the total because it executes each behavior on each of the five endpoints, comprising 50 parameterized contract cases and 7 individual cases.</p><p>During this work, each significant test was therefore challenged in the following manner. A bug was deliberately introduced temporarily into the code that the test protects, the test was executed in order to verify that it failed, and the code was subsequently restored. This was performed by hand, which offers considerably less rigor than a mutation testing tool, yet it yielded very valuable results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtZMJRlbH70GLKfbUg9UDg.png" /></figure><p>The rate limit of the Finnhub free tier excludes load tests against the real service, so the script compare.sh measures the endpoints with wrk against a local stub answering after 200 ms. Each configuration ran for 20 seconds on one 8 core machine that also hosted the load generator and the stub. The figures below thus describe that machine and should not be read as capacity predictions. Each cell gives the requests per second followed by the 99th percentile of latency, and no run reported an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_WmpEa_c4Sn4UyPSsN4gVA.png" /></figure><p>Three observations follow:</p><ol><li>The reactive and virtual endpoints both reach the theoretical ceiling at every tested load. This experiment therefore detects no difference of throughput between the two models, up to 10,000 requests per second, at which point a sample of processor activity, taken during an earlier campaign, showed less than 2 percent of idle time.</li><li>The offload-worker endpoint caps near 1,000 requests per second, as predicted before the measurement. The default worker pool holds the greater of 200 threads and 8 per processor, hence 200 here, and 200 threads each occupied for 200 ms deliver 1,000 requests per second. Beyond this limit, requests wait for a thread, and the latency grows accordingly.</li><li>The offload-virtual endpoint has no such pool and reaches the ceiling. At 100 connections, however, the two offloading strategies are indistinguishable.</li></ol><p>Here are some limits of tha analysis above:</p><ol><li>The tests replace Finnhub by WireMock, and the measurements by a stub.</li><li>The load figures concern one latency, one machine and one kind of operation, with a very small amount of work per request. An application performing substantial computation would probably behave otherwise.</li></ol><p>The result of section 4 might suggest that a pool limit is simply a defect. It is also a protection, since a limit of 200 threads bounds the concurrent calls to the dependency. Virtual threads remove the worker pool limit of 200 threads. This might be seen as an improvement but it’s also a protection. Without it, a rate limited service such as Finnhub would then receive the entire load, a form of generosity that it would acknowledge with status 429. A semaphore or a dedicated limiter becomes the responsibility of the developer. It is significant that Quarkus applies a default concurrency limit of 1024 when @RunOnVirtualThread is used on messaging methods.</p><h3>6. Conclusions</h3><p>Regarding the choice between the two styles, the evidence collected here supports the following recommendations:</p><ol><li>Prefer virtual threads for request and response operations whose logic reads more clearly in sequence, especially when the team or the libraries are oriented toward blocking code. Check the pinning hazard if running on a version earlier than JDK 24.</li><li>Prefer reactive style, with Mutiny, when the application already composes asynchronous steps or requires continuous streams with explicit back pressure.</li><li>Do not select either model for throughput on the basis of this experiment, which detected no difference for input and output bound work up to its highest load. Readability, the existing code and the libraries available constitute better criteria.</li><li>Combine the models in the narrow case of a blocking dependency within an existing reactive pipeline, under concurrency sufficient to exhaust the worker pool. Below that level, the combination provides no measurable benefit, and a pipeline without any blocking call requires no combination at all.</li><li>Whichever style is chosen, assert the thread in the tests, identify the true limiting resource before attributing a result to a model, and vary the order of benchmark runs.</li></ol><h3>References</h3><ol><li>SmallRye, <a href="https://smallrye.io/smallrye-mutiny/">Mutiny documentation</a>.</li><li>Quarkus, <a href="https://quarkus.io/guides/messaging-virtual-threads">Virtual Threads Support for Messaging Applications</a>.</li><li>OpenJDK, <a href="https://openjdk.org/jeps/444">JEP 444, Virtual Threads</a>.</li><li>OpenJDK, <a href="https://openjdk.org/jeps/491">JEP 491, Synchronize Virtual Threads without Pinning</a>.</li><li>IETF, <a href="https://www.rfc-editor.org/rfc/rfc9457">RFC 9457, Problem Details for HTTP APIs</a>.</li><li>The accompanying source code, <a href="https://github.com/nicolasduminil/mutiny-virtual-threads">mutiny-virtual-threads</a>.</li><li>The companion project, <a href="https://github.com/nicolasduminil/reactive-messaging">reactive-messaging</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c126caf7b4de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring AI or LangChain4 j? One App, Three Stacks, One Test]]></title>
            <link>https://medium.com/@nicolasduminil/spring-ai-or-langchain4-j-one-app-three-stacks-one-test-2d5249cccfce?source=rss-dbb8e0d51f2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d5249cccfce</guid>
            <dc:creator><![CDATA[Nicolas Duminil]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 17:26:26 GMT</pubDate>
            <atom:updated>2026-11-10T17:30:15.574Z</atom:updated>
            <content:encoded><![CDATA[<p>Java has quietly become a credible place to build AI applications. That raises a practical question for anyone starting out: which framework do you reach for, <a href="https://docs.spring.io/spring-ai/reference/">Spring AI</a> or <a href="https://docs.langchain4j.dev/">LangChain4j</a>, and does it matter whether you run it on Spring Boot or on Quarkus?</p><p>The consistent way to answer is not a feature table. It is to build the same thing on each stack and read the difference. This article does exactly that for the smallest useful AI application: one HTTP endpoint that forwards a question to a model and returns its answer. We build it three times, in Spring AI, in LangChain4j on Spring Boot, and in LangChain4j on Quarkus, and then hold all three to a single shared test.</p><h3>One interface, three implementations</h3><p>Everything starts from one framework-neutral contract, a plain Java interface that knows nothing about any AI library:</p><pre>public interface QuestionAnsweringService {<br>  Answer askQuestion(Question question);<br>}</pre><p>Question and Answer are simple records. Each stack provides only its own implementation of this interface, and nothing framework-specific leaks into the shared code. So the only thing that varies between the three is how each one talks to the model.</p><h3>Spring AI: a fluent ChatClient</h3><pre>@Service<br>public class SpringAiQuestionAnsweringService implements QuestionAnsweringService {<br>  private final ChatClient chatClient;<br>  public SpringAiQuestionAnsweringService(ChatClient.Builder <br>    chatClientBuilder) {<br>      this.chatClient = chatClientBuilder.build();<br>  }<br><br>  @Override<br>  public Answer askQuestion(Question question) {<br>    var answerText = chatClient.prompt()<br>      .user(question.question())<br>      .call()<br>      .content();<br>    return new Answer(answerText);<br>  }<br>}</pre><p>Spring AI hands you a ChatClient.Builder, auto-configured from your properties, and a fluent API: prompt(), user(), call(), content(). The model, its base URL and its options are all configuration, not code.</p><h3>LangChain4j: a plain ChatModel, and the same code on two runtimes</h3><p>On Spring Boot:</p><pre>@Service<br>public class LangChain4jQuestionAnsweringService implements QuestionAnsweringService {<br>  private final ChatModel chatModel;<br><br>  public LangChain4jQuestionAnsweringService(ChatModel chatModel) {<br>    this.chatModel = chatModel;<br>  }<br><br>  @Override<br>  public Answer askQuestion(Question question) {<br>    return new Answer(chatModel.chat(question.question()));<br>  }<br>}</pre><p>LangChain4j hands you a ChatModel and a single method, chat(). There is no builder to call: the model is injected ready to use.</p><p>Now the Quarkus version:</p><pre>@ApplicationScoped<br>public class LangChain4jQuestionAnsweringService implements QuestionAnsweringService {<br>  private final ChatModel chatModel;<br><br>  public LangChain4jQuestionAnsweringService(ChatModel chatModel) {<br>    this.chatModel = chatModel;<br>  }<br><br>  @Override<br>  public Answer askQuestion(Question question) {<br>    return new Answer(chatModel.chat(question.question()));<br>  }<br>}</pre><p>Look closely. The body is identical to the Spring Boot version. The only difference is the annotation: @ApplicationScoped (CDI) instead of @Service (Spring). Same library, same ChatModel, same chat() call. The runtime changes, the code does not. That is precisely why it is worth running LangChain4j on both: it isolates what the framework costs from what the runtime costs.</p><h3>One test to compare them all</h3><p>Three implementations are only comparable if they are held to the same standard. Each stack’s integration test extends one abstract test that talks to the running application over HTTP:</p><pre>public abstract class AbstractQuestionAnsweringIT {<br>  protected abstract URI baseUri();<br>  <br>  @Test<br>  @DisplayName(&quot;answers a factual question&quot;)<br>  protected void answersAFactualQuestion() {<br>    ask()<br>      .body(new Question(&quot;What is the capital of France? Answer with the city name only.&quot;))<br>      .when()<br>      .post(&quot;/ask&quot;)<br>      .then()<br>      .statusCode(200)<br>      .body(&quot;answer&quot;, not(blankOrNullString()))<br>      .body(&quot;answer&quot;, containsStringIgnoringCase(&quot;paris&quot;));<br>  }<br><br>  private RequestSpecification ask() {<br>    return given().baseUri(baseUri().toString()).contentType(ContentType.JSON);<br>  }<br>}</pre><p>Two things matter here. First, the suite talks HTTP with REST Assured, never an in-process API, so the same test class can hold a Spring Boot application and a Quarkus application to the same standard: a subclass supplies only its base URI. Second, the assertion is semantic, not exact-string. It checks that the answer contains “paris”, case-insensitively, because LLM output is non-deterministic even at temperature zero. Asserting on a literal completion would make the test lie.</p><p>The tests run against a local model in an Ollama container, started with <a href="https://testcontainers.com/">Testcontainers</a>, so there is no API key, no per-run cost, and the whole comparison is reproducible in CI.</p><h3>What the comparison reveals</h3><p>The three stacks are not the same size and do not start at the same speed. Counting only non-blank, non-comment lines of production Java:</p><pre>Spring AI   LangChain4j / Boot   LangChain4j / Quarkus<br>Production Java (LOC)           48                   47                      39<br>Files in src/main/java           3                    3                       2<br>Resolved runtime jars          106                   49                     142<br>Startup, JVM mode           1.74 s               2.69 s                  0.66 s</pre><p>The startup figures are medians of a handful of runs on a single machine, with the Ollama container already up so that only application boot is inside the window: they are indicative, not benchmarks. And the jar counts do not mean Quarkus is three times heavier than LangChain4j on Boot; it simply splits its runtime into many small artifacts. A fair comparison shows that Spring AI brings 106 jars while LangChain4j brings only 49 on the <em>same</em> runtime. That’s because Spring AI brings a JSON-schema generator, a tokenizer and Reactor along with it, none of which this use case touches.</p><p>Even hedged this way, the shape is clear: Quarkus produces the smallest module and starts fastest, Spring AI is compact in code but carries the most dependencies of the two libraries on Spring Boot (106 jars to LangChain4j’s 49), and LangChain4j on Boot sits close to Spring AI, the same three files with a few extra jars for its starter.</p><p>Qualitatively, the differences are small but relevant:</p><ul><li>Spring AI leads with a fluent, builder-based ChatClient, and configuration drives the model.</li><li>LangChain4j leads with a single ChatModel.chat() call, and the injected model is the whole surface.</li><li>Between Spring Boot and Quarkus, the LangChain4j code is identical except for the dependency-injection annotation, which tells you the runtime is the variable, not the library.</li></ul><p>None of this is a verdict. The interesting output of a comparison like this is not a winner, it is the diff, and the diff is what tells you which framework fits the way your team already thinks.</p><h3>Where this goes next</h3><p>This is the smallest use case. The same method, build once per stack and grade with one shared test, carries all the way up: retrieval-augmented generation, conversational memory, tool calling, the Model Context Protocol, observability, security, and agents. Each one adds a capability and shows where the three stacks converge and where they diverge.</p><p>If you want the full treatment, it is the subject of my book, <em>Java AI Frameworks</em>, available on <a href="https://leanpub.com/javaaiframeworks">Leanpub</a> with a free sample of the first two chapters, and on Amazon:</p><figure><a href="https://www.amazon.com/dp/B0HR1T5S4B"><img alt="" src="https://cdn-images-1.medium.com/max/320/0*xJT4wbsDg-uvKZIc.jpg" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d5249cccfce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Anthropic evaluation to check Claude Code plugin efficiency]]></title>
            <link>https://medium.com/@nicolasduminil/using-anthropic-evaluation-to-check-claude-code-plugin-efficiency-dd6f3f16a397?source=rss-dbb8e0d51f2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd6f3f16a397</guid>
            <dc:creator><![CDATA[Nicolas Duminil]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 13:14:58 GMT</pubDate>
            <atom:updated>2026-11-10T13:14:58.469Z</atom:updated>
            <content:encoded><![CDATA[<h3>Context</h3><p>A Claude Code skill is a Markdown document that the assistant loads when a task matches its description. A collection of skills, agents and hooks can be packaged as a plugin and distributed through a marketplace. Since the summer of 2026, my development environment has relied on such a plugin for Java work, consisting in a set of: Spring Boot, Quarkus, Apache Camel and Jakarta EE agents and skills. This collection started as a small set of artifacts but, little by little, I extended it such that, after several months, it contained 43 files and 17,338 lines.</p><p>This raised a precise question: were the stack conventions provided by this plugin really contributing anything of measurable to the final outcome or could the model,by its intrinsic general knowledge, infer the same result, with much fewer tokens ?</p><p>This article describes how the question was answered thanks to the Anthropic evaluation tool, and what the measurements revealed about the skills and about the evaluation method itself.</p><h3>A criterion for useful skill content</h3><p>A skill contributes when it changes what the model produces. Four kinds of content satisfy that criterion:</p><ol><li>Personal or team conventions, which the model has no means to infer.</li><li>Facts more recent than the model’s training data, such as new versions and renamed artifacts.</li><li>Non-obvious pitfalls and the decisions that avoid them.</li><li>Corrections to guidance that is wrong elsewhere, including in upstream plugins.</li></ol><p>Textbook material, such as the definition of an Enterprise Integration Pattern or the meaning of an HTTP status code, belongs to what the model already knows. Trying to provide this same knowledge in skills consumes between 5,000 and 8,000 tokens each time a skill loads. Additionally, the given skill might be outdated. For example, my files still referenced Spring Boot 3.2.1 months after the move to Spring Boot 4.</p><h3>Restructuring before measuring</h3><p>The first step was to collect all the loose folders in ~/.claude, defining agents, skills and hooks, to remove the duplicates and to consolidate them in stand-alone plugins. The result is a marketplace named simplex-software that lists five plugins:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*TGYLjphxRJ5HkvQh5ipytg.png" /></figure><p>The stack plugins take precedence on every conflict. java-extras holds personal rules, cross stack decisions, operational notes and a UserPromptSubmit hook that reminds the model, on every prompt, which skills apply to the detected stack. Activation per project keeps stacks material out of the sessions that don&#39;t use them.</p><h3>The measurement method</h3><p>Claude Code provides claude plugin eval, an open source evaluation tool allowing you to test the pertinence of your skills, agents and plugins. For example, you might want to evaluate the efficiency of a given Claude Code plugin. In order to do that you need to define &quot;test cases&quot;, that are execution scenarios that specify an input prompt, the required context or tools, and the logic or criteria for determining success.</p><p>A case is a directory with a prompt and a set of graders. The harness runs each case with the plugin and without it, several times per arm, and reports the score difference. A case whose score difference stays near zero identifies a plugin which doesn’t contribute much to the content, as the model is already able to produce the same result without it. Such a plugin has to be ablated because its skills add only tokens and nothing else.</p><p>Instead of creating new files in the project, each case asked Claude to provide the requested code and configuration directly in its answer. Therefore, they don’t require a prepared sample project, write permission, etc. The graders examined the text of the answer. Each case combined three kinds of graders:</p><ol><li>Regular expressions for the specific facts the skill claims. These cost nothing.</li><li>A judge model, Claude Haiku by default with three votes, for the overall correctness.</li><li>A tool_used grader that checks whether Claude invoked the skill through the Skilltool. It shows whether the plugin arm actually loaded the skill. It is excluded from the score, because the arm without the plugin has no skill to invoke and would fail it in every run, which would inflate the difference.</li></ol><p>A case for the Camel plugin illustrates the format. The prompt file:</p><pre>---<br>name: quarkus-route-test<br>tags: [camel, quarkus]<br>max_turns: 8<br>allowed_tools: [Skill, Read, Glob, Grep]<br>---<br>Quarkus 3 project using Camel Quarkus. A RouteBuilder defines route <br>id `process-route` from `direct:process` to `kafka:processed-orders`. <br>Write a test that verifies one message reaches the Kafka endpoint <br>without a real Kafka broker being used for that endpoint. <br>Include the Maven test dependencies.<br></pre><p>Its regular expression grader, graders/test-artifact.md:</p><pre>---<br>type: regex<br>pattern: &quot;camel-quarkus-junit(?!5)&quot;<br>match: contains<br>---<br><br>Uses camel-quarkus-junit, the successor of the deprecated camel-quarkus-</pre><p>Its judge grader, graders/judge.md, whose body is the criterion the judge model applies to the answer:</p><pre>---<br>type: llm<br>---<br><br>Pass only if ALL hold:<br>- test dependency is org.apache.camel.quarkus:camel-quarkus-junit (not camel-quarkus-junit5)<br>- test extends CamelQuarkusTestSupport, overrides isUseAdviceWith() to return true, advises route &quot;process-route&quot; (mockEndpoints / mockEndpointsAndSkip) and then starts the context<br>- does not use @MockEndpoints (not available in Camel Quarkus)<br>- no Thread.sleep</pre><p>Its skill indicator, graders/skill-fired.md, which passes when Claude loads a skill whose name contains camel:</p><pre>---<br>type: tool_used<br>tool: Skill<br>input_match: &quot;camel&quot;<br>---<br><br>Indicator only: the plugin skill was loaded.</pre><p>The command runs every case of a plugin, three runs per arm, with a cost ceiling:</p><pre>claude plugin eval . -j 3 --no-publish --max-cost-usd 5</pre><h3>First results</h3><p>Ten cases covered the three own plugins. The table reports the mean score with the plugin, without it, and the difference. Two scores are corrected for grader defects described in the next section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*cdyfGxHWokpjisLtRe-UyA.png" /></figure><p>The cases with a large difference show that the plugin had a consistent contribution to the final result. In the case of Camel, for example, without the plugin the model estimated the Maven artifact version as 4.18.0, whereas the skill states 4.23.0, built on Spring Boot 4.1.1. It also selected the test artifacts camel-test-spring-junit6 instead of camel-quarkus-junit with the skill. For CircleCI it chose a plain Docker executor, which offers no Docker daemon to Testcontainers. For graceful shutdown it omitted the arithmetic that relates the preStop delay, the application shutdown timeout and terminationGracePeriodSeconds.</p><p>The cases with a difference near zero show the opposite pattern. The Reactor to Mutiny cheat sheet, the Jakarta EE pom and the CDI constructor injection rules describe knowledge the model already applies correctly. Reading the answers confirmed it: both arms produced the same code.</p><h3>Trimming, and the regression the evaluation caught</h3><p>The trimming pass removed the content with a difference near zero and reduced the rest to facts, decisions and pitfalls. The Reactor to Mutiny section disappeared. The Spring Boot to Quarkus table kept only the rows where a mistake is likely, the Jakarta EE setup became a short list of facts and The Camel Kafka test skeleton became one sentence.</p><p>The second run, performed after the trimming, confirmed that every case with a large difference kept a score of 1.00 with the plugin. Only the migration from Spring Boot to Quarkus case declined from 1.00 to 0.78 but part of the decline came from judge noise. However, a part was genuine: the shortened table row stated that the Quarkus @Transactional annotation has no readOnly attribute, which determined the model to mistakenly remove the read only behavior of the original method. Without the skill, the model preserved it through a read only Hibernate session.</p><p>The corrected rule prescribes that the intended behavior should be achieved via a read only Session with FlushMode.MANUAL, or a org.hibernate.readOnly query hint. A third run of that case, judged by Claude Sonnet with a criterion that checks the read only behavior, passed six runs out of six. The episode is the strongest argument for the evaluation: a detail that appeared harmless changed the generated code, and only the measurement detected it.</p><h3>Final state and cost</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*cjWSq3u7fTfdco63CG2LKg.png" /></figure><p>The complete exercise, including the exploratory run, both full runs and the verification run, cost about 20 US dollars in model usage. A full run of the remaining suite costs about 6 dollars and takes about five minutes with three parallel runs.</p><h3>Lessons</h3><ol><li>The useful content of a skill is narrow: versions, renamed artifacts, corrections and non-obvious conventions. Explanations of well known frameworks contribute nothing measurable.</li><li>An evaluation with and without the plugin is inexpensive and decisive. It replaces a debate about relevance with a number per case.</li><li>Graders require the same scrutiny as the skills and a small judge model is inconsistent on long answers.</li><li>A reduction of content is a change like any other and deserves a regression test. The readOnly episode demonstrates it.</li></ol><h3>Limitations</h3><p>Each arm ran three times, which indicates a direction rather than a statistically established effect. The results describe one model at one date. Here, our Camel plugin pinned the 4.23 version which a later model may know without assistance. This is precisely why the suite should run again after each model change. The cases reflect one developer’s projects, and the personal rules in house-rules were deliberately left out of the evaluation, since the model has no means of guessing them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd6f3f16a397" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time-Based One-Time Passwords with HashiCorp Vault and Quarkus]]></title>
            <link>https://medium.com/@nicolasduminil/time-based-one-time-passwords-with-hashicorp-vault-and-quarkus-4ec746b18f0a?source=rss-dbb8e0d51f2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ec746b18f0a</guid>
            <category><![CDATA[totp]]></category>
            <category><![CDATA[hashicorp-vault]]></category>
            <category><![CDATA[java-quarkus]]></category>
            <dc:creator><![CDATA[Nicolas Duminil]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 13:12:14 GMT</pubDate>
            <atom:updated>2026-11-03T13:12:14.568Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract</h3><p>This article examines how the <em>Time-Based One-Time Password</em> algorithm (TOTP) can be delegated to the secrets engine of HashiCorp Vault and consumed by a Quarkus application. It first recalls the theoretical foundations of TOTP and the purpose of Vault. It then describes the use cases of the reference implementation with a UML diagram, analyses the Vault configuration and its bootstrap script, comments on the Java code and its integration tests, and finally presents the deployment topology defined by Docker Compose.</p><h3>1. What is TOTP and what problem does it solve ?</h3><p>TOTP is a security algorithm used for two-factor authentication<strong> (</strong>2FA<strong>)</strong> or multi-factor authentication (MFA). It generates a temporary and unique authentication code of 6 digits which automatically changes every 60 seconds.</p><h4>1.1 The weakness of the static password</h4><p>The static password is the oldest and most widely deployed authentication mechanism in computing. It is also among the most fragile. A password is a shared secret that never changes unless its owner decides otherwise, which in practice means rarely. Once it is captured by phishing, keylogging, database leakage or simple observation over the shoulder, it remains valid for an indefinite period, and the legitimate owner usually has no indication that it has been compromised. The problem is aggravated by the well documented human tendency to reuse the same password across many services, so that the compromise of a modest forum may lead to the compromise of a bank account. One could say that the static password is a key that its owner copies generously and then leaves under a great number of doormats.</p><p>Strictly speaking, the defect does not reside in the password as such but in the fact that it is frequently the only proof of identity required. Whoever holds the password is, from the point of view of the system, the legitimate user, and a single theft is therefore sufficient to usurp an identity.</p><h4>1.2 Multi-factor authentication</h4><p>The classical remedy does not consist in abolishing the password, which remains convenient, inexpensive and universally understood, but in depriving it of its exclusive status. The user is required to present several proofs belonging to distinct categories, called authentication factors, which are commonly classified as follows:</p><ol><li>something the user knows, such as a password or a PIN;</li><li>something the user possesses, such as a smartphone or a hardware token;</li><li>something the user is, such as a fingerprint.</li></ol><p>The strength of the approach lies in the independence of these categories. The techniques that capture a password, such as phishing or the leakage of a database, do not provide the attacker with a physical device, and the theft of a device does not reveal what its owner knows.</p><p>The Time-Based One-Time Password algorithm (TOTP) is a widely adopted means of implementing the second category. At the moment of enrollment, the server generates a random secret, called the seed, and transmits it once to the user, generally as a QR code scanned with an authenticator application installed on a smartphone. From then on, the application and the server each derive from this seed and from the current time a short numeric code, typically of six digits, which changes every thirty seconds. To authenticate, the user submits the code currently displayed together with the password, and the server accepts it only if it matches the code computed on its side. The possession of the device holding the seed thus becomes a necessary condition for authentication, so that the knowledge of the password alone is no longer sufficient. The mathematical details of this computation are the subject of section 1.3.</p><p>When a password is combined with TOTP, an attacker must consequently succeed in two attacks of a different nature against the same person:</p><ol><li>obtaining the password, which is usually achieved remotely and on a large scale, by means of a fraudulent login page (phishing), a keylogger installed on the workstation, or the reuse of credentials published after the leakage of another service’s database (credential stuffing);</li><li>obtaining the seed or the device that holds it, which requires either the physical theft of an unlocked smartphone, the installation of malware on that particular smartphone, or the interception of the QR code during the brief moment of enrollment.</li></ol><p>The first attack can be conducted against millions of victims at once from the other side of the world, whereas the second must generally be directed at one specific person and one specific device. Combining them is considerably more difficult than succeeding in either one, and this difference of scale is the essence of the protection. It also explains why TOTP is preferable to codes sent by SMS, whose second factor can be diverted remotely by persuading a mobile operator to transfer the victim’s number to a new SIM card (SIM swapping). The password thus ceases to be the weak point of the system and becomes merely one of its two locks. Section 1.3 mentions the notable exception of real-time phishing, in which a single fraudulent page collects both the password and a fresh code and relays them immediately.</p><p>It may be observed, not without some irony, that the code produced by the device is itself a kind of password. It differs from the static one, however, in every property that made the latter fragile, since it is generated rather than chosen, changes every thirty seconds, cannot be reused and is never memorized, let alone copied under a doormat.</p><h4>1.3 The algorithm</h4><p>TOTP is specified by RFC 6238 and is a direct extension of the <em>HMAC-Based One-Time Password algorithm</em> (HOTP) defined in RFC 4226. HOTP computes a short numeric code from a shared secret K and a counter C according to the following steps:</p><ol><li>compute `HMAC-SHA1(K, C)`, which yields 20 byte value;</li><li>apply the so-called dynamic truncation, which uses the four lowest bits of the last byte as an offset in order to extract 31 bits from the HMAC value;</li><li>reduce the resulting integer modulo 10^d, where d is the number of digits, usually 6.</li></ol><p>The difficulty of HOTP lies in the synchronization of the counter between the client and the server. TOTP removes this difficulty in an elegant manner by replacing the counter with a value that both parties already share without any communication, namely the current time. The counter becomes:</p><p>T = floor((CurrentUnixTime - T0) / X)</p><p>where T0 is the origin of time (usually the Unix epoch) and X is the time step, 30 seconds by default. The one-time password is then simply HOTP(K, T).</p><p>The consequences of this construction are noteworthy:</p><ol><li>each code is valid only during a short time window, so that an intercepted code rapidly loses any value for an attacker;</li><li>the device that generates the codes needs no network connection, since it only needs the seed and a reasonably accurate clock;</li><li>the seed is transmitted only once, at enrollment time, usually through a QR code encoding an otpauth:// URI;</li><li>the server must tolerate a small clock drift, which is achieved by also accepting the codes of the adjacent time steps (the so-called skew).</li></ol><p>TOTP does not eliminate every threat. A real-time phishing proxy may still relay a fresh code within its validity window, and the seed itself must be protected with the utmost care on the server side. This last point is precisely the reason for introducing Vault into the picture.</p><h3>2. What is HashiCorp Vault and what is it used for ?</h3><p>HashiCorp Vault is a secrets management system. Its purpose is to store, generate, distribute and revoke sensitive material such as passwords, API keys, certificates and encryption keys, so that this material does not end up scattered across configuration files, environment variables and source code repositories. Every access to Vault is authenticated by a token or by an authentication method, is authorized by policies expressed in the <em>HashiCorp Configuration Language</em> (HCL), and may be recorded by an audit device.</p><p>Vault organizes its functionalities in pluggable components called secrets engines, each of them mounted at a path of a virtual file system. Among the most frequently used engines are the following:</p><ol><li>the key/value engine, which stores arbitrary static secrets;</li><li>the database engine, which generates short-lived database credentials on demand;</li><li>the PKI engine, which acts as a certification authority;</li><li>the transit engine, which offers encryption as a service;</li><li>the TOTP engine, which is the subject of this article.</li></ol><p>The TOTP engine can play two roles. In the role of a generator, Vault creates the seed, returns a QR code that the user scans with an authenticator application, and later validates the codes submitted by the user. In the role of a provider, Vault receives an existing seed and generates codes on behalf of a client. The present project uses the first role. Its essential benefit is that the seed never leaves Vault after enrollment, and that the application never stores it, never sees it again and therefore cannot leak it. An application that knows nothing can reveal nothing, which is a principle of security that is far older than computing and has been practised with great success by generations of discreet butlers.</p><p>A security-minded reader will notice an apparent paradox. The seed is protected by Vault, but Vault itself requires a secret to be opened. This is solved by the seal mechanism. At startup, the Vault storage is encrypted and Vault is said to be sealed. It must be unsealed by providing a number of key shares produced by Shamir’s secret sharing algorithm before it can serve any request. Section 4 shows how this procedure is automated, in a deliberately simplified form, for local development.</p><h3>3. Use cases</h3><p>The following diagram presents the actors of the system and the use cases in which they participate, together with their pre-conditions and post-conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/0*_af9J8kkMFKqbkcx.png" /></figure><p>The operator intervenes only once, by starting the stack, after which the bootstrap is fully automated. The end user performs the enrollment and then the authentication, whereas the authenticator application and Vault participate as secondary actors. It is worth noting that the authenticator application and Vault never communicate with each other. They are like two correspondents who agreed on a secret at their only meeting and who, from that day on, prove their acquaintance merely by consulting their watches.</p><h3>4. Vault configuration</h3><p>The Vault configuration consists of three files located in the vault/config directory, which is mounted read-only in the containers.</p><p>4.1 The server configuration in vault.hcl</p><pre>storage &quot;file&quot; {<br>  path = &quot;/vault/file&quot;<br>}<br>listener &quot;tcp&quot; {<br>  address     = &quot;0.0.0.0:8200&quot;<br>  tls_disable = 1<br>}<br>api_addr      = &quot;http://0.0.0.0:8200&quot;<br>disable_mlock = true<br>ui            = true</pre><p>The storage stanza selects the file storage backend, which persists the encrypted data of Vault in the /vault/file directory. This directory is backed by the Docker volume vault-file, so that the registered TOTP keys survive the restarts of the container. This choice is deliberate. Vault also offers a development mode, as does the Quarkus Dev Services mechanism, but both are kept entirely in memory and forget everything when stopped. Such amnesia is acceptable in a test but rather inconvenient for a user who has just scanned a QR code and who would discover at the next restart that the application has no recollection of the enrollment.</p><p>The listener stanza opens a TCP listener on all network interfaces on port 8200. The tls_disable directive switches off TLS, which simplifies local development and which would bean unforgivable sin in any other context.</p><p>The api_addr parameter defines the address advertised by the server to its clients, in particular for request forwarding in a cluster. With a single node its role is modest.</p><p>The disable_mlock parameter prevents Vault from calling the mlock system call, whose purpose is to forbid the operating system to swap memory pages containing secrets to disk. Since containers generally lack the IPC_LOCK capability, this protection is disabled here. In a production deployment it should be kept enabled and the capability should be granted.</p><p>Finally, ui = true activates the web interface, available at http://localhost:8200/ui, which is convenient for inspecting the state of the server.</p><h4>4.2 The access policy in totp-policy.hcl</h4><pre>path &quot;totp/*&quot; {<br>  capabilities = [&quot;create&quot;, &quot;read&quot;, &quot;update&quot;, &quot;delete&quot;, &quot;list&quot;]<br>}</pre><p>Vault applies a deny by default model. A token can perform only the operations explicitly granted by the policies attached to it. The totp-policy policy grants the application the capabilities create, read, update, delete and list on every path below totp/, and nothing else. The application can therefore create keys (totp/keys/&lt;name&gt;), generate codes and validate them (totp/code/&lt;name&gt;), but it can neither read the key/value secrets of other teams nor alter the configuration of Vault. This is a direct application of the principle of least privilege. A more restrictive policy is conceivable, for example by removing delete and list if the application never needs them, and the reader is invited to apply such pruning in a real deployment.</p><h4>4.3 The bootstrap script init.sh</h4><p>The script is executed by the one-shot container vault-init. Its main property is idempotence, in other words it can be executed any number of times and always leads to the same final state. It proceeds in six stages.</p><p>Waiting for the server.</p><pre>until vault status 2&gt;&amp;1 | grep -qE &#39;Initialized|Sealed&#39;; do<br>  sleep 1<br>done</pre><p>The depends_on clause of Docker Compose only guarantees that the vault container has been started, not that the Vault process is ready to answer. The script therefore polls the vault status command until its output contains the expected fields. One may observe that the command returns a non-zero exit code when Vault is sealed, which is why the script examines the output rather than the exit code.</p><p><strong>Initialization.</strong></p><pre>if [ ! -s /init/init.json ]; then<br>  vault operator init -key-shares=1 -key-threshold=1 \ <br>    -format=json &gt; /init/init.json<br>fi</pre><p>The initialization creates the master encryption key, splits it into key shares and produces the initial root token. It is performed only once, when the file /init/init.json does not exist or is empty. In production, the master key is typically divided into five shares with a threshold of three, entrusted to different persons who are expected never to travel on the same aircraft. Here, one share and a threshold of one are sufficient, and the result is stored in clear in the vault-init volume. The script comment explicitly warns that this arrangement is acceptable only for local development.</p><p><strong>Unsealing.</strong></p><pre>UNSEAL_KEY=$(jq -r &#39;.unseal_keys_b64[0]&#39; /init/init.json)<br>ROOT_TOKEN=$(jq -r &#39;.root_token&#39; /init/init.json)<br>if vault status -format=json | jq -e &#39;.sealed == true&#39; &gt;/dev/null<br>then<br>  vault operator unseal &quot;$UNSEAL_KEY&quot; &gt;/dev/null<br>fi</pre><p>With the file storage, Vault is sealed again after each restart. The script extracts the unseal key and the root token with `jq`, which is installed on the fly by the container entry poit,and unseals the server only if it is actually sealed.</p><p><strong>Enabling the TOTP engine.</strong></p><pre>export VAULT_TOKEN=&quot;$ROOT_TOKEN&quot;<br>if ! vault secrets list -format=json | jq -e &#39;has(&quot;totp/&quot;)&#39; &gt;/dev/null; then<br>  vault secrets enable totp<br>fi</pre><p>Authenticated with the root token, the script mounts the TOTP secrets engine at its default path totp/, unless it is already mounted.</p><p><strong>Writing the policy.</strong></p><pre>vault policy write totp-policy /vault/config/totp-policy.hcl</pre><p>This command is naturally idempotent, since writing an identical policy twice leaves it unchanged, and it also guarantees that any modification of the HCL file is taken into account at the next start.</p><p><strong>Creating the application token.</strong></p><pre>if ! vault token lookup dev-app-token &gt;/dev/null 2&gt;&amp;1<br>then<br>  vault token create -id=&quot;dev-app-token&quot; -policy=&quot;totp-policy&quot; \<br>    -orphan -no-default-policy -period=&quot;8760h&quot; \<br>    -display-name=&quot;vault-auth&quot; &gt;/dev/null<br>fi</pre><p>This last stage deserves a closer look, since each option carries a precise meaning:</p><ol><li>-id=”dev-app-token” imposes a known token value, so that the application can be configured statically, which is convenient for development and strongly discouraged elsewhere;</li><li>-policy=”totp-policy” attaches the least-privilege policy described above;</li><li>-no-default-policy removes the default policy, which would otherwise grant a few additional capabilities, such as looking up the token itself;</li><li>-orphan detaches the token from its parent, the root token, so that a revocation of the latter does not revoke the application token in cascade;</li><li>-period=”8760h” makes the token periodic, which means that it has no maximum lifetime and remains valid as long as it is renewed at least once a year;</li><li>-display-name=”vault-auth” gives the token a readable name in the audit logs.</li></ol><p>The application thus receives a token that can do exactly what it needs and nothing more, which is the ideal relationship between a software component and its privileges, and which is, regrettably, far less frequent in practice than in textbooks.</p><h3>5. The application code</h3><p>The vault-auth module is a Quarkus 3.37 application built with Quarkus REST and the Quarkiverse quarkus-vault extension. Its configuration, in application.properties, is minimal, as shown below.</p><pre>quarkus.vault.devservices.enabled=false<br>quarkus.vault.url=http://localhost:8200<br>quarkus.vault.authentication.client-token=dev-app-token</pre><p>The Dev Services are disabled for the reason given in section 4.1. The URL and the token designate the Vault server started by Docker Compose and are overridden by the environment variables QUARKUS_VAULT_URL and QUARKUS_VAULT_AUTHENTICATION_CLIENT_TOKEN when the application runs in its own container.</p><h4>5.1 The service TotpService</h4><pre>@ApplicationScoped<br>public class TotpService<br>{<br>  private VaultTOTPSecretEngine vaultTOTPSecretEngine;<br>  public TotpService(VaultTOTPSecretEngine vaultTOTPSecretEngine)<br>  {<br>    this.vaultTOTPSecretEngine = vaultTOTPSecretEngine;<br>  }<br>  public Optional&lt;KeyDefinition&gt; getTotpKeyDefinition(String username)<br>  {<br>    CreateKeyParameters params = <br>     new CreateKeyParameters(&quot;totp-test&quot;, username);<br>    params.setExported(true);<br>    return vaultTOTPSecretEngine.createKey(username, params);<br>  }<br>  public boolean validateCode(String username, String code)<br>  {<br>    return vaultTOTPSecretEngine.validateCode(username, code);<br>  }<br>}</pre><p>The class is an application scoped CDI bean, which means that a single instance is shared by all requests. Its only dependency, VaultTOTPSecretEngine, is supplied by the quarkus-vaultextension and is injected through the constructor, which makes the dependency explicit and the class easy to instantiate in isolation.</p><p>The method getTotpKeyDefinition() creates a TOTP key in Vault. The two-rgument constructor of CreateKeyParameters sets the issuer (totp-test), which the authenticator application displays as the name of the service, and the account name, here the user name. This constructor also sets the generate flag to true, which places Vault in its generator role. Vault therefore creates the seed itself instead of expecting one from the caller. The call to setExported(true) asks Vault to return the provisioning material, namely the otpauth:// URL and the QR code as a Base64 encoded PNG image. The key is stored under the path totp/keys/&lt;username&gt;, so that each user owns a distinct key, and a new registration under the same name replaces the previous key.</p><p>The period, the algorithm and the number of digits are deliberately left to their default values, namely 30 seconds, SHA1 and 6 digits. This apparent lack of ambition is the result of experience. During the development of the project, the period was initially set to one minute. The QR code correctly announced a period of 60 seconds, the authenticator application accepted it without any objection, and every single code was then rejected. The explanation is that Google Authenticator ignores the period, algorithm and digits parameters of the URI and always uses the standard values. The application thus faithfully produced codes for a clock that ticked twice as often as the one of Vault. The comment in the source code preserves this lesson for posterity, and the author recommends it to any reader tempted by originality in this domain.</p><p>The method validateCode() delegates the verification to Vault, which recomputes the expected code for the current time step and its neighbors and compares it with the submitted one. Vault also records the codes already used and rejects a second submission of the same code within its validity window, which protects the application against replay attacks at no cost. The method returns a simple boolean, and the application never manipulates the seed.</p><h4>5.2 The resource TotpApi</h4><pre>@Path(&quot;/totp&quot;)<br>public class TotpApi<br>{<br>  @Inject<br>  TotpService totpService;<br>  <br>  @GET<br>  public Response testTotp(@HeaderParam(&quot;X-User&quot;) String username,<br>    @HeaderParam(&quot;X-TOTP-Code&quot;) String code)<br>  {<br>    return totpService.validateCode(username, code) ? <br>      Response.ok(&quot;Access granted&quot;).build() :<br>      Response.status(Response.Status.UNAUTHORIZED)<br>       .entity(&quot;Invalid TOTP code&quot;).build();<br>  }<br><br>  @GET<br>  @Path(&quot;/register/{username}&quot;)<br>  @Produces(MediaType.TEXT_HTML)<br>  public String register(@PathParam(&quot;username&quot;) String username)<br>  {<br>    return totpService.getTotpKeyDefinition(username)<br>      .map(key -&gt; &quot;&quot;&quot;<br>        &lt;!DOCTYPE html&gt;<br>        &lt;html&gt;<br>            &lt;head&gt;&lt;title&gt;Scan QR Code&lt;/title&gt;&lt;/head&gt;<br>            &lt;body&gt;<br>                &lt;h2&gt;Scan this QR code with Google Authenticator&lt;/h2&gt;<br>                &lt;img src=&quot;data:image/png;base64,%s&quot; alt=&quot;TOTP QR Code&quot;/&gt;<br>            &lt;/body&gt;<br>        &lt;/html&gt;<br>        &quot;&quot;&quot;.formatted(key.getBarcode()))<br>      .orElse(&quot;Failed to generate TOTP key&quot;);<br>  }<br>}</pre><p>The class is a Jakarta REST resource bound to the path /totp and exposes two endpoints.</p><p>The endpoint GET /totp/register/{username} performs the enrollment. It obtains the key definition from the service and, if it is present, inserts the Base64 encoded image returned by getBarcode() into a small HTML page by means of a Java text block and the formatted()method. The image is embedded as a data: URI, so that the browser can display it without any additional request. If the key definition is absent, a short failure message is returned.</p><p>The endpoint GET /totp performs the authentication. The user name and the code are read from the custom headers X-User and X-TOTP-Code. A valid code produces the status 200 and the body Access granted, whereas an invalid one produces the status 401 and the body Invalid TOTP code.</p><p>The reader should keep in mind that this resource is a demonstration and not an authentication service ready for production. The registration endpoint is not protected, so that anybody who knows a user name may replace the key of that user, and the absence of a header is not handled specifically. In a real system, enrollment would occur only after a first authentication, for example by password, and the successful validation of the code would lead to the issuance of a session or of a token, typically through the Quarkus OIDC or JWT extensions. These additions are left as an exercise, according to the venerable academic tradition which consists in calling “exercise” what the author did not have the time to write.</p><h4>5.3 The integration tests</h4><p>The tests are integration tests executed against a real Vault server rather than unit tests based on mocks. Two classes are involved. VaultTestResource implements the QuarkusTestResourceLifecycleManager interface, which allows Quarkus to start an external resource before the application and to stop it afterwards.</p><pre>@Override<br>public Map&lt;String, String&gt; start()<br>{<br>  vault = new VaultContainer&lt;&gt;(IMAGE)<br>    .withVaultToken(ROOT_TOKEN)<br>    .withInitCommand(&quot;secrets enable totp&quot;);<br>  vault.start();<br>  return Map.of(<br>    &quot;quarkus.vault.devservices.enabled&quot;, &quot;false&quot;,<br>    &quot;quarkus.vault.url&quot;, vault.getHttpHostAddress(),<br>    &quot;quarkus.vault.authentication.client-token&quot;, ROOT_TOKEN);<br>}</pre><p>The method starts a Testcontainers VaultContainer based on the image hashicorp/vault:1.18, which is the same version as in Docker Compose. The method asCompatibleSubstituteFor(”vault”) informs Testcontainers that the official HashiCorp image may be used in place of the historical vault image it expects. The container runs in Vault development mode with the root token root, and the init command mounts the TOTP engine. The returned map overrides the application configuration, so that the application under test connects to this ephemeral server on its randomly mapped port instead of the persistent one. Here, the ephemeral nature that was a defect in section 4.1 becomes a virtue, since each test run starts from a perfectly clean state.</p><p>TotpApiTest is annotated with @QuarkusTest, which starts the complete application, and with @WithTestResource(VaultTestResource.class), which attaches the resource described above. It contains three test cases written with REST Assured:</p><ol><li>registerReturnsQrCode() is a positive test which calls /totp/register/alice and verifies that the response has the status 200 and contains an embedded PNG image;</li><li>validCodeGrantsAccess() is a positive test which registers bob, then asks Vault itself to generate the current code by means of generateCode(”bob”), and verifies that submitting this code yields the status 200 and the message Access granted;</li><li>invalidCodeIsRejected() is a negative test which registers carol, submits the code 000000 and verifies the status 401 and the message Invalid TOTP code.</li></ol><p>The second test is particularly instructive. Since no smartphone could reasonably be attached to the build server, the test injects VaultTOTPSecretEngine and lets Vault play the role of the authenticator application. This is possible because the key was created in generator mode, in which Vault is able to compute the current code for its own keys. The third test relies on the fact that 000000 is a valid code with a probability of one in a million for any given time step. Should this test ever fail, the author recommends not correcting it but rather buying a lottery ticket on the same day.</p><p>The tests are executed by mvn -pl vault-auth -am test on any workstation with a running Docker daemon, and by the CircleCI pipeline, which uses a machine executor precisely so that Testcontainers has access to a Docker engine.</p><h3>6. Deployment</h3><p>The file docker-compose.yml defines three services, two named volumes and one bind mount. The following diagram represents this topology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/0*EWXWHF36kL_ghWZa.png" /></figure><p>The service vault runs the Vault server with the configuration of section 4.1. It publishes port 8200 on the host, stores its encrypted data in the volume vault-file and is restarted automatically unless it is explicitly stopped.</p><p>The service vault-init uses the same image, runs as root in order to be able to install jqand to write in its volume, executes the script init.sh and then terminates. Its restart policy is no, which is the expected behaviour of a one-shot task. Its volume vault-init keeps the file init.json between executions, which is what makes the automatic unsealing possible after a restart.</p><p>The service vault-auth runs the Quarkus application, whose image is produced by the Quarkus container image extension during the Maven build. The pull_policy: never clause indicates that the image must exist locally and must not be searched for in a registry. The application starts only once vault-init has completed successfully, which guarantees that Vault is unsealed, that the TOTP engine is mounted and that the token dev-app-token exists at the moment of the first request. Inside the Compose network, the application reaches Vault by its service name, vault, through the environment variable QUARKUS_VAULT_URL.</p><p>The whole stack is started by the following commands.</p><pre>mvn -pl vault-auth -am package -Dquarkus.container-image.build<br>docker compose up -d</pre><p>After that, the user opens http://localhost:8080/totp/register/&lt;username&gt;, scans the QR code and checks a code with</p><pre>curl -H &quot;X-User: &lt;username&gt;&quot; -H &quot;X-TOTP-Code: &lt;code&gt;&quot; \<br>  http://localhost:8080/totp</pre><p>The command docker compose down -v removes the volumes and returns the system to its original state of blissful ignorance.</p><h3>7. Conclusion</h3><p>This project shows that the implementation of a second authentication factor based on TOTP requires remarkably little application code once the cryptographic responsibilities are delegated to Vault. The Quarkus application contains two short classes and never stores a seed. Vault generates the keys, produces the QR codes, validates the codes and prevents their reuse, while the policy and the periodic orphan token restrict the application to the strict minimum. The integration tests, executed against a real Vault container, give a high degree of confidence in this collaboration without resorting to mocks.</p><p>The simplifications adopted for local development, namely the single unseal share stored in clear, the disabled TLS, the fixed token value and the unprotected registration endpoint, must of course be removed before any production use. With this reservation, the approach offers a sound basis on which an authentication service may be built, and the author hopes that the reader, having reached this conclusion without falling asleep, will consider this a valid proof of presence, comparable in rigour to a six digit code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ec746b18f0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DEVOPS: Handling X509 certificates and related keys with OpenSSL]]></title>
            <link>https://medium.com/@nicolasduminil/devops-handling-x509-certificates-and-related-keys-with-openssl-f8c16c53083a?source=rss-dbb8e0d51f2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8c16c53083a</guid>
            <dc:creator><![CDATA[Nicolas Duminil]]></dc:creator>
            <pubDate>Fri, 10 Dec 2021 18:24:03 GMT</pubDate>
            <atom:updated>2021-12-10T18:24:03.499Z</atom:updated>
            <content:encoded><![CDATA[<p>In order to expose HTTPS services one needs to provide an X509 certificate signed by a <em>certificate authority </em>(CA). Several trusted CAs are globally available and their public keys are by default configured in browsers. Hence, when the browser talks to linkedin.com, for example, it can check whether the LinkedIn’s certificate isn’t forged by verifying its signature against the associated CA’s configured public key. This way, the browser makes sure it communicates with the right service.</p><p>The operations required to create, store and convert X509 keys and certificates are not only quite complex but also repetitive, hence this memento of how to do it.</p><p>OpenSSL is a commercial toolkit and cryptographic library for TLS (<em>Transport Layer Security</em>) available for multiple platforms. It comes by default with Linux distributions and, if needed, it can be downloaded from <a href="http://www.openssl.org/">here</a>. But the most practical way to use OpenSSL if you’re not on a Linux platform or if you don’t find the right release for your platform, is to use a Docker image like the one found <a href="https://github.com/alpine-docker/openssl">here</a>. Then, just follow the usage instructions.</p><p>Here we’re focusing on Java micro-services and, consequently, we need to finish up with a Java KeyStore (JKS).</p><p>In any case, whether you’re using a Docker image based OpenSSL or your local on-premise one, the steps you need to perform are as follows:</p><ol><li>Create the CA’s private key</li><li>Create the CA’s public key</li><li>Create the application’s private key</li><li>Create a CSR (<em>Certificate Signing Request</em>) for the application</li><li>Create the application’s CA signed certificate</li><li>Create a Java KeyStore with the application’s public/private keys</li></ol><h4>Create the CA’s private key</h4><p>The following command generates a file containing a private key:</p><pre># openssl genrsa -aes256 -passout pass:”password1&quot; \<br>-out ~/.ssh/keys/ca_key.pem 4096</pre><p>Here we are creating the file ca_key.pem, in the .ssh directory of the current user, using a sub-directory named keys, as specified by the -out argument. The verb genrsa is used in order to generate an RSA private key of 4096 bits and encrypted with the AES-256 algorithm. The argument -passout provides the passphrase which need to be prefixed with the string pass: and must be defined within double quotes.</p><h4>Create the CA’s public key</h4><p>The following command generates a file containing a public key:</p><pre># openssl req -new -passin pass:&quot;password1&quot; \<br>-key ~/.ssh/keys/ca_key.pem -x509 -days 365 \<br>-out ~/.ssh/keys/ca_cert.pem -subj &quot;CN=dev.simplex-software.fr&quot;</pre><p>The req -new verb here above generates a public key that points to the already generated private key, as specified by the -key argument. The expiration time is set at 365 days. In order to generate the public key, OpenSSL needs to know some details related to your organization, for example country, state, company name, etc. Of those details, only the common name (CN) matters, accordingly you need to provide a meaningful one. When a client talks to an HTTPS service, it checks whether the service’s hostname matches the value given to the CN argument in the certificate. If this value doesn’t match, the certificate is rejected. Hence the importance to set it with the -subj argument, as shown above. Last but not least, the -out argument specifies where to store the generated public key.</p><h4>Create the application’s private key</h4><p>Here the application is considered as being a Java micro-service, either stand-alone or deployed on a web or application server. To generate a private key for the application execute the following command:</p><pre># openssl genrsa -aes256 -passout pass:&quot;password1&quot; \<br>-out ~/.ssh/keys/my_key.pem 4096</pre><p>The command above creates a file named my_key.pem containing a private key. The command’s argument have been explained previously.</p><h4>Create a CSR for the application</h4><p>Once we have a private key for the application, we need to create a CSR such that to get this private key signed by the CA. Here is how:</p><pre># openssl req -new -passin pass:&quot;password1&quot; -new \<br>-key ~/.ssh/keys/my_key.pem -out ~/.ssh/keys/csr \<br>-subj &quot;/CN=dev.simplex-software.fr&quot;</pre><p>This command will generate the CSR as a file named csr in the same .ssh/keys directory of the current user.</p><h4>Create the application’s CA signed certificate</h4><p>The following listing gets the previously generated CSR signed by the CA:</p><pre># openssl x509 -req -passin pass:&quot;password1&quot; -days 365 \<br>-in ~/.ssh/keys/csr -CA ~/.ssh/keys/ca_cert.pem \<br>-CAkey ~/.ssh/keys/ca_key.pem \<br>-out ~/.ssh/keys/my_cert.pem -set_serial 01</pre><p>Upon the execution of this command, we get the file my_cert.pem containing an X509 certificate signed by the CA. For Java applications, we need to have both the private key and this signed certificate in a Java KeyStore (JKS), which is a specific Java key storage.</p><h4>Create a Java KeyStore with the application’s public/private keys</h4><p>The following listing shows how to generate a JKS containing a private key and a signed X509 certificate.</p><pre># openssl rsa -passin pass:&quot;password1&quot; \<br>-in ~/.ssh/keys/my_key.pem -out ~/.ssh/keys/my_key.pem<br># cat ~/.ssh/keys/my_key.pem ~/.ssh/keys/my_cert.pem \<br>&gt;&gt; ~/.ssh/keys/my_keys.pem<br># openssl pkcs12 -export -passout pass:&quot;password1&quot; \<br>-in ~/.ssh/keys/my_keys.pem -out ~/.ssh/keys/my_keys.p12<br># keytool -importkeystore -srcstorepass password1 \<br>-srckeystore ~/.ssh/keys/my_keys.p12 \<br>-srcstoretype pkcs12 -deststorepass password1 \<br>-destkeystore ~/.ssh/keys/my_keys.jks -deststoretype JKS</pre><p>The first command in the listing above removes the passphrase of the private key (my_key.pem). The 2nd command creates a file (my_keys.pem) which contains the concatenation of the private key (my_key.pem) and the public signed certificate (my_cert.pem). The 3rd command creates a keystore (my_keys.p12) of the type PKCS containing these keys. Finally, in the last command, we use the keytool utility to create a JKS file from the keystore my_keys.p12. Here we have to pass the passphrase of the source keystore (my_keys.p12) under the argument -srcstorepass and the passphrase of the destination (my_keys.jks) under the argument -deststorepass. For the simplicity sake, we use here the same passphrase for the two keystores, which isn’t recommended, so don’t do that at home.</p><p>Now we have created our JKS and all that remains to do is to configure your HTTPS service (standalone, web or application server) such that to use keys and certificates stored in it. How yo do that depends on your specific architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8c16c53083a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>