Skip to content

Derive public key from private_key.der in the key-folder path - #2367

Open
yajneshx94 wants to merge 15 commits into
unitycatalog:mainfrom
yajneshx94:fix/derive-public-key-from-private-key
Open

yajneshx94 wants to merge 15 commits into
unitycatalog:mainfrom
yajneshx94:fix/derive-public-key-from-private-key

Conversation

@yajneshx94

@yajneshx94 yajneshx94 commented Nov 24, 2026 •

Copy link
Copy Markdown

PR Checklist

  • A description of the changes is added to the description of this PR.
  • If there is a related issue, make sure it is linked to this PR.
  • If you've fixed a bug or added code that should be tested, add tests!
  • If you've added or modified a feature, documentation in docs is updated

Description of changes

Fixes #2363

In the deprecated configuration-folder path:

  • When the RSA private key has CRT fields, the public key is derived from private_key.der and an existing public_key.der is not read.
  • public_key.der is created for earlier releases when it is missing. An existing file is left untouched, except that a stale one is replaced when this start generates a new private key. A failed write only logs a warning. Before rolling back, operators must check that it matches private_key.der and is in DER format (see the upgrade docs).
  • A generated private_key.der is published atomically without replacing an existing key, using a hard link. If the file system does not support hard links, the first start fails with an error that names the cause and suggests
    server.token-signing-private-key-file, and no partial key file is left behind. A failed public_key.der write only logs a warning.
  • Temporary files use a .der suffix so the existing .gitignore rule covers them.
  • The private key is checked at load that it can sign with RS512, using the check from [Server] Reject a token signing key too small for RS512 when it is loaded #2389, for both the folder key and the configured key
    file.
  • For older keys without CRT fields, the server reads public_key.der, checks that the pair matches, and names both files on a mismatch.

Updates the key-folder documentation, including the DER formats earlier releases need for rollback and the command to recreate public_key.der. Adds tests for mismatched, malformed, missing, stale and unwritable public key files, older key formats, concurrent first starts, and file permissions that do not depend on the umask.

@yili-db

yili-db commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

/review

@yili-db
yili-db requested a review from shba24 November 24, 2026 19:26

@shba24 shba24 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On lines this pull request does not change

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:142

Nit (not a blocker): A folder with only private_key.der has its key replaced because public_key.der is missing

initializeIfMissing generates a new pair when either file is missing, and writeOwnerOnly deletes the existing private_key.der before writing. After this PR nothing reads public_key.der, so a file that no longer supplies the key can still decide whether the signing key is replaced. The trigger existed at base, but there the public file was really read. Tokens signed with the replaced key stop verifying.

Cost of keeping it: An operator drops a valid private_key.der into the folder without a public_key.der, or deletes the public file as unused. On start the server writes a fresh pair over their key. If this stays, each later change to the folder path has to keep two ideas of the key folder in step: a pair of files, and one source file.

Make private_key.der the only trigger for generating a pair. If only public_key.der is missing, rewrite it from the derived public key, so rollback to an earlier version (auth.md:296-301) keeps working. If the non-CRT fallback from the blocker comment on SecurityConfiguration.java:74 is added, that case still needs public_key.der and must not regenerate it.

Evidence
SecurityConfiguration.java:70-74 resolves the public file but no longer reads it: `Path publicKeyFile = configurationFolder.resolve("public_key.der");` / `initializeIfMissing(privateKeyFile, publicKeyFile);` / `privateKey = readPrivateKey(privateKeyFile);` / `publicKey = publicKeyOf(privateKey, privateKeyFile);`. The removed lines in the diff were `-    publicKey = readPublicKey(publicKeyFile);` and the whole `readPublicKey` method. Lines 142-146 still regenerate both keys when only the public file is missing: `if (Files.notExists(publicKeyFile) || Files.notExists(privateKeyFile)) {` ... `KeyPair keyPair = keyPairGenerator.generateKeyPair();`, and line 155 writes the private key with `writeOwnerOnly(privateKeyFile, keyPair.getPrivate().getEncoded());`. The class doc at lines 35-36 still describes the pair: `uses {@code private_key.der} and {@code public_key.der} in the UC configuration folder, generating them on first start.` A grep of server/, helm/ and docs/ found no other runtime reader of public_key.der. The only remaining mention is the rollback note in docs/server/auth.md:301: `openssl rsa -in private_key.pem -pubout -outform DER -out etc/conf/public_key.der`.

SecurityConfiguration.java:70-74: `Path publicKeyFile = configurationFolder.resolve("public_key.der"); initializeIfMissing(privateKeyFile, publicKeyFile); privateKey = readPrivateKey(privateKeyFile); publicKey = publicKeyOf(privateKey, privateKeyFile);`. publicKeyFile is now passed only to initializeIfMissing. Lines 141-155: `if (Files.notExists(publicKeyFile) || Files.notExists(privateKeyFile)) { ... KeyPair keyPair = keyPairGenerator.generateKeyPair(); ... writeOwnerOnly(privateKeyFile, keyPair.getPrivate().getEncoded());` and writeOwnerOnly starts with `Files.deleteIfExists(file);`. So when only the unread public file is missing, the existing private key is deleted and replaced. `git grep public_key.der` finds no other reader in server code.

toolkit_errors-1: server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:142: `if (Files.notExists(publicKeyFile) || Files.notExists(privateKeyFile)) {` is followed by key generation and `writeOwnerOnly(privateKeyFile, ...)`, which runs `Files.deleteIfExists(file)` on the private key. The constructor now ignores public_key.der (`publicKey = publicKeyOf(privateKey, privateKeyFile);`), so a folder with a valid private_key.der and no public_key.der still has its private key silently deleted and replaced, and every token signed with the old key stops verifying. The check was already there before this commit. This commit makes public_key.der unnecessary, so the check is now stricter than the code needs.
How it was checked

Checked by 2 independent checks: CONFIRMED

How about generating only when private_key.der is missing and recreating public_key.der from the derived key?

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:35

Nit (not a blocker): Class Javadoc does not say where the public key comes from

The Javadoc says the folder path "uses private_key.der and public_key.der". That is still literally true, since both files are checked and written, but the public key now comes from the private key. The sentence is imprecise rather than wrong.

For example: A reader of the Javadoc would assume public_key.der is read at startup. The code derives the public key from private_key.der.

the server then uses `private_key.der` in the UC configuration folder and derives the public key from it, generating the key on first start; `public_key.der` is also written so that earlier versions can still read the folder.
Evidence
`SecurityConfiguration.java:35`: `* uses {@code private_key.der} and {@code public_key.der} in the UC configuration folder,`
`SecurityConfiguration.java:73-74`: `privateKey = readPrivateKey(privateKeyFile);` and `publicKey = publicKeyOf(privateKey, privateKeyFile);`
The Javadoc says both files supply the folder-path key pair, but the changed constructor derives the public key from the private key instead of reading `public_key.der`.
How it was checked

Checked by 1 independent check: NITPICK

Would this wording work? It will need another look if the public file's role changes in the comment on SecurityConfiguration.java:142.

initializeIfMissing(privateKeyFile, publicKeyFile);
privateKey = readPrivateKey(privateKeyFile);
publicKey = readPublicKey(publicKeyFile);
publicKey = publicKeyOf(privateKey, privateKeyFile);

@shba24 shba24 Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: Server no longer starts from an existing configuration folder whose private key has no CRT fields

The folder constructor now derives the public key with publicKeyOf, which accepts only an RSAPrivateCrtKey. Before this change the folder path read public_key.der, so a private_key.der without CRT fields loaded fine. After the upgrade the same folder throws IllegalStateException ("has no public exponent") and the server does not start. Keys the server generates and keys made with openssl pkcs8 -topk8 carry CRT fields, so only hand-made or tool-exported non-CRT keys are affected.

For example: An operator has a private_key.der that is the PKCS #8 encoding of RSAPrivateKeySpec(n, d), plus the matching public_key.der, in the configuration folder. The server ran on aa8f434. They upgrade to this commit and restart. Startup fails in publicKeyOf, called from line 74.

PrivateKey privateKey = readPrivateKey(privateKeyFile);
PublicKey publicKey =
    privateKey instanceof RSAPrivateCrtKey
        ? publicKeyOf(privateKey)
        : readPublicKey(publicKeyFile); // non-CRT key: public_key.der is the only source
// then check the pair by signing and verifying a probe, and fail if they do not match
Evidence
L20 Check: “Does this behave across supported versions? Am I removing/altering a surface clients depend on without a path?” SecurityConfiguration.java:72-74: `initializeIfMissing(privateKeyFile, publicKeyFile); privateKey = readPrivateKey(privateKeyFile); publicKey = publicKeyOf(privateKey, privateKeyFile);` Lines 127-133 reject keys that are not `RSAPrivateCrtKey`. Previously, the constructor read `public_key.der` independently. On JDK 17, a PKCS #8 RSA private key generated from modulus and private exponent reloads as non-CRT and successfully signs data verified by its matching public key.
How it was checked

Reproduced: dev/run-tests.py -p 1 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest'

head:

[error] Test ...SecurityConfigurationTest.loadsExistingNonCrtKeyPairFromConfigurationFolder failed: java.lang.IllegalStateException: The key in .../private_key.der has no public exponent; create it with `openssl genrsa`  (at SecurityConfiguration.publicKeyOf(SecurityConfiguration.java:131))
[error] Failed: Total 12, Failed 1, Errors 0, Passed 11

with the fix:

Same test on base aa8f4347 SecurityConfiguration.java: it passed (Total 12, Failed 1, Passed 11; the one failure was the PR's own derivesPublicKeyFromPrivateKeyInConfigurationFolder, which expects the new behavior).
@Test
void loadsExistingNonCrtKeyPairFromConfigurationFolder() throws Exception {
  KeyPair crt = newKeyPair();
  java.security.interfaces.RSAPrivateCrtKey c = (java.security.interfaces.RSAPrivateCrtKey) crt.getPrivate();
  java.security.PrivateKey nonCrt = java.security.KeyFactory.getInstance("RSA").generatePrivate(new java.security.spec.RSAPrivateKeySpec(c.getModulus(), c.getPrivateExponent()));
  Files.write(configurationFolder.resolve("private_key.der"), nonCrt.getEncoded());
  Files.write(configurationFolder.resolve("public_key.der"), crt.getPublic().getEncoded());
  SecurityConfiguration configuration = new SecurityConfiguration(configurationFolder);
  assertThat(configuration.rsaPublicKey()).isEqualTo(crt.getPublic());
}

Checked by 2 independent checks: CONTESTED

How about falling back to public_key.der only for non-CRT keys, with a pairing check, and adding loadsExistingNonCrtKeyPairFromConfigurationFolder to SecurityConfigurationTest? If you prefer to keep the stricter rule, would a note in the Upgrading section of docs/server/auth.md work?

KeyPair mismatchedKeyPair = newKeyPair();
Files.write(
configurationFolder.resolve("private_key.der"), signingKeyPair.getPrivate().getEncoded());
Files.write(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): A regression that parses public_key.der again would not be noticed

derivesPublicKeyFromPrivateKeyInConfigurationFolder writes a valid but mismatched public key. This pins that the file is not used for verification, but not that it is not parsed. No test in the class writes malformed bytes there.

For example: A later change parses public_key.der before deriving the key and discards the result. Startup then fails on a corrupt public file, and the current test still passes.

Files.write(configurationFolder.resolve("public_key.der"), new byte[] {1, 2, 3});
SecurityConfiguration configuration = new SecurityConfiguration(configurationFolder);
assertThat(configuration.rsaPublicKey()).isEqualTo(signingPair.getPublic());
Evidence
SecurityConfiguration.java:72-74: `initializeIfMissing(privateKeyFile, publicKeyFile); privateKey = readPrivateKey(privateKeyFile); publicKey = publicKeyOf(privateKey, privateKeyFile);` SecurityConfigurationTest.java:120-125 writes `mismatchedKeyPair.getPublic().getEncoded()` to `public_key.der` and asserts `configuration.rsaPublicKey()` equals `signingKeyPair.getPublic()`. The test uses a valid public-key file, so it would not catch a regression that parses that file before deriving the key.
How it was checked

Checked by 2 independent checks: CONFIRMED

How about adding malformed bytes as a second case in this existing test? Keep a CRT private key there so it pins that the public file is not parsed.

@yajneshx94

Copy link
Copy Markdown
Author

Thanks for the detailed review, I'll update the pull request with the fallback for keys without the extra fields and address the nits.

Preserve non-CRT key compatibility, avoid regenerating a private key when the public key file is missing, and cover malformed, missing, and mismatched public key files.

Signed-off-by: Yajnesh K <[email protected]>

@timothyw553 timothyw553 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

overall direction looks good. i left a few comments on making the public_key.der write best-effort in one place, handling SignatureException on mismatched key sizes, and a nit on the docs.


private static void writePublicKeyIfNeeded(Path file, RSAPublicKey publicKey) throws IOException {
byte[] encoded = publicKey.getEncoded();
if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since we already have the valid public key in memory, should updating this compatibility file be best-effort instead of blocking startup? right now a read-only public_key.der (or even a matching PEM file, whose bytes differ from DER) triggers a write and fails startup. could we catch IOException, log a warning, and add a test with an unwritable public_key.der?

- private static void writePublicKeyIfNeeded(Path file, RSAPublicKey publicKey) throws IOException {
+ private static void writePublicKeyIfNeeded(Path file, RSAPublicKey publicKey) {
    byte[] encoded = publicKey.getEncoded();
-   if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {
-     Files.write(file, encoded);
+   try {
+     if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {
+       Files.write(file, encoded);
+     }
+   } catch (IOException e) {
+     log.warn("Could not update compatibility public key {}", file, e);
    }
  }

Signature verifier = Signature.getInstance("SHA512withRSA");
verifier.initVerify(publicKey);
verifier.update(probe);
if (!verifier.verify(signedProbe)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what happens if the private and public keys have different sizes, like 2048-bit vs 4096-bit? verifier.verify() throws SignatureException ("Bad signature length") instead of returning false, so callers miss the "do not match" error naming both files. should we catch SignatureException and throw the same IllegalStateException with the cause, and add a test for mismatched key sizes?

* once, when the configuration is loaded. Leaving the setting unset is deprecated: the server then
* uses {@code private_key.der} and {@code public_key.der} in the UC configuration folder,
* generating them on first start.
* uses {@code private_key.der} and {@code public_key.der} in the UC configuration folder, deriving

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this javadoc still says public_key.der is only written on first start, whereas now a pair is generated only when private_key.der is missing, CRT keys create/repair public_key.der, and non-CRT keys read and verify it. could we update this to match? also please update the PR description and auth upgrade docs so they don't say readPublicKey was removed or that keys can never mismatch.

Files.createDirectories(parentDirectory);
}
Files.write(publicKeyFile, keyPair.getPublic().getEncoded(), StandardOpenOption.CREATE);
Files.write(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are we writing publicKeyFile both here and in writePublicKeyIfNeeded? if initializeIfMissing only writes privateKeyFile, then writePublicKeyIfNeeded can be the single place that creates or repairs public_key.der with one error policy. could we also add a test where a stale public_key.der exists without private_key.der?

Do not prevent server startup if the compatibility public key cannot be written.

Signed-off-by: Yajnesh K <[email protected]>
Keep compatibility public key writes best-effort in one place, report mismatched key sizes consistently, update the upgrade documentation, and test the edge cases.

Signed-off-by: Yajnesh K <[email protected]>
@yajneshx94

Copy link
Copy Markdown
Author

Thanks @timothyw553 and @shba24. I've pushed updates (c686212 and
1c8545a) addressing your comments: the public_key.der write is
best-effort and happens in one place; a new pair is generated only when
private_key.der is missing; and older keys fall back to public_key.der
with a pair check that handles mismatched key sizes. I also updated the
Javadoc, upgrade docs, and PR description, and added tests for these
cases.

Please let me know if anything else needs changing.

privateKey = readPrivateKey(privateKeyFile);
publicKey = readPublicKey(publicKeyFile);
if (privateKey instanceof RSAPrivateCrtKey) {
publicKey = publicKeyOf(privateKey, privateKeyFile);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): CRT check is repeated, so the rule lives in two places

The folder constructor tests instanceof RSAPrivateCrtKey to choose between deriving and reading the public key. publicKeyOf then tests the same thing and throws. Both are needed, because the settings path relies on that throw, but a change to the rule must be made in both.

Cost of keeping it: If another key type that carries a public exponent were accepted later and only one check were updated, the folder fallback and the fromPrivateKeyFile error would disagree.

private static boolean canDerivePublicKey(RSAPrivateKey key) {
  return key instanceof RSAPrivateCrtKey;
}
Evidence
SecurityConfiguration.java:80-82: `if (privateKey instanceof RSAPrivateCrtKey) {\n      publicKey = publicKeyOf(privateKey, privateKeyFile);` and SecurityConfiguration.java publicKeyOf: `if (!(privateKey instanceof RSAPrivateCrtKey crtKey)) {\n      throw new IllegalStateException(\n          "The key in " ... + " has no public exponent; create it with" + " `openssl genrsa`");`. The same type test sits in both places, and from the folder path the throw cannot run.
How it was checked

Checked by 1 independent check: NITPICK

Is a small shared predicate worth it here, or is leaving it as is fine? Catching the exception from publicKeyOf would be worse, since it mixes unsupported keys with real derivation errors.

private static void verifyKeyPair(
RSAPrivateKey privateKey, RSAPublicKey publicKey, Path privateKeyFile, Path publicKeyFile) {
byte[] probe = "unitycatalog-key-pair-check".getBytes(StandardCharsets.US_ASCII);
Signature signer = Signature.getInstance("SHA512withRSA");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): Key pair check repeats the SHA512withRSA literal apart from the token algorithm

verifyKeyPair types "SHA512withRSA" twice, and algorithmRSA() separately uses Algorithm.RSA512. Nothing keeps these in step. Today they agree, so no behavior is wrong.

Cost of keeping it: If token signing moved to another scheme (RS256 or PSS), the startup probe would keep testing SHA512withRSA. It could then pass or fail for reasons unrelated to how tokens are signed.

private static final String KEY_PAIR_CHECK_ALGORITHM = "SHA512withRSA"; // must match Algorithm.RSA512 in algorithmRSA()
Evidence
SecurityConfiguration.java:187 and :192: `Signature signer = Signature.getInstance("SHA512withRSA");` / `Signature verifier = Signature.getInstance("SHA512withRSA");`. SecurityConfiguration.java:220-221: `public Algorithm algorithmRSA() {\n    return Algorithm.RSA512(publicKey, privateKey);`. The signing algorithm is defined separately for the startup probe and for real token signing.
How it was checked

Checked by 1 independent check: NITPICK

Would a single constant next to algorithmRSA() be enough here?

publicKey = publicKeyOf(privateKey, privateKeyFile);
writePublicKeyIfNeeded(publicKeyFile, publicKey);
} else {
publicKey = readPublicKey(publicKeyFile);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): Missing public_key.der with a non-CRT key fails with a bare NoSuchFileException

The base code regenerated the pair when either file was missing. Now only private_key.der is checked. For a non-CRT key, readPublicKey reaches Files.readAllBytes on the missing file, and @SneakyThrows lets the NoSuchFileException out with only the path as its message. Failing is the intended behavior. What could not be settled is whether anything on the startup path wraps that error with context, because no test ran this input.

For example: An operator upgrades with a legacy folder that holds a non-CRT private_key.der and no public_key.der. Startup stops with a path-only NoSuchFileException, and nothing says the key has no public exponent and so needs a matching public key file.

if (Files.notExists(publicKeyFile)) {
  throw new IllegalStateException(
      "The key in " + privateKeyFile.toAbsolutePath()
          + " has no public exponent, so the server needs the matching public key in "
          + publicKeyFile.toAbsolutePath());
}
Evidence
SecurityConfiguration.java:77-85: `initializeIfMissing(privateKeyFile);` then `privateKey = readPrivateKey(privateKeyFile); if (privateKey instanceof RSAPrivateCrtKey) { ... } else { publicKey = readPublicKey(publicKeyFile); verifyKeyPair(...); }`. readKeyFile begins with `byte[] content = Files.readAllBytes(file);`, and readPublicKey is `@SneakyThrows`, so a missing public_key.der surfaces as a raw NoSuchFileException. The removed guard was `if (Files.notExists(publicKeyFile) || Files.notExists(privateKeyFile)) {`, which used to regenerate the pair in this case. The existing helper `requireFile` ("No token signing key file at " + file.toAbsolutePath()) is used only by fromPrivateKeyFile. SecurityConfigurationTest has no non-CRT test without public_key.der: its non-CRT tests are loadsExistingNonCrtKeyPair..., rejectsMismatchedNonCrtKeyPair... and rejectsNonCrtKeysWithDifferentModulusSizes, and all three write public_key.der.
How it was checked

Checked by 1 independent check: CONFIRMED

Missing fact: Only codex ruled (CONFIRMED, by reading plus JDK 17 class inspection); no proof was run because the gate skipped nits. My own reading supports the claim. At base_sha, initializeIfMissing regenerated the pair whenever either file was missing (base line 143: Files.notExists(publicKeyFile) || Files.notExists(privateKeyFile)). At head it checks only private_key.der (line 152). For a non-CRT key, the constructor calls readPublicKey, then readKeyFile, then Files.readAllBytes (line ~264) with no existence check. readPublicKey catches only InvalidKeySpecException, so the IOException escapes through @SneakyThrows unwrapped. A real operator reaches this by upgrading with a legacy folder that holds a non-CRT private_key.der and no public_key.der. They end with startup failing on a NoSuchFileException that shows only the path. That is better than base, which silently replaced their signing key, but it is undiagnosed. The claim is testable, and nothing tested it. The missing fact: run a test that writes a non-CRT private_key.der with no public_key.der and checks the thrown type and message. If something on the path (for example a wrapper in load() or the server bootstrap) wrapped the error with context, the verdict would drop to DISPROVED or NITPICK. If the test shows a bare NoSuchFileException, it is CONFIRMED.

Would a check like this in the non-CRT branch, with a test on the message, be worth adding?

new RSAPrivateKeySpec(crtKey.getModulus(), crtKey.getPrivateExponent()));
assertThat(nonCrtKey).isNotInstanceOf(RSAPrivateCrtKey.class);
Files.write(configurationFolder.resolve("private_key.der"), nonCrtKey.getEncoded());
Files.write(configurationFolder.resolve("public_key.der"), keyPair.getPublic().getEncoded());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): Non-CRT key with a missing or garbage public_key.der has no failure test

The non-CRT branch is the only one that still reads public_key.der. Every non-CRT test writes a valid encoded public key. The tests with a missing or malformed file use CRT keys, which derive the public key and never read the file.

For example: A change that made a missing file fall back to a freshly generated key, or that tolerated {1, 2, 3} as a public key, would pass the whole suite. The same goes for a PEM file holding only a CERTIFICATE block.

// build a non-CRT private_key.der as loadsExistingNonCrtKeyPairFromConfigurationFolder does, then for each setup:
//   (a) no public_key.der
//   (b) public_key.der = {1, 2, 3}
//   (c) public_key.der = PEM with only a CERTIFICATE block
// assert new SecurityConfiguration(folder) throws,
// private_key.der is byte-for-byte unchanged,
// and in (a) public_key.der was not created
Evidence
SecurityConfiguration.java:79-85: `if (privateKey instanceof RSAPrivateCrtKey) { ... } else { publicKey = readPublicKey(publicKeyFile); verifyKeyPair(privateKey, publicKey, privateKeyFile, publicKeyFile); }`. The non-CRT tests in SecurityConfigurationTest (loadsExistingNonCrtKeyPairFromConfigurationFolder, rejectsMismatchedNonCrtKeyPairFromConfigurationFolder, rejectsNonCrtKeysWithDifferentModulusSizes) each write a valid, parseable public_key.der before constructing. None leaves it missing or malformed, so the read-failure behavior of this branch is not asserted.
How it was checked

Checked by 1 independent check: CONFIRMED

Would a small parameterized case in this class work for these three inputs?

@yajneshx94

Copy link
Copy Markdown
Author

Thanks @shba24. I've pushed an update covering all four points: a shared
canDerivePublicKey check, a single constant for the probe algorithm, a
clearer error when a non-CRT key has no public_key.der, and tests for the
missing, malformed and certificate-only cases. Please take another look
when you have a chance.

@yajneshx94
yajneshx94 force-pushed the fix/derive-public-key-from-private-key branch from 9aa3f94 to f68aadf Compare November 26, 2026 08:34
byte[] encoded = publicKey.getEncoded();
try {
if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {
Files.write(file, encoded);

@shba24 shba24 Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: A failed compatibility write leaves public_key.der empty, so a rollback cannot read the key

writePublicKeyIfNeeded compares the existing bytes with the DER encoding. A valid PEM public_key.der never equals the DER, so Files.write always runs. Files.write opens with CREATE and TRUNCATE_EXISTING, so a failure after the open leaves a 0-byte file. The catch at this line only logs a warning, so startup continues. The previously valid PEM public key is lost, and a rollback to the base release, which reads PEM public keys, fails on the empty file.

The same in-place rewrite shape appears in writeOwnerOnly (about line 227). It deletes private_key.der, creates it empty, then writes it, so a failed write leaves an empty private key. The next start sees that the file exists, does not regenerate it, and fails in readPrivateKey. That one predates this PR and is out of scope here.

For example: An operator has a CRT private_key.der and a matching PEM public_key.der, and the disk fills or returns EIO during startup. The write fails after the file is truncated, the warning is logged, and the server starts with the derived key. public_key.der is now empty, so a rollback to the base release cannot start. The proof test keepsMatchingPemPublicKeyWhenCompatibilityWriteFails fails with expected: [PEM bytes] but was: []. The fault is injected with mockStatic, not a real full disk.

Write the new bytes to a temporary sibling of public_key.der, for example with Files.createTempFile(file.getParent(), ...). Replace the file with Files.move(tmp, file, REPLACE_EXISTING, ATOMIC_MOVE) only after the write succeeds, and delete the temporary file in the catch. Keep the warning-only policy. Skipping the rewrite when the file already parses to the derived key is not enough, because releases before PEM support read only DER and still need the conversion. Keep keepsMatchingPemPublicKeyWhenCompatibilityWriteFails as the regression test.

Evidence

L13 asks, “After it completes, do I verify the expected state?” The write truncates the existing file and catches an I/O failure without preserving it; the upgrade docs identify that file as needed by earlier versions.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:183-195

  private static void writePublicKeyIfNeeded(Path file, RSAPublicKey publicKey) {
    byte[] encoded = publicKey.getEncoded();
    try {
      if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {
        Files.write(file, encoded);
      }
    } catch (IOException e) {
      log.warn(
          "Could not write compatibility public key file {}. The server will continue using the"
              + " public key derived from the private key.",
          file,
          e);
    }

docs/server/auth.md:289-293

When the server uses the deprecated `etc/conf` key folder, it derives the public key from
`private_key.der` when that key contains the required RSA CRT fields. It updates
`public_key.der` on a best-effort basis for compatibility with earlier versions. Older RSA private
keys without CRT fields still require a matching `public_key.der`; the server verifies the pair
when it starts.
How it was checked

Reproduced: dev/run-tests.py -p 1 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest -- --tests=.*keepsMatchingPemPublicKeyWhenCompatibilityWriteFails.*'

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.keepsMatchingPemPublicKeyWhenCompatibilityWriteFails failed: org.opentest4j.AssertionFailedError: expected: [45, 45, 45, 45, 45, 66, 69, 71, 73, 78, 32, 80, 85, 66, 76, 73, 67, 32, 75, 69, 89, ...] (the PEM public key bytes) but was: [], took 1.636s
[error] Failed: Total 22, Failed 1, Errors 0, Passed 12, Skipped 9

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:191-217

  @Test
  void keepsMatchingPemPublicKeyWhenCompatibilityWriteFails() throws Exception {
    KeyPair keyPair = newKeyPair();
    Files.write(configurationFolder.resolve("private_key.der"), keyPair.getPrivate().getEncoded());
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    byte[] pemPublicKey = pem("PUBLIC KEY", keyPair.getPublic().getEncoded()).getBytes();
    Files.write(publicKeyFile, pemPublicKey);

    try (MockedStatic<Files> files = Mockito.mockStatic(Files.class, Mockito.CALLS_REAL_METHODS)) {
      // Like Files.write: open with TRUNCATE_EXISTING, then fail (e.g. disk full).
      files
          .when(() -> Files.write(Mockito.eq(publicKeyFile), Mockito.any(byte[].class)))
          .thenAnswer(
              invocation -> {
                Files.newOutputStream(
                        publicKeyFile,
                        StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING)
                    .close();
                throw new IOException("No space left on device");
              });
      SecurityConfiguration configuration = new SecurityConfiguration(configurationFolder);
      assertThat(configuration.rsaPublicKey()).isEqualTo(keyPair.getPublic());
    }

    assertThat(Files.readAllBytes(publicKeyFile)).isEqualTo(pemPublicKey);
  }

Checked by 2 independent checks: CONTESTED

How about writing to a temporary file and moving it into place, so the old file survives a failed write?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @shba24, good catch. I've changed the compatibility write to use
a temporary file in the same folder and move it into place only after
the write succeeds, so a failed write leaves the existing
public_key.der untouched, and the temporary file is cleaned up. The
warning-only behaviour is unchanged, and I've added
keepsMatchingPemPublicKeyWhenCompatibilityWriteFails. I'm leaving the
Optional suggestion as it is, as you said that's fine.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, and the original truncation concern no longer applies at the head. I checked SecurityConfiguration.java:184-214. writePublicKeyIfNeeded creates a temp file in the same folder as public_key.der and writes to it. It moves the file over public_key.der only after the write returns. A failed write or move goes to the existing warning-only catch and leaves public_key.der as it was. The finally block deletes any temp file still left.

I ran dev/run-tests.py -p 1 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest' at 8bd4a49a, and all 22 tests passed. keepsMatchingPemPublicKeyWhenCompatibilityWriteFails injects an IOException into the temp-file write. It asserts that startup completes, that the PEM bytes in public_key.der are unchanged, and that the folder holds only private_key.der and public_key.der. The same test fails on the earlier in-place write from f68aadfb, with the PEM bytes truncated (SecurityConfigurationTest.java:228). So it does guard against this regression.

I don't need the optional suggestion changed. This thread can be resolved.

}
}

private static boolean canDerivePublicKey(RSAPrivateKey privateKey) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): The CRT rule is checked in the constructor and again in publicKeyOf

The constructor calls canDerivePublicKey at :82, and publicKeyOf checks it again and then casts to RSAPrivateCrtKey at :151-160. The result of the check is not carried in a type, so the rule has to stay in step in the predicate, the cast and the two messages.

The two messages are intentionally different, because fromPrivateKeyFile (:137) also reaches the guard directly and needs the openssl genrsa hint. This is a small shape preference, and leaving it as it is is fine, since the shared predicate was what an earlier review asked for.

Cost of keeping it: A later change, such as a new key type or a reworded message, updates one of the checks and misses the others. The constructor and publicKeyOf then disagree about which keys can be derived.

Optionally replace canDerivePublicKey plus publicKeyOf with derivePublicKey(RSAPrivateKey) returning Optional<RSAPublicKey>. Each caller keeps its own empty-case handling: the folder constructor falls back to public_key.der, and fromPrivateKeyFile throws its existing openssl message.

Evidence

canDerivePublicKey is a boolean that stands in for 'this is an RSAPrivateCrtKey'. The constructor branches on it, and publicKeyOf then checks it again and casts. The type system does not carry the result of the check. The 'no public exponent' state is reported by two different messages: one in the constructor branch, one inside publicKeyOf that the constructor can never reach.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:82-95

    if (canDerivePublicKey(privateKey)) {
      publicKey = publicKeyOf(privateKey, privateKeyFile);
      writePublicKeyIfNeeded(publicKeyFile, publicKey);
    } else {
      if (Files.notExists(publicKeyFile)) {
        throw new IllegalStateException(
            "The private key in "
                + privateKeyFile.toAbsolutePath()
                + " has no public exponent; a matching public key is required at "
                + publicKeyFile.toAbsolutePath());
      }
      publicKey = readPublicKey(publicKeyFile);
      verifyKeyPair(privateKey, publicKey, privateKeyFile, publicKeyFile);
    }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:147-164

  private static boolean canDerivePublicKey(RSAPrivateKey privateKey) {
    return privateKey instanceof RSAPrivateCrtKey;
  }

  @SneakyThrows
  private static RSAPublicKey publicKeyOf(RSAPrivateKey privateKey, Path file) {
    if (!canDerivePublicKey(privateKey)) {
      throw new IllegalStateException(
          "The key in "
              + file.toAbsolutePath()
              + " has no public exponent; create it with"
              + " `openssl genrsa`");
    }
    RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey) privateKey;
    return (RSAPublicKey)
        KeyFactory.getInstance("RSA")
            .generatePublic(new RSAPublicKeySpec(crtKey.getModulus(), crtKey.getPublicExponent()));
  }
