<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://www.simplex-software.fr/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.simplex-software.fr/" rel="alternate" type="text/html" /><updated>2026-11-10T17:32:31+00:00</updated><id>https://www.simplex-software.fr/feed.xml</id><title type="html">Simplex Software</title><subtitle>Senior Silver Software Architect</subtitle><author><name>Nicolas DUMINIL</name></author><entry><title type="html">Spring AI or LangChain4j? One App, Three Stacks, One Test</title><link href="https://www.simplex-software.fr/posts-archive/java-ai/" rel="alternate" type="text/html" title="Spring AI or LangChain4j? One App, Three Stacks, One Test" /><published>2026-11-10T00:00:00+00:00</published><updated>2026-11-10T00:00:00+00:00</updated><id>https://www.simplex-software.fr/posts-archive/java-ai</id><content type="html" xml:base="https://www.simplex-software.fr/posts-archive/java-ai/"><![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>

<h2 id="one-interface-three-implementations">One interface, three implementations</h2>

<p>Everything starts from one framework-neutral contract, a plain Java interface
that knows nothing about any AI library:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">interface</span> <span class="nc">QuestionAnsweringService</span> <span class="o">{</span>
  <span class="nc">Answer</span> <span class="nf">askQuestion</span><span class="o">(</span><span class="nc">Question</span> <span class="n">question</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">Question</code> and <code class="language-plaintext highlighter-rouge">Answer</code> 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>

<h2 id="spring-ai-a-fluent-chatclient">Spring AI: a fluent ChatClient</h2>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Service</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">SpringAiQuestionAnsweringService</span> <span class="kd">implements</span> <span class="nc">QuestionAnsweringService</span> <span class="o">{</span>

  <span class="kd">private</span> <span class="kd">final</span> <span class="nc">ChatClient</span> <span class="n">chatClient</span><span class="o">;</span>

  <span class="kd">public</span> <span class="nf">SpringAiQuestionAnsweringService</span><span class="o">(</span><span class="nc">ChatClient</span><span class="o">.</span><span class="na">Builder</span> <span class="n">chatClientBuilder</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">this</span><span class="o">.</span><span class="na">chatClient</span> <span class="o">=</span> <span class="n">chatClientBuilder</span><span class="o">.</span><span class="na">build</span><span class="o">();</span>
  <span class="o">}</span>

  <span class="nd">@Override</span>
  <span class="kd">public</span> <span class="nc">Answer</span> <span class="nf">askQuestion</span><span class="o">(</span><span class="nc">Question</span> <span class="n">question</span><span class="o">)</span> <span class="o">{</span>
    <span class="kt">var</span> <span class="n">answerText</span> <span class="o">=</span> <span class="n">chatClient</span><span class="o">.</span><span class="na">prompt</span><span class="o">()</span>
      <span class="o">.</span><span class="na">user</span><span class="o">(</span><span class="n">question</span><span class="o">.</span><span class="na">question</span><span class="o">())</span>
      <span class="o">.</span><span class="na">call</span><span class="o">()</span>
      <span class="o">.</span><span class="na">content</span><span class="o">();</span>
    <span class="k">return</span> <span class="k">new</span> <span class="nf">Answer</span><span class="o">(</span><span class="n">answerText</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Spring AI hands you a <code class="language-plaintext highlighter-rouge">ChatClient.Builder</code>, auto-configured from your properties,
and a fluent API: <code class="language-plaintext highlighter-rouge">prompt()</code>, <code class="language-plaintext highlighter-rouge">user()</code>, <code class="language-plaintext highlighter-rouge">call()</code>, <code class="language-plaintext highlighter-rouge">content()</code>. The model, its
base URL and its options are all configuration, not code.</p>

<h2 id="langchain4j-a-plain-chatmodel-and-the-same-code-on-two-runtimes">LangChain4j: a plain ChatModel, and the same code on two runtimes</h2>

<p>On Spring Boot:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Service</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">LangChain4jQuestionAnsweringService</span> <span class="kd">implements</span> <span class="nc">QuestionAnsweringService</span> <span class="o">{</span>

  <span class="kd">private</span> <span class="kd">final</span> <span class="nc">ChatModel</span> <span class="n">chatModel</span><span class="o">;</span>

  <span class="kd">public</span> <span class="nf">LangChain4jQuestionAnsweringService</span><span class="o">(</span><span class="nc">ChatModel</span> <span class="n">chatModel</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">this</span><span class="o">.</span><span class="na">chatModel</span> <span class="o">=</span> <span class="n">chatModel</span><span class="o">;</span>
  <span class="o">}</span>

  <span class="nd">@Override</span>
  <span class="kd">public</span> <span class="nc">Answer</span> <span class="nf">askQuestion</span><span class="o">(</span><span class="nc">Question</span> <span class="n">question</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">return</span> <span class="k">new</span> <span class="nf">Answer</span><span class="o">(</span><span class="n">chatModel</span><span class="o">.</span><span class="na">chat</span><span class="o">(</span><span class="n">question</span><span class="o">.</span><span class="na">question</span><span class="o">()));</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>LangChain4j hands you a <code class="language-plaintext highlighter-rouge">ChatModel</code> and a single method, <code class="language-plaintext highlighter-rouge">chat()</code>. There is no
builder to call: the model is injected ready to use.</p>

<p>Now the Quarkus version:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@ApplicationScoped</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">LangChain4jQuestionAnsweringService</span> <span class="kd">implements</span> <span class="nc">QuestionAnsweringService</span> <span class="o">{</span>

  <span class="kd">private</span> <span class="kd">final</span> <span class="nc">ChatModel</span> <span class="n">chatModel</span><span class="o">;</span>

  <span class="kd">public</span> <span class="nf">LangChain4jQuestionAnsweringService</span><span class="o">(</span><span class="nc">ChatModel</span> <span class="n">chatModel</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">this</span><span class="o">.</span><span class="na">chatModel</span> <span class="o">=</span> <span class="n">chatModel</span><span class="o">;</span>
  <span class="o">}</span>

  <span class="nd">@Override</span>
  <span class="kd">public</span> <span class="nc">Answer</span> <span class="nf">askQuestion</span><span class="o">(</span><span class="nc">Question</span> <span class="n">question</span><span class="o">)</span> <span class="o">{</span>
    <span class="k">return</span> <span class="k">new</span> <span class="nf">Answer</span><span class="o">(</span><span class="n">chatModel</span><span class="o">.</span><span class="na">chat</span><span class="o">(</span><span class="n">question</span><span class="o">.</span><span class="na">question</span><span class="o">()));</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Look closely. The body is identical to the Spring Boot version. The only
difference is the annotation: <code class="language-plaintext highlighter-rouge">@ApplicationScoped</code> (CDI) instead of <code class="language-plaintext highlighter-rouge">@Service</code>
(Spring). Same library, same <code class="language-plaintext highlighter-rouge">ChatModel</code>, same <code class="language-plaintext highlighter-rouge">chat()</code> 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>

<h2 id="one-test-to-compare-them-all">One test to compare them all</h2>

<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>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">AbstractQuestionAnsweringIT</span> <span class="o">{</span>

  <span class="kd">protected</span> <span class="kd">abstract</span> <span class="no">URI</span> <span class="nf">baseUri</span><span class="o">();</span>

  <span class="nd">@Test</span>
  <span class="nd">@DisplayName</span><span class="o">(</span><span class="s">"answers a factual question"</span><span class="o">)</span>
  <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">answersAFactualQuestion</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">ask</span><span class="o">()</span>
      <span class="o">.</span><span class="na">body</span><span class="o">(</span><span class="k">new</span> <span class="nc">Question</span><span class="o">(</span><span class="s">"What is the capital of France? Answer with the city name only."</span><span class="o">))</span>
      <span class="o">.</span><span class="na">when</span><span class="o">()</span>
      <span class="o">.</span><span class="na">post</span><span class="o">(</span><span class="s">"/ask"</span><span class="o">)</span>
      <span class="o">.</span><span class="na">then</span><span class="o">()</span>
      <span class="o">.</span><span class="na">statusCode</span><span class="o">(</span><span class="mi">200</span><span class="o">)</span>
      <span class="o">.</span><span class="na">body</span><span class="o">(</span><span class="s">"answer"</span><span class="o">,</span> <span class="n">not</span><span class="o">(</span><span class="n">blankOrNullString</span><span class="o">()))</span>
      <span class="o">.</span><span class="na">body</span><span class="o">(</span><span class="s">"answer"</span><span class="o">,</span> <span class="n">containsStringIgnoringCase</span><span class="o">(</span><span class="s">"paris"</span><span class="o">));</span>
  <span class="o">}</span>

  <span class="c1">// ... plus: rejects a blank question (400), rejects a malformed payload (400)</span>

  <span class="kd">private</span> <span class="nc">RequestSpecification</span> <span class="nf">ask</span><span class="o">()</span> <span class="o">{</span>
    <span class="k">return</span> <span class="nf">given</span><span class="o">().</span><span class="na">baseUri</span><span class="o">(</span><span class="n">baseUri</span><span class="o">().</span><span class="na">toString</span><span class="o">()).</span><span class="na">contentType</span><span class="o">(</span><span class="nc">ContentType</span><span class="o">.</span><span class="na">JSON</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<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>

<h2 id="what-the-comparison-reveals">What the comparison reveals</h2>

<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>

<table>
  <thead>
    <tr>
      <th> </th>
      <th style="text-align: center">Spring AI</th>
      <th style="text-align: center">LangChain4j / Boot</th>
      <th style="text-align: center">LangChain4j / Quarkus</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Production Java (LOC)</td>
      <td style="text-align: center">48</td>
      <td style="text-align: center">47</td>
      <td style="text-align: center">39</td>
    </tr>
    <tr>
      <td>Files in <code class="language-plaintext highlighter-rouge">src/main/java</code></td>
      <td style="text-align: center">3</td>
      <td style="text-align: center">3</td>
      <td style="text-align: center">2</td>
    </tr>
    <tr>
      <td>Resolved runtime jars</td>
      <td style="text-align: center">106</td>
      <td style="text-align: center">49</td>
      <td style="text-align: center">142</td>
    </tr>
    <tr>
      <td>Startup, JVM mode</td>
      <td style="text-align: center">1.74 s</td>
      <td style="text-align: center">2.69 s</td>
      <td style="text-align: center">0.66 s</td>
    </tr>
  </tbody>
</table>

<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 <code class="language-plaintext highlighter-rouge">ChatClient</code>, and configuration
drives the model.</li>
  <li>LangChain4j leads with a single <code class="language-plaintext highlighter-rouge">ChatModel.chat()</code> 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>

<h2 id="where-this-goes-next">Where this goes next</h2>

<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>

<p><a href="https://www.amazon.com/dp/B0HR1T5S4B"><img src="/assets/images/books/java-ai-frameworks.jpg" alt="Java AI Frameworks" width="160" /></a></p>]]></content><author><name>nicolas-duminil</name></author><category term="AI" /><category term="LangChain4j" /><category term="Spring" /><category term="Java" /><summary type="html"><![CDATA[The same small AI service in Spring AI, LangChain4j on Spring Boot and on Quarkus, held to one shared test. Where they differ, and where they do not.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://www.simplex-software.fr/three-stacks.jpg" /><media:content medium="image" url="https://www.simplex-software.fr/three-stacks.jpg" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Time-Based One-Time Passwords with HashiCorp Vault and Quarkus</title><link href="https://www.simplex-software.fr/posts-archive/totp/" rel="alternate" type="text/html" title="Time-Based One-Time Passwords with HashiCorp Vault and Quarkus" /><published>2026-10-28T00:00:00+00:00</published><updated>2026-10-28T00:00:00+00:00</updated><id>https://www.simplex-software.fr/posts-archive/totp</id><content type="html" xml:base="https://www.simplex-software.fr/posts-archive/totp/"><![CDATA[<h2 id="abstract">Abstract</h2>

<p>This article examines how the Time-Based One-Time Password algorithm (TOTP) can be delegated to the
TOTP 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. Readers who expect a tedious enumeration of
configuration keys will be partly disappointed, since the author has permitted the
occasional remark intended to keep both writer and reader awake.</p>

<h2 id="1-what-is-totp-and-what-problem-does-it-solve">1. What is TOTP and what problem does it solve?</h2>

<h3 id="11-the-weakness-of-the-static-password">1.1 The weakness of the static password</h3>

<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>

<h3 id="12-multi-factor-authentication">1.2 Multi-factor authentication</h3>

<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 enrolment, 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 enrolment.</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 memorised, let alone copied under a doormat.</p>

<h3 id="13-the-algorithm">1.3 The algorithm</h3>

<p>TOTP is specified by RFC 6238 and is a direct extension of the HMAC-Based One-Time Password
algorithm (HOTP) defined in RFC 4226. HOTP computes a short numeric code from a shared secret
<code class="language-plaintext highlighter-rouge">K</code> and a counter <code class="language-plaintext highlighter-rouge">C</code> according to the following steps:</p>

<ol>
  <li>compute <code class="language-plaintext highlighter-rouge">HMAC-SHA1(K, C)</code>, which yields a 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 <code class="language-plaintext highlighter-rouge">10^d</code>, where <code class="language-plaintext highlighter-rouge">d</code> is the number of digits, usually 6.</li>
</ol>

<p>The difficulty of HOTP lies in the synchronisation 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>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>T = floor((CurrentUnixTime - T0) / X)
</code></pre></div></div>

<p>where <code class="language-plaintext highlighter-rouge">T0</code> is the origin of time (usually the Unix epoch) and <code class="language-plaintext highlighter-rouge">X</code> is the time step, 30 seconds
by default. The one-time password is then simply <code class="language-plaintext highlighter-rouge">HOTP(K, T)</code>.</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 enrolment time, usually through a QR code encoding an
<code class="language-plaintext highlighter-rouge">otpauth://</code> 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>

<h2 id="2-what-is-hashicorp-vault-and-what-is-it-used-for">2. What is HashiCorp Vault and what is it used for?</h2>

<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 authorised by policies expressed in the HashiCorp Configuration
Language (HCL), and may be recorded by an audit device.</p>

<p>Vault organises 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 enrolment, 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>

<h2 id="3-use-cases">3. Use cases</h2>

<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>

<p><img src="/assets/images//use-case.png" alt="Use case diagram of the vault-auth application" /></p>

<p><em>The PlantUML source of this diagram is available in <code class="language-plaintext highlighter-rouge">diagrams/use-case.puml</code>.</em></p>

<p>The operator intervenes only once, by starting the stack, after which the bootstrap is fully
automated. The end user performs the enrolment 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>

<h2 id="4-vault-configuration">4. Vault configuration</h2>

<p>The Vault configuration consists of three files located in the <code class="language-plaintext highlighter-rouge">vault/config</code> directory, which
is mounted read-only in the containers.</p>

<h3 id="41-the-server-configuration-in-vaulthcl">4.1 The server configuration in <code class="language-plaintext highlighter-rouge">vault.hcl</code></h3>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">storage</span> <span class="s2">"file"</span> <span class="p">{</span>
  <span class="nx">path</span> <span class="p">=</span> <span class="s2">"/vault/file"</span>
<span class="p">}</span>

<span class="nx">listener</span> <span class="s2">"tcp"</span> <span class="p">{</span>
  <span class="nx">address</span>     <span class="p">=</span> <span class="s2">"0.0.0.0:8200"</span>
  <span class="nx">tls_disable</span> <span class="p">=</span> <span class="mi">1</span>
<span class="p">}</span>

<span class="nx">api_addr</span>      <span class="err">=</span> <span class="s2">"http://0.0.0.0:8200"</span>
<span class="nx">disable_mlock</span> <span class="err">=</span> <span class="kc">true</span>
<span class="nx">ui</span>            <span class="err">=</span> <span class="kc">true</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">storage</code> stanza selects the file storage backend, which persists the encrypted data of
Vault in the <code class="language-plaintext highlighter-rouge">/vault/file</code> directory. This directory is backed by the Docker volume
<code class="language-plaintext highlighter-rouge">vault-file</code>, 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 enrolment.</p>

<p>The <code class="language-plaintext highlighter-rouge">listener</code> stanza opens a TCP listener on all network interfaces on port 8200. The
<code class="language-plaintext highlighter-rouge">tls_disable</code> directive switches off TLS, which simplifies local development and which would be
an unforgivable sin in any other context.</p>

<p>The <code class="language-plaintext highlighter-rouge">api_addr</code> 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 <code class="language-plaintext highlighter-rouge">disable_mlock</code> parameter prevents Vault from calling the <code class="language-plaintext highlighter-rouge">mlock</code> system call, whose purpose
is to forbid the operating system to swap memory pages containing secrets to disk. Since
containers generally lack the <code class="language-plaintext highlighter-rouge">IPC_LOCK</code> capability, this protection is disabled here. In a
production deployment it should be kept enabled and the capability should be granted.</p>

<p>Finally, <code class="language-plaintext highlighter-rouge">ui = true</code> activates the web interface, available at <code class="language-plaintext highlighter-rouge">http://localhost:8200/ui</code>,
which is convenient for inspecting the state of the server.</p>

<h3 id="42-the-access-policy-in-totp-policyhcl">4.2 The access policy in <code class="language-plaintext highlighter-rouge">totp-policy.hcl</code></h3>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">path</span> <span class="s2">"totp/*"</span> <span class="p">{</span>
  <span class="nx">capabilities</span> <span class="p">=</span> <span class="p">[</span><span class="s2">"create"</span><span class="p">,</span> <span class="s2">"read"</span><span class="p">,</span> <span class="s2">"update"</span><span class="p">,</span> <span class="s2">"delete"</span><span class="p">,</span> <span class="s2">"list"</span><span class="p">]</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Vault applies a deny by default model. A token can perform only the operations explicitly
granted by the policies attached to it. The <code class="language-plaintext highlighter-rouge">totp-policy</code> policy grants the application the
capabilities <code class="language-plaintext highlighter-rouge">create</code>, <code class="language-plaintext highlighter-rouge">read</code>, <code class="language-plaintext highlighter-rouge">update</code>, <code class="language-plaintext highlighter-rouge">delete</code> and <code class="language-plaintext highlighter-rouge">list</code> on every path below <code class="language-plaintext highlighter-rouge">totp/</code>, and
nothing else. The application can therefore create keys (<code class="language-plaintext highlighter-rouge">totp/keys/&lt;name&gt;</code>), generate codes
and validate them (<code class="language-plaintext highlighter-rouge">totp/code/&lt;name&gt;</code>), 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 <code class="language-plaintext highlighter-rouge">delete</code> and
<code class="language-plaintext highlighter-rouge">list</code> if the application never needs them, and the reader is invited to apply such pruning in
a real deployment.</p>

<h3 id="43-the-bootstrap-script-initsh">4.3 The bootstrap script <code class="language-plaintext highlighter-rouge">init.sh</code></h3>

<p>The script is executed by the one-shot container <code class="language-plaintext highlighter-rouge">vault-init</code>. 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><strong>Waiting for the server.</strong></p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">until </span>vault status 2&gt;&amp;1 | <span class="nb">grep</span> <span class="nt">-qE</span> <span class="s1">'Initialized|Sealed'</span><span class="p">;</span> <span class="k">do
  </span><span class="nb">sleep </span>1
<span class="k">done</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">depends_on</code> clause of Docker Compose only guarantees that the <code class="language-plaintext highlighter-rouge">vault</code> container has been
started, not that the Vault process is ready to answer. The script therefore polls the
<code class="language-plaintext highlighter-rouge">vault status</code> 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>Initialisation.</strong></p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="o">[</span> <span class="o">!</span> <span class="nt">-s</span> /init/init.json <span class="o">]</span><span class="p">;</span> <span class="k">then
  </span>vault operator init <span class="nt">-key-shares</span><span class="o">=</span>1 <span class="nt">-key-threshold</span><span class="o">=</span>1 <span class="nt">-format</span><span class="o">=</span>json <span class="o">&gt;</span> /init/init.json
<span class="k">fi</span>
</code></pre></div></div>

<p>The initialisation creates the master encryption key, splits it into key shares and produces
the initial root token. It is performed only once, when the file <code class="language-plaintext highlighter-rouge">/init/init.json</code> 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 <code class="language-plaintext highlighter-rouge">vault-init</code> volume. The script comment explicitly warns that this arrangement
is acceptable only for local development.</p>

<p><strong>Unsealing.</strong></p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">UNSEAL_KEY</span><span class="o">=</span><span class="si">$(</span>jq <span class="nt">-r</span> <span class="s1">'.unseal_keys_b64[0]'</span> /init/init.json<span class="si">)</span>
<span class="nv">ROOT_TOKEN</span><span class="o">=</span><span class="si">$(</span>jq <span class="nt">-r</span> <span class="s1">'.root_token'</span> /init/init.json<span class="si">)</span>

<span class="k">if </span>vault status <span class="nt">-format</span><span class="o">=</span>json | jq <span class="nt">-e</span> <span class="s1">'.sealed == true'</span> <span class="o">&gt;</span>/dev/null<span class="p">;</span> <span class="k">then
  </span>vault operator unseal <span class="s2">"</span><span class="nv">$UNSEAL_KEY</span><span class="s2">"</span> <span class="o">&gt;</span>/dev/null
<span class="k">fi</span>
</code></pre></div></div>

<p>With the file storage, Vault is sealed again after each restart. The script extracts the unseal
key and the root token with <code class="language-plaintext highlighter-rouge">jq</code>, which is installed on the fly by the container entry point,
and unseals the server only if it is actually sealed.</p>

<p><strong>Enabling the TOTP engine.</strong></p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">export </span><span class="nv">VAULT_TOKEN</span><span class="o">=</span><span class="s2">"</span><span class="nv">$ROOT_TOKEN</span><span class="s2">"</span>

<span class="k">if</span> <span class="o">!</span> vault secrets list <span class="nt">-format</span><span class="o">=</span>json | jq <span class="nt">-e</span> <span class="s1">'has("totp/")'</span> <span class="o">&gt;</span>/dev/null<span class="p">;</span> <span class="k">then
  </span>vault secrets <span class="nb">enable </span>totp
<span class="k">fi</span>
</code></pre></div></div>

<p>Authenticated with the root token, the script mounts the TOTP secrets engine at its default
path <code class="language-plaintext highlighter-rouge">totp/</code>, unless it is already mounted.</p>

<p><strong>Writing the policy.</strong></p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>vault policy write totp-policy /vault/config/totp-policy.hcl
</code></pre></div></div>

<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>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="o">!</span> vault token lookup dev-app-token <span class="o">&gt;</span>/dev/null 2&gt;&amp;1<span class="p">;</span> <span class="k">then
  </span>vault token create <span class="nt">-id</span><span class="o">=</span><span class="s2">"dev-app-token"</span> <span class="nt">-policy</span><span class="o">=</span><span class="s2">"totp-policy"</span> <span class="se">\</span>
    <span class="nt">-orphan</span> <span class="nt">-no-default-policy</span> <span class="nt">-period</span><span class="o">=</span><span class="s2">"8760h"</span> <span class="nt">-display-name</span><span class="o">=</span><span class="s2">"vault-auth"</span> <span class="o">&gt;</span>/dev/null
<span class="k">fi</span>
</code></pre></div></div>

<p>This last stage deserves a closer look, since each option carries a precise meaning:</p>

<ol>
  <li><code class="language-plaintext highlighter-rouge">-id="dev-app-token"</code> imposes a known token value, so that the application can be configured
statically, which is convenient for development and strongly discouraged elsewhere;</li>
  <li><code class="language-plaintext highlighter-rouge">-policy="totp-policy"</code> attaches the least-privilege policy described above;</li>
  <li><code class="language-plaintext highlighter-rouge">-no-default-policy</code> removes the <code class="language-plaintext highlighter-rouge">default</code> policy, which would otherwise grant a few
additional capabilities, such as looking up the token itself;</li>
  <li><code class="language-plaintext highlighter-rouge">-orphan</code> 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><code class="language-plaintext highlighter-rouge">-period="8760h"</code> 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><code class="language-plaintext highlighter-rouge">-display-name="vault-auth"</code> 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>

<h2 id="5-the-application-code">5. The application code</h2>

<p>The <code class="language-plaintext highlighter-rouge">vault-auth</code> module is a Quarkus 3.37 application built with Quarkus REST and the Quarkiverse
<code class="language-plaintext highlighter-rouge">quarkus-vault</code> extension. Its configuration, in <code class="language-plaintext highlighter-rouge">application.properties</code>, is minimal, as shown below.</p>

<div class="language-properties highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="py">quarkus.vault.devservices.enabled</span><span class="p">=</span><span class="s">false</span>
<span class="py">quarkus.vault.url</span><span class="p">=</span><span class="s">http://localhost:8200</span>
<span class="py">quarkus.vault.authentication.client-token</span><span class="p">=</span><span class="s">dev-app-token</span>
</code></pre></div></div>

<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 <code class="language-plaintext highlighter-rouge">QUARKUS_VAULT_URL</code> and <code class="language-plaintext highlighter-rouge">QUARKUS_VAULT_AUTHENTICATION_CLIENT_TOKEN</code> when the
application runs in its own container.</p>

<h3 id="51-the-service-totpservice">5.1 The service <code class="language-plaintext highlighter-rouge">TotpService</code></h3>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@ApplicationScoped</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">TotpService</span>
<span class="o">{</span>
  <span class="kd">private</span> <span class="nc">VaultTOTPSecretEngine</span> <span class="n">vaultTOTPSecretEngine</span><span class="o">;</span>

  <span class="kd">public</span> <span class="nf">TotpService</span><span class="o">(</span><span class="nc">VaultTOTPSecretEngine</span> <span class="n">vaultTOTPSecretEngine</span><span class="o">)</span>
  <span class="o">{</span>
    <span class="k">this</span><span class="o">.</span><span class="na">vaultTOTPSecretEngine</span> <span class="o">=</span> <span class="n">vaultTOTPSecretEngine</span><span class="o">;</span>
  <span class="o">}</span>

  <span class="kd">public</span> <span class="nc">Optional</span><span class="o">&lt;</span><span class="nc">KeyDefinition</span><span class="o">&gt;</span> <span class="nf">getTotpKeyDefinition</span><span class="o">(</span><span class="nc">String</span> <span class="n">username</span><span class="o">)</span>
  <span class="o">{</span>
    <span class="nc">CreateKeyParameters</span> <span class="n">params</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">CreateKeyParameters</span><span class="o">(</span><span class="s">"totp-test"</span><span class="o">,</span> <span class="n">username</span><span class="o">);</span>
    <span class="n">params</span><span class="o">.</span><span class="na">setExported</span><span class="o">(</span><span class="kc">true</span><span class="o">);</span>
    <span class="k">return</span> <span class="n">vaultTOTPSecretEngine</span><span class="o">.</span><span class="na">createKey</span><span class="o">(</span><span class="n">username</span><span class="o">,</span> <span class="n">params</span><span class="o">);</span>
  <span class="o">}</span>

  <span class="kd">public</span> <span class="kt">boolean</span> <span class="nf">validateCode</span><span class="o">(</span><span class="nc">String</span> <span class="n">username</span><span class="o">,</span> <span class="nc">String</span> <span class="n">code</span><span class="o">)</span>
  <span class="o">{</span>
    <span class="k">return</span> <span class="n">vaultTOTPSecretEngine</span><span class="o">.</span><span class="na">validateCode</span><span class="o">(</span><span class="n">username</span><span class="o">,</span> <span class="n">code</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The class is an application scoped CDI bean, which means that a single instance is shared by
all requests. Its only dependency, <code class="language-plaintext highlighter-rouge">VaultTOTPSecretEngine</code>, is supplied by the <code class="language-plaintext highlighter-rouge">quarkus-vault</code>
extension and is injected through the constructor, which makes the dependency explicit and the
class easy to instantiate in isolation.</p>

<p>The method <code class="language-plaintext highlighter-rouge">getTotpKeyDefinition()</code> creates a TOTP key in Vault. The two-argument constructor of
<code class="language-plaintext highlighter-rouge">CreateKeyParameters</code> sets the issuer (<code class="language-plaintext highlighter-rouge">totp-test</code>), which the authenticator application
displays as the name of the service, and the account name, here the user name. This constructor
also sets the <code class="language-plaintext highlighter-rouge">generate</code> flag to <code class="language-plaintext highlighter-rouge">true</code>, which places Vault in its generator role. Vault
therefore creates the seed itself instead of expecting one from the caller. The call to
<code class="language-plaintext highlighter-rouge">setExported(true)</code> asks Vault to return the provisioning material, namely the <code class="language-plaintext highlighter-rouge">otpauth://</code> URL
and the QR code as a Base64 encoded PNG image. The key is stored under the path
<code class="language-plaintext highlighter-rouge">totp/keys/&lt;username&gt;</code>, 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 <code class="language-plaintext highlighter-rouge">period</code>, <code class="language-plaintext highlighter-rouge">algorithm</code> and <code class="language-plaintext highlighter-rouge">digits</code> 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 <code class="language-plaintext highlighter-rouge">validateCode()</code> delegates the verification to Vault, which recomputes the expected
code for the current time step and its neighbours 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>

<h3 id="52-the-resource-totpapi">5.2 The resource <code class="language-plaintext highlighter-rouge">TotpApi</code></h3>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Path</span><span class="o">(</span><span class="s">"/totp"</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">TotpApi</span>
<span class="o">{</span>
  <span class="nd">@Inject</span>
  <span class="nc">TotpService</span> <span class="n">totpService</span><span class="o">;</span>

  <span class="nd">@GET</span>
  <span class="kd">public</span> <span class="nc">Response</span> <span class="nf">testTotp</span><span class="o">(</span><span class="nd">@HeaderParam</span><span class="o">(</span><span class="s">"X-User"</span><span class="o">)</span> <span class="nc">String</span> <span class="n">username</span><span class="o">,</span>
                           <span class="nd">@HeaderParam</span><span class="o">(</span><span class="s">"X-TOTP-Code"</span><span class="o">)</span> <span class="nc">String</span> <span class="n">code</span><span class="o">)</span>
  <span class="o">{</span>
    <span class="k">return</span> <span class="n">totpService</span><span class="o">.</span><span class="na">validateCode</span><span class="o">(</span><span class="n">username</span><span class="o">,</span> <span class="n">code</span><span class="o">)</span> <span class="o">?</span> <span class="nc">Response</span><span class="o">.</span><span class="na">ok</span><span class="o">(</span><span class="s">"Access granted"</span><span class="o">).</span><span class="na">build</span><span class="o">()</span> <span class="o">:</span>
      <span class="nc">Response</span><span class="o">.</span><span class="na">status</span><span class="o">(</span><span class="nc">Response</span><span class="o">.</span><span class="na">Status</span><span class="o">.</span><span class="na">UNAUTHORIZED</span><span class="o">).</span><span class="na">entity</span><span class="o">(</span><span class="s">"Invalid TOTP code"</span><span class="o">).</span><span class="na">build</span><span class="o">();</span>
  <span class="o">}</span>

  <span class="nd">@GET</span>
  <span class="nd">@Path</span><span class="o">(</span><span class="s">"/register/{username}"</span><span class="o">)</span>
  <span class="nd">@Produces</span><span class="o">(</span><span class="nc">MediaType</span><span class="o">.</span><span class="na">TEXT_HTML</span><span class="o">)</span>
  <span class="kd">public</span> <span class="nc">String</span> <span class="nf">register</span><span class="o">(</span><span class="nd">@PathParam</span><span class="o">(</span><span class="s">"username"</span><span class="o">)</span> <span class="nc">String</span> <span class="n">username</span><span class="o">)</span>
  <span class="o">{</span>
    <span class="k">return</span> <span class="n">totpService</span><span class="o">.</span><span class="na">getTotpKeyDefinition</span><span class="o">(</span><span class="n">username</span><span class="o">)</span>
      <span class="o">.</span><span class="na">map</span><span class="o">(</span><span class="n">key</span> <span class="o">-&gt;</span> <span class="s">"""
        &lt;!DOCTYPE html&gt;
        &lt;html&gt;
            &lt;head&gt;&lt;title&gt;Scan QR Code&lt;/title&gt;&lt;/head&gt;
            &lt;body&gt;
                &lt;h2&gt;Scan this QR code with Google Authenticator&lt;/h2&gt;
                &lt;img src="</span><span class="nl">data:</span><span class="n">image</span><span class="o">/</span><span class="n">png</span><span class="o">;</span><span class="n">base64</span><span class="o">,%</span><span class="n">s</span><span class="s">" alt="</span><span class="no">TOTP</span> <span class="no">QR</span> <span class="nc">Code</span><span class="s">"/&gt;
            &lt;/body&gt;
        &lt;/html&gt;
        """</span><span class="o">.</span><span class="na">formatted</span><span class="o">(</span><span class="n">key</span><span class="o">.</span><span class="na">getBarcode</span><span class="o">()))</span>
      <span class="o">.</span><span class="na">orElse</span><span class="o">(</span><span class="s">"Failed to generate TOTP key"</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The class is a Jakarta REST resource bound to the path <code class="language-plaintext highlighter-rouge">/totp</code> and exposes two endpoints.</p>

<p>The endpoint <code class="language-plaintext highlighter-rouge">GET /totp/register/{username}</code> performs the enrolment. It obtains the key
definition from the service and, if it is present, inserts the Base64 encoded image returned by
<code class="language-plaintext highlighter-rouge">getBarcode()</code> into a small HTML page by means of a Java text block and the <code class="language-plaintext highlighter-rouge">formatted()</code>
method. The image is embedded as a <code class="language-plaintext highlighter-rouge">data:</code> 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 <code class="language-plaintext highlighter-rouge">GET /totp</code> performs the authentication. The user name and the code are read from
the custom headers <code class="language-plaintext highlighter-rouge">X-User</code> and <code class="language-plaintext highlighter-rouge">X-TOTP-Code</code>. A valid code produces the status 200 and the body
<code class="language-plaintext highlighter-rouge">Access granted</code>, whereas an invalid one produces the status 401 and the body
<code class="language-plaintext highlighter-rouge">Invalid TOTP code</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, enrolment 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>

<h3 id="53-the-integration-tests">5.3 The integration tests</h3>

<p>In accordance with the conventions of the project, the tests are integration tests executed
against a real Vault server rather than unit tests based on mocks. Two classes are involved.</p>

<p><strong><code class="language-plaintext highlighter-rouge">VaultTestResource</code></strong> implements the <code class="language-plaintext highlighter-rouge">QuarkusTestResourceLifecycleManager</code> interface, which
allows Quarkus to start an external resource before the application and to stop it afterwards.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Override</span>
<span class="kd">public</span> <span class="nc">Map</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">,</span> <span class="nc">String</span><span class="o">&gt;</span> <span class="nf">start</span><span class="o">()</span>
<span class="o">{</span>
  <span class="n">vault</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">VaultContainer</span><span class="o">&lt;&gt;(</span><span class="no">IMAGE</span><span class="o">)</span>
    <span class="o">.</span><span class="na">withVaultToken</span><span class="o">(</span><span class="no">ROOT_TOKEN</span><span class="o">)</span>
    <span class="o">.</span><span class="na">withInitCommand</span><span class="o">(</span><span class="s">"secrets enable totp"</span><span class="o">);</span>
  <span class="n">vault</span><span class="o">.</span><span class="na">start</span><span class="o">();</span>
  <span class="k">return</span> <span class="nc">Map</span><span class="o">.</span><span class="na">of</span><span class="o">(</span>
    <span class="s">"quarkus.vault.devservices.enabled"</span><span class="o">,</span> <span class="s">"false"</span><span class="o">,</span>
    <span class="s">"quarkus.vault.url"</span><span class="o">,</span> <span class="n">vault</span><span class="o">.</span><span class="na">getHttpHostAddress</span><span class="o">(),</span>
    <span class="s">"quarkus.vault.authentication.client-token"</span><span class="o">,</span> <span class="no">ROOT_TOKEN</span><span class="o">);</span>
<span class="o">}</span>
</code></pre></div></div>

<p>The method starts a Testcontainers <code class="language-plaintext highlighter-rouge">VaultContainer</code> based on the image <code class="language-plaintext highlighter-rouge">hashicorp/vault:1.18</code>,
which is the same version as in Docker Compose. The method <code class="language-plaintext highlighter-rouge">asCompatibleSubstituteFor("vault")</code>
informs Testcontainers that the official HashiCorp image may be used in place of the historical
<code class="language-plaintext highlighter-rouge">vault</code> image it expects. The container runs in Vault development mode with the root token
<code class="language-plaintext highlighter-rouge">root</code>, 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><strong><code class="language-plaintext highlighter-rouge">TotpApiTest</code></strong> is annotated with <code class="language-plaintext highlighter-rouge">@QuarkusTest</code>, which starts the complete application, and
with <code class="language-plaintext highlighter-rouge">@WithTestResource(VaultTestResource.class)</code>, which attaches the resource described above.
It contains three test cases written with REST Assured:</p>

<ol>
  <li><code class="language-plaintext highlighter-rouge">registerReturnsQrCode()</code> is a positive test which calls <code class="language-plaintext highlighter-rouge">/totp/register/alice</code> and verifies
that the response has the status 200 and contains an embedded PNG image;</li>
  <li><code class="language-plaintext highlighter-rouge">validCodeGrantsAccess()</code> is a positive test which registers <code class="language-plaintext highlighter-rouge">bob</code>, then asks Vault itself to
generate the current code by means of <code class="language-plaintext highlighter-rouge">generateCode("bob")</code>, and verifies that submitting
this code yields the status 200 and the message <code class="language-plaintext highlighter-rouge">Access granted</code>;</li>
  <li><code class="language-plaintext highlighter-rouge">invalidCodeIsRejected()</code> is a negative test which registers <code class="language-plaintext highlighter-rouge">carol</code>, submits the code
<code class="language-plaintext highlighter-rouge">000000</code> and verifies the status 401 and the message <code class="language-plaintext highlighter-rouge">Invalid TOTP code</code>.</li>
</ol>

<p>The second test is particularly instructive. Since no smartphone could reasonably be attached to
the build server, the test injects <code class="language-plaintext highlighter-rouge">VaultTOTPSecretEngine</code> 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 <code class="language-plaintext highlighter-rouge">000000</code> 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 <code class="language-plaintext highlighter-rouge">mvn -pl vault-auth -am test</code> on any workstation with a running Docker
daemon, and by the CircleCI pipeline, which uses a <code class="language-plaintext highlighter-rouge">machine</code> executor precisely so that
Testcontainers has access to a Docker engine.</p>

<h2 id="6-deployment">6. Deployment</h2>

<p>The file <code class="language-plaintext highlighter-rouge">docker-compose.yml</code> defines three services, two named volumes and one bind mount. The
following diagram represents this topology.</p>

<p><img src="/assets/images/deployment.png" alt="Deployment diagram of the Docker Compose stack" /></p>

<p><em>The PlantUML source of this diagram is available in <code class="language-plaintext highlighter-rouge">diagrams/deployment.puml</code>.</em></p>

<p>The service <code class="language-plaintext highlighter-rouge">vault</code> 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 <code class="language-plaintext highlighter-rouge">vault-file</code> and is restarted
automatically unless it is explicitly stopped.</p>

<p>The service <code class="language-plaintext highlighter-rouge">vault-init</code> uses the same image, runs as root in order to be able to install <code class="language-plaintext highlighter-rouge">jq</code>
and to write in its volume, executes the script <code class="language-plaintext highlighter-rouge">init.sh</code> and then terminates. Its restart policy
is <code class="language-plaintext highlighter-rouge">no</code>, which is the expected behaviour of a one-shot task. Its volume <code class="language-plaintext highlighter-rouge">vault-init</code> keeps the
file <code class="language-plaintext highlighter-rouge">init.json</code> between executions, which is what makes the automatic unsealing possible after a
restart.</p>

<p>The service <code class="language-plaintext highlighter-rouge">vault-auth</code> runs the Quarkus application, whose image is produced by the Quarkus
container image extension during the Maven build. The <code class="language-plaintext highlighter-rouge">pull_policy: never</code> clause indicates that
the image must exist locally and must not be searched for in a registry. The application starts
only once <code class="language-plaintext highlighter-rouge">vault-init</code> has completed successfully, which guarantees that Vault is unsealed, that
the TOTP engine is mounted and that the token <code class="language-plaintext highlighter-rouge">dev-app-token</code> exists at the moment of the first
request. Inside the Compose network, the application reaches Vault by its service name, <code class="language-plaintext highlighter-rouge">vault</code>,
through the environment variable <code class="language-plaintext highlighter-rouge">QUARKUS_VAULT_URL</code>.</p>

<p>The whole stack is started by the following commands.</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>mvn <span class="nt">-pl</span> vault-auth <span class="nt">-am</span> package <span class="nt">-Dquarkus</span>.container-image.build
docker compose up <span class="nt">-d</span>
</code></pre></div></div>

<p>After that, the user opens <code class="language-plaintext highlighter-rouge">http://localhost:8080/totp/register/&lt;username&gt;</code>, scans the QR code
and checks a code with</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl <span class="nt">-H</span> <span class="s2">"X-User: &lt;username&gt;"</span> <span class="nt">-H</span> <span class="s2">"X-TOTP-Code: &lt;code&gt;"</span> http://localhost:8080/totp
</code></pre></div></div>

<p>The command <code class="language-plaintext highlighter-rouge">docker compose down -v</code> removes the volumes and returns the system to its original
state of blissful ignorance.</p>

<h2 id="7-conclusion">7. Conclusion</h2>

<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>]]></content><author><name>Nicolas Duminil</name></author><category term="java" /><category term="quarkus" /><category term="spring-boot" /><category term="totp" /><summary type="html"><![CDATA[Abstract]]></summary></entry><entry><title type="html">Using Anthropic evaluation to check Claude Code plugin efficiency</title><link href="https://www.simplex-software.fr/posts-archive/claude-eval/" rel="alternate" type="text/html" title="Using Anthropic evaluation to check Claude Code plugin efficiency" /><published>2026-10-23T00:00:00+00:00</published><updated>2026-10-23T00:00:00+00:00</updated><id>https://www.simplex-software.fr/posts-archive/claude-eval</id><content type="html" xml:base="https://www.simplex-software.fr/posts-archive/claude-eval/"><![CDATA[<h1 id="measuring-what-a-claude-code-skill-contributes">Measuring What a Claude Code Skill Contributes</h1>

<h2 id="context">Context</h2>

<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>

<h2 id="a-criterion-for-useful-skill-content">A criterion for useful skill content</h2>

<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>

<h2 id="restructuring-before-measuring">Restructuring before measuring</h2>

<p>The first step was to collect all the loose folders in <code class="language-plaintext highlighter-rouge">~/.claude</code>, defining agents,
skills and hooks, to remove the duplicates and to consolidate them in stand-alone
plugins. The result is a marketplace named <code class="language-plaintext highlighter-rouge">simplex-software</code> that lists five plugins:</p>

<table>
  <thead>
    <tr>
      <th>Plugin</th>
      <th>Activation</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">spring-boot-template</code></td>
      <td>per project</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">quarkus-template</code></td>
      <td>per project</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">java-extras</code></td>
      <td>user scope, every session</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">camel</code></td>
      <td>per project</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">jakarta-ee</code></td>
      <td>per project</td>
    </tr>
  </tbody>
</table>

<p>The stack plugins take precedence on every conflict. <code class="language-plaintext highlighter-rouge">java-extras</code> holds personal rules,
cross stack decisions, operational notes and a <code class="language-plaintext highlighter-rouge">UserPromptSubmit</code> 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’t use them.</p>

<h2 id="the-measurement-method">The measurement method</h2>

<p>Claude Code provides <code class="language-plaintext highlighter-rouge">claude plugin eval</code>, 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 “test cases”, 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 <code class="language-plaintext highlighter-rouge">tool_used</code> grader that checks whether Claude invoked the skill through the <code class="language-plaintext highlighter-rouge">Skill</code>
tool. 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>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">---</span>
<span class="na">name</span><span class="pi">:</span> <span class="s">quarkus-route-test</span>
<span class="na">tags</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">camel</span><span class="pi">,</span> <span class="nv">quarkus</span><span class="pi">]</span>
<span class="na">max_turns</span><span class="pi">:</span> <span class="m">8</span>
<span class="na">allowed_tools</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">Skill</span><span class="pi">,</span> <span class="nv">Read</span><span class="pi">,</span> <span class="nv">Glob</span><span class="pi">,</span> <span class="nv">Grep</span><span class="pi">]</span>
<span class="nn">---</span>

Quarkus 3 project using Camel Quarkus. A RouteBuilder defines route id <span class="sb">`process-route`</span>
from <span class="sb">`direct:process`</span> to <span class="sb">`kafka:processed-orders`</span>. Write a test that verifies one message
reaches the Kafka endpoint without a real Kafka broker being used for that endpoint.
Include the Maven test dependencies.
</code></pre></div></div>

<p>Its regular expression grader, <code class="language-plaintext highlighter-rouge">graders/test-artifact.md</code>:</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">---</span>
<span class="na">type</span><span class="pi">:</span> <span class="s">regex</span>
<span class="na">pattern</span><span class="pi">:</span> <span class="s2">"</span><span class="s">camel-quarkus-junit(?!5)"</span>
<span class="na">match</span><span class="pi">:</span> <span class="s">contains</span>
<span class="nn">---</span>

Uses camel-quarkus-junit, the successor of the deprecated camel-quarkus-junit5.
</code></pre></div></div>

<p>Its judge grader, <code class="language-plaintext highlighter-rouge">graders/judge.md</code>, whose body is the criterion the judge model applies to
the answer:</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">---</span>
<span class="na">type</span><span class="pi">:</span> <span class="s">llm</span>
<span class="nn">---</span>

Pass only if ALL hold:
<span class="p">-</span> test dependency is org.apache.camel.quarkus:camel-quarkus-junit (not camel-quarkus-junit5)
<span class="p">-</span> test extends CamelQuarkusTestSupport, overrides isUseAdviceWith() to return true, advises route "process-route" (mockEndpoints / mockEndpointsAndSkip) and then starts the context
<span class="p">-</span> does not use @MockEndpoints (not available in Camel Quarkus)
<span class="p">-</span> no Thread.sleep
</code></pre></div></div>

<p>Its skill indicator, <code class="language-plaintext highlighter-rouge">graders/skill-fired.md</code>, which passes when Claude loads a skill whose
name contains <code class="language-plaintext highlighter-rouge">camel</code>:</p>

<div class="language-markdown highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">---</span>
<span class="na">type</span><span class="pi">:</span> <span class="s">tool_used</span>
<span class="na">tool</span><span class="pi">:</span> <span class="s">Skill</span>
<span class="na">input_match</span><span class="pi">:</span> <span class="s2">"</span><span class="s">camel"</span>
<span class="nn">---</span>

Indicator only: the plugin skill was loaded.
</code></pre></div></div>

<p>The command runs every case of a plugin, three runs per arm, with a cost ceiling:</p>

<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>claude plugin <span class="nb">eval</span> <span class="nb">.</span> <span class="nt">-j</span> 3 <span class="nt">--no-publish</span> <span class="nt">--max-cost-usd</span> 5
</code></pre></div></div>

<h2 id="first-results">First results</h2>

<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>

<table>
  <thead>
    <tr>
      <th>Plugin</th>
      <th>Case</th>
      <th>With</th>
      <th>Without</th>
      <th>Difference</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>camel</td>
      <td>Camel Quarkus route test</td>
      <td>1.00</td>
      <td>0.33</td>
      <td>+0.67</td>
    </tr>
    <tr>
      <td>camel</td>
      <td>Spring Boot route unit test</td>
      <td>1.00</td>
      <td>0.33</td>
      <td>+0.67</td>
    </tr>
    <tr>
      <td>camel</td>
      <td>Spring Boot Kafka integration test</td>
      <td>1.00</td>
      <td>0.92</td>
      <td>+0.08</td>
    </tr>
    <tr>
      <td>jakarta-ee</td>
      <td>integration test on WildFly</td>
      <td>0.89</td>
      <td>0.33</td>
      <td>+0.56</td>
    </tr>
    <tr>
      <td>jakarta-ee</td>
      <td>pom setup</td>
      <td>equal</td>
      <td>equal</td>
      <td>0</td>
    </tr>
    <tr>
      <td>jakarta-ee</td>
      <td>resource, service and injection</td>
      <td>equal</td>
      <td>equal</td>
      <td>0</td>
    </tr>
    <tr>
      <td>java-extras</td>
      <td>CircleCI with Testcontainers</td>
      <td>1.00</td>
      <td>0.33</td>
      <td>+0.67</td>
    </tr>
    <tr>
      <td>java-extras</td>
      <td>graceful shutdown on Kubernetes</td>
      <td>1.00</td>
      <td>0.50</td>
      <td>+0.50</td>
    </tr>
    <tr>
      <td>java-extras</td>
      <td>Spring Boot to Quarkus migration</td>
      <td>1.00</td>
      <td>0.89</td>
      <td>+0.11</td>
    </tr>
    <tr>
      <td>java-extras</td>
      <td>Reactor to Mutiny translation</td>
      <td>0.56</td>
      <td>0.67</td>
      <td>about 0</td>
    </tr>
  </tbody>
</table>

<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 <code class="language-plaintext highlighter-rouge">4.18.0</code>, whereas the skill states
4.23.0, built on Spring Boot 4.1.1. It also selected the test artifacts 
<code class="language-plaintext highlighter-rouge">camel-test-spring-junit6</code> instead of <code class="language-plaintext highlighter-rouge">camel-quarkus-junit</code> 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
<code class="language-plaintext highlighter-rouge">preStop</code> delay, the application shutdown timeout and <code class="language-plaintext highlighter-rouge">terminationGracePeriodSeconds</code>.</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>

<h2 id="trimming-and-the-regression-the-evaluation-caught">Trimming, and the regression the evaluation caught</h2>

<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 <code class="language-plaintext highlighter-rouge">@Transactional</code> annotation has no <code class="language-plaintext highlighter-rouge">readOnly</code> 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 <code class="language-plaintext highlighter-rouge">Session</code> with <code class="language-plaintext highlighter-rouge">FlushMode.MANUAL</code>, or a <code class="language-plaintext highlighter-rouge">org.hibernate.readOnly</code> 
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>

<h2 id="final-state-and-cost">Final state and cost</h2>

<table>
  <thead>
    <tr>
      <th>Measure</th>
      <th>Before</th>
      <th>After</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Agent and skill files</td>
      <td>43</td>
      <td>6</td>
    </tr>
    <tr>
      <td>Lines of agent and skill content</td>
      <td>17,338</td>
      <td>638</td>
    </tr>
    <tr>
      <td>Tokens added to every session</td>
      <td>about 2,100</td>
      <td>about 520, plus about 150 for each optional plugin enabled in the project</td>
    </tr>
    <tr>
      <td>Evaluation cases</td>
      <td>none</td>
      <td>6, each with a measured difference</td>
    </tr>
  </tbody>
</table>

<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>

<h2 id="lessons">Lessons</h2>

<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
<code class="language-plaintext highlighter-rouge">readOnly</code> episode demonstrates it.</li>
</ol>

<h2 id="limitations">Limitations</h2>

<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 <code class="language-plaintext highlighter-rouge">house-rules</code> were deliberately
left out of the evaluation, since the model has no means of guessing them.</p>]]></content><author><name>Nicolas Duminil</name></author><category term="claude-code" /><category term="ai-assisted-development" /><category term="java" /><category term="quarkus" /><category term="spring-boot" /><category term="apache-camel" /><category term="jakarta-ee" /><category term="evaluation" /><summary type="html"><![CDATA[Measuring What a Claude Code Skill Contributes]]></summary></entry><entry><title type="html">Distributed Transactions in Enterprise Applications: From X/Open to MicroProfile LRA</title><link href="https://www.simplex-software.fr/posts-archive/quarkus-2pc-lra/" rel="alternate" type="text/html" title="Distributed Transactions in Enterprise Applications: From X/Open to MicroProfile LRA" /><published>2026-10-19T00:00:00+00:00</published><updated>2026-10-22T13:05:34+00:00</updated><id>https://www.simplex-software.fr/posts-archive/quarkus-2pc-lra</id><content type="html" xml:base="https://www.simplex-software.fr/posts-archive/quarkus-2pc-lra/"><![CDATA[<h2 id="abstract">Abstract</h2>

<p>The problem of making several independent systems agree on a single outcome is
older than most of the technology used to solve it. Historically, one of the 
first protocols able to provide this synchronization was 2PC (<em>two-phase commit</em>)
that the application servers era made an ordinary feature of enterprise development.
Later lightweight frameworks, service-oriented and microservices architectures
have made the same guarantee considerably harder to obtain.<br />
This article follows that problem from its formalization in the X/Open Distributed
Transaction Processing to the present situation. It then examines two working
implementations of an identical use case, one using XA and two-phase commit, the
other using the saga pattern, as specified by MicroProfile LRA, and compares them
on evidence rather than on preference. The accompanying source code is available
in the <a href="https://github.com/nicolasduminil/quarkus-distributed-tx"><code class="language-plaintext highlighter-rouge">quarkus-distributed-tx</code></a>
repository, where both implementations expose the same REST contract and are
exercised by the same test suite.</p>

<hr />

<h2 id="1-origins-xopen-and-the-formalization-of-2pc">1. Origins: X/Open, and the Formalization of 2PC</h2>

<p>The 2PC protocol is older than the standard that made it famous. Its
essential shape appears in the database literature of the late 1970s, notably in
the work of Jim Gray on the recovery and consistency properties of database
operating systems. The problem it addresses is easy to state and difficult to
solve: several parties must all either perform or decline an action. And they
must do that despite the possibility that any of them, including the party 
conducting the negotiation, may fail at any moment.</p>

<p>As its name states, the protocol proceeds in two phases. In the first, the
coordinator asks every participant whether it is able to commit. A participant
that answers affirmatively cannot retract itself. It must have
written enough durable state to guarantee that it can still commit even after 
a crash. In the second phase, the coordinator informs the participants of the 
collective decision, which is affirmative only if every vote was affirmative.</p>

<p>In early ’90s, the X/Open consortium decided to contribute by formalizing a reference 
model named DTP (<em>Distributed Transaction Processing</em>). This model identified
three roles namely the application program, the transaction manager and the 
resource manager. The following two interfaces have been defined:</p>

<ul>
  <li>the TX (<em>Transaction Demarcation</em>) interface governs how an application demarcates a transaction;</li>
  <li>the XA (<em>eXtended Architecture</em>) interface defines how the transaction manager drives the resource manager through the phases of the commit.</li>
</ul>

<p>Once the XA specifications existed, a transaction manager written by one
vendor could coordinate a database written by another, and the industry acquired
a genuinely portable mechanism for distributed atomicity.</p>

<p>Let’s note a property of the XA specifications that will become important
later. Between the moment a participant votes to commit and the moment it learns
the collective decision, it is <em>blocked</em>. It holds its locks, it cannot proceed,
and it cannot unilaterally decide. If the coordinator fails during this interval,
the participant waits. Skeen and others demonstrated in the early ’80s that this
blocking behavior is not an artifact of a careless design but a logical consequence
of the quorum-based model which tolerates partitions only by blocking whenever no
quorum can be assembled. In 1985, Fischer, Lynch and Paterson published the article
<em>Impossibility of Distributed Consensus with One Faulty Process</em> which establishes
that deterministic consensus cannot be guaranteed in an asynchronous system in 
which even one process may fail.</p>

<p>Because of this vulnerability 2PC was considered in the beginning a flawed protocol
that needed improvements. It took some time and experience to understand that, 
on the opposite, it’s an exact trade-off between perfect atomicity and availability.</p>

<h2 id="2-several-decades-of-service">2. Several Decades of Service</h2>

<p>It would be reasonable to expect that a protocol with a documented blocking
failure mode and a known vulnerability would have been superseded. It has not 
been. 2PC remains the most widely deployed mechanism for distributed atomicity 
in enterprise systems, and it is likely to remain so for some time.</p>

<p>The explanation is that the failure mode is rare and the guarantee is absolute.
Within a single data center, coordinating two databases and a message broker
across a reliable local network, with a transaction manager whose recovery log is
on durable storage, the vulnerable interval is measured in milliseconds and the
recovery procedure is automatic. Financial institutions, telecommunications
operators and government systems adopted the protocol because the alternative was
to write compensation logic by hand for every business operation. Additionally,
software architects and developers are more confident in a protocol than in a 
promise that reconciliation will probably catch any discrepancies.</p>

<p>Another important point to notice is that 2PC places complexity in the 
infrastructure field, written once, by specialists, and consumed through a single
annotation. Every other alternative examined in this article moves that work into
application code, where it must be written again for each operation, by
developers whose principal expertise is the business domain rather than
distributed systems. This is a real cost and it is frequently underestimated.</p>

<h2 id="3-ots-jts-and-jta">3. OTS, JTS and JTA</h2>

<p>The X/Open model assumed a particular shape: an application, a transaction
manager and some resource managers, generally within reach of one another. What
it did not address is the case that the OO (<em>object-oriented</em>) paradigm made 
central the concept of transactions spanning objects that reside in different 
processes, on different machines, supplied by different vendors, and invoked 
remotely as though they were local.</p>

<p>The OMG (<em>Object Management Group</em>), the consortium behind CORBA, answered this in the
mid-1990s with the OTS (<em>Object Transaction Service</em>), adopted as one of the
CORBAservices. OTS described the roles of a distributed transaction in CORBA’s
IDL (<em>Interface Definition Language</em>). The protocol underneath had not changed,
the same resources, participants and quorum, in Gray’s sense, were at work and 
no new algorithms have been proposed. OTS only specified how the 2PC participants
might be distributed objects. And it settled the question that X/Open had left
thin, namely how two transaction managers, from different vendors, should
interoperate.</p>

<p>OTS didn’t displace XA but complemented it. The boundary to the resources, like 
databases or message brokers, remained what it had been, OTS typically only fronted
resource managers driven over XA. Anything that OTS added sat above that 
boundary, between the managers themselves.</p>

<p>The Jakarta EE platform, formerly Java EE and even formerly J2EE, absorbed this
model with considerable thoroughness. The JTA (<em>Java Transaction API</em>) specifications
defined the interface through which applications and application servers demarcate 
transactions. JTS (<em>Java Transaction Service</em>) brought OTS into Java. It required
a transaction manager to implement that specification in its Java-mapped form, 
to propagate transaction context between managers as OTS prescribed, and to 
present JTA to the layer above. JTS was therefore not an alternative design but
OTS in Java, with a JTA façade.</p>

<p>The distinction between JTA and JTS is worth mentioning as the two are habitually
confused, usually as “JTA is the interface and JTS the implementation”. That is
not quite it, since both are specifications. JTA is what an application programmer
sees: <code class="language-plaintext highlighter-rouge">UserTransaction</code>, <code class="language-plaintext highlighter-rouge">TransactionManager</code>, and the interfaces by which resources
are enlisted. JTS specifies what provides the guarantee underneath, including the
propagation of transaction context between processes and the interoperability of
transaction managers from different vendors.</p>

<p>For the application developer, the effect was remarkable and is easily forgotten
now. A method annotated for container-managed transactions would, upon invoking a
remote component, carry its transaction context to that component, enlist the
remote resources, and commit or roll back the entire assembly atomically. The
programmer wrote business logic. The container arranged consensus. This was one
of the genuinely impressive achievements of the enterprise Java period which 
worked reliably across products from competing vendors and it is
somewhat unfair that it is now remembered as an old labyrinthine system.</p>

<h2 id="4-corba-and-iiop-as-the-transport-of-context">4. CORBA and IIOP as the Transport of Context</h2>

<p>The transaction context propagation just described required a mechanism, and the
mechanism was CORBA. Transaction context traveled between application servers 
as part of the IIOP (<em>Internet Inter-ORB Protocol</em>), in the form of a service 
context attached to the remote invocation. OTS defined how that context was
represented and how transaction managers should interoperate. IIOP carried it.</p>

<p>This arrangement was possible because <strong>the transport understood transactions</strong>.
A remote call was not merely a message but an invocation within a transactional
context, and the infrastructure at both ends recognized it as such. Enlistment 
of the remote resource was automatic because the protocol carried the information
required to perform it.</p>

<p>The costs were substantial. CORBA was complex, its interoperability was achieved
by considerable effort and its programming model demanded interface definitions
and generated stubs. As the industry moved towards HTTP and simpler representations,
these costs became decisive. But it is important to record that the price of the
simplicity was HTTP lack of capacity to carry transactional semantics.</p>

<h2 id="5-the-decline-of-heavyweight-servers-and-the-rise-of-lighter-frameworks">5. The Decline of Heavyweight Servers and the Rise of Lighter Frameworks</h2>

<p>The reasons for the decline of the traditional application server are well
documented and only tangentially concerned with transactions. Deployment units
grew large and start-up times grew long at exactly the moment when elastic
infrastructure began to reward the opposite. Container images preferred a single
process to a shared runtime hosting many applications. The operational model of
the application server, in which several applications share a managed container
administered by a specialist team, was displaced by one in which each service
carries its own runtime and is administered by the team that wrote it.</p>

<p>Spring Boot, released in 2014, demonstrated that an embedded server and
convention-based configuration could deliver most of the productivity of the
enterprise stack with a fraction of its ceremony. Quarkus, which followed in 2019,
went further by moving substantial work from run time to build time, producing
start-up characteristics that make Java a plausible choice for serverless and
elastically scaled deployments.</p>

<p>Jakarta EE itself, transferred to the Eclipse Foundation in 2017 and subsequently
renamed, continues to evolve, and both Spring Boot and Quarkus rely on
substantial parts of its specifications. The change is therefore less a
repudiation of the enterprise Java model than a redistribution of it. The
specifications survived, the monolithic container that implemented them did not.</p>

<h2 id="6-what-the-lighter-frameworks-lost">6. What the Lighter Frameworks Lost</h2>

<p>Two changes occurred simultaneously. The first is architectural. The microservice
architecture style holds that each service should own its data, and that no other
service should reach into that data directly. This principle is incompatible with
2PC across services which requires the coordinator to be connected to
the resource managers. A coordinator that must not touch another service’s
resources cannot enlist them.</p>

<p>The second is a matter of transport. HTTP does not propagate transaction context.
It doesn’t provide an equivalent of the IIOP service context. A REST call is an
independent interaction whose relationship to the caller’s transaction is not 
represented anywhere, unless the application arranges to represent it.</p>

<p>The consequence, which is regularly misunderstood in practice, is that
annotating a method as transactional and then invoking a remote service from
within it produces no distributed transaction of any kind. 
If the local transaction rolls back, the remote effect stands. If
the local transaction commits, nothing establishes that the remote one did, and
a remote call that returned no answer may have applied its change or may not,
leaving the caller no basis on which to decide. The divergence does not even
require the remote service to fail. The arrangement has the
appearance of a distributed transaction and none of the substance, which is the
least desirable of the available outcomes, since it fails while presenting the
appearance of success.</p>

<h2 id="7-the-saga-pattern-and-the-ease-of-implementing-it-incorrectly">7. The Saga Pattern, and the Ease of Implementing It Incorrectly</h2>

<p>The saga was described by Garcia-Molina and Salem in 1987, in a paper concerned
with long-lived transactions within a single database. Their observation was that
a transaction holding locks for a long period is destructive to concurrency, and
that certain long transactions may be decomposed into a sequence of shorter ones,
each of which commits independently, with a compensating transaction defined for
each step. If the sequence cannot be completed, the compensations for the
completed steps are executed in reverse order.</p>

<p>The saga doesn’t provide isolation. This is not a defect of a particular
implementation but by definition. Intermediate states are visible to other
observers, because each step has genuinely committed. In exchange, no participant
holds a lock while waiting for a distant coordinator, and each service retains
authority over its own data.</p>

<p>The naive implementation, which is very common, executes each step and defines its
compensation as the arithmetic inverse. Let’s consider the example of a money transfer
service, like the one presented in the associated project. A debit is compensated
by a credit of the same amount. This is wrong in two distinct ways.</p>

<p>The first defect is the visible intermediate state. Between the debit and its
compensation, the balance is genuinely reduced. Any concurrent observer, including
another saga evaluating whether sufficient funds exist, will read that reduced
value and may act upon information that is about to be invalidated.</p>

<p>The second defect is that <strong>the compensating action can itself fail</strong>. A credit is
an operation like any other, subject to validation, to constraints, and to the
account having been closed in the interval. A saga whose compensation fails is in
a worse condition than one that never began, since it has performed part of an
operation and it cannot undo it. The system requires human intervention, and the
humans require an explanation.</p>

<p>The remedy, illustrated in Section 10, is to arrange matters so that no
compensating write is required. If the first step reserves rather than acts, then
compensation releases the reservation, and a release cannot fail for business
reasons because it removes an obligation rather than creating one.</p>

<h2 id="8-microprofile-lra">8. MicroProfile LRA</h2>

<p>MicroProfile LRA, where LRA denotes <em>Long Running Action</em>, specifies a saga
coordination protocol for services communicating over HTTP. It is best understood
as an answer to the two negative effects identified in Section 6: it reintroduces a context
that travels with the call, and it reintroduces a coordinator that drives
participants to a common outcome. It does not, and cannot, reintroduce atomicity.</p>

<p>The programming model is declarative. A method annotated <code class="language-plaintext highlighter-rouge">@LRA</code> participates in a
long-running action, beginning one if required. Context propagates in the
<code class="language-plaintext highlighter-rouge">Long-Running-Action</code> HTTP header, which the implementation attaches to outgoing
calls and interprets on incoming ones. A participant declares its obligations
through further annotations:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">@Compensate</code>, which is invoked if the action is cancelled;</li>
  <li><code class="language-plaintext highlighter-rouge">@Complete</code>, invoked if it is closed successfully;</li>
  <li><code class="language-plaintext highlighter-rouge">@Status</code>, by which the coordinator may enquire what a participant did;</li>
  <li><code class="language-plaintext highlighter-rouge">@Forget</code>, by which a participant may discard state it no longer needs to retain.</li>
</ul>

<p>Two properties of this protocol are commonly overlooked. The first is that participants
must be <strong>idempotent</strong>. The coordinator retries. A participant that applies its
effect a second time corrupts its own data. This is the requirement that appears
in every specification document and is absent from a remarkable proportion of 
first implementations.</p>

<p>The second is that the coordinator is a <strong>separate process that calls the
participants back</strong>. As opposed to JTA where the transaction manager is embedded
in the application, under LRA it is not and the participant must reach the coordinator
to begin, join and end an action. The coordinator must reach every participant
to invoke its callbacks. It is entirely possible to construct a deployment in 
which the first direction works as expected while the second does not, and the resulting 
behavior is discussed in Section 10.</p>

<hr />

<h2 id="9-the-xa-implementation-in-detail">9. The XA Implementation in Detail</h2>

<p>The use case is deliberately modest: transfer an amount from one account to
another and record the transfer. Two databases are involved, one holding accounts
and one holding the transfer log, because a single database would reduce the
problem to a local transaction and demonstrate nothing.</p>

<p>One component in this arrangement is essential: the Narayana transaction manager.
Its lineage is running back to the Arjuna research at the University of Newcastle
and provided two decades of good service as the transaction manager of JBoss and
WildFly. Its Quarkus extension, used here, brings a JTA implementation embedded
in the application’s own process. It owns the object store, decides the outcome
and executes the 2PC protocol on the application’s behalf. The same project supplies
the LRA coordinator that section 10 relies upon, so both implementations in this
article rely on the same body of code.</p>

<h3 id="configuration">Configuration</h3>

<p>Each datasource is declared as an XA one:</p>

<div class="language-properties highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="py">quarkus.datasource.accounts.jdbc.transactions</span><span class="p">=</span><span class="s">xa</span>
<span class="py">quarkus.datasource.xfers.jdbc.transactions</span><span class="p">=</span><span class="s">xa</span>
</code></pre></div></div>

<p>That flag is the entire mechanism. The connection pool supplies <code class="language-plaintext highlighter-rouge">XAConnection</code>
instances rather than ordinary ones, and each pool enlists an <code class="language-plaintext highlighter-rouge">XAResource</code> in the
active transaction upon first use.</p>

<h3 id="the-transactional-method">The transactional method</h3>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Transactional</span>
<span class="kd">public</span> <span class="nc">TransferDto</span> <span class="nf">processTransfer</span><span class="o">(</span><span class="nc">TransferRequest</span> <span class="n">request</span><span class="o">)</span>
<span class="o">{</span>
  <span class="nc">Account</span> <span class="n">source</span> <span class="o">=</span> <span class="n">accountRepository</span><span class="o">.</span><span class="na">getAccount</span><span class="o">(</span><span class="n">request</span><span class="o">.</span><span class="na">getSourceAccountId</span><span class="o">())</span>
    <span class="o">.</span><span class="na">orElseThrow</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="k">new</span> <span class="nc">AccountNotFoundException</span><span class="o">(</span><span class="n">request</span><span class="o">.</span><span class="na">getSourceAccountId</span><span class="o">()));</span>
  <span class="nc">Account</span> <span class="n">destination</span> <span class="o">=</span> <span class="n">accountRepository</span><span class="o">.</span><span class="na">getAccount</span><span class="o">(</span><span class="n">request</span><span class="o">.</span><span class="na">getDestinationAccountId</span><span class="o">())</span>
    <span class="o">.</span><span class="na">orElseThrow</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="k">new</span> <span class="nc">AccountNotFoundException</span><span class="o">(</span><span class="n">request</span><span class="o">.</span><span class="na">getDestinationAccountId</span><span class="o">()));</span>
  <span class="k">if</span> <span class="o">(</span><span class="n">source</span><span class="o">.</span><span class="na">getBalance</span><span class="o">().</span><span class="na">compareTo</span><span class="o">(</span><span class="n">request</span><span class="o">.</span><span class="na">getAmount</span><span class="o">())</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="o">)</span>
    <span class="k">throw</span> <span class="k">new</span> <span class="nf">InsufficientFundsException</span><span class="o">(</span><span class="n">source</span><span class="o">.</span><span class="na">getId</span><span class="o">());</span>
  <span class="n">source</span><span class="o">.</span><span class="na">debit</span><span class="o">(</span><span class="n">request</span><span class="o">.</span><span class="na">getAmount</span><span class="o">());</span>
  <span class="n">destination</span><span class="o">.</span><span class="na">credit</span><span class="o">(</span><span class="n">request</span><span class="o">.</span><span class="na">getAmount</span><span class="o">());</span>
  <span class="nc">Transfer</span> <span class="n">transfer</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Transfer</span><span class="o">(</span><span class="nc">Common</span><span class="o">.</span><span class="na">getRandomId</span><span class="o">(),</span> <span class="n">source</span><span class="o">.</span><span class="na">getId</span><span class="o">(),</span> <span class="n">destination</span><span class="o">.</span><span class="na">getId</span><span class="o">(),</span>
        <span class="n">request</span><span class="o">.</span><span class="na">getAmount</span><span class="o">(),</span> <span class="n">request</span><span class="o">.</span><span class="na">getCurrency</span><span class="o">(),</span> <span class="nc">TransferStatus</span><span class="o">.</span><span class="na">COMPLETED</span><span class="o">,</span> <span class="nc">LocalDateTime</span><span class="o">.</span><span class="na">now</span><span class="o">());</span>
  <span class="n">transferRepository</span><span class="o">.</span><span class="na">createTransfer</span><span class="o">(</span><span class="n">transfer</span><span class="o">);</span>
  <span class="k">return</span> <span class="n">transfer</span><span class="o">.</span><span class="na">toDto</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div></div>

<p>There is no reference to two-phase commit in this code, and that is the
observation worth recording. The annotation causes a JTA transaction to begin. The
two repositories address two different datasources. Each datasource enlists itself.
When the method returns, Narayana performs the protocol.</p>

<h3 id="the-protocol-as-executed">The protocol as executed</h3>

<p>Upon commit the transaction manager calls <code class="language-plaintext highlighter-rouge">prepare</code> on both branches. Each
PostgreSQL instance executes <code class="language-plaintext highlighter-rouge">PREPARE TRANSACTION</code>, writing the changes durably in
a state from which they can still either be committed or rolled back. If both 
branches vote affirmatively, the transaction manager writes its decision to 
its object store. This is the point at which the outcome becomes irrevocable
and then the transaction manager calls <code class="language-plaintext highlighter-rouge">commit</code> on both branches, each of which
executes <code class="language-plaintext highlighter-rouge">COMMIT PREPARED</code>.</p>

<p>Two consequences of operational importance follow. PostgreSQL refuses prepared
transactions unless <code class="language-plaintext highlighter-rouge">max_prepared_transactions</code> is configured with a positive
value, its default being zero, so an otherwise correct application fails at the
first commit. And the transaction manager’s object store must be durable, since it
holds the only record of a decision made but not yet applied. Recovery must be
enabled so that transactions left in doubt by a failure are resolved when the
process returns.</p>

<h3 id="the-architectural-cost">The architectural cost</h3>

<p>The transfer service interacts directly with the <code class="language-plaintext highlighter-rouge">accounts</code> database. It does not
ask anything of the account service, it holds the resource manager instead. This
means that it owns a connection to the <code class="language-plaintext highlighter-rouge">accounts</code> database and enlists it in its
own transaction. The transfer service opens that connection, modifies the account
rows itself through its own persistence layer, and the <code class="language-plaintext highlighter-rouge">XAResource</code> behind that
connection becomes a branch of the transaction that the transfer service began.
The account service plays no part. Its code does not run and it is not informed.
The commit decision belongs to the transfer service’s transaction manager.</p>

<p>This is not an oversight but a requirement. <code class="language-plaintext highlighter-rouge">prepare</code> and <code class="language-plaintext highlighter-rouge">commit</code> are operations
on an <code class="language-plaintext highlighter-rouge">XAResource</code>, and a service boundary exposes no equivalent of them. HTTP
offers no way to ask a remote service to make a change durable while leaving its
outcome open. A coordinator that cannot reach the resource manager cannot enlist
it. The consequence is that the two services need to share a database, and the
independence that the service boundary was intended to establish is not present.
The repository’s <code class="language-plaintext highlighter-rouge">docker-compose.yaml</code> states this fact in one line: <code class="language-plaintext highlighter-rouge">transfer</code> is
given its own database, as well as the accounts datasource URL, whereas 
<code class="language-plaintext highlighter-rouge">transfer-lra</code> is given, in addition to its own database URL, the one of the 
account service.</p>

<h2 id="10-the-lra-implementation-in-detail">10. The LRA Implementation in Detail</h2>

<p>The saga implementation exposes an identical REST contract and reaches balances
only through the account service’s HTTP interface. It has no dependency on the
accounts persistence layer, and that absence is the entire architectural point.</p>

<h3 id="reserve-then-confirm">Reserve, then confirm</h3>

<p>In the LRA implementation and as opposed to the 2PC one, the account service does
not move money when asked to reserve a debit. It records a <code class="language-plaintext highlighter-rouge">Reservation</code> in state
<code class="language-plaintext highlighter-rouge">PENDING</code> and leaves the balance unchanged. Available funds are computed as the
balance minus the sum of pending debits, so another possible concurrent saga 
cannot reserve the same money. Upon <code class="language-plaintext highlighter-rouge">@Complete</code> the reservations are applied; 
upon <code class="language-plaintext highlighter-rouge">@Compensate</code> they are released.</p>

<p>Accordingly, <strong>because the balance never moved, compensation performs no update
and, therefore, no persistence operation can fail during compensation.</strong> Hence,
the second issue identified in Section 7 is eliminated by construction rather 
than by coding.</p>

<h3 id="idempotency-enforced-twice">Idempotency, enforced twice</h3>

<p>Reservations are identified, in business terms, by a triple consisting in the action identifier,
the account and the reservation type. Notice that the triple is not the entity’s primary key, 
which is a generated value, so nothing in the object model prevents a second row carrying the
same triple. And in order to avoid that, it is declared as a unique constraint in the database:</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Table</span><span class="o">(</span><span class="n">name</span> <span class="o">=</span> <span class="s">"RESERVATIONS"</span><span class="o">,</span>
  <span class="n">uniqueConstraints</span> <span class="o">=</span> <span class="nd">@UniqueConstraint</span><span class="o">(</span><span class="n">name</span> <span class="o">=</span> <span class="s">"UK_RESERVATION_LRA"</span><span class="o">,</span>
    <span class="n">columnNames</span> <span class="o">=</span> <span class="o">{</span><span class="s">"LRA_ID"</span><span class="o">,</span> <span class="s">"ACCOUNT_ID"</span><span class="o">,</span> <span class="s">"RESERVATION_TYPE"</span><span class="o">}))</span>
</code></pre></div></div>

<p>The constraint is needed because the account service, when asked to reserve a
debit, looks for an existing reservation before writing one, which is a
check-then-act sequence and, therefore, not atomic. Two deliveries of the same
reserve request can both find nothing and both insert. The constraint avoids that
and guarantees that the database refuses the 2nd reserve.</p>

<p>Retries could also cause the effect described above. The coordinator waits for
each callback, but a call that times out or whose reply is lost leaves the
action unresolved, so it keeps calling again and again. A settlement instruction
therefore might arrive more than once for a reservation that is already recorded. The
database constraint cannot help here, since no row is being inserted. Then the guard
sits one level down, in the service class shown below. As you can see, the two 
callbacks annotated with <code class="language-plaintext highlighter-rouge">@Compensate</code> and <code class="language-plaintext highlighter-rouge">@Complete</code> annotations obtain their
reservations from a single helper, the <code class="language-plaintext highlighter-rouge">pendingFor(...)</code> method, that selects
only the <code class="language-plaintext highlighter-rouge">PENDING</code> reservations, so that the ones already confirmed or already
released are passed over rather than settled again.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>@ApplicationScoped
public class AccountLraService
{
  ...
  @Transactional
  public ParticipantStatus complete(String lraId)
  {
    pendingFor(lraId).forEach(this::confirm);
    return ParticipantStatus.Completed;
  }
  ...
  @Transactional
  public ParticipantStatus compensate(String lraId)
  {
    pendingFor(lraId).forEach(reservation -&gt; reservation.setState(ReservationState.RELEASED));
    return ParticipantStatus.Compensated;
  }
  ...
  private Stream&lt;Reservation&gt; pendingFor(String lraId)
  {
    return reservations.findByLra(lraId).stream()
     .filter(reservation -&gt; reservation.getState() == ReservationState.PENDING);
  }
  ...
}  
</code></pre></div></div>

<h2 id="11-the-project">11. The Project</h2>

<p>The project that illustrates this article is a Quarkus workshop, available at
<a href="https://github.com/nicolasduminil/quarkus-distributed-tx"><code class="language-plaintext highlighter-rouge">quarkus-distributed-tx</code></a>,
showing a simple money transfer use case in the two ways that we discussed along
the article:</p>

<ul>
  <li><strong>XA / 2PC</strong> (<code class="language-plaintext highlighter-rouge">transfer</code>, port 8080): a genuine 2PC across two XA
datasources, coordinated by Narayana.</li>
  <li><strong>Saga / MicroProfile LRA</strong> (<code class="language-plaintext highlighter-rouge">transfer-lra</code>, port 8090 and <code class="language-plaintext highlighter-rouge">account</code>, port 8081): a compensation-based
consistency example across autonomous services, coordinated by a Narayana LRA coordinator.</li>
</ul>

<p>Both expose the same <code class="language-plaintext highlighter-rouge">/xfers</code> REST contract and are driven by the same shared
test suite (<code class="language-plaintext highlighter-rouge">transfer-tck</code>), so any difference you observe is a difference in
transaction strategy and nothing else.</p>

<h3 id="modules">Modules</h3>

<p>The following modules are part of the workshop project.</p>

<table>
  <thead>
    <tr>
      <th>Module</th>
      <th>Role</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">common</code></td>
      <td>Shared library: <code class="language-plaintext highlighter-rouge">Common</code> utility, the transfer DTOs (<code class="language-plaintext highlighter-rouge">TransferDto</code>, <code class="language-plaintext highlighter-rouge">TransferRequest</code>, <code class="language-plaintext highlighter-rouge">TransferResponse</code>, <code class="language-plaintext highlighter-rouge">TransferStatus</code>), the application exception hierarchy and the single <code class="language-plaintext highlighter-rouge">ApplicationExceptionMapper</code> that maps them to HTTP status codes.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account-repository</code></td>
      <td>Shared persistence layer for accounts: the <code class="language-plaintext highlighter-rouge">Account</code> entity, <code class="language-plaintext highlighter-rouge">AccountDto</code>, the <code class="language-plaintext highlighter-rouge">AccountRepository</code> interface and its two implementations. Depended on by <code class="language-plaintext highlighter-rouge">account</code> and by <code class="language-plaintext highlighter-rouge">transfer</code> — and pointedly <strong>not</strong> by <code class="language-plaintext highlighter-rouge">transfer-lra</code>.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer-tck</code></td>
      <td>The REST contract both transfer implementations must satisfy, as an abstract test class. Test tooling is at compile scope so consumers depend on it with <code class="language-plaintext highlighter-rouge">&lt;scope&gt;test&lt;/scope&gt;</code>.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code></td>
      <td>Account microservice (port 8081). Owns the <code class="language-plaintext highlighter-rouge">accounts</code> schema. CRUD + debit/credit, <strong>plus</strong> the LRA participant endpoints under <code class="language-plaintext highlighter-rouge">/lra/accounts</code>.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer</code></td>
      <td>XA coordinator (port 8080). Two XA datasources (<code class="language-plaintext highlighter-rouge">accounts</code>, <code class="language-plaintext highlighter-rouge">xfers</code>). Transfer CRUD plus the 2PC transfer operation.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer-lra</code></td>
      <td>Saga orchestrator (port 8090). One plain datasource for its own transfer log; reaches balances only through the account service’s API.</td>
    </tr>
  </tbody>
</table>

<p>Each repository has two implementations: an in-memory one (<code class="language-plaintext highlighter-rouge">DefaultAccountRepository</code>,
<code class="language-plaintext highlighter-rouge">DefaultTransferRepository</code>) and a JPA/Panache one (<code class="language-plaintext highlighter-rouge">AccountRepositoryXA</code>,
<code class="language-plaintext highlighter-rouge">TransferRepositoryXA</code>). Both are <code class="language-plaintext highlighter-rouge">@Alternative</code>, so neither is enabled by default;
each application picks the XA pair explicitly through
<code class="language-plaintext highlighter-rouge">quarkus.arc.selected-alternatives</code>. Only the XA implementations participate in 2PC —
the in-memory ones are there to run the services without a database.</p>

<p>All four modules carry the Jandex plugin so their <code class="language-plaintext highlighter-rouge">@Entity</code>, <code class="language-plaintext highlighter-rouge">@Provider</code> and CDI bean
classes are indexed when consumed as external dependencies.</p>

<h3 id="endpoints">Endpoints</h3>

<p>Three services expose an HTTP API, each with a Swagger UI at <code class="language-plaintext highlighter-rouge">/q/swagger-ui</code>. The
rows marked as callbacks are invoked by the LRA coordinator, not by clients.</p>

<table>
  <thead>
    <tr>
      <th>Service</th>
      <th>Method</th>
      <th>Path</th>
      <th>Purpose</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">GET</code></td>
      <td><code class="language-plaintext highlighter-rouge">/accounts</code></td>
      <td>List the accounts</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">POST</code></td>
      <td><code class="language-plaintext highlighter-rouge">/accounts</code></td>
      <td>Create an account</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">GET</code></td>
      <td><code class="language-plaintext highlighter-rouge">/accounts/{accountId}</code></td>
      <td>Read one account</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">PUT</code></td>
      <td><code class="language-plaintext highlighter-rouge">/accounts/{accountId}</code></td>
      <td>Update one account</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">DELETE</code></td>
      <td><code class="language-plaintext highlighter-rouge">/accounts/{accountId}</code></td>
      <td>Delete one account</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">POST</code></td>
      <td><code class="language-plaintext highlighter-rouge">/accounts/{accountId}/debit</code></td>
      <td>Debit, amount in the body</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">POST</code></td>
      <td><code class="language-plaintext highlighter-rouge">/accounts/{accountId}/credit</code></td>
      <td>Credit, amount in the body</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">POST</code></td>
      <td><code class="language-plaintext highlighter-rouge">/lra/accounts/{accountId}/debit</code></td>
      <td>Reserve a debit, <code class="language-plaintext highlighter-rouge">@LRA(MANDATORY)</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">POST</code></td>
      <td><code class="language-plaintext highlighter-rouge">/lra/accounts/{accountId}/credit</code></td>
      <td>Reserve a credit, <code class="language-plaintext highlighter-rouge">@LRA(MANDATORY)</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">GET</code></td>
      <td><code class="language-plaintext highlighter-rouge">/lra/accounts/{accountId}/availability</code></td>
      <td>Balance, held and available amounts</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">PUT</code></td>
      <td><code class="language-plaintext highlighter-rouge">/lra/accounts/complete</code></td>
      <td><code class="language-plaintext highlighter-rouge">@Complete</code> callback</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">PUT</code></td>
      <td><code class="language-plaintext highlighter-rouge">/lra/accounts/compensate</code></td>
      <td><code class="language-plaintext highlighter-rouge">@Compensate</code> callback</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">GET</code></td>
      <td><code class="language-plaintext highlighter-rouge">/lra/accounts/status</code></td>
      <td><code class="language-plaintext highlighter-rouge">@Status</code> callback</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code> (8081)</td>
      <td><code class="language-plaintext highlighter-rouge">DELETE</code></td>
      <td><code class="language-plaintext highlighter-rouge">/lra/accounts/forget</code></td>
      <td><code class="language-plaintext highlighter-rouge">@Forget</code> callback</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer</code> (8080)</td>
      <td><code class="language-plaintext highlighter-rouge">POST</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers</code></td>
      <td>Transfer, in one 2PC transaction</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer</code> (8080)</td>
      <td><code class="language-plaintext highlighter-rouge">GET</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers</code></td>
      <td>List the transfer log</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer</code> (8080)</td>
      <td><code class="language-plaintext highlighter-rouge">GET</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers/{transferId}</code></td>
      <td>Read one transfer</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer</code> (8080)</td>
      <td><code class="language-plaintext highlighter-rouge">PUT</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers/{transferId}</code></td>
      <td>Update one transfer</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer</code> (8080)</td>
      <td><code class="language-plaintext highlighter-rouge">DELETE</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers/{transferId}</code></td>
      <td>Delete one transfer</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer-lra</code> (8090)</td>
      <td><code class="language-plaintext highlighter-rouge">POST</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers</code></td>
      <td>Transfer, as a saga, <code class="language-plaintext highlighter-rouge">@LRA(REQUIRED)</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer-lra</code> (8090)</td>
      <td><code class="language-plaintext highlighter-rouge">GET</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers</code></td>
      <td>List the transfer log</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer-lra</code> (8090)</td>
      <td><code class="language-plaintext highlighter-rouge">GET</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers/{transferId}</code></td>
      <td>Read one transfer</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer-lra</code> (8090)</td>
      <td><code class="language-plaintext highlighter-rouge">PUT</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers/{transferId}</code></td>
      <td>Update one transfer</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer-lra</code> (8090)</td>
      <td><code class="language-plaintext highlighter-rouge">DELETE</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers/{transferId}</code></td>
      <td>Delete one transfer</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer-lra</code> (8090)</td>
      <td><code class="language-plaintext highlighter-rouge">PUT</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers/lra/complete</code></td>
      <td><code class="language-plaintext highlighter-rouge">@Complete</code> callback</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer-lra</code> (8090)</td>
      <td><code class="language-plaintext highlighter-rouge">PUT</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers/lra/compensate</code></td>
      <td><code class="language-plaintext highlighter-rouge">@Compensate</code> callback</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer-lra</code> (8090)</td>
      <td><code class="language-plaintext highlighter-rouge">GET</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers/lra/status</code></td>
      <td><code class="language-plaintext highlighter-rouge">@Status</code> callback</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer-lra</code> (8090)</td>
      <td><code class="language-plaintext highlighter-rouge">DELETE</code></td>
      <td><code class="language-plaintext highlighter-rouge">/xfers/lra/forget</code></td>
      <td><code class="language-plaintext highlighter-rouge">@Forget</code> callback</td>
    </tr>
  </tbody>
</table>

<p>Two things are worth reading off the table. The two transfer services present the
same <code class="language-plaintext highlighter-rouge">POST /xfers</code> contract, taking the same request body of
<code class="language-plaintext highlighter-rouge">{sourceAccountId, destinationAccountId, amount, currency}</code>, which is what allows
a single test class to exercise both. And the account service’s participant API
sits under its own path prefix instead of altering the existing endpoints, which
is why the saga work left the original account tests untouched.</p>

<h3 id="build--test">Build &amp; test</h3>

<p>Integration tests use Quarkus Dev Services (Testcontainers), so a running Docker
daemon is required. No manual database setup is needed. Each service seeds its own
data in dev/test profiles, on the behalf of the <code class="language-plaintext highlighter-rouge">import.sql</code> file for <code class="language-plaintext highlighter-rouge">account</code> and of the
<code class="language-plaintext highlighter-rouge">import-accounts.sql</code> for <code class="language-plaintext highlighter-rouge">transfer</code>. In the <code class="language-plaintext highlighter-rouge">prod</code> profile the account service
owns the <code class="language-plaintext highlighter-rouge">accounts</code> schema and no generation or seeding happens.</p>

<p>The following command runs the integration tests:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>mvn clean verify
</code></pre></div></div>

<p>Here is the list of the integration tests provided with the project:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">AbstractMoneyTransferContractIT</code> (transfer-tck): this is an abstract class serving as a superclass for all the integration tests. It defines the shared scenarios: happy
path, insufficient funds, unknown account, listing
and deletion. Assertions are on deltas, and the balance/count probes are
abstract, because the XA service can read the databases directly while the
saga service can only get them by calling the API over HTTP. Failure paths assert the response body
as well as the status. Both stacks must return the business error rather than
transaction plumbing, which a status-only assertion would not catch.</li>
  <li><code class="language-plaintext highlighter-rouge">MoneyTransferIT</code> (transfer): the contract against XA, with repository-based probes.</li>
  <li><code class="language-plaintext highlighter-rouge">MoneyTransferSagaIT</code> (transfer-lra): the contract against LRA, with HTTP probes,
plus saga-only assertions about the <code class="language-plaintext highlighter-rouge">COMPENSATED</code> audit row and released reservations.</li>
  <li><code class="language-plaintext highlighter-rouge">AccountResourceIT</code> (account): account CRUD, debit/credit, 404 on unknown account,
and rejection of overdrafts and invalid amounts.</li>
</ul>

<h3 id="run-the-full-stack">Run the full stack</h3>

<p>In order to run the full stack, production like, proceed as follows:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Build the container images (container-image.build=true is enabled)</span>
mvn clean package
docker compose up <span class="nt">-d</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">docker-compose.yaml</code> starts the whole comparison:</p>

<table>
  <thead>
    <tr>
      <th>Service</th>
      <th>Port</th>
      <th>Role</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">accounts-db</code></td>
      <td>5432</td>
      <td>Accounts, <code class="language-plaintext highlighter-rouge">max_prepared_transactions=100</code> for XA</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">xfers-db</code></td>
      <td>5433</td>
      <td>XA transfer log, <code class="language-plaintext highlighter-rouge">max_prepared_transactions=100</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">xfers-lra-db</code></td>
      <td>5434</td>
      <td>Saga transfer log (no XA needed)</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">lra-coordinator</code></td>
      <td>50000</td>
      <td><code class="language-plaintext highlighter-rouge">quay.io/jbosstm/lra-coordinator</code></td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">account</code></td>
      <td>8081</td>
      <td>CRUD + LRA participant</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer</code></td>
      <td>8080</td>
      <td>XA/2PC</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">transfer-lra</code></td>
      <td>8090</td>
      <td>Saga/LRA</td>
    </tr>
  </tbody>
</table>

<p>Both transfer services run against the same accounts, so you can drive the same
transfer through each and compare:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">BODY</span><span class="o">=</span><span class="s1">'{"sourceAccountId":"ACC1","destinationAccountId":"ACC2","amount":10.00,"currency":"EUR"}'</span>
curl <span class="nt">-s</span> <span class="nt">-XPOST</span> <span class="nt">-H</span> <span class="s1">'Content-Type: application/json'</span> <span class="nt">-d</span> <span class="s2">"</span><span class="nv">$BODY</span><span class="s2">"</span> http://localhost:8080/xfers  <span class="c"># XA</span>
curl <span class="nt">-s</span> <span class="nt">-XPOST</span> <span class="nt">-H</span> <span class="s1">'Content-Type: application/json'</span> <span class="nt">-d</span> <span class="s2">"</span><span class="nv">$BODY</span><span class="s2">"</span> http://localhost:8090/xfers  <span class="c"># Saga</span>
curl <span class="nt">-s</span> http://localhost:8081/lra/accounts/ACC1/availability                                <span class="c"># reservations</span>
</code></pre></div></div>

<p>Note <code class="language-plaintext highlighter-rouge">QUARKUS_LRA_BASE_URI</code> on the two participants: it is the address the
coordinator uses to call them back, and without it a participant advertises a URL
that is only meaningful from its own side of the network.</p>

<p>A Swagger interface is also available with each API, as explained at §11 Endpoints.
Additionally, the smoke test script <code class="language-plaintext highlighter-rouge">test-all.sh</code> is a very convenient way to make
sure to cover all the test case possible combinations. Here below is an example
of how to run it:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>docker compose up <span class="nt">-d</span>
<span class="nv">$ </span>./test-all.sh

<span class="o">===</span> Account API - http://localhost:8081/accounts <span class="o">===</span>
PASS POST /accounts <span class="o">(</span>create ACC90, 1000.00<span class="o">)</span> -&gt; 201
PASS POST /accounts <span class="o">(</span>create ACC91, 0.00<span class="o">)</span> -&gt; 201
PASS POST /accounts <span class="o">(</span>create ACC92, 10.00<span class="o">)</span> -&gt; 201
PASS GET /accounts/ACC90 -&gt; 200
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> <span class="o">==</span> 1000.00
PASS GET /accounts <span class="o">(</span>list<span class="o">)</span> -&gt; 200
PASS PUT /accounts/ACC90 <span class="o">(</span>rename owner<span class="o">)</span> -&gt; 200
PASS GET /accounts/ACC90 <span class="o">(</span>confirm rename<span class="o">)</span> -&gt; 200
PASS customerName updated
PASS POST /accounts/ACC90/credit <span class="o">(</span>50.00<span class="o">)</span> -&gt; 200
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> <span class="o">==</span> 1050.00
PASS POST /accounts/ACC90/debit <span class="o">(</span>200.00<span class="o">)</span> -&gt; 200
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> <span class="o">==</span> 850.00

<span class="o">===</span> Account API - negative cases <span class="o">===</span>
PASS POST credit <span class="o">(</span><span class="nt">-1</span>.00<span class="o">)</span> rejected -&gt; 400
PASS POST debit <span class="o">(</span>0.00<span class="o">)</span> rejected -&gt; 400
PASS POST debit <span class="o">(</span>999999.00<span class="o">)</span> insufficient funds -&gt; 400
PASS GET /accounts/NOSUCH -&gt; 404
PASS POST credit on unknown account -&gt; 404
PASS POST credit without Content-Type -&gt; 415
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> <span class="o">==</span> 850.00
PASS DELETE /accounts/ACC92 -&gt; 204
PASS GET deleted account -&gt; 404
PASS DELETE already-deleted account -&gt; 404

<span class="o">===</span> Account LRA participant API - http://localhost:8081/lra/accounts <span class="o">===</span>
PASS GET /lra/accounts/ACC90/availability -&gt; 200
PASS availability exposes balance/held/available
PASS POST /lra/accounts/ACC90/debit without LRA context -&gt; 412
PASS POST /lra/accounts/ACC90/credit without LRA context -&gt; 412
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> <span class="o">==</span> 850.00

<span class="o">===</span> XA Transfer API <span class="o">(</span>2PC<span class="o">)</span> - http://localhost:8080/xfers <span class="o">===</span>
PASS POST /xfers <span class="o">(</span>ACC90 -&gt; ACC91, 100.00<span class="o">)</span> -&gt; 200
PASS transferId returned: raizmjf
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> <span class="o">==</span> 750.00
PASS balance<span class="o">(</span>ACC91<span class="o">)</span> <span class="o">==</span> 100.00
PASS GET /xfers/raizmjf -&gt; 200
PASS GET /xfers <span class="o">(</span>list<span class="o">)</span> -&gt; 200
PASS PUT /xfers/raizmjf <span class="o">(</span>currency -&gt; USD<span class="o">)</span> -&gt; 200

<span class="o">===</span> XA Transfer API - negative cases <span class="o">(</span>nothing must move<span class="o">)</span> <span class="o">===</span>
PASS POST /xfers insufficient funds -&gt; 400
PASS POST /xfers negative amount -&gt; 400
PASS POST /xfers unknown <span class="nb">source</span> -&gt; 404
PASS POST /xfers unknown destination -&gt; 404
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> <span class="o">==</span> 750.00
PASS balance<span class="o">(</span>ACC91<span class="o">)</span> <span class="o">==</span> 100.00
PASS GET /xfers/NOSUCH -&gt; 404
PASS DELETE /xfers/raizmjf -&gt; 204
PASS GET deleted transfer -&gt; 404

<span class="o">===</span> Saga Transfer API <span class="o">(</span>LRA<span class="o">)</span> - http://localhost:8090/xfers <span class="o">===</span>
PASS POST /xfers <span class="o">(</span>ACC90 -&gt; ACC91, 25.00<span class="o">)</span> -&gt; 200
PASS transferId returned: etmlebm
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> <span class="o">==</span> 725.00
PASS balance<span class="o">(</span>ACC91<span class="o">)</span> <span class="o">==</span> 125.00
PASS GET /xfers/etmlebm -&gt; 200
PASS GET /xfers <span class="o">(</span>list, includes compensated<span class="o">)</span> -&gt; 200
PASS @Complete flipped the transfer to COMPLETED

<span class="o">===</span> Saga Transfer API - cancellation and compensation <span class="o">===</span>
PASS POST /xfers insufficient funds <span class="o">(</span>saga cancels<span class="o">)</span> -&gt; 400
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> <span class="o">==</span> 725.00
PASS balance<span class="o">(</span>ACC91<span class="o">)</span> <span class="o">==</span> 125.00
PASS @Compensate logged the cancelled transfer as COMPENSATED
PASS POST /xfers unknown destination <span class="o">(</span>saga cancels<span class="o">)</span> -&gt; 404
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> <span class="o">==</span> 725.00
PASS GET availability after settled sagas -&gt; 200
PASS held <span class="o">==</span> 0 <span class="o">(</span>no reservation left dangling<span class="o">)</span>
PASS PUT /xfers/etmlebm <span class="o">(</span>currency -&gt; USD<span class="o">)</span> -&gt; 200
PASS GET /xfers/NOSUCH -&gt; 404
PASS DELETE /xfers/etmlebm -&gt; 204
PASS GET deleted transfer -&gt; 404

<span class="o">===</span> Saga participant callbacks - @Status and @Forget <span class="o">(</span>transfer-lra<span class="o">)</span> <span class="o">===</span>
PASS coordinator started LRA: http://lra-coordinator:8080/lra-coordinator/0_ffffac120002_a03b_6ad35817_1ed
PASS POST /xfers with an externally started LRA -&gt; 412
PASS GET /xfers/lra/status <span class="o">(</span>@Status<span class="o">)</span> -&gt; 200
PASS @Status reports Compensated <span class="k">for </span>the cancelled LRA
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> moved by 0 <span class="o">(</span>now 725.00<span class="o">)</span>
PASS DELETE /xfers/lra/forget <span class="o">(</span>@Forget<span class="o">)</span> -&gt; 200
PASS GET /xfers/lra/status after @Forget -&gt; 404
PASS @Forget kept the transfer, only dropped its LRA <span class="nb">id</span>

<span class="o">===</span> Account LRA participant API - driving a saga by hand <span class="o">===</span>
PASS coordinator started LRA: http://lra-coordinator:8080/lra-coordinator/0_ffffac120002_a03b_6ad35817_1f2
PASS POST /lra/accounts/ACC90/debit <span class="o">(</span>40.00, <span class="k">in </span>LRA<span class="o">)</span> -&gt; 200
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> moved by 0 <span class="o">(</span>now 725.00<span class="o">)</span>
PASS held<span class="o">(</span>ACC90<span class="o">)</span> moved by 40.00 <span class="o">(</span>now 40.00<span class="o">)</span>
PASS POST /lra/accounts/ACC91/credit <span class="o">(</span>40.00, <span class="k">in </span>LRA<span class="o">)</span> -&gt; 200
PASS balance<span class="o">(</span>ACC91<span class="o">)</span> moved by 0 <span class="o">(</span>now 125.00<span class="o">)</span>
PASS coordinator closed the LRA -&gt; 200
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> moved by <span class="nt">-40</span>.00 <span class="o">(</span>now 685.00<span class="o">)</span>
PASS balance<span class="o">(</span>ACC91<span class="o">)</span> moved by 40.00 <span class="o">(</span>now 165.00<span class="o">)</span>
PASS held<span class="o">(</span>ACC90<span class="o">)</span> moved by 0 <span class="o">(</span>now 0<span class="o">)</span>

<span class="o">===</span> Account LRA participant API - cancelling a saga by hand <span class="o">===</span>
PASS coordinator started LRA: http://lra-coordinator:8080/lra-coordinator/0_ffffac120002_a03b_6ad35817_1f7
PASS POST /lra/accounts/ACC90/debit <span class="o">(</span>15.00, <span class="k">in </span>LRA<span class="o">)</span> -&gt; 200
PASS held<span class="o">(</span>ACC90<span class="o">)</span> moved by 15.00 <span class="o">(</span>now 15.00<span class="o">)</span>
PASS coordinator cancelled the LRA -&gt; 200
PASS balance<span class="o">(</span>ACC90<span class="o">)</span> moved by 0 <span class="o">(</span>now 685.00<span class="o">)</span>
PASS held<span class="o">(</span>ACC90<span class="o">)</span> moved by 0 <span class="o">(</span>now 0<span class="o">)</span>

<span class="o">===</span> Summary <span class="o">===</span>
87 passed, 0 failed
</code></pre></div></div>

<h2 id="12-comparison">12. Comparison</h2>

<p>The attached GitHub repository contains a multi-module Maven project with two
implementations. The
first uses JTA and XA to obtain a two-phase commit, and is contained entirely in
the <code class="language-plaintext highlighter-rouge">transfer</code> module. The second uses MicroProfile LRA, and is necessarily
spread across two modules: <code class="language-plaintext highlighter-rouge">transfer-lra</code> orchestrates the saga, while <code class="language-plaintext highlighter-rouge">account</code>
takes part in it. That difference in shape is not an accident of packaging. A
JTA coordinator that enlists resource managers directly can live in a single 
module, the <code class="language-plaintext highlighter-rouge">transfer</code> one, whereas a saga cannot exist unless its participants
are reachable and callable, hence the necessity for it to live in two modules,
<code class="language-plaintext highlighter-rouge">transfer-lra</code> and <code class="language-plaintext highlighter-rouge">account</code>.</p>

<p>Both implementations satisfy the same test contract. The following differences
are therefore differences of mechanism and of consequence, not of capability.</p>

<table>
  <thead>
    <tr>
      <th>Dimension</th>
      <th>XA and two-phase commit</th>
      <th>Saga and LRA</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Coordinator</td>
      <td>Embedded in the application process</td>
      <td>Separate process, must call participants back</td>
    </tr>
    <tr>
      <td>Data ownership</td>
      <td>Coordinator holds the resource managers, so services share a database</td>
      <td>Each service retains its own data</td>
    </tr>
    <tr>
      <td>Isolation</td>
      <td>Complete; no intermediate state is observable</td>
      <td>Absent by design; a reservation is observable while in flight</td>
    </tr>
    <tr>
      <td>Failure</td>
      <td>Rollback leaves no trace whatsoever</td>
      <td>Leaves a record that the operation was attempted and undone</td>
    </tr>
    <tr>
      <td>Locks</td>
      <td>Held between prepare and commit</td>
      <td>None held across the action</td>
    </tr>
    <tr>
      <td>Availability</td>
      <td>Participants block if the coordinator fails while in doubt</td>
      <td>Participants remain available; completion may occur later</td>
    </tr>
    <tr>
      <td>Location of difficulty</td>
      <td>Infrastructure, written once</td>
      <td>Application code, written for each operation</td>
    </tr>
    <tr>
      <td>Failure of the undo</td>
      <td>Not applicable; nothing was committed</td>
      <td>Possible, unless reservations are used</td>
    </tr>
  </tbody>
</table>

<p>Two entries deserve comment.</p>

<p>The row concerning failure is frequently presented as an advantage of 2PC on the
grounds that the rollbacks are clean. It may equally be regarded as a loss of 
information. A cancelled saga records that a transfer was attempted and
subsequently undone, which is an audit trail that a rollback cannot produce
because the rows were never committed. Whether this constitutes an advantage
depends entirely on whether the business is required to account for attempts as
well as for outcomes, and this is a question for the domain rather than for the
architecture.</p>

<p>The row concerning the location of difficulty is, in my opinion, the
one most often omitted from comparisons. 2PC is difficult once, in
infrastructure maintained by specialists. Sagas are difficult repeatedly, in
application code and this argument is important.</p>

<p>The correct conclusion is not that one approach supersedes the other. It is that
the choice is determined by whether the resource managers can be co-located under
a single coordinator. If they can, 2PC provides a stronger guarantee
for less application code. If they cannot, because the services are genuinely
independent or the resources do not support XA, then a saga is not the inferior
option but the only option, and the engineering effort should be directed at
implementing it correctly rather than at regretting the atomicity that was never
available.</p>

<h2 id="13-the-present-and-the-future">13. The Present and the Future</h2>

<p>Two-phase commit is not disappearing. It remains appropriate wherever resources
can be co-located, and a significant proportion of enterprise data continues to
reside in exactly such arrangements. Reports of its obsolescence generally
originate from contexts in which it was never applicable.</p>

<p>Sagas are becoming ordinary. What is changing is the level of abstraction at which
they are expressed. Handwritten orchestration is giving way to specified
protocols such as LRA, to workflow engines that record the state of long-running
processes durably, and to durable execution platforms in which the compensation
logic is expressed as ordinary code. The direction of travel is consistent: the difficulty is being moved
back out of application code and into infrastructure, which is where the industry
placed it in the first place, some thirty years ago, and where it appears to
belong.</p>

<p>Two developments merit attention. The first is the growing use of the outbox
pattern with event streaming, which achieves atomicity between a database change
and a message by writing both to the same database and publishing asynchronously.
This is neither 2PC nor a saga in the classical sense, and for many integration
problems it is a better answer than either. The second is the increasing
availability of formal verification tools for distributed protocols, which offers
some prospect that compensation logic might eventually be checked rather than
merely reviewed.</p>

<p>The underlying tension, however, is not a matter of technology and will not be
resolved by these developments. Atomicity across independent parties
requires either that they transfer autonomy to a coordinator or that they accept
observable intermediate states. The FLP (<em>Fischer, Lynch and Paterson</em>) result and its relatives indicate that no
implementation will escape this choice. What improves is the quality of the tools
with which each side of the choice may be pursued, and the clarity with which the
choice is presented to the practitioners.</p>

<p>The most costly systems are not those that chose two-phase commit, nor those that
chose sagas, but those that believed they had chosen the former while in fact
operating the latter, without compensations.</p>

<hr />

<h2 id="references-and-further-reading">References and Further Reading</h2>

<ul>
  <li>Gray, J. <em>Notes on Data Base Operating Systems</em>, 1978.</li>
  <li>Fischer, M., Lynch, N., Paterson, M. <em>Impossibility of Distributed Consensus
with One Faulty Process</em>, Journal of the ACM, 1985.</li>
  <li>Garcia-Molina, H., Salem, K. <em>Sagas</em>, ACM SIGMOD, 1987.</li>
  <li>X/Open. <em>Distributed Transaction Processing: The XA Specification</em>.</li>
  <li>Object Management Group. <em>Object Transaction Service</em>.</li>
  <li>Eclipse MicroProfile. <em>MicroProfile LRA Specification</em>.</li>
  <li>The accompanying source code, <a href="https://github.com/nicolasduminil/quarkus-distributed-tx"><code class="language-plaintext highlighter-rouge">quarkus-distributed-tx</code></a>,
containing both implementations, the shared contract test suite and a Docker
Compose deployment that runs the two stacks side by side.</li>
</ul>]]></content><author><name>Nicolas DUMINIL</name></author><category term="Java" /><category term="Quarkus" /><category term="Microprofile" /><category term="2PC, JTA, XA" /><category term="LRA" /><category term="LinkedIn" /><category term="Dev" /><category term="Substack" /><category term="HackerNoon" /><summary type="html"><![CDATA[Abstract]]></summary></entry><entry><title type="html">Releasing Spring Boot Applications on Kubernetes (4)</title><link href="https://www.simplex-software.fr/posts-archive/sbk8s-4/" rel="alternate" type="text/html" title="Releasing Spring Boot Applications on Kubernetes (4)" /><published>2026-10-10T00:00:00+00:00</published><updated>2026-10-10T13:05:34+00:00</updated><id>https://www.simplex-software.fr/posts-archive/sbk8s-4</id><content type="html" xml:base="https://www.simplex-software.fr/posts-archive/sbk8s-4/"><![CDATA[<p>The <a href="https://www.simplex-software.fr/posts-archive/sbk8s-3/">previous post</a> in 
this series demonstrates how to deploy and run Spring Boot applications on K8s,
using the mutual TLS authentication. According to the proposed scenario, the TLS
hanshake is accepted or refused, depending wether the X509 certificate provided
by the client is signed by a trusted authority or not. While this scenario is 
a great improvment of our use case, from the security point of view, , it still
presented a drawback. The application itself has no idea who the caller is and 
every certificate signed by the trusted CA is equally, anonymously accepted.</p>

<p>In this 4th part we’re pushing authentication a step further. Here, Spring Security
reads the client certificate that already satisfied the handshake, extracts its
subject Common Name and maps it to a named principal with roles. The certificate
stops being a mere door key and becomes the user’s identity. Endpoints are then
authorized on that
identity.</p>

<p>You can find the project in the same <a href="https://github.com/nicolasduminil/sb-k8s.git">GitHub repository</a>, on the <code class="language-plaintext highlighter-rouge">mtls-security</code> branch.</p>

<h1 id="identity-based-authorization-with-spring-security-x509">Identity-based authorization with Spring Security X.509</h1>

<p>The mTLS handshake is unchanged. The property <code class="language-plaintext highlighter-rouge">server.ssl.client-auth = need</code> 
defined in the <code class="language-plaintext highlighter-rouge">application.properties</code> file still requires a CA-signed client 
certificate. What is new is a Spring Security filter chain declared in the class
<code class="language-plaintext highlighter-rouge">SecurityConfig</code>, configured for X.509 authentication, as shown below:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>@Configuration
@EnableWebSecurity
@EnableMethodSecurity(jsr250Enabled = true)
public class SecurityConfig
{
  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception
  {
    return http
      .authorizeHttpRequests(auth -&gt; auth.anyRequest().authenticated())
      .x509(x509 -&gt; x509
      .subjectPrincipalRegex("CN=(.*?)(?:,|$)")
      .userDetailsService(userDetailsService()))
      .csrf(AbstractHttpConfigurer::disable)
      .build();
  }

  @Bean
  public UserDetailsService userDetailsService()
  {
    UserDetails admin = User.withUsername("sb-k8s-admin")
      .password("{noop}unused")
      .roles("ADMIN", "USER")
      .build();
    UserDetails user = User.withUsername("sb-k8s-user")
      .password("{noop}unused")
      .roles("USER")
      .build();
    return new InMemoryUserDetailsManager(admin, user);
  }
}
</code></pre></div></div>

<p>In the listing above the expression <code class="language-plaintext highlighter-rouge">x509().subjectPrincipalRegex("CN=(.*?)(?:,|$)")</code>
 pulls the CN out of the certificate subject as the principal name. The filter 
 chain carries a single baseline rule, <code class="language-plaintext highlighter-rouge">anyRequest().authenticated()</code>, so every
 call is at least a certificate-resolved identity. Then a <code class="language-plaintext highlighter-rouge">UserDetailsService</code>
 resolves that name to roles. In our case, the principal <code class="language-plaintext highlighter-rouge">CN=sb-k8s-admin</code> is 
 assigned the <code class="language-plaintext highlighter-rouge">ROLE_ADMIN</code> and the <code class="language-plaintext highlighter-rouge">ROLE_USER</code> roles while the principal <code class="language-plaintext highlighter-rouge">CN=sb-k8s-user</code>
 is assigned the <code class="language-plaintext highlighter-rouge">ROLE_USER</code> role.</p>

<p>The annotation <code class="language-plaintext highlighter-rouge">@EnableMethodSecurity(jsr250Enabled = true)</code> activates the 
 JSR-250 annotations on the controller class <code class="language-plaintext highlighter-rouge">K8sSbController</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>@RestController
public class K8sSbController
{
  @RolesAllowed("USER")
  @GetMapping("/hello/{who}")
  public String sayHello(@PathVariable String who, Authentication authentication)
  {
    return "Hello %s, greeted by %s".formatted(who, authentication.getName());
  }

  @RolesAllowed("USER")
  @GetMapping("/whoami")
  public Map&lt;String, Object&gt; whoami(Authentication authentication)
  {
    return Map.of(
      "identity", authentication.getName(),
      "authorities", authentication.getAuthorities().stream()
      .map(GrantedAuthority::getAuthority)
      .toList());
  }

  @RolesAllowed("ADMIN")
  @GetMapping("/admin")
  public String admin(Authentication authentication)
  {
    return "Hello %s, you have elevated (admin) access".formatted(authentication.getName());
  }
}
</code></pre></div></div>

<p>Here the endpoint <code class="language-plaintext highlighter-rouge">/admin</code> is allowed for prinicpals having the <code class="language-plaintext highlighter-rouge">ROLE_ADMIN</code> role
while the <code class="language-plaintext highlighter-rouge">/whoami</code> and <code class="language-plaintext highlighter-rouge">/hello/{who}</code> ones are allowed for prinicpals having 
either the <code class="language-plaintext highlighter-rouge">ROLE_ADMIN</code> or <code class="language-plaintext highlighter-rouge">ROLE_USER</code> roles.</p>

<p>The decisive consequence: a certificate that is CA-signed, such that so it clears
the handshake, but whose CN is not in the <code class="language-plaintext highlighter-rouge">UserDetailsService</code>, is rejected at the
authentication layer. Hence, CA trust alone is no longer enough.</p>

<h2 id="what-changed-compared-to-the-mtls-branch">What changed compared to the <code class="language-plaintext highlighter-rouge">mtls</code> branch</h2>

<table>
  <thead>
    <tr>
      <th>Artifact</th>
      <th>Change</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">pom.xml</code></td>
      <td>Adds <code class="language-plaintext highlighter-rouge">spring-boot-starter-security</code>; test-only <code class="language-plaintext highlighter-rouge">spring-security-test</code>/<code class="language-plaintext highlighter-rouge">webmvc-test</code> (unit tier) and <code class="language-plaintext highlighter-rouge">rest-assured</code> (e2e tier, via failsafe; Groovy pinned to 4.0.x, the line REST Assured expects).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">SecurityConfig.java</code></td>
      <td>New — the X.509 filter chain (baseline <code class="language-plaintext highlighter-rouge">anyRequest().authenticated()</code>), CN→principal regex, the in-memory identity registry and <code class="language-plaintext highlighter-rouge">@EnableMethodSecurity(jsr250Enabled = true)</code>.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">K8sSbController.java</code></td>
      <td><code class="language-plaintext highlighter-rouge">/hello/{who}</code> now names the authenticated caller; adds <code class="language-plaintext highlighter-rouge">/whoami</code> (echoes the resolved identity + authorities) and an admin-only <code class="language-plaintext highlighter-rouge">/admin</code>. Roles are enforced with JSR-250 <code class="language-plaintext highlighter-rouge">@RolesAllowed</code>.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">k8s/client-certificate.yaml</code></td>
      <td>Now issues three client certificates with different CNs — <code class="language-plaintext highlighter-rouge">sb-k8s-admin</code>, <code class="language-plaintext highlighter-rouge">sb-k8s-user</code> and <code class="language-plaintext highlighter-rouge">sb-k8s-intruder</code> (CA-signed but not a known identity, for the e2e rejection case) — replacing the single <code class="language-plaintext highlighter-rouge">sb-k8s-client</code>.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">skaffold.yaml</code> / <code class="language-plaintext highlighter-rouge">redeploy.sh</code> / <code class="language-plaintext highlighter-rouge">start-all.sh</code></td>
      <td>The <code class="language-plaintext highlighter-rouge">reset</code> hook deletes the new secrets; the scripts extract the three client certs and build the PKCS12 keystores (<code class="language-plaintext highlighter-rouge">admin.p12</code>/<code class="language-plaintext highlighter-rouge">user.p12</code>/<code class="language-plaintext highlighter-rouge">intruder.p12</code> + <code class="language-plaintext highlighter-rouge">truststore.p12</code>) that <code class="language-plaintext highlighter-rouge">SecurityE2eIT</code> loads.</td>
    </tr>
  </tbody>
</table>

<h2 id="testing-identity-based-authorization">Testing identity-based authorization</h2>

<p>Deploy and extract both identities (<code class="language-plaintext highlighter-rouge">redeploy.sh</code> does this automatically on this
branch):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ./redeploy.sh mtls-security
$ kubectl port-forward svc/sb-k8s 8443:8443      # or: skaffold dev --port-forward
</code></pre></div></div>

<p>Confirm the two client certificates are issued:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl get certificate
NAME           READY   SECRET              AGE
sb-k8s         True    sb-k8s-cert         1m
sb-k8s-ca      True    sb-k8s-ca           1m
sb-k8s-admin   True    sb-k8s-admin-cert   1m
sb-k8s-user    True    sb-k8s-user-cert    1m
</code></pre></div></div>

<p>Either identity can greet, and the response names the caller — the CN travelled
all the way from the certificate to the controller:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert user.crt --key user.key https://localhost:8443/hello/nicolas
Hello nicolas, greeted by sb-k8s-user

$ curl --cacert ca.crt --cert admin.crt --key admin.key https://localhost:8443/whoami
{"identity":"sb-k8s-admin","authorities":["ROLE_ADMIN","ROLE_USER"]}
</code></pre></div></div>

<p>Only the admin identity reaches the admin-only endpoint. The user certificate is
a perfectly valid, CA-signed, authenticated identity — it simply lacks the role,
so it is rejected with <code class="language-plaintext highlighter-rouge">403 Forbidden</code> inside the application, not at the
handshake:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert admin.crt --key admin.key https://localhost:8443/admin
Hello sb-k8s-admin, you have elevated (admin) access

$ curl --cacert ca.crt --cert user.crt --key user.key https://localhost:8443/admin
{"status":403,"error":"Forbidden", ...}
</code></pre></div></div>

<p>That 403 is the whole point of this branch: two callers that are indistinguishable
to plain mTLS (both hold a CA-signed certificate) are told apart by <em>identity</em>.
Dropping the client certificate entirely still fails at the handshake exactly as
on the <code class="language-plaintext highlighter-rouge">mtls</code> branch, since <code class="language-plaintext highlighter-rouge">client-auth = need</code> is unchanged.</p>

<h3 id="testing">Testing</h3>

<p>The tests come in two tiers:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">SecurityAuthorizationTest</code> — unit (<code class="language-plaintext highlighter-rouge">mvn test</code>). A fast <code class="language-plaintext highlighter-rouge">@WebMvcTest</code>
MockMvc slice with no cluster. <code class="language-plaintext highlighter-rouge">@WithUserDetails("sb-k8s-admin"/"sb-k8s-user")</code>
loads the principal from the real <code class="language-plaintext highlighter-rouge">UserDetailsService</code>, so the CN→roles mapping
and the <code class="language-plaintext highlighter-rouge">@RolesAllowed</code> rules are exercised; only the TLS/certificate handshake
itself is out of scope.</li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">SecurityE2eIT</code> — end to end (<code class="language-plaintext highlighter-rouge">mvn verify</code>). A REST Assured test that
hits the <em>deployed</em> app on <code class="language-plaintext highlighter-rouge">https://localhost:8443</code> over a real mTLS handshake,
presenting the actual cluster-issued certificates. It reuses the PKCS12
keystores that <code class="language-plaintext highlighter-rouge">start-all.sh</code> / <code class="language-plaintext highlighter-rouge">redeploy.sh</code> build from the extracted certs, so
it covers the two cases the unit tier structurally cannot: a missing certificate
(handshake refused) and a CA-signed certificate with an unknown CN — the
<code class="language-plaintext highlighter-rouge">sb-k8s-intruder</code> cert — rejected by the app. It self-skips when no cluster
is up, so <code class="language-plaintext highlighter-rouge">mvn verify</code> stays green on a bare checkout; to run it for real:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ./start-all.sh                              # or ./redeploy.sh mtls-security
$ kubectl port-forward svc/sb-k8s 8443:8443   # if not already forwarding
$ mvn verify
</code></pre></div>    </div>
  </li>
</ul>

<h2 id="certificate-renewal-and-rotation">Certificate renewal and rotation</h2>

<p><code class="language-plaintext highlighter-rouge">cert-manager</code> owns the whole lifecycle of the server certificate, not just its first
issuance. <code class="language-plaintext highlighter-rouge">renewBefore</code> on <code class="language-plaintext highlighter-rouge">k8s/certificate.yaml</code> says how long before expiry a
replacement is issued. When that moment arrives cert-manager signs a new server
certificate from <code class="language-plaintext highlighter-rouge">ca-issuer</code>, rebuilds the JKS keystore and truststore, and
overwrites the <code class="language-plaintext highlighter-rouge">sb-k8s-cert</code> secret in place. The secret name never changes, only
its contents.</p>

<p>The property that makes this branch interesting is its stable CA. The server
leaf is signed by <code class="language-plaintext highlighter-rouge">ca-issuer</code>, which is backed by the long-lived <code class="language-plaintext highlighter-rouge">sb-k8s-ca</code>
certificate (see <a href="#why-a-ca-hierarchy-is-required">Why a CA hierarchy is required</a>).
So while the server leaf rotates, <code class="language-plaintext highlighter-rouge">ca.crt</code>, as the CA the client pins with <code class="language-plaintext highlighter-rouge">--cacert</code>,
does not change. That is exactly what lets a client keep trusting the connection
across a rotation, and it is the difference from the self-signed <code class="language-plaintext highlighter-rouge">cert-manager</code>
branch, where <code class="language-plaintext highlighter-rouge">ca.crt</code> rotates together with the leaf and this whole walkthrough is
impossible.</p>

<h3 id="trying-it-end-to-end">Trying it end to end</h3>

<p>The steps below are the runnable version of everything in this section, framed as
two experiments:</p>

<ul>
  <li>without in-place reload the pod eventually breaks;</li>
  <li>with it, the pod keeps working.</li>
</ul>

<p>Here are the steps:</p>

<ol>
  <li>
    <p>With the cluster running, as documented on the <code class="language-plaintext highlighter-rouge">master</code> branch, shorten the server certificate so it expires within the hour by adding <code class="language-plaintext highlighter-rouge">duration: 1h</code> to <code class="language-plaintext highlighter-rouge">k8s/certificate.yaml</code> (it already carries <code class="language-plaintext highlighter-rouge">renewBefore: 5m</code>):</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>spec:
  duration: 1h
  renewBefore: 5m
</code></pre></div>    </div>
  </li>
  <li>
    <p>If you manually have activated the port forwarding then kill it. Then, redeploy by running <code class="language-plaintext highlighter-rouge">redeploy.sh</code>:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ./redeploy.sh mtls-security
</code></pre></div>    </div>
  </li>
  <li>
    <p>Forward the port either manually, as shown below, or use <code class="language-plaintext highlighter-rouge">skaffold dev --port-forward</code>, which survives pod restarts:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl port-forward svc/sb-k8s 8443:8443
</code></pre></div>    </div>
  </li>
  <li>
    <p>Confirm that the <code class="language-plaintext highlighter-rouge">curl</code> request below works.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert admin.crt --key admin.key https://localhost:8443/hello/nicolas
Hello nicolas, greeted by sb-k8s-admin
</code></pre></div>    </div>
  </li>
</ol>

<p>Experiment A — no <code class="language-plaintext highlighter-rouge">reload-on-update</code>: the pod breaks after an hour</p>

<ol>
  <li>
    <p>Go to do something else and come back after an hour. <code class="language-plaintext highlighter-rouge">cert-manager</code> rotated
the secret ~5 minutes before expiry, but the running app never reloaded it and is
still serving the certificate that it have read at startup, which has now expired, so the same call fails:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert admin.crt --key admin.key \
    https://localhost:8443/hello/nicolas
curl: (60) SSL certificate problem: certificate has expired
</code></pre></div>    </div>
  </li>
</ol>

<p>Experiment B — with <code class="language-plaintext highlighter-rouge">reload-on-update</code>: the pod keeps working</p>

<ol>
  <li>
    <p>Enable in-place reload by adding to the bundle in <code class="language-plaintext highlighter-rouge">k8s/configmap.yaml</code>:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>spring.ssl.bundle.jks.server.reload-on-update = true
</code></pre></div>    </div>
  </li>
  <li>
    <p>Redeploy and forward again:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ./redeploy.sh mtls-security
$ kubectl port-forward svc/sb-k8s 8443:8443
</code></pre></div>    </div>
  </li>
  <li>
    <p>Come back again after an hour and repeat the exact same call. This time the
server reloaded the rotated certificate in place, and because <code class="language-plaintext highlighter-rouge">ca.crt</code> (the CA)
never changed, the unchanged client command still succeeds:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert admin.crt --key admin.key https://localhost:8443/hello/nicolas
Hello nicolas, greeted by sb-k8s-admin
</code></pre></div>    </div>
  </li>
</ol>

<p>The subsections below explain each moving part.</p>

<h3 id="watching-it-happen">Watching it happen</h3>

<p>By default, <code class="language-plaintext highlighter-rouge">cert-manager</code> issues a 90-day certificate, so nothing visibly rotates
during a test session. To watch a full cycle on a human timescale, after having
shortened the server certificate’s lifetime, as explained above, look at the
serial inside the issued certificate:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl get secret sb-k8s-cert -o jsonpath='{.data.tls\.crt}' \
    | base64 -d | openssl x509 -noout -serial -dates
</code></pre></div></div>

<p>You’ll se two timestamps:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">notAfter</code> is the expiry;</li>
  <li><code class="language-plaintext highlighter-rouge">renewalTime</code> is when cert-manager plans to rotate.</li>
</ul>

<p>This serial is the cleanest rotation fingerprint. It changes on every renewal, 
while <code class="language-plaintext highlighter-rouge">ca.crt</code> stays the same.</p>

<h3 id="does-the-running-application-pick-up-the-new-certificate">Does the running application pick up the new certificate?</h3>

<p>Rotating the secret is only half the story. The pod mounts <code class="language-plaintext highlighter-rouge">keystore.jks</code> and
<code class="language-plaintext highlighter-rouge">truststore.jks</code> from that secret (see <code class="language-plaintext highlighter-rouge">CERT_PATH</code> in <code class="language-plaintext highlighter-rouge">k8s/deployment.yaml</code>), and
two things stand between a rotated secret and a server that actually serves the new
certificate.</p>

<p>First, <code class="language-plaintext highlighter-rouge">kubelet</code> refreshes the mounted files a short while after the secret changes
(up to ~60–90 s), not instantly. Second, and more importantly, Spring Boot reads
the keystore when it builds its SSL context. According to the property 
<code class="language-plaintext highlighter-rouge">server.ssl.bundle = server</code> in <code class="language-plaintext highlighter-rouge">k8s/configmap.yaml</code>, this project configures 
TLS through an SSL bundle, rather than the classic <code class="language-plaintext highlighter-rouge">server.ssl.key-store</code>, and 
that matters: SSL bundles can be reloaded without a restart.</p>

<p>Add the following property to the <code class="language-plaintext highlighter-rouge">configmap.yaml</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>spring.ssl.bundle.jks.server.reload-on-update = true
</code></pre></div></div>

<p>and Spring Boot watches the keystore and truststore files and rebuilds the SSL
context in place when <code class="language-plaintext highlighter-rouge">cert-manager</code> rotates them, so the new certificate is served
with no downtime. Without that property, the bundle is read once at startup and a
rotated secret is ignored until the pod restarts:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl rollout restart deployment/sb-k8s
</code></pre></div></div>

<p>To verify end-to-end whether the server presents the new certificate, compare 
the currently served against the old one. In order to do that, before rotating, 
with the port-forward still running, record the current serial and
keep a copy of the leaf:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ echo | openssl s_client -connect localhost:8443 2&gt;/dev/null \
    | openssl x509 -noout -serial -enddate         # note the serial + notAfter
$ echo | openssl s_client -connect localhost:8443 2&gt;/dev/null \
    | openssl x509 &gt; old-cert.pem                  # keep the old leaf
</code></pre></div></div>

<p>Wait for <code class="language-plaintext highlighter-rouge">renewBefore</code> to fire and repeat. Read the wire again:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ echo | openssl s_client -connect localhost:8443 2&gt;/dev/null \
    | openssl x509 -noout -serial -enddate
</code></pre></div></div>

<p>The renewed certificate works when this handshake still succeeds and the
serial has changed to a later <code class="language-plaintext highlighter-rouge">notAfter</code>. Confirm a real mTLS request still goes
through with the same <code class="language-plaintext highlighter-rouge">ca.crt</code> and client certificate as before:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert admin.crt --key admin.key \
    https://localhost:8443/hello/nicolas
Hello nicolas, greeted by sb-k8s-admin
</code></pre></div></div>

<p>To confirm that the old certificate is retired:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl x509 -in old-cert.pem -noout -checkend 0    # "is it expired right now?"
Certificate expired

$ openssl verify -CAfile ca.crt old-cert.pem          # validate old leaf against the CA
old-cert.pem: ... certificate has expired
</code></pre></div></div>

<p>As opposed to before, when the old one-hour certificate reaches its <code class="language-plaintext highlighter-rouge">notAfter</code>, 
both commands still report it valid. Now, once it expires they flip as shown above.</p>

<h3 id="watching-an-expired-certificate-get-rejected">Watching an expired certificate get rejected</h3>

<p>The checks above validate a saved file; the more convincing proof is a live
handshake refused because the certificate on the wire has expired. That happens
naturally when <code class="language-plaintext highlighter-rouge">reload-on-update</code> is <em>not</em> enabled: the server keeps serving the
certificate it read at startup and ignores the rotated secret, so once that
in-memory certificate passes its one-hour <code class="language-plaintext highlighter-rouge">notAfter</code> the running server is presenting
an expired certificate. From then on the client rejects it:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert admin.crt --key admin.key \
    https://localhost:8443/hello/nicolas
curl: (60) SSL certificate problem: certificate has expired

$ echo | openssl s_client -connect localhost:8443 2&gt;/dev/null | grep -i verify
Verify return code: 10 (certificate has expired)
</code></pre></div></div>

<p>(The exact wording varies a little between curl/OpenSSL versions.) This is the
concrete reason to enable <code class="language-plaintext highlighter-rouge">reload-on-update</code> or restart the pod on rotation: left
alone, a long-running pod will eventually serve a stale, expired certificate and
break TLS on its own — even though cert-manager rotated the secret an hour earlier.</p>

<blockquote>
  <p>The client certificates rotate too. <code class="language-plaintext highlighter-rouge">sb-k8s-admin</code> and <code class="language-plaintext highlighter-rouge">sb-k8s-user</code> renew
on their own lifecycle, and because <code class="language-plaintext highlighter-rouge">client-auth = need</code> the <em>server</em> validates
them against its truststore on every handshake. An expired client certificate is
refused exactly like the missing one in
<a href="#the-mtls-check-client-authentication">The mTLS check</a> — the mutual counterpart
of the rejection above.</p>
</blockquote>

<h2 id="switching-branches-and-redeploying">Switching branches and redeploying</h2>

<p>This repository has more than one branch: <code class="language-plaintext highlighter-rouge">cert-manager</code>, <code class="language-plaintext highlighter-rouge">mtls</code>, <code class="language-plaintext highlighter-rouge">mtls-security</code>, …. Switching
between them is a <em>cluster</em> operation. <code class="language-plaintext highlighter-rouge">minikube</code> and <code class="language-plaintext highlighter-rouge">cert-manager</code> stay up the
whole time, only the application’s own resources are recreated. In particular 
there is no need to stop/restart minikube or to build by hand since <code class="language-plaintext highlighter-rouge">skaffold run</code>
does it in one step.</p>

<p>The <code class="language-plaintext highlighter-rouge">redeploy.sh</code> helper automates the full sequence:</p>

<ul>
  <li>tear down:</li>
  <li>optionally switch branch;</li>
  <li>rebuild and redeploy;</li>
  <li>
    <p>re-extract <code class="language-plaintext highlighter-rouge">ca.crt</code> and, on <code class="language-plaintext highlighter-rouge">mtls</code>, the client certificate, or on <code class="language-plaintext highlighter-rouge">mtls-security</code>, the <code class="language-plaintext highlighter-rouge">admin</code> and <code class="language-plaintext highlighter-rouge">user</code> client certificates.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ./redeploy.sh               # redeploy the current branch
$ ./redeploy.sh mtls-security # switch to mtls-security, then redeploy
$ ./redeploy.sh mtls          # switch to mtls, then redeploy
$ ./redeploy.sh cert-manager  # switch to cert-manager, then redeploy
</code></pre></div>    </div>
  </li>
</ul>

<p>Under the hood it runs <code class="language-plaintext highlighter-rouge">skaffold delete</code>, <code class="language-plaintext highlighter-rouge">git checkout &lt;branch&gt;</code>, then
<code class="language-plaintext highlighter-rouge">skaffold run -p reset</code>. The <code class="language-plaintext highlighter-rouge">reset</code> profile, defined in <code class="language-plaintext highlighter-rouge">skaffold.yaml</code>,
deletes the <code class="language-plaintext highlighter-rouge">cert-manager</code>-generated secrets <em>before</em> deploying, so the new branch
gets freshly issued certificates. This matters when switching branches because
those secrets are not garbage-collected on their own and their contents differ
between branches.</p>

<p>Two things the script takes care of that are easy to forget by hand:</p>

<ul>
  <li>the <code class="language-plaintext highlighter-rouge">ca.crt</code> changes between branches (different issuer), so it must be
re-extracted;</li>
  <li>a manual <code class="language-plaintext highlighter-rouge">kubectl port-forward</code> dies with the old pod and has to be restarted. Using <code class="language-plaintext highlighter-rouge">skaffold dev --port-forward</code> avoids that entirely.</li>
</ul>

<p>Enjoy !</p>]]></content><author><name>Nicolas DUMINIL</name></author><category term="Java" /><category term="Spring Boot 4" /><category term="Kubernetes" /><category term="Minikube" /><category term="LinkedIn" /><category term="DZone" /><summary type="html"><![CDATA[The previous post in this series demonstrates how to deploy and run Spring Boot applications on K8s, using the mutual TLS authentication. According to the proposed scenario, the TLS hanshake is accepted or refused, depending wether the X509 certificate provided by the client is signed by a trusted authority or not. While this scenario is a great improvment of our use case, from the security point of view, , it still presented a drawback. The application itself has no idea who the caller is and every certificate signed by the trusted CA is equally, anonymously accepted.]]></summary></entry><entry><title type="html">Releasing Spring Boot Applications on Kubernetes (3)</title><link href="https://www.simplex-software.fr/posts-archive/sbk8s-3/" rel="alternate" type="text/html" title="Releasing Spring Boot Applications on Kubernetes (3)" /><published>2026-09-11T00:00:00+00:00</published><updated>2026-09-11T13:05:34+00:00</updated><id>https://www.simplex-software.fr/posts-archive/sbk8s-3</id><content type="html" xml:base="https://www.simplex-software.fr/posts-archive/sbk8s-3/"><![CDATA[<p>The <a href="https://www.simplex-software.fr/posts-archive/sbk8s-2/">previous post</a> in this series demonstrates how to deploy and run Spring Boot
applications on K8s, using one way TLS and a X509 certificate that is provisioned,
renewed and rotated automatically by <code class="language-plaintext highlighter-rouge">cert-manager</code>. While this scenario provides
advanced functionalities and unquestionable advantages, it presents an issue: 
<em>anyone</em> who can reach the socket gets served.</p>

<p>This 3nd part turns on mutual TLS (mTLS), so the server also
requires the <em>client</em> to present a certificate signed by a trusted CA. A caller
without a valid client certificate is rejected during the TLS handshake. This 
authentication happens at the transport layer.</p>

<p>You can find the project in the same <a href="https://github.com/nicolasduminil/sb-k8s.git">GitHub repository</a>, on the <code class="language-plaintext highlighter-rouge">mtls</code> branch.</p>

<h2 id="a-ca-hierarchy-is-required">A CA hierarchy is required</h2>

<p>Plain mutual TLS cannot work with a single <em>self-signed</em> issuer: every
certificate would be its own, unrelated root, so the server would have no way to
validate a client certificate. This 3rd part therefore introduces a tiny in-cluster
PKI (in <code class="language-plaintext highlighter-rouge">k8s/issuers.yaml</code>):</p>

<ol>
  <li>a self-signed issuer named <code class="language-plaintext highlighter-rouge">selfsigned-issuer</code> is used only to bootstrap the CA;</li>
  <li>a CA certificate named <code class="language-plaintext highlighter-rouge">sb-k8s-ca</code> with <code class="language-plaintext highlighter-rouge">isCA: true</code> is the shared root of trust;</li>
  <li>a CA issuer named <code class="language-plaintext highlighter-rouge">ca-issuer</code> signs both the server and the client certificates.</li>
</ol>

<p>Because both certificates share the same CA, the server’s truststore, which
<code class="language-plaintext highlighter-rouge">cert-manager</code> initializes with that CA, validates the client certificate and vice
versa. Namespaced <code class="language-plaintext highlighter-rouge">Issuer</code>s are used rather than <code class="language-plaintext highlighter-rouge">ClusterIssuer</code>s so the CA secret
stays in the <code class="language-plaintext highlighter-rouge">default</code> namespace, as opposed to the CA <code class="language-plaintext highlighter-rouge">ClusterIssuer</code>, used 
previously, that would have expected it in <code class="language-plaintext highlighter-rouge">cert-manager</code>’s cluster-resource 
namespace instead.</p>

<h2 id="what-changed-compared-to-the-cert-manager-branch">What changed compared to the <code class="language-plaintext highlighter-rouge">cert-manager</code> branch</h2>

<table>
  <thead>
    <tr>
      <th>Artifact</th>
      <th>Change</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">k8s/issuers.yaml</code></td>
      <td>New — replaces <code class="language-plaintext highlighter-rouge">cluster-issuer.yaml</code>. Holds the self-signed <code class="language-plaintext highlighter-rouge">Issuer</code>, the CA <code class="language-plaintext highlighter-rouge">Certificate</code>, and the CA <code class="language-plaintext highlighter-rouge">Issuer</code> described above.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">k8s/certificate.yaml</code></td>
      <td>The server certificate is now signed by <code class="language-plaintext highlighter-rouge">ca-issuer</code> (was the self-signed issuer) and declares <code class="language-plaintext highlighter-rouge">usages: [server auth, …]</code>.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">k8s/client-certificate.yaml</code></td>
      <td>New — a client certificate (<code class="language-plaintext highlighter-rouge">sb-k8s-client</code>, <code class="language-plaintext highlighter-rouge">usages: [client auth, …]</code>) signed by the same <code class="language-plaintext highlighter-rouge">ca-issuer</code>, stored as PEM in the <code class="language-plaintext highlighter-rouge">sb-k8s-client-cert</code> secret.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">k8s/configmap.yaml</code></td>
      <td>Adds <code class="language-plaintext highlighter-rouge">server.ssl.client-auth = need</code>, which makes a client certificate mandatory.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">skaffold.yaml</code></td>
      <td>Deploys <code class="language-plaintext highlighter-rouge">issuers.yaml</code> and <code class="language-plaintext highlighter-rouge">client-certificate.yaml</code>; no longer references <code class="language-plaintext highlighter-rouge">cluster-issuer.yaml</code>.</td>
    </tr>
  </tbody>
</table>

<p>Deploy it exactly as before:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ skaffold run
</code></pre></div></div>

<p>and confirm all three certificates are issued:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl get certificate

NAME            READY   SECRET               AGE
sb-k8s          True    sb-k8s-cert          1m
sb-k8s-ca       True    sb-k8s-ca            1m
sb-k8s-client   True    sb-k8s-client-cert   1m
</code></pre></div></div>

<h2 id="testing-mtls">Testing mTLS</h2>

<p>First extract the client certificate, its key and the CA from the <code class="language-plaintext highlighter-rouge">sb-k8s-client-cert</code>
secret so <code class="language-plaintext highlighter-rouge">curl</code> can use them:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl get secret sb-k8s-client-cert -o jsonpath='{.data.tls\.crt}' | base64 -d &gt; client.crt
$ kubectl get secret sb-k8s-client-cert -o jsonpath='{.data.tls\.key}' | base64 -d &gt; client.key
$ kubectl get secret sb-k8s-client-cert -o jsonpath='{.data.ca\.crt}'  | base64 -d &gt; ca.crt
</code></pre></div></div>

<p>Port-forward the service (leave it running in its own terminal):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl port-forward svc/sb-k8s 8443:8443
</code></pre></div></div>

<h3 id="the-quick-way-skips-server-verification">The quick way (skips server verification)</h3>

<p>You can pass <code class="language-plaintext highlighter-rouge">-k</code> (or <code class="language-plaintext highlighter-rouge">--insecure</code>) to skip verifying the <em>server’s</em> certificate.
On this branch you still have to send the <em>client</em> certificate as <code class="language-plaintext highlighter-rouge">-k</code> only turns
off the client-side identity check of the server, it does not disable TLS or
waive the server’s <code class="language-plaintext highlighter-rouge">client-auth = need</code> requirement:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl -k --cert client.crt --key client.key https://localhost:8443/hello/nicolas
Hello nicolas
</code></pre></div></div>

<h3 id="the-proper-way-verifies-the-server-too">The proper way (verifies the server too)</h3>

<p><code class="language-plaintext highlighter-rouge">-k</code> is not required since the server certificate is verifiable, it is just signed by
a CA (<code class="language-plaintext highlighter-rouge">sb-k8s-ca</code>) that your machine does not trust by default. <code class="language-plaintext highlighter-rouge">cert-manager</code> writes
that CA into the <code class="language-plaintext highlighter-rouge">ca.crt</code> extracted above, so pass it with <code class="language-plaintext highlighter-rouge">--cacert</code> to validate
the server for real. The certificate has a <code class="language-plaintext highlighter-rouge">localhost</code> SAN, which is why
<code class="language-plaintext highlighter-rouge">localhost</code> is accepted:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert client.crt --key client.key https://localhost:8443/hello/nicolas
Hello nicolas
</code></pre></div></div>

<p>If you point <code class="language-plaintext highlighter-rouge">curl</code> at a CA that did <em>not</em> sign the server certificate or omit
<code class="language-plaintext highlighter-rouge">--cacert</code> so it falls back to the system trust store, then the request fails with
<code class="language-plaintext highlighter-rouge">unable to get local issuer certificate</code>. That is the proof the server is really
being verified.</p>

<h3 id="the-mtls-check-client-authentication">The mTLS check (client authentication)</h3>

<p>Now drop the client certificate but keep verifying the server. The server aborts
the handshake:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt https://localhost:8443/hello/nicolas
curl: (56) OpenSSL SSL_read: ... alert certificate required
</code></pre></div></div>

<p>That rejection is the proof that mutual TLS is enforced: only callers holding a
certificate signed by <code class="language-plaintext highlighter-rouge">sb-k8s-ca</code> are allowed through.</p>

<h3 id="trusting-the-ca-machine-wide-optional">Trusting the CA machine-wide (optional)</h3>

<p>To avoid passing <code class="language-plaintext highlighter-rouge">--cacert</code> every time, install the CA into your operating
system’s trust store once (you still need <code class="language-plaintext highlighter-rouge">--cert</code>/<code class="language-plaintext highlighter-rouge">--key</code> for client auth):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo cp ca.crt /usr/local/share/ca-certificates/sb-k8s-ca.crt
$ sudo update-ca-certificates
$ curl --cert client.crt --key client.key https://localhost:8443/hello/nicolas
Hello nicolas
</code></pre></div></div>

<blockquote>
  <p><strong>Note</strong> — at this stage authentication stops at the transport layer: the
server accepts or refuses the handshake but the application itself does not yet
know <em>who</em> the caller is. Mapping the client certificate to an authenticated
principal (and authorizing on it) with Spring Security X.509 is the subject of a
later episode.</p>
</blockquote>

<h2 id="certificate-renewal-and-rotation">Certificate renewal and rotation</h2>

<p><code class="language-plaintext highlighter-rouge">cert-manager</code> owns the whole lifecycle of the server certificate, not just its first
issuance. <code class="language-plaintext highlighter-rouge">renewBefore</code> on <code class="language-plaintext highlighter-rouge">k8s/certificate.yaml</code> says how long before expiry a
replacement is issued. When that moment arrives cert-manager signs a new server
certificate from <code class="language-plaintext highlighter-rouge">ca-issuer</code>, rebuilds the JKS keystore and truststore, and
overwrites the <code class="language-plaintext highlighter-rouge">sb-k8s-cert</code> secret in place. The secret name never changes, only
its contents.</p>

<p>The property that makes this scenario interesting is its stable CA. The server
leaf is signed by <code class="language-plaintext highlighter-rouge">ca-issuer</code>, which is backed by the long-lived <code class="language-plaintext highlighter-rouge">sb-k8s-ca</code>
certificate (see <a href="#a-ca-hierarchy-is-required">A CA hierarchy is required</a>).
So while the server leaf rotates, <code class="language-plaintext highlighter-rouge">ca.crt</code>, as the CA the client pins with <code class="language-plaintext highlighter-rouge">--cacert</code>,
does not change. That is exactly what lets a client keep trusting the connection
across a rotation, and it is the difference from the previous self-signed <code class="language-plaintext highlighter-rouge">cert-manager</code>
scenario, where <code class="language-plaintext highlighter-rouge">ca.crt</code> rotates together with the leaf and this whole walkthrough is
impossible.</p>

<h3 id="trying-it-end-to-end">Trying it end to end</h3>

<p>The steps below are the runnable version of everything in this section, framed as
two experiments:</p>

<ul>
  <li>without in-place reload the pod eventually breaks;</li>
  <li>with it, the pod keeps working.</li>
</ul>

<p>Here are the steps:</p>

<ol>
  <li>
    <p>With the cluster running, as documented on the <code class="language-plaintext highlighter-rouge">master</code> branch, shorten the server certificate so it expires within the hour by adding <code class="language-plaintext highlighter-rouge">duration: 1h</code> to <code class="language-plaintext highlighter-rouge">k8s/certificate.yaml</code> (it already carries <code class="language-plaintext highlighter-rouge">renewBefore: 5m</code>):</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>spec:
  duration: 1h
  renewBefore: 5m
</code></pre></div>    </div>
  </li>
  <li>
    <p>If you manually have activated the port forwarding then kill it. Then, redeploy by running <code class="language-plaintext highlighter-rouge">redeploy.sh</code>:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ./redeploy.sh mtls
</code></pre></div>    </div>
  </li>
  <li>
    <p>Forward the port either manually, as shown below, or use <code class="language-plaintext highlighter-rouge">skaffold dev --port-forward</code>, which survives pod restarts:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl port-forward svc/sb-k8s 8443:8443
</code></pre></div>    </div>
  </li>
  <li>
    <p>Confirm that the <code class="language-plaintext highlighter-rouge">curl</code> request below works.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert client.crt --key client.key https://localhost:8443/hello/nicolas
Hello nicolas
</code></pre></div>    </div>
  </li>
</ol>

<p><strong>Experiment A — no <code class="language-plaintext highlighter-rouge">reload-on-update</code>: the pod breaks after an hour</strong></p>

<ol>
  <li>
    <p>Go to do something else and come back after an hour. <code class="language-plaintext highlighter-rouge">cert-manager</code> rotated
the secret ~5 minutes before expiry, but the running app never reloaded it and is
still serving the certificate that it has read at startup, which has now expired, so the same call fails:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert client.crt --key client.key \
    https://localhost:8443/hello/nicolas
curl: (60) SSL certificate problem: certificate has expired
</code></pre></div>    </div>
  </li>
</ol>

<p><strong>Experiment B — with <code class="language-plaintext highlighter-rouge">reload-on-update</code>: the pod keeps working</strong></p>

<ol>
  <li>
    <p>Enable in-place reload by adding to the bundle in <code class="language-plaintext highlighter-rouge">k8s/configmap.yaml</code>:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>spring.ssl.bundle.jks.server.reload-on-update = true
</code></pre></div>    </div>
  </li>
  <li>
    <p>Redeploy and forward again:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ./redeploy.sh mtls
$ kubectl port-forward svc/sb-k8s 8443:8443
</code></pre></div>    </div>
  </li>
  <li>
    <p>Come back again after an hour and repeat the exact same call. This time the
server reloaded the rotated certificate in place, and because <code class="language-plaintext highlighter-rouge">ca.crt</code> (the CA)
never changed, the unchanged client command still succeeds:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert client.crt --key client.key https://localhost:8443/hello/nicolas
Hello nicolas
</code></pre></div>    </div>
  </li>
</ol>

<p>The subsections below explain each moving part.</p>

<h3 id="watching-it-happen">Watching it happen</h3>

<p>By default, <code class="language-plaintext highlighter-rouge">cert-manager</code> issues a 90-day certificate, so nothing visibly rotates
during a test session. To watch a full cycle on a human timescale, after having
shortened the server certificate’s lifetime, as explained above, look at the
serial inside the issued certificate:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl get secret sb-k8s-cert -o jsonpath='{.data.tls\.crt}' \
    | base64 -d | openssl x509 -noout -serial -dates
</code></pre></div></div>

<p>You’ll se two timestamps:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">notAfter</code> is the expiry;</li>
  <li><code class="language-plaintext highlighter-rouge">renewalTime</code> is when cert-manager plans to rotate.</li>
</ul>

<p>This serial is the cleanest rotation fingerprint. It changes on every renewal, 
while <code class="language-plaintext highlighter-rouge">ca.crt</code> stays the same.</p>

<h3 id="does-the-running-application-pick-up-the-new-certificate">Does the running application pick up the new certificate?</h3>

<p>Rotating the secret is only half the story. The pod mounts <code class="language-plaintext highlighter-rouge">keystore.jks</code> and
<code class="language-plaintext highlighter-rouge">truststore.jks</code> from that secret (see <code class="language-plaintext highlighter-rouge">CERT_PATH</code> in <code class="language-plaintext highlighter-rouge">k8s/deployment.yaml</code>), and
two things stand between a rotated secret and a server that actually serves the new
certificate.</p>

<p>First, <code class="language-plaintext highlighter-rouge">kubelet</code> refreshes the mounted files a short while after the secret changes
(up to ~60–90 s), not instantly. Second, and more importantly, Spring Boot reads
the keystore when it builds its SSL context. According to the property 
<code class="language-plaintext highlighter-rouge">server.ssl.bundle = server</code> in <code class="language-plaintext highlighter-rouge">k8s/configmap.yaml</code>, this project configures 
TLS through an SSL bundle, rather than the classic <code class="language-plaintext highlighter-rouge">server.ssl.key-store</code>, and 
that matters: SSL bundles can be reloaded without a restart.</p>

<p>Add the following property to the <code class="language-plaintext highlighter-rouge">configmap.yaml</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>spring.ssl.bundle.jks.server.reload-on-update = true
</code></pre></div></div>

<p>and Spring Boot watches the keystore and truststore files and rebuilds the SSL
context in place when <code class="language-plaintext highlighter-rouge">cert-manager</code> rotates them, so the new certificate is served
with no downtime. Without that property, the bundle is read once at startup and a
rotated secret is ignored until the pod restarts:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl rollout restart deployment/sb-k8s
</code></pre></div></div>

<p>To verify end-to-end whether the server presents the new certificate, compare 
the currently served against the old one. In order to do that, before rotating, 
with the port-forward still running, record the current serial and
keep a copy of the leaf:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ echo | openssl s_client -connect localhost:8443 2&gt;/dev/null \
    | openssl x509 -noout -serial -enddate         # note the serial + notAfter
$ echo | openssl s_client -connect localhost:8443 2&gt;/dev/null \
    | openssl x509 &gt; old-cert.pem                  # keep the old leaf
</code></pre></div></div>

<p>Wait for <code class="language-plaintext highlighter-rouge">renewBefore</code> to fire and repeat. Read the wire again:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ echo | openssl s_client -connect localhost:8443 2&gt;/dev/null \
    | openssl x509 -noout -serial -enddate
</code></pre></div></div>

<p>The renewed certificate works when this handshake still succeeds and the
serial has changed to a later <code class="language-plaintext highlighter-rouge">notAfter</code>. Confirm a real mTLS request still goes
through with the same <code class="language-plaintext highlighter-rouge">ca.crt</code> and client certificate as before:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert client.crt --key client.key \
    https://localhost:8443/hello/nicolas
Hello nicolas
</code></pre></div></div>

<p>To confirm that the old certificate is retired:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ openssl x509 -in old-cert.pem -noout -checkend 0    # "is it expired right now?"
Certificate expired

$ openssl verify -CAfile ca.crt old-cert.pem          # validate old leaf against the CA
old-cert.pem: ... certificate has expired
</code></pre></div></div>

<p>As opposed to before, when the old one-hour certificate reaches its <code class="language-plaintext highlighter-rouge">notAfter</code>, 
both commands still reported it valid, now, once it expires, they flip as shown above.</p>

<h3 id="watching-an-expired-certificate-get-rejected">Watching an expired certificate get rejected</h3>

<p>The checks above validate a saved file; the more convincing proof is a live
handshake refused because the certificate on the wire has expired. That happens
naturally when <code class="language-plaintext highlighter-rouge">reload-on-update</code> is <em>not</em> enabled: the server keeps serving the
certificate it read at startup and ignores the rotated secret, so once that
in-memory certificate passes its one-hour <code class="language-plaintext highlighter-rouge">notAfter</code> the running server is presenting
an expired certificate. From then on the client rejects it:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert client.crt --key client.key \
    https://localhost:8443/hello/nicolas
curl: (60) SSL certificate problem: certificate has expired

$ echo | openssl s_client -connect localhost:8443 2&gt;/dev/null | grep -i verify
Verify return code: 10 (certificate has expired)
</code></pre></div></div>

<p>(The exact wording varies a little between curl/OpenSSL versions.) This is the
concrete reason to enable <code class="language-plaintext highlighter-rouge">reload-on-update</code> or restart the pod on rotation: left
alone, a long-running pod will eventually serve a stale, expired certificate and
break TLS on its own — even though cert-manager rotated the secret an hour earlier.</p>

<blockquote>
  <p><strong>The client certificate rotates too.</strong> <code class="language-plaintext highlighter-rouge">sb-k8s-client</code> renews on its own
lifecycle, and because <code class="language-plaintext highlighter-rouge">client-auth = need</code> the <em>server</em> validates it against its
truststore on every handshake. An expired client certificate is refused exactly
like the missing one in
<a href="#the-mtls-check-client-authentication">The mTLS check</a> — the mutual counterpart
of the rejection above.</p>
</blockquote>

<h2 id="switching-branches-and-redeploying">Switching branches and redeploying</h2>

<p>This repository has more than one branch: <code class="language-plaintext highlighter-rouge">cert-manager</code>, <code class="language-plaintext highlighter-rouge">mtls</code>, …. Switching
between them is a <em>cluster</em> operation. <code class="language-plaintext highlighter-rouge">minikube</code> and <code class="language-plaintext highlighter-rouge">cert-manager</code> stay up the
whole time, only the application’s own resources are recreated. In particular 
there is no need to stop/restart minikube or to build by hand since <code class="language-plaintext highlighter-rouge">skaffold run</code>
does it in one step.</p>

<p>The <code class="language-plaintext highlighter-rouge">redeploy.sh</code> helper automates the full sequence:</p>

<ul>
  <li>tear down:</li>
  <li>optionally switch branch;</li>
  <li>rebuild and redeploy;</li>
  <li>
    <p>re-extract <code class="language-plaintext highlighter-rouge">ca.crt</code> and, on the <code class="language-plaintext highlighter-rouge">mtls</code> branch, the client certificate.</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ./redeploy.sh              # redeploy the current branch
$ ./redeploy.sh mtls         # switch to mtls, then redeploy
$ ./redeploy.sh cert-manager # switch to cert-manager, then redeploy
</code></pre></div>    </div>
  </li>
</ul>

<p>Under the hood it runs <code class="language-plaintext highlighter-rouge">skaffold delete</code>, <code class="language-plaintext highlighter-rouge">git checkout &lt;branch&gt;</code>, then
<code class="language-plaintext highlighter-rouge">skaffold run -p reset</code>. The <code class="language-plaintext highlighter-rouge">reset</code> profile, defined in <code class="language-plaintext highlighter-rouge">skaffold.yaml</code>,
deletes the <code class="language-plaintext highlighter-rouge">cert-manager</code>-generated secrets <em>before</em> deploying, so the new branch
gets freshly issued certificates. This matters when switching branches because
those secrets are not garbage-collected on their own and their contents differ
between branches.</p>

<p>Two things the script takes care of that are easy to forget by hand:</p>

<ul>
  <li>the <code class="language-plaintext highlighter-rouge">ca.crt</code> changes between branches (different issuer), so it must be
re-extracted;</li>
  <li>a manual <code class="language-plaintext highlighter-rouge">kubectl port-forward</code> dies with the old pod and has to be restarted. Using <code class="language-plaintext highlighter-rouge">skaffold dev --port-forward</code> avoids that entirely.</li>
</ul>

<h2 id="cert-manager-vs-mtls-the-subtle-difference"><code class="language-plaintext highlighter-rouge">cert-manager</code> vs <code class="language-plaintext highlighter-rouge">mtls</code>: the subtle difference</h2>

<p>The <code class="language-plaintext highlighter-rouge">cert-manager</code> and <code class="language-plaintext highlighter-rouge">mtls</code> branches look almost identical: same cert-manager,
same JKS keystore, same Skaffold flow, HTTPS on 8443. Yet they answer two
different questions, and the difference is easy to miss:</p>

<ul>
  <li>
    <p><code class="language-plaintext highlighter-rouge">cert-manager</code> does one-way TLS. The server presents a certificate,
the connection is encrypted and the client can verify the server. The client
is not authenticated. So this succeeds with no client certificate:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt https://localhost:8443/hello/nicolas
Hello nicolas
</code></pre></div>    </div>
  </li>
  <li>
    <p><code class="language-plaintext highlighter-rouge">mtls</code> does mutual TLS. Everything above, plus the server
requires and verifies a client certificate. This is set by the property <code class="language-plaintext highlighter-rouge">server.ssl.client-auth = need</code>.
The exact same command above is now rejected during the handshake:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt https://localhost:8443/hello/nicolas
curl: (56) ... tlsv13 alert certificate required
</code></pre></div>    </div>

    <p>and you must present a client certificate signed by the trusted CA:</p>

    <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl --cacert ca.crt --cert client.crt --key client.key https://localhost:8443/hello/nicolas
Hello nicolas
</code></pre></div>    </div>
  </li>
</ul>

<p>The subtlety is that the two are indistinguishable until a client connects
without a certificate: only then does <code class="language-plaintext highlighter-rouge">mtls</code> reject it. Under the hood the
enabling differences are small but essential: <code class="language-plaintext highlighter-rouge">mtls</code> adds
<code class="language-plaintext highlighter-rouge">server.ssl.client-auth = need</code>, a client certificate and a CA hierarchy, consisting in a self-signed root with the CA
issuer signing both server and client certificates, so the server can validate the
client. 
The <code class="language-plaintext highlighter-rouge">cert-manager</code> branch instead uses a
single self-signed issuer and never asks the client for anything.</p>]]></content><author><name>Nicolas DUMINIL</name></author><category term="Java" /><category term="Spring Boot 4" /><category term="Kubernetes" /><category term="Minikube" /><category term="LinkedIn" /><category term="DZone" /><summary type="html"><![CDATA[The previous post in this series demonstrates how to deploy and run Spring Boot applications on K8s, using one way TLS and a X509 certificate that is provisioned, renewed and rotated automatically by cert-manager. While this scenario provides advanced functionalities and unquestionable advantages, it presents an issue: anyone who can reach the socket gets served.]]></summary></entry><entry><title type="html">Releasing Spring Boot Applications on Kubernetes (2)</title><link href="https://www.simplex-software.fr/posts-archive/sbk8s-2/" rel="alternate" type="text/html" title="Releasing Spring Boot Applications on Kubernetes (2)" /><published>2026-08-21T00:00:00+00:00</published><updated>2026-08-21T13:05:34+00:00</updated><id>https://www.simplex-software.fr/posts-archive/sbk8s-2</id><content type="html" xml:base="https://www.simplex-software.fr/posts-archive/sbk8s-2/"><![CDATA[<p>The <a href="https://www.simplex-software.fr/posts-archive/sbk8s/">previous post</a> in this series demonstrates how to deploy and run Spring Boot
applications on K8s without having to manually craft YAML files. This 2nd part
takes it one step further and serves the very same <code class="language-plaintext highlighter-rouge">/hello/{who}</code> endpoint, but
over HTTPS on port 8443, using an X.509 certificate that is provisioned, renewed
and rotated automatically by <a href="https://cert-manager.io/">cert-manager</a>.It requires
<code class="language-plaintext highlighter-rouge">docker</code> and <code class="language-plaintext highlighter-rouge">minikube</code> installed locally, as well as having a docker hub account.</p>

<p>You can find the project in the same <a href="https://github.com/nicolasduminil/sb-k8s.git">GitHub repository</a>, on the <code class="language-plaintext highlighter-rouge">cert-manager</code> branch.</p>

<p>Instead of manually running <code class="language-plaintext highlighter-rouge">kubectl create deployment</code> and <code class="language-plaintext highlighter-rouge">kubectl expose</code>, as
we did previously, this branch describes the whole desired state as a set of 
YAML manifests (under <code class="language-plaintext highlighter-rouge">k8s/</code>) and lets <a href="https://skaffold.dev/">Skaffold</a> build the image and apply the
manifests in one shot.</p>

<h2 id="managing-certificates-with-cert-manager">Managing Certificates with <code class="language-plaintext highlighter-rouge">cert-manager</code></h2>

<p>In order to setup HTTPS connections to our endpoint we need to generate an X509
certificate for it such that any client be able to validate the service identity.
Otherwise a malicious service might impersonate the ours and causing annoiances.
The primary tools for dealing with X509 certificates are <code class="language-plaintext highlighter-rouge">openssl</code> and <code class="language-plaintext highlighter-rouge">keytool</code>.
Both offer commands for creating public/private key pairs as well as signing and
converting keys and certificates.</p>

<p>Certificates have an expiration date which, once exceeded, they become automatically
lapsed and, hence, should be replaced by new ones. This process is known as 
<em>certificate rotation</em> and is a critical one, enterprise-wide, as it’s quite easy
to imagine the effects of expired certificates preventing applications and services
to communicate. hence the importance of automating this process.</p>

<p>With Kubernetes, this automation cand be achived using <code class="language-plaintext highlighter-rouge">cert-manager</code>, a native
tool for managing X.509 certificates. Among its main automated functionalities:</p>

<ul>
  <li>obtaining X.509 certificates from the most popular public issuers;</li>
  <li>validating their activation period as being between their associated <code class="language-plaintext highlighter-rouge">notBefore</code> and <code class="language-plaintext highlighter-rouge">notAfter</code> timestamps;</li>
  <li>renewing them before they expire.</li>
</ul>

<p>A Kubernetes operator able to generate, rotate and save certificates as secrets
is available and can be installed via its official Helm chart, as we will show
in a moment.</p>

<h2 id="handling-k8s-manifest-files-with-skaffold">Handling K8s manifest files with <code class="language-plaintext highlighter-rouge">skaffold</code></h2>

<p><code class="language-plaintext highlighter-rouge">skaffold</code>, as defined by its maintainers in the official GIT <a href="https://github.com/GoogleContainerTools/skaffold.git">repository</a>,
is “a command line tool that facilitates continuous development for Kubernetes 
applications”. It can be used to build and deploy K8s controllers while avoiding
having to handle individual YAML files.</p>

<p>A <code class="language-plaintext highlighter-rouge">skaffold.yaml</code> file groups all the other YAML files a cluster needs to handle.
In our case, given that we need to deal with a half dozen of YAML files that 
define the deployment, the service, the certificate, the configmap, the secrets, etc.
it is much easir to group all these files in a <code class="language-plaintext highlighter-rouge">skaffold.yaml</code> one and perform
the required operation as described <a href="https://skaffold.dev/docs/install/">here</a>.</p>

<h2 id="the-manifest-files">The manifest files</h2>

<table>
  <thead>
    <tr>
      <th>Artifact</th>
      <th>Kind</th>
      <th>Purpose</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">k8s/cluster-issuer.yaml</code></td>
      <td><code class="language-plaintext highlighter-rouge">ClusterIssuer</code></td>
      <td>A cluster-wide, self-signed issuer (<code class="language-plaintext highlighter-rouge">ss-cluster-issuer</code>) used by cert-manager to sign the certificate.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">k8s/certificate.yaml</code></td>
      <td><code class="language-plaintext highlighter-rouge">Certificate</code></td>
      <td>Requests a certificate (<code class="language-plaintext highlighter-rouge">sb-k8s</code>) from the issuer. cert-manager stores the result in the <code class="language-plaintext highlighter-rouge">sb-k8s-cert</code> secret and, because of the <code class="language-plaintext highlighter-rouge">keystores.jks</code> block, also generates a JKS keystore and truststore protected by the password held in <code class="language-plaintext highlighter-rouge">jks-password-secret</code>. Uses an ECDSA/P-256 key, is valid for <code class="language-plaintext highlighter-rouge">sb-k8s</code> and <code class="language-plaintext highlighter-rouge">localhost</code>, and is renewed 5 minutes before expiry.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">k8s/secret.yaml</code></td>
      <td><code class="language-plaintext highlighter-rouge">Secret</code></td>
      <td>Holds the password (<code class="language-plaintext highlighter-rouge">jks-password-secret</code>) used both by cert-manager to create the JKS stores and by the application to open them. The password is given under <code class="language-plaintext highlighter-rouge">stringData</code> so Kubernetes base64-encodes it for us (a plaintext value under <code class="language-plaintext highlighter-rouge">data</code> would be interpreted as base64 and decode to invalid bytes).</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">k8s/configmap.yaml</code></td>
      <td><code class="language-plaintext highlighter-rouge">ConfigMap</code></td>
      <td>The externalised <code class="language-plaintext highlighter-rouge">application.properties</code>: switches the server to port <code class="language-plaintext highlighter-rouge">8443</code>, enables the Spring SSL <em>bundle</em> named <code class="language-plaintext highlighter-rouge">server</code>, and points the keystore/truststore locations at the mounted certificate.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">k8s/deployment.yaml</code></td>
      <td><code class="language-plaintext highlighter-rouge">Deployment</code></td>
      <td>Runs the application. Mounts the <code class="language-plaintext highlighter-rouge">sb-k8s-cert</code> secret (the JKS files) at <code class="language-plaintext highlighter-rouge">/opt/secret</code>, mounts the ConfigMap at <code class="language-plaintext highlighter-rouge">/config</code>, injects the keystore password via the <code class="language-plaintext highlighter-rouge">PASSWORD</code> env var, sets <code class="language-plaintext highlighter-rouge">CERT_PATH=/opt/secret</code>, and points Spring at the mounted config with <code class="language-plaintext highlighter-rouge">SPRING_CONFIG_ADDITIONAL_LOCATION=/config/application.properties</code>. Exposes the container on <code class="language-plaintext highlighter-rouge">8443</code>.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">k8s/service.yaml</code></td>
      <td><code class="language-plaintext highlighter-rouge">Service</code></td>
      <td>A <code class="language-plaintext highlighter-rouge">ClusterIP</code> service exposing port <code class="language-plaintext highlighter-rouge">8443</code>.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">skaffold.yaml</code></td>
      <td>Skaffold <code class="language-plaintext highlighter-rouge">Config</code></td>
      <td>Builds the image with Cloud Native Buildpacks (the Paketo <code class="language-plaintext highlighter-rouge">builder-jammy-base</code> builder, with <code class="language-plaintext highlighter-rouge">BP_JVM_VERSION=21</code>) and applies all the manifests above.</td>
    </tr>
  </tbody>
</table>

<h2 id="prerequisites">Prerequisites</h2>

<p>In addition to <code class="language-plaintext highlighter-rouge">docker</code>, <code class="language-plaintext highlighter-rouge">minikube</code>, <code class="language-plaintext highlighter-rouge">kubectl</code> and a DockerHub account already 
required by the <code class="language-plaintext highlighter-rouge">master</code> branch, you need:</p>

<ul>
  <li><a href="https://skaffold.dev/docs/install/"><code class="language-plaintext highlighter-rouge">skaffold</code></a>;</li>
  <li><a href="https://cert-manager.io/docs/installation/">cert-manager</a></li>
</ul>

<p>installed in the cluster (see below).</p>

<h2 id="building-deploying-and-running">Building, deploying and running</h2>

<p>In order to build and deploy the project proceed as documented below:</p>

<h3 id="1-start-minikube">1. Start minikube</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ minikube start
</code></pre></div></div>

<h3 id="2-install-cert-manager-in-the-cluster">2. Install cert-manager in the cluster</h3>

<p><code class="language-plaintext highlighter-rouge">cert-manager</code> is not part of Kubernetes and, consequently, it has to be installed
once per cluster. If it is already installed, skip this step, otherwise install
it as shown below:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.20.2/cert-manager.yaml
</code></pre></div></div>

<p>Wait until the three cert-manager components are up before going further:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl wait --for=condition=Available --timeout=120s -n cert-manager deployment --all

deployment.apps/cert-manager condition met
deployment.apps/cert-manager-cainjector condition met
deployment.apps/cert-manager-webhook condition met
</code></pre></div></div>

<h3 id="3-build-the-image-and-deploy-everything-with-skaffold">3. Build the image and deploy everything with Skaffold</h3>

<p>From the project root, a single command builds the image and applies all the
manifests listed in <code class="language-plaintext highlighter-rouge">skaffold.yaml</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ skaffold run
</code></pre></div></div>

<p>Use <code class="language-plaintext highlighter-rouge">skaffold dev</code> instead if you want Skaffold to keep watching your sources and
redeploy on every change; <code class="language-plaintext highlighter-rouge">Ctrl-C</code> then automatically cleans up what it created.</p>

<p>Behind the scenes Skaffold creates, in order:</p>

<ul>
  <li>the cluster issuer;</li>
  <li>the X509 certificate that refers the cluster issuer;</li>
  <li>the K8s config map containing the Spring Boot application properties. 
These properties are generally provided as the <code class="language-plaintext highlighter-rouge">application.properties</code> 
file but here we need to mount them at <code class="language-plaintext highlighter-rouge">/config</code>.</li>
  <li>the K8s secret used as a password required by the <code class="language-plaintext highlighter-rouge">keystore</code> where 
the <code class="language-plaintext highlighter-rouge">cert-manager</code> stores the private key and the associated X509 certificate;</li>
  <li>the K8s deployment;</li>
  <li>the K8s service.</li>
</ul>

<p>A couple of build details worth knowing:</p>

<ul>
  <li>The image is built with the Paketo <code class="language-plaintext highlighter-rouge">builder-jammy-base</code> builder and
<code class="language-plaintext highlighter-rouge">BP_JVM_VERSION=21</code>. The Google Cloud
buildpacks builder (<code class="language-plaintext highlighter-rouge">gcr.io/buildpacks/builder:v1</code>) is <em>not</em> used because its
Ubuntu 18.04 base does not offer a Java 21 runtime.</li>
  <li>The application container runs from <code class="language-plaintext highlighter-rouge">/workspace</code>, so Spring Boot’s default
<code class="language-plaintext highlighter-rouge">./config/</code> lookup would resolve to <code class="language-plaintext highlighter-rouge">/workspace/config</code>, not the ConfigMap
mounted at <code class="language-plaintext highlighter-rouge">/config</code>. That is why <code class="language-plaintext highlighter-rouge">deployment.yaml</code> sets
<code class="language-plaintext highlighter-rouge">SPRING_CONFIG_ADDITIONAL_LOCATION=/config/application.properties</code>. Without it
the server would ignore the ConfigMap and stay on the default HTTP port 8080.</li>
</ul>

<h3 id="4-check-that-the-certificate-has-been-issued">4. Check that the certificate has been issued</h3>

<p><code class="language-plaintext highlighter-rouge">cert-manager</code> needs a few seconds to sign the certificate and to write the JKS
keystore/truststore into the <code class="language-plaintext highlighter-rouge">sb-k8s-cert</code> secret:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl get certificate

NAME     READY   SECRET        AGE
sb-k8s   True    sb-k8s-cert   20s

$ kubectl get secret sb-k8s-cert -o jsonpath='{.data}' | tr ',' '\n'
</code></pre></div></div>

<p>You should see <code class="language-plaintext highlighter-rouge">keystore.jks</code> and <code class="language-plaintext highlighter-rouge">truststore.jks</code> entries alongside the usual
<code class="language-plaintext highlighter-rouge">tls.crt</code>/<code class="language-plaintext highlighter-rouge">tls.key</code>. If <code class="language-plaintext highlighter-rouge">READY</code> stays <code class="language-plaintext highlighter-rouge">False</code>, describe the resource to find out
why:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl describe certificate sb-k8s
</code></pre></div></div>

<h3 id="5-check-that-the-pod-is-running">5. Check that the pod is running</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl get pods

NAME                      READY   STATUS    RESTARTS   AGE
sb-k8s-6d4c9f8b7c-abcde   1/1     Running   0          30s
</code></pre></div></div>

<p>If needed, follow the application logs to confirm it started on the HTTPS port:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl logs -l app.kubernetes.io/name=sb-k8s -f
</code></pre></div></div>

<h2 id="testing-the-https-endpoint">Testing the HTTPS endpoint</h2>

<p>The service is of type <code class="language-plaintext highlighter-rouge">ClusterIP</code>, so it is only reachable from inside the
cluster. The easiest way to test it from your machine is to port-forward it:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl port-forward svc/sb-k8s 8443:8443
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">skaffold.yaml</code> also declares this forward, so you can let Skaffold manage it
instead, as it re-establishes the tunnel automatically whenever the pod is
replaced, which a manual <code class="language-plaintext highlighter-rouge">kubectl port-forward</code> does not:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ skaffold dev --port-forward
</code></pre></div></div>

<p>Note that <code class="language-plaintext highlighter-rouge">port-forward</code> is a local debugging convenience, not a way to <em>run</em> the
service. It is a single tunnel to one pod, tied to your machine. For real access
you would expose the service through a <code class="language-plaintext highlighter-rouge">NodePort</code>, a <code class="language-plaintext highlighter-rouge">LoadBalancer</code>
(<code class="language-plaintext highlighter-rouge">minikube tunnel</code>), or an <code class="language-plaintext highlighter-rouge">Ingress</code>. Keep in mind the certificate’s SANs are
<code class="language-plaintext highlighter-rouge">sb-k8s</code> and <code class="language-plaintext highlighter-rouge">localhost</code>, so any other host/IP you expose it under must be added
to the certificate’s <code class="language-plaintext highlighter-rouge">dnsNames</code>/<code class="language-plaintext highlighter-rouge">ipAddresses</code> for verification to pass.</p>

<p>Then, in another terminal, call the endpoint over HTTPS.</p>

<h3 id="the-quick-way-skips-verification">The quick way (skips verification)</h3>

<p>For a throw-away check you can pass <code class="language-plaintext highlighter-rouge">-k</code> (or <code class="language-plaintext highlighter-rouge">--insecure</code>), which tells <code class="language-plaintext highlighter-rouge">curl</code>
not to verify the server’s certificate:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ curl -k https://localhost:8443/hello/nicolas
Hello nicolas
</code></pre></div></div>

<p>Be aware of what <code class="language-plaintext highlighter-rouge">-k</code> really does: it does not disable TLS, the connection
is still encrypted and the server still presents its certificate. It only turns
off the client-side <em>identity</em> check. It is a convenience for testing, not how
you would call a service in production.</p>

<h3 id="the-proper-way-verifies-the-server">The proper way (verifies the server)</h3>

<p><code class="language-plaintext highlighter-rouge">-k</code> is not required here and the certificate is perfectly verifiable, it is simply
signed by an issuer your machine does not trust by default. “Self-signed” means
“not in the system trust store”, not “unverifiable”. <code class="language-plaintext highlighter-rouge">cert-manager</code> conveniently
writes the signing certificate into the <code class="language-plaintext highlighter-rouge">ca.crt</code> entry of the <code class="language-plaintext highlighter-rouge">sb-k8s-cert</code>
secret, so you can extract it and tell <code class="language-plaintext highlighter-rouge">curl</code> to trust it:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl get secret sb-k8s-cert -o jsonpath='{.data.ca\.crt}' | base64 -d &gt; ca.crt
$ curl --cacert ca.crt https://localhost:8443/hello/nicolas
Hello nicolas
</code></pre></div></div>

<p>This time the server’s identity is actually validated as the certificate has a
<code class="language-plaintext highlighter-rouge">localhost</code> SAN, which is why <code class="language-plaintext highlighter-rouge">localhost</code> is accepted. If you point <code class="language-plaintext highlighter-rouge">curl</code> at a
CA that did not sign the certificate or omit <code class="language-plaintext highlighter-rouge">--cacert</code> so it falls back to
the system trust store, then the request is rejected with
<code class="language-plaintext highlighter-rouge">unable to get local issuer certificate</code>. That rejection is the proof that
verification is really happening.</p>

<h3 id="trusting-the-ca-machine-wide-optional">Trusting the CA machine-wide (optional)</h3>

<p>If you would rather run <code class="language-plaintext highlighter-rouge">curl</code> or a browser with no flags at all, install
that CA into your operating system’s trust store once:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sudo cp ca.crt /usr/local/share/ca-certificates/sb-k8s-ca.crt
$ sudo update-ca-certificates
$ curl https://localhost:8443/hello/nicolas        # no -k, no --cacert
Hello nicolas
</code></pre></div></div>

<p>Note that a certificate trusted with zero configuration everywhere, which is the way a
public website is, requires one issued by a <em>publicly trusted</em> CA. The <code class="language-plaintext highlighter-rouge">cert-manager</code>
ACME issuer is Let’s Encrypt. Trusting this issuer by our certificate needs a real,
internet-resolvable domain name and a solvable ACME challenge. That is a
deployment-to-a-real-domain concern and is not achievable against <code class="language-plaintext highlighter-rouge">localhost</code> on
<code class="language-plaintext highlighter-rouge">minikube</code>. Locally, trusting our own CA, as above, is the equivalent.</p>

<h2 id="certificate-renewal-and-rotation">Certificate renewal and rotation</h2>

<p><code class="language-plaintext highlighter-rouge">cert-manager</code> owns the whole lifecycle of the <code class="language-plaintext highlighter-rouge">sb-k8s</code> certificate, not just its
first issuance. Two fields on <code class="language-plaintext highlighter-rouge">k8s/certificate.yaml</code> drive it: the certificate’s
<code class="language-plaintext highlighter-rouge">duration</code> (how long each certificate stays valid) and <code class="language-plaintext highlighter-rouge">renewBefore</code> (how long
before expiry a replacement is issued). When that moment arrives <code class="language-plaintext highlighter-rouge">cert-manager</code>
signs a new certificate from <code class="language-plaintext highlighter-rouge">ss-cluster-issuer</code>, rebuilds the JKS keystore and
truststore, and overwrites the <code class="language-plaintext highlighter-rouge">sb-k8s-cert</code> secret in place. The secret name
never changes, only its contents.</p>

<p>Because <code class="language-plaintext highlighter-rouge">ss-cluster-issuer</code> is a self-signed issuer, there is no separate,
long-lived CA: each certificate is its own root, so <code class="language-plaintext highlighter-rouge">ca.crt</code> in the secret is the
leaf itself and is re-generated on every renewal. That is enough to demonstrate
that rotation happens, but it also means a client cannot keep trusting one stable
CA across rotations. See the note at the end of this section.</p>

<h3 id="watching-it-happen">Watching it happen</h3>

<p><code class="language-plaintext highlighter-rouge">cert-manager</code> records the schedule on the <code class="language-plaintext highlighter-rouge">Certificate</code> object itself:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl get certificate sb-k8s \
    -o jsonpath='{.status.notAfter}{"\n"}{.status.renewalTime}{"\n"}'
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">notAfter</code> is the expiry; <code class="language-plaintext highlighter-rouge">renewalTime</code> is when <code class="language-plaintext highlighter-rouge">cert-manager</code> plans to rotate (five
minutes earlier). The serial number carried inside the issued certificate is the
cleanest rotation fingerprint. It changes on every renewal:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl get secret sb-k8s-cert -o jsonpath='{.data.tls\.crt}' \
    | base64 -d | openssl x509 -noout -serial -dates
</code></pre></div></div>

<p>With the 90-day default nothing visibly rotates during a test session. To watch a
full cycle on a human timescale, shorten the lifetime temporarily (<code class="language-plaintext highlighter-rouge">cert-manager</code>
enforces a one-hour minimum, and <code class="language-plaintext highlighter-rouge">renewBefore</code> must be smaller than <code class="language-plaintext highlighter-rouge">duration</code>):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>spec:
  duration: 1h
  renewBefore: 5m       # renew five minutes before the hour is up
</code></pre></div></div>

<p>Reapply the manifest so <code class="language-plaintext highlighter-rouge">cert-manager</code> adopts the new lifetime. It then re-issues
straight away and keeps rotating on the shortened schedule:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl apply -f k8s/certificate.yaml
</code></pre></div></div>

<p>Because this issuer in this example is self-signed, the walkthrough stops here: <code class="language-plaintext highlighter-rouge">ca.crt</code>
rotates together with the leaf, so a client cannot keep validating against a single
pinned CA across renewals, and the application cannot reload rotated certificates
in a way that stays trusted. Getting a running application to pick up rotated
certificates in place, and keep clients connected across a rotation, relies on a
stable CA that outlives the leaf certificates. A next post will address this point.</p>

<h2 id="cleaning-up">Cleaning up</h2>

<p>If you deployed with <code class="language-plaintext highlighter-rouge">skaffold run</code>, remove everything it created with:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ skaffold delete
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">cert-manager</code> itself and the <code class="language-plaintext highlighter-rouge">minikube</code> cluster can be left in place for the
next run, or removed with <code class="language-plaintext highlighter-rouge">kubectl delete -f &lt;the cert-manager manifest URL&gt;</code> and
<code class="language-plaintext highlighter-rouge">minikube delete</code>.</p>]]></content><author><name>Nicolas DUMINIL</name></author><category term="Java" /><category term="Spring Boot 4" /><category term="Kubernetes" /><category term="Minikube" /><category term="LinkedIn" /><category term="DZone" /><summary type="html"><![CDATA[The previous post in this series demonstrates how to deploy and run Spring Boot applications on K8s without having to manually craft YAML files. This 2nd part takes it one step further and serves the very same /hello/{who} endpoint, but over HTTPS on port 8443, using an X.509 certificate that is provisioned, renewed and rotated automatically by cert-manager.It requires docker and minikube installed locally, as well as having a docker hub account.]]></summary></entry><entry><title type="html">Releasing Spring Boot Applications on Kubernetes</title><link href="https://www.simplex-software.fr/posts-archive/sbk8s/" rel="alternate" type="text/html" title="Releasing Spring Boot Applications on Kubernetes" /><published>2026-08-05T00:00:00+00:00</published><updated>2026-08-05T13:05:34+00:00</updated><id>https://www.simplex-software.fr/posts-archive/sbk8s</id><content type="html" xml:base="https://www.simplex-software.fr/posts-archive/sbk8s/"><![CDATA[<p>This project demonstrates how to deploy and run Spring Boot applications on K8S.
It requires <code class="language-plaintext highlighter-rouge">docker</code> and <code class="language-plaintext highlighter-rouge">minikube</code> installed locally, as well as having a 
docker hub account.</p>

<p>The typical way to deploy and run applications on K8S is to provide YAML manifest
files defining the kind of K8S controllers to be used, for example pods, deployments,
services, etc. It’s quite common that, in order to deploy and run a simple Spring
Boot application that does “hello world”, one needs a half dozen of YAML manifest
files. And the fact that these files could be concatenated in a single one doesn’t
change much to the fact that, at the end of the day, almost 100 YAML lines are 
required for such a simple operation.</p>

<p>The good news is that, using Cloud Native Buildpacks, you don’t need to provide
anymore all these YAML files and to bother with K8S details, because the <code class="language-plaintext highlighter-rouge">spring
-boot-maven-plugin</code> is able to generate the Docker image of the application, by
simply leveraging its <code class="language-plaintext highlighter-rouge">build-image</code> goal.</p>

<p>Here is the plugin configuration:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  &lt;plugin&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
    &lt;configuration&gt;
      &lt;image&gt;
        &lt;name&gt;nicolasduminil/k8s-sb:buildpacks&lt;/name&gt;
        &lt;env&gt;
          &lt;BP_JVM_VERSION&gt;25&lt;/BP_JVM_VERSION&gt;
        &lt;/env&gt;
        &lt;publish&gt;true&lt;/publish&gt;
      &lt;/image&gt;
    &lt;/configuration&gt;
  &lt;/plugin&gt;
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">name</code> element above overrides the Docker image name that will be generated
while the <code class="language-plaintext highlighter-rouge">env</code> element defines the JVM version. The generated image is published
on DockerHub registry. By default, Spring Boot uses Packeto Bellsoft Liberica 
Java Buildpack, which is a Cloud Native Buildpacks provider. If you prefer to 
use another one, you need then to override the buildpacks list in the Maven plugin
configuration, for example:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  &lt;plugin&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
    &lt;configuration&gt;
      &lt;image&gt;
        &lt;name&gt;nicolasduminil/k8s-sb:buildpacks&lt;/name&gt;
        &lt;buildpack&gt;
          &lt;buildpack&gt;gcr.io/packeto-buildpacks/adoptium:latest&lt;buldpack&gt;
          &lt;buildpack&gt;urn:cnb:builder:paketo-buildpacks/java&lt;/buildpack&gt;
        &lt;/env&gt;
        &lt;publish&gt;true&lt;/publish&gt;
      &lt;/image&gt;
    &lt;/configuration&gt;
  &lt;/plugin&gt;
</code></pre></div></div>

<p>The configuration above allows to use Eclipse Temurin instead of Bellsoft 
Liberica OpenJDK.</p>

<h2 id="building-deploying-and-running">Building, deploying and running</h2>

<p>In order to build the application execute the following command:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mvn clean package spring-boot:build-image
</code></pre></div></div>

<p>This will create the application JAR and the Docker image associated to it.
You should see something like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>INFO] Successfully built image 'docker.io/nicolasduminil/k8s-sb:buildpacks'
[INFO]
[INFO]  &gt; Pushing image 'docker.io/nicolasduminil/k8s-sb:buildpacks' 11%
[INFO]  &gt; Pushing image 'docker.io/nicolasduminil/k8s-sb:buildpacks' 15%
[INFO]  &gt; Pushing image 'docker.io/nicolasduminil/k8s-sb:buildpacks' 15%
[INFO]  &gt; Pushing image 'docker.io/nicolasduminil/k8s-sb:buildpacks' 100%
[INFO]  &gt; Pushed image 'docker.io/nicolasduminil/k8s-sb:buildpacks'
</code></pre></div></div>

<p>Now, start <code class="language-plaintext highlighter-rouge">minikube</code> if not already done:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ minikube start
😄  minikube v1.32.0 on Ubuntu 24.04  
✨  Using the docker driver based on user configuration
📌  Using Docker driver with root privileges
👍  Starting control plane node minikube in cluster minikube
🚜  Pulling base image ...
🔥  Creating docker container (CPUs=2, Memory=7900MB) ...
🐳  Preparing Kubernetes v1.28.3 on Docker 24.0.7 ...
▪ Generating certificates and keys ...
▪ Booting up control plane ...
▪ Configuring RBAC rules ...
🔗  Configuring bridge CNI (Container Networking Interface) ...
▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5
🔎  Verifying Kubernetes components...
🌟  Enabled addons: storage-provisioner, default-storageclass
🏄  Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default
</code></pre></div></div>

<p>Next, you need to create a deployment:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl create deployment k8s-sb --image nicolasduminil/k8s-sb:buildpacks
</code></pre></div></div>

<p>and to expose the associated service:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ kubectl expose deployment k8s-sb --type=NodePort --port=8080
</code></pre></div></div>

<p>In order to invoke the REST endpoint, you need to have its public URL. The 
following command will show it to you:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ minikube service list
|-------------|------------|--------------|---------------------------|
|  NAMESPACE  |    NAME    | TARGET PORT  |            URL            |
|-------------|------------|--------------|---------------------------|
| default     | k8s-sb     |         8080 | http://192.168.49.2:30809 |
| default     | kubernetes | No node port |                           |
| kube-system | kube-dns   | No node port |                           |
|-------------|------------|--------------|---------------------------|
</code></pre></div></div>

<p>All you need to do now is to send a HTTP GET request to the endpoint, as follows:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl http://192.168.49.2:30809/hello/nicolas
Hello nicolas
</code></pre></div></div>

<p>As you can see, as a proof a goodwill the endpoint greets you.</p>

<p>You’ve succeeded to release a Spring Boot application on Kubernetes without
having to write a line of YAML. Congratulations. Now, stay tuned to see what comes next.</p>]]></content><author><name>Nicolas DUMINIL</name></author><category term="Java" /><category term="Spring Boot 4" /><category term="Kubernetes" /><category term="Minikube" /><category term="LinkedIn" /><category term="DZone" /><summary type="html"><![CDATA[This project demonstrates how to deploy and run Spring Boot applications on K8S. It requires docker and minikube installed locally, as well as having a docker hub account.]]></summary></entry><entry><title type="html">Rethinking Java Design Patterns: from OOP to FP (5)</title><link href="https://www.simplex-software.fr/posts-archive/fdp5/" rel="alternate" type="text/html" title="Rethinking Java Design Patterns: from OOP to FP (5)" /><published>2026-07-27T00:00:00+00:00</published><updated>2026-07-27T13:05:34+00:00</updated><id>https://www.simplex-software.fr/posts-archive/fdp5</id><content type="html" xml:base="https://www.simplex-software.fr/posts-archive/fdp5/"><![CDATA[<p>After having rethought the <a href="http://www.simplex-software.fr/posts-archive/fdp/">Factory</a>, the <a href="https://www.simplex-software.fr/posts-archive/fdp2/">Visitor</a>, the <a href="https://www.simplex-software.fr/posts-archive/fdp3/">Builder</a> and the <a href="https://www.simplex-software.fr/posts-archive/fdp4/">Decorator</a> paterns in previous posts, let’s look now at a behavioral one: the Strategy.</p>

<h2 id="the-strategy">The Strategy</h2>

<p>This design pattern belongs to the behavioral category and its purpose is to
define a family of algorithms, encapsulate each one of them and make them
interchangeable, such that the algorithm may vary independently of its consumer.
Where the decorator asked <em>what else should happen to this object ?</em>,
the strategy asks <em>which one of these algorithms should be applied ?</em>.</p>

<p>We keep the same <code class="language-plaintext highlighter-rouge">Product</code> domain and we compute a shipping cost for it. Three
interchangeable algorithms are provided:</p>

<ul>
  <li>Standard: a flat <code class="language-plaintext highlighter-rouge">4.99</code> fee.</li>
  <li>Express: <code class="language-plaintext highlighter-rouge">9.99</code> plus 2% of the product price.</li>
  <li>FreeOver: the familiar <em>“free delivery over 50.00”</em> commercial rule. It is
parameterized by a price threshold and by the strategy to apply when the
threshold isn’t reached. Should the product price be greater than or equal to
the threshold, the shipping is free, otherwise the product doesn’t qualify and
the cost is the one computed by that other strategy.</li>
</ul>

<p>For our <code class="language-plaintext highlighter-rouge">100.00</code> book, the standard shipping costs <code class="language-plaintext highlighter-rouge">4.99</code>, the express one costs
<code class="language-plaintext highlighter-rouge">11.99</code> and, with a <code class="language-plaintext highlighter-rouge">50.00</code> threshold, the free-over one costs <code class="language-plaintext highlighter-rouge">0.00</code>, since <code class="language-plaintext highlighter-rouge">100.00</code>
is above the threshold. Raising that same threshold to <code class="language-plaintext highlighter-rouge">150.00</code> falls back to the
standard shipping and, hence, to <code class="language-plaintext highlighter-rouge">4.99</code>.
Notice that, unlike the visitor, nothing here varies per product <em>type</em>: what varies is the
algorithm and it is the caller that picks it.</p>

<h3 id="the-object-oriented-approach">The object-oriented approach</h3>

<p>The figure below shows the class diagram of the object-oriented strategy:</p>

<p><img src="/assets/images/strategy-oop.png" alt="strategy-oop" title="OOP Strategy" /></p>

<p>The classic <em>Gang of Four</em> Strategy declares an interface for the family of the
algorithms and one class per algorithm:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public interface ShippingStrategy
{
  BigDecimal cost(Product product);
}

public class ExpressShipping implements ShippingStrategy
{
  private static final BigDecimal FEE = new BigDecimal("9.99");
  private static final BigDecimal RATE = new BigDecimal("0.02");

  public BigDecimal cost(Product product)
  {
    return FEE.add(product.price().multiply(RATE).setScale(2, RoundingMode.HALF_UP));
  }
}
</code></pre></div></div>

<p>An algorithm that needs to be parameterized becomes a class with state. Here
<code class="language-plaintext highlighter-rouge">FreeOverShipping</code> holds its threshold and the strategy to fall back to:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public FreeOverShipping(BigDecimal threshold, ShippingStrategy otherwise) { ... }

public BigDecimal cost(Product product)
{
  return product.price().compareTo(threshold) &gt;= 0 ? FREE : otherwise.cost(product);
}
</code></pre></div></div>

<p>Last but not least, the <code class="language-plaintext highlighter-rouge">ShippingCalculator</code> class, as the <em>context</em>, is the object that uses the algorithm without
knowing which one it is. It only holds a reference to the interface, which is
what allows the algorithm to be replaced at runtime:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ShippingCalculator calculator = new ShippingCalculator(new StandardShipping());
BigDecimal cost = calculator.cost(book);      // 4.99

calculator.setStrategy(new ExpressShipping());
cost = calculator.cost(book);                 // 11.99
</code></pre></div></div>

<p>Contrary to the visitor and to the decorator, the strategy doesn’t require
anything at all from the elements it processes: no <code class="language-plaintext highlighter-rouge">accept</code> method and no shared
component interface. Consequently, and this is the first time it happens on the
object-oriented side, the module reuses the sealed <code class="language-plaintext highlighter-rouge">common.Product</code> directly, with
neither its own hierarchy, nor any adapter.</p>

<h3 id="the-functional-approach">The functional approach</h3>

<p>Look now at the class diagram of the functional style implementation:</p>

<p><img src="/assets/images/strategy-fp.png" alt="strategy-fp" title="FP Strategy" /></p>

<p>Of all the patterns seen so far, this is the one where the functional answer is the
most radical. The interface <code class="language-plaintext highlighter-rouge">ShippingStrategy</code> in the OO implementation declares one single
method and, like any interface, holds no state, such that everything it tells us is
<em>a <code class="language-plaintext highlighter-rouge">Product</code> comes in, a <code class="language-plaintext highlighter-rouge">BigDecimal</code> comes out</em>.</p>

<p>In functional terms, this is nothing more than a <code class="language-plaintext highlighter-rouge">Function&lt;Product, BigDecimal&gt;</code> type.
So each algorithm becomes a plain value of the function type, for example:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public static final Function&lt;Product, BigDecimal&gt; EXPRESS = product -&gt;
  EXPRESS_FEE.add(product.price().multiply(EXPRESS_RATE).setScale(2, RoundingMode.HALF_UP));
</code></pre></div></div>

<p>As opposed to the OO side which required the <code class="language-plaintext highlighter-rouge">FreeOverShipping</code> class holding
the threshold and the shipping strategy, the FP side captures them in a closure.
So this class on the OO side becomes on the FP side a higher-order function,
i.e. a function returning the strategy itself:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public static Function&lt;Product, BigDecimal&gt; freeOver(BigDecimal threshold,
  Function&lt;Product, BigDecimal&gt; otherwise)
{
  return product -&gt; product.price().compareTo(threshold) &gt;= 0 ? FREE : otherwise.apply(product);
}
</code></pre></div></div>

<p>The very same happens to <code class="language-plaintext highlighter-rouge">ShippingCalculator</code>, the context class on the OOP side.
Its whole reason to exist was to hold a strategy in a field, such that its <code class="language-plaintext highlighter-rouge">cost()</code>
and <code class="language-plaintext highlighter-rouge">total()</code> operations could delegate to it. But a context is just an operation
parameterized by an algorithm and this, once again, is precisely a higher-order
function. Hence, the <code class="language-plaintext highlighter-rouge">ShippingCalculator.total()</code> method on the OO side becomes on the FP one:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public static Function&lt;Product, BigDecimal&gt; totalWith(Function&lt;Product, BigDecimal&gt; strategy)
{
  return product -&gt; product.price().add(strategy.apply(product));
}
</code></pre></div></div>

<p>such that the following call on the OO side, shown above:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ShippingCalculator calculator = new ShippingCalculator(new StandardShipping());
...
BigDecimal total = calculator.total(book);
</code></pre></div></div>

<p>becomes on the FP side:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>BigDecimal total = totalWith(STANDARD).apply(book);
</code></pre></div></div>

<p>There is no property to hold the strategy anymore and, consequently, no <code class="language-plaintext highlighter-rouge">setStrategy()</code>
method either. Here the strategy is an argument which doesn’t need to be stored
in the context, just call the function with the right value and that’s all.</p>

<p>But the real advantage of the strategies as ordinary values is that they can be
combined. Picking the cheapest of several shipping options requires yet another
class on the OO side, while here it’s a simple combinator:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Function&lt;Product, BigDecimal&gt; best = cheapest(STANDARD, EXPRESS);   // 4.99
</code></pre></div></div>

<p>And as usual, they compose with <code class="language-plaintext highlighter-rouge">andThen</code>, for example to apply
a promotion to whatever cost has been computed:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Function&lt;Product, BigDecimal&gt; promo =
  EXPRESS.andThen(cost -&gt; cost.divide(TWO, 2, RoundingMode.HALF_UP));   // 6.00
</code></pre></div></div>

<p>The OO Strategy encapsulates each algorithm in a class implementing a
common interface and injects the chosen one into a context object, while the
functional one observes that such an interface describes nothing but a function type
which the JDK already provides and, consequently, keeps only the algorithms
themselves. “Turtles all the way down”, and both compute the same cost.</p>

<h2 id="project-structure">Project structure</h2>

<p>The code is organized as a multi-module Maven project. The product domain lives
in its own <code class="language-plaintext highlighter-rouge">common</code> module: a <code class="language-plaintext highlighter-rouge">sealed</code> <code class="language-plaintext highlighter-rouge">Product</code> interface, the three product
records and the <code class="language-plaintext highlighter-rouge">ProductType</code> enumerated which already carries the FP factory
function seen above. Everything that can reuse that domain does:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>oop-fp-design-patterns        (parent POM)
├── common                    sealed Product, the records, ProductType(+factory)
├── factory   (→ common)      ProductFactory (OOP); the FP factory *is* common.ProductType
├── visitor   (→ common)      FP: operations over the common records (switch + lambda bundle)
│                             OOP: its own element hierarchy (see below)
├── builder   (→ common)      immutable Order over the common records; OOP: fluent
│                             OrderBuilder; FP: composed UnaryOperator&lt;Order&gt; steps
├── decorator (→ common)      FP: composed UnaryOperator&lt;Product&gt; decorations over the
│                             common records; OOP: its own Product interface (see below)
└── strategy  (→ common)      shipping algorithms over the common records; OOP: the
                              ShippingStrategy hierarchy + context; FP: plain
                              Function&lt;Product, BigDecimal&gt; values
</code></pre></div></div>

<p>The FP factory, the FP visitor and the FP decorator all operate directly on the
<code class="language-plaintext highlighter-rouge">common</code> records, so nothing is duplicated there, and the Strategy does so on
<em>both</em> of its sides. The two exceptions are the object-oriented Visitor and the
object-oriented Decorator.</p>

<p>The Visitor needs an
<code class="language-plaintext highlighter-rouge">accept</code> method on every element (double dispatch); the Decorator needs a
non-sealed <code class="language-plaintext highlighter-rouge">Product</code> interface that its wrappers can implement. In both cases
<code class="language-plaintext highlighter-rouge">common.Product</code> is <code class="language-plaintext highlighter-rouge">sealed</code> and cannot be extended from another module, so each
owns its own element/component types and reuses only the <code class="language-plaintext highlighter-rouge">ProductType</code> enumerated -
the OOP decorator bridges back to <code class="language-plaintext highlighter-rouge">common</code> through a small <code class="language-plaintext highlighter-rouge">BaseProduct</code> adapter.
This asymmetry is not accidental.</p>

<p>The classic Visitor requires every element to
expose an <code class="language-plaintext highlighter-rouge">accept</code> method and the classic Decorator requires every component to
share the wrappers’ interface; both couple the elements to the pattern’s
abstraction, so they cannot be the sealed records defined in <code class="language-plaintext highlighter-rouge">common</code>. The
functional approach has no such coupling: it operates over the sealed type from the
outside - pattern-matching for the visitor, rebuilding through the factory for the
decorator - so the elements know nothing about the operations applied to them and,
hence, can be the shared <code class="language-plaintext highlighter-rouge">common</code> records.</p>

<p>The Strategy confirms the rule the other
way around: it doesn’t couple the elements to its abstraction either, only the
<em>client</em> to it, and this is precisely why it is the only pattern here whose
object-oriented implementation reuses <code class="language-plaintext highlighter-rouge">common</code> as freely as its functional one.</p>

<p>The full code of these examples, including the associated unit tests,
can be found <a href="https://github.com/nicolasduminil/oop-fp-design-patterns">here</a>.</p>]]></content><author><name>Nicolas DUMINIL</name></author><category term="Java" /><category term="Design patterns" /><category term="Functional style" /><category term="LinkedIn" /><summary type="html"><![CDATA[After having rethought the Factory, the Visitor, the Builder and the Decorator paterns in previous posts, let’s look now at a behavioral one: the Strategy.]]></summary></entry><entry><title type="html">Rethinking Java Design Patterns: from OOP to FP (4)</title><link href="https://www.simplex-software.fr/posts-archive/fdp4/" rel="alternate" type="text/html" title="Rethinking Java Design Patterns: from OOP to FP (4)" /><published>2026-07-19T00:00:00+00:00</published><updated>2026-07-12T13:05:34+00:00</updated><id>https://www.simplex-software.fr/posts-archive/fdp4</id><content type="html" xml:base="https://www.simplex-software.fr/posts-archive/fdp4/"><![CDATA[<p>After having rethought the <a href="http://www.simplex-software.fr/posts-archive/fdp/">Factory</a>, the <a href="https://www.simplex-software.fr/posts-archive/fdp2/">Visitor</a> and the <a href="https://www.simplex-software.fr/posts-archive/fdp3/">Builder</a> paterns in previous posts, let’s look now at another structural one: the Decorator.</p>

<h2 id="the-decorator">The Decorator</h2>

<p>This design pattern belongs to the structural category and its purpose is to
attach additional responsibilities to an object dynamically, by wrapping it in
another object that shares the same interface. It is the flexible alternative to
subclassing for extending behavior: rather than a combinatorial explosion of
<code class="language-plaintext highlighter-rouge">DiscountedTaxedGiftWrappedProduct</code> subclasses, you wrap a product in as many
independent decorators as you need, and they stack.</p>

<p>We reuse the same <code class="language-plaintext highlighter-rouge">Product</code> domain. Each decorator changes the <code class="language-plaintext highlighter-rouge">price()</code> and the
<code class="language-plaintext highlighter-rouge">description()</code> while leaving everything else untouched. To keep the pattern
visibly distinct from the visitor, whose rules varied per product type, the
decorators here apply the same rule to every product:</p>

<ul>
  <li>Discounted: 10% off the wrapped price.</li>
  <li>Taxed: adds 20% VAT to the wrapped price.</li>
  <li>GiftWrapped: adds a flat <code class="language-plaintext highlighter-rouge">5.00</code> wrapping fee.</li>
</ul>

<p>Because they stack, a 100.00 book decorated <code class="language-plaintext highlighter-rouge">Discounted</code> → <code class="language-plaintext highlighter-rouge">Taxed</code> →
<code class="language-plaintext highlighter-rouge">GiftWrapped</code> goes <code class="language-plaintext highlighter-rouge">100.00 → 90.00 → 108.00 → 113.00</code>, and its description reads
<code class="language-plaintext highlighter-rouge">"A book (discounted) (VAT incl.) (gift-wrapped)"</code>.</p>

<h3 id="the-object-oriented-approach">The object-oriented approach</h3>

<p>The figure below shows the class diagram of the object-oriented decorator:</p>

<p><img src="/assets/images/decorator-oop.png" alt="decorator-oop" title="OOP Decorator" /></p>

<p>The classic <em>Gang of Four</em> Decorator is an object that implements the component
interface and holds a reference to another component, delegating the untouched
operations and overriding the ones it enhances. An abstract <code class="language-plaintext highlighter-rouge">ProductDecorator</code>
captures the delegation once:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public abstract class ProductDecorator implements Product
{
  protected final Product product;

  protected ProductDecorator(Product product)
  {
    this.product = Objects.requireNonNull(product, "Product is null");
  }

  public String name() { return product.name(); }
  public String description() { return product.description(); }
  public BigDecimal price() { return product.price(); }
  public ProductType type() { return product.type(); }
}
</code></pre></div></div>

<p>Each concrete decorator then overrides only what it changes:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public class Discounted extends ProductDecorator
{
  private static final BigDecimal RATE = new BigDecimal("0.10");

  public Discounted(Product product) { super(product); }

  public BigDecimal price()
  {
    return product.price().subtract(amount(product.price(), RATE));
  }

  public String description()
  {
    return product.description() + " (discounted)";
  }
}
</code></pre></div></div>

<p>Since a decorator is a <code class="language-plaintext highlighter-rouge">Product</code>, decorators wrap decorators and the enhancements
compose by nesting:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Product wrapped = new GiftWrapped(new Taxed(new Discounted(new BaseProduct(book))));
BigDecimal price = wrapped.price();   // 113.00
</code></pre></div></div>

<p>The leaf being wrapped is a <code class="language-plaintext highlighter-rouge">BaseProduct</code>, a small record that adapts a shared
<code class="language-plaintext highlighter-rouge">common.Product</code> into the decorator’s own interface. This is necessary because
<code class="language-plaintext highlighter-rouge">common.Product</code> is <code class="language-plaintext highlighter-rouge">sealed</code> and so, exactly like the object-oriented visitor, the
decorator cannot make the <code class="language-plaintext highlighter-rouge">common</code> records implement its interface directly.</p>

<h3 id="the-functional-approach">The functional approach</h3>

<p>Look now at the class diagram of the functional style implementation:</p>

<p><img src="/assets/images/decorator-fp.png" alt="decorator-fp" title="FP Decorator" /></p>

<p>The functional counterpart of a decorator is simply a function whicg maps a product
to an enhanced product and implemented as an <code class="language-plaintext highlighter-rouge">UnaryOperator&lt;Product&gt;</code>. Because
the <code class="language-plaintext highlighter-rouge">common</code> records are immutable, “enhancing” one means rebuilding it through
the <code class="language-plaintext highlighter-rouge">ProductType</code> factory, already seen at the very beginning, which is why the
FP side reuses <code class="language-plaintext highlighter-rouge">common</code> directly with no adapter:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>public static final UnaryOperator&lt;Product&gt; DISCOUNTED = product -&gt;
  product.type().newInstance(product.name(),
    product.description() + " (discounted)",
    product.price().subtract(amount(product.price(), "0.10")));
</code></pre></div></div>

<p>Being ordinary values, the decorations compose with <code class="language-plaintext highlighter-rouge">andThen</code>, exactly as the
factory composed its <code class="language-plaintext highlighter-rouge">factory</code> function, the visitor composed its operations and
the builder composed its steps:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>UnaryOperator&lt;Product&gt; decorate = DISCOUNTED.andThen(TAXED).andThen(GIFT_WRAPPED);
Product wrapped = decorate.apply(book);   // price 113.00
</code></pre></div></div>

<p>And, just like the functional builder step, a decoration is a reusable first-class
value. For example, the same discount could be applied twice:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Product wrapped = DISCOUNTED.andThen(DISCOUNTED).apply(book);   // 100 -&gt; 90 -&gt; 81
</code></pre></div></div>

<p>The object-oriented Decorator wraps the component in a stack of objects sharing its
interface, while the functional one expresses the very same stacking as the
composition of pure <code class="language-plaintext highlighter-rouge">Product</code> to <code class="language-plaintext highlighter-rouge">Product</code> functions. “Turtles all the way down”,
and both land on the same enhanced product.</p>

<h2 id="project-structure">Project structure</h2>

<p>The code is organized as a multi-module Maven project. The product domain lives
in its own <code class="language-plaintext highlighter-rouge">common</code> module: a <code class="language-plaintext highlighter-rouge">sealed</code> <code class="language-plaintext highlighter-rouge">Product</code> interface, the three product
records and the <code class="language-plaintext highlighter-rouge">ProductType</code> enumerated which already carries the FP factory
function seen above. Everything that can reuse that domain does:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>oop-fp-design-patterns        (parent POM)
├── common                    sealed Product, the records, ProductType(+factory)
├── factory   (→ common)      ProductFactory (OOP); the FP factory *is* common.ProductType
├── visitor   (→ common)      FP: operations over the common records (switch + lambda bundle)
│                             OOP: its own element hierarchy (see below)
├── builder   (→ common)      immutable Order over the common records; OOP: fluent
│                             OrderBuilder; FP: composed UnaryOperator&lt;Order&gt; steps
└── decorator (→ common)      FP: composed UnaryOperator&lt;Product&gt; decorations over the
                              common records; OOP: its own Product interface (see below)
</code></pre></div></div>

<p>The FP factory, the FP visitor and the FP decorator all operate directly on the
<code class="language-plaintext highlighter-rouge">common</code> records, so nothing is duplicated there. The two exceptions are the
object-oriented Visitor and the object-oriented Decorator. The Visitor needs an
<code class="language-plaintext highlighter-rouge">accept</code> method on every element (double dispatch); the Decorator needs a
non-sealed <code class="language-plaintext highlighter-rouge">Product</code> interface that its wrappers can implement. In both cases
<code class="language-plaintext highlighter-rouge">common.Product</code> is <code class="language-plaintext highlighter-rouge">sealed</code> and cannot be extended from another module, so each
owns its own element/component types and reuses only the <code class="language-plaintext highlighter-rouge">ProductType</code> enumerated -
the OOP decorator bridges back to <code class="language-plaintext highlighter-rouge">common</code> through a small <code class="language-plaintext highlighter-rouge">BaseProduct</code> adapter.
This asymmetry is not accidental. The classic Visitor requires every element to
expose an <code class="language-plaintext highlighter-rouge">accept</code> method and the classic Decorator requires every component to
share the wrappers’ interface; both couple the elements to the pattern’s
abstraction, so they cannot be the sealed records defined in <code class="language-plaintext highlighter-rouge">common</code>. The
functional approach has no such coupling: it operates over the sealed type from the
outside - pattern-matching for the visitor, rebuilding through the factory for the
decorator - so the elements know nothing about the operations applied to them and,
hence, can be the shared <code class="language-plaintext highlighter-rouge">common</code> records.</p>

<p>The full code of these examples, including the associated unit tests,
can be found <a href="https://github.com/nicolasduminil/oop-fp-design-patterns">here</a>.</p>]]></content><author><name>Nicolas DUMINIL</name></author><category term="Java" /><category term="Design patterns" /><category term="Functional style" /><category term="LinkedIn" /><summary type="html"><![CDATA[After having rethought the Factory, the Visitor and the Builder paterns in previous posts, let’s look now at another structural one: the Decorator.]]></summary></entry></feed>