# Semgrep security rules for Familienarchiv backend.
# These rules catch the absence of XXE protection on XML parser factories.
# CWE-611: Improper Restriction of XML External Entity Reference.
# Run: semgrep --config .semgrep/security.yml --error backend/src/

rules:

  # DocumentBuilderFactory without XXE hardening.
  # All call sites must call setFeature("…disallow-doctype-decl", true) before use.
  - id: dbf-xxe-default
    patterns:
      - pattern: $X = DocumentBuilderFactory.newInstance();
      - pattern-not-inside: |
          ...
          $X.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
          ...
    message: >
      DocumentBuilderFactory without XXE protection (CWE-611).
      Call XxeSafeXmlParser.hardenedFactory() instead of DocumentBuilderFactory.newInstance().
      See: https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
    languages: [java]
    severity: ERROR

  # SAXParserFactory without XXE hardening.
  - id: sax-xxe-default
    patterns:
      - pattern: $X = SAXParserFactory.newInstance();
      - pattern-not-inside: |
          ...
          $X.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
          ...
    message: >
      SAXParserFactory without XXE protection (CWE-611).
      Set disallow-doctype-decl=true, external-general-entities=false, external-parameter-entities=false,
      and load-external-dtd=false before use. Follow the pattern in XxeSafeXmlParser.hardenedFactory().
      See: https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
    languages: [java]
    severity: ERROR

  # XMLInputFactory without XXE hardening (StAX parser).
  - id: stax-xxe-default
    patterns:
      - pattern: $X = XMLInputFactory.newInstance();
      - pattern-not-inside: |
          ...
          $X.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
          ...
    message: >
      XMLInputFactory without XXE protection (CWE-611).
      Set IS_SUPPORTING_EXTERNAL_ENTITIES=false and SUPPORT_DTD=false before use.
      Follow the pattern in XxeSafeXmlParser.hardenedFactory().
      See: https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
    languages: [java]
    severity: ERROR
