authentik.providers.oauth2.migrations.0039_refresh_token_hash_family

Hash refresh tokens at rest and add refresh token families.

This migration is written by hand, as the auto-generated version would be unsafe:

  • The plaintext token column is kept (as legacy_token, same column) instead of being dropped, and new tokens still write it. The previous version looks tokens up by it, without guarding against a missing token (token=None, which matches every row without a plaintext). So during a rolling upgrade, or after rolling the image back, the previous version finds the tokens issued by this one, and never matches one when it looks up a missing token. It ignores the new columns, which are nullable and have no database default. It is made nullable for a future release, which will stop writing it, hash and clear the remaining tokens, and then drop it.
  • family is added without a default. Adding it with default=uuid4 would put every existing token into the same family, so that any reuse would revoke all refresh tokens.

Existing tokens are deliberately not backfilled. This migration holds an exclusive lock on the refresh token table, so instances still running the previous version can't refresh tokens until it commits. In a local benchmark with 5M refresh tokens, a backfill (hashing every token and assigning each a family) held that lock for 66s and wrote 20GB of WAL. Without it, only the index builds remain. A backfill isn't needed either:

  • Lookups fall back to the plaintext column, and RefreshToken.save() hashes an existing token the next time it is saved.
  • A backfilled family would only ever contain the token itself, as previous versions didn't record which token was rotated from which. A family is started when an existing token is first refreshed instead.
  • Expired tokens are deleted by clean_expired_models.
  1"""Hash refresh tokens at rest and add refresh token families.
  2
  3This migration is written by hand, as the auto-generated version would be unsafe:
  4
  5- The plaintext `token` column is kept (as `legacy_token`, same column) instead of being
  6  dropped, and new tokens still write it. The previous version looks tokens up by it, without
  7  guarding against a missing token (`token=None`, which matches every row without a
  8  plaintext). So during a rolling upgrade, or after rolling the image back, the previous
  9  version finds the tokens issued by this one, and never matches one when it looks up a missing
 10  token. It ignores the new columns, which are nullable and have no database default. It is
 11  made nullable for a future release, which will stop writing it, hash and clear the remaining
 12  tokens, and then drop it.
 13- `family` is added without a default. Adding it with `default=uuid4` would put every existing
 14  token into the same family, so that any reuse would revoke all refresh tokens.
 15
 16Existing tokens are deliberately not backfilled. This migration holds an exclusive lock on the
 17refresh token table, so instances still running the previous version can't refresh tokens
 18until it commits. In a local benchmark with 5M refresh tokens, a backfill (hashing every token
 19and assigning each a family) held that lock for 66s and wrote 20GB of WAL. Without it, only the
 20index builds remain. A backfill isn't needed either:
 21
 22- Lookups fall back to the plaintext column, and `RefreshToken.save()` hashes an existing token
 23  the next time it is saved.
 24- A backfilled family would only ever contain the token itself, as previous versions didn't
 25  record which token was rotated from which. A family is started when an existing token is
 26  first refreshed instead.
 27- Expired tokens are deleted by `clean_expired_models`.
 28"""
 29
 30import uuid
 31
 32import django.contrib.postgres.indexes
 33from django.db import migrations, models
 34
 35import authentik.lib.utils.time
 36
 37
 38class Migration(migrations.Migration):
 39
 40    dependencies = [
 41        ("authentik_providers_oauth2", "0038_oauth2sessionlogin"),
 42    ]
 43
 44    operations = [
 45        # Rename `token` to `legacy_token` without touching the column, and make it nullable
 46        migrations.SeparateDatabaseAndState(
 47            state_operations=[
 48                migrations.RemoveIndex(
 49                    model_name="refreshtoken",
 50                    name="authentik_p_token_32e2b7_hash",
 51                ),
 52                migrations.RenameField(
 53                    model_name="refreshtoken",
 54                    old_name="token",
 55                    new_name="legacy_token",
 56                ),
 57                migrations.AlterField(
 58                    model_name="refreshtoken",
 59                    name="legacy_token",
 60                    field=models.TextField(db_column="token", default=None, null=True),
 61                ),
 62                migrations.AddIndex(
 63                    model_name="refreshtoken",
 64                    index=django.contrib.postgres.indexes.HashIndex(
 65                        fields=["legacy_token"], name="authentik_p_token_32e2b7_hash"
 66                    ),
 67                ),
 68            ],
 69            database_operations=[
 70                migrations.AlterField(
 71                    model_name="refreshtoken",
 72                    name="token",
 73                    field=models.TextField(default=None, null=True),
 74                ),
 75            ],
 76        ),
 77        migrations.AddField(
 78            model_name="refreshtoken",
 79            name="token_hash",
 80            field=models.TextField(default=None, null=True),
 81        ),
 82        migrations.AddField(
 83            model_name="refreshtoken",
 84            name="family",
 85            field=models.UUIDField(default=None, null=True),
 86        ),
 87        migrations.AddField(
 88            model_name="refreshtoken",
 89            name="rotated_at",
 90            field=models.DateTimeField(default=None, null=True),
 91        ),
 92        # Existing tokens have no family, only index the ones that do
 93        migrations.AddIndex(
 94            model_name="refreshtoken",
 95            index=models.Index(
 96                condition=models.Q(("family__isnull", False)),
 97                fields=["family"],
 98                name="authentik_p_rt_family_idx",
 99            ),
100        ),
101        # Only new tokens get a family by default, so this doesn't change existing rows
102        migrations.AlterField(
103            model_name="refreshtoken",
104            name="family",
105            field=models.UUIDField(default=uuid.uuid4, null=True),
106        ),
107        migrations.AddIndex(
108            model_name="refreshtoken",
109            index=django.contrib.postgres.indexes.HashIndex(
110                fields=["token_hash"], name="authentik_p_token_h_51a65d_hash"
111            ),
112        ),
113        # `token_hash` has no planner statistics yet. Without them, a lookup by token is
114        # estimated to match many rows, and `.first()` (ORDER BY id LIMIT 1) is planned as a
115        # walk of the primary key instead of an index lookup. In a local benchmark with 1M
116        # refresh tokens, that made looking up a new or unknown token take ~250ms instead of
117        # ~0.02ms until autovacuum analyzed the table. ANALYZE only samples the table, so it
118        # is fast.
119        migrations.RunSQL(
120            "ANALYZE authentik_providers_oauth2_refreshtoken", reverse_sql=migrations.RunSQL.noop
121        ),
122        # Existing providers keep the previous behavior (reuse is only logged), new providers
123        # revoke the family on reuse. The columns keep a database default so that instances
124        # still running the previous version can insert providers during a rolling upgrade.
125        migrations.AddField(
126            model_name="oauth2provider",
127            name="refresh_token_revoke_family_on_reuse",
128            field=models.BooleanField(
129                default=False,
130                db_default=False,
131                help_text=(
132                    "When a refresh token which has already been rotated is used again, revoke "
133                    "all refresh and access tokens issued from the same authorization. Reuse "
134                    "indicates that the token may have been stolen."
135                ),
136            ),
137        ),
138        migrations.AlterField(
139            model_name="oauth2provider",
140            name="refresh_token_revoke_family_on_reuse",
141            field=models.BooleanField(
142                default=True,
143                db_default=True,
144                help_text=(
145                    "When a refresh token which has already been rotated is used again, revoke "
146                    "all refresh and access tokens issued from the same authorization. Reuse "
147                    "indicates that the token may have been stolen."
148                ),
149            ),
150        ),
151        migrations.AddField(
152            model_name="oauth2provider",
153            name="refresh_token_reuse_grace_period",
154            field=models.TextField(
155                default="seconds=30",
156                db_default="seconds=30",
157                help_text=(
158                    "Allow the most recently rotated refresh token to be used again for this "
159                    "duration without revoking its family, for clients which retry or send "
160                    "concurrent refresh requests. Only applies when revoking the family on reuse "
161                    "is enabled. (Format: hours=1;minutes=2;seconds=3)."
162                ),
163                validators=[authentik.lib.utils.time.timedelta_string_validator],
164            ),
165        ),
166    ]
class Migration(django.db.migrations.migration.Migration):
 39class Migration(migrations.Migration):
 40
 41    dependencies = [
 42        ("authentik_providers_oauth2", "0038_oauth2sessionlogin"),
 43    ]
 44
 45    operations = [
 46        # Rename `token` to `legacy_token` without touching the column, and make it nullable
 47        migrations.SeparateDatabaseAndState(
 48            state_operations=[
 49                migrations.RemoveIndex(
 50                    model_name="refreshtoken",
 51                    name="authentik_p_token_32e2b7_hash",
 52                ),
 53                migrations.RenameField(
 54                    model_name="refreshtoken",
 55                    old_name="token",
 56                    new_name="legacy_token",
 57                ),
 58                migrations.AlterField(
 59                    model_name="refreshtoken",
 60                    name="legacy_token",
 61                    field=models.TextField(db_column="token", default=None, null=True),
 62                ),
 63                migrations.AddIndex(
 64                    model_name="refreshtoken",
 65                    index=django.contrib.postgres.indexes.HashIndex(
 66                        fields=["legacy_token"], name="authentik_p_token_32e2b7_hash"
 67                    ),
 68                ),
 69            ],
 70            database_operations=[
 71                migrations.AlterField(
 72                    model_name="refreshtoken",
 73                    name="token",
 74                    field=models.TextField(default=None, null=True),
 75                ),
 76            ],
 77        ),
 78        migrations.AddField(
 79            model_name="refreshtoken",
 80            name="token_hash",
 81            field=models.TextField(default=None, null=True),
 82        ),
 83        migrations.AddField(
 84            model_name="refreshtoken",
 85            name="family",
 86            field=models.UUIDField(default=None, null=True),
 87        ),
 88        migrations.AddField(
 89            model_name="refreshtoken",
 90            name="rotated_at",
 91            field=models.DateTimeField(default=None, null=True),
 92        ),
 93        # Existing tokens have no family, only index the ones that do
 94        migrations.AddIndex(
 95            model_name="refreshtoken",
 96            index=models.Index(
 97                condition=models.Q(("family__isnull", False)),
 98                fields=["family"],
 99                name="authentik_p_rt_family_idx",
100            ),
101        ),
102        # Only new tokens get a family by default, so this doesn't change existing rows
103        migrations.AlterField(
104            model_name="refreshtoken",
105            name="family",
106            field=models.UUIDField(default=uuid.uuid4, null=True),
107        ),
108        migrations.AddIndex(
109            model_name="refreshtoken",
110            index=django.contrib.postgres.indexes.HashIndex(
111                fields=["token_hash"], name="authentik_p_token_h_51a65d_hash"
112            ),
113        ),
114        # `token_hash` has no planner statistics yet. Without them, a lookup by token is
115        # estimated to match many rows, and `.first()` (ORDER BY id LIMIT 1) is planned as a
116        # walk of the primary key instead of an index lookup. In a local benchmark with 1M
117        # refresh tokens, that made looking up a new or unknown token take ~250ms instead of
118        # ~0.02ms until autovacuum analyzed the table. ANALYZE only samples the table, so it
119        # is fast.
120        migrations.RunSQL(
121            "ANALYZE authentik_providers_oauth2_refreshtoken", reverse_sql=migrations.RunSQL.noop
122        ),
123        # Existing providers keep the previous behavior (reuse is only logged), new providers
124        # revoke the family on reuse. The columns keep a database default so that instances
125        # still running the previous version can insert providers during a rolling upgrade.
126        migrations.AddField(
127            model_name="oauth2provider",
128            name="refresh_token_revoke_family_on_reuse",
129            field=models.BooleanField(
130                default=False,
131                db_default=False,
132                help_text=(
133                    "When a refresh token which has already been rotated is used again, revoke "
134                    "all refresh and access tokens issued from the same authorization. Reuse "
135                    "indicates that the token may have been stolen."
136                ),
137            ),
138        ),
139        migrations.AlterField(
140            model_name="oauth2provider",
141            name="refresh_token_revoke_family_on_reuse",
142            field=models.BooleanField(
143                default=True,
144                db_default=True,
145                help_text=(
146                    "When a refresh token which has already been rotated is used again, revoke "
147                    "all refresh and access tokens issued from the same authorization. Reuse "
148                    "indicates that the token may have been stolen."
149                ),
150            ),
151        ),
152        migrations.AddField(
153            model_name="oauth2provider",
154            name="refresh_token_reuse_grace_period",
155            field=models.TextField(
156                default="seconds=30",
157                db_default="seconds=30",
158                help_text=(
159                    "Allow the most recently rotated refresh token to be used again for this "
160                    "duration without revoking its family, for clients which retry or send "
161                    "concurrent refresh requests. Only applies when revoking the family on reuse "
162                    "is enabled. (Format: hours=1;minutes=2;seconds=3)."
163                ),
164                validators=[authentik.lib.utils.time.timedelta_string_validator],
165            ),
166        ),
167    ]

