Stop CI/CD from processing tags with commits not on a branch

Problem to solve

We have a long testing pipeline that runs for every commit. We don’t want the entire pipeline to run when a tag is pushed that has commits that have already been tested as that is a waste of resources.

Is there a way to block running pipelines on a tag when the commits do not exist in the main branch?

Configuration

All of our testing jobs have this rule:

  rules:
    - if: $CI_COMMIT_TAG =~ /^v[\d+]\.[\d+]\.[\d+](\-.+)?/
      when: never
    - when: always

All of our jobs relating to releasing a package when a tag is pushed have this rule:

  rules:
    - if: $CI_COMMIT_TAG && $CI_COMMIT_REF_PROTECTED == 'true' && $CI_COMMIT_TAG =~ /^v[\d+]\.[\d+]\.[\d+](\-.+)?/