Fix the secret scan for an AI-written report script
Your task
An AI wrote a Python script that reads your Postgres database and emails a daily report. It worked, and the database password and SMTP password were written straight into the code. Before anyone commits AI-written code, your team now scans the diff for credentials assigned as string literals.
An assistant wrote find_hardcoded_secrets(diff_lines). It is in the editor. It has a bug. Find it and fix it.
Input and output:
diff_lines: the lines of a unified diff, such as+db_password = "Pr0d-9f2c!".- Return the names that are assigned a hardcoded credential, in the order found, repeats included.
Rules the tests check:
- Only added lines count: lines that start with
+but not with+++, which is a file header. Drop the+and trim whitespace from both ends. Skip the line if it then starts with#, a comment. - Look at each
=in the line, left to right. Skip an=that is part of==,!=,<=or>=: the next character is=, or the previous one is=,!,<or>. - The key is the name just before the
=: skip any space characters, then take the run of ASCII letters, digits and_that ends there. - The value starts after the
=and any space characters. It is a literal only when it starts with"or'. The literal runs to the next quote of the same kind, or to the end of the line when there is none. - Report the key when it is not empty, the literal is not empty, and the key, lowercased, contains any of
password,passwd,secret,token,api_key,apikeyorcredential. - After a literal, carry on scanning just past its closing quote, so an
=inside it is ignored. When the key is empty, or the value is not a literal, carry on scanning from the value's first character.
Examples
find_hardcoded_secrets(diff_lines: list[str]) -> list[str]Example 1
Input
find_hardcoded_secrets(["+db_password = \"Pr0d-Rds-9f2c!\"", "-db_password = \"old\"", " conn = connect()"])Output
["db_password"]Example 2
Input
find_hardcoded_secrets(["+db_password = os.environ[\"DB_PASSWORD\"]", "+api_key=\"\"", "+timeout = 30"])Output
[]Example 3
Input
find_hardcoded_secrets(["+conn = psycopg2.connect(", "+ user=\"report_bot\", password=\"Pr0d-Rds-9f2c!\")"])Output
["password"]