← Back to Pull requests

feat: Add live device screen sharing via WebSocket and FCM #209

Open
tobiasmcnulty opened this pull request with 4397 lines diff across 51 files
View on GitHub
tobiasmcnulty tobiasmcnulty commented on Apr 28, 2026 20:12 UTC
Author

  • Add Device.screen_stream_token and fcm_token fields (single migration)

  • Add FCM helper (apps/mdm/fcm.py) to trigger screen-share consent on device

  • Add WebSocket consumers for device→server→browser frame relay

  • Add device_screen_view and template for live screen viewer UI

  • Add device_fcm_token_view API endpoint for FCM token registration

  • Include screen-stream config in AMAPI managed configuration

  • Add firebase-admin and channels dependencies

  • Add tests for FCM token view, screen stream token, FCM helper, and WebSocket consumers
  • Diff: 4397 lines (+4286 / -111) across 51 files Reviewer: tobiasmcnulty Review duration: 317755m
    All Vouch review confidence checks passed
    Residual risk 0.16 = Change Risk (0.93) × (1 − Review Confidence (0.82)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.93 · 4397 lines diff across 51 files
    0.93
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    82%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    41 items
    Copilot Copilot commented on code on Apr 28, 2026 23:09 UTC
    Code Review
    apps/publish_mdm/views.py:1
    @@ -1526,3 +1526,71 @@ def enterprise_callback(request: HttpRequest, callback_token):
             )
     
         return redirect(redirect_to)
    +
    +
    +@login_required
    +def device_screen_view(request: HttpRequest, organization_slug, device_pk):
    +    """Render the live screen viewer page for a device.
    +
    +    Generates the per-device screen-stream token if one isn't set yet, then
    +    syncs the device's policy so the firmware app receives the new managed
    +    configuration (token + WebSocket URL) on its next pull.
    +    """
    +    from apps.mdm.models import Device  # noqa: PLC0415
    +
    +    device = get_object_or_404(
    +        Device.objects.select_related("fleet__organization"),
    +        pk=device_pk,
    +        fleet__organization=request.organization,
    +    )
    +    device.ensure_screen_stream_token()
    +
    +    # Send FCM trigger so the app shows the MediaProjection consent dialog.
    +    logger.info(
    +        "device_screen_view: FCM trigger",
    +        device_pk=device.pk,
    +        has_fcm_token=bool(device.fcm_token),
    +    )
    +    if device.fcm_token:
    +        from django.conf import settings  # noqa: PLC0415
    +
    +        from apps.mdm.fcm import send_start_screen_share  # noqa: PLC0415
    +
    +        cb_domain = getattr(settings, "ANDROID_ENTERPRISE_CALLBACK_DOMAIN", "") or ""
    +        if not cb_domain:
    +            from django.contrib.sites.models import Site  # noqa: PLC0415
    +
    +            try:
    +                cb_domain = Site.objects.get_current().domain
    +            except Exception:
    +                cb_domain = ""
    +        scheme = "ws" if cb_domain.startswith("localhost") or ":" in cb_domain else "wss"
    +        stream_url = (
    +            f"{scheme}://{cb_domain}/ws/devices/screen-publish/{device.screen_stream_token}/"
    +        )
    +        sent = send_start_screen_share(
    +            device.fcm_token,
    +            screen_stream_url=stream_url,
    +            screen_stream_token=device.screen_stream_token,
    +        )
    +        logger.info("device_screen_view: FCM send result", device_pk=device.pk, sent=sent)

    The WebSocket URL construction can produce an invalid or insecure URL: if ANDROID_ENTERPRISE_CALLBACK_DOMAIN is empty and Site.get_current() fails/returns empty, cb_domain becomes "" and stream_url becomes wss:///.... Also, treating any domain containing ":" as needing ws will incorrectly downgrade example.com:443 to ws. Prefer deriving the host from request.get_host() as a fallback, and choose ws/wss based on request.is_secure() (or a dedicated setting) rather than string heuristics.

            cb_domain = (getattr(settings, "ANDROID_ENTERPRISE_CALLBACK_DOMAIN", "") or "").strip()
            if not cb_domain:
                from django.contrib.sites.models import Site  # noqa: PLC0415
    
                try:
                    cb_domain = (Site.objects.get_current().domain or "").strip()
                except Exception:
                    cb_domain = ""
            if not cb_domain:
                cb_domain = (request.get_host() or "").strip()
    
            if cb_domain.startswith(("http://", "https://", "ws://", "wss://")):
                cb_domain = cb_domain.split("://", 1)[1]
    
            if cb_domain:
                scheme = "wss" if request.is_secure() else "ws"
                stream_url = (
                    f"{scheme}://{cb_domain}/ws/devices/screen-publish/{device.screen_stream_token}/"
                )
                sent = send_start_screen_share(
                    device.fcm_token,
                    screen_stream_url=stream_url,
                    screen_stream_token=device.screen_stream_token,
                )
                logger.info("device_screen_view: FCM send result", device_pk=device.pk, sent=sent)
            else:
                logger.warning(
                    "device_screen_view: no callback host available — cannot trigger screen share",
                    device_pk=device.pk,
                )
    

    Copilot Copilot commented on code on Apr 28, 2026 23:09 UTC
    Code Review
    apps/mdm/models.py:1
    @@ -639,10 +640,32 @@ class Device(SoftDeleteModel):
             null=True,
             blank=True,
         )
    +    screen_stream_token = models.CharField(
    +        max_length=64,
    +        blank=True,
    +        default="",
    +        help_text="Per-device secret used by the firmware app to authenticate"
    +        " its screen-share WebSocket connection.",
    +    )

    screen_stream_token is used as a bearer-style authentication secret, but the model field has no uniqueness guarantee. If two rows ever share a token (accidentally, via data migration, or manual edits), lookups will be ambiguous and endpoints like FCM registration could update multiple devices. Consider enforcing uniqueness (e.g., a partial UniqueConstraint that excludes the empty-string default) and/or generating tokens in a loop until an unused value is found.

    Copilot Copilot commented on code on Apr 28, 2026 23:09 UTC
    Code Review
    apps/mdm/views.py:1
    @@ -38,6 +38,34 @@
     logger = structlog.get_logger()
     
     
    +@csrf_exempt
    +@require_POST
    +def device_fcm_token_view(request):
    +    """Register an FCM token for a device, authenticated by its screen_stream_token.
    +
    +    The firmware app calls this endpoint after Firebase assigns/refreshes a token.
    +    Auth: the ``screen_stream_token`` stored in the device record (bearer-style,
    +    sent in the JSON body rather than an Authorization header to keep the app simple).
    +    """
    +    try:
    +        body = json.loads(request.body)
    +    except (json.JSONDecodeError, ValueError):
    +        return HttpResponse(status=400)
    +
    +    fcm_token = body.get("fcm_token", "").strip()
    +    screen_stream_token = body.get("screen_stream_token", "").strip()
    +    if not fcm_token or not screen_stream_token:
    +        return HttpResponse(status=400)
    +
    +    updated = Device.all_objects.filter(screen_stream_token=screen_stream_token).update(

    This endpoint authenticates by screen_stream_token but updates via Device.all_objects, so a soft-deleted device can still register/update an FCM token. For consistency with other device-ingest endpoints (which use Device.objects) and to prevent reactivating deleted devices, filter with the active manager (Device.objects) or explicitly exclude deleted rows.

        updated = Device.objects.filter(screen_stream_token=screen_stream_token).update(
    

    Copilot Copilot commented on code on Apr 28, 2026 23:09 UTC
    Code Review
    apps/publish_mdm/screen_consumers.py:1
    @@ -0,0 +1,151 @@
    +"""WebSocket consumers for live device screen sharing.
    +
    +A device running the firmware app connects to ``DeviceScreenPublisherConsumer``
    +authenticated by its per-device ``screen_stream_token`` (passed in the URL).
    +Every binary frame (a JPEG byte string) it sends is broadcast to a Channels
    +group named ``device-screen-<device_pk>``. The browser-side viewer connects to
    +``DeviceScreenViewerConsumer`` (auth via the standard Django session) and is
    +joined to that same group, receiving each frame and rendering it.
    +"""
    +
    +from __future__ import annotations
    +
    +import structlog
    +from channels.db import database_sync_to_async
    +from channels.generic.websocket import AsyncWebsocketConsumer
    +
    +from apps.mdm.models import Device
    +
    +logger = structlog.getLogger(__name__)
    +
    +# Tracks how many browser viewers are watching each device (keyed by device_pk).
    +# Scoped to the process — sufficient with InMemoryChannelLayer.
    +_viewer_counts: dict[int, int] = {}
    +
    +
    +def _group_name(device_pk: int) -> str:
    +    return f"device-screen-{device_pk}"
    +
    +
    +class DeviceScreenPublisherConsumer(AsyncWebsocketConsumer):
    +    """Receives binary screen frames from a device and fans them out."""
    +
    +    async def connect(self):
    +        token = self.scope["url_route"]["kwargs"]["token"]
    +        self.device_pk = await self._lookup_device_pk(token)
    +        if self.device_pk is None:
    +            logger.warning("Device screen publish: invalid token")
    +            await self.close(code=4401)
    +            return
    +        self.group_name = _group_name(self.device_pk)
    +        await self.channel_layer.group_add(self.group_name, self.channel_name)
    +        await self.accept()
    +        # Notify any current viewers that the device is now publishing
    +        await self.channel_layer.group_send(
    +            self.group_name, {"type": "device.status", "status": "connected"}
    +        )
    +        logger.info("Device screen publisher connected", device_pk=self.device_pk)
    +
    +    async def disconnect(self, code):
    +        if getattr(self, "group_name", None):
    +            await self.channel_layer.group_send(
    +                self.group_name, {"type": "device.status", "status": "disconnected"}
    +            )
    +            await self.channel_layer.group_discard(self.group_name, self.channel_name)
    +
    +    async def receive(self, text_data=None, bytes_data=None):
    +        if bytes_data is None:
    +            return
    +        await self.channel_layer.group_send(
    +            self.group_name, {"type": "device.frame", "data": bytes_data}
    +        )
    +
    +    async def device_frame(self, event):
    +        # Publisher does not need to receive its own frames
    +        return
    +
    +    async def device_status(self, event):
    +        return
    +
    +    async def device_stop(self, event):
    +        """All viewers have disconnected — tell the device to stop streaming."""
    +        await self.send(text_data='{"action":"stop"}')
    +        await self.close()
    +
    +    @staticmethod
    +    @database_sync_to_async
    +    def _lookup_device_pk(token: str) -> int | None:
    +        if not token:
    +            return None
    +        return (
    +            Device.all_objects.filter(screen_stream_token=token)
    +            .values_list("pk", flat=True)
    +            .first()
    +        )

    _lookup_device_pk uses Device.all_objects, so a soft-deleted device can still publish frames if it still has a token. If deleted devices should no longer be able to stream, use Device.objects (active manager) here. Also, if tokens aren’t guaranteed unique, .first() could map a token to the wrong device; enforcing uniqueness at the model/DB level would prevent that ambiguity.

            try:
                return Device.objects.get(screen_stream_token=token).pk
            except (Device.DoesNotExist, Device.MultipleObjectsReturned):
                return None
    

    Copilot Copilot commented on code on Apr 28, 2026 23:09 UTC
    Code Review
    apps/publish_mdm/screen_consumers.py:1
    @@ -0,0 +1,151 @@
    +"""WebSocket consumers for live device screen sharing.
    +
    +A device running the firmware app connects to ``DeviceScreenPublisherConsumer``
    +authenticated by its per-device ``screen_stream_token`` (passed in the URL).
    +Every binary frame (a JPEG byte string) it sends is broadcast to a Channels
    +group named ``device-screen-<device_pk>``. The browser-side viewer connects to
    +``DeviceScreenViewerConsumer`` (auth via the standard Django session) and is
    +joined to that same group, receiving each frame and rendering it.
    +"""
    +
    +from __future__ import annotations
    +
    +import structlog
    +from channels.db import database_sync_to_async
    +from channels.generic.websocket import AsyncWebsocketConsumer
    +
    +from apps.mdm.models import Device
    +
    +logger = structlog.getLogger(__name__)
    +
    +# Tracks how many browser viewers are watching each device (keyed by device_pk).
    +# Scoped to the process — sufficient with InMemoryChannelLayer.
    +_viewer_counts: dict[int, int] = {}
    +
    +
    +def _group_name(device_pk: int) -> str:
    +    return f"device-screen-{device_pk}"
    +
    +
    +class DeviceScreenPublisherConsumer(AsyncWebsocketConsumer):
    +    """Receives binary screen frames from a device and fans them out."""
    +
    +    async def connect(self):
    +        token = self.scope["url_route"]["kwargs"]["token"]
    +        self.device_pk = await self._lookup_device_pk(token)
    +        if self.device_pk is None:
    +            logger.warning("Device screen publish: invalid token")
    +            await self.close(code=4401)
    +            return
    +        self.group_name = _group_name(self.device_pk)
    +        await self.channel_layer.group_add(self.group_name, self.channel_name)
    +        await self.accept()
    +        # Notify any current viewers that the device is now publishing
    +        await self.channel_layer.group_send(
    +            self.group_name, {"type": "device.status", "status": "connected"}
    +        )
    +        logger.info("Device screen publisher connected", device_pk=self.device_pk)
    +
    +    async def disconnect(self, code):
    +        if getattr(self, "group_name", None):
    +            await self.channel_layer.group_send(
    +                self.group_name, {"type": "device.status", "status": "disconnected"}
    +            )
    +            await self.channel_layer.group_discard(self.group_name, self.channel_name)
    +
    +    async def receive(self, text_data=None, bytes_data=None):
    +        if bytes_data is None:
    +            return
    +        await self.channel_layer.group_send(
    +            self.group_name, {"type": "device.frame", "data": bytes_data}
    +        )
    +
    +    async def device_frame(self, event):
    +        # Publisher does not need to receive its own frames
    +        return
    +
    +    async def device_status(self, event):
    +        return
    +
    +    async def device_stop(self, event):
    +        """All viewers have disconnected — tell the device to stop streaming."""
    +        await self.send(text_data='{"action":"stop"}')
    +        await self.close()
    +
    +    @staticmethod
    +    @database_sync_to_async
    +    def _lookup_device_pk(token: str) -> int | None:
    +        if not token:
    +            return None
    +        return (
    +            Device.all_objects.filter(screen_stream_token=token)
    +            .values_list("pk", flat=True)
    +            .first()
    +        )
    +
    +
    +class DeviceScreenViewerConsumer(AsyncWebsocketConsumer):
    +    """Streams binary screen frames to an authenticated browser session."""
    +
    +    async def connect(self):
    +        user = self.scope.get("user")
    +        if not user or not user.is_authenticated:
    +            await self.close(code=4401)
    +            return
    +        self.device_pk = int(self.scope["url_route"]["kwargs"]["device_pk"])
    +        if not await self._user_can_view(user, self.device_pk):
    +            await self.close(code=4403)
    +            return
    +        self.group_name = _group_name(self.device_pk)
    +        await self.channel_layer.group_add(self.group_name, self.channel_name)
    +        await self.accept()
    +        count = await self._increment_viewer_count(self.device_pk, delta=1)
    +        logger.info("Screen viewer connected", device_pk=self.device_pk, viewer_count=count)
    +
    +    async def disconnect(self, code):
    +        if getattr(self, "group_name", None):
    +            remaining = await self._increment_viewer_count(self.device_pk, delta=-1)
    +            logger.info(
    +                "Screen viewer disconnected",
    +                device_pk=self.device_pk,
    +                viewer_count=remaining,
    +            )
    +            if remaining <= 0:
    +                logger.info("Last viewer left, sending stop to device", device_pk=self.device_pk)
    +                await self.channel_layer.group_send(self.group_name, {"type": "device.stop"})
    +            await self.channel_layer.group_discard(self.group_name, self.channel_name)
    +
    +    async def device_frame(self, event):
    +        await self.send(bytes_data=event["data"])
    +
    +    async def device_status(self, event):
    +        await self.send(text_data=f'{{"status": "{event["status"]}"}}')
    +
    +    async def device_stop(self, event):
    +        # Viewers don't need to act on this message — it is handled by the publisher.
    +        return
    +
    +    @staticmethod
    +    @database_sync_to_async
    +    def _user_can_view(user, device_pk: int) -> bool:
    +        org_ids = list(user.get_organizations().values_list("pk", flat=True))
    +        if not org_ids:
    +            return False
    +        return Device.objects.filter(pk=device_pk, fleet__organization_id__in=org_ids).exists()
    +
    +    @database_sync_to_async
    +    def _increment_viewer_count(self, device_pk: int, delta: int) -> int:
    +        """Atomically increment/decrement the in-memory viewer count.
    +
    +        Returns the new count.  Uses a module-level dict so the count is shared
    +        across all consumer instances in the same process (sufficient for
    +        InMemoryChannelLayer; with Redis channel layers a Redis counter would be
    +        needed for multi-process deployments).
    +        """
    +        count = _viewer_counts.get(device_pk, 0) + delta
    +        count = max(count, 0)
    +        if count == 0:
    +            _viewer_counts.pop(device_pk, None)
    +        else:
    +            _viewer_counts[device_pk] = count
    +        return count

    _increment_viewer_count is marked "Atomically" but it mutates a shared module-level dict without any locking, and it’s wrapped in database_sync_to_async even though no DB work happens. With concurrent connects/disconnects, counts can race and trigger premature device.stop messages. Consider managing the counter in-process with an asyncio.Lock (and keeping it async), or moving the counter to a shared store (Redis) if you expect multiple processes.

    Copilot Copilot commented on code on Apr 28, 2026 23:09 UTC
    Code Review
    config/settings/base.py:1
    @@ -130,6 +130,13 @@
     ASGI_APPLICATION = "config.asgi.application"
     WSGI_APPLICATION = "config.wsgi.application"
     
    +# Channels channel layer. The in-memory layer is fine for single-process Daphne
    +# in local development. Production deployments running multiple ASGI workers
    +# should override this with a Redis-backed layer (channels_redis).
    +CHANNEL_LAYERS = {
    +    "default": {"BACKEND": "channels.layers.InMemoryChannelLayer"},
    +}

    CHANNEL_LAYERS defaults to InMemoryChannelLayer in base settings and deploy.py doesn’t override it. This will break screen-share fanout (and any other Channels features) when running multiple ASGI workers or multiple pods, because groups won’t be shared across processes. Consider configuring a Redis-backed channel layer in deploy.py (and adding channels_redis as a dependency), or making the backend configurable via an env var so production deployments don’t accidentally run in-memory.

    # Channels channel layer. Default to the in-memory layer for local development,
    # but allow deployments to opt into a shared Redis-backed layer so group sends
    # and fanout work correctly across multiple ASGI workers or pods.
    _channel_layers_redis_url = os.getenv("CHANNEL_LAYERS_REDIS_URL")
    if _channel_layers_redis_url:
        CHANNEL_LAYERS = {
            "default": {
                "BACKEND": "channels_redis.core.RedisChannelLayer",
                "CONFIG": {
                    "hosts": [_channel_layers_redis_url],
                },
            },
        }
    else:
        CHANNEL_LAYERS = {
            "default": {"BACKEND": "channels.layers.InMemoryChannelLayer"},
        }
    

    Copilot Copilot commented on code on Apr 28, 2026 23:09 UTC
    Code Review
    apps/publish_mdm/views.py:1
    @@ -1526,3 +1526,71 @@ def enterprise_callback(request: HttpRequest, callback_token):
             )
     
         return redirect(redirect_to)
    +
    +
    +@login_required
    +def device_screen_view(request: HttpRequest, organization_slug, device_pk):
    +    """Render the live screen viewer page for a device.
    +
    +    Generates the per-device screen-stream token if one isn't set yet, then
    +    syncs the device's policy so the firmware app receives the new managed
    +    configuration (token + WebSocket URL) on its next pull.

    The docstring says this view "syncs the device's policy" after generating the token, but the implementation only calls ensure_screen_stream_token() and does not trigger a push_to_mdm/policy sync. Either update the docstring to match the actual behavior, or call the appropriate push/sync method so the managed configuration is actually propagated.

        Ensures the per-device screen-stream token exists, then attempts to
        trigger screen sharing via FCM so the firmware app can start the
        MediaProjection consent flow.
    

    Copilot Copilot commented on code on Apr 28, 2026 23:09 UTC
    Code Review
    apps/mdm/views.py:1
    @@ -38,6 +38,34 @@
     logger = structlog.get_logger()
     
     
    +@csrf_exempt
    +@require_POST
    +def device_fcm_token_view(request):
    +    """Register an FCM token for a device, authenticated by its screen_stream_token.
    +
    +    The firmware app calls this endpoint after Firebase assigns/refreshes a token.
    +    Auth: the ``screen_stream_token`` stored in the device record (bearer-style,
    +    sent in the JSON body rather than an Authorization header to keep the app simple).
    +    """
    +    try:
    +        body = json.loads(request.body)
    +    except (json.JSONDecodeError, ValueError):
    +        return HttpResponse(status=400)
    +
    +    fcm_token = body.get("fcm_token", "").strip()
    +    screen_stream_token = body.get("screen_stream_token", "").strip()
    +    if not fcm_token or not screen_stream_token:
    +        return HttpResponse(status=400)

    device_fcm_token_view strips inputs but doesn’t validate max lengths. If the firmware posts an oversized fcm_token or screen_stream_token, the DB update can raise a DataError and return 500. Validate lengths against the model limits (e.g., <=256 for fcm_token and <=64 for screen_stream_token) and return 400 on invalid input.

            return HttpResponse(status=400)
        if len(fcm_token) > 256 or len(screen_stream_token) > 64:
            return HttpResponse(status=400)
    

    Copilot Copilot commented on code on Apr 28, 2026 23:09 UTC
    Code Review
    apps/mdm/fcm.py:1
    @@ -0,0 +1,88 @@
    +"""Firebase Cloud Messaging helpers.
    +
    +Initialises the Firebase Admin SDK from the same service-account file used
    +for Android Enterprise (ANDROID_ENTERPRISE_SERVICE_ACCOUNT_FILE) and exposes
    +a single helper for sending screen-share trigger messages.
    +"""
    +
    +import os
    +
    +import structlog
    +
    +logger = structlog.get_logger(__name__)
    +
    +_app = None
    +
    +
    +def _get_app():
    +    """Return (or lazily create) the firebase_admin App instance."""
    +    global _app
    +    if _app is not None:
    +        return _app
    +
    +    import firebase_admin  # noqa: PLC0415
    +    from firebase_admin import credentials  # noqa: PLC0415
    +
    +    service_account_file = os.getenv("ANDROID_ENTERPRISE_SERVICE_ACCOUNT_FILE")
    +    if not service_account_file:
    +        raise RuntimeError("ANDROID_ENTERPRISE_SERVICE_ACCOUNT_FILE is not set")
    +
    +    cred = credentials.Certificate(service_account_file)
    +    # The service account lives in the Android Enterprise GCP project, but FCM
    +    # is in a separate Firebase project.  Override the project ID so the Admin
    +    # SDK sends messages to the correct project.
    +    firebase_project_id = os.getenv("FIREBASE_PROJECT_ID")
    +    if not firebase_project_id:
    +        raise RuntimeError("FIREBASE_PROJECT_ID is not set")
    +    try:
    +        _app = firebase_admin.get_app("publishmdm")
    +    except ValueError:
    +        _app = firebase_admin.initialize_app(
    +            cred,
    +            options={"projectId": firebase_project_id},
    +            name="publishmdm",
    +        )
    +    return _app
    +
    +
    +def send_start_screen_share(
    +    fcm_token: str, screen_stream_url: str = "", screen_stream_token: str = ""
    +) -> bool:
    +    """Send a data-only FCM message that triggers the screen-share consent UI.
    +
    +    Includes screen_stream_url and screen_stream_token in the payload so the
    +    device can start the WebSocket immediately without waiting for the AMAPI
    +    managed-config push to propagate (which can take 20-30 seconds).
    +
    +    Returns True on success, False (with a logged warning) on failure.
    +    """
    +    from firebase_admin import messaging  # noqa: PLC0415
    +
    +    message = messaging.Message(
    +        notification=messaging.Notification(
    +            title="Screen share requested",
    +            body="An administrator wants to view this device\u2019s screen. Tap to allow.",
    +        ),
    +        data={

    send_start_screen_share() docstring says "data-only" but the message includes a notification payload. Either remove the notification to make this truly data-only, or update the docstring to reflect that it sends a user-visible notification + data payload.

    Copilot Copilot commented on code on Apr 28, 2026 23:09 UTC
    Code Review
    apps/mdm/fcm.py:1
    @@ -0,0 +1,88 @@
    +"""Firebase Cloud Messaging helpers.
    +
    +Initialises the Firebase Admin SDK from the same service-account file used
    +for Android Enterprise (ANDROID_ENTERPRISE_SERVICE_ACCOUNT_FILE) and exposes
    +a single helper for sending screen-share trigger messages.
    +"""
    +
    +import os
    +
    +import structlog
    +
    +logger = structlog.get_logger(__name__)
    +
    +_app = None
    +
    +
    +def _get_app():
    +    """Return (or lazily create) the firebase_admin App instance."""
    +    global _app
    +    if _app is not None:
    +        return _app
    +
    +    import firebase_admin  # noqa: PLC0415
    +    from firebase_admin import credentials  # noqa: PLC0415
    +
    +    service_account_file = os.getenv("ANDROID_ENTERPRISE_SERVICE_ACCOUNT_FILE")
    +    if not service_account_file:
    +        raise RuntimeError("ANDROID_ENTERPRISE_SERVICE_ACCOUNT_FILE is not set")
    +
    +    cred = credentials.Certificate(service_account_file)
    +    # The service account lives in the Android Enterprise GCP project, but FCM
    +    # is in a separate Firebase project.  Override the project ID so the Admin
    +    # SDK sends messages to the correct project.
    +    firebase_project_id = os.getenv("FIREBASE_PROJECT_ID")
    +    if not firebase_project_id:
    +        raise RuntimeError("FIREBASE_PROJECT_ID is not set")
    +    try:
    +        _app = firebase_admin.get_app("publishmdm")
    +    except ValueError:
    +        _app = firebase_admin.initialize_app(
    +            cred,
    +            options={"projectId": firebase_project_id},
    +            name="publishmdm",
    +        )
    +    return _app
    +
    +
    +def send_start_screen_share(
    +    fcm_token: str, screen_stream_url: str = "", screen_stream_token: str = ""
    +) -> bool:
    +    """Send a data-only FCM message that triggers the screen-share consent UI.
    +
    +    Includes screen_stream_url and screen_stream_token in the payload so the
    +    device can start the WebSocket immediately without waiting for the AMAPI
    +    managed-config push to propagate (which can take 20-30 seconds).
    +
    +    Returns True on success, False (with a logged warning) on failure.
    +    """
    +    from firebase_admin import messaging  # noqa: PLC0415
    +
    +    message = messaging.Message(
    +        notification=messaging.Notification(
    +            title="Screen share requested",
    +            body="An administrator wants to view this device\u2019s screen. Tap to allow.",
    +        ),
    +        data={
    +            "action": "start_screen_share",
    +            "screen_stream_url": screen_stream_url,
    +            "screen_stream_token": screen_stream_token,
    +        },
    +        android=messaging.AndroidConfig(
    +            priority="high",
    +            notification=messaging.AndroidNotification(
    +                channel_id="screen_share_request",
    +                click_action="com.publishmdm.firmwareapp.ACTION_SHOW_SCREEN_CONSENT",
    +            ),
    +        ),
    +        token=fcm_token,
    +    )
    +    try:
    +        msg_id = messaging.send(message, app=_get_app())
    +        logger.info(
    +            "FCM screen-share trigger sent: message_id=%s token_prefix=%s", msg_id, fcm_token[:8]

    logger.info is using printf-style positional formatting here, while most of the codebase logs structured fields via keyword args. Using structured fields (e.g., message_id and token_prefix) will make logs more searchable/consistent with existing structlog usage.

                "FCM screen-share trigger sent",
                message_id=msg_id,
                token_prefix=fcm_token[:8],
    

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Apr 28, 2026 23:09 UTC
    Reviewer

    Pull request overview

    Adds end-to-end live device screen sharing by introducing per-device auth tokens, an FCM “start screen share” trigger, and Channels WebSocket consumers to relay JPEG frames from device → server → browser, plus a simple viewer UI.

    Changes:

  • Add Device.screen_stream_token and Device.fcm_token fields + token generation helper.

  • Add FCM helper + device API endpoint for registering FCM tokens.

  • Add Channels consumers/routing + a Django view/template for live screen viewing; update docs/deps and add tests.
  • Reviewed changes

    Copilot reviewed 19 out of 20 changed files in this pull request and generated 10 comments.

    <details>
    <summary>Show a summary per file</summary>

    | File | Description |
    | ---- | ----------- |
    | uv.lock | Locks new transitive deps (firebase-admin + google cloud libs, etc.). |
    | pyproject.toml | Adds firebase-admin dependency. |
    | config/settings/base.py | Adds default Channels CHANNEL_LAYERS configuration. |
    | apps/mdm/models.py | Adds screen_stream_token/fcm_token fields + ensure_screen_stream_token(). |
    | apps/mdm/migrations/0014_device_screen_sharing.py | Migration for the new Device fields. |
    | apps/mdm/views.py | Adds device_fcm_token_view endpoint for firmware token registration. |
    | apps/mdm/urls.py | Routes the new FCM token registration endpoint. |
    | apps/mdm/fcm.py | Implements Firebase Admin SDK init + FCM “start screen share” sender. |
    | apps/publish_mdm/screen_consumers.py | Adds publisher/viewer WebSocket consumers and frame relay logic. |
    | apps/publish_mdm/routing.py | Adds websocket URL patterns for viewer and publisher sockets. |
    | apps/publish_mdm/views.py | Adds device_screen_view to render the viewer page and trigger FCM. |
    | apps/publish_mdm/urls.py | Adds URL route to the live screen viewer page. |
    | config/templates/publish_mdm/device_screen.html | Viewer UI template + JS websocket client to render JPEG frames. |
    | config/templates/publish_mdm/device_detail.html | Adds link to “View live device screen”. |
    | docs/src/running/tutorial.rst | Documents FIREBASE_PROJECT_ID requirement for FCM. |
    | docs/src/local-development/setup.rst | Adds local dev FCM setup instructions. |
    | tests/publish_mdm/test_screen_consumers.py | Tests for publisher/viewer websocket consumers. |
    | tests/mdm/test_screen_stream_token.py | Tests for ensure_screen_stream_token(). |
    | tests/mdm/test_fcm_token_view.py | Tests for the FCM token registration endpoint. |
    | tests/mdm/test_fcm.py | Tests for FCM helper payload/behavior. |
    </details>

    ---

    💡 <a href="/caktus/publish-mdm/new/main?filename=.github/instructions/*.instructions.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add Copilot custom instructions</a> for smarter, more guided reviews. <a href="https://docs.github.com/en/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn how to get started</a>.

    tobiasmcnulty tobiasmcnulty commented on Apr 28, 2026 23:12 UTC
    Author

    @copilot apply changes based on the comments in this thread

    Copilot Copilot commented on Apr 28, 2026 23:21 UTC
    Bot

    @copilot apply changes based on the comments in this thread

    Applied all changes from the review thread in commits 320ebfd and c4c390c:

  • FCM docstring & logging (fcm.py): updated docstring to reflect notification+data payload; switched logger.info to structured keyword args (message_id=, token_prefix=)

  • FCM token view (mdm/views.py): added length validation (400 if fcm_token > 256 or screen_stream_token > 64); switched Device.all_objects → Device.objects to exclude soft-deleted devices

  • Unique token constraint (models.py + migration 0014): added UniqueConstraint with condition=~Q(screen_stream_token="") so only non-empty tokens must be unique

  • Publisher consumer (screen_consumers.py): _lookup_device_pk now uses Device.objects.get() (excludes soft-deleted, raises MultipleObjectsReturned defensively)

  • Viewer count (screen_consumers.py): replaced @database_sync_to_async with an asyncio.Lock on the module-level dict — no DB work was happening anyway

  • Channel layers (base.py): added CHANNEL_LAYERS_REDIS_URL env var support; if set, uses channels_redis.core.RedisChannelLayer; otherwise falls back to in-memory

  • WebSocket URL (views.py): fallback chain is now settings → Site.get_current() → request.get_host(); uses urlparse().netloc to safely strip any scheme/path; scheme derived from request.is_secure()

  • Docstring (views.py): corrected to reflect FCM trigger, not a policy sync
  • [!WARNING]

    > <details>

    <summary>Firewall rules blocked me from connecting to one or more addresses (expand for details)</summary>

    > #### I tried to connect to the following addresses, but was blocked by firewall rules:

    > - astral.sh

    - Triggering command: /usr/bin/curl curl -LsSf REDACTED (dns block)

    > If you need me to access, download, or install something from one of these locations, you can either:

    > - Configure Actions setup steps to set up my environment, which run before the firewall is enabled

    - Add the appropriate URLs or hosts to the custom allowlist in this repository's Copilot coding agent settings (admins only)

    > </details>

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    apps/mdm/models.py:1
    @@ -736,6 +800,116 @@ def fallback_firmware_version(self):
                 return software_info.get("androidBuildNumber")
     
     
    +class DeviceBindCode(models.Model):
    +    """One-time bootstrap code used to bind a device public key."""
    +
    +    device = models.ForeignKey(
    +        Device,
    +        on_delete=models.CASCADE,
    +        related_name="bind_codes",
    +    )
    +    code_hash = models.CharField(max_length=64, db_index=True)
    +    expires_at = models.DateTimeField()
    +    used_at = models.DateTimeField(null=True, blank=True)
    +    created_at = models.DateTimeField(auto_now_add=True)
    +
    +    class Meta:
    +        indexes = (
    +            models.Index(fields=["device", "expires_at"]),
    +            models.Index(fields=["used_at"]),
    +        )
    +
    +    def __str__(self):
    +        return f"BindCode({self.device_id}, expires={self.expires_at})"

    __str__ references self.device_id, but DeviceBindCode has no device_id field (it has a device FK). This will raise AttributeError when the object is stringified (e.g., in admin/logging). Use self.device.device_id (or self.device_id_id if you store an integer FK id) and handle device possibly being unset if needed.

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    apps/mdm/models.py:1
    @@ -736,6 +800,116 @@ def fallback_firmware_version(self):
                 return software_info.get("androidBuildNumber")
     
     
    +class DeviceBindCode(models.Model):
    +    """One-time bootstrap code used to bind a device public key."""
    +
    +    device = models.ForeignKey(
    +        Device,
    +        on_delete=models.CASCADE,
    +        related_name="bind_codes",
    +    )
    +    code_hash = models.CharField(max_length=64, db_index=True)
    +    expires_at = models.DateTimeField()
    +    used_at = models.DateTimeField(null=True, blank=True)
    +    created_at = models.DateTimeField(auto_now_add=True)
    +
    +    class Meta:
    +        indexes = (
    +            models.Index(fields=["device", "expires_at"]),
    +            models.Index(fields=["used_at"]),
    +        )
    +
    +    def __str__(self):
    +        return f"BindCode({self.device_id}, expires={self.expires_at})"
    +
    +
    +class DeviceAuthChallenge(models.Model):
    +    """One-time challenge used for runtime device proof-of-possession."""
    +
    +    challenge_id = models.UUIDField(unique=True)
    +    device = models.ForeignKey(
    +        Device,
    +        on_delete=models.CASCADE,
    +        related_name="auth_challenges",
    +    )
    +    request_id = models.CharField(max_length=64)
    +    nonce = models.CharField(max_length=128)
    +    expires_at = models.DateTimeField()
    +    used_at = models.DateTimeField(null=True, blank=True)
    +    created_at = models.DateTimeField(auto_now_add=True)
    +
    +    class Meta:
    +        indexes = (
    +            models.Index(fields=["challenge_id"]),
    +            models.Index(fields=["device", "request_id"]),
    +            models.Index(fields=["expires_at"]),
    +            models.Index(fields=["used_at"]),
    +        )
    +
    +    def __str__(self):
    +        return f"AuthChallenge({self.challenge_id}, device={self.device_id})"

    __str__ references self.device_id, but DeviceAuthChallenge has no device_id field (it has a device FK). This will raise AttributeError when stringified. Use self.device.device_id (and consider also including self.device.pk for robustness if device_id can be blank).

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    apps/mdm/models.py:1
    @@ -736,6 +800,116 @@ def fallback_firmware_version(self):
                 return software_info.get("androidBuildNumber")
     
     
    +class DeviceBindCode(models.Model):
    +    """One-time bootstrap code used to bind a device public key."""
    +
    +    device = models.ForeignKey(
    +        Device,
    +        on_delete=models.CASCADE,
    +        related_name="bind_codes",
    +    )
    +    code_hash = models.CharField(max_length=64, db_index=True)
    +    expires_at = models.DateTimeField()
    +    used_at = models.DateTimeField(null=True, blank=True)
    +    created_at = models.DateTimeField(auto_now_add=True)
    +
    +    class Meta:
    +        indexes = (
    +            models.Index(fields=["device", "expires_at"]),
    +            models.Index(fields=["used_at"]),
    +        )
    +
    +    def __str__(self):
    +        return f"BindCode({self.device_id}, expires={self.expires_at})"
    +
    +
    +class DeviceAuthChallenge(models.Model):
    +    """One-time challenge used for runtime device proof-of-possession."""
    +
    +    challenge_id = models.UUIDField(unique=True)
    +    device = models.ForeignKey(
    +        Device,
    +        on_delete=models.CASCADE,
    +        related_name="auth_challenges",
    +    )
    +    request_id = models.CharField(max_length=64)
    +    nonce = models.CharField(max_length=128)
    +    expires_at = models.DateTimeField()
    +    used_at = models.DateTimeField(null=True, blank=True)
    +    created_at = models.DateTimeField(auto_now_add=True)
    +
    +    class Meta:
    +        indexes = (
    +            models.Index(fields=["challenge_id"]),
    +            models.Index(fields=["device", "request_id"]),
    +            models.Index(fields=["expires_at"]),
    +            models.Index(fields=["used_at"]),
    +        )
    +
    +    def __str__(self):
    +        return f"AuthChallenge({self.challenge_id}, device={self.device_id})"
    +
    +
    +class ScreenShareSession(models.Model):
    +    """Single-use, short-lived session credential for screen-share websocket auth."""
    +
    +    session_id = models.UUIDField(unique=True)
    +    token_hash = models.CharField(max_length=64, db_index=True)
    +    device = models.ForeignKey(
    +        Device,
    +        on_delete=models.CASCADE,
    +        related_name="screen_share_sessions",
    +    )
    +    request_id = models.CharField(max_length=64)
    +    expires_at = models.DateTimeField()
    +    used_at = models.DateTimeField(null=True, blank=True)
    +    created_at = models.DateTimeField(auto_now_add=True)
    +
    +    class Meta:
    +        indexes = (
    +            models.Index(fields=["session_id"]),
    +            models.Index(fields=["device", "request_id"]),
    +            models.Index(fields=["expires_at"]),
    +            models.Index(fields=["used_at"]),
    +        )
    +
    +    def __str__(self):
    +        return f"ScreenShareSession({self.session_id}, device={self.device_id})"

    __str__ references self.device_id, but ScreenShareSession has no device_id field (it has a device FK). This will raise AttributeError when stringified. Use self.device.device_id or self.device_id (the implicit FK id field) depending on what you want to display.

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    apps/mdm/models.py:1
    @@ -736,6 +800,116 @@ def fallback_firmware_version(self):
                 return software_info.get("androidBuildNumber")
     
     
    +class DeviceBindCode(models.Model):
    +    """One-time bootstrap code used to bind a device public key."""
    +
    +    device = models.ForeignKey(
    +        Device,
    +        on_delete=models.CASCADE,
    +        related_name="bind_codes",
    +    )
    +    code_hash = models.CharField(max_length=64, db_index=True)
    +    expires_at = models.DateTimeField()
    +    used_at = models.DateTimeField(null=True, blank=True)
    +    created_at = models.DateTimeField(auto_now_add=True)
    +
    +    class Meta:
    +        indexes = (
    +            models.Index(fields=["device", "expires_at"]),
    +            models.Index(fields=["used_at"]),
    +        )
    +
    +    def __str__(self):
    +        return f"BindCode({self.device_id}, expires={self.expires_at})"
    +
    +
    +class DeviceAuthChallenge(models.Model):
    +    """One-time challenge used for runtime device proof-of-possession."""
    +
    +    challenge_id = models.UUIDField(unique=True)
    +    device = models.ForeignKey(
    +        Device,
    +        on_delete=models.CASCADE,
    +        related_name="auth_challenges",
    +    )
    +    request_id = models.CharField(max_length=64)
    +    nonce = models.CharField(max_length=128)
    +    expires_at = models.DateTimeField()
    +    used_at = models.DateTimeField(null=True, blank=True)
    +    created_at = models.DateTimeField(auto_now_add=True)
    +
    +    class Meta:
    +        indexes = (
    +            models.Index(fields=["challenge_id"]),
    +            models.Index(fields=["device", "request_id"]),
    +            models.Index(fields=["expires_at"]),
    +            models.Index(fields=["used_at"]),
    +        )
    +
    +    def __str__(self):
    +        return f"AuthChallenge({self.challenge_id}, device={self.device_id})"
    +
    +
    +class ScreenShareSession(models.Model):
    +    """Single-use, short-lived session credential for screen-share websocket auth."""
    +
    +    session_id = models.UUIDField(unique=True)
    +    token_hash = models.CharField(max_length=64, db_index=True)
    +    device = models.ForeignKey(
    +        Device,
    +        on_delete=models.CASCADE,
    +        related_name="screen_share_sessions",
    +    )
    +    request_id = models.CharField(max_length=64)
    +    expires_at = models.DateTimeField()
    +    used_at = models.DateTimeField(null=True, blank=True)
    +    created_at = models.DateTimeField(auto_now_add=True)
    +
    +    class Meta:
    +        indexes = (
    +            models.Index(fields=["session_id"]),
    +            models.Index(fields=["device", "request_id"]),
    +            models.Index(fields=["expires_at"]),
    +            models.Index(fields=["used_at"]),
    +        )
    +
    +    def __str__(self):
    +        return f"ScreenShareSession({self.session_id}, device={self.device_id})"
    +
    +
    +class ScreenShareAuditLog(models.Model):
    +    """Audit trail for screen-share auth and session lifecycle events."""
    +
    +    event_type = models.CharField(max_length=64)
    +    device = models.ForeignKey(
    +        Device,
    +        on_delete=models.SET_NULL,
    +        related_name="screen_share_audit_logs",
    +        null=True,
    +        blank=True,
    +    )
    +    actor = models.ForeignKey(
    +        "users.User",
    +        on_delete=models.SET_NULL,
    +        related_name="screen_share_audit_logs",
    +        null=True,
    +        blank=True,
    +    )
    +    ip_address = models.GenericIPAddressField(null=True, blank=True)
    +    metadata_json = models.JSONField(default=dict, blank=True)
    +    created_at = models.DateTimeField(auto_now_add=True)
    +
    +    class Meta:
    +        indexes = (
    +            models.Index(fields=["event_type", "created_at"]),
    +            models.Index(fields=["device", "created_at"]),
    +            models.Index(fields=["actor", "created_at"]),
    +        )
    +
    +    def __str__(self):
    +        return f"AuditLog({self.event_type}, device={self.device_id}, {self.created_at})"

    __str__ references self.device_id, but ScreenShareAuditLog has no device_id field (it has a nullable device FK). This will raise AttributeError when stringified. Use self.device.device_id if self.device else None (or the implicit device_id FK id field) to avoid crashing on null device logs.

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    apps/mdm/views.py:1
    @@ -33,16 +41,430 @@
     from .mdms import get_active_mdm_instance
     from .models import (
         Device,
    +    DeviceAuthChallenge,
    +    DeviceBindCode,
         EnrollmentToken,
         Policy,
         PolicyApplication,
         PolicyVariable,
         PolicyVariableScope,
    +    ScreenShareAuditLog,
    +    ScreenShareSession,
     )
    +from .serializers import FIRMWARE_APP_PACKAGE
     from .tables import EnrollmentTokenTable, PolicyTable
    +from .utils import get_callback_domain
     
     logger = structlog.get_logger()
     
    +CHALLENGE_TTL_SECONDS = 60
    +SESSION_TTL_SECONDS = 60
    +TIMESTAMP_SKEW_SECONDS = 30
    +
    +
    +def _sha256_hex(value: str) -> str:
    +    return hashlib.sha256(value.encode("utf-8")).hexdigest()
    +
    +
    +def _client_ip(request) -> str:
    +    forwarded_for = request.headers.get("x-forwarded-for", "")
    +    if forwarded_for:
    +        return forwarded_for.split(",", 1)[0].strip()
    +    return request.META.get("REMOTE_ADDR", "")
    +
    +
    +def _is_rate_limited(scope: str, key: str, limit: int, window_seconds: int) -> bool:
    +    cache_key = f"mdm-auth-rl:{scope}:{key}"
    +    if cache.add(cache_key, 1, timeout=window_seconds):
    +        return False
    +    try:
    +        count = cache.incr(cache_key)
    +    except ValueError:
    +        cache.set(cache_key, 1, timeout=window_seconds)
    +        return False
    +    return count > limit
    +
    +
    +def _audit_event(event_type: str, request, device: Device | None = None, **metadata) -> None:
    +    ScreenShareAuditLog.objects.create(
    +        event_type=event_type,
    +        device=device,
    +        actor=request.user
    +        if getattr(request, "user", None) and request.user.is_authenticated
    +        else None,
    +        ip_address=_client_ip(request) or None,
    +        metadata_json=metadata or {},
    +    )
    +
    +
    +def _load_ec_public_key(public_key_pem: str):
    +    try:
    +        key = serialization.load_pem_public_key(public_key_pem.encode("utf-8"))
    +    except ValueError:
    +        return None
    +    if not isinstance(key, ec.EllipticCurvePublicKey):
    +        return None
    +    return key
    +
    +
    +def _find_device(identifier: str, **extra_filters):
    +    """Look up a device by device_id or serial_number.
    +
    +    The companion app sends its managed-config ``device_identifier`` value
    +    which may resolve to either ``Device.device_id`` (MDM identifier) or
    +    ``Device.serial_number`` depending on the policy variable template.
    +    """
    +    device = Device.objects.filter(device_id=identifier, **extra_filters).first()
    +    if device:
    +        return device
    +    return Device.objects.filter(serial_number=identifier, **extra_filters).first()
    +
    +
    +@csrf_exempt
    +@require_POST
    +def device_sync_policy_view(request):
    +    """Trigger a policy re-push for a device.
    +
    +    Accepts ``device_id`` in the JSON body.  If the device has an active auth
    +    key the request is currently accepted without signature verification (the
    +    client *should* send signed requests once full signed-request support is
    +    added, but for now we accept plain ``device_id`` regardless of key state).
    +    """
    +    if _is_rate_limited("sync-policy-ip", _client_ip(request), limit=10, window_seconds=60):
    +        return HttpResponse(status=429)
    +
    +    try:
    +        body = json.loads(request.body)
    +    except (json.JSONDecodeError, ValueError):
    +        return HttpResponse(status=400)
    +
    +    device_id = body.get("device_id", "").strip()
    +    if not device_id or len(device_id) > 255:
    +        return HttpResponse(status=400)
    +
    +    device = _find_device(device_id)
    +    if not device:
    +        return HttpResponse(status=404)
    +
    +    mdm = get_active_mdm_instance(organization=device.fleet.organization)
    +    if mdm:
    +        try:
    +            mdm.push_device_config(device)
    +        except Exception:
    +            logger.exception("push_device_config failed", device=device)
    +            return HttpResponse(status=502)
    +
    +    return HttpResponse(status=204)
    +
    +
    +@csrf_exempt
    +@require_POST
    +def device_fcm_token_view(request):
    +    """Register an FCM token for a device.
    +
    +    Accepts authentication via either:
    +    - ``device_id`` — identifies the device by its MDM device ID (requires key to be registered)
    +    - ``screen_stream_token`` — legacy auth (will be removed)
    +    """
    +    try:
    +        body = json.loads(request.body)
    +    except (json.JSONDecodeError, ValueError):
    +        return HttpResponse(status=400)
    +
    +    fcm_token = body.get("fcm_token", "").strip()
    +    if not fcm_token or len(fcm_token) > 256:
    +        return HttpResponse(status=400)
    +
    +    device_id = body.get("device_id", "").strip()
    +    screen_stream_token = body.get("screen_stream_token", "").strip()
    +
    +    if device_id:
    +        if len(device_id) > 255:
    +            return HttpResponse(status=400)
    +        device = _find_device(device_id, auth_key_state="active")
    +        if not device:
    +            return HttpResponse(status=404)
    +        device.fcm_token = fcm_token
    +        device.save(update_fields=["fcm_token"])
    +        updated = True
    +    elif screen_stream_token:

    This endpoint allows updating fcm_token with only a device_id (and the view is csrf_exempt). Since device_id is not a secret, anyone who knows/guesses it can overwrite the device’s FCM token, breaking screen-share triggers (and potentially redirecting future pushes). Consider requiring a signed request using the registered device key (e.g., signature over body + timestamp), or restrict token registration to the legacy screen_stream_token until signed requests are implemented.

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    apps/mdm/views.py:1
    @@ -33,16 +41,430 @@
     from .mdms import get_active_mdm_instance
     from .models import (
         Device,
    +    DeviceAuthChallenge,
    +    DeviceBindCode,
         EnrollmentToken,
         Policy,
         PolicyApplication,
         PolicyVariable,
         PolicyVariableScope,
    +    ScreenShareAuditLog,
    +    ScreenShareSession,
     )
    +from .serializers import FIRMWARE_APP_PACKAGE
     from .tables import EnrollmentTokenTable, PolicyTable
    +from .utils import get_callback_domain
     
     logger = structlog.get_logger()
     
    +CHALLENGE_TTL_SECONDS = 60
    +SESSION_TTL_SECONDS = 60
    +TIMESTAMP_SKEW_SECONDS = 30
    +
    +
    +def _sha256_hex(value: str) -> str:
    +    return hashlib.sha256(value.encode("utf-8")).hexdigest()
    +
    +
    +def _client_ip(request) -> str:
    +    forwarded_for = request.headers.get("x-forwarded-for", "")
    +    if forwarded_for:
    +        return forwarded_for.split(",", 1)[0].strip()
    +    return request.META.get("REMOTE_ADDR", "")
    +
    +
    +def _is_rate_limited(scope: str, key: str, limit: int, window_seconds: int) -> bool:
    +    cache_key = f"mdm-auth-rl:{scope}:{key}"
    +    if cache.add(cache_key, 1, timeout=window_seconds):
    +        return False
    +    try:
    +        count = cache.incr(cache_key)
    +    except ValueError:
    +        cache.set(cache_key, 1, timeout=window_seconds)
    +        return False
    +    return count > limit
    +
    +
    +def _audit_event(event_type: str, request, device: Device | None = None, **metadata) -> None:
    +    ScreenShareAuditLog.objects.create(
    +        event_type=event_type,
    +        device=device,
    +        actor=request.user
    +        if getattr(request, "user", None) and request.user.is_authenticated
    +        else None,
    +        ip_address=_client_ip(request) or None,
    +        metadata_json=metadata or {},
    +    )
    +
    +
    +def _load_ec_public_key(public_key_pem: str):
    +    try:
    +        key = serialization.load_pem_public_key(public_key_pem.encode("utf-8"))
    +    except ValueError:
    +        return None
    +    if not isinstance(key, ec.EllipticCurvePublicKey):
    +        return None
    +    return key
    +
    +
    +def _find_device(identifier: str, **extra_filters):
    +    """Look up a device by device_id or serial_number.
    +
    +    The companion app sends its managed-config ``device_identifier`` value
    +    which may resolve to either ``Device.device_id`` (MDM identifier) or
    +    ``Device.serial_number`` depending on the policy variable template.
    +    """
    +    device = Device.objects.filter(device_id=identifier, **extra_filters).first()
    +    if device:
    +        return device
    +    return Device.objects.filter(serial_number=identifier, **extra_filters).first()
    +
    +
    +@csrf_exempt
    +@require_POST
    +def device_sync_policy_view(request):
    +    """Trigger a policy re-push for a device.
    +
    +    Accepts ``device_id`` in the JSON body.  If the device has an active auth
    +    key the request is currently accepted without signature verification (the
    +    client *should* send signed requests once full signed-request support is
    +    added, but for now we accept plain ``device_id`` regardless of key state).
    +    """
    +    if _is_rate_limited("sync-policy-ip", _client_ip(request), limit=10, window_seconds=60):
    +        return HttpResponse(status=429)
    +
    +    try:
    +        body = json.loads(request.body)
    +    except (json.JSONDecodeError, ValueError):
    +        return HttpResponse(status=400)
    +
    +    device_id = body.get("device_id", "").strip()
    +    if not device_id or len(device_id) > 255:
    +        return HttpResponse(status=400)
    +
    +    device = _find_device(device_id)
    +    if not device:
    +        return HttpResponse(status=404)
    +
    +    mdm = get_active_mdm_instance(organization=device.fleet.organization)
    +    if mdm:
    +        try:
    +            mdm.push_device_config(device)
    +        except Exception:
    +            logger.exception("push_device_config failed", device=device)
    +            return HttpResponse(status=502)
    +
    +    return HttpResponse(status=204)
    +
    +
    +@csrf_exempt
    +@require_POST
    +def device_fcm_token_view(request):
    +    """Register an FCM token for a device.
    +
    +    Accepts authentication via either:
    +    - ``device_id`` — identifies the device by its MDM device ID (requires key to be registered)
    +    - ``screen_stream_token`` — legacy auth (will be removed)
    +    """
    +    try:
    +        body = json.loads(request.body)
    +    except (json.JSONDecodeError, ValueError):
    +        return HttpResponse(status=400)
    +
    +    fcm_token = body.get("fcm_token", "").strip()
    +    if not fcm_token or len(fcm_token) > 256:
    +        return HttpResponse(status=400)
    +
    +    device_id = body.get("device_id", "").strip()
    +    screen_stream_token = body.get("screen_stream_token", "").strip()
    +
    +    if device_id:
    +        if len(device_id) > 255:
    +            return HttpResponse(status=400)
    +        device = _find_device(device_id, auth_key_state="active")
    +        if not device:
    +            return HttpResponse(status=404)
    +        device.fcm_token = fcm_token
    +        device.save(update_fields=["fcm_token"])
    +        updated = True
    +    elif screen_stream_token:
    +        if len(screen_stream_token) > 64:
    +            return HttpResponse(status=400)
    +        updated = Device.objects.filter(screen_stream_token=screen_stream_token).update(
    +            fcm_token=fcm_token
    +        )
    +    else:
    +        return HttpResponse(status=400)
    +
    +    if not updated:
    +        return HttpResponse(status=404)
    +
    +    return HttpResponse(status=204)
    +
    +
    +@csrf_exempt
    +@require_POST
    +def device_register_key_view(request):
    +    if _is_rate_limited("register-key-ip", _client_ip(request), limit=20, window_seconds=60):
    +        return HttpResponse(status=429)
    +
    +    try:
    +        body = json.loads(request.body)
    +    except (json.JSONDecodeError, ValueError):
    +        return HttpResponse(status=400)
    +
    +    device_id = body.get("device_id", "").strip()
    +    bind_code = body.get("bind_code", "").strip()
    +    public_key_pem = body.get("public_key_pem", "").strip()
    +    package_name = body.get("package_name", "").strip()
    +    fcm_token = body.get("fcm_token", "").strip()
    +
    +    if not device_id or not public_key_pem or not package_name:
    +        return HttpResponse(status=400)
    +    if len(device_id) > 255 or len(public_key_pem) > 8192:
    +        return HttpResponse(status=400)
    +    if package_name != FIRMWARE_APP_PACKAGE:
    +        return HttpResponse(status=403)
    +
    +    device = _find_device(device_id)
    +    if not device:
    +        logger.warning("Device not found during key registration", device_id=device_id)
    +        return HttpResponse(status=404)
    +
    +    # Validate bind_code if provided; otherwise allow direct registration
    +    # (suitable for development — production should always require a bind code).
    +    if bind_code:

    Key registration succeeds when bind_code is omitted (commented as “dev mode”), which means any party that can identify a device (device_id/serial) can bind their own key and impersonate the device. This is a high-risk default for production. Consider enforcing bind-code requirement unless an explicit development setting is enabled (e.g., settings.DEBUG or ALLOW_UNAUTHENTICATED_DEVICE_KEY_REGISTRATION).

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    apps/mdm/views.py:1
    @@ -33,16 +41,430 @@
     from .mdms import get_active_mdm_instance
     from .models import (
         Device,
    +    DeviceAuthChallenge,
    +    DeviceBindCode,
         EnrollmentToken,
         Policy,
         PolicyApplication,
         PolicyVariable,
         PolicyVariableScope,
    +    ScreenShareAuditLog,
    +    ScreenShareSession,
     )
    +from .serializers import FIRMWARE_APP_PACKAGE
     from .tables import EnrollmentTokenTable, PolicyTable
    +from .utils import get_callback_domain
     
     logger = structlog.get_logger()
     
    +CHALLENGE_TTL_SECONDS = 60
    +SESSION_TTL_SECONDS = 60
    +TIMESTAMP_SKEW_SECONDS = 30
    +
    +
    +def _sha256_hex(value: str) -> str:
    +    return hashlib.sha256(value.encode("utf-8")).hexdigest()
    +
    +
    +def _client_ip(request) -> str:
    +    forwarded_for = request.headers.get("x-forwarded-for", "")
    +    if forwarded_for:
    +        return forwarded_for.split(",", 1)[0].strip()
    +    return request.META.get("REMOTE_ADDR", "")
    +
    +
    +def _is_rate_limited(scope: str, key: str, limit: int, window_seconds: int) -> bool:
    +    cache_key = f"mdm-auth-rl:{scope}:{key}"
    +    if cache.add(cache_key, 1, timeout=window_seconds):
    +        return False
    +    try:
    +        count = cache.incr(cache_key)
    +    except ValueError:
    +        cache.set(cache_key, 1, timeout=window_seconds)
    +        return False
    +    return count > limit
    +
    +
    +def _audit_event(event_type: str, request, device: Device | None = None, **metadata) -> None:
    +    ScreenShareAuditLog.objects.create(
    +        event_type=event_type,
    +        device=device,
    +        actor=request.user
    +        if getattr(request, "user", None) and request.user.is_authenticated
    +        else None,
    +        ip_address=_client_ip(request) or None,
    +        metadata_json=metadata or {},
    +    )
    +
    +
    +def _load_ec_public_key(public_key_pem: str):
    +    try:
    +        key = serialization.load_pem_public_key(public_key_pem.encode("utf-8"))
    +    except ValueError:
    +        return None
    +    if not isinstance(key, ec.EllipticCurvePublicKey):
    +        return None
    +    return key
    +
    +
    +def _find_device(identifier: str, **extra_filters):
    +    """Look up a device by device_id or serial_number.
    +
    +    The companion app sends its managed-config ``device_identifier`` value
    +    which may resolve to either ``Device.device_id`` (MDM identifier) or
    +    ``Device.serial_number`` depending on the policy variable template.
    +    """
    +    device = Device.objects.filter(device_id=identifier, **extra_filters).first()
    +    if device:
    +        return device
    +    return Device.objects.filter(serial_number=identifier, **extra_filters).first()
    +
    +
    +@csrf_exempt
    +@require_POST
    +def device_sync_policy_view(request):
    +    """Trigger a policy re-push for a device.
    +
    +    Accepts ``device_id`` in the JSON body.  If the device has an active auth
    +    key the request is currently accepted without signature verification (the
    +    client *should* send signed requests once full signed-request support is
    +    added, but for now we accept plain ``device_id`` regardless of key state).
    +    """
    +    if _is_rate_limited("sync-policy-ip", _client_ip(request), limit=10, window_seconds=60):
    +        return HttpResponse(status=429)
    +
    +    try:
    +        body = json.loads(request.body)
    +    except (json.JSONDecodeError, ValueError):
    +        return HttpResponse(status=400)
    +
    +    device_id = body.get("device_id", "").strip()
    +    if not device_id or len(device_id) > 255:
    +        return HttpResponse(status=400)
    +
    +    device = _find_device(device_id)
    +    if not device:
    +        return HttpResponse(status=404)
    +
    +    mdm = get_active_mdm_instance(organization=device.fleet.organization)
    +    if mdm:
    +        try:
    +            mdm.push_device_config(device)
    +        except Exception:
    +            logger.exception("push_device_config failed", device=device)
    +            return HttpResponse(status=502)
    +
    +    return HttpResponse(status=204)
    +
    +
    +@csrf_exempt
    +@require_POST
    +def device_fcm_token_view(request):
    +    """Register an FCM token for a device.
    +
    +    Accepts authentication via either:
    +    - ``device_id`` — identifies the device by its MDM device ID (requires key to be registered)
    +    - ``screen_stream_token`` — legacy auth (will be removed)
    +    """
    +    try:
    +        body = json.loads(request.body)
    +    except (json.JSONDecodeError, ValueError):
    +        return HttpResponse(status=400)
    +
    +    fcm_token = body.get("fcm_token", "").strip()
    +    if not fcm_token or len(fcm_token) > 256:
    +        return HttpResponse(status=400)
    +
    +    device_id = body.get("device_id", "").strip()
    +    screen_stream_token = body.get("screen_stream_token", "").strip()
    +
    +    if device_id:
    +        if len(device_id) > 255:
    +            return HttpResponse(status=400)
    +        device = _find_device(device_id, auth_key_state="active")
    +        if not device:
    +            return HttpResponse(status=404)
    +        device.fcm_token = fcm_token
    +        device.save(update_fields=["fcm_token"])
    +        updated = True
    +    elif screen_stream_token:
    +        if len(screen_stream_token) > 64:
    +            return HttpResponse(status=400)
    +        updated = Device.objects.filter(screen_stream_token=screen_stream_token).update(
    +            fcm_token=fcm_token
    +        )
    +    else:
    +        return HttpResponse(status=400)
    +
    +    if not updated:
    +        return HttpResponse(status=404)
    +
    +    return HttpResponse(status=204)
    +
    +
    +@csrf_exempt
    +@require_POST
    +def device_register_key_view(request):
    +    if _is_rate_limited("register-key-ip", _client_ip(request), limit=20, window_seconds=60):
    +        return HttpResponse(status=429)
    +
    +    try:
    +        body = json.loads(request.body)
    +    except (json.JSONDecodeError, ValueError):
    +        return HttpResponse(status=400)
    +
    +    device_id = body.get("device_id", "").strip()
    +    bind_code = body.get("bind_code", "").strip()
    +    public_key_pem = body.get("public_key_pem", "").strip()
    +    package_name = body.get("package_name", "").strip()
    +    fcm_token = body.get("fcm_token", "").strip()
    +
    +    if not device_id or not public_key_pem or not package_name:
    +        return HttpResponse(status=400)
    +    if len(device_id) > 255 or len(public_key_pem) > 8192:
    +        return HttpResponse(status=400)
    +    if package_name != FIRMWARE_APP_PACKAGE:
    +        return HttpResponse(status=403)
    +
    +    device = _find_device(device_id)
    +    if not device:
    +        logger.warning("Device not found during key registration", device_id=device_id)
    +        return HttpResponse(status=404)
    +
    +    # Validate bind_code if provided; otherwise allow direct registration
    +    # (suitable for development — production should always require a bind code).
    +    if bind_code:
    +        if len(bind_code) > 512:
    +            return HttpResponse(status=400)
    +        bind_code_hash = _sha256_hex(bind_code)
    +        bind_code_record = (
    +            DeviceBindCode.objects.filter(
    +                device=device,
    +                code_hash=bind_code_hash,
    +                used_at__isnull=True,
    +            )
    +            .order_by("-created_at")
    +            .first()
    +        )
    +        if not bind_code_record or bind_code_record.expires_at <= now():
    +            _audit_event("register_key_invalid_bind_code", request, device=device)
    +            return HttpResponse(status=401)
    +    else:
    +        bind_code_record = None
    +
    +    key = _load_ec_public_key(public_key_pem)
    +    if key is None:
    +        return HttpResponse(status=400)
    +
    +    public_key_der = key.public_bytes(
    +        encoding=serialization.Encoding.DER,
    +        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    +    )
    +    fingerprint = hashlib.sha256(public_key_der).hexdigest()
    +    bound_at = now()
    +
    +    update_fields = [
    +        "auth_public_key_pem",
    +        "auth_public_key_fingerprint",
    +        "auth_key_bound_at",
    +        "auth_key_version",
    +        "auth_key_state",
    +    ]
    +
    +    device.auth_public_key_pem = public_key_pem
    +    device.auth_public_key_fingerprint = fingerprint
    +    device.auth_key_bound_at = bound_at
    +    device.auth_key_version = max(0, device.auth_key_version) + 1
    +    device.auth_key_state = "active"
    +
    +    if fcm_token and len(fcm_token) <= 256:
    +        device.fcm_token = fcm_token
    +        update_fields.append("fcm_token")
    +
    +    device.save(update_fields=update_fields)
    +
    +    if bind_code_record:
    +        bind_code_record.used_at = bound_at
    +        bind_code_record.save(update_fields=["used_at"])
    +
    +    _audit_event(
    +        "register_key_success",
    +        request,
    +        device=device,
    +        key_fingerprint=fingerprint,
    +        key_version=device.auth_key_version,
    +    )
    +    return JsonResponse(
    +        {
    +            "key_fingerprint": fingerprint,
    +            "key_version": device.auth_key_version,
    +            "bound_at": bound_at.isoformat(),
    +        },
    +        status=201,
    +    )
    +
    +
    +@csrf_exempt
    +@require_POST
    +def device_auth_challenge_view(request):
    +    if _is_rate_limited("auth-challenge-ip", _client_ip(request), limit=60, window_seconds=60):
    +        return HttpResponse(status=429)
    +
    +    try:
    +        body = json.loads(request.body)
    +    except (json.JSONDecodeError, ValueError):
    +        return HttpResponse(status=400)
    +
    +    device_id = body.get("device_id", "").strip()
    +    request_id = body.get("request_id", "").strip()
    +    if not device_id or not request_id:
    +        return HttpResponse(status=400)
    +    if len(device_id) > 255 or len(request_id) > 64:
    +        return HttpResponse(status=400)
    +
    +    device = _find_device(device_id, auth_key_state="active")
    +    if not device or not device.auth_public_key_pem:
    +        return HttpResponse(status=404)
    +
    +    challenge_id = uuid.uuid4()
    +    challenge = DeviceAuthChallenge.objects.create(
    +        challenge_id=challenge_id,
    +        device=device,
    +        request_id=request_id,
    +        nonce=secrets.token_urlsafe(32),
    +        expires_at=now() + dt.timedelta(seconds=CHALLENGE_TTL_SECONDS),
    +    )
    +
    +    _audit_event(
    +        "auth_challenge_issued",
    +        request,
    +        device=device,
    +        challenge_id=str(challenge.challenge_id),
    +        request_id=request_id,
    +    )
    +
    +    return JsonResponse(
    +        {
    +            "challenge_id": str(challenge.challenge_id),
    +            "nonce": challenge.nonce,
    +            "expires_at": challenge.expires_at.isoformat(),
    +        }
    +    )
    +
    +
    +@csrf_exempt
    +@require_POST
    +def device_auth_verify_view(request):
    +    if _is_rate_limited("auth-verify-ip", _client_ip(request), limit=120, window_seconds=60):
    +        return HttpResponse(status=429)
    +
    +    try:
    +        body = json.loads(request.body)
    +    except (json.JSONDecodeError, ValueError):
    +        return HttpResponse(status=400)
    +
    +    challenge_id_raw = str(body.get("challenge_id", "")).strip()
    +    device_id = body.get("device_id", "").strip()
    +    request_id = body.get("request_id", "").strip()
    +    timestamp_raw = str(body.get("timestamp", "")).strip()
    +    signature_b64 = body.get("signature_b64", "").strip()
    +
    +    if (
    +        not challenge_id_raw
    +        or not device_id
    +        or not request_id
    +        or not timestamp_raw
    +        or not signature_b64
    +    ):
    +        return HttpResponse(status=400)
    +
    +    try:
    +        challenge_uuid = uuid.UUID(challenge_id_raw)
    +    except ValueError:
    +        return HttpResponse(status=400)
    +
    +    challenge = (
    +        DeviceAuthChallenge.objects.select_related("device")
    +        .filter(
    +            challenge_id=challenge_uuid,
    +            request_id=request_id,
    +        )
    +        .filter(Q(device__device_id=device_id) | Q(device__serial_number=device_id))
    +        .first()
    +    )
    +    if not challenge:
    +        return HttpResponse(status=404)
    +    if challenge.used_at is not None:
    +        return HttpResponse(status=409)
    +    if challenge.expires_at <= now():
    +        return HttpResponse(status=410)

    Challenge replay protection is not atomic: the code checks challenge.used_at and then sets it later. Two concurrent verify requests could both pass the used_at is None check and each create a session. Use an atomic update (e.g., filter(..., used_at__isnull=True).update(used_at=...) and verify rows-updated == 1) or a transaction with select_for_update() before issuing a session.

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    apps/publish_mdm/screen_consumers.py:1
    @@ -0,0 +1,175 @@
    +"""WebSocket consumers for live device screen sharing.
    +
    +A device running the firmware app connects to ``DeviceScreenPublisherConsumer``
    +authenticated by a short-lived session token obtained via challenge-response
    +(passed in the URL).  Every binary frame (a JPEG byte string) it sends is
    +broadcast to a Channels group named ``device-screen-<device_pk>``. The
    +browser-side viewer connects to ``DeviceScreenViewerConsumer`` (auth via the
    +standard Django session) and is joined to that same group, receiving each frame
    +and rendering it.
    +"""
    +
    +from __future__ import annotations
    +
    +import asyncio
    +import hashlib
    +
    +import structlog
    +from channels.db import database_sync_to_async
    +from channels.generic.websocket import AsyncWebsocketConsumer
    +
    +from apps.mdm.models import Device, ScreenShareSession
    +
    +logger = structlog.getLogger(__name__)
    +
    +# Tracks how many browser viewers are watching each device (keyed by device_pk).
    +# Scoped to the process — sufficient with InMemoryChannelLayer.
    +_viewer_counts: dict[int, int] = {}
    +_viewer_counts_lock = asyncio.Lock()
    +
    +
    +def _group_name(device_pk: int) -> str:
    +    return f"device-screen-{device_pk}"
    +
    +
    +class DeviceScreenPublisherConsumer(AsyncWebsocketConsumer):
    +    """Receives binary screen frames from a device and fans them out."""
    +
    +    async def connect(self):
    +        token = self.scope["url_route"]["kwargs"]["token"]
    +        self.device_pk = await self._lookup_device_pk(token)
    +        if self.device_pk is None:
    +            logger.warning("Device screen publish: invalid token")
    +            await self.close(code=4401)
    +            return
    +        self.group_name = _group_name(self.device_pk)
    +        await self.channel_layer.group_add(self.group_name, self.channel_name)
    +        await self.accept()
    +        # Notify any current viewers that the device is now publishing
    +        await self.channel_layer.group_send(
    +            self.group_name, {"type": "device.status", "status": "connected"}
    +        )
    +        logger.info("Device screen publisher connected", device_pk=self.device_pk)
    +
    +    async def disconnect(self, code):
    +        if getattr(self, "group_name", None):
    +            await self.channel_layer.group_send(
    +                self.group_name, {"type": "device.status", "status": "disconnected"}
    +            )
    +            await self.channel_layer.group_discard(self.group_name, self.channel_name)
    +
    +    async def receive(self, text_data=None, bytes_data=None):
    +        if bytes_data is None:
    +            return
    +        await self.channel_layer.group_send(
    +            self.group_name, {"type": "device.frame", "data": bytes_data}
    +        )
    +
    +    async def device_frame(self, event):
    +        # Publisher does not need to receive its own frames
    +        return
    +
    +    async def device_status(self, event):
    +        return
    +
    +    async def device_stop(self, event):
    +        """All viewers have disconnected — tell the device to stop streaming."""
    +        await self.send(text_data='{"action":"stop"}')
    +        await self.close()
    +
    +    @staticmethod
    +    @database_sync_to_async
    +    def _lookup_device_pk(token: str) -> int | None:
    +        """Look up the device PK from a session token (challenge-response flow)
    +        or legacy screen_stream_token."""
    +        if not token:
    +            return None
    +        # Try session token first (new auth flow).
    +        token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
    +        try:
    +            from django.utils.timezone import now  # noqa: PLC0415
    +
    +            session = ScreenShareSession.objects.select_related("device").get(
    +                token_hash=token_hash,
    +                used_at__isnull=True,
    +                expires_at__gt=now(),
    +            )
    +            # Mark as used (single-use).
    +            ScreenShareSession.objects.filter(pk=session.pk, used_at__isnull=True).update(
    +                used_at=now()
    +            )
    +            return session.device_id

    Single-use session enforcement isn’t guaranteed under concurrency: you get() a ScreenShareSession with used_at__isnull=True and then separately update() it, but you don’t check whether the update actually modified a row. Two concurrent connections can both obtain the same session and both be accepted. Consider making the “mark used” step atomic and only returning the device pk when exactly one row was updated.

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    apps/publish_mdm/screen_consumers.py:1
    @@ -0,0 +1,175 @@
    +"""WebSocket consumers for live device screen sharing.
    +
    +A device running the firmware app connects to ``DeviceScreenPublisherConsumer``
    +authenticated by a short-lived session token obtained via challenge-response
    +(passed in the URL).  Every binary frame (a JPEG byte string) it sends is
    +broadcast to a Channels group named ``device-screen-<device_pk>``. The
    +browser-side viewer connects to ``DeviceScreenViewerConsumer`` (auth via the
    +standard Django session) and is joined to that same group, receiving each frame
    +and rendering it.
    +"""
    +
    +from __future__ import annotations
    +
    +import asyncio
    +import hashlib
    +
    +import structlog
    +from channels.db import database_sync_to_async
    +from channels.generic.websocket import AsyncWebsocketConsumer
    +
    +from apps.mdm.models import Device, ScreenShareSession
    +
    +logger = structlog.getLogger(__name__)
    +
    +# Tracks how many browser viewers are watching each device (keyed by device_pk).
    +# Scoped to the process — sufficient with InMemoryChannelLayer.
    +_viewer_counts: dict[int, int] = {}
    +_viewer_counts_lock = asyncio.Lock()
    +
    +
    +def _group_name(device_pk: int) -> str:
    +    return f"device-screen-{device_pk}"
    +
    +
    +class DeviceScreenPublisherConsumer(AsyncWebsocketConsumer):
    +    """Receives binary screen frames from a device and fans them out."""
    +
    +    async def connect(self):
    +        token = self.scope["url_route"]["kwargs"]["token"]
    +        self.device_pk = await self._lookup_device_pk(token)
    +        if self.device_pk is None:
    +            logger.warning("Device screen publish: invalid token")
    +            await self.close(code=4401)
    +            return
    +        self.group_name = _group_name(self.device_pk)
    +        await self.channel_layer.group_add(self.group_name, self.channel_name)
    +        await self.accept()
    +        # Notify any current viewers that the device is now publishing
    +        await self.channel_layer.group_send(
    +            self.group_name, {"type": "device.status", "status": "connected"}
    +        )
    +        logger.info("Device screen publisher connected", device_pk=self.device_pk)
    +
    +    async def disconnect(self, code):
    +        if getattr(self, "group_name", None):
    +            await self.channel_layer.group_send(
    +                self.group_name, {"type": "device.status", "status": "disconnected"}
    +            )
    +            await self.channel_layer.group_discard(self.group_name, self.channel_name)
    +
    +    async def receive(self, text_data=None, bytes_data=None):
    +        if bytes_data is None:
    +            return
    +        await self.channel_layer.group_send(
    +            self.group_name, {"type": "device.frame", "data": bytes_data}
    +        )
    +
    +    async def device_frame(self, event):
    +        # Publisher does not need to receive its own frames
    +        return
    +
    +    async def device_status(self, event):
    +        return
    +
    +    async def device_stop(self, event):
    +        """All viewers have disconnected — tell the device to stop streaming."""
    +        await self.send(text_data='{"action":"stop"}')
    +        await self.close()
    +
    +    @staticmethod
    +    @database_sync_to_async
    +    def _lookup_device_pk(token: str) -> int | None:
    +        """Look up the device PK from a session token (challenge-response flow)
    +        or legacy screen_stream_token."""
    +        if not token:
    +            return None
    +        # Try session token first (new auth flow).
    +        token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
    +        try:
    +            from django.utils.timezone import now  # noqa: PLC0415
    +
    +            session = ScreenShareSession.objects.select_related("device").get(
    +                token_hash=token_hash,
    +                used_at__isnull=True,
    +                expires_at__gt=now(),
    +            )
    +            # Mark as used (single-use).
    +            ScreenShareSession.objects.filter(pk=session.pk, used_at__isnull=True).update(
    +                used_at=now()
    +            )
    +            return session.device_id
    +        except ScreenShareSession.DoesNotExist:
    +            pass
    +        # Fallback: legacy screen_stream_token.
    +        try:
    +            return Device.objects.get(screen_stream_token=token).pk
    +        except (Device.DoesNotExist, Device.MultipleObjectsReturned):
    +            return None
    +
    +
    +class DeviceScreenViewerConsumer(AsyncWebsocketConsumer):
    +    """Streams binary screen frames to an authenticated browser session."""
    +
    +    async def connect(self):
    +        user = self.scope.get("user")
    +        if not user or not user.is_authenticated:
    +            await self.close(code=4401)
    +            return
    +        self.device_pk = int(self.scope["url_route"]["kwargs"]["device_pk"])
    +        if not await self._user_can_view(user, self.device_pk):
    +            await self.close(code=4403)
    +            return
    +        self.group_name = _group_name(self.device_pk)
    +        await self.channel_layer.group_add(self.group_name, self.channel_name)
    +        await self.accept()
    +        count = await self._increment_viewer_count(self.device_pk, delta=1)
    +        logger.info("Screen viewer connected", device_pk=self.device_pk, viewer_count=count)
    +
    +    async def disconnect(self, code):
    +        if getattr(self, "group_name", None):
    +            remaining = await self._increment_viewer_count(self.device_pk, delta=-1)
    +            logger.info(
    +                "Screen viewer disconnected",
    +                device_pk=self.device_pk,
    +                viewer_count=remaining,
    +            )
    +            if remaining <= 0:
    +                logger.info("Last viewer left, sending stop to device", device_pk=self.device_pk)
    +                await self.channel_layer.group_send(self.group_name, {"type": "device.stop"})
    +            await self.channel_layer.group_discard(self.group_name, self.channel_name)

    Viewer tracking uses a process-local dict, but config/settings/base.py now supports a Redis channel layer intended for multi-worker deployments. In a multi-process setup, each worker will maintain its own viewer count, and one worker may send device.stop while viewers are still connected on another worker. Consider either (1) implementing a shared counter (e.g., Redis INCR/DECR) when using Redis channel layers, or (2) removing/guarding the “stop on last viewer” behavior for multi-worker deployments.

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    config/settings/base.py:1
    @@ -130,6 +130,24 @@
     ASGI_APPLICATION = "config.asgi.application"
     WSGI_APPLICATION = "config.wsgi.application"
     
    +# Channels channel layer. Default to the in-memory layer for local development,
    +# but allow deployments to opt into a shared Redis-backed layer so group sends
    +# and fanout work correctly across multiple ASGI workers or pods.
    +_channel_layers_redis_url = os.getenv("CHANNEL_LAYERS_REDIS_URL")
    +if _channel_layers_redis_url:
    +    CHANNEL_LAYERS = {
    +        "default": {
    +            "BACKEND": "channels_redis.core.RedisChannelLayer",
    +            "CONFIG": {
    +                "hosts": [_channel_layers_redis_url],
    +            },
    +        },
    +    }

    CHANNEL_LAYERS is configured to use channels_redis.core.RedisChannelLayer when CHANNEL_LAYERS_REDIS_URL is set, but channels-redis doesn’t appear in the project dependencies/lockfile. If someone sets this env var in a deployment, Django will crash on startup. Either add channels-redis as a dependency or guard this branch with an import check / clearer startup error message.

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    apps/mdm/views.py:1
    @@ -197,11 +619,21 @@ def _push_policy_to_mdm(policy, request):
             logger.error("Failed to push base policy to MDM", policy=policy, exc_info=True)
         child_devices = Device.objects.filter(
             fleet__policy=policy,
    -        raw_mdm_device__policyName__endswith=F("device_id"),
    +        raw_mdm_device__isnull=False,
         )
         device_pks = list(child_devices.values_list("pk", flat=True))
         if not device_pks:
    +        logger.debug(
    +            "No enrolled devices found for policy; skipping per-device push",
    +            policy=policy,
    +        )
             return
    +    logger.debug(
    +        "Queuing per-device config push via Dagster",
    +        policy=policy,
    +        device_count=len(device_pks),
    +        device_pks=device_pks,

    This debug log includes the full device_pks list. For large fleets this can create very large log lines and increase log ingestion costs/noise. Prefer logging only device_count (and possibly a truncated sample) rather than the full list.

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    docs/src/local-development/infisical.rst:1
    @@ -25,14 +25,23 @@ The URL you use to access Infisical will be your value for the ``INFISICAL_API_U
     Setting up a KMS Project
     ------------------------
     
    -Go to the KMS page in Infisical and create a project:
    +Once logged in, navigate to http://localhost:8888/ and you'll be direct to the

    Grammar: “you’ll be direct to” should be “you’ll be directed to”.

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    docs/src/local-development/setup.rst:1
    @@ -58,6 +58,16 @@ rather use Docker, see :doc:`../running/docker-compose`.
         # host is "localhost" and Google's API rejects it.
         export ANDROID_ENTERPRISE_CALLBACK_DOMAIN=
     
    +    # Firebase project ID for FCM (screen-share push notifications to the firmware app).
    +    # Required when using a Firebase project whose ID differs from the GCP project that
    +    # hosts the Android Enterprise service account.
    +    export FIREBASE_PROJECT_ID=
    +
    +    # Install type (AVAILABLE, FORCE_INSTALLED , etc.) for the Android firmware companion app.

    Minor punctuation/spacing: there’s an extra space before the comma in “FORCE_INSTALLED ,”.

    Copilot Copilot commented on code on May 12, 2026 18:49 UTC
    Code Review
    apps/publish_mdm/views.py:1
    @@ -1540,3 +1538,52 @@ def get_context_data(self, **kwargs):
                 .select_related("android_enterprise")
             )
             return context
    +
    +
    +@login_required
    +def device_screen_view(request: HttpRequest, organization_slug, device_pk):
    +    """Render the live screen viewer page for a device.
    +
    +    Sends an FCM trigger with a unique ``request_id`` so the device can use
    +    challenge-response auth to obtain a session token for the WebSocket.
    +    """
    +    from apps.mdm.models import Device  # noqa: PLC0415
    +
    +    device = get_object_or_404(
    +        Device.objects.select_related("fleet__organization"),
    +        pk=device_pk,
    +        fleet__organization=request.organization,
    +    )
    +
    +    request_id = str(uuid.uuid4())
    +
    +    # Send FCM trigger so the app shows the MediaProjection consent dialog.
    +    logger.info(
    +        "device_screen_view: FCM trigger",
    +        device_pk=device.pk,
    +        has_fcm_token=bool(device.fcm_token),
    +        request_id=request_id,
    +    )
    +    if device.fcm_token:
    +        sent = send_start_screen_share(device.fcm_token, request_id=request_id)
    +        logger.info("device_screen_view: FCM send result", device_pk=device.pk, sent=sent)

    This GET view has a significant side effect: it sends an FCM push every time the page is loaded/refreshed. That breaks the “safe/idempotent GET” expectation and can lead to accidental/spam triggers (e.g., link prefetchers, refreshes, crawlers hitting authenticated pages). Consider moving the FCM trigger behind an explicit POST action (or a separate endpoint called via JS) with CSRF protection, and keep the viewer page render side-effect-free.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on May 12, 2026 18:49 UTC
    Reviewer

    Pull request overview

    Copilot reviewed 34 out of 45 changed files in this pull request and generated 14 comments.

    tobiasmcnulty tobiasmcnulty commented on May 13, 2026 01:39 UTC
    Author

    @copilot apply changes based on the comments in this thread

    Copilot Copilot commented on May 13, 2026 01:57 UTC
    Bot

    @copilot apply changes based on the comments in this thread

    Applied all changes from the review thread in commits 4211dc0 and 834fdbc:

  • __str__ fixes (models.py): DeviceAuthChallenge, ScreenShareSession, and ScreenShareAuditLog now use self.device.device_id (the human-readable AMAPI ID) with null guards (self.device_id is not None) to match the nullable FK pattern used in ScreenShareAuditLog.
  • Removed insecure device_id auth path from device_fcm_token_view — only screen_stream_token (a secret) is now accepted. FCM token can still be set during authenticated key registration via device_register_key_view. Removed test_fcm_token_via_device_id test and added oversized-token 400 tests.
  • Atomic challenge replay protection (device_auth_verify_view): replaced non-atomic challenge.save() with filter(used_at__isnull=True).update(used_at=...) + row-count check.
  • Atomic session single-use enforcement (_lookup_device_pk consumer): now checks that the update() actually modified a row before returning the device PK.
  • Multi-process viewer count caveat (screen_consumers.py): added a comment explaining the process-local counter limitation and when a Redis counter would be needed.
  • channels-redis~=4.3 added to pyproject.toml (enables CHANNEL_LAYERS_REDIS_URL without a crash on startup).
  • Debug log (views.py): removed device_pks=device_pks from the log call; only device_count is logged.
  • Docs: "directed to" (infisical.rst), "FORCE_INSTALLED," (setup.rst).
  • FCM trigger moved to POST (device_screen_trigger_view): the GET viewer page is now side-effect-free. The template calls the new POST endpoint via fetch() with X-CSRFToken on page load. URL: o/<slug>/devices/<pk>/screen/trigger/.
  • [!WARNING]

    > <details>

    <summary>Firewall rules blocked me from connecting to one or more addresses (expand for details)</summary>

    > #### I tried to connect to the following addresses, but was blocked by firewall rules:

    > - accounts.google.com

    - Triggering command: /home/REDACTED/work/publish-mdm/publish-mdm/.venv/bin/pytest pytest tests/ -x -q --no-cov --noprofile (dns block)

    - Triggering command: /home/REDACTED/work/publish-mdm/publish-mdm/.venv/bin/pytest pytest tests/mdm/ tests/publish_mdm/test_screen_consumers.py -x -q --no-cov (dns block)

    > If you need me to access, download, or install something from one of these locations, you can either:

    > - Configure Actions setup steps to set up my environment, which run before the firewall is enabled

    - Add the appropriate URLs or hosts to the custom allowlist in this repository's Copilot coding agent settings (admins only)

    > </details>

    Copilot Copilot commented on code on May 13, 2026 02:15 UTC
    Code Review
    docker-compose.yaml:1
    @@ -12,7 +12,7 @@ services:
         ports:
           - "9062:5432"
         volumes:
    -      - dev_pgdata:/var/lib/postgresql/data
    +      - dev_pgdata:/var/lib/postgresql
     

    Mounting the Postgres data volume at /var/lib/postgresql changes the effective PGDATA path (default is /var/lib/postgresql/data). This will cause existing dev_pgdata volumes (previously storing the cluster root) to be ignored and Postgres to re-initialize a new cluster under /var/lib/postgresql/data, effectively “losing” persisted data. Mount the volume at /var/lib/postgresql/data (or explicitly set PGDATA to match the mount) to preserve existing data.

    This issue also appears on line 49 of the same file.

    Copilot Copilot commented on code on May 13, 2026 02:15 UTC
    Code Review
    apps/mdm/views.py:1
    @@ -33,16 +42,532 @@
     from .mdms import get_active_mdm_instance
     from .models import (
         Device,
    +    DeviceAttestationNonce,
    +    DeviceAuthChallenge,
         EnrollmentToken,
         Policy,
         PolicyApplication,
         PolicyVariable,
         PolicyVariableScope,
    +    ScreenShareAuditLog,
    +    ScreenShareSession,
     )
    +from .serializers import FIRMWARE_APP_PACKAGE
     from .tables import EnrollmentTokenTable, PolicyTable
    +from .utils import get_callback_domain
     
     logger = structlog.get_logger()
     
    +CHALLENGE_TTL_SECONDS = 60
    +SESSION_TTL_SECONDS = 60
    +TIMESTAMP_SKEW_SECONDS = 30
    +
    +
    +def _sha256_hex(value: str) -> str:
    +    return hashlib.sha256(value.encode("utf-8")).hexdigest()
    +
    +
    +def _client_ip(request) -> str:
    +    forwarded_for = request.headers.get("x-forwarded-for", "")
    +    if forwarded_for:
    +        return forwarded_for.split(",", 1)[0].strip()
    +    return request.META.get("REMOTE_ADDR", "")
    +
    +
    +def _is_rate_limited(scope: str, key: str, limit: int, window_seconds: int) -> bool:
    +    cache_key = f"mdm-auth-rl:{scope}:{key}"
    +    if cache.add(cache_key, 1, timeout=window_seconds):
    +        return False
    +    try:
    +        count = cache.incr(cache_key)
    +    except ValueError:
    +        cache.set(cache_key, 1, timeout=window_seconds)
    +        return False
    +    return count > limit
    +
    +
    +def _audit_event(event_type: str, request, device: Device | None = None, **metadata) -> None:
    +    ScreenShareAuditLog.objects.create(
    +        event_type=event_type,
    +        device=device,
    +        actor=request.user
    +        if getattr(request, "user", None) and request.user.is_authenticated
    +        else None,
    +        ip_address=_client_ip(request) or None,
    +        metadata_json=metadata or {},
    +    )
    +
    +
    +def _load_ec_public_key(public_key_pem: str):
    +    try:
    +        key = serialization.load_pem_public_key(public_key_pem.encode("utf-8"))
    +    except ValueError:
    +        return None
    +    if not isinstance(key, ec.EllipticCurvePublicKey):
    +        return None
    +    return key
    +
    +
    +def _find_device(identifier: str, **extra_filters):
    +    """Look up a device by device_id or serial_number.
    +
    +    The companion app sends its managed-config ``device_identifier`` value
    +    which may resolve to either ``Device.device_id`` (MDM identifier) or
    +    ``Device.serial_number`` depending on the policy variable template.
    +    """
    +    device = Device.objects.filter(device_id=identifier, **extra_filters).first()
    +    if device:
    +        return device
    +    return Device.objects.filter(serial_number=identifier, **extra_filters).first()
    +
    +
    +@csrf_exempt
    +@require_POST
    +def device_sync_policy_view(request):
    +    """Trigger a policy re-push for a device.
    +
    +    Accepts ``device_id`` in the JSON body.  If the device has an active auth
    +    key the request is currently accepted without signature verification (the
    +    client *should* send signed requests once full signed-request support is
    +    added, but for now we accept plain ``device_id`` regardless of key state).
    +    """

    This endpoint explicitly accepts requests without any signature/secret (it only takes a device_id). That makes it easy for anyone who can guess/learn a device identifier to trigger repeated mdm.push_device_config calls (operational abuse/DoS). Consider requiring a valid device auth signature (challenge/verify) or a per-device secret, and/or add rate limiting keyed by device as well as IP.

    This issue also appears in the following locations of the same file:

  • line 198

  • line 265
  • Copilot Copilot commented on code on May 13, 2026 02:15 UTC
    Code Review
    config/templates/publish_mdm/device_screen.html:1
    @@ -0,0 +1,84 @@
    +{% extends "base.html" %}
    +{% block page_header %}
    +    <span class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between w-full">
    +        <span>{{ breadcrumbs.crumbs|last }}</span>
    +        <div class="flex items-center gap-2">
    +            <span id="screen-status"
    +                  class="text-sm px-2.5 py-0.5 rounded-full bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300">
    +                Connecting…
    +            </span>
    +            <a href="{% url 'publish_mdm:device-detail' request.organization.slug device.pk %}"
    +               class="btn btn-outline">Back to device</a>
    +        </div>
    +    </span>
    +{% endblock page_header %}
    +{% block content %}
    +    <div class="p-4 bg-white rounded-lg border border-gray-200 dark:bg-gray-800 dark:border-gray-700">
    +        <p class="mb-3 text-sm text-gray-600 dark:text-gray-400">
    +            The device must have the firmware app installed and a screen-share
    +            session must be started on the device. The session uses a
    +            per-device token delivered via Android Enterprise managed
    +            configuration.
    +        </p>
    +        <div class="bg-black rounded-md flex items-center justify-center min-h-[40vh]">
    +            <img id="screen-frame"
    +                 alt="Device screen"
    +                 width=""
    +                 height=""

    The img tag includes width and height attributes set to empty strings. Empty dimension attributes are invalid HTML and can lead to layout/validation issues. Prefer omitting these attributes (or set numeric values) and rely on the existing CSS classes for sizing.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on May 13, 2026 02:15 UTC
    Reviewer

    Pull request overview

    Copilot reviewed 37 out of 48 changed files in this pull request and generated 3 comments.

    <details>
    <summary>Comments suppressed due to low confidence (3)</summary>

    docker-compose.yaml:54
    Same issue as the main db service: mounting infisical_pgdata at /var/lib/postgresql instead of /var/lib/postgresql/data will break existing volumes and trigger a fresh initdb under /var/lib/postgresql/data. Either mount at /var/lib/postgresql/data or set PGDATA to /var/lib/postgresql (and ensure init scripts use it).

        image: postgres:18-alpine
        restart: always
        env_file: .infisical.env
        volumes:
          - infisical_pgdata:/var/lib/postgresql
        ports:
    

    apps/mdm/views.py:202
    This nonce issuance endpoint is unauthenticated (device_id in JSON is sufficient). Because the nonce is later used to bind a public key to the device, an attacker who knows/guesses a device identifier can obtain nonces for that device and attempt to register their own key. Require an authentication factor (e.g., per-device secret from managed config, or enrollment-specific secret) before issuing nonces.
        a hardware-backed key pair.  The nonce is valid for 10 minutes and can only
        be used once.
    
        Accepts ``device_id`` in the JSON body.
        """
    

    apps/mdm/views.py:269
  • Key registration is gated only by device_id + package_name. In combination with the unauthenticated nonce issuance endpoint, this allows hijacking a device record by registering a new attested key for a target device_id. Add a device-held secret (screen_stream_token/enrollment secret) or validate enrollment_specific_id against authoritative MDM data before accepting the key.

  •     device_id = body.get("device_id", "").strip()
        package_name = body.get("package_name", "").strip()
        fcm_token = body.get("fcm_token", "").strip()
        certificate_chain = body.get("certificate_chain")
        public_key_pem = body.get("public_key_pem", "").strip()
    

    </details>

    Copilot Copilot commented on code on May 13, 2026 11:00 UTC
    Code Review
    apps/publish_mdm/views.py:1
    @@ -1540,3 +1538,70 @@ def get_context_data(self, **kwargs):
                 .select_related("android_enterprise")
             )
             return context
    +
    +
    +@login_required
    +def device_screen_view(request: HttpRequest, organization_slug, device_pk):
    +    """Render the live screen viewer page for a device.
    +
    +    The page itself has no side effects.  The FCM trigger is sent by a separate
    +    POST endpoint (device-screen-trigger) called from the browser via fetch,
    +    so that refreshing the viewer page does not spam the device with FCM pushes.
    +    """
    +    from apps.mdm.models import Device  # noqa: PLC0415
    +
    +    device = get_object_or_404(
    +        Device.objects.select_related("fleet__organization"),
    +        pk=device_pk,
    +        fleet__organization=request.organization,
    +    )
    +
    +    device_label = device.device_id or device.name or f"Device {device.pk}"
    +    context = {
    +        "device": device,
    +        "device_label": device_label,
    +        "breadcrumbs": Breadcrumbs.from_items(
    +            request=request,
    +            items=[
    +                ("Devices", "devices-list"),
    +                (device_label, "device-detail", [device.pk]),
    +                ("Live Screen", "device-screen-view", [device.pk]),
    +            ],
    +        ),
    +    }
    +    return render(request, "publish_mdm/device_screen.html", context)
    +
    +
    +@login_required
    +@require_POST
    +def device_screen_trigger_view(request: HttpRequest, organization_slug, device_pk):
    +    """Send an FCM trigger to the device to start the screen-share consent flow.
    +
    +    Called via fetch from the browser viewer page.  Separating the trigger into
    +    a POST prevents accidental re-triggers on page refresh or link prefetch.
    +    """
    +    from apps.mdm.models import Device  # noqa: PLC0415
    +
    +    device = get_object_or_404(
    +        Device.objects.select_related("fleet__organization"),
    +        pk=device_pk,
    +        fleet__organization=request.organization,
    +    )
    +
    +    request_id = str(uuid.uuid4())
    +    logger.info(
    +        "device_screen_trigger_view: FCM trigger",
    +        device_pk=device.pk,
    +        has_fcm_token=bool(device.fcm_token),
    +        request_id=request_id,
    +    )
    +    if device.fcm_token:
    +        sent = send_start_screen_share(device.fcm_token, request_id=request_id)
    +        logger.info("device_screen_trigger_view: FCM send result", device_pk=device.pk, sent=sent)
    +        return HttpResponse(status=204)
    +

    device_screen_trigger_view returns HTTP 204 even when send_start_screen_share(...) returns False (FCM send failure). This makes the UI/API report success when the trigger wasn't actually delivered; consider returning an error status (e.g. 502) when sent is false, and only 204 on success.

    Copilot Copilot commented on code on May 13, 2026 11:00 UTC
    Code Review
    docker-compose.yaml:1
    @@ -12,7 +12,7 @@ services:
         ports:
           - "9062:5432"
         volumes:
    -      - dev_pgdata:/var/lib/postgresql/data
    +      - dev_pgdata:/var/lib/postgresql
     

    The Postgres data volume is mounted at /var/lib/postgresql, but the official Postgres image’s default PGDATA is /var/lib/postgresql/data. Mounting the parent directory can lead to initdb/permission surprises and differs from the standard layout; consider mounting the volume at /var/lib/postgresql/data (or explicitly set PGDATA to match the mount).

    This issue also appears on line 50 of the same file.

    Copilot Copilot commented on code on May 13, 2026 11:00 UTC
    Code Review
    config/settings/base.py:1
    @@ -461,3 +479,23 @@
     # derived from the incoming request, which is useful for local development where the request
     # host is "localhost" and Google's API rejects it.
     ANDROID_ENTERPRISE_CALLBACK_DOMAIN = os.getenv("ANDROID_ENTERPRISE_CALLBACK_DOMAIN", "")
    +
    +# Controls how the firmware companion app is installed on managed devices.
    +# Valid values (from Android Management API):
    +#   - FORCE_INSTALLED (default, prod): Always installed; cannot be uninstalled by user
    +#   - AVAILABLE (local dev): User can install/uninstall via Play Store
    +#   - OPTIONAL: Device can install if desired
    +#   - REQUIRED_FOR_SETUP: Required before device setup completes
    +FIRMWARE_APP_INSTALL_TYPE = os.getenv("FIRMWARE_APP_INSTALL_TYPE", "FORCE_INSTALLED")
    +
    +# Controls whether companion app devices must use hardware-backed key attestation for
    +# registration. Set to False to allow emulators or dev devices that lack a TEE/StrongBox
    +# to skip the Google attestation chain check. Defaults to True (production behaviour).
    +REQUIRE_HARDWARE_ATTESTATION = os.getenv("REQUIRE_HARDWARE_ATTESTATION", "true").lower() != "false"
    +
    +# Play Store track IDs accessible on devices for the firmware companion app.
    +PUBLISH_MDM_AGENT_TRACK_IDS: list[str] = [
    +    # Closed testing track:
    +    # https://play.google.com/console/u/0/developers/7481408635650691303/app/4972886268045285910/tracks/4699961510397865384?tab=testers
    +    "4699961510397865384",

    PUBLISH_MDM_AGENT_TRACK_IDS is hard-coded to a specific closed testing track ID. This will cause accessibleTrackIds to be included in all pushed policies by default, which can unintentionally restrict Play delivery in production. Consider defaulting this to an empty list and sourcing track IDs from an environment variable/config.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on May 13, 2026 11:00 UTC
    Reviewer

    Pull request overview

    Copilot reviewed 37 out of 48 changed files in this pull request and generated 6 comments.

    <details>
    <summary>Comments suppressed due to low confidence (2)</summary>

    docker-compose.yaml:54
    Same issue as the main DB service: infisical-db mounts the volume at /var/lib/postgresql instead of the default /var/lib/postgresql/data. This may break persistence or initialization unless PGDATA is adjusted accordingly.

        restart: always
        env_file: .infisical.env
        volumes:
          - infisical_pgdata:/var/lib/postgresql
        ports:
    

    apps/mdm/models.py:844
    Same as DeviceAuthChallenge.__str__: ScreenShareSession.__str__ checks self.device_id (FK integer) even though it will always be set, then reads self.device.device_id. Consider simplifying to avoid the misleading condition.
        def __str__(self):
            device_id = self.device.device_id if self.device_id is not None else None
            return f"ScreenShareSession({self.session_id}, device={device_id})"
    

    </details>

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on May 13, 2026 11:08 UTC
    Reviewer

    Pull request overview

    Copilot reviewed 37 out of 48 changed files in this pull request and generated 4 comments.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on May 14, 2026 12:21 UTC
    Reviewer

    Pull request overview

    Copilot reviewed 40 out of 51 changed files in this pull request and generated 7 comments.

    Reviewers
    Assignees
    tobiasmcnulty tobiasmcnulty
    Labels
    risk: low confidence: 82.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 92.5% (HIGH) · Higher = larger blast radius
    92.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 82.5% · Lower = rushed or shallow review
    82.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 16.2% · Safe to merge
    16.2%