Skip to content
Merged
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
28 changes: 27 additions & 1 deletion docs/server/upgrades.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,30 @@ a reporting tool. If `--upgrade-schema` stays at a step for long, look for such
them: `SELECT pid, state, query FROM pg_stat_activity WHERE datname = current_database()` on
PostgreSQL, `SHOW PROCESSLIST` on MySQL.

### Credentials as text

Schema step V4 widens `uc_credentials.credential` from `tinytext` to `mediumtext` on MySQL, and
changes nothing on H2. On PostgreSQL it stores each credential as text instead of a large object,
read as UTF-8, so a database whose encoding cannot hold a stored credential's characters fails the
step.

Step V4 reads every credential's large object, so `--upgrade-schema` must connect as a user that
can read them: their owner, or a user granted `SELECT` on each of them
(`GRANT SELECT ON LARGE OBJECT <oid> TO <user>`). It connects as `hibernate.connection.username`,
or `hibernate.connection.user` when that is not set. Step V4 fails, and leaves `uc_credentials` as
it was, in two cases; steps before it that succeeded stay applied:

- The user cannot read a large object: grant `SELECT` on it, or run `--upgrade-schema` as the
owner, then run it again.
- A large object is missing: restore it, or restore the backup, then run `--upgrade-schema` again.

The large objects stay in the database afterwards, holding the credentials as the earlier release
stored them, including earlier versions of updated ones: remove them with `vacuumlo -v ucdb`.
`vacuumlo` removes every large object that no column references, not only the credentials' ones, so
run it only when the database holds nothing but Unity Catalog, and check first with
`vacuumlo -n -v ucdb`. On PostgreSQL a release from before schema step V4 cannot read the converted
column, so going back to it needs the backup.

## Backing up the database

Take the backup with all servers stopped, so that it holds no half-written change. The examples use
Expand All @@ -174,7 +198,9 @@ To go back, stop the new release's servers and restore the backup you took befor

