Skip to content

Commit e7139a7

Browse files
rusackasaminghadersohiclaude
authored
fix(models): enforce one OAuth2 token per user+database (#42897)
Co-authored-by: Amin Ghadersohi <amin.ghadersohi@gmail.com> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 21ae918 commit e7139a7

6 files changed

Lines changed: 380 additions & 4 deletions

File tree

‎superset/commands/database/oauth2.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from typing import cast
2222
from uuid import UUID
2323

24+
from superset import db
2425
from superset.commands.base import BaseCommand
2526
from superset.commands.database.exceptions import DatabaseNotFoundError
2627
from superset.daos.database import DatabaseUserOAuth2TokensDAO
@@ -96,6 +97,11 @@ def run(self) -> DatabaseUserOAuth2Tokens:
9697
database_id=self._state["database_id"],
9798
):
9899
DatabaseUserOAuth2TokensDAO.delete([existing])
100+
# flush the delete before inserting the replacement -- the unit
101+
# of work otherwise emits INSERTs before DELETEs within a single
102+
# flush, which would trip the (user_id, database_id) unique
103+
# index below on the old row.
104+
db.session.flush()
99105

100106
# store tokens
101107
expiration = datetime.now() + timedelta(seconds=token_response["expires_in"])
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# Licensed to the Apache Software Foundation (ASF) under one
2+
# or more contributor license agreements. See the NOTICE file
3+
# distributed with this work for additional information
4+
# regarding copyright ownership. The ASF licenses this file
5+
# to you under the Apache License, Version 2.0 (the
6+
# "License"); you may not use this file except in compliance
7+
# with the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing,
12+
# software distributed under the License is distributed on an
13+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
# KIND, either express or implied. See the License for the
15+
# specific language governing permissions and limitations
16+
# under the License.
17+
"""Enforce one OAuth2 token per (user_id, database_id).
18+
19+
`OAuth2StoreTokenCommand` always deletes any existing token for a
20+
user+database pair before storing a new one, so the table is only ever
21+
meant to carry a single live row per pair -- but that invariant was only
22+
enforced in application code, via a plain (non-unique) lookup index. A
23+
race between two concurrent OAuth2 callbacks for the same user+database
24+
can leave duplicate rows behind, and nothing downstream picks a
25+
deterministic one of them. Flagged as a follow-up during review of #42211
26+
(which fixed an unrelated `purge_oauth2_tokens` filter bug on this same
27+
table).
28+
29+
Pre-flight: deletes any pre-existing duplicate rows, keeping the
30+
highest-id row per (user_id, database_id) pair, since
31+
`OAuth2StoreTokenCommand` always deletes-then-inserts and a higher id is
32+
therefore the more recently issued token.
33+
34+
Revision ID: da0e3f0081bf
35+
Revises: b8d2f4a6c901
36+
Create Date: 2026-08-07 09:00:00.000000
37+
38+
"""
39+
40+
import sqlalchemy as sa
41+
from alembic import op
42+
43+
from superset.migrations.shared.utils import create_index, drop_index
44+
45+
# revision identifiers, used by Alembic.
46+
revision: str = "da0e3f0081bf"
47+
down_revision: str = "b8d2f4a6c901"
48+
49+
TABLE_NAME = "database_user_oauth2_tokens"
50+
INDEX_NAME = "idx_user_id_database_id"
51+
# Temporary name for the unique index while it and the old non-unique index
52+
# briefly coexist -- see the comment in ``upgrade`` below.
53+
TMP_INDEX_NAME = "idx_user_id_database_id_tmp_unique"
54+
55+
56+
def upgrade() -> None:
57+
bind = op.get_bind()
58+
metadata = sa.MetaData()
59+
table = sa.Table(TABLE_NAME, metadata, autoload_with=bind)
60+
61+
# Find the highest id per (user_id, database_id) pair by reading into
62+
# Python first, rather than deleting via a subquery on the same table:
63+
# MySQL rejects a DELETE whose WHERE clause subqueries the target table
64+
# (error 1093).
65+
rows = bind.execute(
66+
sa.select(table.c.id, table.c.user_id, table.c.database_id)
67+
).fetchall()
68+
max_id_by_pair: dict[tuple[int, int], int] = {}
69+
for row in rows:
70+
pair = (row.user_id, row.database_id)
71+
if row.id > max_id_by_pair.get(pair, -1):
72+
max_id_by_pair[pair] = row.id
73+
keep_ids = set(max_id_by_pair.values())
74+
dupe_ids = [row.id for row in rows if row.id not in keep_ids]
75+
if dupe_ids:
76+
bind.execute(table.delete().where(table.c.id.in_(dupe_ids)))
77+
78+
# MySQL's InnoDB won't drop an index that's still needed to satisfy a
79+
# foreign key (error 1553) -- the existing (user_id, database_id) index
80+
# is the only one covering the `user_id` FK. Create the new unique
81+
# index (which covers the same leading column) before dropping the old
82+
# one, so an FK-satisfying index always exists, then swap it into its
83+
# final name.
84+
create_index(TABLE_NAME, TMP_INDEX_NAME, ["user_id", "database_id"], unique=True)
85+
drop_index(TABLE_NAME, INDEX_NAME)
86+
create_index(TABLE_NAME, INDEX_NAME, ["user_id", "database_id"], unique=True)
87+
drop_index(TABLE_NAME, TMP_INDEX_NAME)
88+
89+
90+
def downgrade() -> None:
91+
# The pre-flight dedupe above is not reversible -- any rows it removed
92+
# stay removed -- but that only ever discards rows that violated the
93+
# single-token-per-pair invariant the application already assumed.
94+
create_index(TABLE_NAME, TMP_INDEX_NAME, ["user_id", "database_id"])
95+
drop_index(TABLE_NAME, INDEX_NAME)
96+
create_index(TABLE_NAME, INDEX_NAME, ["user_id", "database_id"])
97+
drop_index(TABLE_NAME, TMP_INDEX_NAME)
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Licensed to the Apache Software Foundation (ASF) under one
2+
# or more contributor license agreements. See the NOTICE file
3+
# distributed with this work for additional information
4+
# regarding copyright ownership. The ASF licenses this file
5+
# to you under the Apache License, Version 2.0 (the
6+
# "License"); you may not use this file except in compliance
7+
# with the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing,
12+
# software distributed under the License is distributed on an
13+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
# KIND, either express or implied. See the License for the
15+
# specific language governing permissions and limitations
16+
# under the License.
17+
"""merge oauth2 token uniqueness with report_schedule include_cta
18+
19+
Revision ID: 1072de5ed955
20+
Revises: ('da0e3f0081bf', '2d6ad72e4af6')
21+
Create Date: 2026-08-15 01:39:00.000000
22+
23+
"""
24+
25+
# revision identifiers, used by Alembic.
26+
revision = "1072de5ed955"
27+
down_revision = ("da0e3f0081bf", "2d6ad72e4af6")
28+
29+
30+
def upgrade():
31+
pass
32+
33+
34+
def downgrade():
35+
pass

