authentik.providers.rac.consumer_client

RAC Client consumer

  1"""RAC Client consumer"""
  2
  3from hashlib import sha256
  4
  5from asgiref.sync import async_to_sync
  6from channels.db import database_sync_to_async
  7from channels.exceptions import ChannelFull, DenyConnection
  8from channels.generic.websocket import AsyncWebsocketConsumer
  9from django.db import connection
 10from django.http.request import QueryDict
 11from structlog.stdlib import BoundLogger, get_logger
 12
 13from authentik.outposts.consumer import build_outpost_group_instance
 14from authentik.outposts.models import Outpost, OutpostState, OutpostType
 15from authentik.providers.rac.guacamole import (
 16    GuacamoleInstructionParser,
 17    GuacamoleProtocolError,
 18)
 19from authentik.providers.rac.models import ConnectionToken, RACProvider
 20
 21
 22def build_rac_client_group() -> str:
 23    """
 24    Global broadcast group, which messages are sent to when the outpost connects back
 25    to authentik for a specific connection
 26    The `RACClientConsumer` consumer adds itself to this group on connection,
 27    and removes itself once it has been assigned a specific outpost channel
 28    """
 29    return sha256(f"{connection.schema_name}/group_rac_client".encode()).hexdigest()
 30
 31
 32def build_rac_client_group_session(session_key: str) -> str:
 33    """
 34    A group for all connections in a given authentik session ID
 35    A disconnect message is sent to this group when the session expires/is deleted
 36    """
 37    return sha256(f"{connection.schema_name}/group_rac_client_{session_key}".encode()).hexdigest()
 38
 39
 40def build_rac_client_group_token(token: str) -> str:
 41    """
 42    A group for all connections with a specific token, which in almost all cases
 43    is just one connection, however this is used to disconnect the connection
 44    when the token is deleted
 45    """
 46    return sha256(f"{connection.schema_name}/group_rac_token_{token}".encode()).hexdigest()
 47
 48
 49# Step 1: Client connects to this websocket endpoint
 50# Step 2: We prepare all the connection args for Guac
 51# Step 3: Send a websocket message to a single outpost that has this provider assigned
 52#         (Currently sending to all of them)
 53#         (Should probably do different load balancing algorithms)
 54# Step 4: Outpost creates a websocket connection back to authentik
 55#         with /ws/outpost_rac/<our_channel_id>/
 56# Step 5: This consumer transfers data between the two channels
 57
 58
 59class RACClientConsumer(AsyncWebsocketConsumer):
 60    """RAC client consumer the browser connects to"""
 61
 62    dest_channel_id: str = ""
 63    provider: RACProvider
 64    token: ConnectionToken
 65    logger: BoundLogger
 66    guacamole_parser: GuacamoleInstructionParser
 67
 68    async def connect(self):
 69        self.logger = get_logger()
 70        self.guacamole_parser = GuacamoleInstructionParser()
 71        await self.accept("guacamole")
 72        await self.channel_layer.group_add(build_rac_client_group(), self.channel_name)
 73        await self.channel_layer.group_add(
 74            build_rac_client_group_session(self.scope["session"].session_key),
 75            self.channel_name,
 76        )
 77        await self.init_outpost_connection()
 78
 79    async def disconnect(self, code):
 80        self.logger.debug("Disconnecting")
 81        if self.dest_channel_id:
 82            # Tell the outpost we're disconnecting
 83            await self.channel_layer.send(
 84                self.dest_channel_id,
 85                {
 86                    "type": "event.disconnect",
 87                },
 88            )
 89
 90    @database_sync_to_async
 91    def init_outpost_connection(self):
 92        """Initialize guac connection settings"""
 93        self.token = (
 94            ConnectionToken.objects.filter(
 95                token=self.scope["url_route"]["kwargs"]["token"],
 96                session__session__session_key=self.scope["session"].session_key,
 97            )
 98            .select_related("device", "provider", "session", "session__user")
 99            .first()
100        )
101        if not self.token:
102            raise DenyConnection()
103        self.provider = self.token.provider
104        params = self.token.get_settings()
105        self.logger = get_logger().bind(
106            device=self.token.device.name, user=self.scope["user"].username
107        )
108        msg = {
109            "type": "event.provider.specific",
110            "sub_type": "init_connection",
111            "dest_channel_id": self.channel_name,
112            "params": params,
113            "protocol": self.token.protocol,
114        }
115        query = QueryDict(self.scope["query_string"].decode())
116        for key in ["screen_width", "screen_height", "screen_dpi", "audio"]:
117            value = query.get(key, None)
118            if not value:
119                continue
120            msg[key] = str(value)
121        outposts = Outpost.objects.filter(
122            type=OutpostType.RAC,
123            providers__in=[self.provider],
124        )
125        if not outposts.exists():
126            self.logger.warning("Provider has no outpost")
127            raise DenyConnection()
128        for outpost in outposts:
129            # Sort all states for the outpost by connection count
130            states = sorted(
131                OutpostState.for_outpost(outpost),
132                key=lambda state: int(state.args.get("active_connections", 0)),
133            )
134            if len(states) < 1:
135                continue
136            self.logger.debug("Sending out connection broadcast")
137            group = build_outpost_group_instance(outpost.pk, states[0].uid)
138            async_to_sync(self.channel_layer.group_send)(group, msg)
139        if self.provider and self.provider.delete_token_on_disconnect:
140            self.logger.info("Deleting connection token to prevent reconnect", token=self.token)
141            self.token.delete()
142
143    async def receive(self, text_data=None, bytes_data=None):
144        """Filter tunnel instructions and mirror protocol data to guacd."""
145        if self.token.is_expired:
146            await self.event_disconnect({"reason": "token_expiry"})
147            return
148        # The Guacamole protocol is text-only, binary frames are not part of it.
149        if text_data is None:
150            return
151        try:
152            responses, forwarded = self.guacamole_parser.split_internal(
153                self.guacamole_parser.feed(text_data)
154            )
155        except GuacamoleProtocolError as exc:
156            self.logger.debug("Ignoring malformed Guacamole protocol data", error=str(exc))
157            return
158
159        for response in responses:
160            await self.send(text_data=response)
161
162        if not forwarded or self.dest_channel_id == "":
163            return
164        try:
165            await self.channel_layer.send(
166                self.dest_channel_id,
167                {
168                    "type": "event.send",
169                    "text_data": forwarded,
170                },
171            )
172        except ChannelFull:
173            pass
174
175    async def event_outpost_connected(self, event: dict):
176        """Handle event broadcasted from outpost consumer, and check if they
177        created a connection for us"""
178        outpost_channel = event.get("outpost_channel")
179        if event.get("client_channel") != self.channel_name:
180            return
181        if self.dest_channel_id != "":
182            # We've already selected an outpost channel, so tell the other channel to disconnect
183            # This should never happen since we remove ourselves from the broadcast group
184            await self.channel_layer.send(
185                outpost_channel,
186                {
187                    "type": "event.disconnect",
188                },
189            )
190            return
191        self.logger.debug("Connected to a single outpost instance")
192        self.dest_channel_id = outpost_channel
193        # Since we have a specific outpost channel now, we can remove
194        # ourselves from the global broadcast group
195        await self.channel_layer.group_discard(build_rac_client_group(), self.channel_name)
196
197    async def event_send(self, event: dict):
198        """Handler called by outpost websocket that sends data to this specific
199        client connection"""
200        if self.token.is_expired:
201            await self.event_disconnect({"reason": "token_expiry"})
202            return
203        await self.send(text_data=event.get("text_data"), bytes_data=event.get("bytes_data"))
204
205    async def event_disconnect(self, event: dict):
206        """Disconnect when the session ends"""
207        self.logger.info("Disconnecting RAC connection", reason=event.get("reason"))
208        await self.close()
def build_rac_client_group() -> str:
23def build_rac_client_group() -> str:
24    """
25    Global broadcast group, which messages are sent to when the outpost connects back
26    to authentik for a specific connection
27    The `RACClientConsumer` consumer adds itself to this group on connection,
28    and removes itself once it has been assigned a specific outpost channel
29    """
30    return sha256(f"{connection.schema_name}/group_rac_client".encode()).hexdigest()