How it was checked

Checked by 1 independent check: DISPROVED

Does folding the check into one Optional-returning method seem worth it, or is the current shape fine?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I'll keep the current shape since you mentioned it's fine as is.

try {
if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {
temporaryFile =
Files.createTempFile(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: Replacing the public key can remove rollback readers' access

Files.createTempFile creates an owner-only file on POSIX. Moving that file into place removes the existing group's read access even though the compatibility write reports success.

For example: A service account repairs a stale public key with mode 0640. On JDK 17 the replacement has mode 0600, so a rollback account that relied on group access can no longer read it.

Before Files.move, when public_key.der exists and the file system supports POSIX, copy its PosixFilePermissions (Files.getPosixFilePermissions / setPosixFilePermissions) and, where possible, its group (PosixFileAttributeView.setGroup) onto the temp file. When it does not exist, create the temp file with PosixFilePermissions.asFileAttribute(rw-r--r--). Extend the stale-public-key test to assert the mode is preserved.

Evidence

The temp file is created without attributes, and the move installs that file at the existing path. I checked the entire writer for preservation of access attributes. On the local JDK 17 POSIX filesystem, these operations replaced a file with mode 0640 with one having mode 0600. A rollback process that previously relied on group read permission loses access even when the publication succeeds.

L20 asks: “Does this behave across supported versions?” The atomic replacement installs a new temporary file without preserving the existing file’s permissions; on this Linux host it changed 0644 to 0600. The documentation identifies the file as compatibility data for earlier releases, which read it at startup.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:188-198

      if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {
        temporaryFile =
            Files.createTempFile(
                file.toAbsolutePath().getParent(), file.getFileName().toString(), ".tmp");
        Files.write(temporaryFile, encoded);
        Files.move(
            temporaryFile,
            file,
            StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.ATOMIC_MOVE);
        temporaryFile = null;

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:266-270

  @SneakyThrows
  private static RSAPublicKey readPublicKey(Path file) {
    X509EncodedKeySpec spec = new X509EncodedKeySpec(readKeyFile(file, "PUBLIC KEY"));
    try {
      return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(spec);

docs/server/auth.md:289-293

When the server uses the deprecated `etc/conf` key folder, it derives the public key from
`private_key.der` when that key contains the required RSA CRT fields. It updates
`public_key.der` on a best-effort basis for compatibility with earlier versions. Older RSA private
keys without CRT fields still require a matching `public_key.der`; the server verifies the pair
when it starts.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:184-197

  private static void writePublicKeyIfNeeded(Path file, RSAPublicKey publicKey) {
    byte[] encoded = publicKey.getEncoded();
    Path temporaryFile = null;
    try {
      if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {
        temporaryFile =
            Files.createTempFile(
                file.toAbsolutePath().getParent(), file.getFileName().toString(), ".tmp");
        Files.write(temporaryFile, encoded);
        Files.move(
            temporaryFile,
            file,
            StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.ATOMIC_MOVE);
How it was checked

Reproduced: dev/run-tests.py "server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest"

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.keepsGroupReadOnReplacedPublicKey failed: org.opentest4j.AssertionFailedError: 
[error] Failed: Total 23, Failed 1, Errors 0, Passed 22
Failed tests:
  io.unitycatalog.server.security.SecurityConfigurationTest#keepsGroupReadOnReplacedPublicKey(): org.opentest4j.AssertionFailedError: expected: "rw-r-----" but was: "rw-------" (SecurityConfigurationTest.java:165)

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:152-166


  @Test
  void keepsGroupReadOnReplacedPublicKey() throws Exception {
    KeyPair keyPair = newKeyPair();
    Files.write(configurationFolder.resolve("private_key.der"), keyPair.getPrivate().getEncoded());
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    Files.write(publicKeyFile, newKeyPair().getPublic().getEncoded());
    Files.setPosixFilePermissions(publicKeyFile, PosixFilePermissions.fromString("rw-r-----"));

    new SecurityConfiguration(configurationFolder);

    assertThat(Files.readAllBytes(publicKeyFile)).isEqualTo(keyPair.getPublic().getEncoded());
    assertThat(PosixFilePermissions.toString(Files.getPosixFilePermissions(publicKeyFile)))
        .isEqualTo("rw-r-----");
  }

Checked by 2 independent checks, which split: CONTESTED, CONFIRMED

References:

Could the replacement retain the existing public file's access permissions?

Files.createTempFile(
file.toAbsolutePath().getParent(), file.getFileName().toString(), ".tmp");
Files.write(temporaryFile, encoded);
Files.move(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: A compatibility update can erase the signing key

The legacy reader can select either key from a PEM bundle. If the private-key path points to the file being replaced, publishing the derived key removes the only private key on disk. This is one bug class: The compatibility write replaces whatever public_key.der resolves to without checking whether that path is the private key or another file the operator manages. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:188 (The check compares raw bytes, so a valid public_key.der in PEM that matches the key is still treated as stale and rewritten as DER (the test keepsMatchingPemPub); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:169 (Files.notExists follows links, so a dangling private_key.der symlink (for example to a secret that is not mounted yet) counts as missing. writeOwnerOnly (line 2).

For example: Suppose private_key.der links to public_key.der, which contains matching private and public PEM blocks. The first start succeeds, but the next follows the same link and finds only public DER.

Pass the private-key path to writePublicKeyIfNeeded. Before replacing an existing public_key.der, check Files.isSameFile(privateKeyFile, publicKeyFile). If both names resolve to the same file, leave it alone and log a warning that the compatibility public key was not written. Add the symlinked-PEM-bundle test (two constructions must both succeed) to SecurityConfigurationTest.

Evidence

The constructor resolves two names and reads the private key before calling the compatibility writer. readKeyFile selects a block by kind, so both names can previously have worked with the same PEM bundle. I checked load, initializeIfMissing and writePublicKeyIfNeeded. None checks whether the private path resolves to the public destination. The successful move replaces the only copy of the bundle in this layout.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:78-85

  public SecurityConfiguration(Path configurationFolder) {
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    initializeIfMissing(privateKeyFile);
    privateKey = readPrivateKey(privateKeyFile);
    if (canDerivePublicKey(privateKey)) {
      publicKey = publicKeyOf(privateKey, privateKeyFile);
      writePublicKeyIfNeeded(publicKeyFile, publicKey);

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:188-197

      if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {
        temporaryFile =
            Files.createTempFile(
                file.toAbsolutePath().getParent(), file.getFileName().toString(), ".tmp");
        Files.write(temporaryFile, encoded);
        Files.move(
            temporaryFile,
            file,
            StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.ATOMIC_MOVE);

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:297-306

  private static byte[] readKeyFile(Path file, String kind) throws IOException {
    byte[] content = Files.readAllBytes(file);
    Matcher pem = PEM_BLOCK.matcher(new String(content, StandardCharsets.US_ASCII));
    boolean foundPem = false;
    while (pem.find()) {
      foundPem = true;
      String type = pem.group(1);
      if (!type.endsWith(kind)) {
        continue;
      }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:313-325

      byte[] der;
      try {
        der = Base64.getMimeDecoder().decode(pem.group(2));
      } catch (IllegalArgumentException e) {
        throw new IllegalStateException("Cannot read the PEM key in " + file.toAbsolutePath(), e);
      }
      return type.equals("RSA PRIVATE KEY") ? pkcs1ToPkcs8(der) : der;
    }
    if (foundPem) {
      throw new IllegalStateException("No " + kind + " PEM block in " + file.toAbsolutePath());
    }
    return content;
  }
How it was checked

Reproduced: dev/run-tests.py "server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest"

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.keepsPemBundleWhenPrivateKeyFileLinksToPublicKeyFile failed: java.lang.IllegalStateException: Cannot read the RSA private key in .../junit-8133005624009554537/private_key.der; expected an unencrypted RSA private key in PKCS #8 PEM or DER, or PKCS #1 PEM
[error] Failed: Total 23, Failed 1, Errors 0, Passed 22

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:235-248

  @Test
  void keepsPemBundleWhenPrivateKeyFileLinksToPublicKeyFile() throws Exception {
    KeyPair keyPair = newKeyPair();
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    Files.writeString(
        publicKeyFile,
        pem("PRIVATE KEY", keyPair.getPrivate().getEncoded())
            + pem("PUBLIC KEY", keyPair.getPublic().getEncoded()));
    Files.createSymbolicLink(configurationFolder.resolve("private_key.der"), publicKeyFile);

    new SecurityConfiguration(configurationFolder);
    SecurityConfiguration second = new SecurityConfiguration(configurationFolder);

    assertThat(second.rsaPublicKey()).isEqualTo(keyPair.getPublic());

Checked by 2 independent checks, which split: CONTESTED, CONFIRMED

References:

Could we skip the compatibility write when both paths resolve to the same file?

publicKey = readPublicKey(publicKeyFile);
if (canDerivePublicKey(privateKey)) {
publicKey = publicKeyOf(privateKey, privateKeyFile);
writePublicKeyIfNeeded(publicKeyFile, publicKey);

@shba24 shba24 Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: Concurrent starts can leave a mismatched key pair on disk

writeOwnerOnly can delete a key installed after the existence check. The final atomic move then lets a delayed initializer publish a public key that no longer matches the private file. This is one bug class: First-time key installation and the public-key publish are check-then-act steps across processes, with no single winner and no re-read of the persisted key. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:193 (Each process publishes the public key derived from the private key it read itself. If B overwrote private_key.der after A read it, A's later move installs A's p); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:246 (writeOwnerOnly deletes any existing private_key.der before creating it, so a second initializer that passed the notExists check at line 169 destroys a key the f); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:248 (createFile followed by Files.write leaves a window where private_key.der exists but is empty or partial. A concurrent starter sees that it exists, skips initial); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:180 (The head now writes private_key.der first and public_key.der later, at line 193. In a mixed-version rolling start, an earlier-release instance that checks the f).

For example: Both servers see private_key.der missing. The first installs and reads its key, the second installs and publishes its own pair, then the first publishes its older public key last.

Serialize first-time initialization across processes, or publish a fully written private key without replacing an existing winner and have every initializer derive from that winner.

Evidence

Both processes can pass notExists before either finishes generating. writeOwnerOnly deletes any file that appeared in the meantime. Each constructor then retains the key it read, and the new move can publish that key's public half after another process has installed both halves of a newer pair. I checked UnityCatalogServer startup, the constructor, both file writers and the test setup. Only the test fixture serializes initialization. The atomic move protects one file, not the pair.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:78-85

  public SecurityConfiguration(Path configurationFolder) {
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    initializeIfMissing(privateKeyFile);
    privateKey = readPrivateKey(privateKeyFile);
    if (canDerivePublicKey(privateKey)) {
      publicKey = publicKeyOf(privateKey, privateKeyFile);
      writePublicKeyIfNeeded(publicKeyFile, publicKey);

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:168-181

  private static void initializeIfMissing(Path privateKeyFile) {
    if (Files.notExists(privateKeyFile)) {
      log.info("Initializing security configuration.");
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(2048);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();

      // Create parent directory first if it does not exist
      Path parentDirectory = privateKeyFile.getParent();
      if (parentDirectory != null && !Files.exists(parentDirectory)) {
        Files.createDirectories(parentDirectory);
      }
      writeOwnerOnly(privateKeyFile, keyPair.getPrivate().getEncoded());
    }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:244-252

  // Creates the file readable and writable by its owner only, where the file system supports it.
  private static void writeOwnerOnly(Path file, byte[] content) throws IOException {
    Files.deleteIfExists(file);
    if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
      Files.createFile(
          file, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
    }
    Files.write(file, content);
  }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:188-198

      if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {
        temporaryFile =
            Files.createTempFile(
                file.toAbsolutePath().getParent(), file.getFileName().toString(), ".tmp");
        Files.write(temporaryFile, encoded);
        Files.move(
            temporaryFile,
            file,
            StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.ATOMIC_MOVE);
        temporaryFile = null;

server/src/test/java/io/unitycatalog/server/base/BaseServerTest.java:139-147

  /**
   * Copies this JVM's signing keys into {@code target}, generating them on first use. Saves the RSA
   * key generation the server would otherwise do for every test.
   */
  private static synchronized void copySigningKeys(Path target) throws IOException {
    if (signingKeysFolder == null) {
      Path folder = Files.createTempDirectory("uc-test-keys");
      new SecurityConfiguration(folder);
      folder.toFile().deleteOnExit();
How it was checked

Reproduced: build/sbt "server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest"

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.disproveConcurrentFirstStartsLeaveMatchingPair failed: org.opentest4j.AssertionFailedError: 
[error] expected: 28000375918648889365709007017764380320252541924288323208928992613404817895557603567711592474879216326840825750838111947204090211170668359142345832177772801107764889877233834406254678331845719739842609980242427759935571081256849334573609303119707738241876338013201919532185975226001989506203781191728045915300742367833910363607851646186588774453074158339775154822599536618013206892464629687127801377604170654764606942006365769814483921476123729803194989530113713763824098727558243429642958313841046760864737857972171736352641859221265198439606048422257937349933442125728345947388807195245939585845118070527175398553379
[error]  but was: 22706575729564969731442251644069304592566990574081482243190997592222882142514705433374740045241996650919936975166647039727654930936833172904694837703897060304614465208967686588714489270189986222906029577546881533033685834528588831385782420925245923924277326759035050031421899703308411722197287272016815779821570111593332658302969219301383158058014118640867351532752894153150840244421226640160538003873525137764651281913702010354116383679669600104858949530028879906214000288436430748051762104553737877128730887293614336248849520848795709692083818244805229605740789006259345693253161010868378187183234771297577783776053, took 4.029s
[error] Failed: Total 23, Failed 1, Errors 0, Passed 22

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:330-423

  // Two servers start on one empty folder. Both see no key; A writes and reads its key; B replaces
  // it and publishes its public key; then A publishes its own public key over B's.
  @Test
  void disproveConcurrentFirstStartsLeaveMatchingPair() throws Exception {
    CountDownLatch aChecked = new CountDownLatch(1);
    CountDownLatch bChecked = new CountDownLatch(1);
    CountDownLatch aReadyToPublish = new CountDownLatch(1);
    CountDownLatch bDone = new CountDownLatch(1);
    ExecutorService executor = Executors.newFixedThreadPool(2);
    try {
      Future<?> a =
          executor.submit(
              () ->
                  startWithHooks(
                      () -> {
                        aChecked.countDown();
                        await(bChecked);
                      },
                      () -> {
                        aReadyToPublish.countDown();
                        await(bDone);
                      }));
      while (!aChecked.await(1, TimeUnit.SECONDS)) {
        if (a.isDone()) {
          a.get();
        }
      }
      Future<?> b =
          executor.submit(
              () ->
                  startWithHooks(
                      () -> {
                        bChecked.countDown();
                        await(aReadyToPublish);
                      },
                      () -> {}));
      b.get(60, TimeUnit.SECONDS);
      bDone.countDown();
      a.get(60, TimeUnit.SECONDS);
    } finally {
      executor.shutdownNow();
    }

    RSAPrivateCrtKey privateKey =
        (RSAPrivateCrtKey)
            KeyFactory.getInstance("RSA")
                .generatePrivate(
                    new PKCS8EncodedKeySpec(
                        Files.readAllBytes(configurationFolder.resolve("private_key.der"))));
    RSAPublicKey publicKey =
        (RSAPublicKey)
            KeyFactory.getInstance("RSA")
                .generatePublic(
                    new X509EncodedKeySpec(
                        Files.readAllBytes(configurationFolder.resolve("public_key.der"))));
    assertThat(publicKey.getModulus()).isEqualTo(privateKey.getModulus());
  }

  private static void await(CountDownLatch latch) {
    try {
      assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue();
    } catch (InterruptedException e) {
      throw new IllegalStateException(e);
    }
  }

  // Starts a server on the folder; the hooks run once, right after the private key existence check
  // and right before the public key file is replaced. Static mocks are thread-local.
  private void startWithHooks(Runnable afterPrivateKeyCheck, Runnable beforePublicKeyMove) {
    AtomicBoolean checked = new AtomicBoolean();
    AtomicBoolean moved = new AtomicBoolean();
    try (MockedStatic<Files> files =
        mockStatic(
            Files.class,
            invocation -> {
              String name = invocation.getMethod().getName();
              Object[] args = invocation.getArguments();
              Object first = args.length > 0 ? args[0] : "";
              if (name.equals("move")
                  && args[1].toString().endsWith("public_key.der")
                  && moved.compareAndSet(false, true)) {
                beforePublicKeyMove.run();
              }
              Object result = invocation.callRealMethod();
              if (name.equals("notExists")
                  && first.toString().endsWith("private_key.der")
                  && checked.compareAndSet(false, true)) {
                afterPrivateKeyCheck.run();
              }
              return result;
            })) {
      new SecurityConfiguration(configurationFolder);
    }
  }

Checked by 2 independent checks: CONFIRMED

Could both startups use the same persisted private key before either publishes its public half?

byte[] signedProbe = signer.sign();

Signature verifier = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
verifier.initVerify(publicKey);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: A short mismatched public key bypasses the two-file diagnostic

initVerify runs before the mismatch handler. A parseable RSA key can be too short for SHA512withRSA, so the startup error identifies neither key file. This is one bug class: Exceptions from the key-pair probe that are not SignatureException bypass the diagnostic that names both files. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:222 (signer.initSign(privateKey) also runs outside the try block. A non-CRT private key too short for SHA512withRSA throws an InvalidKeyException that does not name ).

For example: With a 2048-bit non-CRT private key and a 512-bit public key, JDK 17 throws InvalidKeyException in initVerify. The larger public key in the existing test reaches verify instead.

Compare the two RSA moduli first and use the existing two-path mismatch message when they differ. Keep the signing probe for keys with equal moduli.

Evidence

readPublicKey parses an RSA public key without testing its suitability for SHA512withRSA. verifyKeyPair initializes the verifier before constructing the two-path error and before entering the try block. I confirmed that initialization with a 512-bit RSA public key throws InvalidKeyException on JDK 17. The existing different-size test supplies a larger public key, which reaches verify instead.

The mismatch message and its exception handler come after verifier.initVerify. I checked the JDK 17 provider source and called initVerify with a 512-bit RSA public key locally. It threw InvalidKeyException with the message 'Key is too short for this signature algorithm'. The PR's different-size test uses a 4096-bit public key and reaches verify instead.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:94-95

      publicKey = readPublicKey(publicKeyFile);
      verifyKeyPair(privateKey, publicKey, privateKeyFile, publicKeyFile);

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:226-241

    Signature verifier = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
    verifier.initVerify(publicKey);
    verifier.update(probe);
    String mismatchMessage =
        "The RSA keys in "
            + privateKeyFile.toAbsolutePath()
            + " and "
            + publicKeyFile.toAbsolutePath()
            + " do not match";
    try {
      if (!verifier.verify(signedProbe)) {
        throw new IllegalStateException(mismatchMessage);
      }
    } catch (SignatureException e) {
      throw new IllegalStateException(mismatchMessage, e);
    }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:267-274

  private static RSAPublicKey readPublicKey(Path file) {
    X509EncodedKeySpec spec = new X509EncodedKeySpec(readKeyFile(file, "PUBLIC KEY"));
    try {
      return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(spec);
    } catch (InvalidKeySpecException e) {
      throw new IllegalStateException(
          "Cannot read the RSA public key in " + file.toAbsolutePath(), e);
    }

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:263-273

  void rejectsNonCrtKeysWithDifferentModulusSizes() throws Exception {
    KeyPair signingKeyPair = newKeyPair();
    KeyPair mismatchedKeyPair = newKeyPair(4096);
    PrivateKey nonCrtKey = nonCrtPrivateKey(signingKeyPair);
    Files.write(configurationFolder.resolve("private_key.der"), nonCrtKey.getEncoded());
    Files.write(
        configurationFolder.resolve("public_key.der"), mismatchedKeyPair.getPublic().getEncoded());

    assertThatThrownBy(() -> new SecurityConfiguration(configurationFolder))
        .hasMessageContaining("do not match")
        .hasCauseInstanceOf(SignatureException.class);

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:220-241

    byte[] probe = "unitycatalog-key-pair-check".getBytes(StandardCharsets.US_ASCII);
    Signature signer = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
    signer.initSign(privateKey);
    signer.update(probe);
    byte[] signedProbe = signer.sign();

    Signature verifier = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
    verifier.initVerify(publicKey);
    verifier.update(probe);
    String mismatchMessage =
        "The RSA keys in "
            + privateKeyFile.toAbsolutePath()
            + " and "
            + publicKeyFile.toAbsolutePath()
            + " do not match";
    try {
      if (!verifier.verify(signedProbe)) {
        throw new IllegalStateException(mismatchMessage);
      }
    } catch (SignatureException e) {
      throw new IllegalStateException(mismatchMessage, e);
    }
How it was checked

Reproduced: dev/run-tests.py "server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest"

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.rejectsNonCrtKeyWithShortMismatchedPublicKey failed: java.lang.AssertionError: 
[error] Failed: Total 23, Failed 1, Errors 0, Passed 22
rejectsNonCrtKeyWithShortMismatchedPublicKey(): java.lang.AssertionError: Expecting actual throwable to be an instance of: java.lang.IllegalStateException but was: java.security.InvalidKeyException: Key is too short for this signature algorithm at java.base/sun.security.rsa.RSASignature.initCommon(RSASignature.java:138)

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:276-288

  @Test
  void rejectsNonCrtKeyWithShortMismatchedPublicKey() throws Exception {
    KeyPair signingKeyPair = newKeyPair();
    KeyPair shortKeyPair = newKeyPair(512);
    PrivateKey nonCrtKey = nonCrtPrivateKey(signingKeyPair);
    Files.write(configurationFolder.resolve("private_key.der"), nonCrtKey.getEncoded());
    Files.write(
        configurationFolder.resolve("public_key.der"), shortKeyPair.getPublic().getEncoded());

    assertThatThrownBy(() -> new SecurityConfiguration(configurationFolder))
        .isInstanceOf(IllegalStateException.class)
        .hasMessageContaining("do not match");
  }

Checked by 2 independent checks: CONFIRMED

References:

Could we detect different moduli before initializing the signature probe?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1, should we move initVerify inside the try and catch InvalidKeyException too, with a test for a short key mismatch?

byte[] encoded = publicKey.getEncoded();
Path temporaryFile = null;
try {
if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): Rewriting an already-matching public_key.der on every start would go unnoticed

writePublicKeyIfNeeded skips the write when public_key.der already holds the derived key. No test asserts that skip.

If the equality check is lost, every start replaces the file through a temp file. On a read-only config folder, every start would also log the compatibility warning. This is one bug class: The no-write branches of the best-effort compatibility write have no test that would notice an unnecessary or leftover write. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:193 (Temp-file cleanup when Files.move fails (rather than Files.write) is untested. startsWhenCompatibilityPublicKeyCannotBeUpdated makes the move fail because publi).

For example: Replacing !Arrays.equals(Files.readAllBytes(file), encoded) with an always-true check leaves all 22 tests in SecurityConfigurationTest passing.

createsAGeneratedPrivateKeyReadableByItsOwnerOnly does start a second time on a matching pair, but it only checks the private key.

@Test
void keepsMatchingPublicKeyFileUntouched() throws Exception {
  KeyPair keyPair = newKeyPair();
  Files.write(configurationFolder.resolve("private_key.der"), keyPair.getPrivate().getEncoded());
  Path publicKeyFile = configurationFolder.resolve("public_key.der");
  Files.write(publicKeyFile, keyPair.getPublic().getEncoded());
  Files.setLastModifiedTime(publicKeyFile, FileTime.fromMillis(0));

  new SecurityConfiguration(configurationFolder);

  assertThat(Files.getLastModifiedTime(publicKeyFile).toMillis()).isZero();
}
Evidence

Line 188 skips the temp-file write and move when the file already matches. The only test that starts a second time on a matching pair (lines 110-124) checks only the private key. No test reads the public key file's metadata or the folder after a matching start. I searched the whole of SecurityConfigurationTest and the callers of new SecurityConfiguration( in BaseServerTest, BaseAuthCRUDTest, BaseAccessControlCRUDTest and AuthDecoratorTest. A mutant that always writes passed all 22 tests.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:184-199

  private static void writePublicKeyIfNeeded(Path file, RSAPublicKey publicKey) {
    byte[] encoded = publicKey.getEncoded();
    Path temporaryFile = null;
    try {
      if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {
        temporaryFile =
            Files.createTempFile(
                file.toAbsolutePath().getParent(), file.getFileName().toString(), ".tmp");
        Files.write(temporaryFile, encoded);
        Files.move(
            temporaryFile,
            file,
            StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.ATOMIC_MOVE);
        temporaryFile = null;
      }

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:109-124

  @Test
  void createsAGeneratedPrivateKeyReadableByItsOwnerOnly() throws Exception {
    // A blank setting counts as unset, so the server uses the key in the configuration folder.
    SecurityConfiguration generated =
        SecurityConfiguration.load(settings(Path.of(" ")), configurationFolder);

    assertThat(
            PosixFilePermissions.toString(
                Files.getPosixFilePermissions(configurationFolder.resolve("private_key.der"))))
        .isEqualTo("rw-------");
    assertThat(configurationFolder.resolve("public_key.der")).exists();
    // A later start reuses that key; key_id.txt is not needed.
    assertThat(configurationFolder.resolve("key_id.txt")).doesNotExist();
    assertThat(new SecurityConfiguration(configurationFolder).rsaPrivateKey())
        .isEqualTo(generated.rsaPrivateKey());
  }
How it was checked

Checked by 1 independent check: CONFIRMED

Would a small test like this, pinning the no-write case, be worth adding next to the stale-key tests?

byte[] encoded = publicKey.getEncoded();
Path temporaryFile = null;
try {
if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {

@shba24 shba24 Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: An oversized compatibility file can prevent startup

Files.readAllBytes sizes its allocation from the existing compatibility file. An OutOfMemoryError bypasses the IOException handler, so an optional repair can stop startup. This is one bug class: The best-effort compatibility step reads an operator-controlled file without a size bound, and only IOException is treated as best-effort. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:298 (readKeyFile also reads private_key.der, and on the non-CRT path public_key.der, in full and then runs the DOTALL PEM regex over it, with no size bound. That is ).

For example: An operator restores a valid private_key.der alongside an oversized public_key.der. The server derives its key successfully, then attempts to allocate an array for the entire stale file.

Compare at most the expected DER length plus one byte using a bounded read, then replace the file if the bytes or length differ.

Evidence

The comparison reads the entire existing file before replacing it. I checked constructor dispatch, the compatibility writer and its recovery path. They neither limit the read to the encoded key length nor handle the documented allocation failure. The startup caller needs no bytes from this file to sign or verify tokens in the CRT branch.

The in-memory verification key is already available when the constructor calls writePublicKeyIfNeeded. That helper reads all existing file bytes to compare them, and catches only IOException. JDK 17 explicitly throws OutOfMemoryError when the requested array is too large, so the compatibility comparison can terminate startup.

How it was checked

Reproduced: build/sbt "server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest"

head:

[info] Test ...SecurityConfigurationTest#startsWithOversizedStalePublicKey() started
[error] java.lang.OutOfMemoryError: Required array size too large
[error] 	at io.unitycatalog.server.security.SecurityConfiguration.writePublicKeyIfNeeded(SecurityConfiguration.java:188)
[error] 	at io.unitycatalog.server.security.SecurityConfiguration.<init>(SecurityConfiguration.java:85)
[error] 	at ...SecurityConfigurationTest.startsWithOversizedStalePublicKey(SecurityConfigurationTest.java:245)
[error] Error: Total 3, Failed 0, Errors 1, Passed 2

Checked by 2 independent checks: CONTESTED

References:

Could we bound the comparison by the size of the derived key?

Path temporaryFile = null;
try {
if (Files.notExists(file) || !Arrays.equals(Files.readAllBytes(file), encoded)) {
temporaryFile =

@shba24 shba24 Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): The compatibility public_key.der becomes readable by its owner only

writePublicKeyIfNeeded writes the public key to a temp file from Files.createTempFile and then moves it over public_key.der.

On POSIX that temp file is created rw-------, so the moved file keeps those permissions. The old code wrote public_key.der with Files.write, which follows the umask.

For example: Say a fresh install, or a start that repairs a stale or missing public_key.der, runs under user uc. It ends with public_key.der at mode 0600.

Any process that reads that file as another user, for example a sidecar verifying the server's tokens, then fails to read it. This matters only if such a reader exists.

Evidence

Lines 189-197 create the new public_key.der with Files.createTempFile and no attributes, then move it into place, so it keeps the temp file's owner-only mode (measured [OWNER_READ, OWNER_WRITE] on JDK 17). The base wrote public_key.der with Files.write(publicKeyFile, keyPair.getPublic().getEncoded(), StandardOpenOption.CREATE) (base line 154), which uses the umask. The stored file's permissions change without being disclosed.

How it was checked

Reproduced: (umask 022; dev/run-tests.py "server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest")

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.newPublicKeyFollowsUmask failed: org.opentest4j.AssertionFailedError: expected: [OWNER_READ, OWNER_WRITE, OTHERS_READ, GROUP_READ] but was: [OWNER_READ, OWNER_WRITE] (at SecurityConfigurationTest.java:322)
1 suites, 23 tests, 1 failed

with the fix:

On base SecurityConfiguration (git show 23795fc7 version), same command under umask 022: newPublicKeyFollowsUmask did not appear among failures (7 other tests failed there because they exercise this PR's new behavior). Under the default shell umask 077 on head the test also passes, since both files are 0600; so it only discriminates under umask 022.

Checked by 1 independent check: CONTESTED

References:

Is public_key.der read only by the server's own user, or should the temp file be created with the old permissions (for example rw-r--r-- via PosixFilePermissions.asFileAttribute)?


private static final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);

// Keep the key-pair probe aligned with Algorithm.RSA512 used for token signing.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): Comment ties the key-pair probe to the token algorithm, though the check does not depend on it

Line 48 says the probe must stay aligned with Algorithm.RSA512, but nothing links the two. Any RSA signature algorithm proves the private and public keys match.

The comment creates a second place to update whenever token signing changes, for no functional reason.

Cost of keeping it: If token signing moves to Algorithm.RSA256, the comment asks for an edit to KEY_PAIR_CHECK_SIGNATURE_ALGORITHM that changes nothing. If nobody makes that edit, the comment becomes false.

Suggested change
// Keep the key-pair probe aligned with Algorithm.RSA512 used for token signing.
// Any RSA signature proves the pair matches; this is independent of the token algorithm.
private static final String KEY_PAIR_CHECK_SIGNATURE_ALGORITHM = "SHA512withRSA";
Evidence

Line 48 claims an alignment with Algorithm.RSA512, but line 255 uses Algorithm.RSA512 on its own and nothing ties the two together. verifyKeyPair (lines 218-241) uses the constant only to show that the pair matches, which works with any RSA algorithm.

How it was checked

Checked by 1 independent check: NITPICK

Would it read better to describe the constant as independent of the token algorithm?

Comment thread docs/server/auth.md Outdated

When the server uses the deprecated `etc/conf` key folder, it derives the public key from
`private_key.der` when that key contains the required RSA CRT fields. It updates
`public_key.der` on a best-effort basis for compatibility with earlier versions. Older RSA private

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: Rollback after a public-key write warning can replace the signing key

The current release can keep signing after a failed compatibility write. If public_key.der is still missing at rollback, the earlier server replaces the signing key, invalidating previously issued tokens. This is one bug class: The rollback and folder docs still describe public_key.der as always present, though the server now writes it only best-effort. The same issue appears in docs/server/auth.md:301 (The rollback bullet says only to create key_id.txt. If the best-effort write warned and left public_key.der missing (read-only folder, or a directory in its pla); docs/server/configuration.md:88 (The page still says the server keeps private_key.der, public_key.der and generates them on first start. The head generates only the private key and writes t).

For example: A folder has private_key.der and key_id.txt but no public_key.der. The new server starts after a failed compatibility write; restarting the earlier version on that folder generates another pair.

Suggested change
`public_key.der` on a best-effort basis for compatibility with earlier versions. Older RSA private
If startup warned that it could not write `public_key.der`, verify that the file exists and matches `private_key.der` before rollback. Restore the matching public key before starting the earlier server.
Evidence

The compatibility writer catches IOException and lets startup continue even if public_key.der was missing when the write began. I checked the upgrade section, the configuration reference's rollback link, the sample server properties, and the class Javadoc. The rollback instructions cover key_id.txt and configured-file deployments, but omit checking the folder's public key after this warning. The earlier implementation linked below regenerates the pair when the public file is missing.

The docs promise that public_key.der is kept up to date for earlier versions. The code only logs a warning when the write fails, and the base version regenerates both keys when public_key.der is missing. I searched docs/server/auth.md (Upgrading and its rollback bullet), docs/server/configuration.md:86-91 and the class Javadoc, and none of them tells the operator to fix the file before rolling back.

How it was checked

Checked by 2 independent checks: CONTESTED

References:

Could the rollback instructions tell operators how to check the companion file after this warning?

Comment thread docs/server/auth.md Outdated
When the server uses the deprecated `etc/conf` key folder, it derives the public key from
`private_key.der` when that key contains the required RSA CRT fields. It updates
`public_key.der` on a best-effort basis for compatibility with earlier versions. Older RSA private
keys without CRT fields still require a matching `public_key.der`; the server verifies the pair

@shba24 shba24 Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: The recommended upgrade fails for a working non-CRT key pair

The folder loader can verify a non-CRT private key with its companion public key. Setting the property selects a loader that only takes the private file, so the same deployment fails to start after following the migration step. This is one bug class: The upgrade advice to set server.token-signing-private-key-file to the existing folder key ignores that the settings path rejects non-CRT keys the folder path accepts. The same issue appears in docs/server/auth.md:285 ('point it at the key the server already has, etc/conf/private_key.der' fails startup for the non-CRT pair the new paragraph at line 291 says is supported, becau); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:116 (The startup warning tells every folder user to 'set it to your own private key file' with no caveat. For a working non-CRT folder pair, following it breaks star); docs/server/configuration.md:76 (The property description says the key file may be any unencrypted PKCS #8 key, without saying it must carry CRT fields. A non-CRT PKCS #8 DER key matches the de).

For example: An operator with a working non-CRT pair follows the instruction to point server.token-signing-private-key-file at etc/conf/private_key.der. On restart, publicKeyOf reports that the key has no public exponent.

Suggested change
keys without CRT fields still require a matching `public_key.der`; the server verifies the pair
If your existing private key lacks CRT fields, leave `server.token-signing-private-key-file` unset and keep the matching `public_key.der` until you can supply a private key with CRT fields.
Evidence

The upgrade instructions tell operators to select their existing private key, then describe support for non-CRT pairs in the folder. Only the folder constructor reads the companion file. Setting the property takes the direct-file path, where publicKeyOf throws for that same private key.

How it was checked

Reproduced: build/sbt "server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest"

head:

[error] Test SecurityConfigurationTest.documentedUpgradeStepStartsWithNonCrtFolderKey failed: java.lang.IllegalStateException: The key in /tmp/junit-.../private_key.der has no public exponent; create it with `openssl genrsa`
[error]   at SecurityConfiguration.publicKeyOf(SecurityConfiguration.java:157)
[error]   at SecurityConfiguration.fromPrivateKeyFile(SecurityConfiguration.java:138)
[error]   at SecurityConfiguration.load(SecurityConfiguration.java:110)
[info] Test run finished: 1 failed, 0 ignored, 23 total
[error] Failed: Total 23, Failed 1, Errors 0, Passed 22

Checked by 2 independent checks: CONTESTED

Could we qualify the migration step where it tells operators to reuse their existing key?

@yajneshx94

Copy link
Copy Markdown
Author

Thanks for the thorough review. Before changing the writer again, could you confirm the preferred policy? Would you accept creating public_key.der only when it’s missing and leaving existing files untouched? My concern is that this would not repair a stale or malformed file, which may affect rollback compatibility. I also understand that concurrent first-start initialization is a separate race in private-key creation; should I address that in this PR, or keep the scope focused? I’ll also address the short-key diagnostic and clarify the upgrade/rollback docs.

@shba24 shba24 left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, approved by mistake.

@shba24 shba24 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, approved by mistake.

@timothyw553 timothyw553 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

overall fix looks good, nothing blocking here. i +1'd the open thread on handling InvalidKeyException for a short key mismatch.

byte[] signedProbe = signer.sign();

Signature verifier = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
verifier.initVerify(publicKey);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1, should we move initVerify inside the try and catch InvalidKeyException too, with a test for a short key mismatch?

@yajneshx94

Copy link
Copy Markdown
Author

Thanks @timothyw553, I've addressed this in 2f5318b. Signature
initialization is now inside the mismatch handler, which wraps
InvalidKeyException with the two-file diagnostic, and I added a test using
a 512-bit public key against a 2048-bit private key.

@shba24

shba24 commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

On the point that a folder with only private_key.der got its key replaced: thanks for tracing it to the missing public_key.der and fixing it in c686212 and 1c8545a. You're right, and I checked the head.

  • SecurityConfiguration(Path) generates a new pair only when private_key.der is missing. A missing public_key.der no longer replaces an existing private key.
  • public_key.der is written in one method. An IOException there only logs a warning. For private keys without CRT fields, the server reads public_key.der and checks the pair. A mismatch, including different key sizes, gives the two-file "do not match" error.
  • The Javadoc, docs/server/auth.md and the tests cover these cases.

I haven't compared the PR description with the final behavior. Worth a quick read to make sure it says the same as the code now does.

This thread looks resolved to me. The other open threads, such as the file permissions and symlink ones, are separate.

@yajneshx94

Copy link
Copy Markdown
Author

Thanks @shba24. I'll go with create-if-missing: public_key.der is written
only when it is absent, and an existing file is never replaced. I'll
update the upgrade and rollback docs to tell operators to check that
public_key.der matches private_key.der before rolling back. The
concurrent first-start race in private key creation predates this PR, so
I'll note it in the description as a follow-up and keep this PR focused.

@shba24 shba24 left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On lines this pull request does not change

server/src/main/java/io/unitycatalog/server/UnityCatalogServer.java:757

Nit (not a blocker): The builder promises recovery for a missing key that can prevent startup

configurationFolder describes both signing files together. With an existing non-CRT private key, the caller must supply the matching public file. This is one bug class: Docs and Javadoc still promise that the folder path creates whatever key file is missing, but it now creates only the private key and requires a public companion for non-CRT keys. The same issue appears in server/src/main/java/io/unitycatalog/server/UnityCatalogServer.java:756 ('the signing keys, which the server creates if missing' is wrong for a non-CRT private_key.der with no public_key.der: construction throws and nothing is create); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:77 (The constructor Javadoc 'Uses the key in the configuration folder, generating it if missing' does not mention the non-CRT companion requirement, the pair check,); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:106 (The load() Javadoc 'or else the key in the configuration folder, generating it if it is missing' has the same gap.); docs/server/configuration.md:88 (The text '(private_key.der, public_key.der), generating it on first start' still describes the pair as generated and read together. public_key.der is now derive).

For example: The builder says the server creates missing signing keys. If only public_key.der is missing from a non-CRT pair, the constructor raises a matching public key is required.

* {@code server.token-signing-private-key-file} is set, the signing keys. The server generates a private key if it is missing. An existing non-CRT private key requires its matching public key.
Evidence

The public builder describes both signing keys as created if missing. With an existing non-CRT private key, the newly changed constructor explicitly throws if only the public file is missing. With a CRT key it attempts publication but can continue without creating the file.

server/src/main/java/io/unitycatalog/server/UnityCatalogServer.java:754-758

    /**
     * Sets the folder for the {@code token.txt} the server writes when constructed and, unless
     * {@code server.token-signing-private-key-file} is set, the signing keys, which the server
     * creates if missing. Defaults to {@code etc/conf}; tests pass their own folder so concurrent
     * servers do not share these files.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:80-97

    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    initializeIfMissing(privateKeyFile);
    privateKey = readPrivateKey(privateKeyFile);
    if (canDerivePublicKey(privateKey)) {
      publicKey = publicKeyOf(privateKey, privateKeyFile);
      writePublicKeyIfNeeded(publicKeyFile, publicKey);
    } else {
      if (Files.notExists(publicKeyFile)) {
        throw new IllegalStateException(
            "The private key in "
                + privateKeyFile.toAbsolutePath()
                + " has no public exponent; a matching public key is required at "
                + publicKeyFile.toAbsolutePath());
      }
      publicKey = readPublicKey(publicKeyFile);
      verifyKeyPair(privateKey, publicKey, privateKeyFile, publicKeyFile);
    }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:201-206

    } catch (IOException e) {
      log.warn(
          "Could not write compatibility public key file {}. The server will continue using the"
              + " public key derived from the private key.",
          file,
          e);
How it was checked

Reproduced: dev/run-tests.py -p 1 --jvm-heap 2g 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest'

with the fix:

1 suites, 23 tests, 0 failed, wall time 2m15s (includes the existing parameterized rejectsNonCrtKeyWithoutUsablePublicKey[missing], which asserts the constructor throws 'has no public exponent' and creates no public_key.der)

Checked by 1 independent check: CONFIRMED

Could the builder Javadoc distinguish private-key generation from public-key recovery?

throw new IllegalStateException(mismatchMessage);
}
} catch (InvalidKeyException | SignatureException e) {
throw new IllegalStateException(mismatchMessage, e);

@shba24 shba24 Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: A matching key pair is reported as mismatched

signer.initSign can reject the private key before the probe uses the public key. Wrapping that failure as a mismatch points the operator at the wrong repair: restoring the matching public file produces the same error. This is one bug class: The key-pair check reports every signer or verifier failure as 'do not match', so an unusable private key is diagnosed as a mismatch. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:230 (initSign throws InvalidKeyException ('Key is too short for this signature algorithm') for a matching non-CRT pair of 736 bits or fewer. The catch at line 240 re); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:232 (The same catch covers SignatureException from signer.sign(), which comes from the private key alone, for example a private exponent the provider rejects. It is ); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:85 (A sibling path with no diagnosis at all: a short CRT key in the folder, or any short key on the settings path (line 139), passes startup validation. It fails on); server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:278 (The only short-key test pairs a 2048-bit private key with a 512-bit public key, a real mismatch, so it asserts 'do not match' and confirms the conflation instea).

For example: Loading a 512-bit non-CRT private key with its own public key produced do not match. The cause was Key is too short for this signature algorithm.

Move signer.initSign/sign out of the mismatch catch. Report an InvalidKeyException there as 'the private key in cannot sign with SHA512withRSA (RS512)', with the cause. Keep 'do not match' for initVerify failures and for verify() returning false.

Evidence

The exception handler maps signer initialization failure to the same message as a failed verification. I supplied a 512-bit non-CRT private key and the public key from the same generated pair to the compiled constructor. It reported 'do not match' with cause 'Key is too short for this signature algorithm'. The added test uses an unrelated short public key, so it exercises a different path.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:95-96

      publicKey = readPublicKey(publicKeyFile);
      verifyKeyPair(privateKey, publicKey, privateKeyFile, publicKeyFile);

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:221-242

    String mismatchMessage =
        "The RSA keys in "
            + privateKeyFile.toAbsolutePath()
            + " and "
            + publicKeyFile.toAbsolutePath()
            + " do not match";
    try {
      byte[] probe = "unitycatalog-key-pair-check".getBytes(StandardCharsets.US_ASCII);
      Signature signer = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
      signer.initSign(privateKey);
      signer.update(probe);
      byte[] signedProbe = signer.sign();

      Signature verifier = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
      verifier.initVerify(publicKey);
      verifier.update(probe);
      if (!verifier.verify(signedProbe)) {
        throw new IllegalStateException(mismatchMessage);
      }
    } catch (InvalidKeyException | SignatureException e) {
      throw new IllegalStateException(mismatchMessage, e);
    }

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:278-292

  void rejectsNonCrtKeyWithShortMismatchedPublicKey() throws Exception {
    KeyPair signingKeyPair = newKeyPair();
    KeyPair shortKeyPair = newKeyPair(512);
    PrivateKey nonCrtKey = nonCrtPrivateKey(signingKeyPair);
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    Files.write(privateKeyFile, nonCrtKey.getEncoded());
    Files.write(publicKeyFile, shortKeyPair.getPublic().getEncoded());

    assertThatThrownBy(() -> new SecurityConfiguration(configurationFolder))
        .isInstanceOf(IllegalStateException.class)
        .hasMessageContaining(privateKeyFile.toAbsolutePath().toString())
        .hasMessageContaining(publicKeyFile.toAbsolutePath().toString())
        .hasMessageContaining("do not match")
        .hasCauseInstanceOf(InvalidKeyException.class);
How it was checked

Reproduced: dev/run-tests.py -p 1 --jvm-heap 2g 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest'

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.reportsShortMatchingNonCrtKeyPairAsUnusableNotMismatched failed: org.opentest4j.AssertionFailedError: Expecting actual: "The RSA keys in .../private_key.der and .../public_key.der do not match" ... (SecurityConfigurationTest.java:304)
[error] Failed: Total 24, Failed 1, Errors 0, Passed 23

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:295-305

  @Test
  void reportsShortMatchingNonCrtKeyPairAsUnusableNotMismatched() throws Exception {
    KeyPair shortKeyPair = newKeyPair(512);
    PrivateKey nonCrtKey = nonCrtPrivateKey(shortKeyPair);
    Files.write(configurationFolder.resolve("private_key.der"), nonCrtKey.getEncoded());
    Files.write(
        configurationFolder.resolve("public_key.der"), shortKeyPair.getPublic().getEncoded());

    assertThatThrownBy(() -> new SecurityConfiguration(configurationFolder))
        .hasMessageNotContaining("do not match");
  }

Checked by 2 independent checks, which split: CONFIRMED, CONTESTED

References:

Could signer initialization report that the private key cannot sign with SHA512withRSA, while keeping the two-path diagnostic for a failed pair check?

if (!verifier.verify(signedProbe)) {
throw new IllegalStateException(mismatchMessage);
}
} catch (InvalidKeyException | SignatureException e) {

@shba24 shba24 Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): A short but matching key pair fails startup with "do not match"

verifyKeyPair wraps every InvalidKeyException in the "do not match" message, including the one signer.initSign throws when the private key is too short for SHA512withRSA.

An operator with a matching pair is then told the files differ, when the real problem is the key size.

For example: A folder holds a 512-bit non-CRT private_key.der and its own matching public_key.der. At startup, initSign throws Key is too short for this signature algorithm, and the server reports that the keys in the two files do not match.

Signature signer = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
try {
  signer.initSign(privateKey);
} catch (InvalidKeyException e) {
  throw new IllegalStateException(
      "The private key in " + privateKeyFile.toAbsolutePath()
          + " is too short for RS512 token signing", e);
}
try {
  ... // update, sign, initVerify, verify as today
} catch (InvalidKeyException | SignatureException e) {
  throw new IllegalStateException(mismatchMessage, e);
}
Evidence

initSign runs inside the try whose InvalidKeyException handler throws mismatchMessage. SHA512withRSA rejects private keys of 736 bits or fewer in initSign, so a matching short pair gets the mismatch message.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:49-50

  // Keep the key-pair probe aligned with Algorithm.RSA512 used for token signing.
  private static final String KEY_PAIR_CHECK_SIGNATURE_ALGORITHM = "SHA512withRSA";

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:219-243

  private static void verifyKeyPair(
      RSAPrivateKey privateKey, RSAPublicKey publicKey, Path privateKeyFile, Path publicKeyFile) {
    String mismatchMessage =
        "The RSA keys in "
            + privateKeyFile.toAbsolutePath()
            + " and "
            + publicKeyFile.toAbsolutePath()
            + " do not match";
    try {
      byte[] probe = "unitycatalog-key-pair-check".getBytes(StandardCharsets.US_ASCII);
      Signature signer = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
      signer.initSign(privateKey);
      signer.update(probe);
      byte[] signedProbe = signer.sign();

      Signature verifier = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
      verifier.initVerify(publicKey);
      verifier.update(probe);
      if (!verifier.verify(signedProbe)) {
        throw new IllegalStateException(mismatchMessage);
      }
    } catch (InvalidKeyException | SignatureException e) {
      throw new IllegalStateException(mismatchMessage, e);
    }
  }
How it was checked

Reproduced: dev/run-tests.py -p 1 --jvm-heap 2g 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest'

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.distinguishesUnusableSignerFromPairMismatch failed: org.opentest4j.AssertionFailedError: Expecting actual: "The RSA keys in .../private_key.der and .../public_key.der do not match" (SecurityConfigurationTest.java:304). [error] Failed: Total 24, Failed 1, Errors 0, Passed 23

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:295-306

  @Test
  void distinguishesUnusableSignerFromPairMismatch() throws Exception {
    KeyPair shortKeyPair = newKeyPair(512);
    PrivateKey nonCrtKey = nonCrtPrivateKey(shortKeyPair);
    Files.write(configurationFolder.resolve("private_key.der"), nonCrtKey.getEncoded());
    Files.write(
        configurationFolder.resolve("public_key.der"), shortKeyPair.getPublic().getEncoded());

    assertThatThrownBy(() -> new SecurityConfiguration(configurationFolder))
        .hasMessageNotContaining("do not match");
  }

Checked by 1 independent check: CONFIRMED

Would a separate message for the private-key length make this case easier to diagnose?

@SneakyThrows
private static RSAPublicKey publicKeyOf(RSAPrivateKey privateKey, Path file) {
if (!(privateKey instanceof RSAPrivateCrtKey crtKey)) {
if (!canDerivePublicKey(privateKey)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): A non-CRT key in the private key file setting could fail with ClassCastException without a test catching it

publicKeyOf now checks canDerivePublicKey and then casts to RSAPrivateCrtKey.

The actionable error (has no public exponent; create it with openssl genrsa) is only reached through server.token-signing-private-key-file, and no test feeds a non-CRT key through that path. This is one bug class: The settings path's non-CRT rejection has no test, because every non-CRT test goes through the folder constructor, which branches before publicKeyOf. The same issue appears in server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:74 (The rejectsAnUnusablePrivateKey CsvSource has no non-CRT row, so nothing covers the guard at SecurityConfiguration.java:155 on the path that relies on it.); server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:237 (The non-CRT folder tests never load the same key through load(settings(...)), so the split between the two paths (the the "Following the upgrade instructions can prevent a working non-CRT deployment from starting" comment (docs/server/auth.md:292) class) has no test ei).

For example: Changing the guard at SecurityConfiguration.java:155 to if (false) keeps all 23 tests green. An operator who points the setting at a non-CRT key would then get a bare ClassCastException naming an internal JDK class instead of the message with the file and the openssl genrsa hint.

// in rejectsAnUnusablePrivateKey
"non-CRT key, has no public exponent"
...
case "non-CRT key" -> Files.write(privateKey, nonCrtPrivateKey(newKeyPair()).getEncoded());
Evidence

The rewritten guard at 155 protects the cast at 162. It is reachable only through fromPrivateKeyFile (line 139), because the constructor checks canDerivePublicKey first. I searched the test file for openssl genrsa and no public exponent: the only match is the folder-path message at line 314. A local mutation to if (false) passed 23/23.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:153-166

  @SneakyThrows
  private static RSAPublicKey publicKeyOf(RSAPrivateKey privateKey, Path file) {
    if (!canDerivePublicKey(privateKey)) {
      throw new IllegalStateException(
          "The key in "
              + file.toAbsolutePath()
              + " has no public exponent; create it with"
              + " `openssl genrsa`");
    }
    RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey) privateKey;
    return (RSAPublicKey)
        KeyFactory.getInstance("RSA")
            .generatePublic(new RSAPublicKeySpec(crtKey.getModulus(), crtKey.getPublicExponent()));
  }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:135-140

  /** Uses the given private key file and the public key derived from it. Nothing is written. */
  private static SecurityConfiguration fromPrivateKeyFile(Path privateKeyFile) {
    requireFile(privateKeyFile);
    RSAPrivateKey privateKey = readPrivateKey(privateKeyFile);
    return new SecurityConfiguration(privateKey, publicKeyOf(privateKey, privateKeyFile));
  }

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:73-81

  @ParameterizedTest
  @CsvSource({
    "encrypted PKCS #8, is encrypted",
    "encrypted PKCS #1, is encrypted",
    "certificate only, No PRIVATE KEY PEM block",
    "garbage bytes, Cannot read the RSA private key",
    "EC key, expected an unencrypted RSA private key"
  })
  void rejectsAnUnusablePrivateKey(String problem, String message) throws Exception {
How it was checked

Checked by 1 independent check: CONFIRMED

How about adding this as another row of rejectsAnUnusablePrivateKey, since it already checks the file name and the empty folder?

@shba24

shba24 commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

Thanks for taking the earlier points on board, in particular create-if-absent for public_key.der and the rollback docs check.

On the first-start race for private_key.der: you're right. Two servers starting together on an empty folder could already create competing private keys before this PR, so noting it in the description as a follow-up is fine with me.

One small thing to keep separate. The new step that publishes public_key.der is added by this PR, so a concurrent start could leave a pair that doesn't match. With your plan to write public_key.der only when it is absent, a loser can't replace a winner's file. That should cover the part this PR introduces. If you'd like, a small concurrent-start test would confirm it.

The promises above (absent-only write, docs check before rollback) sound good. Happy to take another look once they are in.

@yajneshx94

Copy link
Copy Markdown
Author

Thanks @shba24. I've pushed 083c7bb: public_key.der is created only when
missing and never replaced, a private key too short to sign has its own
error, the Javadoc and docs are updated (including the rollback check),
and there are tests for the non-CRT cases and a concurrent first start.

I also made the generated private key install without replacing one
created by another starter. Since you said the private key race could be
a follow-up, would you prefer I move that part to a separate pull
request? I'm happy to either way.

@shba24

shba24 commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

On the Javadoc, docs and non-CRT key point, and the private key race: thank you for fixing both in 083c7bb and adding the tests for the non-CRT cases and the concurrent first start. You're right on both.

  • public_key.der is created only when it is missing and is never replaced.
  • A too-short private key now gets its own error.
  • The Javadoc and docs match the code.
  • The generated private key is installed with a no-replace move, and every starter reads the winning key back from disk. The public key is derived from that key, so the pair stays consistent.

On your question: I'd keep the private key race fix in this PR. It is already small and tested, and it is what makes the public key publish step safe, so splitting it out now would add churn. I only suggested a follow-up when it looked bigger. Please keep it in the PR description so reviewers know it is in scope.

One small thing worth a look: one of the new tests seems to depend on the umask of the machine running it. It would be safer to make it independent of the umask, for example by setting the permissions explicitly in the test. Otherwise I think this thread can be resolved.

assertThat(Files.readAllBytes(publicKeyFile)).isEqualTo(keyPair.getPublic().getEncoded());
if (configurationFolder.getFileSystem().supportedFileAttributeViews().contains("posix")) {
assertThat(PosixFilePermissions.toString(Files.getPosixFilePermissions(publicKeyFile)))
.isEqualTo("rw-r--r--");

@shba24 shba24 Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: The public-key permission assertion fails under umask 077

createPublicKeyTempFile supplies permissions at file creation, so the process mask still applies. Checking for posix support does not establish the mask.

For example: With umask 077, the requested 0644 produced 0600 on JDK 17. The content assertions pass for a matching key, but the mode assertion rejects the result.

Suggested change
.isEqualTo("rw-r--r--");
Path reference = Files.createFile(
configurationFolder.resolve("public-mode-reference"),
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-r--r--")));
assertThat(Files.getPosixFilePermissions(publicKeyFile))
.isEqualTo(Files.getPosixFilePermissions(reference));
Evidence

The production helper requests 0644 at creation and moves that file into place. The test checks for POSIX support but never accounts for the process creation mask. Using the same Files.createTempFile attributes on JDK 17 with the checkout's umask 077 produced rw-------, which fails the new equality assertion.

L4 asks, "Would this test fail if the bug returned?" The test assumes the requested mode survives the process umask, but the temp-file creation respects that umask.

The code requests rw-r--r-- via a create-time attribute, which the umask masks; the test compares the on-disk mode to that exact literal, so on this host (umask 077) the unmodified head fails with rw-------.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:194-197

      temporaryFile = createPublicKeyTempFile(file);
      Files.write(temporaryFile, publicKey.getEncoded());
      Files.move(temporaryFile, file);
      temporaryFile = null;

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:220-226

    if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
      return Files.createTempFile(
          parentDirectory,
          prefix,
          ".tmp",
          PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-r--r--")));
    }

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:170-177

    SecurityConfiguration configuration = new SecurityConfiguration(configurationFolder);

    assertThat(Files.readAllBytes(privateKeyFile)).isEqualTo(privateKey);
    assertThat(Files.readAllBytes(publicKeyFile)).isEqualTo(keyPair.getPublic().getEncoded());
    if (configurationFolder.getFileSystem().supportedFileAttributeViews().contains("posix")) {
      assertThat(PosixFilePermissions.toString(Files.getPosixFilePermissions(publicKeyFile)))
          .isEqualTo("rw-r--r--");
    }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:217-225

  private static Path createPublicKeyTempFile(Path file) throws IOException {
    Path parentDirectory = file.toAbsolutePath().getParent();
    String prefix = file.getFileName().toString();
    if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
      return Files.createTempFile(
          parentDirectory,
          prefix,
          ".tmp",
          PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-r--r--")));

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:217-228

  private static Path createPublicKeyTempFile(Path file) throws IOException {
    Path parentDirectory = file.toAbsolutePath().getParent();
    String prefix = file.getFileName().toString();
    if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
      return Files.createTempFile(
          parentDirectory,
          prefix,
          ".tmp",
          PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-r--r--")));
    }
    return Files.createTempFile(parentDirectory, prefix, ".tmp");
  }
How it was checked

Reproduced: (umask 077; build/sbt "server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest")

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.preservesPrivateKeyAndRecreatesMissingPublicKey failed: org.opentest4j.AssertionFailedError: 
[error] expected: "rw-r--r--"
[error]  but was: "rw-------", took 1.085s
[error]     at io.unitycatalog.server.security.SecurityConfigurationTest.preservesPrivateKeyAndRecreatesMissingPublicKey(SecurityConfigurationTest.java:176)
[error] Failed: Total 26, Failed 1, Errors 0, Passed 25

with the fix:

Same command with umask 022: [info] Test ...SecurityConfigurationTest#preservesPrivateKeyAndRecreatesMissingPublicKey() started ... [info] Passed: Total 26, Failed 0, Errors 0, Passed 26

Checked by 2 independent checks: CONFIRMED

References:

Could the assertion compare against a reference file created under the same mask?

private static void writePublicKeyIfMissing(Path file, RSAPublicKey publicKey) {
Path temporaryFile = null;
try {
if (Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {

@shba24 shba24 Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

UPDATE: The PR description promises a rewritten public_key.der that the code no longer writes

The description says public_key.der is rewritten on a best-effort basis so earlier releases can still read it. Since the last commit, writePublicKeyIfMissing returns as soon as any public_key.der exists. A stale or malformed file is left in place.

For example: derivesPublicKeyWithoutReplacingExistingCompatibilityFile writes a mismatched public_key.der and asserts it is unchanged after startup. A reviewer going by the description would expect it to be repaired, so they would expect rollback to be safe without the manual check that auth.md now asks for.

Reword the compatibility bullet and the summary: the file is created only when missing, an existing file is never rewritten, and operators must check the pair before rolling back.

Evidence

writePublicKeyIfMissing returns early whenever any public_key.der exists (line 191-193), so nothing is rewritten. The test at 134-147 asserts that a mismatched file is left byte-for-byte unchanged. Both contradict the restated claim that the file is rewritten.

L5 asks, "Does every sentence of my description/title map to a hunk?" The supplied PR description says the compatibility file is rewritten, while the implementation and test deliberately preserve an existing file.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:188-197

  private static void writePublicKeyIfMissing(Path file, RSAPublicKey publicKey) {
    Path temporaryFile = null;
    try {
      if (Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
        return;
      }
      temporaryFile = createPublicKeyTempFile(file);
      Files.write(temporaryFile, publicKey.getEncoded());
      Files.move(temporaryFile, file);
      temporaryFile = null;

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:133-147

  @Test
  void derivesPublicKeyWithoutReplacingExistingCompatibilityFile() throws Exception {
    KeyPair signingKeyPair = newKeyPair();
    KeyPair mismatchedKeyPair = newKeyPair();
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    Files.write(
        configurationFolder.resolve("private_key.der"), signingKeyPair.getPrivate().getEncoded());
    byte[] existingPublicKey = mismatchedKeyPair.getPublic().getEncoded();
    Files.write(publicKeyFile, existingPublicKey);

    SecurityConfiguration configuration = new SecurityConfiguration(configurationFolder);

    assertThat(configuration.rsaPublicKey()).isEqualTo(signingKeyPair.getPublic());
    assertThat(Files.readAllBytes(publicKeyFile)).isEqualTo(existingPublicKey);
  }

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:133-146

  @Test
  void derivesPublicKeyWithoutReplacingExistingCompatibilityFile() throws Exception {
    KeyPair signingKeyPair = newKeyPair();
    KeyPair mismatchedKeyPair = newKeyPair();
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    Files.write(
        configurationFolder.resolve("private_key.der"), signingKeyPair.getPrivate().getEncoded());
    byte[] existingPublicKey = mismatchedKeyPair.getPublic().getEncoded();
    Files.write(publicKeyFile, existingPublicKey);

    SecurityConfiguration configuration = new SecurityConfiguration(configurationFolder);

    assertThat(configuration.rsaPublicKey()).isEqualTo(signingKeyPair.getPublic());
    assertThat(Files.readAllBytes(publicKeyFile)).isEqualTo(existingPublicKey);
How it was checked

Reproduced: build/sbt "server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest"

with the fix:

Existing tests derivesPublicKeyWithoutReplacingExistingCompatibilityFile and leavesMalformedPublicKeyWhenPrivateKeyHasCrtFields ran and passed, so the head leaves an existing stale or malformed public_key.der untouched. The run finished with 26 total, 1 failed, 25 passed. The one failure, preservesPrivateKeyAndRecreatesMissingPublicKey (expected rw-r--r-- but was rw-------), is a file-permission assertion and does not touch the rewrite behaviour.

Checked by 1 independent check: CONFIRMED

Could you update the description so it matches the create-if-missing behavior?

}

// Installs the generated private key without replacing a key another starter already installed.
private static void writeOwnerOnly(Path file, byte[] content) throws IOException {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): Two first starts can still replace each other's private key, and the install step is written twice

writeOwnerOnly and writePublicKeyIfMissing both write a temp file and publish it with Files.move without REPLACE_EXISTING, so a key another starter installed is not replaced.

On JDK 17 for Unix, Files.move stats the target, throws FileAlreadyExistsException if it exists, and then calls rename(2), which replaces the target. The check and the rename are separate steps, so the no-replace guarantee is not atomic.

Cost of keeping it: Two copies of the same routine already differ: the public-key one logs a failed temp-file delete, and the private-key one lets it throw. Fixing the check-then-rename window, or changing cleanup or permissions, means editing both and keeping them in step.

If two first starts both pass the stat inside Files.move, the second rename replaces the first private key. Each process then signs with a different key.

Pull both into one helper, for example installIfAbsent(Path file, byte[] content, String posixPermissions). It writes the temp file in the same folder and publishes it with Files.createLink(file, temporaryFile), which fails when the name exists instead of replacing it. It always deletes the temp file and returns whether it installed. initializeIfMissing passes rw------- and propagates IOException; writePublicKeyIfMissing passes rw-r--r-- and logs. Keep the current move as a fallback where hard links are not supported.

Evidence

Both methods create a temp file in the parent folder with a POSIX-permission branch, write it, call Files.move without REPLACE_EXISTING and swallow FileAlreadyExistsException; only the permission string and error policy differ. The L268 comment claims no-replace. JDK 17 UnixCopyFile.move (src.zip, sun/nio/fs/UnixCopyFile.java ~L431-472) gets the target's attributes, throws if !flags.replaceExisting, then calls rename(source, target) as a separate step, so the guarantee is check-then-act. I looked for another install helper in the server package and found none.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:188-228

  private static void writePublicKeyIfMissing(Path file, RSAPublicKey publicKey) {
    Path temporaryFile = null;
    try {
      if (Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
        return;
      }
      temporaryFile = createPublicKeyTempFile(file);
      Files.write(temporaryFile, publicKey.getEncoded());
      Files.move(temporaryFile, file);
      temporaryFile = null;
    } catch (FileAlreadyExistsException e) {
      // Another server instance published the compatibility key first.
    } catch (IOException e) {
      log.warn(
          "Could not write compatibility public key file {}. The server will continue using the"
              + " public key derived from the private key.",
          file,
          e);
    } finally {
      if (temporaryFile != null) {
        try {
          Files.deleteIfExists(temporaryFile);
        } catch (IOException e) {
          log.warn("Could not remove temporary compatibility public key file {}", temporaryFile, e);
        }
      }
    }
  }

  private static Path createPublicKeyTempFile(Path file) throws IOException {
    Path parentDirectory = file.toAbsolutePath().getParent();
    String prefix = file.getFileName().toString();
    if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
      return Files.createTempFile(
          parentDirectory,
          prefix,
          ".tmp",
          PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-r--r--")));
    }
    return Files.createTempFile(parentDirectory, prefix, ".tmp");
  }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:268-293

  // Installs the generated private key without replacing a key another starter already installed.
  private static void writeOwnerOnly(Path file, byte[] content) throws IOException {
    Path temporaryFile = null;
    try {
      Path parentDirectory = file.toAbsolutePath().getParent();
      if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
        temporaryFile =
            Files.createTempFile(
                parentDirectory,
                file.getFileName().toString(),
                ".tmp",
                PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
      } else {
        temporaryFile =
            Files.createTempFile(parentDirectory, file.getFileName().toString(), ".tmp");
      }
      Files.write(temporaryFile, content);
      Files.move(temporaryFile, file);
    } catch (FileAlreadyExistsException e) {
      // Another server instance installed the private key first.
    } finally {
      if (temporaryFile != null) {
        Files.deleteIfExists(temporaryFile);
      }
    }
  }
How it was checked

Checked by 2 independent checks: CONFIRMED

References:

Would a single createLink-based helper work for both files here?

@@ -753,9 +753,10 @@ public UnityCatalogServer.Builder fileOperationsDecorator(

/**
* Sets the folder for the {@code token.txt} the server writes when constructed and, unless

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): Key-folder behavior is described in six places that have to change together

The rule for the deprecated key folder is written out in the class, constructor and load Javadoc, the UnityCatalogServer builder Javadoc, configuration.md and auth.md. The rule: generate only private_key.der, derive the public key for CRT keys, create public_key.der only if missing, and require a matching public key for non-CRT keys.

The builder edit also removed the sentence that tests pass their own folder so concurrent servers do not share these files. This is one bug class: The deprecated key-folder rule is restated as prose in several Javadocs and doc pages with no single source, so edits to the rule leave some copies stale, incomplete or missing a sentence.. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:37 (The class Javadoc says 'an unencrypted PEM key (PKCS #8 or PKCS #1), or a PKCS #8 DER key with CRT fields', which reads as a CRT requirement for DER only. publi); docs/server/auth.md:291 (The upgrade notes in auth.md and configuration.md:78-93 describe the key requirements (CRT fields, create-if-missing) but not the new startup check that the pri).

Cost of keeping it: An earlier round of this PR found stale wording in four of these copies after the behavior changed. Each later change to when public_key.der is written or read means six edits, and any copy that is missed ends up contradicting the code.

Keep the full rule once in the SecurityConfiguration class Javadoc and once in configuration.md, and have auth.md link to it. Reduce the constructor, load and builder Javadoc to a pointer such as the signing keys (see {@link SecurityConfiguration}). Put back the sentence about tests using their own folder.

Evidence

The same four-part rule is in each quoted block. AGENTS.md on origin/main L201 says 'Do not duplicate a check ... that already has a home', and L207 says 'Do not delete existing docs while editing'; the builder edit removed 'tests pass their own folder so concurrent servers do not share these files'.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:37-42

 * <p>The private key is read from the file set in {@code server.token-signing-private-key-file}: an
 * unencrypted PEM key (PKCS #8 or PKCS #1), or a PKCS #8 DER key with CRT fields. The public key is
 * derived from it once, when the configuration is loaded. Leaving the setting unset is deprecated:
 * the server then uses {@code private_key.der} in the UC configuration folder, deriving the public
 * key from it when possible and creating {@code public_key.der} only if it is missing. For older
 * private keys without CRT fields, it reads and verifies the matching {@code public_key.der}.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:76-79

  /**
   * Uses the private key in the configuration folder, generating it if missing. A non-CRT private
   * key requires its matching {@code public_key.der}.
   */

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:108-112

  /**
   * Uses the private key file in the settings, or else the private key in the configuration folder,
   * generating the folder key if it is missing. A configured key file must exist and contain CRT
   * fields; a non-CRT folder key requires its matching {@code public_key.der}.
   */

server/src/main/java/io/unitycatalog/server/UnityCatalogServer.java:754-759

    /**
     * Sets the folder for the {@code token.txt} the server writes when constructed and, unless
     * {@code server.token-signing-private-key-file} is set, the signing keys. The server generates
     * {@code private_key.der} if it is missing; for a CRT private key it derives the public key and
     * writes {@code public_key.der} only if that file is missing. An existing non-CRT private key
     * requires its matching public key file. Defaults to {@code etc/conf}.

docs/server/configuration.md:86-94

    !!! warning "Deprecated: the generated signing key"
        When the key file is not set, the server signs with a key it keeps in `etc/conf`
        (`private_key.der`, `public_key.der`), generating the private key on first start. For CRT keys it derives
        the public key and creates `public_key.der` only if missing; an existing non-CRT private key requires its
        matching public key. With authorization enabled it logs a warning at each start. This still works, but is
        deprecated; set the key file setting instead. A newly generated private key is readable by its owner only.
        Before rolling back to an earlier version, verify that `public_key.der` contains the public key for
        `private_key.der`; see
        [Upgrading](auth.md#upgrading) in the authentication docs.
How it was checked

Checked by 1 independent check: CONFIRMED

Would pointing the method-level Javadoc at the class Javadoc keep this easier to maintain?


@SneakyThrows
private static byte[] signProbe(RSAPrivateKey privateKey, Path privateKeyFile) {
byte[] probe = "unitycatalog-key-pair-check".getBytes(StandardCharsets.US_ASCII);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): Changing one probe string would make every non-CRT key pair report 'do not match'

signProbe and verifyKeyPair each build the probe from their own "unitycatalog-key-pair-check" literal, and the pair check works only while the two match.

signProbe returns a signature that only the non-CRT branch uses. The CRT branch and fromPrivateKeyFile call it only to see whether it throws. Its message also repeats SHA512withRSA instead of using KEY_PAIR_CHECK_SIGNATURE_ALGORITHM.

Cost of keeping it: If someone edits the literal in one method and not the other, every non-CRT folder fails startup with 'do not match'. A method used once for its value and twice only to see whether it throws is easy to misread.

private static final byte[] KEY_PAIR_CHECK_PROBE =
    "unitycatalog-key-pair-check".getBytes(StandardCharsets.US_ASCII);

// signProbe: signer.update(KEY_PAIR_CHECK_PROBE); message uses KEY_PAIR_CHECK_SIGNATURE_ALGORITHM
// verifyKeyPair: verifier.update(KEY_PAIR_CHECK_PROBE);
Evidence

L242 and L253 each spell the probe literal; L263 repeats the algorithm that L49 holds; L86 and L143 ignore or only conditionally use the returned signature. The verification only passes while both literals are equal.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:239-245

    try {
      Signature verifier = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
      verifier.initVerify(publicKey);
      verifier.update("unitycatalog-key-pair-check".getBytes(StandardCharsets.US_ASCII));
      if (!verifier.verify(signedProbe)) {
        throw new IllegalStateException(mismatchMessage);
      }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:251-266

  @SneakyThrows
  private static byte[] signProbe(RSAPrivateKey privateKey, Path privateKeyFile) {
    byte[] probe = "unitycatalog-key-pair-check".getBytes(StandardCharsets.US_ASCII);
    Signature signer = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
    try {
      signer.initSign(privateKey);
      signer.update(probe);
      return signer.sign();
    } catch (InvalidKeyException | SignatureException e) {
      throw new IllegalStateException(
          "The private key in "
              + privateKeyFile.toAbsolutePath()
              + " cannot sign with SHA512withRSA (RS512)",
          e);
    }
  }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:140-145

  private static SecurityConfiguration fromPrivateKeyFile(Path privateKeyFile) {
    requireFile(privateKeyFile);
    RSAPrivateKey privateKey = readPrivateKey(privateKeyFile);
    signProbe(privateKey, privateKeyFile);
    return new SecurityConfiguration(privateKey, publicKeyOf(privateKey, privateKeyFile));
  }
How it was checked

Checked by 1 independent check: NITPICK

Could the probe live in one constant next to the algorithm name?

@@ -753,9 +753,10 @@ public UnityCatalogServer.Builder fileOperationsDecorator(

/**
* Sets the folder for the {@code token.txt} the server writes when constructed and, unless

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): configurationFolder Javadoc loses why tests set their own folder

The rewrite of the configurationFolder Javadoc dropped tests pass their own folder so concurrent servers do not share these files. That still describes how BaseServerTest uses the builder.

For example: BaseServerTest still calls .configurationFolder(configurationFolder) for each test, and the reason for doing so is now undocumented.

Suggested change
* Sets the folder for the {@code token.txt} the server writes when constructed and, unless
* requires its matching public key file. Defaults to {@code etc/conf}; tests pass their own
* folder so concurrent servers do not share these files.
Evidence

The new Javadoc at 754-759 no longer has the sentence about tests passing their own folder. BaseServerTest line 179 still does that, and the AGENTS.md rule at line 207 forbids deleting existing docs.

server/src/main/java/io/unitycatalog/server/UnityCatalogServer.java:754-759

    /**
     * Sets the folder for the {@code token.txt} the server writes when constructed and, unless
     * {@code server.token-signing-private-key-file} is set, the signing keys. The server generates
     * {@code private_key.der} if it is missing; for a CRT private key it derives the public key and
     * writes {@code public_key.der} only if that file is missing. An existing non-CRT private key
     * requires its matching public key file. Defaults to {@code etc/conf}.

server/src/test/java/io/unitycatalog/server/base/BaseServerTest.java:179

              .configurationFolder(configurationFolder);

AGENTS.md:207

- **Document the non-obvious, for a human, sparingly.** Public types and methods get doc comments describing intent, parameters, returns, and errors, and capture domain knowledge that cannot be inferred from the code (for example why a storage or identity flow works the way it does). But do not narrate trivial or self-evident lines, and do not write long prose-paragraph comments: prefer a tight sentence, or a short structured list a reader can scan, over a wall of text. Annotate non-obvious literal arguments inline (`/* force= */ true`). Do not delete existing docs while editing.
How it was checked

Checked by 1 independent check: CONFIRMED

Could we keep that sentence alongside the new text?

Comment thread docs/server/auth.md Outdated
ignores the key file setting, so before rolling back a server that uses it, write its key to `etc/conf` in the
formats an earlier version reads:
started on this version, create `etc/conf/key_id.txt` with any value, for example `uc`. Before rolling back, check
that `etc/conf/public_key.der` exists and contains the public key for `etc/conf/private_key.der`; this release only

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: A matching PEM public key still prevents rollback to v0.7.0

The upgrade guide asks folder users to check that public_key.der exists and matches. This release preserves an existing PEM file, while v0.7.0 passes its raw bytes directly to the DER key decoder. This is one bug class: The rollback contract with v0.7.0 (public_key.der holds the matching X.509 SubjectPublicKeyInfo DER key, and private_key.der holds PKCS #8 DER) is neither documented in full for folder deployments nor checked by this release, which accepts files that the earlier release cannot read or that do not match.. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:191 (On the CRT path an existing stale, mismatched or malformed public_key.der is left as it is with no warning, so this release starts cleanly while leaving a file ); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:98 (On the non-CRT folder path, readPublicKey goes through readKeyFile, which accepts PEM, so a PEM public_key.der passes the pair check here while v0.7.0 cannot pa); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:85 (The folder private_key.der is also read through readKeyFile, which accepts PEM and PKCS #1, while v0.7.0 requires PKCS #8 DER. A folder key in PEM works on this).

For example: A folder can contain a DER private key and its matching PEM public key. It passes the stated check, but v0.7.0 cannot load the public file.

In the docs/server/auth.md rollback bullet, require public_key.der to be the matching public key in X.509 SubjectPublicKeyInfo DER, and private_key.der to be PKCS #8 DER, for folder deployments too. Give openssl rsa -in etc/conf/private_key.der -inform DER -pubout -outform DER -out etc/conf/public_key.der as the restore command, and keep the existing key-file export commands.

Evidence

The folder rollback instructions require a matching public key, then give the DER conversion steps specifically for servers using the key-file setting. The head retains an existing PEM public key for CRT keys and can decode PEM for non-CRT keys. The v0.7.0 reader instead passes the file bytes directly to X509EncodedKeySpec. I verified that reader operation rejects a valid PEM encoding on Java 17.

docs/server/auth.md:303-312

- The server no longer writes `etc/conf/key_id.txt` or `etc/conf/certs.json`, and leaves existing ones in place. An
  earlier version generates a new key when `key_id.txt` is missing, so before rolling back a server that was first
  started on this version, create `etc/conf/key_id.txt` with any value, for example `uc`. Before rolling back, check
  that `etc/conf/public_key.der` exists and contains the public key for `etc/conf/private_key.der`; this release only
  creates the public file when it is missing and leaves existing files untouched. Restore the matching public key
  before starting the earlier version if the file is absent or does not match. An earlier version also ignores the
  key file setting, so before rolling back a server that uses it, write its key to `etc/conf` in the formats an
  earlier version reads:
  `openssl pkcs8 -topk8 -nocrypt -in private_key.pem -outform DER -out etc/conf/private_key.der` and
  `openssl rsa -in private_key.pem -pubout -outform DER -out etc/conf/public_key.der`.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:87-99

    if (canDerivePublicKey(privateKey)) {
      publicKey = publicKeyOf(privateKey, privateKeyFile);
      writePublicKeyIfMissing(publicKeyFile, publicKey);
    } else {
      if (Files.notExists(publicKeyFile)) {
        throw new IllegalStateException(
            "The private key in "
                + privateKeyFile.toAbsolutePath()
                + " has no public exponent; a matching public key is required at "
                + publicKeyFile.toAbsolutePath());
      }
      publicKey = readPublicKey(publicKeyFile);
      verifyKeyPair(signedProbe, publicKey, privateKeyFile, publicKeyFile);

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:188-193

  private static void writePublicKeyIfMissing(Path file, RSAPublicKey publicKey) {
    Path temporaryFile = null;
    try {
      if (Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
        return;
      }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:332-336

  /**
   * Reads a key file in DER, or the first PEM block of the given kind ({@code PRIVATE KEY} or
   * {@code PUBLIC KEY}), skipping others such as a certificate. A PKCS #1 private key ({@code BEGIN
   * RSA PRIVATE KEY}, as written by the Helm chart and some {@code openssl genrsa} versions) is
   * wrapped in PKCS #8.
How it was checked

Checked by 2 independent checks, which split: CONTESTED, NITPICK

References:

Could the folder rollback instructions require the earlier release's encoding as well as a matching key?

initializeIfMissing(privateKeyFile);
privateKey = readPrivateKey(privateKeyFile);
publicKey = readPublicKey(publicKeyFile);
byte[] signedProbe = signProbe(privateKey, privateKeyFile);

@shba24 shba24 Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): The two-file mismatch diagnostic requires a usable private key

The description promises both filenames for mismatched non-CRT keys of different sizes. The constructor first signs a probe, so a signing failure takes precedence over the pair check.

For example: A 512-bit non-CRT private key paired with a different 2048-bit public key produces an error naming only the private file. Startup has not read public_key.der at that point.

Suggested change
byte[] signedProbe = signProbe(privateKey, privateKeyFile);
If the private key cannot sign with RS512, startup names the private-key file. If signing succeeds but the public key cannot verify the signature, startup names both files.
Evidence

The constructor signs before it reads the fallback public file. Signer errors name the private path, whereas the two-path message is constructed only in verifyKeyPair. The short-private-key test confirms the distinct diagnostic. Changing that test's public file to a different key cannot affect the earlier signing failure.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:84-99

    initializeIfMissing(privateKeyFile);
    privateKey = readPrivateKey(privateKeyFile);
    byte[] signedProbe = signProbe(privateKey, privateKeyFile);
    if (canDerivePublicKey(privateKey)) {
      publicKey = publicKeyOf(privateKey, privateKeyFile);
      writePublicKeyIfMissing(publicKeyFile, publicKey);
    } else {
      if (Files.notExists(publicKeyFile)) {
        throw new IllegalStateException(
            "The private key in "
                + privateKeyFile.toAbsolutePath()
                + " has no public exponent; a matching public key is required at "
                + publicKeyFile.toAbsolutePath());
      }
      publicKey = readPublicKey(publicKeyFile);
      verifyKeyPair(signedProbe, publicKey, privateKeyFile, publicKeyFile);

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:231-248

  private static void verifyKeyPair(
      byte[] signedProbe, RSAPublicKey publicKey, Path privateKeyFile, Path publicKeyFile) {
    String mismatchMessage =
        "The RSA keys in "
            + privateKeyFile.toAbsolutePath()
            + " and "
            + publicKeyFile.toAbsolutePath()
            + " do not match";
    try {
      Signature verifier = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
      verifier.initVerify(publicKey);
      verifier.update("unitycatalog-key-pair-check".getBytes(StandardCharsets.US_ASCII));
      if (!verifier.verify(signedProbe)) {
        throw new IllegalStateException(mismatchMessage);
      }
    } catch (InvalidKeyException | SignatureException e) {
      throw new IllegalStateException(mismatchMessage, e);
    }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:254-265

    Signature signer = Signature.getInstance(KEY_PAIR_CHECK_SIGNATURE_ALGORITHM);
    try {
      signer.initSign(privateKey);
      signer.update(probe);
      return signer.sign();
    } catch (InvalidKeyException | SignatureException e) {
      throw new IllegalStateException(
          "The private key in "
              + privateKeyFile.toAbsolutePath()
              + " cannot sign with SHA512withRSA (RS512)",
          e);
    }

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:331-346

  void reportsMatchingNonCrtKeyThatIsTooShortToSign() throws Exception {
    KeyPair shortKeyPair = newKeyPair(512);
    PrivateKey nonCrtKey = nonCrtPrivateKey(shortKeyPair);
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    Files.write(privateKeyFile, nonCrtKey.getEncoded());
    Files.write(publicKeyFile, shortKeyPair.getPublic().getEncoded());

    assertThatThrownBy(() -> new SecurityConfiguration(configurationFolder))
        .isInstanceOf(IllegalStateException.class)
        .hasMessageContaining(privateKeyFile.toAbsolutePath().toString())
        .hasMessageContaining("cannot sign with SHA512withRSA")
        .satisfies(error -> assertThat(error.getMessage()).doesNotContain("do not match"))
        .hasCauseInstanceOf(InvalidKeyException.class);
  }
How it was checked

Reproduced: build/sbt "server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest"

head:

Test ...SecurityConfigurationTest.namesBothFilesWhenShortNonCrtPrivateKeyMismatchesPublicKey failed: java.lang.AssertionError: Expecting throwable message: "The private key in /tmp/junit-3261055175605293687/private_key.der cannot sign with SHA512withRSA (RS512)" to contain: "/tmp/junit-3261055175605293687/public_key.der" but did not. Caused by: java.security.InvalidKeyException: Key is too short for this signature algorithm at SecurityConfiguration.signProbe(SecurityConfiguration.java:256)

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:330-342

  @Test
  void namesBothFilesWhenShortNonCrtPrivateKeyMismatchesPublicKey() throws Exception {
    PrivateKey nonCrtKey = nonCrtPrivateKey(newKeyPair(512));
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    Files.write(privateKeyFile, nonCrtKey.getEncoded());
    Files.write(publicKeyFile, newKeyPair().getPublic().getEncoded());

    assertThatThrownBy(() -> new SecurityConfiguration(configurationFolder))
        .isInstanceOf(IllegalStateException.class)
        .hasMessageContaining(privateKeyFile.toAbsolutePath().toString())
        .hasMessageContaining(publicKeyFile.toAbsolutePath().toString());
  }

Checked by 1 independent check: CONFIRMED

Could the mismatch claim distinguish a private signing failure from a public verification failure?

* once, when the configuration is loaded. Leaving the setting unset is deprecated: the server then
* uses {@code private_key.der} and {@code public_key.der} in the UC configuration folder,
* generating them on first start.
* unencrypted PEM key (PKCS #8 or PKCS #1), or a PKCS #8 DER key with CRT fields. The public key is

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): The configured-key Javadoc makes the CRT requirement look DER-specific

The class Javadoc attaches with CRT fields to the DER alternative. publicKeyOf applies the same requirement after decoding every configured private key.

For example: The phrase or a PKCS #8 DER key with CRT fields leaves a non-CRT PKCS #8 PEM key looking supported. The configured-file loader rejects it too.

Suggested change
* unencrypted PEM key (PKCS #8 or PKCS #1), or a PKCS #8 DER key with CRT fields. The public key is
* unencrypted RSA private key with CRT fields, in PKCS #8 PEM or DER, or PKCS #1 PEM. The public key is
Evidence

The class Javadoc attaches the CRT qualifier to the DER alternative. The configured-file loader sends every decoded private key through the same CRT check. The configuration reference already expresses the common requirement across encodings.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:37-42

 * <p>The private key is read from the file set in {@code server.token-signing-private-key-file}: an
 * unencrypted PEM key (PKCS #8 or PKCS #1), or a PKCS #8 DER key with CRT fields. The public key is
 * derived from it once, when the configuration is loaded. Leaving the setting unset is deprecated:
 * the server then uses {@code private_key.der} in the UC configuration folder, deriving the public
 * key from it when possible and creating {@code public_key.der} only if it is missing. For older
 * private keys without CRT fields, it reads and verifies the matching {@code public_key.der}.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:139-145

  /** Uses the given private key file and the public key derived from it. Nothing is written. */
  private static SecurityConfiguration fromPrivateKeyFile(Path privateKeyFile) {
    requireFile(privateKeyFile);
    RSAPrivateKey privateKey = readPrivateKey(privateKeyFile);
    signProbe(privateKey, privateKeyFile);
    return new SecurityConfiguration(privateKey, publicKeyOf(privateKey, privateKeyFile));
  }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:154-166

  private static boolean canDerivePublicKey(RSAPrivateKey privateKey) {
    return privateKey instanceof RSAPrivateCrtKey;
  }

  @SneakyThrows
  private static RSAPublicKey publicKeyOf(RSAPrivateKey privateKey, Path file) {
    if (!canDerivePublicKey(privateKey)) {
      throw new IllegalStateException(
          "The key in "
              + file.toAbsolutePath()
              + " has no public exponent; create it with"
              + " `openssl genrsa`");
    }

docs/server/configuration.md:77-80

- `server.token-signing-private-key-file`: The RSA private key the server signs and checks its own tokens with: an
    unencrypted RSA private key with CRT fields in PKCS #8 PEM or DER, or PKCS #1 PEM. The server derives the public
    key from it once, at startup. A file that is set must exist. Use the same key on every server instance. The
    server only reads the file, so it can be a read-only mount of a Kubernetes Secret. Create a key with:
How it was checked

Checked by 1 independent check: CONFIRMED

Could the Javadoc put the CRT requirement before the list of encodings?

}
}

// Installs the generated private key without replacing a key another starter already installed.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): The description leaves out how simultaneous first starts publish the private key

The description covers when the server generates a pair. It leaves out the new temporary-file installation procedure and its intended behavior when servers start against the same empty folder.

For example: The new concurrent-start test expects both servers and both files to agree on one key pair. That expectation is separate from preserving a private key when only the public file is missing.

Suggested change
// Installs the generated private key without replacing a key another starter already installed.
Private-key initialization now stages the generated key in a temporary file before publication. Concurrent first starts are intended to load the same installed key.
Evidence

I checked the full supplied description and its untruncated claims for simultaneous starts, shared folders, temporary files, and publication of the private key. None mentions this change. The head replaces the private-key installation procedure and adds a test requiring two starters to adopt the same key.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:268-292

  // Installs the generated private key without replacing a key another starter already installed.
  private static void writeOwnerOnly(Path file, byte[] content) throws IOException {
    Path temporaryFile = null;
    try {
      Path parentDirectory = file.toAbsolutePath().getParent();
      if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
        temporaryFile =
            Files.createTempFile(
                parentDirectory,
                file.getFileName().toString(),
                ".tmp",
                PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
      } else {
        temporaryFile =
            Files.createTempFile(parentDirectory, file.getFileName().toString(), ".tmp");
      }
      Files.write(temporaryFile, content);
      Files.move(temporaryFile, file);
    } catch (FileAlreadyExistsException e) {
      // Another server instance installed the private key first.
    } finally {
      if (temporaryFile != null) {
        Files.deleteIfExists(temporaryFile);
      }
    }

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:235-262

  @Test
  void concurrentFirstStartsInstallAMatchingKeyPair() throws Exception {
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    CyclicBarrier start = new CyclicBarrier(2);
    ExecutorService executor = Executors.newFixedThreadPool(2);
    try {
      Future<SecurityConfiguration> first =
          executor.submit(
              () -> {
                start.await(10, TimeUnit.SECONDS);
                return new SecurityConfiguration(configurationFolder);
              });
      Future<SecurityConfiguration> second =
          executor.submit(
              () -> {
                start.await(10, TimeUnit.SECONDS);
                return new SecurityConfiguration(configurationFolder);
              });

      SecurityConfiguration firstConfiguration = first.get(30, TimeUnit.SECONDS);
      SecurityConfiguration secondConfiguration = second.get(30, TimeUnit.SECONDS);
      assertThat(firstConfiguration.rsaPublicKey()).isEqualTo(secondConfiguration.rsaPublicKey());
      assertThat(firstConfiguration.rsaPrivateKey()).isEqualTo(secondConfiguration.rsaPrivateKey());
      assertThat(Files.readAllBytes(publicKeyFile))
          .isEqualTo(firstConfiguration.rsaPublicKey().getEncoded());
      assertThat(Files.readAllBytes(privateKeyFile))
          .isEqualTo(firstConfiguration.rsaPrivateKey().getEncoded());
How it was checked

Checked by 2 independent checks: NITPICK

Could the description call out the shared-folder case and the intended publication guarantee?

@yajneshx94

Copy link
Copy Markdown
Author

Thanks @shba24, I've pushed b9565da with the fixes for your blockers and nits:

  • The permission test now compares against a reference file created under the same umask instead of hardcoding rw-r--r--.
  • Configured key files no longer run the signing probe, so the change stays scoped to the deprecated folder path.
  • The rollback docs state the required DER formats (PKCS Add issue templates #8 private key, X.509 public key) and include the openssl command to recreate public_key.der.
  • The class Javadoc now applies the CRT wording to every encoding, the builder Javadoc note about tests using separate folders is back, and the probe string is a single constant.

I kept concurrent installation best effort rather than adding the createLink helper, and left the other non-blocking nits as follow-ups. Is there anything else blocking?

@shba24 shba24 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for taking a look and working on this . We really appreciate it. We almost at the end of finishing the review of this PR.

Files.createTempFile(
parentDirectory,
file.getFileName().toString(),
".tmp",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: A first start can stage the active private signing key in Git

The repository ignores etc/conf/*.der. Both staging branches write the generated private key under a .tmp name, so the signing key can enter the Git index even though its final filename is ignored. This is one bug class: Secret key bytes get staged on disk under a name that the checkout's signing-key ignore rules do not cover. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:278 (On POSIX, writeOwnerOnly writes the newly generated PKCS#8 private key into private_key.der<random>.tmp, which Git does not ignore. A concurrent git add -A ); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:285 (The non-POSIX branch has the same .tmp suffix. It also creates the temp file with default permissions, so the exposed key file is not owner-only either.); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:287 (If the process dies between Files.write(temporaryFile) and Files.move, the finally block never runs. The private key then stays in the unignored .tmp file per); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:223 (createPublicKeyTempFile stages public_key.der<random>.tmp, which is also unignored. The public key is not secret, but a crash leaves an untracked file in the ).

For example: If a developer runs git add -A after Files.write and before Files.move, Git can stage the temporary file. Moving it to the ignored final name does not remove the staged bytes.

Suggested change
".tmp",
".der",
Evidence

initializeIfMissing passes the generated private encoding into writeOwnerOnly. Both filesystem branches create a .tmp file, then write the actual private key before moving it. I checked both branches, the finally cleanup and the repository’s signing-key ignore rules. git check-ignore matched etc/conf/private_key.der and did not match etc/conf/private_key.der123.tmp. A Git add during this interval can retain the subsequently installed key in the index after the move.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:181-187

    if (Files.notExists(privateKeyFile)) {
      log.info("Initializing security configuration.");
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(2048);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();
      writeOwnerOnly(privateKeyFile, keyPair.getPrivate().getEncoded());
    }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:275-295

      Path parentDirectory = file.toAbsolutePath().getParent();
      if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
        temporaryFile =
            Files.createTempFile(
                parentDirectory,
                file.getFileName().toString(),
                ".tmp",
                PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
      } else {
        temporaryFile =
            Files.createTempFile(parentDirectory, file.getFileName().toString(), ".tmp");
      }
      Files.write(temporaryFile, content);
      Files.move(temporaryFile, file);
    } catch (FileAlreadyExistsException e) {
      // Another server instance installed the private key first.
    } finally {
      if (temporaryFile != null) {
        Files.deleteIfExists(temporaryFile);
      }
    }

.gitignore:27-37

# Signing keys and access tokens
etc/conf/certs.json
etc/conf/*.txt
etc/conf/*.der
etc/conf/*.pem
connectors/spark/etc/conf/certs.json
connectors/spark/etc/conf/*.txt
connectors/spark/etc/conf/*.der
integration-tests/etc/conf/certs.json
integration-tests/etc/conf/*.txt
integration-tests/etc/conf/*.der
How it was checked

Reproduced: dev/run-tests.py -p 1 -v 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest -- --tests=.*stagedGeneratedPrivateKeyNameIsGitIgnored.*'

head:

SecurityConfigurationTest#stagedGeneratedPrivateKeyNameIsGitIgnored(): org.opentest4j.AssertionFailedError: [git check-ignore etc/conf/private_key.der8077142540366762893.tmp (0 = ignored)] expected: 0 but was: 1 (at SecurityConfigurationTest.java:262). Failed: Total 28, Failed 1, Passed 13, Skipped 14

with the fix:

With the fix (both temp-file suffixes changed from .tmp to .der): Test run finished: 0 failed, 0 ignored, 14 total. Passed: Total 28, Failed 0, Errors 0, Passed 14, Skipped 14 (13 earlier passes plus the target test).

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:225-265

  @Test
  void stagedGeneratedPrivateKeyNameIsGitIgnored() throws Exception {
    java.util.List<String> stagedNames = new java.util.ArrayList<>();
    try (MockedStatic<Files> files = mockStatic(Files.class, Mockito.CALLS_REAL_METHODS)) {
      files
          .when(
              () ->
                  Files.write(
                      argThat(
                          file ->
                              file != null
                                  && file.getParent().equals(configurationFolder)
                                  && file.getFileName().toString().startsWith("private_key.der")),
                      any(byte[].class)))
          .thenAnswer(
              invocation -> {
                stagedNames.add(((Path) invocation.getArgument(0)).getFileName().toString());
                return invocation.callRealMethod();
              });

      SecurityConfiguration.load(settings(Path.of(" ")), configurationFolder);
    }

    assertThat(stagedNames).hasSize(1);
    String root =
        new String(
                new ProcessBuilder("git", "rev-parse", "--show-toplevel")
                    .start()
                    .getInputStream()
                    .readAllBytes())
            .trim();
    for (String name : java.util.List.of("private_key.der", stagedNames.get(0))) {
      int exit =
          new ProcessBuilder("git", "check-ignore", "-q", "etc/conf/" + name)
              .directory(new java.io.File(root))
              .start()
              .waitFor();
      assertThat(exit).as("git check-ignore etc/conf/" + name + " (0 = ignored)").isZero();
    }
  }

Checked by 2 independent checks: CONFIRMED

References:

Could both private-key temp-file branches use a suffix already covered by the signing-key ignore rules?

}
Files.write(temporaryFile, content);
Files.move(temporaryFile, file);
} catch (FileAlreadyExistsException e) {

@shba24 shba24 Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: A dangling private-key link now stops a single server from starting

The PR description covers concurrent installation. The same change also affects an existing symbolic link whose target is missing, even when only one server starts. This is one bug class: Existence checks that follow links are paired with a move that does not replace a link, so a dangling key-file link is neither fixed nor reported. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:181 (Files.notExists follows the dangling private_key.der link and returns true, so a key is generated. Files.move then sees the link and throws FileAlreadyExistsExc); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:193 (A dangling public_key.der link exists under NOFOLLOW_LINKS, so the server returns early and leaves the link dangling. Before this change, the base saw notExists); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:94 (In the non-CRT branch, notExists follows a dangling public_key.der link. The server reports that 'a matching public key is required at …/public_key.der' without).

For example: With private_key.der pointing to an absent file, Files.move throws FileAlreadyExistsException. The handler proceeds and startup fails with NoSuchFileException when the constructor reads the link.

Suggested change
} catch (FileAlreadyExistsException e) {
A dangling `private_key.der` symlink is preserved. Startup now fails until the target is restored or the link is removed to allow a new signing key to be generated.
Evidence

The private-key existence check follows the dangling link. The move encounters the existing directory entry, its exception is treated as another starter succeeding, and the constructor reads the still-missing target. I reproduced that sequence on JDK 17 with one process. The base deleted the entry before creating the private file. I checked the full restated description, builder Javadoc, auth guide, and configuration reference for this change in startup behavior.

Both Javadocs say a missing key is generated. Files.notExists (line 181) follows links, so a dangling symlink counts as missing. Files.move without REPLACE_EXISTING (line 288) throws FileAlreadyExistsException on the link itself, and the catch (lines 289-290) swallows it with a comment that names another cause. readPrivateKey (line 88), through Files.readAllBytes (line 342), then throws a raw NoSuchFileException. I reproduced this on JDK 21: notExists=true, then FileAlreadyExists, then a NoSuchFileException on read.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:84-88

  public SecurityConfiguration(Path configurationFolder) {
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    initializeIfMissing(privateKeyFile);
    privateKey = readPrivateKey(privateKeyFile);

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:181-187

    if (Files.notExists(privateKeyFile)) {
      log.info("Initializing security configuration.");
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(2048);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();
      writeOwnerOnly(privateKeyFile, keyPair.getPrivate().getEncoded());
    }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:287-295

      Files.write(temporaryFile, content);
      Files.move(temporaryFile, file);
    } catch (FileAlreadyExistsException e) {
      // Another server instance installed the private key first.
    } finally {
      if (temporaryFile != null) {
        Files.deleteIfExists(temporaryFile);
      }
    }

server/src/main/java/io/unitycatalog/server/UnityCatalogServer.java:755-759

     * Sets the folder for the {@code token.txt} the server writes when constructed and, unless
     * {@code server.token-signing-private-key-file} is set, the signing keys. The server generates
     * {@code private_key.der} if it is missing; for a CRT private key it derives the public key and
     * writes {@code public_key.der} only if that file is missing. An existing non-CRT private key
     * requires its matching public key file. Defaults to {@code etc/conf}.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:79-88

  /**
   * Uses the private key in the configuration folder, generating it if missing. A non-CRT private
   * key requires its matching {@code public_key.der}.
   */
  @SneakyThrows
  public SecurityConfiguration(Path configurationFolder) {
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    initializeIfMissing(privateKeyFile);
    privateKey = readPrivateKey(privateKeyFile);
How it was checked

Reproduced: dev/run-tests.py -p 1 -v 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest'

head:

SecurityConfigurationTest#replacesDanglingPrivateKeyLinkWithGeneratedKey(): java.nio.file.NoSuchFileException: .../server/target/test-tmp/0/junit-17116592067250561937/private_key.der
  at java.nio.file.Files.readAllBytes(Files.java:3288)
  at SecurityConfiguration.readKeyFile(SecurityConfiguration.java:342)
  at SecurityConfiguration.readPrivateKey(SecurityConfiguration.java:323)
  at SecurityConfiguration.<init>(SecurityConfiguration.java:88)
  at SecurityConfigurationTest.replacesDanglingPrivateKeyLinkWithGeneratedKey(SecurityConfigurationTest.java:81)
Failed: Total 28, Failed 1, Errors 0, Passed 27

with the fix:

Base run (SecurityConfiguration.java from 23795fc7, with the same test): the test started and no failure line was reported for it. The other 12 failures in that run are older head-specific tests that the base code does not satisfy. The test passes on the base: the old writeOwnerOnly deleted the link before writing the new key.

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:75-85

  // A dangling private_key.der link used to be replaced by a generated key on first startup.
  @Test
  void replacesDanglingPrivateKeyLinkWithGeneratedKey() throws Exception {
    Files.createSymbolicLink(
        configurationFolder.resolve("private_key.der"), keyDirectory.resolve("missing.der"));

    SecurityConfiguration configuration = new SecurityConfiguration(configurationFolder);

    assertThat(configuration.rsaPrivateKey()).isNotNull();
  }

Checked by 2 independent checks: CONFIRMED

References:

Could we call out this change and tell operators how to recover?

@shba24

shba24 commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

Thanks for working through the open blockers in b9565da and for stating which ones you left as follow-ups. On the two points you made, you're right.

  • Permission test: SecurityConfigurationTest now compares public_key.der with a reference file created under the same umask, so the assertion no longer depends on rw-r--r--. It still checks that the file is created with the mode we intended.
  • Configured key files: the signing probe now runs only in the deprecated folder constructor in SecurityConfiguration. A key set through the key-file property loads as it did before, including short CRT keys. That keeps the change scoped to the folder path, as the description says.

On your question about anything else blocking, I'd go with your plan. Best-effort concurrent installation without the createLink helper matches what the description now says, and the remaining nits can wait for follow-ups. The rollback docs, Javadoc and probe constant fixes are worth a quick look against their own threads before resolving them, since this reply doesn't cover them. Otherwise nothing further from my side on these two points, and they can be resolved.

@yili-db

yili-db commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

/review

@yili-db yili-db left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] Comment. Two blockers, then normal items. This is our first review on this PR.

Blockers:

  • Rebase onto main: the PR is DIRTY with main commit 80b1c5e (#2389, RS512 check when a signing key is loaded). Resolving the conflict in SecurityConfigurationTest.java to this PR's version leaves two failing tests: loadsConfiguredCrtKeyWithoutSigningProbe and reportsMatchingNonCrtKeyThatIsTooShortToSign (72 tests, 2 failed). The description sentence "The explicitly configured key-file path keeps its existing loading behavior" is also no longer accurate after the merge.
  • Dangling private_key.der link: with a dangling symbolic link in the folder, startup fails with NoSuchFileException and keeps the link. At aa8f434 the same folder loads and the link is replaced by a regular file. Inline comment at SecurityConfiguration.java:181.

Normal:

  • A stale public_key.der is kept when a new private key is generated (inline, SecurityConfiguration.java:92).
  • Concurrent first starts can leave two different private keys, and the test that asserts equal keys can flake (inline, SecurityConfiguration.java:288).
  • The temp file private_key.der<random>.tmp is not matched by etc/conf/*.der in .gitignore. Adding etc/conf/*.tmp would cover it. This file is not in the diff, so it is noted here.
  • A PEM public_key.der is left untouched, and an earlier release cannot read it on rollback (inline, docs/server/auth.md:306).

Redundancy:

  • The folder path runs two RS512 sign checks with different messages: signProbe and the check in readPrivateKey from #2389 (inline, SecurityConfiguration.java:89).
  • The CRT rule is written in canDerivePublicKey and again in publicKeyOf.
  • The SHA512withRSA literal appears in the constant and in the new check.
  • The install code is duplicated in writeOwnerOnly and writePublicKeyIfMissing.

Checked: the suites pass at b9565da before the merge (72 tests). Reverting the derivation back to reading public_key.der fails 8 of 27 SecurityConfigurationTest tests.

if (parentDirectory != null) {
Files.createDirectories(parentDirectory);
}
if (Files.notExists(privateKeyFile)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] With private_key.der set to a dangling symbolic link, startup now fails. Files.notExists follows the link and reports the file missing, so a key is generated, and writeOwnerOnly then moves it onto the link. That fails with NoSuchFileException and leaves the link in place. At aa8f434 the same folder loads and the link is replaced by a regular file, so this is a startup regression.

Suggested fix: remove the link before the install (Files.deleteIfExists, as writeOwnerOnly did before), or reject a dangling link with a message that names the file. Please add a test for a dangling link in the folder that asserts whichever behavior is chosen.

byte[] signedProbe = signProbe(privateKey, privateKeyFile);
if (canDerivePublicKey(privateKey)) {
publicKey = publicKeyOf(privateKey, privateKeyFile);
writePublicKeyIfMissing(publicKeyFile, publicKey);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] When private_key.der is missing and public_key.der already exists, this generates a new private key, and writePublicKeyIfMissing keeps the existing file. The server serves the derived key, but the file on disk now belongs to a different key. An earlier release that reads public_key.der then rejects every token it signs. The docs' manual check covers this, but the server created the mismatch itself.

Suggested fix: when this call generated the private key, replace the public file with the derived key. Keep the create-if-missing rule in every other case. A test with a stale public file and a missing private file would pin the behavior.

Files.createTempFile(parentDirectory, file.getFileName().toString(), ".tmp");
}
Files.write(temporaryFile, content);
Files.move(temporaryFile, file);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] Files.move without REPLACE_EXISTING checks for the target and then renames, so two first starts can both pass the check, and the second rename replaces the first start's key. Each server may then hold a different private key. concurrentFirstStartsInstallAMatchingKeyPair asserts equal keys, so it can fail intermittently.

Suggested fix: publish with Files.createLink(file, temporaryFile), which fails when the target exists, and fall back to move only where links are not supported. Alternatively, assert only that the files on disk form a matching pair.

initializeIfMissing(privateKeyFile);
privateKey = readPrivateKey(privateKeyFile);
publicKey = readPublicKey(publicKeyFile);
byte[] signedProbe = signProbe(privateKey, privateKeyFile);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] With #2389 on main, the folder path signs with RS512 twice: readPrivateKey runs requireCanSignRs512, and this signProbe runs right after it with a different message. Keep one check. The #2389 message is the one that names the file and the setting.

Comment thread docs/server/auth.md Outdated
ignores the key file setting, so before rolling back a server that uses it, write its key to `etc/conf` in the
formats an earlier version reads:
started on this version, create `etc/conf/key_id.txt` with any value, for example `uc`. Before rolling back, check
that `etc/conf/public_key.der` exists and contains the public key for `etc/conf/private_key.der`; this release only

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] This says the file must contain the public key, but an earlier release reads public_key.der as raw X.509 DER: v0.7.0 rsaPublicKey() passes the bytes straight to X509EncodedKeySpec. A PEM file that this release leaves in place therefore breaks rollback.

Suggested fix: state that the file must be DER, and give the openssl rsa ... -outform DER command for a PEM key.

…ey-from-private-key

Signed-off-by: yajneshx94 <[email protected]>

# Conflicts:
#	server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java
@yajneshx94

Copy link
Copy Markdown
Author

Thanks @yili-db and @shba24. I've merged main (3534a94) and addressed
the blockers: a dangling private_key.der link now fails with a clear
message, the temporary files use a .der suffix covered by .gitignore, a
stale public_key.der is replaced when a new private key is generated,
keys are installed with a no-replace hard link where supported, there is
now a single RS512 signing check, and the rollback docs mention DER. I've
updated the description to match. The remaining nits I'm leaving as
follow-ups.

@yili-db

yili-db commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

/review

@yajneshx94

Copy link
Copy Markdown
Author

Thanks for the review @yili-db . I pushed (dcc7962) addressing the hard-link fallback and the two related test nits:

  • If hard-link creation fails, installation now falls back to CREATE_NEW, which still never overwrites an existing key. I added a test that simulates the link failure and checks cleanup.
  • The concurrent-start test now compares both starters' keys with the persisted pair.
  • The git-dependent test skips when git or repository metadata isn't available, and uses timeouts.

@yili-db

yili-db commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

/review

Set<OpenOption> options = Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
boolean posix = file.getFileSystem().supportedFileAttributeViews().contains("posix");
boolean created = false;
try (SeekableByteChannel channel =

@shba24 shba24 Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker, medium probability: Concurrent starts can read an incomplete signing key

The fallback makes the destination visible before its contents are complete, so startup can fail while another server is installing the key.

Details

For example: On a filesystem without hard links, one server creates private_key.der and another reads it before the first finishes writing. The second server fails to parse the key; an interrupted writer can also leave the incomplete file for later starts.

Publish the staged key with an atomic no-replace operation, or fail safely when the filesystem cannot provide one.

Evidence:

The hard-link fallback creates the destination before writing its bytes. The constructor immediately reads any existing private key, with no coordination or recovery for an incomplete file.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:237-248

      } else {
        try {
          Files.createLink(file, temporaryFile);
        } catch (FileAlreadyExistsException e) {
          throw e;
        } catch (UnsupportedOperationException | FileSystemException e) {
          writeNewFile(file, content, permissions);
        }
      }
      return true;
    } catch (FileAlreadyExistsException e) {
      return false;

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:254-270

  private static void writeNewFile(Path file, byte[] content, String permissions)
      throws IOException {
    Set<OpenOption> options = Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
    boolean posix = file.getFileSystem().supportedFileAttributeViews().contains("posix");
    boolean created = false;
    try (SeekableByteChannel channel =
        posix
            ? Files.newByteChannel(
                file,
                options,
                PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(permissions)))
            : Files.newByteChannel(file, options)) {
      created = true;
      ByteBuffer buffer = ByteBuffer.wrap(content);
      while (buffer.hasRemaining()) {
        channel.write(buffer);
      }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:93-97

  public SecurityConfiguration(Path configurationFolder) {
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    boolean generatedPrivateKey = initializeIfMissing(privateKeyFile);
    privateKey = readPrivateKey(privateKeyFile);

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:197-203

    if (Files.notExists(privateKeyFile)) {
      log.info("Initializing security configuration.");
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(2048);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();
      return writeOwnerOnly(privateKeyFile, keyPair.getPrivate().getEncoded());
    }

How it was checked:

Reproduced: dev/run-tests.py -p 1 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest'

head:

1 suites, 33 tests, 1 failed
Failed tests:
  io.unitycatalog.server.security.SecurityConfigurationTest#fallbackInstallNeverExposesAnIncompleteKeyToAConcurrentStart(): org.opentest4j.AssertionFailedError: [a start that overlaps the first install must not fail on a partial key] expected: null but was: java.lang.IllegalStateException: Cannot read the RSA private key in .../private_key.der (at SecurityConfiguration.readPrivateKey(SecurityConfiguration.java:371)). A debug run of the same test printed 'size at inner start=0' before the inner start threw.

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:314-388

  @Test
  void fallbackInstallNeverExposesAnIncompleteKeyToAConcurrentStart() throws Exception {
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    java.util.concurrent.atomic.AtomicReference<Throwable> concurrentStart =
        new java.util.concurrent.atomic.AtomicReference<>();
    boolean[] started = {false};

    try (MockedStatic<Files> files = mockStatic(Files.class, Mockito.CALLS_REAL_METHODS)) {
      files
          .when(() -> Files.createLink(any(Path.class), any(Path.class)))
          .thenThrow(new FileSystemException("hard links are unavailable"));
      files
          .when(() -> Files.newByteChannel(any(Path.class), any(java.util.Set.class), any()))
          .thenAnswer(
              invocation -> {
                java.nio.channels.SeekableByteChannel real =
                    (java.nio.channels.SeekableByteChannel) invocation.callRealMethod();
                Path target = invocation.getArgument(0);
                if (!target.getFileName().toString().equals("private_key.der")) {
                  return real;
                }
                return new java.nio.channels.SeekableByteChannel() {
                  public int write(java.nio.ByteBuffer src) throws IOException {
                    if (!started[0]) {
                      started[0] = true;
                      // Another process starts after the key path exists but before its bytes.
                      try {
                        new SecurityConfiguration(configurationFolder);
                      } catch (Throwable t) {
                        concurrentStart.set(t);
                      }
                    }
                    return real.write(src);
                  }

                  public int read(java.nio.ByteBuffer dst) throws IOException {
                    return real.read(dst);
                  }

                  public long position() throws IOException {
                    return real.position();
                  }

                  public java.nio.channels.SeekableByteChannel position(long p) throws IOException {
                    real.position(p);
                    return this;
                  }

                  public long size() throws IOException {
                    return real.size();
                  }

                  public java.nio.channels.SeekableByteChannel truncate(long n) throws IOException {
                    real.truncate(n);
                    return this;
                  }

                  public boolean isOpen() {
                    return real.isOpen();
                  }

                  public void close() throws IOException {
                    real.close();
                  }
                };
              });
      new SecurityConfiguration(configurationFolder);
    }

    assertThat(started[0]).as("fallback write path was reached").isTrue();
    assertThat(concurrentStart.get())
        .as("a start that overlaps the first install must not fail on a partial key")
        .isNull();
  }

Checked by 2 independent checks: CONFIRMED

Could we publish only a complete key, or fail safely when that is unavailable?

file,
options,
PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(permissions)))
: Files.newByteChannel(file, options)) {

@shba24 shba24 Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker, low probability: A second server can read an empty signing key during first start

CREATE_NEW makes private_key.der visible before channel.write supplies its bytes. A server that sees the path skips generation, so startup can fail on a key that is still being installed.

Details

For example: On a filesystem without hard links, one server opens private_key.der and another loads it before the first channel.write. The second server gets Cannot read the RSA private key. If the writer stops at that point, subsequent starts see the same empty file. This is one bug class: A key file becomes visible at its final path before its bytes are complete and durable, and every reader treats any existing file as a finished key. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:259 (When hard links are unavailable, CREATE_NEW creates an empty private_key.der at its final path and only then writes the bytes.); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:216 (The public compatibility file goes through the same fallback and is also visible empty before it is written.); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:234; server/src/main/java/io/unitycatalog/server/security/SecurityContext.java:73 (Files.writeString truncates token.txt in place and then writes it, on every start.).

Coordinate fallback initialization across processes, recheck the destination while holding the lock, and publish the completed staging file atomically. If the filesystem cannot support safe publication, fail before creating the final key path.

Evidence:

installFile falls back to writeNewFile when linking fails. That method opens the final path with CREATE_NEW before its first channel.write. I checked the constructor, initializeIfMissing, installFile, and readPrivateKey: no lock covers publication and reading. A reader that sees the path skips generation and decodes its current bytes immediately. In a single-threaded Java 17 check after opening the channel and before writing, Files.notExists returned false, readAllBytes returned zero bytes, and RSA decoding threw InvalidKeySpecException. The fallback test observes the file only after construction returns. The concurrent test does not force the fallback.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:238-245

        try {
          Files.createLink(file, temporaryFile);
        } catch (FileAlreadyExistsException e) {
          throw e;
        } catch (UnsupportedOperationException | FileSystemException e) {
          writeNewFile(file, content, permissions);
        }
      }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:254-270

  private static void writeNewFile(Path file, byte[] content, String permissions)
      throws IOException {
    Set<OpenOption> options = Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
    boolean posix = file.getFileSystem().supportedFileAttributeViews().contains("posix");
    boolean created = false;
    try (SeekableByteChannel channel =
        posix
            ? Files.newByteChannel(
                file,
                options,
                PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(permissions)))
            : Files.newByteChannel(file, options)) {
      created = true;
      ByteBuffer buffer = ByteBuffer.wrap(content);
      while (buffer.hasRemaining()) {
        channel.write(buffer);
      }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:197-204

    if (Files.notExists(privateKeyFile)) {
      log.info("Initializing security configuration.");
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(2048);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();
      return writeOwnerOnly(privateKeyFile, keyPair.getPrivate().getEncoded());
    }
    return false;

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:93-98

  public SecurityConfiguration(Path configurationFolder) {
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    boolean generatedPrivateKey = initializeIfMissing(privateKeyFile);
    privateKey = readPrivateKey(privateKeyFile);
    byte[] signedProbe = signProbe(privateKey, privateKeyFile);

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:363-374

  @SneakyThrows
  private static RSAPrivateKey readPrivateKey(Path file) {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(readKeyFile(file, "PRIVATE KEY"));
    try {
      return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(spec);
    } catch (InvalidKeySpecException e) {
      throw new IllegalStateException(
          "Cannot read the RSA private key in "
              + file.toAbsolutePath()
              + "; expected an unencrypted RSA private key in PKCS #8 PEM or DER, or PKCS #1 PEM",
          e);
    }

How it was checked:

Reproduced: dev/run-tests.py -p 1 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest -- *fallbackInstallNever*'

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.fallbackInstallNeverExposesAnIncompleteKeyToAConcurrentStart failed: java.lang.AssertionError: [a start racing the fallback install]
Failed tests:
  SecurityConfigurationTest#fallbackInstallNeverExposesAnIncompleteKeyToAConcurrentStart(): java.lang.AssertionError: [a start racing the fallback install] Expecting empty but was: [java.lang.IllegalStateException: Cannot read the RSA private key in .../private_key.der ... (at io.unitycatalog.server.security.SecurityConfiguration.readPrivateKey(SecurityConfiguration.java:371))
1 suites, 23 tests, 1 failed

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:314-353

  @Test
  void fallbackInstallNeverExposesAnIncompleteKeyToAConcurrentStart() throws Exception {
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    List<Throwable> concurrentStartFailures = new ArrayList<>();
    boolean[] observed = {false};

    try (MockedStatic<Files> files = mockStatic(Files.class, Mockito.CALLS_REAL_METHODS)) {
      files
          .when(() -> Files.createLink(any(Path.class), any(Path.class)))
          .thenThrow(new FileSystemException("hard links are unavailable"));
      files
          .when(
              () ->
                  Files.newByteChannel(
                      argThat(path -> privateKeyFile.equals(path)),
                      any(java.util.Set.class),
                      any(java.nio.file.attribute.FileAttribute[].class)))
          .thenAnswer(
              invocation -> {
                java.nio.channels.SeekableByteChannel real =
                    (java.nio.channels.SeekableByteChannel) invocation.callRealMethod();
                if (observed[0]) {
                  return real;
                }
                // The destination now exists and is still empty: start a second server here.
                observed[0] = true;
                try {
                  new SecurityConfiguration(configurationFolder);
                } catch (Throwable t) {
                  concurrentStartFailures.add(t);
                }
                return real;
              });

      new SecurityConfiguration(configurationFolder);
    }

    assertThat(observed[0]).as("fallback created the destination file").isTrue();
    assertThat(concurrentStartFailures).as("a start racing the fallback install").isEmpty();
  }

Checked by 2 independent checks: CONFIRMED

References:

Could the fallback publish the completed staging file under a lock shared by first starts?

return installFile(file, content, "rw-------", false);
}

private static boolean installFile(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit, high probability: One boolean picks between two file-install algorithms, and a helper named IfMissing can replace the file

installFile(..., replaceExisting) replaces the target with a move when the flag is true, and creates it only if absent (hard link, then a CREATE_NEW fallback) when it is false.
The returned boolean is only meaningful in the second mode. The flag also passes through writePublicKeyIfMissing, which replaces the file when it is set.

Details

Cost of keeping it: The next file installed in the configuration folder has to pick a flag value and learn that the return value matters in only one mode. Readers of writePublicKeyIfMissing cannot tell from its name that it may overwrite public_key.der. The POSIX permission branch also lives in both createTempFile and writeNewFile, so the two copies can drift apart.

private static boolean createIfAbsent(Path file, byte[] content, String permissions)
    throws IOException { /* temp file + createLink, CREATE_NEW fallback */ }

private static void replace(Path file, byte[] content, String permissions)
    throws IOException { /* temp file + move REPLACE_EXISTING */ }

// caller
if (generatedPrivateKey) {
  replace(publicKeyFile, encoded, "rw-r--r--");
} else if (!Files.exists(publicKeyFile, LinkOption.NOFOLLOW_LINKS)) {
  createIfAbsent(publicKeyFile, encoded, "rw-r--r--");
}

Evidence:

Lines 230-252: replaceExisting selects either a move that replaces the target and always returns true, or a hard link that never replaces, with a CREATE_NEW fallback, whose result means "this call won". Lines 207-216: writePublicKeyIfMissing passes its replaceExisting flag on and replaces the file when it is true, which its name does not say. Lines 226-228: writeOwnerOnly is a one-line wrapper with one caller (line 202). Lines 256-265 and 286-293 each build the POSIX permission attribute behind the same supportedFileAttributeViews().contains("posix") check. I grepped server/src/main for an existing install helper and found none. The rules come from CODE_REVIEW.md on main, "make illegal states unrepresentable" and "Inline single-use helpers; collapse one-liners", and from AGENTS.md on main, "Prefer construction that makes illegal states unrepresentable."

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:207-228

  private static void writePublicKeyIfMissing(
      Path file, RSAPublicKey publicKey, boolean replaceExisting) {
    try {
      if (!replaceExisting && Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
        if (Files.isSymbolicLink(file) && Files.notExists(file)) {
          log.warn("Compatibility public key path {} is a dangling symbolic link", file);
        }
        return;
      }
      installFile(file, publicKey.getEncoded(), "rw-r--r--", replaceExisting);
    } catch (IOException e) {
      log.warn(
          "Could not write compatibility public key file {}. The server will continue using the"
              + " public key derived from the private key.",
          file,
          e);
    }
  }

  private static boolean writeOwnerOnly(Path file, byte[] content) throws IOException {
    return installFile(file, content, "rw-------", false);
  }

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:230-294

  private static boolean installFile(
      Path file, byte[] content, String permissions, boolean replaceExisting) throws IOException {
    Path temporaryFile = createTempFile(file, permissions);
    try {
      Files.write(temporaryFile, content);
      if (replaceExisting) {
        Files.move(temporaryFile, file, StandardCopyOption.REPLACE_EXISTING);
      } else {
        try {
          Files.createLink(file, temporaryFile);
        } catch (FileAlreadyExistsException e) {
          throw e;
        } catch (UnsupportedOperationException | FileSystemException e) {
          writeNewFile(file, content, permissions);
        }
      }
      return true;
    } catch (FileAlreadyExistsException e) {
      return false;
    } finally {
      Files.deleteIfExists(temporaryFile);
    }
  }

  private static void writeNewFile(Path file, byte[] content, String permissions)
      throws IOException {
    Set<OpenOption> options = Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
    boolean posix = file.getFileSystem().supportedFileAttributeViews().contains("posix");
    boolean created = false;
    try (SeekableByteChannel channel =
        posix
            ? Files.newByteChannel(
                file,
                options,
                PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(permissions)))
            : Files.newByteChannel(file, options)) {
      created = true;
      ByteBuffer buffer = ByteBuffer.wrap(content);
      while (buffer.hasRemaining()) {
        channel.write(buffer);
      }
    } catch (IOException | RuntimeException e) {
      if (created) {
        try {
          Files.deleteIfExists(file);
        } catch (IOException cleanupException) {
          e.addSuppressed(cleanupException);
        }
      }
      throw e;
    }
  }

  private static Path createTempFile(Path file, String permissions) throws IOException {
    Path parentDirectory = file.toAbsolutePath().getParent();
    String prefix = file.getFileName().toString();
    if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
      return Files.createTempFile(
          parentDirectory,
          prefix,
          ".der",
          PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(permissions)));
    }
    return Files.createTempFile(parentDirectory, prefix, ".der");
  }

How it was checked:

Checked by 2 independent checks: NITPICK

Would two named operations, with writeOwnerOnly inlined, read more clearly than the flag?

} catch (FileAlreadyExistsException e) {
throw e;
} catch (UnsupportedOperationException | FileSystemException e) {
writeNewFile(file, content, permissions);

@shba24 shba24 Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit, medium probability: A second server can see an empty signing key on the fallback path

The description covers the no-replace hard link. The fallback opens the final filename before writing the key, so a concurrent start can fail to load it.

Details

For example: If one server opens private_key.der with CREATE_NEW and pauses before channel.write, a second server sees the file, skips generation, and tries to parse the empty contents.

Mention the exclusive-create fallback and limit the guarantee that readers see a complete key to the hard-link path.

Evidence:

I checked the complete restated description, the final installation commit, both server docs, and the fallback and concurrency tests. The description covers hard-link installation where supported. It omits the alternate path that creates the final filename before writing any bytes. A competing constructor proceeds directly to parsing that file.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:94-98

    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    boolean generatedPrivateKey = initializeIfMissing(privateKeyFile);
    privateKey = readPrivateKey(privateKeyFile);
    byte[] signedProbe = signProbe(privateKey, privateKeyFile);

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:197-204

    if (Files.notExists(privateKeyFile)) {
      log.info("Initializing security configuration.");
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(2048);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();
      return writeOwnerOnly(privateKeyFile, keyPair.getPrivate().getEncoded());
    }
    return false;

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:238-249

        try {
          Files.createLink(file, temporaryFile);
        } catch (FileAlreadyExistsException e) {
          throw e;
        } catch (UnsupportedOperationException | FileSystemException e) {
          writeNewFile(file, content, permissions);
        }
      }
      return true;
    } catch (FileAlreadyExistsException e) {
      return false;
    } finally {

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:254-270

  private static void writeNewFile(Path file, byte[] content, String permissions)
      throws IOException {
    Set<OpenOption> options = Set.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
    boolean posix = file.getFileSystem().supportedFileAttributeViews().contains("posix");
    boolean created = false;
    try (SeekableByteChannel channel =
        posix
            ? Files.newByteChannel(
                file,
                options,
                PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(permissions)))
            : Files.newByteChannel(file, options)) {
      created = true;
      ByteBuffer buffer = ByteBuffer.wrap(content);
      while (buffer.hasRemaining()) {
        channel.write(buffer);
      }

How it was checked:

Reproduced: umask 022; dev/run-tests.py -p 1 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest'

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.fallbackReaderDoesNotObserveAnIncompletePrivateKey failed: java.lang.AssertionError: Expecting empty but was: [java.lang.IllegalStateException: Cannot read the RSA private key in .../private_key.der ... (at SecurityConfiguration.readPrivateKey(SecurityConfiguration.java:371))
1 suites, 33 tests, 1 failed

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:315-345

  void fallbackReaderDoesNotObserveAnIncompletePrivateKey() throws Exception {
    Path privateKeyFile = configurationFolder.resolve("private_key.der");
    List<Throwable> readerFailures = new ArrayList<>();
    java.util.concurrent.atomic.AtomicBoolean readerRan =
        new java.util.concurrent.atomic.AtomicBoolean();

    try (MockedStatic<Files> files =
        mockStatic(
            Files.class,
            invocation -> {
              if (invocation.getMethod().getName().equals("createLink")) {
                throw new FileSystemException("hard links are unavailable");
              }
              Object result = invocation.callRealMethod();
              if (invocation.getMethod().getName().equals("newByteChannel")
                  && invocation.getArgument(0).equals(privateKeyFile)
                  && readerRan.compareAndSet(false, true)) {
                // The file now exists at its final path; another server starts here.
                try {
                  new SecurityConfiguration(configurationFolder);
                } catch (Throwable e) {
                  readerFailures.add(e);
                }
              }
              return result;
            })) {
      new SecurityConfiguration(configurationFolder);
    }

    assertThat(readerFailures).isEmpty();
  }

Checked by 2 independent checks: CONFIRMED

References:

Could we describe what a concurrent first start can observe on this fallback?

warning at each start. This still works, but is deprecated; set the key file setting instead. A newly
generated private key is readable by its owner only. Before rolling back to an earlier version, see
(`private_key.der`, `public_key.der`), generating the private key on first start. For CRT keys it derives
the public key and creates the matching `public_key.der`; if it generates a private key, it replaces a stale

@shba24 shba24 Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit, medium probability: A successful start does not guarantee a matching public key on disk

Only the in-memory key is guaranteed to match. An existing compatibility file is preserved, and a failed write can leave the file absent after successful startup.

Details

For example: The reference says startup creates the matching public_key.der. With an existing CRT private key and an unrelated public file, the server derives the right key in memory and leaves the unrelated file untouched. This is one bug class: Docs state that the compatibility public_key.der write, which is best-effort and skips existing files, is guaranteed. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:48 (Says that for CRT keys it 'creates the matching public_key.der', with no mention of best-effort or of an existing file being kept.); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:87 (Says 'the matching public_key.der is created; a stale public key is replaced when a private key is generated'.); server/src/main/java/io/unitycatalog/server/UnityCatalogServer.java:757 (Repeats 'creates the matching public_key.der, replacing a stale compatibility file' as an unconditional statement.); docs/server/auth.md:294.

Qualify the compatibility write as best-effort: 'creates public_key.der when it is missing (best-effort; a failed write only logs a warning). An existing file is left as is unless the server generates a new private key, and the server always uses the public key it derives in memory.' Use the same wording in configuration.md, the SecurityConfiguration class and constructor Javadocs, and the UnityCatalogServer builder Javadoc.

Evidence:

I compared the configuration reference, builder and constructor Javadocs, upgrade guide, and the compatibility write. The reference and Javadocs promise a matching file. The implementation returns immediately for any existing directory entry on a later CRT start and swallows write IOExceptions. The mismatch test expressly keeps the unrelated public key.

docs/server/configuration.md:87-91

        When the key file is not set, the server signs with a key it keeps in `etc/conf`
        (`private_key.der`, `public_key.der`), generating the private key on first start. For CRT keys it derives
        the public key and creates the matching `public_key.der`; if it generates a private key, it replaces a stale
        existing public key. An existing non-CRT private key requires its matching public key. With authorization
        enabled it logs a warning at each start. This still works, but is

server/src/main/java/io/unitycatalog/server/UnityCatalogServer.java:755-760

     * Sets the folder for the {@code token.txt} the server writes when constructed and, unless
     * {@code server.token-signing-private-key-file} is set, the signing keys. The server generates
     * {@code private_key.der} if it is missing; for a CRT private key it derives the public key and
     * creates the matching {@code public_key.der}, replacing a stale compatibility file only when
     * it generates a new private key. An existing non-CRT private key requires its matching public
     * key file. Restore or remove a dangling {@code private_key.der} symlink before starting.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:86-90

  /**
   * Uses the private key in the configuration folder, generating it if missing. For CRT keys, the
   * matching {@code public_key.der} is created; a stale public key is replaced when a private key
   * is generated. A non-CRT private key requires its matching public key file. Restore or remove a
   * dangling {@code private_key.der} symlink before starting.

server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:209-223

    try {
      if (!replaceExisting && Files.exists(file, LinkOption.NOFOLLOW_LINKS)) {
        if (Files.isSymbolicLink(file) && Files.notExists(file)) {
          log.warn("Compatibility public key path {} is a dangling symbolic link", file);
        }
        return;
      }
      installFile(file, publicKey.getEncoded(), "rw-r--r--", replaceExisting);
    } catch (IOException e) {
      log.warn(
          "Could not write compatibility public key file {}. The server will continue using the"
              + " public key derived from the private key.",
          file,
          e);
    }

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:183-196

  void derivesPublicKeyWithoutReplacingExistingCompatibilityFile() throws Exception {
    KeyPair signingKeyPair = newKeyPair();
    KeyPair mismatchedKeyPair = newKeyPair();
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    Files.write(
        configurationFolder.resolve("private_key.der"), signingKeyPair.getPrivate().getEncoded());
    byte[] existingPublicKey = mismatchedKeyPair.getPublic().getEncoded();
    Files.write(publicKeyFile, existingPublicKey);

    SecurityConfiguration configuration = new SecurityConfiguration(configurationFolder);

    assertThat(configuration.rsaPublicKey()).isEqualTo(signingKeyPair.getPublic());
    assertThat(Files.readAllBytes(publicKeyFile)).isEqualTo(existingPublicKey);
  }

How it was checked:

Reproduced: umask 022; dev/run-tests.py -p 1 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest'

head:

[error] Failed: Total 35, Failed 3, Errors 0, Passed 32
SecurityConfigurationTest#documentedCompatibilityFileGuaranteeHoldsAfterSuccessfulStartup(String):1: AssertionFailedError: expected: [48, -126, 1, 34, ...] (SecurityConfigurationTest.java:266) [malformed]
...(String):2: AssertionFailedError: expected: [48, -126, 1, 34, ...] (:266) [unrelated]
...(String):3: AssertionFailedError: Expecting value to be true but was false (:265) [directory, write fails]

server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java:249-269

  @ParameterizedTest
  @ValueSource(strings = {"malformed", "unrelated", "directory"})
  void documentedCompatibilityFileGuaranteeHoldsAfterSuccessfulStartup(String existing)
      throws Exception {
    KeyPair keyPair = newKeyPair();
    Files.write(configurationFolder.resolve("private_key.der"), keyPair.getPrivate().getEncoded());
    Path publicKeyFile = configurationFolder.resolve("public_key.der");
    switch (existing) {
      case "malformed" -> Files.write(publicKeyFile, new byte[] {1, 2, 3});
      case "unrelated" -> Files.write(publicKeyFile, newKeyPair().getPublic().getEncoded());
      default -> Files.createDirectory(publicKeyFile);
    }

    new SecurityConfiguration(configurationFolder);

    // configuration.md: the server "creates the matching public_key.der"
    assertThat(Files.isRegularFile(publicKeyFile)).isTrue();
    assertThat(Files.readAllBytes(publicKeyFile)).isEqualTo(keyPair.getPublic().getEncoded());
  }

  @Test

Checked by 2 independent checks, which split: CONFIRMED, NITPICK

Could we use the same best-effort wording here and in the folder Javadocs?

…ey-from-private-key

Signed-off-by: yajneshx94 <[email protected]>

# Conflicts:
#	server/src/test/java/io/unitycatalog/server/security/SecurityConfigurationTest.java
@yili-db

yili-db commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

/review

@yili-db yili-db left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] Comment. The fail-safe behavior is accepted as is: when hard links are unavailable, the first start fails and no key files are left behind. No fallback is requested here.

Normal:

  • The hard-link requirement and the server.token-signing-private-key-file workaround are not documented yet. Inline comments at SecurityConfiguration.java:83, auth.md:291 and configuration.md:88 ask for a short statement in each.

Still open from the earlier review:

  • The PEM public_key.der and v0.7.0 rollback text (inline, auth.md:308).
  • The CRT rule written in canDerivePublicKey and again in publicKeyOf (inline, SecurityConfiguration.java:164).
  • startsWhenCompatibilityPublicKeyCannotBeUpdated returns early at the directory check and never reaches the replace path (inline, SecurityConfigurationTest.java:266).

Nit:

  • The deleteIfExists in the finally of installFile can replace the original error (inline, SecurityConfiguration.java:252).

The open threads from shba24 on the replaceExisting naming and the configuration.md note on an absent public file still apply and are not repeated here.

/**
* Uses the private key in the configuration folder, generating it if missing. For CRT keys, the
* matching {@code public_key.der} is created; a stale public key is replaced when a private key
* is generated. A non-CRT private key requires its matching public key file. Restore or remove a

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] Suggest stating the hard-link requirement here. The private key is installed with a hard link, so a file system without hard link support fails the first start, and no key files are left behind. Setting server.token-signing-private-key-file to a key the operator provides avoids the folder install, because the server only reads that file.

Comment thread docs/server/auth.md
the setting keeps signing with the key it generated in `etc/conf`, which is deprecated (see
[Configuration](configuration.md#configuration)).

When the server uses the deprecated `etc/conf` key folder, it derives the public key from

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] This paragraph should also say that the folder install needs hard link support. On a file system without it, the first start fails and no key files are left behind. The workaround is to set server.token-signing-private-key-file to a key file the operator provides.

(`private_key.der`, `public_key.der`), generating it on first start; with authorization enabled it logs a
warning at each start. This still works, but is deprecated; set the key file setting instead. A newly
generated private key is readable by its owner only. Before rolling back to an earlier version, see
(`private_key.der`, `public_key.der`), generating the private key on first start. For CRT keys it derives

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] Same point here: generating the folder key needs hard link support. On a file system without it, startup fails and no key files are left behind. Setting server.token-signing-private-key-file avoids the folder key.

Comment thread docs/server/auth.md
formats an earlier version reads:
started on this version, create `etc/conf/key_id.txt` with any value, for example `uc`. Before rolling back, check
that `etc/conf/public_key.der` exists and contains the public key for `etc/conf/private_key.der`; this release
repairs a stale public file when it generates a new private key but leaves existing files untouched on later

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] The text asks operators to check that this file contains the public key, but it does not give the format. An earlier release reads public_key.der as raw X.509 DER (v0.7.0 rsaPublicKey() passes the file bytes to X509EncodedKeySpec), and this release leaves an existing file untouched. A PEM file that is already present therefore fails on rollback. Suggest saying that the file must be DER, with the openssl command for a PEM key.

}
}

private static boolean canDerivePublicKey(RSAPrivateKey privateKey) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] The CRT rule is written here and again in publicKeyOf. A change to one needs the same change in the other. Suggest keeping one check, for example having publicKeyOf be the only place that tests for RSAPrivateCrtKey.

}

@Test
void startsWhenCompatibilityPublicKeyCannotBeUpdated() throws Exception {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] This test puts a directory at public_key.der, so writePublicKeyIfMissing returns at the existence check and never reaches the replace or failure path. Suggest a case where the private key is generated and a non-empty directory sits at public_key.der, so the replace fails, and assert that startup still succeeds.

} catch (FileAlreadyExistsException e) {
return false;
} finally {
Files.deleteIfExists(temporaryFile);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] If deleteIfExists throws after the install has failed, its exception replaces the original one, so the operator sees a cleanup error instead of the reason the install failed. The temp file can also remain, and it holds the private key. Suggest catching the cleanup exception and adding it as suppressed to the primary exception when there is one.

@yili-db

yili-db commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

/review

@yajneshx94

Copy link
Copy Markdown
Author

Thanks @yili-db. I've pushed de03bec addressing the hard-link point: a file system that refuses hard links now fails the first start with a message that names the cause and points to server.token-signing-private-key-file as the workaround, and the
hard-link requirement is documented in the constructor Javadoc, auth.md and configuration.md. I've also updated the escription. I'm leaving the remaining nits (the duplicated CRT check, the directory test, and the cleanup exception masking) as follow-ups.

@yili-db

yili-db commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

/review

@yili-db yili-db left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] Comment. Fresh pass on de03bec. Some issues from our earlier rounds came from our own suggestions, mainly the hard-link approach, and the changes below correct that. The hard-link requirement for the private key stays: a file system without hard links, or a denied hard link, fails startup with the underlying error and leaves no key files behind. The workaround is server.token-signing-private-key-file with an operator-provided key.

Proposed changes:

  • Diagnosis: only a missing link capability gets the hard-link hint. Other FileSystemExceptions keep their own message.
  • The compatibility public_key.der is published without a hard link: a move without REPLACE_EXISTING, where FileAlreadyExistsException counts as success. The private key keeps the hard link.
  • A dangling private_key.der symlink fails startup with a message that names the path and says the target is missing. No key is generated in its place.
  • The CRT rule is written in one place.
  • A failed cleanup of the temporary file is attached to the install error instead of replacing it.
  • Docs: the PEM public_key.der rollback text, and a note that a compatibility file that cannot be written stays absent.

shba24's two threads are answered by these changes. The replaceExisting flag is gone: the private key path only creates, and the public key path has separate replace and create methods. The configuration.md note on an absent public file is now stated in the docs.

Code outside the suggestion blocks, for reference:

// writeOwnerOnly: hint only for a missing link capability
} catch (UnsupportedOperationException e) {
  IOException hinted = hardLinkUnavailable(file, e);
  failure = hinted;
  throw hinted;
} catch (FileSystemException e) {
  IOException translated = isLinkUnsupported(e) ? hardLinkUnavailable(file, e) : e;
  failure = translated;
  throw translated;
}
// initializeIfMissing: a dangling link fails before anything is generated
if (Files.isSymbolicLink(privateKeyFile) && Files.notExists(privateKeyFile)) {
  throw new IllegalStateException(
      "The private key path "
          + privateKeyFile.toAbsolutePath()
          + " is a dangling symbolic link: its target is missing; restore the target or remove"
          + " the link");
}
// The compatibility public key is published without a hard link.
private static void createPublicKey(Path file, RSAPublicKey publicKey) throws IOException {
  Path temporaryFile = createTempFile(file, "rw-r--r--");
  Throwable failure = null;
  try {
    Files.write(temporaryFile, publicKey.getEncoded());
    Files.move(temporaryFile, file);
  } catch (FileAlreadyExistsException e) {
    // Another start published the same key first.
  } catch (IOException | RuntimeException e) {
    failure = e;
    throw e;
  } finally {
    deleteTemporaryFile(temporaryFile, failure);
  }
}
// A failed cleanup is attached to an install error instead of replacing it.
private static void deleteTemporaryFile(Path temporaryFile, Throwable failure)
    throws IOException {
  try {
    Files.deleteIfExists(temporaryFile);
  } catch (IOException cleanup) {
    if (failure == null) {
      throw cleanup;
    }
    failure.addSuppressed(cleanup);
  }
}
// Early-return test: the replace path is now exercised.
@Test
void attemptsToReplaceCompatibilityPublicKeyWhenGeneratingPrivateKey() throws Exception {
  Path publicKeyFile = configurationFolder.resolve("public_key.der");
  Files.createDirectory(publicKeyFile);
  Path occupant = Files.createFile(publicKeyFile.resolve("occupant"));

  try (MockedStatic<Files> files = mockStatic(Files.class, Mockito.CALLS_REAL_METHODS)) {
    SecurityConfiguration configuration = new SecurityConfiguration(configurationFolder);
    assertThat(configuration.rsaPublicKey()).isNotNull();
    files.verify(
        () ->
            Files.move(
                any(Path.class), eq(publicKeyFile), eq(StandardCopyOption.REPLACE_EXISTING)));
  }
  assertThat(publicKeyFile).isDirectory();
  assertThat(occupant).exists();
}

Proposed note for configuration.md, after the paragraph on the derived key:

The compatibility public_key.der is published without a hard link. If it cannot be written, startup continues with a warning and the file stays absent, so create it before rolling back to an earlier version.

Tests: each change above has a test, and each named test fails when its change is reverted. This covers the diagnosis split, the public key without a hard link, the dangling-link failure, the cleanup masking, the early-return replace path, and the denied link. On the proposed change set, the security and auth suites pass (83 of 83).

Differences from main, intended: a dangling private_key.der symlink fails startup, where main replaces it. A denied hard link fails startup with the underlying error, as the fail-safe requires.

Nothing here asks for a hard-link fallback.

existing public key. An existing non-CRT private key requires its matching public key. With authorization
enabled it logs a warning at each start. This still works, but is
deprecated; set the key file setting instead. A newly generated private key is readable by its owner only.
A dangling `private_key.der` symlink must be restored or removed before startup.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted]

Suggested change
A dangling `private_key.der` symlink must be restored or removed before startup.
A dangling `private_key.der` symlink fails startup; the message names the path and the missing target. No key is generated in its place.

* {@code private_key.der} if it is missing; for a CRT private key it derives the public key and
* creates the matching {@code public_key.der}, replacing a stale compatibility file only when
* it generates a new private key. An existing non-CRT private key requires its matching public
* key file. Restore or remove a dangling {@code private_key.der} symlink before starting.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted]

Suggested change
* key file. Restore or remove a dangling {@code private_key.der} symlink before starting.
* key file. A dangling {@code private_key.der} symlink fails startup; no key is generated.

Comment thread docs/server/auth.md
Comment on lines +313 to +315
match. An earlier version reads
`private_key.der` as PKCS #8 DER and `public_key.der` as X.509 SubjectPublicKeyInfo DER. If
`private_key.der` is already in that format, recreate its matching public key before rollback with:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted]

Suggested change
match. An earlier version reads
`private_key.der` as PKCS #8 DER and `public_key.der` as X.509 SubjectPublicKeyInfo DER. If
`private_key.der` is already in that format, recreate its matching public key before rollback with:
match. An earlier version reads `private_key.der` as PKCS #8 DER and `public_key.der` as X.509
SubjectPublicKeyInfo DER, and it does not read PEM. If `public_key.der` is PEM text, convert it in
place with `openssl pkey -pubin -in etc/conf/public_key.der -outform DER -out etc/conf/public_key.der.tmp`
and rename `public_key.der.tmp` over `public_key.der`. If `private_key.der` is already in the DER
format, recreate its matching public key before rollback with:

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Server] Derive the public key from private_key.der on the deprecated key-folder path

4 participants