Fix the certificate check that replaced trust-all code

Review the AI's codeEasy15 min

Your task

Your service calls a partner's HTTPS webhook. The first version installed a trust manager that accepted every certificate, which made the TLS errors go away and switched off HTTPS's protection with them. Now the client checks the partner's certificate itself.

An assistant wrote certificate_is_trusted(cert_subject, cert_issuer, requested_host, trusted_issuers). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • cert_subject: the host name the certificate is for, such as api.example.com, or a wildcard such as *.example.com.
  • cert_issuer: the name of the certificate authority (CA) that signed it.
  • requested_host: the host your client connected to.
  • trusted_issuers: the CA names in your trust store. It can be empty.
  • Return true when the certificate is trusted for that host, false otherwise.

Rules the tests check:

  • Trim whitespace at both ends of the subject, the issuer, the host and each trust store entry.
  • If the subject, the issuer or the host is empty after trimming, return false.
  • The issuer must equal a trust store entry exactly, case included. An empty trust store trusts nothing.
  • Compare the subject and the host in lowercase, since host names ignore case.
  • A subject that does not start with *. must equal the host.
  • A subject *.<rest> is a wildcard. It matches when all of these hold:
    • <rest> contains at least one ., so *.com matches nothing.
    • The host ends with . followed by <rest>.
    • The part of the host before that is exactly one label: not empty and with no . in it. So *.example.com covers api.example.com but not example.com or a.b.example.com.

Examples:

  • certificate_is_trusted("api.example.com", "Real CA", "api.example.com", ["Real CA"]) returns true.
  • certificate_is_trusted("api.example.com", "Rogue CA", "api.example.com", ["Real CA"]) returns false: the issuer is not in the trust store.
  • certificate_is_trusted("*.example.com", "Real CA", "api.example.com", ["Other CA", "Real CA"]) returns true.

Then, in a sentence or two: how would you catch this kind of bug in review?

Examples

certificate_is_trusted(cert_subject: str, cert_issuer: str, requested_host: str, trusted_issuers: list[str]) -> bool
Example 1
Inputcertificate_is_trusted("api.example.com", "Real CA", "api.example.com", ["Real CA"])
OutputTrue
Example 2
Inputcertificate_is_trusted("api.example.com", "Rogue CA", "api.example.com", ["Real CA"])
OutputFalse
Example 3
Inputcertificate_is_trusted("*.example.com", "Real CA", "api.example.com", ["Other CA", "Real CA"])
OutputTrue