Global broadcast group, which messages are sent to when the outpost connects back to authentik for a specific connection The RACClientConsumer consumer adds itself to this group on connection, and removes itself once it has been assigned a specific outpost channel

def build_rac_client_group_session(session_key: str) -> str:
33def build_rac_client_group_session(session_key: str) -> str:
34    """
35    A group for all connections in a given authentik session ID
36    A disconnect message is sent to this group when the session expires/is deleted
37    """
38    return sha256(f"{connection.schema_name}/group_rac_client_{session_key}".encode()).hexdigest()

A group for all connections in a given authentik session ID A disconnect message is sent to this group when the session expires/is deleted

def build_rac_client_group_token(token: str) -> str:
41def build_rac_client_group_token(token: str) -> str:
42    """
43    A group for all connections with a specific token, which in almost all cases
44    is just one connection, however this is used to disconnect the connection
45    when the token is deleted
46    """
47    return sha256(f"{connection.schema_name}/group_rac_token_{token}".encode()).hexdigest()

A group for all connections with a specific token, which in almost all cases is just one connection, however this is used to disconnect the connection when the token is deleted

class RACClientConsumer(channels.generic.websocket.AsyncWebsocketConsumer):
 60class RACClientConsumer(AsyncWebsocketConsumer):
 61    """RAC client consumer the browser connects to"""
 62
 63    dest_channel_id: str = ""
 64    provider: RACProvider
 65    token: ConnectionToken
 66    logger: BoundLogger
 67    guacamole_parser: GuacamoleInstructionParser
 68
 69    async def connect(self):
 70        self.logger = get_logger()
 71        self.guacamole_parser = GuacamoleInstructionParser()
 72        await self.accept("guacamole")
 73        await self.channel_layer.group_add(build_rac_client_group(), self.channel_name)
 74        await self.channel_layer.group_add(
 75            build_rac_client_group_session(self.scope["session"].session_key),
 76            self.channel_name,
 77        )
 78        await self.init_outpost_connection()
 79
 80    async def disconnect(self, code):
 81        self.logger.debug("Disconnecting")
 82        if self.dest_channel_id:
 83            # Tell the outpost we're disconnecting
 84            await self.channel_layer.send(
 85                self.dest_channel_id,
 86                {
 87                    "type": "event.disconnect",
 88                },
 89            )
 90
 91    @database_sync_to_async
 92    def init_outpost_connection(self):
 93        """Initialize guac connection settings"""
 94        self.token = (
 95            ConnectionToken.objects.filter(
 96                token=self.scope["url_route"]["kwargs"]["token"],
 97                session__session__session_key=self.scope["session"].session_key,
 98            )
 99            .select_related("device", "provider", "session", "session__user")
100            .first()
101        )
102        if not self.token:
103            raise DenyConnection()
104        self.provider = self.token.provider
105        params = self.token.get_settings()
106        self.logger = get_logger().bind(
107            device=self.token.device.name, user=self.scope["user"].username
108        )
109        msg = {
110            "type": "event.provider.specific",
111            "sub_type": "init_connection",
112            "dest_channel_id": self.channel_name,
113            "params": params,
114            "protocol": self.token.protocol,
115        }
116        query = QueryDict(self.scope["query_string"].decode())
117        for key in ["screen_width", "screen_height", "screen_dpi", "audio"]:
118            value = query.get(key, None)
119            if not value:
120                continue
121            msg[key] = str(value)
122        outposts = Outpost.objects.filter(
123            type=OutpostType.RAC,
124            providers__in=[self.provider],
125        )
126        if not outposts.exists():
127            self.logger.warning("Provider has no outpost")
128            raise DenyConnection()
129        for outpost in outposts:
130            # Sort all states for the outpost by connection count
131            states = sorted(
132                OutpostState.for_outpost(outpost),
133                key=lambda state: int(state.args.get("active_connections", 0)),
134            )
135            if len(states) < 1:
136                continue
137            self.logger.debug("Sending out connection broadcast")
138            group = build_outpost_group_instance(outpost.pk, states[0].uid)
139            async_to_sync(self.channel_layer.group_send)(group, msg)
140        if self.provider and self.provider.delete_token_on_disconnect:
141            self.logger.info("Deleting connection token to prevent reconnect", token=self.token)
142            self.token.delete()
143
144    async def receive(self, text_data=None, bytes_data=None):
145        """Filter tunnel instructions and mirror protocol data to guacd."""
146        if self.token.is_expired:
147            await self.event_disconnect({"reason": "token_expiry"})
148            return
149        # The Guacamole protocol is text-only, binary frames are not part of it.
150        if text_data is None:
151            return
152        try:
153            responses, forwarded = self.guacamole_parser.split_internal(
154                self.guacamole_parser.feed(text_data)
155            )
156        except GuacamoleProtocolError as exc:
157            self.logger.debug("Ignoring malformed Guacamole protocol data", error=str(exc))
158            return
159
160        for response in responses:
161            await self.send(text_data=response)
162
163        if not forwarded or self.dest_channel_id == "":
164            return
165        try:
166            await self.channel_layer.send(
167                self.dest_channel_id,
168                {
169                    "type": "event.send",
170                    "text_data": forwarded,
171                },
172            )
173        except ChannelFull:
174            pass
175
176    async def event_outpost_connected(self, event: dict):
177        """Handle event broadcasted from outpost consumer, and check if they
178        created a connection for us"""
179        outpost_channel = event.get("outpost_channel")
180        if event.get("client_channel") != self.channel_name:
181            return
182        if self.dest_channel_id != "":
183            # We've already selected an outpost channel, so tell the other channel to disconnect
184            # This should never happen since we remove ourselves from the broadcast group
185            await self.channel_layer.send(
186                outpost_channel,
187                {
188                    "type": "event.disconnect",
189                },
190            )
191            return
192        self.logger.debug("Connected to a single outpost instance")
193        self.dest_channel_id = outpost_channel
194        # Since we have a specific outpost channel now, we can remove
195        # ourselves from the global broadcast group
196        await self.channel_layer.group_discard(build_rac_client_group(), self.channel_name)
197
198    async def event_send(self, event: dict):
199        """Handler called by outpost websocket that sends data to this specific
200        client connection"""
201        if self.token.is_expired:
202            await self.event_disconnect({"reason": "token_expiry"})
203            return
204        await self.send(text_data=event.get("text_data"), bytes_data=event.get("bytes_data"))
205
206    async def event_disconnect(self, event: dict):
207        """Disconnect when the session ends"""
208        self.logger.info("Disconnecting RAC connection", reason=event.get("reason"))
209        await self.close()

