Implement cleanup job for OAuth2 authorization grants

Add cleanup job that removes authorization grants older than 7 days.
Uses ULID cursor-based pagination for efficiency.

- Add cleanup method to OAuth2AuthorizationGrantRepository trait
- Add CleanupOAuthAuthorizationGrantsJob task
- Register handler and schedule to run hourly
This commit is contained in:
Quentin Gliech
2026-01-16 12:30:19 +01:00
parent 1b7fe64165
commit fc07a32a8c
6 changed files with 178 additions and 2 deletions

View File

@@ -0,0 +1,24 @@
{
"db_name": "PostgreSQL",
"query": "\n WITH to_delete AS (\n SELECT oauth2_authorization_grant_id\n FROM oauth2_authorization_grants\n WHERE ($1::uuid IS NULL OR oauth2_authorization_grant_id > $1)\n AND oauth2_authorization_grant_id <= $2\n ORDER BY oauth2_authorization_grant_id\n LIMIT $3\n )\n DELETE FROM oauth2_authorization_grants\n USING to_delete\n WHERE oauth2_authorization_grants.oauth2_authorization_grant_id = to_delete.oauth2_authorization_grant_id\n RETURNING oauth2_authorization_grants.oauth2_authorization_grant_id\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "oauth2_authorization_grant_id",
"type_info": "Uuid"
}
],
"parameters": {
"Left": [
"Uuid",
"Uuid",
"Int8"
]
},
"nullable": [
false
]
},
"hash": "d4bc51c30f1119ea9d117fb565ec554d63c8773040679a77e99ac3fa24cec71d"
}

View File

@@ -1,3 +1,4 @@
// Copyright 2025, 2026 Element Creations Ltd.
// Copyright 2024, 2025 New Vector Ltd.
// Copyright 2021-2024 The Matrix.org Foundation C.I.C.
//
@@ -448,4 +449,54 @@ impl OAuth2AuthorizationGrantRepository for PgOAuth2AuthorizationGrantRepository
Ok(grant)
}
#[tracing::instrument(
name = "db.oauth2_authorization_grant.cleanup",
skip_all,
fields(
db.query.text,
since = since.map(tracing::field::display),
until = %until,
limit = limit,
),
err,
)]
async fn cleanup(
&mut self,
since: Option<Ulid>,
until: Ulid,
limit: usize,
) -> Result<(usize, Option<Ulid>), Self::Error> {
// `MAX(uuid)` isn't a thing in Postgres, so we can't just re-select the
// deleted rows and do a MAX on the `oauth2_authorization_grant_id`.
// Instead, we do the aggregation on the client side, which is a little
// less efficient, but good enough.
let res = sqlx::query_scalar!(
r#"
WITH to_delete AS (
SELECT oauth2_authorization_grant_id
FROM oauth2_authorization_grants
WHERE ($1::uuid IS NULL OR oauth2_authorization_grant_id > $1)
AND oauth2_authorization_grant_id <= $2
ORDER BY oauth2_authorization_grant_id
LIMIT $3
)
DELETE FROM oauth2_authorization_grants
USING to_delete
WHERE oauth2_authorization_grants.oauth2_authorization_grant_id = to_delete.oauth2_authorization_grant_id
RETURNING oauth2_authorization_grants.oauth2_authorization_grant_id
"#,
since.map(Uuid::from),
Uuid::from(until),
i64::try_from(limit).unwrap_or(i64::MAX)
)
.traced()
.fetch_all(&mut *self.conn)
.await?;
let count = res.len();
let max_id = res.into_iter().max();
Ok((count, max_id.map(Ulid::from)))
}
}