Fix the certificate check that replaced trust-all code
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 asapi.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*.commatches 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.comcoversapi.example.combut notexample.comora.b.example.com.
Examples:
certificate_is_trusted("api.example.com", "Real CA", "api.example.com", ["Real CA"])returnstrue.certificate_is_trusted("api.example.com", "Rogue CA", "api.example.com", ["Real CA"])returnsfalse: the issuer is not in the trust store.certificate_is_trusted("*.example.com", "Real CA", "api.example.com", ["Other CA", "Real CA"])returnstrue.
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]) -> boolExample 1
Input
certificate_is_trusted("api.example.com", "Real CA", "api.example.com", ["Real CA"])Output
TrueExample 2
Input
certificate_is_trusted("api.example.com", "Rogue CA", "api.example.com", ["Real CA"])Output
FalseExample 3
Input
certificate_is_trusted("*.example.com", "Real CA", "api.example.com", ["Other CA", "Real CA"])Output
True