|
| 1 | +from graphql import GraphQLResolveInfo |
| 2 | +from graphql import GraphQLError |
| 3 | +from api.models import NetworkAccessPolicy, Organisation, OrganisationMember |
| 4 | + |
| 5 | +from itertools import chain |
| 6 | + |
| 7 | + |
| 8 | +class IPRestrictedError(GraphQLError): |
| 9 | + def __init__(self, organisation_name: str): |
| 10 | + super().__init__( |
| 11 | + message=f"Your IP address is not allowed to access {organisation_name}", |
| 12 | + extensions={ |
| 13 | + "code": "IP_RESTRICTED", |
| 14 | + "organisation_name": organisation_name, |
| 15 | + }, |
| 16 | + ) |
| 17 | + |
| 18 | + |
| 19 | +class IPWhitelistMiddleware: |
| 20 | + """ |
| 21 | + Graphene middleware to enforce network access policy for human users |
| 22 | + based on their organisation membership and IP address. |
| 23 | + """ |
| 24 | + |
| 25 | + def resolve(self, next, root, info: GraphQLResolveInfo, **kwargs): |
| 26 | + request = info.context |
| 27 | + user = getattr(request, "user", None) |
| 28 | + |
| 29 | + organisation_id = kwargs.get("organisation_id") |
| 30 | + if not user or not user.is_authenticated: |
| 31 | + raise GraphQLError("Authentication required") |
| 32 | + |
| 33 | + if not organisation_id: |
| 34 | + # If the operation doesn't involve an org, skip check |
| 35 | + return next(root, info, **kwargs) |
| 36 | + |
| 37 | + org = Organisation.objects.get(id=organisation_id) |
| 38 | + |
| 39 | + if org.plan == Organisation.FREE_PLAN: |
| 40 | + return next(root, info, **kwargs) |
| 41 | + |
| 42 | + else: |
| 43 | + from ee.access.utils.network import is_ip_allowed |
| 44 | + |
| 45 | + try: |
| 46 | + org_member = OrganisationMember.objects.get( |
| 47 | + organisation_id=organisation_id, |
| 48 | + user_id=user.userId, |
| 49 | + deleted_at__isnull=True, |
| 50 | + ) |
| 51 | + except OrganisationMember.DoesNotExist: |
| 52 | + raise GraphQLError("You are not a member of this organisation") |
| 53 | + |
| 54 | + ip = self.get_client_ip(request) |
| 55 | + |
| 56 | + account_policies = org_member.network_policies.all() |
| 57 | + global_policies = ( |
| 58 | + NetworkAccessPolicy.objects.filter( |
| 59 | + organisation_id=organisation_id, is_global=True |
| 60 | + ) |
| 61 | + if org.plan == Organisation.ENTERPRISE_PLAN |
| 62 | + else [] |
| 63 | + ) |
| 64 | + |
| 65 | + all_policies = list(chain(account_policies, global_policies)) |
| 66 | + |
| 67 | + if not all_policies or is_ip_allowed(ip, all_policies): |
| 68 | + return next(root, info, **kwargs) |
| 69 | + |
| 70 | + raise IPRestrictedError(org_member.organisation.name) |
| 71 | + |
| 72 | + def get_client_ip(self, request): |
| 73 | + x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") |
| 74 | + if x_forwarded_for: |
| 75 | + return x_forwarded_for.split(",")[0].strip() |
| 76 | + return request.META.get("REMOTE_ADDR") |
0 commit comments