authentik.providers.rac.migrations.0009_rac_devices

  1# Move RAC endpoints into the endpoint device inventory
  2
  3import django.db.models.deletion
  4from django.apps.registry import Apps
  5from django.db import migrations, models
  6from django.db.backends.base.schema import BaseDatabaseSchemaEditor
  7
  8
  9def migrate_endpoints_to_devices(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
 10    """Convert every RAC endpoint into a device.
 11
 12    The device re-uses the endpoint's primary key as its `device_uuid`, and the
 13    endpoint's host and protocol become a connection override for the device."""
 14    db_alias = schema_editor.connection.alias
 15    Endpoint = apps.get_model("authentik_providers_rac", "Endpoint")
 16    ConnectionToken = apps.get_model("authentik_providers_rac", "ConnectionToken")
 17    RACConnectionOverride = apps.get_model("authentik_providers_rac", "RACConnectionOverride")
 18    Device = apps.get_model("authentik_endpoints", "Device")
 19    PolicyBinding = apps.get_model("authentik_policies", "PolicyBinding")
 20
 21    # Connection tokens are bound to a single browser session and are re-created on the
 22    # next launch, so they're dropped instead of migrated.
 23    ConnectionToken.objects.using(db_alias).all().delete()
 24
 25    # Device names are unique, endpoint names are not
 26    taken_names = set(Device.objects.using(db_alias).values_list("name", flat=True))
 27
 28    def unique_name(endpoint) -> str:
 29        name = endpoint.name
 30        if name in taken_names:
 31            name = f"{endpoint.name} ({endpoint.provider.name})"
 32        base = name
 33        suffix = 2
 34        while name in taken_names:
 35            name = f"{base} {suffix}"
 36            suffix += 1
 37        taken_names.add(name)
 38        return name
 39
 40    for endpoint in Endpoint.objects.using(db_alias).select_related("provider").iterator():
 41        device = Device.objects.using(db_alias).create(
 42            device_uuid=endpoint.pk,
 43            name=unique_name(endpoint),
 44            identifier=f"rac://{endpoint.pk}",
 45            expiring=False,
 46            policy_engine_mode=endpoint.policy_engine_mode,
 47        )
 48        RACConnectionOverride.objects.using(db_alias).create(
 49            device=device,
 50            host=endpoint.host,
 51            protocol=endpoint.protocol,
 52        )
 53        # Policies bound to the endpoint now apply to the device
 54        PolicyBinding.objects.using(db_alias).filter(target_id=endpoint.pk).update(
 55            target_id=device.pbm_uuid
 56        )
 57
 58    # Deleting the endpoints also removes their policy binding model rows
 59    Endpoint.objects.using(db_alias).all().delete()
 60    # The deletes above queue deferred FK-constraint triggers on `endpoint`; the RemoveField
 61    # operations later in this migration ALTER that same table, which Postgres refuses to do
 62    # while those triggers are still pending in the same transaction
 63    schema_editor.execute("SET CONSTRAINTS ALL IMMEDIATE")
 64
 65
 66def remove_endpoint_permissions(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
 67    """Remove permissions (and object-level permissions) of the removed models"""
 68    db_alias = schema_editor.connection.alias
 69    ContentType = apps.get_model("contenttypes", "ContentType")
 70    ContentType.objects.using(db_alias).filter(
 71        app_label="authentik_providers_rac",
 72        model__in=["endpoint", "endpointpropertymapping"],
 73    ).delete()
 74
 75
 76class Migration(migrations.Migration):
 77
 78    dependencies = [
 79        ("authentik_endpoints", "0005_alter_deviceuserbinding_managers"),
 80        ("authentik_policies", "0011_policybinding_failure_result_and_more"),
 81        ("authentik_providers_rac", "0008_endpointpropertymapping_and_more"),
 82        ("contenttypes", "0002_remove_content_type_name"),
 83    ]
 84
 85    operations = [
 86        migrations.AddField(
 87            model_name="racprovider",
 88            name="maximum_connections",
 89            field=models.IntegerField(
 90                default=1,
 91                help_text=(
 92                    "Maximum concurrent connections to a single device. Can be set to -1 to "
 93                    "disable the limit."
 94                ),
 95            ),
 96        ),
 97        migrations.AddField(
 98            model_name="racprovider",
 99            name="access_group",
100            field=models.ForeignKey(
101                blank=True,
102                default=None,
103                help_text=(
104                    "Only devices in this access group can be accessed through this provider. "
105                    "When left empty, every device the user has access to can be accessed."
106                ),
107                null=True,
108                on_delete=django.db.models.deletion.SET_DEFAULT,
109                to="authentik_endpoints.deviceaccessgroup",
110            ),
111        ),
112        migrations.CreateModel(
113            name="RACConnectionOverride",
114            fields=[
115                (
116                    "id",
117                    models.AutoField(
118                        auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
119                    ),
120                ),
121                (
122                    "host",
123                    models.TextField(
124                        help_text="Hostname/IP to connect to. Optionally specify the port."
125                    ),
126                ),
127                (
128                    "protocol",
129                    models.TextField(choices=[("rdp", "Rdp"), ("vnc", "Vnc"), ("ssh", "Ssh")]),
130                ),
131                (
132                    "device",
133                    models.OneToOneField(
134                        on_delete=django.db.models.deletion.CASCADE,
135                        related_name="rac_override",
136                        to="authentik_endpoints.device",
137                    ),
138                ),
139            ],
140            options={
141                "verbose_name": "RAC Connection override",
142                "verbose_name_plural": "RAC Connection overrides",
143            },
144        ),
145        migrations.RunPython(migrate_endpoints_to_devices, migrations.RunPython.noop),
146        migrations.RemoveField(
147            model_name="connectiontoken",
148            name="endpoint",
149        ),
150        migrations.AddField(
151            model_name="connectiontoken",
152            name="protocol",
153            # All connection tokens are deleted above, so the column can be added as
154            # non-nullable without a default
155            field=models.TextField(choices=[("rdp", "Rdp"), ("vnc", "Vnc"), ("ssh", "Ssh")]),
156        ),
157        migrations.AddField(
158            model_name="connectiontoken",
159            name="device",
160            field=models.ForeignKey(
161                on_delete=django.db.models.deletion.CASCADE,
162                to="authentik_endpoints.device",
163            ),
164        ),
165        migrations.RemoveField(
166            model_name="endpointpropertymapping",
167            name="endpoint",
168        ),
169        migrations.RemoveField(
170            model_name="endpointpropertymapping",
171            name="property_mapping",
172        ),
173        migrations.RemoveField(
174            model_name="endpoint",
175            name="property_mappings",
176        ),
177        migrations.RemoveField(
178            model_name="endpoint",
179            name="provider",
180        ),
181        migrations.DeleteModel(
182            name="EndpointPropertyMapping",
183        ),
184        migrations.DeleteModel(
185            name="Endpoint",
186        ),
187        migrations.RunPython(remove_endpoint_permissions, migrations.RunPython.noop),
188    ]
def migrate_endpoints_to_devices( apps: django.apps.registry.Apps, schema_editor: django.db.backends.base.schema.BaseDatabaseSchemaEditor):
10def migrate_endpoints_to_devices(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
11    """Convert every RAC endpoint into a device.
12
13    The device re-uses the endpoint's primary key as its `device_uuid`, and the
14    endpoint's host and protocol become a connection override for the device."""
15    db_alias = schema_editor.connection.alias
16    Endpoint = apps.get_model("authentik_providers_rac", "Endpoint")
17    ConnectionToken = apps.get_model("authentik_providers_rac", "ConnectionToken")
18    RACConnectionOverride = apps.get_model("authentik_providers_rac", "RACConnectionOverride")
19    Device = apps.get_model("authentik_endpoints", "Device")
20    PolicyBinding = apps.get_model("authentik_policies", "PolicyBinding")
21
22    # Connection tokens are bound to a single browser session and are re-created on the
23    # next launch, so they're dropped instead of migrated.
24    ConnectionToken.objects.using(db_alias).all().delete()
25
26    # Device names are unique, endpoint names are not
27    taken_names = set(Device.objects.using(db_alias).values_list("name", flat=True))
28
29    def unique_name(endpoint) -> str:
30        name = endpoint.name
31        if name in taken_names:
32            name = f"{endpoint.name} ({endpoint.provider.name})"
33        base = name
34        suffix = 2
35        while name in taken_names:
36            name = f"{base} {suffix}"
37            suffix += 1
38        taken_names.add(name)
39        return name
40
41    for endpoint in Endpoint.objects.using(db_alias).select_related("provider").iterator():
42        device = Device.objects.using(db_alias).create(
43            device_uuid=endpoint.pk,
44            name=unique_name(endpoint),
45            identifier=f"rac://{endpoint.pk}",
46            expiring=False,
47            policy_engine_mode=endpoint.policy_engine_mode,
48        )
49        RACConnectionOverride.objects.using(db_alias).create(
50            device=device,
51            host=endpoint.host,
52            protocol=endpoint.protocol,
53        )
54        # Policies bound to the endpoint now apply to the device
55        PolicyBinding.objects.using(db_alias).filter(target_id=endpoint.pk).update(
56            target_id=device.pbm_uuid
57        )
58
59    # Deleting the endpoints also removes their policy binding model rows
60    Endpoint.objects.using(db_alias).all().delete()
61    # The deletes above queue deferred FK-constraint triggers on `endpoint`; the RemoveField
62    # operations later in this migration ALTER that same table, which Postgres refuses to do
63    # while those triggers are still pending in the same transaction
64    schema_editor.execute("SET CONSTRAINTS ALL IMMEDIATE")

Convert every RAC endpoint into a device.

The device re-uses the endpoint's primary key as its device_uuid, and the endpoint's host and protocol become a connection override for the device.

def remove_endpoint_permissions( apps: django.apps.registry.Apps, schema_editor: django.db.backends.base.schema.BaseDatabaseSchemaEditor):
67def remove_endpoint_permissions(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
68    """Remove permissions (and object-level permissions) of the removed models"""
69    db_alias = schema_editor.connection.alias
70    ContentType = apps.get_model("contenttypes", "ContentType")
71    ContentType.objects.using(db_alias).filter(
72        app_label="authentik_providers_rac",
73        model__in=["endpoint", "endpointpropertymapping"],
74    ).delete()

Remove permissions (and object-level permissions) of the removed models

class Migration(django.db.migrations.migration.Migration):
 77class Migration(migrations.Migration):
 78
 79    dependencies = [
 80        ("authentik_endpoints", "0005_alter_deviceuserbinding_managers"),
 81        ("authentik_policies", "0011_policybinding_failure_result_and_more"),
 82        ("authentik_providers_rac", "0008_endpointpropertymapping_and_more"),
 83        ("contenttypes", "0002_remove_content_type_name"),
 84    ]
 85
 86    operations = [
 87        migrations.AddField(
 88            model_name="racprovider",
 89            name="maximum_connections",
 90            field=models.IntegerField(
 91                default=1,
 92                help_text=(
 93                    "Maximum concurrent connections to a single device. Can be set to -1 to "
 94                    "disable the limit."
 95                ),
 96            ),
 97        ),
 98        migrations.AddField(
 99            model_name="racprovider",
100            name="access_group",
101            field=models.ForeignKey(
102                blank=True,
103                default=None,
104                help_text=(
105                    "Only devices in this access group can be accessed through this provider. "
106                    "When left empty, every device the user has access to can be accessed."
107                ),
108                null=True,
109                on_delete=django.db.models.deletion.SET_DEFAULT,
110                to="authentik_endpoints.deviceaccessgroup",
111            ),
112        ),
113        migrations.CreateModel(
114            name="RACConnectionOverride",
115            fields=[
116                (
117                    "id",
118                    models.AutoField(
119                        auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
120                    ),
121                ),
122                (
123                    "host",
124                    models.TextField(
125                        help_text="Hostname/IP to connect to. Optionally specify the port."
126                    ),
127                ),
128                (
129                    "protocol",
130                    models.TextField(choices=[("rdp", "Rdp"), ("vnc", "Vnc"), ("ssh", "Ssh")]),
131                ),
132                (
133                    "device",
134                    models.OneToOneField(
135                        on_delete=django.db.models.deletion.CASCADE,
136                        related_name="rac_override",
137                        to="authentik_endpoints.device",
138                    ),
139                ),
140            ],
141            options={
142                "verbose_name": "RAC Connection override",
143                "verbose_name_plural": "RAC Connection overrides",
144            },
145        ),
146        migrations.RunPython(migrate_endpoints_to_devices, migrations.RunPython.noop),
147        migrations.RemoveField(
148            model_name="connectiontoken",
149            name="endpoint",
150        ),
151        migrations.AddField(
152            model_name="connectiontoken",
153            name="protocol",
154            # All connection tokens are deleted above, so the column can be added as
155            # non-nullable without a default
156            field=models.TextField(choices=[("rdp", "Rdp"), ("vnc", "Vnc"), ("ssh", "Ssh")]),
157        ),
158        migrations.AddField(
159            model_name="connectiontoken",
160            name="device",
161            field=models.ForeignKey(
162                on_delete=django.db.models.deletion.CASCADE,
163                to="authentik_endpoints.device",
164            ),
165        ),
166        migrations.RemoveField(
167            model_name="endpointpropertymapping",
168            name="endpoint",
169        ),
170        migrations.RemoveField(
171            model_name="endpointpropertymapping",
172            name="property_mapping",
173        ),
174        migrations.RemoveField(
175            model_name="endpoint",
176            name="property_mappings",
177        ),
178        migrations.RemoveField(
179            model_name="endpoint",
180            name="provider",
181        ),
182        migrations.DeleteModel(
183            name="EndpointPropertyMapping",
184        ),
185        migrations.DeleteModel(
186            name="Endpoint",
187        ),
188        migrations.RunPython(remove_endpoint_permissions, migrations.RunPython.noop),
189    ]

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_endpoints', '0005_alter_deviceuserbinding_managers'), ('authentik_policies', '0011_policybinding_failure_result_and_more'), ('authentik_providers_rac', '0008_endpointpropertymapping_and_more'), ('contenttypes', '0002_remove_content_type_name')]
operations = [<AddField model_name='racprovider', name='maximum_connections', field=<django.db.models.fields.IntegerField>>, <AddField model_name='racprovider', name='access_group', field=<django.db.models.fields.related.ForeignKey>>, <CreateModel name='RACConnectionOverride', fields=[('id', <django.db.models.fields.AutoField>), ('host', <django.db.models.fields.TextField>), ('protocol', <django.db.models.fields.TextField>), ('device', <django.db.models.fields.related.OneToOneField>)], options={'verbose_name': 'RAC Connection override', 'verbose_name_plural': 'RAC Connection overrides'}>, <RunPython <function migrate_endpoints_to_devices>, <function RunPython.noop>>, <RemoveField model_name='connectiontoken', name='endpoint'>, <AddField model_name='connectiontoken', name='protocol', field=<django.db.models.fields.TextField>>, <AddField model_name='connectiontoken', name='device', field=<django.db.models.fields.related.ForeignKey>>, <RemoveField model_name='endpointpropertymapping', name='endpoint'>, <RemoveField model_name='endpointpropertymapping', name='property_mapping'>, <RemoveField model_name='endpoint', name='property_mappings'>, <RemoveField model_name='endpoint', name='provider'>, <DeleteModel name='EndpointPropertyMapping'>, <DeleteModel name='Endpoint'>, <RunPython <function remove_endpoint_permissions>, <function RunPython.noop>>]