Skip to content

[Server] Stop writing the admin token to a file - #2082

Open
shba24 wants to merge 2 commits into
unitycatalog:mainfrom
shba24:stack/ep31-admin-token-in-memory
Open

shba24 wants to merge 2 commits into
unitycatalog:mainfrom
shba24:stack/ep31-admin-token-in-memory

Conversation

@shba24

@shba24 shba24 commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

🥞 Stacked PR

Use this link to review incremental changes.


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

This is part 4 of 4 in a stack; each PR handles one kind of secret end to end (server, Helm chart, docs, tests). Review only this PR's changes with its incremental link above.

Description of changes

The server no longer writes an admin token to etc/conf/token.txt. That token never expires, and the server never reads the file; it only handed the token to whoever set up the first users.

  • The server no longer creates that token. At startup it deletes a token.txt it finds in the configuration folder, so no plaintext copy stays on disk. If it cannot (a folder the server's user cannot write to, where an earlier version overwrote the file), it logs a warning naming the file and starts.
  • New bin/uc-admin-token prints an admin token signed with the server's key, for creating the first users and grants. It reads the key the server signs with (the token signing key file setting, or etc/conf), fails if there is none, and writes no files. Like the server, it reads etc/conf in the current directory and the UC_ environment variables, so run it from the directory the server starts in, with the same environment.
  • The docs use bin/uc --auth_token "$(bin/uc-admin-token)" ... in place of $(cat etc/conf/token.txt), and the auth upgrade notes explain the change.

Release note (also in the Upgrading section of docs/server/auth.md): scripts that read etc/conf/token.txt must switch to bin/uc-admin-token. Copies of an old token.txt stay valid until the signing key changes; deleting the file does not revoke them.

📐 Design notes & details

Why a new tool. With authorization on, a user can log in only if UC already knows them, so someone has to create the first users. bin/uc user create needs an admin token for that (--auth_token), and token.txt was the only source. The Helm chart already mints its own token from the key in its create-users job.

Why a separate script, not a bin/uc subcommand. bin/uc is a REST client: at runtime it uses only the generated client (io.unitycatalog.client.*), with no server code, and it usually runs away from the server and its key. The script runs where the key is readable and reuses the server's own code: SecurityConfiguration.loadExisting for the key, and SecurityContext.createServiceToken for the token.

Details.

  • No expiry. The token has no expiry, like the admin token the server used to write. Expiry is separate work.
  • Read-only. The command never generates a key and writes no key or token files.
  • Clean output. Its logs go to etc/logs/cli.log, or nowhere when there is no CLI log config (as in a Helm pod), so standard output holds only the token. A failure (no key, or a key the user cannot read) prints one line to stderr and exits 1.

Tests.

  • UnityCatalogServerTest.startFailsWhenThePortIsTaken: a stale token.txt in the configuration folder is gone once the server is built, and one in a folder the server cannot write to stays without stopping it.
  • Migration tests (TestServer, OldServer): sign an admin token with the server's key instead of reading token.txt; a server from an earlier release still gets the token it writes.
  • SecurityConfigurationTest.loadsAnExistingKeyWithoutGeneratingOne: the command fails without a key and creates nothing; with the generated key it prints exactly one line, an admin token that key verifies. readsTheOperatorsKeyFile also checks that the command reads the key file setting.
  • CliAuthCrudTest: takes the admin token from the test's security context instead of the file.
  • Checked by hand on an earlier revision of this stack that also had a public-key setting:
    • a local server with authorization on deleted a stale token.txt;
    • bin/uc --auth_token "$(bin/uc-admin-token)" user list worked;
    • with no key it exited 1 with "No token signing key file at …" and generated nothing;
    • on kind it worked inside the server pod against the chart's key Secret.

This pull request and its description were written by Isaac.

@shba24

shba24 commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator Author

Local AI review run

The CI /review workflow is skipped for this account, so the repository's reviewer roles were run locally once, on the stack before its final fixes (Claude models; the Codex role was not run):

  • uc-domain-reviewer and maintainer-claude-reviewer (one pass)
  • architecture-reviewer, docs-reviewer and test-coverage-reviewer (one pass)
  • a silent-failure pass

Each finding was checked against the code before acting on it.

Finding Outcome
A line break at the end of a Secret value broke env-sourced secrets (the old envsubst path dropped it) Fixed in #2079: dropped for the upper-case names
bin/uc-admin-token could generate a new key when run from another directory, and rewrote certs.json, which the server re-reads for every internal token check Fixed in #2082: reads the key only, fails if missing, writes no files, runs from the install directory
A stale public_key.der in the key directory could mismatch the signing key Fixed in #2081: the public key is always derived from the private key
token.txt deletion described as making the old token invalid Fixed in #2082: the comment, log and docs say copies stay valid until the key changes
Misleading warning for hibernate.connection.password in server.properties Fixed in #2080
Encryption key: untrimmed inline value, invalid base64 reported as wrong length, key file path missing from errors, name-based bean lookup Fixed in #2083
Weak test assertion on the in-memory token Fixed in #2082: the token is verified against the key
No AAD binding a ciphertext to its row; no bulk re-encryption; generic 500 when a key is missing Kept, documented in #2083
Public HibernateConfigurator(Properties) stores plaintext Kept: callers are tests only
PEM key path has no unit test Kept: the secret scanner blocks PEM headers in test sources; covered end to end with an openssl genrsa key and the chart's generated key on kind

Reviewed heads: 2f4bb5a, 690745f, 8b8356b, c0bc199, d7bf525. Current heads: 81e48b4, eba9f92, 99ae5a0, b91905f, b19e7a5.

@shba24
shba24 force-pushed the stack/ep31-admin-token-in-memory branch from b91905f to ccb9bf1 Compare October 29, 2026 20:40
@shba24

shba24 commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator Author

Local AI review run (round 2)

The CI /review workflow is skipped for this account, so the review pipeline was run locally on the reworked stack (two-file signing key, no key ID, no certs.json, encryption dropped). Each finding was checked against the code before acting on it.

  • Repository reviewer roles (.github/omnigent/reviewer, Claude): uc-domain-reviewer, maintainer-claude-reviewer, architecture-reviewer, test-coverage-reviewer, docs-reviewer. The Codex role was not run.
  • Isaac Review, twice.
  • pr-review-toolkit: code, tests, comments, silent failures, plus a docs-completeness pass for the deprecations.
Finding Outcome
bin/uc auth login read the client secret only from server.properties Fixed in #2079: reads SERVER_CLIENT_SECRET first
aws.sessionToken listed as a secret, but the server never reads it Fixed in #2079: dropped from the secret list and docs
docs/server/aws.md showed aws.s3.* keys the server does not read Fixed in #2079
A DB password in server.properties was ignored silently Fixed in #2080: warns that it is ignored
Password precedence test depended on the shell's environment Fixed in #2080
No test rejects an internal token signed with another key Fixed in #2081 (AuthDecoratorTest); deleting the signature check fails it
Deprecation warning for the generated key fired with authorization off Fixed in #2081: only with authorization enabled
Encrypted or malformed PEM keys gave errors without the file Fixed in #2081
Helm init container continued after an openssl failure Fixed in #2081
Advice to delete key_id.txt broke rollback Fixed in #2081: docs say keep it while a rollback is possible
Unused fields and an uncalled method across commits Fixed in #2081 / #2082
bin/uc-admin-token: wrong-directory key generation, rewrote certs.json, logs on stdout in Helm pods, stale-file failure on a read-only folder Fixed in #2082
Missing tests: ADLS env secret, both key settings, PEM public key, loadExisting, stray files after startup Added to existing tests
No check that the two key files are one pair Kept: operator's responsibility, as in Polaris
No PEM private-key unit test Kept: the pre-commit secret scanner blocks PEM private-key headers; covered end to end
Chart CI never renders the secret env vars (defaults only) Kept: checked on kind with PostgreSQL 18, auth, S3 and create-users
Shared owner for the secret lookup; security → utils dependency Kept for now (refactor, not a defect)

Verification on the current heads:

  • build/sbt clean test is green, and server Javadoc builds.
  • Each lower commit builds and passes its tests on its own.
  • Seven deliberate code breaks were each caught by a test.
  • Helm lints, renders and matches helm-docs at every commit.

Current heads: b2cb578, cf24a2d, 2748528, ccb9bf1.

@shba24

shba24 commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@shba24
shba24 force-pushed the stack/ep31-admin-token-in-memory branch from ccb9bf1 to bb27e14 Compare October 29, 2026 23:26
@shba24
shba24 marked this pull request as ready for review October 29, 2026 23:28
@shba24
shba24 force-pushed the stack/ep31-admin-token-in-memory branch 2 times, most recently from 88c8448 to f9bf141 Compare November 3, 2026 10:17
@shba24 shba24 changed the title [Server] Keep the admin token in memory [Server] Stop writing the admin token to a file Nov 3, 2026
@shba24
shba24 force-pushed the stack/ep31-admin-token-in-memory branch from f9bf141 to 90c184c Compare November 4, 2026 00:58
@shba24
shba24 requested a review from timothyw553 as a code owner November 4, 2026 00:58
@shba24

shba24 commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@shba24 shba24 closed this Nov 5, 2026
@shba24 shba24 reopened this Nov 5, 2026
@shba24 shba24 closed this Nov 5, 2026
@shba24 shba24 reopened this Nov 5, 2026
timothyw553 pushed a commit that referenced this pull request Nov 6, 2026
## 🥞 Stacked PR
Use this
[link](https://github.com/unitycatalog/unitycatalog/pull/2079/files) to
review incremental changes.
-
[**stack/ep31-config-secrets-env**](#2079)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2079/files)]
← _this PR_
-
[stack/ep31-db-password-env](#2080)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2080/files/6af48d7037ce77ff96e920c539c9d770d6ef830a..52be2ac3336ec008692a713804031a9779cac524)]
-
[stack/ep31-signing-key-dir](#2081)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2081/files/52be2ac3336ec008692a713804031a9779cac524..2b96c369d6a90b52461eb617050dd7b35d3b1bb0)]
-
[stack/ep31-admin-token-in-memory](#2082)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2082/files/2b96c369d6a90b52461eb617050dd7b35d3b1bb0..576ec307a689978e488eb7b36ae8c6f01d8fccc8)]

---------

**PR Checklist**

- [x] 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.
- [x] If you've fixed a bug or added code that should be tested, add
tests!
- [x] If you've added or modified a feature, documentation in `docs` is
updated

This is part 1 of 4 in a stack; each PR handles one kind of secret end
to end (server, Helm chart, docs, tests). Review only this PR's changes
with its incremental link above.

**Description of changes**

Operators can now set any server setting, and so every secret, in an
environment variable that a shell or a Kubernetes Secret can supply.
Before, UC looked only for a variable named exactly like the key
(`s3.secretKey.0`), which no shell can export, so secrets lived in
`server.properties` in plaintext, and the Helm chart rendered them
there.

- A setting's variable is `UC_`, then the key in upper case, with `_`
for every character that is not a letter or digit:
`UC_S3_SECRETKEY_<n>`, `UC_S3_SESSIONTOKEN_<n>`,
`UC_ADLS_CLIENTSECRET_<n>`, `UC_AWS_SECRETKEY`,
`UC_SERVER_CLIENT_SECRET`. It takes precedence over `server.properties`.
- At startup the server logs the name of each environment variable it
uses for a setting, never its value.
- Secrets in `server.properties` still work. The server logs a
deprecation warning at startup for each one (key name only), and the
docs mark that way as deprecated. The warning for `server.client-secret`
says that only `bin/uc auth login` reads it and to set
`UC_SERVER_CLIENT_SECRET` in the shell that runs that command; setting
the variable for the server does not silence it.
- The Helm chart passes the S3 and ADLS secrets to the server container
as environment variables from the same Kubernetes Secrets, instead of
rendering them into `server.properties`. Chart values are unchanged. The
OAuth client secret is no longer passed to the server at all: only
`bin/uc auth login` reads it.
- `bin/uc auth login` reads `UC_SERVER_CLIENT_SECRET` before
`etc/conf/server.properties`.
- `docs/server/aws.md` also gets the master user keys right: the server
reads `aws.masterRoleArn` / `aws.accessKey` / `aws.secretKey`, not the
`aws.s3.*` names the page showed.
- Docs that showed secrets in `server.properties` now use the
environment variables and mark the file deprecated: configuration, auth,
AWS, Docker Compose, the Spark and XTable integrations, the
integration-test setup, the sample `server.properties` files, and the
Helm `config.override` / `extraProperties` values.

```sh
export UC_S3_SECRETKEY_0='<secret key>'
bin/start-uc-server
```

<details><summary><b>📐 Design notes &amp; details</b></summary>

**Why this shape.** Apache Polaris reads settings from environment
variables under the property name in upper case (SmallRye config rules),
and its chart passes Kubernetes Secrets in with `secretKeyRef`. This PR
follows the same model. No generic "read any secret from a file" option
is added.

**Why the `UC_` prefix, for every key.** One rule for all keys is easier
to use than a list of secret keys. Without a prefix, variables that
runtimes set for their own use would change UC settings: `aws.region`
would map to `AWS_REGION`, which AWS runtimes set, and `server.env` to
`SERVER_ENV`. With the prefix, only variables meant for UC count.

**Details.**
- Lookup order: system property, then the variable under the exact key,
then the `UC_` name, then `server.properties`.
- An empty `UC_` variable is ignored, like an empty value in
`server.properties`.
- A line break at the end of a `UC_` value is dropped. Before, the
chart's envsubst wrote the value into `server.properties`, and
`Properties.load` ended it at the line break; Secrets made from a file
often end with one.
- The deprecation warning fires only when a secret's value really comes
from the file. A secret also set in the environment does not warn,
except `server.client-secret`: the server never reads it, so a variable
in the server's environment is not a fix.
- Kubernetes service links: the variables Kubernetes adds for each
Service end in `_SERVICE_HOST`, `_SERVICE_PORT` or `_PORT[...]`. The
only key whose `UC_` name has that shape is `server.redirect-port`, and
only for a Service named `uc-server-redirect`; the chart's Services are
named `<fullname>-server` and `<fullname>-ui`. A wrong value there fails
startup validation.
- Helm: a `server.config.override` or `extraProperties` template that
uses the chart's old `${OAUTH_CLIENT_SECRET}`, `${S3_SECRET_KEY_<n>}` or
`${ADLS_CLIENT_SECRET_<n>}` keeps working, for any key (for example
`aws.secretKey=${S3_SECRET_KEY_0}`): when either setting is set, the
init container still gets those variables. That is deprecated, and
`values.yaml` says so. `OAUTH_CLIENT_SECRET` is an optional ref, since
nothing else in the chart reads the client secret; the auth Secret only
needs `clientId`.

**Compatibility.** Users see these in the new Upgrading list under
Secrets in `docs/server/configuration.md`.
- A `UC_` variable already set in the server's environment now takes
precedence over the same key in `server.properties`.
- Secrets in `server.properties` keep working, with a warning.
- Helm with `server.deployment.image.tag` pinned to an older server
image: that image doesn't read these variables, so S3 and ADLS lose
their secrets. The image tag note in `values.yaml` says to use the
server image from the chart's release (the default).
- Helm: the rendered `server.properties` no longer holds these secrets,
and without a custom template the init container no longer has
`OAUTH_CLIENT_SECRET`, `S3_SECRET_KEY_<n>` or `ADLS_CLIENT_SECRET_<n>`.
A container added through `extraInitContainers` or `extraContainers`
that needs them must read them from the Kubernetes Secret itself.

**Tests.**
- `ServerPropertiesTest.testSettingsFromEnvironment`: `UC_` variables
for the client secret, S3 secret key and session token, ADLS client
secret and a non-secret key (`s3.region.0`); a trailing CR/LF is
dropped; an empty `UC_` variable is ignored; `AWS_REGION` does not
change `aws.region`; the exact-name variable wins over the `UC_` one.
-
`CliAuthCrudTest.testAuthLoginReadsTheClientSecretFromTheEnvironmentBeforeTheFile`:
`bin/uc auth login` takes `UC_SERVER_CLIENT_SECRET` over
`server.client-secret`, drops a trailing line break, and falls back to
the file when the variable is absent, empty or only a line break. The
other CLI login tests pass `--identity_token`, so they skip this path.
- `helm/ci/secrets-values.yaml` renders the S3 and ADLS secret variables
in chart lint, plus the deprecated init container variables through
`extraProperties`; `helm template` renders with and without auth, S3 and
ADLS, and with none of them no `env:` block is emitted.
- Checked by hand on a local server: a secret in `server.properties`
logs the warning; with `UC_S3_SECRETKEY_0` set, the log names the
variable and only the remaining file secrets warn; no value appears in
the log.

</details>

This pull request and its description were written by Isaac.

---------

Signed-off-by: Shubham Bansal <[email protected]>
Co-authored-by: Isaac <[email protected]>
yili-db pushed a commit that referenced this pull request Nov 10, 2026
## 🥞 Stacked PR
Use this
[link](https://github.com/unitycatalog/unitycatalog/pull/2080/files) to
review incremental changes.
-
[**stack/ep31-db-password-env**](#2080)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2080/files)]
← _this PR_
-
[stack/ep31-signing-key-dir](#2081)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2081/files/eed6b861dd82b5c368ad6da8ebfbe89621180173..802da6226dc081b8ac47b21f4a5ae9b0ce03a643)]
-
[stack/ep31-admin-token-in-memory](#2082)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2082/files/802da6226dc081b8ac47b21f4a5ae9b0ce03a643..3cfcc332bb89c4ca0c2303acf3b13af2e233b207)]

---------

**PR Checklist**

- [x] 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.
- [x] If you've fixed a bug or added code that should be tested, add
tests!
- [x] If you've added or modified a feature, documentation in `docs` is
updated

This is part 2 of 4 in a stack; each PR handles one kind of secret end
to end (server, Helm chart, docs, tests). Review only this PR's changes
with its incremental link above.

**Description of changes**

The database password can now come from the
`UC_HIBERNATE_CONNECTION_PASSWORD` environment variable. Before, it
could only be written in `etc/conf/hibernate.properties`, and the Helm
chart rendered it there from its Kubernetes Secret.

- The variable takes precedence over `hibernate.properties`, the same
order as for `server.properties`.
- A password in `hibernate.properties` still works. The server logs a
deprecation warning at startup, and the docs mark that way as
deprecated.
- The Helm chart passes the password to the server container as an
environment variable from
`server.db.postgresqlConfig.passwordSecretName`, instead of rendering it
into `hibernate.properties`.
- A `hibernate.connection.password` line in `server.properties`, where
the server never reads it, logs a warning saying it is ignored.
- Docs that showed the password in `hibernate.properties` now use the
variable and mark the file deprecated: configuration, deployment, Docker
Compose, and the Helm `db.overrideConfig` value.

```sh
export UC_HIBERNATE_CONNECTION_PASSWORD=uc_default_password
bin/start-uc-server
```

<details><summary><b>📐 Design notes &amp; details</b></summary>

- The variable name follows the `UC_` rule from the previous PR in this
stack and gets the same handling: an empty variable is ignored, a line
break at the end is dropped, and the startup log names the variable,
never the value.
- Only the password gets the override; the URL, user and driver stay in
`hibernate.properties`.
- The password comes from the environment only, not from a
`-Dhibernate.connection.password` system property. Hibernate copies all
system properties into its own settings, and a password there makes
Hibernate ask the Hikari pool for a connection with a user and password,
which Hikari does not support, so startup fails. That happens before
this PR too.
- A `hibernate.connection.password` line in `server.properties` does not
trigger the `server.properties` deprecation warning, only the "ignored"
one.

**Compatibility.** Users see these in the Upgrading list under Secrets
in `docs/server/configuration.md`.
- A password in `hibernate.properties` keeps working, with a warning.
- Helm with `server.deployment.image.tag` pinned to an older server
image: that image doesn't read the variable, so the PostgreSQL
connection fails. The image tag note in `values.yaml` covers it.
- Helm: the init container no longer receives `DB_PASSWORD`. A
`db.overrideConfig` template with
`hibernate.connection.password=${DB_PASSWORD}` still connects (the line
is left empty and the variable supplies the password); `values.yaml`
says to remove that line. A container added through
`extraInitContainers` that needs the password must read it from the
Kubernetes Secret itself.

**Tests.**
-
`HibernateConfiguratorTest.prefersThePasswordFromTheEnvironmentToTheFile`:
the file value is kept without an override, the override wins, and
`setupHibernateProperties` takes it from `ServerProperties.getEnv`.
- `ServerPropertiesTest.testSettingsFromEnvironment` also covers
`UC_HIBERNATE_CONNECTION_PASSWORD`.
- `helm/ci/secrets-values.yaml` adds a PostgreSQL database with a
password Secret, so chart lint renders the variable.
- Checked by hand against PostgreSQL 18 (Docker), with no password in
`hibernate.properties` (before the variable got its `UC_` prefix): with
no variable set, startup fails ("no password was provided"); with the
variable set, the server serves; with the password only in the file, it
serves and logs the deprecation warning. The password never appears in
the log.

</details>

This pull request and its description were written by Isaac.

---------

Signed-off-by: Shubham Bansal <[email protected]>
Co-authored-by: Isaac <[email protected]>
@shba24
shba24 marked this pull request as draft November 19, 2026 23:24
@shba24

shba24 commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

/review

1 similar comment
@shba24

shba24 commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

/review

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

Looks good

@shba24 shba24 closed this Nov 21, 2026
@shba24 shba24 reopened this Nov 21, 2026
@shba24

shba24 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@shba24
shba24 marked this pull request as ready for review November 23, 2026 21:22
@shba24
shba24 marked this pull request as draft November 23, 2026 22:41
@shba24 shba24 closed this Nov 23, 2026
@shba24 shba24 reopened this Nov 23, 2026
@shba24
shba24 marked this pull request as ready for review November 24, 2026 00:13
@yili-db

yili-db commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

/review

@shba24
shba24 marked this pull request as draft November 24, 2026 02:56

@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] Summary: no blocker. Findings 1 to 4, 6 and 8 are inline.

Wording: the description says "so no plaintext copy stays on disk". The code deletes only the file in the configuration folder, and deletion can fail, so the sentence overstates it. Suggested wording: "so the server does not leave its own copy behind."

Question on the failed-deletion path: When token.txt cannot be deleted at startup, the server logs a warning and keeps starting, so the file and the token in it stay usable. An earlier commit in this PR failed startup instead. Is the warning the intended behavior?

Comment thread docs/server/users-privileges.md Resolved
@shba24

shba24 commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks Yi for the review. Replies to the two points in the summary:

Wording ("so no plaintext copy stays on disk"): the sentence is about the server's own copy, and the next sentence of the description covers the case where deletion fails: "If it cannot (a folder the server's user cannot write to, where an earlier version overwrote the file), it logs a warning naming the file and starts." Read together, they match the code (SecurityContext.deleteServiceTokenFile), so I've left it.

Failed deletion, warning instead of failing startup: yes, that is intended. The earlier commit failed startup, but that broke a setup that works today: with a folder the server's user cannot write to, an earlier version started fine, because it overwrote token.txt in place, while that commit refused to start. A stale admin token is no reason to take a server down on upgrade, so the server logs a warning that names the file and says to delete it, and docs/server/auth.md tells operators to delete it themselves in that case.

The inline points are answered in their threads.

@shba24
shba24 marked this pull request as ready for review November 24, 2026 03:34
yili-db pushed a commit that referenced this pull request Nov 24, 2026
## 🥞 Stacked PR
Use this
[link](https://github.com/unitycatalog/unitycatalog/pull/2081/files) to
review incremental changes.
-
[**stack/ep31-signing-key-dir**](#2081)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2081/files)]
← _this PR_
-
[stack/ep31-admin-token-in-memory](#2082)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2082/files/f68156648362c71f09cf599733b7d32cff1d7031..b079c3cb23822bc4ddcf239578afc58bc927cb2a)]

---------

**PR Checklist**

- [x] 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.
- [x] If you've fixed a bug or added code that should be tested, add
tests!
- [x] If you've added or modified a feature, documentation in `docs` is
updated

This is part 3 of 4 in a stack; each PR handles one kind of secret end
to end (server, Helm chart, docs, tests). Review only this PR's changes
with its incremental link above.

**Description of changes**

Operators can now give the server its token signing key as a file they
choose, for example a read-only mount of a Kubernetes Secret. Before,
the key had to be in `etc/conf`: the server generated it there on first
start, and the Helm chart copied its key Secret into `etc/conf`
(converting PEM to DER) to fit.

- **One setting:** `server.token-signing-private-key-file`, an
unencrypted RSA private key: PKCS #8 in PEM or DER, or PKCS #1 in PEM
(as the chart and some `openssl genrsa` versions write it). Other PEM
blocks in the file, such as a certificate, are skipped. The server only
reads the file and derives the public key from it once, at startup, so
checking a token costs nothing extra. A missing file, an encrypted key
or an unreadable key stops startup with a message naming the file.
- **Without it** the key source does not change: the server uses the key
in `etc/conf` and generates it on first start. That is now deprecated:
with authorization enabled the server logs a warning at each start
(without authorization no request checks the key, but it still signs
`token.txt` at startup), and a newly generated private key is readable
by its owner only (0600).
- **One key, no key ID.** The server checks its own tokens directly with
that key, with RS512 only, so it no longer writes `etc/conf/certs.json`,
and it no longer uses a key ID: new tokens carry none, and checks ignore
one. A token signed with another key is now rejected with 401 "Invalid
access token", instead of a 500 that clients retried.
- **Helm:** the init container points the setting at `private_key.pem`
(or `private_key.der`) in the Secret mount; it no longer copies keys
into `etc/conf` or needs openssl. A key file you set yourself
(`server.config.override` or `extraProperties`) is kept. The Secret no
longer needs `key_id.txt`, and the create-users job no longer sets one.
Generating the key Secret (`server.jwtKeypairSecret.create: true`, the
default) still works for this release, but is deprecated: `values.yaml`,
the install notes and the new "Token signing key" section in the Helm
guide say how to keep the current key or bring your own.
- **Docs:** configuration (the setting and the deprecation), the auth
upgrade and rollback notes, the Helm guide, and the sample
`server.properties`.

```sh
openssl genrsa -out private_key.pem 2048
# server.properties
server.token-signing-private-key-file=/etc/uc/private_key.pem
```

<details><summary><b>📐 Design notes &amp; details</b></summary>

**Why this shape.** This follows Apache Polaris: the operator provides
the key, and the server checks its own tokens against that one key with
no key ID. Polaris's chart never generates keys, and its
production-readiness check flags a generated key. Unlike Polaris, which
takes both key files, UC takes only the private key: the public key is
part of it, so a second setting would only add a way to configure a pair
that doesn't match.

**Why the key ID and `certs.json` could go.**
- **The key ID decided nothing.** The server published one key, so the
key ID only ever picked that key. With the same key the ID matched
anyway; with a different key the signature failed anyway.
- **`certs.json` had no readers.** It was a JWKS copy of the public key
that only the server read back, to reuse the JWKS code it uses for
external identity providers. No endpoint served it.
- **A wrong key ID returned 500.** It surfaced as
`SigningKeyNotFoundException` → `INTERNAL`, which the Java client used
by the Spark and Hadoop connectors retries (5xx, 3 attempts).
- The checker for the server's own tokens and both keys are built once
at startup.

**Compatibility.** Users see these in the Upgrading section of
`docs/server/auth.md`.
- **Existing tokens keep working:** they carry a key ID, which is now
ignored, and are signed by the same key. To keep them when moving to the
setting, point it at `etc/conf/private_key.der` or a copy of it; a new
key makes them fail with 401.
- **Mixed versions during a rolling upgrade work:** a server on the
previous version accepts the new tokens without a key ID, because its
`certs.json` holds one key. I checked jwks-rsa 0.24.1 `UrlJwkProvider`:
no kid with one key returns that key, and a wrong kid throws
`SigningKeyNotFoundException`.
- **Internal tokens signed with RS256 or RS384** were accepted before
(the algorithm came from the token header) and now get 401. The server
itself only ever signed with RS512.
- **Rollback:** an existing `key_id.txt` and `certs.json` are left in
place, which a previous version needs. The docs say to keep them while a
rollback is possible, and how to write the operator's key to `etc/conf`
in the formats an earlier version reads.
- **Rollback after a fresh install on this version:** there is no
`key_id.txt`, so an earlier server generates a new key (tokens must be
reissued), and an earlier chart stops without one in the Secret. The
docs say to add a `key_id.txt` with any value first.
- **Helm upgrade:** the generated Secret is kept on upgrade
(`resource-policy: keep`), so its key and its old `key_id.txt` stay.
- **Helm with a pinned older server image:** that image ignores the
setting and generates its own key in each pod, so tokens from other pods
and the create-users job are rejected. The image tag note in
`values.yaml` says to use the image from the chart's release.
- **Helm Secret with both `private_key.pem` and `private_key.der`:** the
chart now uses the PEM one (before: the DER one).
- **Helm with a key file set through `server.config.override` or
`extraProperties`:** it must point at the key in the Secret. The
create-users job signs with that key and retries without a limit, so
with another key the install waits until Helm's timeout.

**Not done (on purpose).**
- **Key rotation** is separate work.
- **No `defaultMode` on the Secret volume.** The private key mount keeps
today's mode.

**Tests.**
- **`SecurityConfigurationTest`:**
- `readsTheOperatorsKeyFile`, one row per format (PKCS #8 DER, PKCS #8
PEM, PKCS #1 PEM, a certificate followed by a PEM key): reads the
private key, derives the matching public key, and writes nothing to the
configuration folder. The PEM headers are built at runtime so the secret
scanner doesn't flag the test source;
  - `rejectsAnEncryptedPrivateKey`;
- `createsAGeneratedPrivateKeyReadableByItsOwnerOnly`: a blank setting
falls back to `etc/conf`, the generated key is `rw-------`, no
`key_id.txt` is written, and a later start reuses the key.
- **`AuthDecoratorTest.tokenSignedWithAnotherKeyIsRejected`:** with a
key ID the server never had, which gave 500 before.
-
**`UnityCatalogServerTest.startupUsesTheTokenSigningKeyFileSettings`:**
startup uses the setting, fails on a missing file, and creates a
configuration folder that does not exist yet.
- **Old tokens:** the access-control suites mint their tokens with a key
ID, so tokens like those from earlier versions are checked through the
real server.
- **`helm template` / chart lint:** a key file set through
`extraProperties` is kept; a blank one gets the chart's key. The CI
render step checks that the init container appends the setting and that
the server container mounts the key Secret: the CI installs run with
authorization off, where a server given no key file falls back to a
generated key. The init container's check was run against each form
(`=`, `:`, a space, blank, commented out) under `sh` and BusyBox `grep`.
- **Checked by hand** on an earlier revision of this PR that also had a
public-key setting: a local server with an `openssl genrsa` PKCS #1 PEM
key (valid token 200, broken signature 401, no token 401; an encrypted
key stops startup), and a fresh install on kind with PostgreSQL 18, auth
and a create-users user.

</details>

This pull request and its description were written by Isaac.

---------

Signed-off-by: Shubham Bansal <[email protected]>
Co-authored-by: Isaac <[email protected]>
@shba24
shba24 marked this pull request as draft November 24, 2026 06:30
@shba24
shba24 marked this pull request as ready for review November 24, 2026 06:37

@shba24 shba24 left a comment •

Copy link
Copy Markdown
Collaborator Author

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

examples/cli/src/main/java/io/unitycatalog/cli/AuthCli.java:57

Nit (not a blocker): The CLI already performs part of login outside the generated client

bin/uc auth login reads etc/conf/server.properties and uses HttpURLConnection for part of the OAuth flow. The separate launcher's rationale still holds because the CLI does not depend on the server signing implementation at runtime.

For example: The description attributes all client behavior to the generated client, while Oauth2CliExchange.authenticate() posts directly to the identity provider.

The separate launcher can load the server's signing code where the private key is readable, without adding that runtime dependency to bin/uc.
Evidence

AuthCli.login invokes Oauth2CliExchange.authenticate before calling its exchange helper. That implementation reads local properties and sends the identity-provider request directly through HttpURLConnection. The build separately scopes its server dependency to tests.

How it was checked

Checked by 1 independent check: CONFIRMED

Could the rationale name the production dependency that the separate launcher avoids?

.gitignore:31

Nit (not a blocker): Building from a configured checkout can distribute its signing key

The new ignore rule keeps PEM files out of Git. Docker and the tarball builder copy etc/ directly from disk, so the resulting artifact can contain the deployment's private signing key.

For example: An operator keeps etc/conf/private_key.pem in a checkout and builds a release from it. Both packaging paths copy that file alongside the configuration shipped to recipients.

In a separate PR, exclude operator signing material (etc/conf/*.pem, *.der) from both distribution builds, or stage only the shipped configuration files explicitly, which also covers custom key filenames.

Evidence

The change recognizes etc/conf/*.pem as local signing material. The Dockerfile copies etc/ into the runtime image, and Tarball.scala copies the same directory into the release tree. I checked .dockerignore and the tarball cleanup for exclusions. Neither excludes the new PEM input, so a build from a configured checkout distributes it.

How it was checked

Reproduced: openssl genrsa -out etc/conf/private_key.pem 2048; build/sbt -batch createTarball; tar tzf target/unitycatalog-0.8.0-SNAPSHOT.tar.gz | grep private_key

head:

./etc/conf/private_key.pem  (listed in the tarball; git check-ignore: .gitignore:31:etc/conf/*.pem matches it)

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

References:

Could both packagers exclude local signing material before copying the configuration directory?

docs/server/helm.md:155

Nit (not a blocker): The signing-key example fails on a fresh cluster

The install guide normally lets helm install --create-namespace create the namespace. An operator supplying a signing key must create the Secret before that install.

For example: The new-install example runs kubectl create secret ... --namespace unitycatalog first. On a fresh cluster, the target namespace does not exist yet.

For a new install, first create the release namespace with `kubectl create namespace unitycatalog` if it does not already exist. Then create the signing-key Secret in that namespace.
Evidence

The guide creates the namespace during helm install, but the operator-managed-key path requires creating the Secret there before install. I checked the prerequisites, install command, and new token-signing section for an earlier namespace-creation step.

How it was checked

Checked by 1 independent check: CONTESTED

References:

Could the example create the namespace first when it does not exist?

// does not stop startup.
private void deleteServiceTokenFile() {
try {
if (Files.deleteIfExists(serviceTokenFile)) {

@shba24 shba24 Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Blocker: Startup can delete the configured signing key

Startup reads the configured key before cleaning up the old token path. When those paths coincide, cleanup deletes the operator's signing key while the running process still has a copy in memory. This is one bug class: Startup deletes a fixed path without checking it against the operator-configured key file. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:170 (The generated-key path deletes private_key.der and rewrites it whenever public_key.der is missing. auth.md tells operators to point the setting at etc/conf/priv).

For example: An operator sets server.token-signing-private-key-file=etc/conf/token.txt and starts the server. The first start succeeds, but bin/uc-admin-token and the next start report a missing key.

Check the effective signing-key path against the cleanup target before deletion. Reject a collision with a clear configuration error and preserve the file.

Evidence

this comment: fromSettings accepts an arbitrary nonblank path. UnityCatalogServer loads it before constructing SecurityContext, which resolves token.txt independently and deletes it without a path-identity check. I checked property validation, both constructors, and cleanup. With a valid key at that path, context construction removed the file and the next load reported it missing.

a related comment: The configuration reference promises read-only treatment of the operator's key. I checked the property loader, server constructor, and cleanup method. The loader accepts this path, then the constructor deletes it by name without checking whether it is the active key.

How it was checked

Reproduced: build/sbt -batch 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest'

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.keepsAKeyFileNamedTokenTxtInTheConfigurationFolder failed: java.lang.AssertionError: Expecting path: /tmp/junit-11527497622720907414/token.txt to exist (symbolic links were followed). Test run finished: 1 failed, 0 ignored, 8 total. Failed: Total 8, Failed 1, Errors 0, Passed 7

Checked by 2 independent checks: CONFIRMED

Could startup detect that both paths refer to the same file before running cleanup?

}
try {
run(
new ServerProperties(UnityCatalogServer.SERVER_PROPERTIES_FILE),

@shba24 shba24 Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Blocker: The command can print a token the running server rejects

ServerProperties logs a file-read failure and returns. The command then interprets the missing setting as permission to use the legacy key, so success can return an unusable admin token. This is one bug class: An unreadable server.properties is logged and treated as absent, so callers fall back to defaults. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:87 (At server startup, the same swallowed read makes load generate or reuse the deprecated etc/conf key instead of the operator's key, so tokens from the other repl); server/src/main/java/io/unitycatalog/server/utils/ServerProperties.java:513 (The root cause, on the same read: every setting falls back to its default, including server.authorization, so the server starts with authorization disabled (fai).

For example: A deployment switches to an operator key and leaves etc/conf/private_key.der in place. If server.properties becomes unreadable after startup, bin/uc-admin-token signs with that old key and exits successfully.

Give the command a configuration-loading path that propagates read errors. Use the legacy key only after establishing that the setting is genuinely absent.

Evidence

The new command constructs ServerProperties inside its error handler, but that implementation catches and logs file-read IOExceptions itself. With no signing-key environment override, loadExisting then selects private_key.der. I confirmed that a server.properties path that exists but cannot be read as a file proceeds to the legacy key. The caller loses the distinction between an absent setting and an unread setting.

How it was checked

Reproduced: build/sbt -batch javafmtAll 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest'

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.adminTokenCommandFailsWhenServerPropertiesCannotBeRead failed: java.lang.AssertionError: 
[error] Expecting code to raise a throwable., took 5.241s
[error] Failed: Total 8, Failed 1, Errors 0, Passed 7

Checked by 2 independent checks: CONFIRMED

Could the command propagate a failure to read an existing properties file?

}
Path conf = Path.of("etc", "conf");
String token =
new SecurityContext(conf, new SecurityConfiguration(conf), "server", INTERNAL)

@shba24 shba24 Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Nit (not a blocker): Migration requests fail with a configured signing key

The server reads the key setting through ServerProperties. The migration client bypasses those settings and can even generate a separate key pair, making an authentication mismatch look like an upgrade failure.

For example: A developer sets UC_SERVER_TOKEN_SIGNING_PRIVATE_KEY_FILE and runs an upgrade test. TestServer.start honors it, but apiClient() uses etc/conf, so the first authenticated request returns 401.

If addressed, have the migration fixtures, and ideally the shared auth test bases, reuse the started server's effective signer instead of building SecurityConfiguration(Path.of("etc","conf")). Otherwise leave as is.

Evidence

this comment: TestServer.start passes environment-aware ServerProperties into the real server. TestServer.apiClient constructs a new SecurityConfiguration directly from etc/conf, bypassing the configured key. OldServer’s no-token fallback does the same. I checked process startup, both fixture constructors, and the request verifier. A signature failure maps to UNAUTHENTICATED, HTTP 401.

a related comment: TestServer builds its server with environment-aware ServerProperties, then apiClient bypasses those properties and directly constructs the generated-key configuration. OldServer uses the same fallback when token.txt is absent. RealUpgradeTest makes authenticated catalog calls with this client.

How it was checked

Reproduced: UC_TEST_DATABASE=<H2|POSTGRES_18|MYSQL_8> dev/run-tests.py "server/testOnly io.unitycatalog.server.migrate.RealUpgradeTest"

head:

1 suites, 4 tests, 1 failed. Failed tests: io.unitycatalog.server.migrate.RealUpgradeTest#configuredSigningKeyAuthenticatesMigrationClient(Path, Path): io.unitycatalog.client.ApiException: listCatalogs call failed with: 401 - {"error_code":"UNAUTHENTICATED",...,"message":"Invalid access token."} (RealUpgradeTest.java:165). Same on POSTGRES_18 and MYSQL_8 (1 failed each).

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

Could the migration fixtures obtain their token from the same effective key configuration as the server they started?


private AdminTokenCommand() {}

public static void main(String[] args) throws Exception {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Nit (not a blocker): bin/uc-admin-token brings a second launcher and command pattern next to --upgrade-schema

The server already runs one-shot commands through UnityCatalogServer.main: OptionParser has a schema-command group, and SchemaMigrator.runCommand(boolean, Path, PrintStream) returns the exit code.

AdminTokenCommand adds a separate main with its own log setup, exit handling and etc/conf literal. bin/uc-admin-token adds its own classpath lookup, and that lookup already differs from bin/start-uc-server: it uses a fixed jars/classpath instead of find, and it does not build a missing jar.

Cost of keeping it: Once this ships, bin/uc-admin-token is a documented CLI name that is hard to take back. The next server-side command then has two patterns to copy, and any change to how the launcher finds the jars has to be made in both scripts.

Add an option such as --print-admin-token to the schema-command group in OptionParser. Give AdminTokenCommand.run the shape of SchemaMigrator.runCommand (it returns an exit code and prints to the streams it is given) and call it from UnityCatalogServer.main. If you want to keep the bin/uc-admin-token name, make it a one-line exec "$SCRIPT_DIR/start-uc-server" --print-admin-token wrapper.

Evidence

AdminTokenCommand.main builds its own log setup, a fixed etc/conf path and System.exit, and bin/uc-admin-token resolves the classpath itself. Meanwhile UnityCatalogServer.main already sends one-shot commands through OptionParser and SchemaMigrator.runCommand, which returns an exit code, and bin/start-uc-server holds the existing classpath lookup (find under jars, build when a jar is missing). So the same concept now has two shapes. I looked for a shared launcher helper or a server option for the token and found none.

How it was checked

Checked by 1 independent check: NITPICK

Was a bin/start-uc-server option considered? The description covers why this is not a bin/uc subcommand, but not this alternative.

// output holds only the token.
Path logConfig = Path.of("etc", "conf", "cli.log4j2.properties");
if (Files.exists(logConfig)) {
Configurator.initialize(null, logConfig.toString());

@shba24 shba24 Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

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 failed token command can still create the CLI log

AdminTokenCommand initializes the CLI file appender before reading the signing key. The narrower guarantee already appears in the class documentation.

For example: The description says there are no file writes. With the default CLI configuration, a missing key exits with 1 after creating etc/logs/cli.log.

Suggested change
Configurator.initialize(null, logConfig.toString());
The command reads the existing signing key and writes no key or token files.
Evidence

AdminTokenCommand initializes the checked-in CLI File appender before attempting to load the key. I compiled the changed command and security classes and confirmed that an invocation with a missing key created etc/logs/cli.log. The command's own Javadoc already states the narrower guarantee.

How it was checked

Reproduced: build/sbt -batch javafmtAll 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest'

head:

Expecting actual: ["etc/logs/cli.log", "etc/conf/cli.log4j2.properties"] to contain exactly (and in same order): ["etc/conf/cli.log4j2.properties"] but some elements were not expected: ["etc/logs/cli.log"] at SecurityConfigurationTest.commandCreatesNoFilesOnMissingKey(SecurityConfigurationTest.java:132)  (Failed: Total 8, Failed 1)

Checked by 1 independent check: CONFIRMED

References:

Could the description use the same file guarantee as the command's Javadoc?

} catch (Exception e) {
// One line, not a stack trace: a missing key, or one this user cannot read.
System.err.println(
"uc-admin-token: " + (e instanceof IllegalStateException ? e.getMessage() : e));

@shba24 shba24 Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

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 missing-key error can span multiple lines

The missing-key exception includes the configured pathname. A single println preserves any line breaks already present in that message. This is one bug class: The one-line error output embeds unescaped pathnames and exception text. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:132 (requireFile's message includes the configured path, so a newline in the path splits the diagnostic.).

For example: With an embedded newline between absent and key.pem in UC_SERVER_TOKEN_SIGNING_PRIVATE_KEY_FILE, the command exits with 1 and writes two stderr lines.

String detail = e instanceof IllegalStateException ? e.getMessage() : e.toString();
System.err.println("uc-admin-token: " + detail.replace("\r", "\\r").replace("\n", "\\n"));
Evidence

The missing-key exception includes the pathname verbatim, and the handler prints the message verbatim. With an embedded newline in the configured pathname, the compiled command returned exit 1 and wrote two stderr lines.

How it was checked

Reproduced: build/sbt -batch 'server/testOnly io.unitycatalog.server.security.SecurityConfigurationTest'

head:

[error] Test ...SecurityConfigurationTest.mainFailureWithNewlinePathHasOneDiagnosticLine failed: java.lang.AssertionError: Expected size: 1 but was: 2 in: ["uc-admin-token: No token signing key file at /no/such", "key"]

Checked by 1 independent check: CONFIRMED

Could the command escape embedded line breaks when rendering its diagnostic?

+ " changes.",
serviceTokenFile);
}
} catch (IOException e) {

Copy link
Copy Markdown
Collaborator Author

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 token.txt the server cannot delete could stay on disk with no warning, and no test would notice

When the stale token.txt cannot be deleted, the LOGGER.warn in the catch (IOException e) branch is the only thing that tells an operator a non-expiring admin token is still on disk.

startFailsWhenThePortIsTaken checks the file and that build() succeeds, but neither warning. This is one bug class: The new operator-facing warnings and their conditions are never asserted. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityContext.java:82 (Removing the 'Deleted ...' WARN passes every test.); server/src/main/java/io/unitycatalog/server/security/SecurityContext.java:89 (Removing or silencing the cannot-delete WARN, the only signal that a non-expiring token is still on disk, passes every test.); server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:94 (Inverting or removing the isAuthorizationEnabled condition, or deleting the deprecation WARN, passes every test.).

For example: Removing either LOGGER.warn call in deleteServiceTokenFile (or the catch body) leaves the test green. The operator then gets no hint that a never-expiring admin token is still readable in the configuration folder.

CapturingAppender appender = new CapturingAppender();
Logger logger = (Logger) LogManager.getLogger(SecurityContext.class);
logger.addAppender(appender);
try {
  // existing builds
  assertThat(appender.messages()).anyMatch(m -> m.startsWith("Deleted ") && m.contains("token.txt"));
  // after the unwritable-folder build
  assertThat(appender.messages()).anyMatch(m -> m.startsWith("Cannot delete ") && m.contains("token.txt"));
} finally {
  logger.removeAppender(appender);
}
Evidence

Both LOGGER.warn calls in deleteServiceTokenFile are unasserted. The test checks only file existence and that build() succeeds. ServerPropertiesTest already captures warnings with a CapturingAppender, so the repo has a pattern for asserting logs.

How it was checked

Checked by 1 independent check: CONFIRMED

How about reusing the log-capture approach from ServerPropertiesTest here, so the warning is part of what the test pins?

@shba24 shba24 left a comment •

Copy link
Copy Markdown
Collaborator Author

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

Blocker: An interrupted first start can prevent every subsequent restart

The final private-key filename becomes visible before it contains the key. Recovery checks only whether both names exist, so an interrupted write is treated as completed initialization. This is one bug class: Key generation decides it is done from whether the files exist, but publishes the private-key filename before its bytes are complete. The same issue appears in server/src/main/java/io/unitycatalog/server/security/SecurityConfiguration.java:175 (On a file system without POSIX views, Files.write creates and fills the file in one non-atomic call. A short write leaves a truncated private_key.der that passe).

For example: The first start writes public_key.der and creates private_key.der, then the process stops before writing its bytes. Every later start tries to parse the empty file.

Write the complete private key to an owner-only temporary file in the same directory, publish it atomically, and clean up the temporary file on failure.

Evidence

On a POSIX filesystem, the public key is written first, then the final private filename is created, then its bytes are written. The retry predicate in initializeIfMissing checks only whether the files exist. I checked the constructor and decoder for recovery and confirmed that a valid public file plus an empty private file fails the next construction.

How it was checked

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

head:

[error] Test io.unitycatalog.server.security.SecurityConfigurationTest.recoversFromAnInterruptedPrivateKeyWrite failed: java.lang.IllegalStateException: Cannot read the RSA private key in /tmp/junit-.../private_key.der; expected a PEM key, or a PKCS #8 DER one
[error] Caused by: java.security.InvalidKeyException: Missing key encoding
[error] Failed: Total 8, Failed 1, Errors 0, Passed 7

Checked by 2 independent checks: CONFIRMED

Could the generator publish the private filename only after the complete key has been written?

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

Nit (not a blocker): The server and bin/uc-admin-token can use different public keys for the same etc/conf

fromPrivateKeyFile derives the public key from the private key, and loadExisting uses it for etc/conf/private_key.der. The server's generated-key path (new SecurityConfiguration(folder)) reads public_key.der instead.

So two code paths get one fact from two places. readPublicKey, and the PUBLIC KEY PEM handling in readKeyFile, exist only for a file the server writes itself in DER.

Cost of keeping it: As it stands, any later key format has to be added to both read paths. If public_key.der and private_key.der ever stop matching, the server rejects its own tokens while the command's derived key still matches the private key.

public SecurityConfiguration(Path configurationFolder) {
  Path privateKeyFile = configurationFolder.resolve("private_key.der");
  initializeIfMissing(privateKeyFile, configurationFolder.resolve("public_key.der"));
  this(fromPrivateKeyFile(privateKeyFile)); // or a static generated(Path) factory
}
Evidence

The constructor reads public_key.der with readPublicKey, while fromPrivateKeyFile derives the public key with publicKeyOf. loadExisting runs fromPrivateKeyFile on the same private_key.der that load reads through the constructor, so the server and the command get the public key from different sources. readPublicKey is the only caller of readKeyFile with "PUBLIC KEY".

How it was checked

Checked by 1 independent check: NITPICK

Could the generated-key path derive the public key too, keeping public_key.der only as a file written for rollback?

docs/server/auth.md:300

Blocker: Existing internal tokens can stop working after this upgrade

The diff includes the signing-key changes as well as the admin-token command. The auth upgrade notes cover the narrower verifier, discontinued files, and Helm rollback requirements, but the PR description omits them.

For example: The description focuses on replacing token.txt. In the supplied range, an internal RS256 token signed with the same key is no longer accepted, and the chart now reads its signing key from the Secret mount.

This diff also includes the prerequisite signing-key change. Internal tokens now require RS512, new servers stop writing key_id.txt and certs.json, and Helm reads the mounted private key directly. See the auth upgrade notes before rollout or rollback.
Evidence

I compared the full restated description with the auth upgrade notes, configuration reference, JwksOperations, SecurityContext, Helm values, and deployment and Secret templates. The supplied range includes the signing-key change introduced by 35945bb. The description mentions reading the setting but omits the narrower accepted algorithms, discontinued key artifacts, and chart migration.

How it was checked

Checked by 2 independent checks: CONTESTED

Could the description identify the signing-key changes included from the prerequisite commit?

docs/server/auth.md:322

Nit (not a blocker): An alternate key does not always cause a Helm timeout

The retry loop belongs to the optional create-users Job. Its template requires both authentication and at least one configured user. This is one bug class: The Helm key-mismatch warning omits the condition under which the create-users Job exists. The same issue appears in docs/server/auth.md:321 (The doc says that with another key, 'the install or upgrade waits until Helm's timeout', but with auth.users empty there is no Job and nothing waits.).

For example: The upgrade notes predict a timeout with another key. With auth.enabled: true and no auth.users, the chart renders no create-users Job.

When auth.enabled is true and auth.users is nonempty, a signing-key override must use the same key as the Secret. Otherwise the create-users Job keeps retrying until Helm times out.
Evidence

The guide predicts a create-users retry and Helm timeout unconditionally. The template gates the entire Job on authentication and a nonempty user list. I rendered the chart with authentication enabled and no users and confirmed the Job was absent.

How it was checked

Reproduced: helm template uc helm --set auth.enabled=true --set 'server.config.override=server.authorization.token-signing-key-file=/x/other.pem' | grep -c create-users; helm template uc helm --set auth.enabled=true --set 'auth.users[0][email protected]' | grep -c create-users

head:

0 (auth.enabled=true, alternate key file, no auth.users: no create-users Job rendered)

with the fix:

3 (with auth.users set, the create-users Job is rendered)

Checked by 1 independent check: CONFIRMED

Could the warning name the two values that enable the Job?

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

Nit (not a blocker): The deprecated-key warning could disappear or show with authorization off, and no test would notice

SecurityConfiguration.load warns that the generated key is deprecated only when authorization is enabled and no key file is set.

No test asserts the warning or the disabled case.

For example: Changing if (serverProperties.isAuthorizationEnabled()) to if (!serverProperties.isAuthorizationEnabled()), or deleting the log.warn, keeps every test green. Operators on the deprecated path then get no notice, or get it only when it does not matter.

@ParameterizedTest
@ValueSource(booleans = {true, false})
void warnsAboutTheGeneratedKeyOnlyWithAuthorization(boolean authorization) {
  Properties properties = new Properties();
  properties.setProperty("server.authorization", authorization ? "enable" : "disable");
  // capture the SecurityConfiguration logger as ServerPropertiesTest does
  SecurityConfiguration.load(new ServerProperties(properties), configurationFolder);
  assertThat(warnings).hasSize(authorization ? 1 : 0);
}
Evidence

The isAuthorizationEnabled() guard and the log.warn are never asserted. SecurityConfigurationTest and UnityCatalogServerTest check only the returned keys and the missing-file error.

How it was checked

Checked by 1 independent check: CONFIRMED

Would a two-row test over server.authorization like this fit in SecurityConfigurationTest?

@shba24
shba24 force-pushed the stack/ep31-admin-token-in-memory branch from f73b5d7 to 3bf4124 Compare November 30, 2026 22:24
@yili-db

yili-db commented Dec 1, 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] Re-review at 3bf4124. Verdict: changes needed for one item; the rest are tests and wording.

Blocker: when the configured key file is token.txt in the configuration folder, startup deletes it after loading it. The running server keeps working, but the next start fails with "No token signing key file", and every token signed with that key stops working. Reproduced with a local test on this head (not in the repo); see the inline comment on SecurityContext.java.

Other inline items: AdminTokenCommand.java (the CLI log file is created by a failed run, and main is untested), and UnityCatalogServerTest.java (the key-wiring check was removed).

Stale references (outside the diff, so listed here):

  • server/src/test/java/io/unitycatalog/server/migrate/TestServer.java:43: the Javadoc says the folder holds token.txt.
  • server/src/test/java/io/unitycatalog/server/migrate/SchemaGateTest.java:33: the comment mentions token.txt.
  • AGENTS.md:218: says a server writes token.txt.
  • project/scripts/check_etc_conf.sh:4: the comment says the server writes token.txt.

Question (behavior on main, not changed by this PR): when server.properties cannot be read, ServerProperties logs the error and continues with defaults, so the server and bin/uc-admin-token fall back to the key in etc/conf. Should an unreadable settings file fail startup instead?

// output holds only the token.
Path logConfig = Path.of("etc", "conf", "cli.log4j2.properties");
if (Files.exists(logConfig)) {
Configurator.initialize(null, logConfig.toString());

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 the default CLI log configuration, a failed run creates etc/logs/cli.log before the key check, so the command does write a file. Either say so in the description, or initialize logging only after the key is read.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed, and thanks for the catch. The command initializes logging before it reads the key, so a failed run can create the CLI log file. The Javadoc already limits the claim to key and token files, but the PR description says the command writes no files, which is too broad. I kept the code as it is. The description should say that the command writes no key or token files and may create the CLI log file.


@Test
public void startupUsesTheTokenSigningKeyFileSettings() throws Exception {
public void startupUsesTheTokenSigningKeyFileSettings() {

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 used to verify a token against the configured key. That check is gone, so nothing ties the server's security context to the key file setting. Restore it: verify a token from the open server's security context with the configured key.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thank you, you were right that nothing tied the server's security context to the key file setting any more. I restored the check in abfab6a. As you chose, I added a package-visible securityContext() accessor on UnityCatalogServer. The startup test now verifies a token from the server's security context against the key loaded from the configured setting. To check that the test can fail, I made the server ignore the setting, and the test then failed. With the real code it passes, together with the rest of UnityCatalogServerTest and SecurityConfigurationTest, on H2.


private AdminTokenCommand() {}

public static void main(String[] args) 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] bin/uc-admin-token is tested only through run(...). Please cover the output of main with a process test: stdout holds only the token, and a failure prints one stderr line and exits 1.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thank you for the suggestion. I'm keeping the code as it is. run(...) holds the logic and is tested in SecurityConfigurationTest, and main is three lines of wiring around it. Asserting stdout, stderr and the exit code needs a child JVM with the test classpath, which is new test infrastructure for three lines. I checked that output by hand.

The server no longer writes an admin token to etc/conf/token.txt and deletes a
leftover one at startup, warning when it cannot. bin/uc-admin-token prints an
admin token signed with the server's key instead; docs and tests use it.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
@shba24
shba24 force-pushed the stack/ep31-admin-token-in-memory branch from 3bf4124 to 091138b Compare December 1, 2026 19:08
…wiring

Startup deleted the stale admin token file even when the configured signing key
file is that same file. It now keeps it with a warning. The startup test also
verifies a token from the server's security context against the configured key.

Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]>
@shba24
shba24 marked this pull request as draft December 1, 2026 23:14
@shba24
shba24 marked this pull request as ready for review December 2, 2026 00:21
@shba24

shba24 commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

Replying to @yili-db on this review body:

[AI Assisted] Re-review at 3bf4124. Verdict: changes needed for one item; the rest are tests and wording.

Blocker: when the configured key file is token.txt in the configuration folder, startup deletes it after loading it. The running server keeps working, but the next start fails with "No token

Thank you for the careful read. On the stale token.txt mentions in TestServer.java, SchemaGateTest.java, AGENTS.md and check_etc_conf.sh: they are comments and docs only, and I left them for this round; behavior is not affected. On your question about an unreadable server.properties: it would probably be better if that stopped startup, but the catch-and-continue in ServerProperties.readPropertiesFromFile is unchanged from main (lines 502-517 at 7a3c269 and at the head), and AdminTokenCommand builds the same ServerProperties as the server. So both fall back to the etc/conf key together. They disagree only if the file is readable by one process user and not the other. Then the command prints a token the server rejects with 401, which fails closed. Changing startup for every deployment belongs in its own PR. It is not filed yet; the change would make an unreadable file throw an IllegalStateException that names the file.

@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] Approving at abfab6a. The blocker is fixed: a signing key file named token.txt is kept at startup, and the revert check fails startupKeepsASigningKeyFileNamedTokenTxt when the guard is removed. The key-wiring check is restored. No code path writes the admin token file any more, and the migration note is in docs/server/auth.md (Upgrading). Validation: 63 server tests and 6 CLI auth tests pass.

Non-blocking follow-ups:

  • loadExisting (inline): a folder with only private_key.der lets the command print a token that stops verifying after the server's next start.
  • The PR text still says the command "writes no files" and "no plaintext copy stays on disk". Both should mention the CLI log file that a failed run can create, as agreed in the thread.
  • Stale token.txt references outside this diff, as a follow-up: server/src/test/java/io/unitycatalog/server/migrate/TestServer.java:43, server/src/test/java/io/unitycatalog/server/migrate/SchemaGateTest.java:33, AGENTS.md:218, project/scripts/check_etc_conf.sh:4.

}

/** Like {@link #load}, but never generates a key: a missing key is an error. */
static SecurityConfiguration loadExisting(

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] loadExisting requires only private_key.der in the configuration folder, so a folder with only that file lets bin/uc-admin-token print a token. Once the server starts, its constructor regenerates both key files, and the printed token stops verifying. Scratch test on this head: the command printed a token, and it did not verify after the constructor ran (tokenVerifiesAfterRestart=false). Suggested change: require public_key.der in the folder branch too, and add a case to loadsAnExistingKeyWithoutGeneratingOne where only private_key.der exists: the command fails and writes nothing.

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.

3 participants