Skip to content

[Server] Invalidate access tokens on logout - #1781

Merged
yili-db merged 1 commit into
unitycatalog:mainfrom
yili-db:token_logout
Dec 2, 2026
Merged

yili-db merged 1 commit into
unitycatalog:mainfrom
yili-db:token_logout

Conversation

@yili-db

@yili-db yili-db commented Aug 17, 2026 •

Copy link
Copy Markdown
Collaborator

PR Checklist

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

Description of changes

  • Add TokenRevocationDAO (uc_token_revocations, keyed by jti) and TokenRevocationRepository to record revoked tokens.
    • Cleanup of expired rows is single-flight and async.
    • If the cleanup cannot start, the next revocation starts it.
    • A row is kept for RETENTION_GRACE (2 days) past its expiry, since expires_at has no time zone.
  • Add schema steps for H2, MySQL, and PostgreSQL, with their effect files:
    • V22__create_token_revocations
    • V23__index_token_revocations_expires_at
  • On /logout, revoke the presented ACCESS token until its exp; SERVICE tokens are left untouched.
  • Reject revoked tokens with 401 in AuthDecorator and in grantToken, so a logged-out token cannot be exchanged for a new one.
    • Re-check expiry after the revocation lookup, so a row purged during the lookup cannot let a revoked token through.
    • Only internal tokens have their jti checked; external tokens' jti is not parsed.
  • Keep database messages out of the error responses of the auth lookup, revoke, and isRevoked.
  • Treat a duplicate revoke as success when the row is present or the token has expired (its row may have been purged).
    • If the row cannot be read back after a failed insert, the insert's failure is thrown, with the read's failure attached.
  • Document logout in api/control.yaml (and the generated control.gen.ts) and docs/server/auth.md.
  • Ignore JaCoCo *.exec coverage files in .gitignore.
  • Tests:
    • Add TokenRevocationRepositoryTest, on a per-test @TempDatabase.
    • Extend AuthServiceTest and AuthDecoratorTest.

API change

  • POST /auth/logout (api/control.yaml): only the summary and description change, to say that logout revokes the access token. The request and response are unchanged.

Testing

  • dev/run-tests.py
  • Migration and auth tests with UC_TEST_DATABASE set to H2, POSTGRES_18, and MYSQL_8, with UC_TEST_MIGRATION_CHECKS=true

This pull request and its description were written by Isaac.

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

two comments.

Comment on lines +227 to +230
Date expiresAt =
decodedJWT.getExpiresAt() != null
? decodedJWT.getExpiresAt()
: Date.from(Instant.now().plus(serverProperties.getAccessTokenTimeout()));

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.

fall back to the configured access-token lifetime if one is somehow absent.

but null could mean no expiry right? if that's the case then tokens with no expiry will remain and continue working.

- Date expiresAt =
-     decodedJWT.getExpiresAt() != null
-         ? decodedJWT.getExpiresAt()
-         : Date.from(Instant.now().plus(serverProperties.getAccessTokenTimeout()));
+ // null means this token never expires, so its revocation must be permanent.
+ Date expiresAt = decodedJWT.getExpiresAt();

Comment on lines +48 to +54
TokenRevocationDAO existing = session.get(TokenRevocationDAO.class, jti);
if (existing == null) {
session.persist(TokenRevocationDAO.builder().jti(jti).expiresAt(expiresAt).build());
} else {
// existing is managed, so the updated expiry is flushed on commit.
existing.setExpiresAt(expiresAt);
}

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.

so to my understanding: someone logs out -> we need to revoke their credentials -> when we revoke, we check this TokenRevocationDAO table and add that credential to the table. future API request checks said table. if its in it, DENIED

not a blocker, but suppose two logouts happen at the same time. both check the table before either adds the row. both try to add the same token -- one insert succeeds, while the other fails with HTTP 500.

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.

actually maybe the simplest solution is just to do an upsert: Insert the token ID. If it already exists, update it instead.
something like:

 session -> {
-  TokenRevocationDAO existing =
-      session.get(TokenRevocationDAO.class, jti);
-  if (existing == null) {
-    session.persist(
-        TokenRevocationDAO.builder()
-            .jti(jti)
-            .expiresAt(expiresAt)
-            .build());
-  } else {
-    existing.setExpiresAt(expiresAt);
-  }
+  MutationQuery upsert =
+      session.createMutationQuery(
+          "INSERT INTO TokenRevocationDAO (jti, expiresAt) "
+              + "VALUES (:jti, :expiresAt) "
+              + "ON CONFLICT (jti) DO UPDATE "
+              + "SET expiresAt = excluded.expiresAt");
+  upsert.setParameter("jti", jti);
+  upsert.setParameter("expiresAt", expiresAt);
+  upsert.executeUpdate();
+
   return null;
 }

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.