RAC client consumer the browser connects to

dest_channel_id: str = ''
logger: structlog.stdlib.BoundLogger
async def connect(self):
69    async def connect(self):
70        self.logger = get_logger()
71        self.guacamole_parser = GuacamoleInstructionParser()
72        await self.accept("guacamole")
73        await self.channel_layer.group_add(build_rac_client_group(), self.channel_name)
74        await self.channel_layer.group_add(
75            build_rac_client_group_session(self.scope["session"].session_key),
76            self.channel_name,
77        )
78        await self.init_outpost_connection()
async def disconnect(self, code):
80    async def disconnect(self, code):
81        self.logger.debug("Disconnecting")
82        if self.dest_channel_id:
83            # Tell the outpost we're disconnecting
84            await self.channel_layer.send(
85                self.dest_channel_id,
86                {
87                    "type": "event.disconnect",
88                },
89            )

Called when a WebSocket connection is closed.

@database_sync_to_async
def init_outpost_connection(self):
 91    @database_sync_to_async
 92    def init_outpost_connection(self):
 93        """Initialize guac connection settings"""
 94        self.token = (
 95            ConnectionToken.objects.filter(
 96                token=self.scope["url_route"]["kwargs"]["token"],
 97                session__session__session_key=self.scope["session"].session_key,
 98            )
 99            .select_related("device", "provider", "session", "session__user")
100            .first()
101        )
102        if not self.token:
103            raise DenyConnection()
104        self.provider = self.token.provider
105        params = self.token.get_settings()
106        self.logger = get_logger().bind(
107            device=self.token.device.name, user=self.scope["user"].username
108        )
109        msg = {
110            "type": "event.provider.specific",
111            "sub_type": "init_connection",
112            "dest_channel_id": self.channel_name,
113            "params": params,
114            "protocol": self.token.protocol,
115        }
116        query = QueryDict(self.scope["query_string"].decode())
117        for key in ["screen_width", "screen_height", "screen_dpi", "audio"]:
118            value = query.get(key, None)
119            if not value:
120                continue
121            msg[key] = str(value)
122        outposts = Outpost.objects.filter(
123            type=OutpostType.RAC,
124            providers__in=[self.provider],
125        )
126        if not outposts.exists():
127            self.logger.warning("Provider has no outpost")
128            raise DenyConnection()
129        for outpost in outposts:
130            # Sort all states for the outpost by connection count
131            states = sorted(
132                OutpostState.for_outpost(outpost),
133                key=lambda state: int(state.args.get("active_connections", 0)),
134            )
135            if len(states) < 1:
136                continue
137            self.logger.debug("Sending out connection broadcast")
138            group = build_outpost_group_instance(outpost.pk, states[0].uid)
139            async_to_sync(self.channel_layer.group_send)(group, msg)
140        if self.provider and self.provider.delete_token_on_disconnect:
141            self.logger.info("Deleting connection token to prevent reconnect", token=self.token)
142            self.token.delete()