Do not start the baseline release on the upgraded database as it is: its Hibernate setting
`hibernate.hbm2ddl.auto=update` changes column types back (it narrows the column that step 2
widened) while the schema history still records the step.
widened) while the schema history still records the steps. On PostgreSQL it also cannot read the
credentials that schema step V4 stored as text (see [Credentials as text](#credentials-as-text)),
so restore the backup.

## Messages

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.Lob;
import jakarta.persistence.Table;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
Expand All @@ -42,8 +41,8 @@

/**
* Data Access Object for storing cloud provider credentials in Unity Catalog. The credential
* payload is stored as a JSON blob in the {@code credential} column, with the {@code
* credentialType} discriminator indicating how to deserialize it.
* payload is stored as JSON text in the {@code credential} column, with the {@code credentialType}
* discriminator indicating how to deserialize it.
*
* @see CredentialService
* @see AwsCredentialVendor
Expand All @@ -59,8 +58,8 @@
@EqualsAndHashCode(callSuper = true)
public class CredentialDAO extends IdentifiableDAO {
private static ObjectMapper objectMapper = new ObjectMapper();
// Write-only request field of s3_compatible: stored in the blob next to the S3CompatibleResponse
// fields and dropped when the blob is read back as a response.
// Write-only request field of s3_compatible: stored in the JSON next to the S3CompatibleResponse
// fields and dropped when the JSON is read back as a response.
private static final String SECRET_ACCESS_KEY_FIELD = "secret_access_key";

public enum CredentialType {
Expand All @@ -75,8 +74,8 @@ public enum CredentialType {
@Setter(AccessLevel.NONE)
private CredentialType credentialType;

@Lob
@Column(name = "credential", nullable = false)
// Text, not a large object; the length makes it mediumtext rather than tinytext on MySQL.
@Column(name = "credential", nullable = false, length = 16777215)

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.

if the new server starts on postgresql before v4 runs, hibernate's hbm2ddl.auto=update converts oid to text holding the raw oid number (e.g. "16871"), making existing credentials unreadable and causing a later v4 run to fail on lo_get(text). why not keep @Lob with length = 16777215 like ColumnInfoDAO.typeText so mysql gets mediumtext while postgresql keeps its existing storage and a comment-only v4 step? if we keep the postgresql conversion instead, shouldn't server startup refuse an outdated schema before hibernate can alter it? could we also add a test that starts the server against a pre-v4 credential without migrating first?

-  // Text, not a large object; the length makes it mediumtext rather than tinytext on MySQL.
+  @Lob
   @Column(name = "credential", nullable = false, length = 16777215)

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.

Thanks, I reproduced it on PostgreSQL 18. Starting the server before V4 does turn the column into text holding the large object's number. V4 then passes rather than failing on lo_get(text), and the column stays that way, so the credentials can't be read.

We don't plan to support that order. On PostgreSQL this release has to run --upgrade-schema before its first start, and #2117, which this PR merges after, makes the server refuse an outdated schema rather than let Hibernate alter it. docs/server/upgrades.md now says the earlier start isn't supported, describes what it does, and gives the backup as the recovery. So I left out a test for that start, since it's an unsupported path.

I kept the conversion rather than @Lob. Text is the storage that #1928 plans for these columns, and this PR stands in for that part of it. Keeping @Lob would keep credentials as large objects on PostgreSQL, which is what the step removes.

// No direct access from outside
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
Expand Down Expand Up @@ -212,10 +211,6 @@ public void setAwsIamRole(AwsIamRoleRequest awsIamRole) {
* Validates an {@code s3_compatible} credential and stores it, replacing the stored credential;
* its {@code secret_access_key} goes through {@code secretStore}, bound to this credential's id.
*
* <p>TODO(#2169): on MySQL, {@code credential} is {@code tinytext} (255 bytes) until #2169 widens
* it, which an {@code s3_compatible} credential with {@code assume_role} and real endpoints
* usually exceeds.
*
* @param s3Compatible the credential to store
* @param secretStore keeps its {@code secret_access_key}
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
-- H2 stores credentials as clob, which already fits any credential.
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- Credentials can exceed tinytext's 255 bytes, so use mediumtext, the size of the other large text columns.
ALTER TABLE uc_credentials MODIFY COLUMN credential mediumtext NOT NULL;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- Credentials are stored as text instead of large objects. The conversion reads each large object; the
-- large objects themselves stay until vacuumlo removes them (see docs/server/upgrades.md).
ALTER TABLE uc_credentials ALTER COLUMN credential TYPE text USING convert_from(lo_get(credential), 'UTF8');

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.

Question (not a blocker): on PostgreSQL this step is not compatible with servers of the previous release. After it, they fail to read credentials, and a credential they create stores a large-object id (for example 17397) in the text column, which no release can read. The upgrade procedure already stops all servers, so nothing breaks if it's followed. Would it be worth making this step online-compatible, so a rolling upgrade works later? For example, add a credential_text column in this step, have the server read it with the oid column as fallback and write both, and drop oid in a later release. Happy to leave it as is if stopping all servers stays the supported path.

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.

Thanks for checking. I think it is fine for servers of an older release to stop working once the database is upgraded to the newer schema: the upgrade guide already has you stop all servers before running the step, so I will keep it as it is rather than make this step online-compatible.

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.

running MigrationStepRulesTest with UC_TEST_MIGRATION_CHECKS=true fails on all three databases right now. typeChangesWiden rejects both oid to text and mysql's tinytext to mediumtext, and eachStepIsOneAllowedStatement also rejects the USING clause here. if we drop the postgresql conversion, could we add tinytext to MigrationStepRulesTest.WIDER for mysql (or add a narrow tested rule if the conversion stays) and rerun UC_TEST_MIGRATION_CHECKS=true across h2, postgresql, and mysql?

           DatabaseKind.MYSQL,
           Map.of(
+              "tinytext", Set.of("text", "mediumtext", "longtext"),
               "varchar", Set.of("text", "mediumtext", "longtext"),

1 change: 1 addition & 0 deletions server/src/main/resources/schema-effects/h2/V4.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

2 changes: 2 additions & 0 deletions server/src/main/resources/schema-effects/mysql/V4.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- column uc_credentials.credential type=tinytext size=255 nullable=NO default=null
+ column uc_credentials.credential type=mediumtext size=16777215 nullable=NO default=null
2 changes: 2 additions & 0 deletions server/src/main/resources/schema-effects/postgresql/V4.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- column uc_credentials.credential type=oid size=10 nullable=NO default=null
+ column uc_credentials.credential type=text size=2147483647 nullable=NO default=null
Original file line number Diff line number Diff line change
Expand Up @@ -282,10 +282,31 @@ public void testS3CompatibleCredential() throws ApiException {
credentialOperations.deleteCredential(CREDENTIAL_NAME, Optional.empty());
}

@Test
public void testLongS3CompatibleCredential() throws ApiException {
// Longer than MySQL's tinytext (255 bytes) once stored, with non-ASCII text, on every database.
String roleArn = "arn:aws:iam::123456789012:role/réle-" + "r".repeat(1000);
S3AssumeRole assumeRole = new S3AssumeRole().stsEndpoint(S3_ENDPOINT).roleArn(roleArn);
CredentialInfo created =
credentialOperations.createCredential(request(keyPair().assumeRole(assumeRole)));
assertThat(created.getS3Compatible().getAssumeRole()).isEqualTo(assumeRole);
assertThat(credentialOperations.getCredential(CREDENTIAL_NAME)).isEqualTo(created);
assertThat(credentialOperations.listCredentials(Optional.empty(), CredentialPurpose.STORAGE))
.contains(created);

String updatedArn = roleArn + "-2";
CredentialInfo updated =
credentialOperations.updateCredential(
CREDENTIAL_NAME,
new UpdateCredentialRequest()
.s3Compatible(keyPair().assumeRole(assumeRole.roleArn(updatedArn))));
assertThat(updated.getS3Compatible().getAssumeRole().getRoleArn()).isEqualTo(updatedArn);
assertThat(credentialOperations.getCredential(CREDENTIAL_NAME)).isEqualTo(updated);
credentialOperations.deleteCredential(CREDENTIAL_NAME, Optional.empty());
}

private record InvalidCreate(CreateCredentialRequest request, String error) {}

// Short, so a credential with assume_role fits MySQL's tinytext (255 bytes) before the
// credential column is widened.
private static final String S3_ENDPOINT = "http://s3:9000";
private static final String S3_ROLE_ARN = "arn:aws:iam::1:role/r";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@
* PostgreSQL index entry, INCLUDE columns too, fits 2,704 bytes, add a column (NOT NULL only
* with a literal DEFAULT, without a key or CHECK rule), change a column's type (each index on
* the column still fitting an index entry), drop its NOT NULL, or, on PostgreSQL, replace a
* column's CHECK of its values with one that keeps them all.
* column's CHECK of its values with one that keeps them all, or read an {@code oid} column's
* large objects as text, the one change rows can fail ({@link #readsLargeObjectsAsText}).
* <li>A type change widens the column, keeps its default, collation and enum or set members, and
* no change makes an existing nullable column NOT NULL ({@link #typeChangesWiden}). Adding a
* Java enum constant changes the type on MySQL and H2, where the type holds the members; on
Expand Down Expand Up @@ -109,10 +110,13 @@ public class MigrationStepRulesTest {
DatabaseKind.POSTGRESQL,
Map.of(
"varchar", Set.of("text"),
// An oid column holds large object ids; only readsLargeObjectsAsText changes it.
"oid", Set.of("text"),
"int2", Set.of("int4", "int8"),
"int4", Set.of("int8")),
DatabaseKind.MYSQL,
Map.of(
"tinytext", Set.of("text", "mediumtext", "longtext"),
"varchar", Set.of("text", "mediumtext", "longtext"),
"text", Set.of("mediumtext", "longtext"),
"mediumtext", Set.of("longtext"),
Expand Down Expand Up @@ -284,6 +288,21 @@ void eachStepIsOneAllowedStatement() throws IOException {
"MYSQL|CREATE FULLTEXT INDEX i ON t (c)|creates a fulltext index",
"POSTGRESQL|ALTER TABLE t ALTER COLUMN c TYPE text|",
"POSTGRESQL|ALTER TABLE t ALTER COLUMN c TYPE int USING c::int|is not an allowed change",
// Large objects read as text: only on an oid column, and only as UTF-8. A plain type change
// of an oid column would keep the ids as values.
"POSTGRESQL|ALTER TABLE t ALTER COLUMN lo TYPE text|is not an allowed change",
"POSTGRESQL|ALTER TABLE t ALTER COLUMN \"lo\" TYPE text|is not an allowed change",
"POSTGRESQL|ALTER TABLE \"t\" ALTER COLUMN lo TYPE text|is not an allowed change",
"POSTGRESQL|ALTER TABLE \"t\" ALTER COLUMN \"lo\" TYPE text USING"
+ " convert_from(lo_get(\"lo\"), 'UTF8')|",
"POSTGRESQL|ALTER TABLE t ALTER COLUMN lo TYPE text USING convert_from(lo_get(lo),"
+ " 'UTF8')|",
"POSTGRESQL|ALTER TABLE t ALTER COLUMN c TYPE text USING convert_from(lo_get(c), 'UTF8')|is"
+ " not an allowed change",
"POSTGRESQL|ALTER TABLE t ALTER COLUMN lo TYPE text USING convert_from(lo_get(lo),"
+ " 'LATIN1')|is not an allowed change",
"MYSQL|ALTER TABLE t ALTER COLUMN lo TYPE text USING convert_from(lo_get(lo), 'UTF8')|is"
+ " not an allowed change",
"POSTGRESQL|ALTER TABLE t ALTER COLUMN c DROP NOT NULL|",
"POSTGRESQL|ALTER TABLE t ALTER COLUMN c SET NOT NULL|is not an allowed change",
"POSTGRESQL|ALTER TABLE t ADD UNIQUE (c)|is not an allowed change",
Expand Down Expand Up @@ -325,6 +344,7 @@ void laterStepsOnlyMakeChangesRowsCannotFail(DatabaseKind kind, String sql, Stri
new SchemaSnapshot(
List.of(
"column t.c type=varchar size=255 nullable=YES default=null",
"column t.lo type=oid size=10 nullable=YES default=null",
"column t.long type=varchar size=65535 nullable=YES default=null",
"column t.body type=text size=2147483647 nullable=YES default=null",
"column t.a type=varchar size=600 nullable=YES default=null",
Expand Down Expand Up @@ -701,7 +721,11 @@ private static String refusal(
case ADD -> NEW_COLUMN.matcher(columnSpecs(change)).matches();
// PostgreSQL and H2: ALTER TABLE t ALTER COLUMN c [SET DATA] TYPE <type>, or
// ALTER TABLE t ALTER COLUMN c DROP NOT NULL
case ALTER -> kind != DatabaseKind.MYSQL && (changesType(change) || dropsNotNull(change));
case ALTER ->
kind != DatabaseKind.MYSQL
&& (changesType(change) && !isLargeObjectColumn(kind, alter, change, before)
|| dropsNotNull(change)
|| readsLargeObjectsAsText(kind, alter, change, before));
// MySQL: ALTER TABLE t MODIFY c <type> [NULL | NOT NULL] [DEFAULT x] [COLLATE x], which
// must restate the column's default and collation (typeChangesWiden checks they stay)
case MODIFY ->
Expand Down Expand Up @@ -1015,6 +1039,41 @@ private static boolean changesType(AlterExpression change) {
&& change.getColDataTypeList().get(0).getUsingExpression() == null;
}

/**
* PostgreSQL's {@code ALTER TABLE t ALTER COLUMN c TYPE text USING convert_from(lo_get(c),
* 'UTF8')} on an {@code oid} column, which replaces each large object id with the object's text.
* Unlike the other changes, rows can fail it (a missing large object, or one that is not UTF-8),
* so only this exact form is allowed; {@code docs/server/upgrades.md} says how to recover.
*/
private static boolean readsLargeObjectsAsText(
DatabaseKind kind, Alter alter, AlterExpression change, SchemaSnapshot before) {
if (!isLargeObjectColumn(kind, alter, change, before)) {
return false;
}
AlterExpression.ColumnDataType column = change.getColDataTypeList().get(0);
String name = unquoted(column.getColumnName());
return column.getColDataType().getDataType().equalsIgnoreCase("text")
&& column.getUsingExpression() != null
&& unquoted(column.getUsingExpression().toString().replace(" ", ""))
.equals("convert_from(lo_get(" + name + "),'utf8')");
}

/**
* Whether {@code change} changes a PostgreSQL {@code oid} column, which holds large object ids:
* any other type change would keep the ids as values, so only {@link #readsLargeObjectsAsText}
* may change it.
*/
private static boolean isLargeObjectColumn(
DatabaseKind kind, Alter alter, AlterExpression change, SchemaSnapshot before) {
if (kind != DatabaseKind.POSTGRESQL || !columnSpecs(change).isEmpty()) {
return false;
}
String table = unquoted(alter.getTable().getName());
String name = unquoted(change.getColDataTypeList().get(0).getColumnName());
return before.entries().stream()
.anyMatch(entry -> entry.startsWith("column " + table + "." + name + " type=oid "));
}

private static boolean dropsNotNull(AlterExpression change) {
return change.getColDataTypeList() == null
&& change.getColumnDropNotNullList() != null
Expand Down
Loading
Loading