HQL on conflict is a Hibernate 7.0 feature — 6.5 doesn't have it yet.
I am fixing it using a try-catch and read back method.

@timothyw553

Copy link
Copy Markdown
Collaborator

@yili-db there is a conflict

@timothyw553

Copy link
Copy Markdown
Collaborator

@yili-db bump on the merge conflict here

@yili-db

yili-db commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator Author

@yili-db bump on the merge conflict here

@timothyw553 Rebased. PTAL

@timothyw553

Copy link
Copy Markdown
Collaborator

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

two small comments.

Comment on lines +108 to +110
if (tokenRevocationRepository.isRevoked(session, jti)) {
throw new AuthorizationException(
ErrorCode.PERMISSION_DENIED, "Access token has been revoked.");

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.

should this be PERMISSION_DENIED or UNAUTHENTICATED?

my understanding:

  • 401 (UNAUTHENTICATED): The credential is invalid. The client needs a valid token.
  • 403 (PERMISSION_DENIED): The credential is valid, but it does not grant the required permission.

token revoked sounds more like 401.

String subject = verifiedJWT.getSubject();
// Tokens this server issues always carry a UUID jti; an absent or non-UUID jti fails here
// (acceptable, since only issued tokens are revoked).
UUID jti = UUID.fromString(verifiedJWT.getId());

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] A signed token with no jti throws a NullPointerException, which becomes a 500. A token with a non-UUID jti throws an IllegalArgumentException, which becomes a 400. Both should be 401.

LOGGER.debug("Token jti={} was already revoked; treating this revoke as a no-op", jti);
}

CompletableFuture.runAsync(this::deleteExpiredQuietly);

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.

one thing to think about is if we submit 100 revocations, then each of these 100 recovactions will have a worker doing overlapping work with the other 99 workers.

@yili-db yili-db changed the title Invalidate access tokens on logout [Server] Invalidate access tokens on logout Oct 21, 2026
@yili-db
yili-db requested a review from timothyw553 October 21, 2026 00:02
Comment on lines +106 to +109
if (tokenRevocationRepository.isRevoked(session, jti)) {
throw new AuthorizationException(
ErrorCode.UNAUTHENTICATED, "Access token has been revoked.");
}

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.

Expiry is checked before the database lookup. During a delay, the token can expire and cleanup can delete its revocation record. The lookup then treats the missing record as permission to continue.

Keep the initial verification. Verify expiry again after database access and before accepting the request:

+    verifiedJWT = jwtVerifier.verify(verifiedJWT);
     ctx.setAttr(DECODED_JWT_ATTR, verifiedJWT);

Apply the same check in grantToken() before creating a replacement token.

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.

Done. Expiry is re-checked after the lookup in both AuthDecorator and grantToken. A token is accepted only before its exp, and cleanup deletes only rows past it, so a purged row always fails the re-check.