Initialize guac connection settings

async def receive(self, text_data=None, bytes_data=None):
144    async def receive(self, text_data=None, bytes_data=None):
145        """Filter tunnel instructions and mirror protocol data to guacd."""
146        if self.token.is_expired:
147            await self.event_disconnect({"reason": "token_expiry"})
148            return
149        # The Guacamole protocol is text-only, binary frames are not part of it.
150        if text_data is None:
151            return
152        try:
153            responses, forwarded = self.guacamole_parser.split_internal(
154                self.guacamole_parser.feed(text_data)
155            )
156        except GuacamoleProtocolError as exc:
157            self.logger.debug("Ignoring malformed Guacamole protocol data", error=str(exc))
158            return
159
160        for response in responses:
161            await self.send(text_data=response)
162
163        if not forwarded or self.dest_channel_id == "":
164            return
165        try:
166            await self.channel_layer.send(
167                self.dest_channel_id,
168                {
169                    "type": "event.send",
170                    "text_data": forwarded,
171                },
172            )
173        except ChannelFull:
174            pass

Filter tunnel instructions and mirror protocol data to guacd.

async def event_outpost_connected(self, event: dict):
176    async def event_outpost_connected(self, event: dict):
177        """Handle event broadcasted from outpost consumer, and check if they
178        created a connection for us"""
179        outpost_channel = event.get("outpost_channel")
180        if event.get("client_channel") != self.channel_name:
181            return
182        if self.dest_channel_id != "":
183            # We've already selected an outpost channel, so tell the other channel to disconnect
184            # This should never happen since we remove ourselves from the broadcast group
185            await self.channel_layer.send(
186                outpost_channel,
187                {
188                    "type": "event.disconnect",
189                },
190            )
191            return
192        self.logger.debug("Connected to a single outpost instance")
193        self.dest_channel_id = outpost_channel
194        # Since we have a specific outpost channel now, we can remove
195        # ourselves from the global broadcast group
196        await self.channel_layer.group_discard(build_rac_client_group(), self.channel_name)

Handle event broadcasted from outpost consumer, and check if they created a connection for us

async def event_send(self, event: dict):
198    async def event_send(self, event: dict):
199        """Handler called by outpost websocket that sends data to this specific
200        client connection"""
201        if self.token.is_expired:
202            await self.event_disconnect({"reason": "token_expiry"})
203            return
204        await self.send(text_data=event.get("text_data"), bytes_data=event.get("bytes_data"))

Handler called by outpost websocket that sends data to this specific client connection

async def event_disconnect(self, event: dict):
206    async def event_disconnect(self, event: dict):
207        """Disconnect when the session ends"""
208        self.logger.info("Disconnecting RAC connection", reason=event.get("reason"))
209        await self.close()

Disconnect when the session ends