Repository navigation
[Server] Invalidate access tokens on logout - #1781
Conversation
| Date expiresAt = | ||
| decodedJWT.getExpiresAt() != null | ||
| ? decodedJWT.getExpiresAt() | ||
| : Date.from(Instant.now().plus(serverProperties.getAccessTokenTimeout())); |
There was a problem hiding this comment.
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();| 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); | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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;
}There was a problem hiding this comment.
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.
c19252d to
045a251
Compare
|
@yili-db there is a conflict |
|
@yili-db bump on the merge conflict here |
045a251 to
b8bb530
Compare
@timothyw553 Rebased. PTAL |
|
/review |
timothyw553
left a comment
There was a problem hiding this comment.
two small comments.
| if (tokenRevocationRepository.isRevoked(session, jti)) { | ||
| throw new AuthorizationException( | ||
| ErrorCode.PERMISSION_DENIED, "Access token has been revoked."); |
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
[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); |
There was a problem hiding this comment.
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.
| if (tokenRevocationRepository.isRevoked(session, jti)) { | ||
| throw new AuthorizationException( | ||
| ErrorCode.UNAUTHENTICATED, "Access token has been revoked."); | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| TransactionManager.executeWithTransaction( | ||
| sessionFactory, | ||
| session -> { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| if (!isRevoked(jti)) { | ||
| throw e; | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
and please rebase. |
d997360 to
fce5f08
Compare
|
/review |
timothyw553
left a comment
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
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)) { |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
fce5f08 to
6ba71f5
Compare
|
/review |
timothyw553
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Approving -- feel free to merge once you have addressed my last comment and fixed the merge conflict.
eafa45c to
07a9979
Compare
|
/review |
9c053a4 to
cb8cc71
Compare
|
/review |
**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]>
|
/review |
|
/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]>
|
/review |
PR Checklist
docsis updatedDescription of changes
TokenRevocationDAO(uc_token_revocations, keyed byjti) andTokenRevocationRepositoryto record revoked tokens.RETENTION_GRACE(2 days) past its expiry, sinceexpires_athas no time zone.V22__create_token_revocationsV23__index_token_revocations_expires_at/logout, revoke the presentedACCESStoken until itsexp;SERVICEtokens are left untouched.AuthDecoratorand ingrantToken, so a logged-out token cannot be exchanged for a new one.jtichecked; external tokens'jtiis not parsed.revoke, andisRevoked.api/control.yaml(and the generatedcontrol.gen.ts) anddocs/server/auth.md.*.execcoverage files in.gitignore.TokenRevocationRepositoryTest, on a per-test@TempDatabase.AuthServiceTestandAuthDecoratorTest.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.pyUC_TEST_DATABASEset toH2,POSTGRES_18, andMYSQL_8, withUC_TEST_MIGRATION_CHECKS=trueThis pull request and its description were written by Isaac.