Comment on lines +103 to +105
TransactionManager.executeWithTransaction(
sessionFactory,
session -> {

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.

The new authentication transaction has no catch that sanitizes database failures. TransactionManager includes the database exception message in its error. The global handler sends that message to the client.

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.

Done. Database failures in the auth lookup are rethrown as Failed to authorize request with the same error code; the original error stays as the cause for the server log.

Comment on lines +69 to +71
if (!isRevoked(jti)) {
throw e;
}

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.

Two logout requests can pass authentication together. One inserts the revocation; the other encounters a duplicate key. If cleanup removes the expired record before the recovery lookup, this branch rethrows the error.

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.

Done. A failed duplicate insert is also treated as success when the token has already expired, since only then can cleanup have deleted the row. Added a test that reproduces the race.

@timothyw553

Copy link
Copy Markdown
Collaborator

and please rebase.

@yili-db

yili-db commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@yili-db
yili-db requested a review from timothyw553 November 12, 2026 23:30

@timothyw553 timothyw553 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

overall approach looks reasonable, though i think the early-purge issue in cleanup needs fixing before merge. also left a few comments on tests, error handling, and layering.

session -> {
MutationQuery purge =
session.createMutationQuery("DELETE FROM TokenRevocationDAO WHERE expiresAt < :now");
purge.setParameter("now", new Date());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

since expires_at is stored without a timezone, couldn't a JVM timezone difference or DST change cause expiresAt < :now to purge a revocation before the token actually expires? once the row is gone the token would work again until it expires. could we keep a retention buffer here (e.g., 2 days) and test that a row 1h past expiry survives while an older one gets deleted?

+private static final Duration RETENTION_GRACE = Duration.ofDays(2);
...
-          purge.setParameter("now", new Date());
+          purge.setParameter("now", Date.from(Instant.now().minus(RETENTION_GRACE)));

// Use a dedicated in-memory database so the test is hermetic and does not touch the on-disk
// dev database referenced by etc/conf/hibernate.properties.
Properties properties = new Properties();
properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver");

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.

this fixture hardcodes an in-memory H2 db shared across all test methods, so running with UC_TEST_DATABASE set to MySQL or PostgreSQL still only tests H2 here. since this repository relies on duplicate-key errors and timestamp comparisons, could we switch to a per-test @TempDatabase TestDatabase like the other repository tests? also worth keeping cleanup controlled in the duplicate-insert test so an earlier async sweep doesn't race with it.

// This endpoint is not behind the auth decorator, so check revocation here. Otherwise, when
// the issuer allowlist matches the internal issuer (for example "*"), a logged-out access
// token could be exchanged for a fresh one.
if (INTERNAL.equals(issuer)) {

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.

we test invalid jti on /logout, but do we have /auth/tokens tests for this INTERNAL.equals(issuer) boundary? specifically, an internal token with missing/malformed jti returning 401, and an external token with an opaque or missing jti still succeeding? otherwise removing the issuer check could break external IdPs without any test catching it.

.equals(decodedJWT.getClaim(JwtClaim.TOKEN_TYPE.key()).asString())) {
// Retain the denylist entry until the token would have expired anyway. A null exp means the
// token never expires, so revoke it permanently (the repository keeps a null-expiry row).
tokenRevocationRepository.revoke(

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.

only AuthDecorator strips the database message on failure -- both revoke here and isRevoked in grantToken still let TransactionManager's e.getMessage() leak through to the caller, so the PR's claim about auth-path error sanitization isn't quite true yet. should we drop e.getMessage() in TransactionManager (keeping e as the cause) or wrap it in the repo/service, and add failure tests for logout and exchange?

@AuthorizeExpression("#principal != null")
public HttpResponse logout(HttpRequest request) {
public HttpResponse logout(ServiceRequestContext ctx, HttpRequest request) {
// Revoke the presented access token so it cannot be reused after logout. The auth decorator has

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.

in api/control.yaml, /auth/logout still just says "Revoke access token cookie" -- should we update it and docs/server/auth.md to document that logout revokes the access token server-side (and leaves SERVICE tokens untouched)?

-      summary: Revoke access token cookie
+      summary: Log out and revoke the access token
       description: |
-        Revokes the access token cookie.
+        Revokes the presented access token and clears the UC_TOKEN cookie if present.
+        Revoked access tokens are rejected by authentication and token exchange.
+        The server's SERVICE token is not revoked.

nit: the comment at line 192 mentions "*" as an issuer allowlist example which isn't supported, and TokenRevocationDAO says the table stays bounded even though null-expiry rows stay forever.

@yili-db

yili-db commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@maharanay22 maharanay22 mentioned this pull request Nov 21, 2026
2 of 4 tasks

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

thanks for addressing the earlier comments. overall looks good, i just left a few comments on the tests, the stray jacoco files, and some small cleanup details.

looks like server/jacoco.exec and examples/sample-database/jacoco.exec slipped into the commit. could we remove both and add *.exec to .gitignore?

return user(User.StateEnum.ENABLED);
});

assertThatThrownBy(this::serve).isInstanceOf(TokenExpiredException.class);

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 test pauses before calling serve(), won't the 2s token (with whole-second JWT timestamps) expire on the first verify before ever reaching the lookup? if we verify userRepository.getUserByEmail was called, we make sure the second verify is actually exercised:

 assertThatThrownBy(this::serve).isInstanceOf(TokenExpiredException.class);
+verify(userRepository).getUserByEmail(any(), eq(EMAIL));
 verifyNotDelegated();

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

Approving -- feel free to merge once you have addressed my last comment and fixed the merge conflict.

@yili-db
yili-db force-pushed the token_logout branch 2 times, most recently from eafa45c to 07a9979 Compare November 24, 2026 22:51
@yili-db

yili-db commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@yili-db
yili-db force-pushed the token_logout branch 2 times, most recently from 9c053a4 to cb8cc71 Compare November 25, 2026 08:52
@yili-db

yili-db commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

/review

yili-db pushed a commit that referenced this pull request Nov 25, 2026
**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!
- [ ] If you've added or modified a feature, documentation in `docs` is
updated (not needed, the docs don't describe column widths)

**Description of changes**

Creating a catalog whose storage root is longer than 255 characters
fails with a 500:

```
POST /api/2.1/unity-catalog/catalogs  {"name": "c", "storage_root": "s3://catalog-bucket/<1000 characters>"}
500 INTERNAL ... Value too long for column "STORAGE_ROOT CHARACTER VARYING(255)"
```

The same happens for a schema storage root, a managed volume whose
catalog or schema location is long enough that
`<location>/volumes/<uuid>` passes 255 characters, an external volume
over 255 characters, and a model version `source` over 255 characters.
Table locations don't have this problem because `uc_tables.url` is
`varchar(2048)`, and staging table locations are 2048 as well.

This PR widens these columns to 2048, the width of `uc_tables.url`, with
one single-statement step per column for H2, MySQL and PostgreSQL, each
with its own effect file, the same way #2187 widens the function
columns:

- V11 `uc_catalogs.storage_root` and V12 `uc_catalogs.storage_location`
- V13 `uc_schemas.storage_root` and V14 `uc_schemas.storage_location`
- V15 `uc_volumes.storage_location`
- V16 `uc_model_versions.source`


The matching DAO fields use one constant,
`Constants.MAX_STORAGE_LOCATION_LENGTH` (2048), which the table url and
staging table location columns now use too. Their width doesn't change.
Each step only changes a column type from `varchar(255)` to
`varchar(2048)`, and all six columns are nullable and have no default,
so the MySQL `MODIFY` restates `NULL` and drops nothing. None of the six
columns is in an index, so no index entry grows.

A new database gets the wider columns from the steps. An existing
database gets them when `bin/start-uc-server --upgrade-schema` runs the
new steps.

The steps are V11 to V16, the next numbers after the V10 step #2187
added, because `SchemaMigratorTest` expects the step versions to have no
gaps. #2260 and #1781 also add a V11, so whichever of these merges
second needs to renumber its steps.

`uc_external_locations.url` is also `varchar(255)`, but it is not
widened here. It has the `idx_url` index on all three databases, and at
2048 characters that index would go over MySQL's 3,072 byte key limit
and PostgreSQL's 2,704 byte index entry limit, which
`MigrationStepRulesTest` refuses. Widening it needs a step that drops or
replaces the index, which the step rules don't allow yet, so it can
follow separately.

**Follow-up**

Location validation against the columns and the cloud limits moved to
its own PR, #2378, which builds on this one. A root that fits its column
can still be too long for the managed locations under it, and that PR
rejects such roots before they are stored.

**Testing**

`SdkManagedLocationTest.testStoragePathsLongerThan255Characters` creates
a 1,020 character catalog root and a 1,219 character schema root and
reads them back. It also creates managed volumes under each, then an
external volume and a model version source of exactly 2,048 characters,
which are read back. On main, each of these fails with a 500.
`SchemaMigratorTest` and `MigrationStepRulesTest` check the new steps on
H2, MySQL and PostgreSQL. `javafmtCheck`, `checkstyle` and
`Test/compile` pass for `server`. The Sdk tests can't start on Windows,
so they run on CI.

---------

Signed-off-by: Maha Rana Yadavalli <[email protected]>
Co-authored-by: Maha Rana Yadavalli <[email protected]>
@yili-db

yili-db commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@yili-db

yili-db commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

/review

- Add `TokenRevocationDAO` (`uc_token_revocations`, keyed by `jti`) and `TokenRevocationRepository` to record revoked tokens.
  - Cleanup of expired rows is single-flight and async.
  - If the cleanup cannot start, the next revocation starts it.
  - A row is kept for `RETENTION_GRACE` (2 days) past its expiry, since `expires_at` has no time zone.
- Add schema steps for H2, MySQL, and PostgreSQL, with their effect files:
  - `V22__create_token_revocations`
  - `V23__index_token_revocations_expires_at`
- On `/logout`, revoke the presented `ACCESS` token until its `exp`; `SERVICE` tokens are left untouched.
- Reject revoked tokens with 401 in `AuthDecorator` and in `grantToken`, so a logged-out token cannot be exchanged for a new one.
  - Re-check expiry after the revocation lookup, so a row purged during the lookup cannot let a revoked token through.
  - Only internal tokens have their `jti` checked; external tokens' `jti` is not parsed.
- Keep database messages out of the error responses of the auth lookup, `revoke`, and `isRevoked`.
- Treat a duplicate revoke as success when the row is present or the token has expired (its row may have been purged).
  - If the row cannot be read back after a failed insert, the insert's failure is thrown, with the read's failure attached.
- Document logout in `api/control.yaml` (and the generated `control.gen.ts`) and `docs/server/auth.md`.
- Ignore JaCoCo `*.exec` coverage files in `.gitignore`.
- Tests:
  - Add `TokenRevocationRepositoryTest`, on a per-test `@TempDatabase`.
  - Extend `AuthServiceTest` and `AuthDecoratorTest`.

Signed-off-by: Yi Li <[email protected]>
Co-authored-by: Isaac <[email protected]>
@yili-db

yili-db commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@yili-db
yili-db merged commit a25cec0 into unitycatalog:main Dec 2, 2026
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