Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions bin/uc-admin-token
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/bin/bash

# Prints an admin token signed with the server's key, for example:
# bin/uc --auth_token "$(bin/uc-admin-token)" user list
# Like the server, it reads etc/conf in the current directory and the UC_ environment variables,
# so run it from the directory you start the server in, with the same environment.

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
ROOT_DIR="$(dirname "$SCRIPT_DIR")"

if [ -d "$ROOT_DIR/jars" ]; then
CLASSPATH_FILE="$ROOT_DIR/jars/classpath"
else
CLASSPATH_FILE="$ROOT_DIR/server/target/classpath"
fi
if [ ! -f "$CLASSPATH_FILE" ]; then
echo "No classpath file at $CLASSPATH_FILE; in a source checkout, run build/sbt package first." >&2
exit 1
fi

exec java -cp "$(cat "$CLASSPATH_FILE")" io.unitycatalog.server.security.AdminTokenCommand
4 changes: 2 additions & 2 deletions clients/python/build/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,8 @@ for field in table.metadata.columns.fields:
```

The `Authorization` header is only needed when the server has
[authentication](https://docs.unitycatalog.io/server/auth/) enabled, where a local server writes its admin token to
`etc/conf/token.txt`. Leave out `header_name` and `header_value` for the local unauthenticated server used in the
[authentication](https://docs.unitycatalog.io/server/auth/) enabled; `bin/uc-admin-token` prints an admin token for a
local server. Leave out `header_name` and `header_value` for the local unauthenticated server used in the
examples above. The token goes in a header because `Configuration(access_token=...)` does not send it.

## Feedback
Expand Down
32 changes: 21 additions & 11 deletions docs/server/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,13 @@ working, point it at the key the server already has, `etc/conf/private_key.der`,
those tokens fail with 401. A server without the setting keeps signing with the key it generated in `etc/conf`, which
is deprecated (see [Configuration](configuration.md#configuration)).

The server no longer writes the admin token to `etc/conf/token.txt`, and deletes that file at startup; if it cannot, it
logs a warning, so delete the file yourself. Use `bin/uc-admin-token` instead (see [Testing User and Admin
Authentication](#testing-user-and-admin-authentication)). Copies of the old token stay valid until the signing key
changes, so change the key to revoke them: point the token signing key file setting at a new key, or, with the generated
key, delete `etc/conf/private_key.der` and `etc/conf/public_key.der`. A server reads its key only at startup, so restart
every server instance that uses the old key. Every token signed with the old key stops working once it is restarted.

Other changes to the server's own tokens:

- A token signed with a different key always gets 401. Before, one with a key ID the server did not know got 500,
Expand All @@ -300,6 +307,8 @@ Other changes to the server's own tokens:
`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`.
- A newly generated `etc/conf/private_key.der` is readable by its owner only, on file systems with POSIX permissions.
Run `bin/uc-admin-token` as the user that runs the server, from the directory the server starts in, with the same
environment.
- With authorization enabled and no key file setting, the server logs a warning at each start.
- Helm: use the server image from the chart's release, which is the default. An older server image ignores the key
file setting and generates its own key in each pod, so tokens from other pods and from the create-users job are
Expand Down Expand Up @@ -498,7 +507,6 @@ Behind the scenes, on startup, the UC server will configure itself with the foll

* Creation of an internal signing key in `etc/conf` on first start, unless the
[token signing key file](configuration.md#configuration) is set; generating the key is deprecated
* Creation of an admin access token in `etc/conf/token.txt`
* Creation of an admin account in the user database
* Granting the admin account as the metastore admin for the server

Expand All @@ -508,11 +516,13 @@ The following steps allow you to test user and admin authentication to your loca

### Use admin token to verify admin user is in local database

As noted earlier, on startup the UC server configured itself and created the admin access token at
`etc/conf/token.txt`. The following command uses the same admin authentication token to view the user list.
`bin/uc-admin-token` prints an admin token signed with the server's key. Like the server, it reads `etc/conf` in
the current directory and the `UC_` environment variables, so run it from the directory you start the server in, with
the same environment; the server does not write the token to a file. The token does not expire, so treat it like the
key itself. The following command uses it to view the user list.

```sh
bin/uc --auth_token $(cat etc/conf/token.txt) user list
bin/uc --auth_token "$(bin/uc-admin-token)" user list
```

The output should look something like this
Expand Down Expand Up @@ -565,7 +575,7 @@ To fix this error, let’s start by adding your user account to the UC local dat
to add your account to the local database.

```sh
bin/uc --auth_token $(cat etc/conf/token.txt) user create --name "Bobbie Draper" --email bobbie@rocinante
bin/uc --auth_token "$(bin/uc-admin-token)" user create --name "Bobbie Draper" --email bobbie@rocinante
```

### Try to log in with your user account
Expand Down Expand Up @@ -615,13 +625,13 @@ bin/uc catalog list
bin/uc --auth_token $token catalog list

# Succeeds
bin/uc --auth_token $(cat etc/conf/token.txt) catalog list
bin/uc --auth_token "$(bin/uc-admin-token)" catalog list
```