The base class for all migrations.

Migration files will import this from django.db.migrations.Migration and subclass it as a class called Migration. It will have one or more of the following attributes:

  • operations: A list of Operation instances, probably from django.db.migrations.operations
  • dependencies: A list of tuples of (app_path, migration_name)
  • run_before: A list of tuples of (app_path, migration_name)
  • replaces: A list of migration_names

Note that all migrations come out of migrations and into the Loader or Graph as instances, having been initialized with their app label and name.

dependencies = [('authentik_providers_oauth2', '0038_oauth2sessionlogin')]
operations = [<SeparateDatabaseAndState state_operations=[<RemoveIndex model_name='refreshtoken', name='authentik_p_token_32e2b7_hash'>, <RenameField model_name='refreshtoken', old_name='token', new_name='legacy_token'>, <AlterField model_name='refreshtoken', name='legacy_token', field=<django.db.models.fields.TextField>>, <AddIndex model_name='refreshtoken', index=<HashIndex: fields=['legacy_token'] name='authentik_p_token_32e2b7_hash'>>], database_operations=[<AlterField model_name='refreshtoken', name='token', field=<django.db.models.fields.TextField>>]>, <AddField model_name='refreshtoken', name='token_hash', field=<django.db.models.fields.TextField>>, <AddField model_name='refreshtoken', name='family', field=<django.db.models.fields.UUIDField>>, <AddField model_name='refreshtoken', name='rotated_at', field=<django.db.models.fields.DateTimeField>>, <AddIndex model_name='refreshtoken', index=<Index: fields=['family'] name='authentik_p_rt_family_idx' condition=(AND: ('family__isnull', False))>>, <AlterField model_name='refreshtoken', name='family', field=<django.db.models.fields.UUIDField>>, <AddIndex model_name='refreshtoken', index=<HashIndex: fields=['token_hash'] name='authentik_p_token_h_51a65d_hash'>>, <RunSQL 'ANALYZE authentik_providers_oauth2_refreshtoken' reverse_sql=''>, <AddField model_name='oauth2provider', name='refresh_token_revoke_family_on_reuse', field=<django.db.models.fields.BooleanField>>, <AlterField model_name='oauth2provider', name='refresh_token_revoke_family_on_reuse', field=<django.db.models.fields.BooleanField>>, <AddField model_name='oauth2provider', name='refresh_token_reuse_grace_period', field=<django.db.models.fields.TextField>>]