‎superset/models/core.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1607,7 +1607,9 @@ class DatabaseUserOAuth2Tokens(Model, AuditMixinNullable):
16071607
"""
16081608

16091609
__tablename__ = "database_user_oauth2_tokens"
1610-
__table_args__ = (sqla.Index("idx_user_id_database_id", "user_id", "database_id"),)
1610+
__table_args__ = (
1611+
sqla.Index("idx_user_id_database_id", "user_id", "database_id", unique=True),
1612+
)
16111613

16121614
id = Column(Integer, primary_key=True)
16131615

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
# Licensed to the Apache Software Foundation (ASF) under one
2+
# or more contributor license agreements. See the NOTICE file
3+
# distributed with this work for additional information
4+
# regarding copyright ownership. The ASF licenses this file
5+
# to you under the Apache License, Version 2.0 (the
6+
# "License"); you may not use this file except in compliance
7+
# with the License. You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing,
12+
# software distributed under the License is distributed on an
13+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
# KIND, either express or implied. See the License for the
15+
# specific language governing permissions and limitations
16+
# under the License.
17+
"""Tests for migration ``da0e3f0081bf_enforce_oauth2_token_uniqueness``.
18+
19+
Runs the migration's ``upgrade()`` and ``downgrade()`` against an
20+
in-memory SQLite engine seeded with pre-existing duplicate
21+
(user_id, database_id) rows -- the state a deployment could be in today,
22+
since the prior plain index never stopped them from accumulating.
23+
"""
24+
25+
from __future__ import annotations
26+
27+
from importlib import import_module
28+
29+
import pytest
30+
from alembic.migration import MigrationContext
31+
from alembic.operations import Operations
32+
from sqlalchemy import (
33+
Column,
34+
create_engine,
35+
inspect,
36+
Integer,
37+
MetaData,
38+
select,
39+
Table,
40+
)
41+
from sqlalchemy.engine import Engine
42+
from sqlalchemy.exc import IntegrityError
43+
44+
migration = import_module(
45+
"superset.migrations.versions."
46+
"2026-08-07_09-00_da0e3f0081bf_enforce_oauth2_token_uniqueness"
47+
)
48+
49+
TABLE_NAME: str = migration.TABLE_NAME # "database_user_oauth2_tokens"
50+
INDEX_NAME: str = migration.INDEX_NAME # "idx_user_id_database_id"
51+
52+
53+
@pytest.fixture
54+
def engine() -> Engine:
55+
"""In-memory SQLite seeded with a minimal pre-migration token table,
56+
including duplicate (user_id, database_id) rows -- id 2 and id 3 both
57+
belong to user 1 + database 10, which the plain index never prevented.
58+
"""
59+
engine = create_engine("sqlite:///:memory:", future=True)
60+
md = MetaData()
61+
table = Table(
62+
TABLE_NAME,
63+
md,
64+
Column("id", Integer, primary_key=True),
65+
Column("user_id", Integer, nullable=False),
66+
Column("database_id", Integer, nullable=False),
67+
)
68+
md.create_all(engine)
69+
70+
with engine.begin() as conn:
71+
conn.execute(
72+
table.insert(),
73+
[
74+
{"id": 1, "user_id": 1, "database_id": 20},
75+
{"id": 2, "user_id": 1, "database_id": 10},
76+
{"id": 3, "user_id": 1, "database_id": 10},
77+
{"id": 4, "user_id": 2, "database_id": 10},
78+
],
79+
)
80+
81+
return engine
82+
83+
84+
def _indexes(engine: Engine) -> dict[str, bool]:
85+
"""Map of index name -> ``unique`` flag on the target table."""
86+
return {ix["name"]: ix["unique"] for ix in inspect(engine).get_indexes(TABLE_NAME)}
87+
88+
89+
def _rows(engine: Engine) -> list[tuple[int, int, int]]:
90+
with engine.begin() as conn:
91+
table = Table(TABLE_NAME, MetaData(), autoload_with=conn)
92+
return sorted(
93+
(r.id, r.user_id, r.database_id)
94+
for r in conn.execute(select(table)).fetchall()
95+
)
96+
97+
98+
def test_upgrade_deletes_duplicates_keeping_highest_id(engine: Engine) -> None:
99+
"""Only the highest-id row survives per (user_id, database_id) pair;
100+
unrelated pairs are untouched.
101+
"""
102+
with engine.begin() as conn:
103+
ctx = MigrationContext.configure(conn)
104+
with Operations.context(ctx):
105+
migration.upgrade()
106+
107+
assert _rows(engine) == [
108+
(1, 1, 20),
109+
(3, 1, 10),
110+
(4, 2, 10),
111+
], "upgrade() must keep only the highest-id row per duplicate pair"
112+
113+
114+
def test_upgrade_makes_the_index_unique(engine: Engine) -> None:
115+
"""upgrade() replaces the plain lookup index with a unique one."""
116+
with engine.begin() as conn:
117+
ctx = MigrationContext.configure(conn)
118+
with Operations.context(ctx):
119+
migration.upgrade()
120+
121+
assert _indexes(engine) == {INDEX_NAME: True}
122+
123+
124+
def test_upgrade_index_rejects_new_duplicates(engine: Engine) -> None:
125+
"""After upgrade(), inserting a second row for an existing
126+
(user_id, database_id) pair is rejected at the DB level.
127+
"""
128+
with engine.begin() as conn:
129+
ctx = MigrationContext.configure(conn)
130+
with Operations.context(ctx):
131+
migration.upgrade()
132+
133+
table = Table(TABLE_NAME, MetaData(), autoload_with=engine)
134+
with pytest.raises(IntegrityError):
135+
with engine.begin() as conn:
136+
conn.execute(table.insert().values(id=99, user_id=1, database_id=20))
137+
138+
139+
def test_downgrade_restores_a_plain_non_unique_index(engine: Engine) -> None:
140+
"""downgrade() drops the unique index and recreates a plain one --
141+
the dedupe deletions from upgrade() are not reversed, since those rows
142+
already violated the single-token-per-pair invariant the application
143+
assumed.
144+
"""
145+
with engine.begin() as conn:
146+
ctx = MigrationContext.configure(conn)
147+
with Operations.context(ctx):
148+
migration.upgrade()
149+
migration.downgrade()
150+
151+
assert _indexes(engine) == {INDEX_NAME: False}
152+
assert _rows(engine) == [
153+
(1, 1, 20),
154+
(3, 1, 10),
155+
(4, 2, 10),
156+
]
157+
158+
# Now that the index is plain again, duplicates are allowed once more.
159+
table = Table(TABLE_NAME, MetaData(), autoload_with=engine)
160+
with engine.begin() as conn:
161+
conn.execute(table.insert().values(id=99, user_id=1, database_id=20))
162+
assert (99, 1, 20) in _rows(engine)
163+
164+
165+
def test_upgrade_is_idempotent(engine: Engine) -> None:
166+
"""``create_index``/``drop_index`` are skip-if-exists; running
167+
``upgrade()`` twice must not raise.
168+
"""
169+
with engine.begin() as conn:
170+
ctx = MigrationContext.configure(conn)
171+
with Operations.context(ctx):
172+
migration.upgrade()
173+
migration.upgrade()

0 commit comments

Comments
 (0)