But if you were to add `USE CATALOG` permission to your user account

```sh
bin/uc --auth_token $(cat etc/conf/token.txt) permission create --securable_type catalog --name unity --privilege 'USE CATALOG' --principal bobbie@rocinante
bin/uc --auth_token "$(bin/uc-admin-token)" permission create --securable_type catalog --name unity --privilege 'USE CATALOG' --principal bobbie@rocinante
```

then the following command would work.
Expand All @@ -642,7 +652,7 @@ bin/uc --auth_token $token catalog create --name myfirstcatalog
Thus, let’s provide your account with the necessary permissions.

```sh
bin/uc --auth_token $(cat etc/conf/token.txt) permission create --securable_type metastore --name metastore --privilege "CREATE CATALOG" --principal bobbie@rocinante
bin/uc --auth_token "$(bin/uc-admin-token)" permission create --securable_type metastore --name metastore --privilege "CREATE CATALOG" --principal bobbie@rocinante
```

With the permission set, the preceding command will succeed because your user account has the `CREATE CATALOG`
Expand All @@ -655,9 +665,9 @@ Notice how we’re providing access using the three-part naming convention of *c
each level of permissions, we progress down the three parts.

```sh
bin/uc --auth_token $(cat etc/conf/token.txt ) permission create --securable_type catalog --name unity --privilege "USE CATALOG" --principal bobbie@rocinante
bin/uc --auth_token $(cat etc/conf/token.txt ) permission create --securable_type schema --name unity.default --privilege "USE SCHEMA" --principal bobbie@rocinante
bin/uc --auth_token $(cat etc/conf/token.txt ) permission create --securable_type table --name unity.default.numbers --privilege "SELECT" --principal bobbie@rocinante
bin/uc --auth_token "$(bin/uc-admin-token)" permission create --securable_type catalog --name unity --privilege "USE CATALOG" --principal bobbie@rocinante
bin/uc --auth_token "$(bin/uc-admin-token)" permission create --securable_type schema --name unity.default --privilege "USE SCHEMA" --principal bobbie@rocinante
bin/uc --auth_token "$(bin/uc-admin-token)" permission create --securable_type table --name unity.default.numbers --privilege "SELECT" --principal bobbie@rocinante
```

