Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

2.5 KB
Raw Blame
rules:
    - id: user-email-lookups-use-the-shared-fold
      message: |
          Resolve a `User` by address through `EmailLookupHandler`, not `email__iexact`.

          Django compiles `email__iexact` to Postgres `UPPER`, and every account lookup
          resolves on `LOWER`. The two folds disagree: `UPPER` maps `ı` (U+0131) to `I` and
          `ſ` (U+017F) to `S`, while `LOWER` leaves both alone and maps `İ` (U+0130) to a
          plain `i`. A gate that reads one fold therefore admits an address that the login
          lookup later resolves onto somebody else's account.

          Use `EmailLookupHandler.get_user_by_email(...)` for one account, or
          `EmailLookupHandler.users_matching_email(...)` for the queryset. Both fold the
          way the lookups do, and the `posthog_user_lower_email_idx` index serves them.

          Invites are not in scope: `target_email__iexact` has its own `UPPER` index.

          Suppress a legitimate exception with
          `# nosemgrep: user-email-lookups-use-the-shared-fold -- <reason>`.
      languages: [python]
      severity: ERROR
      patterns:
          - pattern-either:
                # `email__iexact` is flagged on any receiver. A bare `email=` is flagged only on
                # `User`, because other models carry an `email` column of their own.
                - pattern: $QS.filter(..., email__iexact=$VALUE, ...)
                - pattern: $QS.exclude(..., email__iexact=$VALUE, ...)
                - pattern: $QS.get(..., email__iexact=$VALUE, ...)
                - pattern: User.objects.filter(..., email=$VALUE, ...)
                - pattern: User.objects.get(..., email=$VALUE, ...)
                - pattern: get_user_model().objects.filter(..., email=$VALUE, ...)
                - pattern: get_user_model().objects.get(..., email=$VALUE, ...)
      paths:
          # The paths that resolve a `User` by address, where a disagreeing fold sends a
          # request to the wrong account and an unindexed fold scans the whole table.
          include:
              - /ee/api/agentic_provisioning/**/*.py
              - /ee/api/authentication.py
              - /posthog/api/scim/**/*.py
              - /ee/partners/stripe/api/provisioning/**/*.py
              - /posthog/api/authentication.py
              - /posthog/api/id_jag.py
              - /posthog/api/signup.py
              - /posthog/api/sso.py
              - /posthog/api/user.py
              - /posthog/api/webauthn.py
              - /posthog/models/user.py
          exclude:
              - '**/test_*.py'
              - '**/tests/**'