Then start a new DuckDB session.
Expand Down
7 changes: 7 additions & 0 deletions docs/server/helm.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,13 @@ server:
name: uc-token-signing-key
```

To get an admin token signed with that key, for example to create the first users, run `bin/uc-admin-token` in the
server container:

```sh
kubectl exec --namespace unitycatalog deploy/unitycatalog-server -c server -- bin/uc-admin-token
```

## Upgrade and uninstall

To upgrade, read the release notes, scale the server to 0 replicas (`kubectl scale deployment` with the chart's
Expand Down
10 changes: 5 additions & 5 deletions docs/server/users-privileges.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Here's a quick overview:
When you enable external authorization on a catalog, Unity Catalog automatically:

- creates an admin account in the user database
- creates an admin token
- lets `bin/uc-admin-token` print an admin token signed with the server's key
Comment thread
shba24 marked this conversation as resolved.
Resolved
- grants the admin account the metastore admin privileges for the server.

Read the [Auth docs](auth.md) to learn how you can configure authentication and authorization.
Expand All @@ -25,7 +25,7 @@ When you create a new catalog with external authentication enabled, Unity Catalo

**Admins:**

- Use the admin token (in `etc/conf/token.txt`) to authenticate
- Use the admin token (printed by `bin/uc-admin-token`) to authenticate
- Have full privileges to access and transform catalogs, schemas and assets
- Can create user accounts

Expand All @@ -40,7 +40,7 @@ When you create a new catalog with external authentication enabled, Unity Catalo
Admins can create new users using the Unity Catalog CLI:

```sh
bin/uc --auth_token $(cat etc/conf/token.txt) user create --name "Bobbie Draper" --email bobbie@rocinante
bin/uc --auth_token "$(bin/uc-admin-token)" user create --name "Bobbie Draper" --email bobbie@rocinante
```

This will add a new user to the local Unity Catalog user database.
Expand All @@ -52,13 +52,13 @@ An admin can grant users privileges using the Unity Catalog CLI.
For example, to grant a user the `USE CATALOG` privileg:

```sh
bin/uc --auth_token $(cat etc/conf/token.txt) permission create --securable_type catalog --name unity --privilege 'USE CATALOG' --principal bobbie@rocinante
bin/uc --auth_token "$(bin/uc-admin-token)" permission create --securable_type catalog --name unity --privilege 'USE CATALOG' --principal bobbie@rocinante
```

Or to grant the `CREATE CATALOG` privilege:

```sh
bin/uc --auth_token $(cat etc/conf/token.txt) permission create --securable_type metastore --name metastore --privilege "CREATE CATALOG" --principal bobbie@rocinante
bin/uc --auth_token "$(bin/uc-admin-token)" permission create --securable_type metastore --name metastore --privilege "CREATE CATALOG" --principal bobbie@rocinante
```

`READ METADATA` permits full metadata reads and viewing all direct grants. It can be granted on a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
import io.unitycatalog.server.security.JwtClaim;
import io.unitycatalog.server.security.JwtTokenType;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
Expand Down Expand Up @@ -61,7 +59,7 @@ public void testAuthLoginExchangeWithCorrectIssuerAndAudience() throws IOExcepti

// The exchanged principal must be an enabled user, so create one with the bootstrap admin
// token before exchanging as that user.
String adminToken = Files.readString(configurationFolder.resolve("token.txt"));
String adminToken = securityContext.createServiceToken();
serverConfig.setAuthToken(adminToken);
executeCliCommand(
serverConfig,
Expand Down Expand Up @@ -156,8 +154,7 @@ public void testAuthAccess()
.isInstanceOf(RuntimeException.class);

// Test with Authentication on authenticated end point
Path path = configurationFolder.resolve("token.txt");
String token = Files.readString(path);
String token = securityContext.createServiceToken();

serverConfig.setAuthToken(token);

Expand Down Expand Up @@ -210,8 +207,7 @@ public void testAuthAccess()
@Test
public void testUserCrud() throws IOException {
// Test with Authentication on authenticated end point
Path path = configurationFolder.resolve("token.txt");
String token = Files.readString(path);
String token = securityContext.createServiceToken();

serverConfig.setAuthToken(token);
// Test creating a user
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ public class UnityCatalogServer implements AutoCloseable {
Configurator.initialize(null, "etc/conf/server.log4j2.properties");
}

/** The context that signs and verifies this server's tokens; for tests. */
SecurityContext securityContext() {
return securityContext;
}

private UnityCatalogServer(UnityCatalogServer.Builder unityCatalogServerBuilder) {
setDefaults(unityCatalogServerBuilder);
unityCatalogServerBuilder.serverProperties.validateProperties();
Expand Down Expand Up @@ -752,15 +757,14 @@ public UnityCatalogServer.Builder fileOperationsDecorator(
}

/**
* 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.
* Sets the folder for the signing keys the server keeps, and creates if missing, when {@code
* server.token-signing-private-key-file} is not set. Defaults to {@code etc/conf}; tests pass
* their own folder so concurrent servers do not share these files.
*
* <p>Only these files move: {@code server.properties}, {@code hibernate.properties} and the
* log4j configuration are still read from {@code etc/conf}.
*
* @param configurationFolder the folder for {@code token.txt} and any server-kept signing keys
* @param configurationFolder the folder for the server-kept signing keys
* @return this builder
*/
public UnityCatalogServer.Builder configurationFolder(Path configurationFolder) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package io.unitycatalog.server.security;

import io.unitycatalog.server.UnityCatalogServer;
import io.unitycatalog.server.security.SecurityContext.Issuers;
import io.unitycatalog.server.utils.ServerProperties;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.config.Configurator;

/**
* Prints an admin token signed with the server's key, for creating the first users and grants:
* {@code bin/uc --auth_token "$(bin/uc-admin-token)" user list}. It reads the key the server signs
* with, from the token signing key file setting or {@code etc/conf}, and writes no key or token
* files. Run it with the server's environment, which can hold that setting.
*/
public final class AdminTokenCommand {

private AdminTokenCommand() {}

public static void main(String[] args) throws Exception {
Comment thread
shba24 marked this conversation as resolved.
Resolved

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.

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.

// Logs go to the CLI log file, or nowhere when there is none (as in a Helm pod), so standard
// 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?

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.

} else {
Configurator.setRootLevel(Level.OFF);
}
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.of("etc", "conf"),
System.out);
} 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));
Comment thread
shba24 marked this conversation as resolved.
Resolved

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

System.exit(1);
}
}

// Prints one admin token, signed with the key the server uses, to out.
static void run(ServerProperties serverProperties, Path configurationFolder, PrintStream out) {
// Only reads the key: a missing key is an error here, not a reason to generate one.
SecurityConfiguration securityConfiguration =
SecurityConfiguration.loadExisting(serverProperties, configurationFolder);
out.println(
SecurityContext.createServiceToken(
securityConfiguration.algorithmRSA(), "server", Issuers.INTERNAL));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.Getter;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -68,17 +69,22 @@ public class SecurityConfiguration {
private final RSAPrivateKey privateKey;
private final RSAPublicKey publicKey;

/** The file the private key was read from. */
@Getter private final Path privateKeyFile;

/** Uses the key in the configuration folder, generating it if missing. */
@SneakyThrows
public SecurityConfiguration(Path configurationFolder) {
Path privateKeyFile = configurationFolder.resolve("private_key.der");
privateKeyFile = configurationFolder.resolve("private_key.der");
Path publicKeyFile = configurationFolder.resolve("public_key.der");
initializeIfMissing(privateKeyFile, publicKeyFile);
privateKey = readPrivateKey(privateKeyFile);
publicKey = readPublicKey(publicKeyFile);
}

private SecurityConfiguration(RSAPrivateKey privateKey, RSAPublicKey publicKey) {
private SecurityConfiguration(
Path privateKeyFile, RSAPrivateKey privateKey, RSAPublicKey publicKey) {
this.privateKeyFile = privateKeyFile;
this.privateKey = privateKey;
this.publicKey = publicKey;
}
Expand All @@ -104,6 +110,15 @@ public static SecurityConfiguration load(
return new SecurityConfiguration(configurationFolder);
}

/** 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.

ServerProperties serverProperties, Path configurationFolder) {
SecurityConfiguration configured = fromSettings(serverProperties);
return configured != null
? configured
: fromPrivateKeyFile(configurationFolder.resolve("private_key.der"));
}

// Returns null when the key file is not set.
private static SecurityConfiguration fromSettings(ServerProperties serverProperties) {
String privateKeyFile = serverProperties.get(Property.TOKEN_SIGNING_PRIVATE_KEY_FILE);
Expand All @@ -117,7 +132,8 @@ private static SecurityConfiguration fromSettings(ServerProperties serverPropert
private static SecurityConfiguration fromPrivateKeyFile(Path privateKeyFile) {
requireFile(privateKeyFile);
RSAPrivateKey privateKey = readPrivateKey(privateKeyFile);
return new SecurityConfiguration(privateKey, publicKeyOf(privateKey, privateKeyFile));
return new SecurityConfiguration(
privateKeyFile, privateKey, publicKeyOf(privateKey, privateKeyFile));
}

// A file that exists but cannot be read is reported by the read, with the real cause.
Expand Down
Loading
Loading