Fix the field validator for a profile update
Your task
An AI wrote POST /profile, which copied displayName, age and role from the request body straight into the database. Anyone could send role: admin and make themselves an administrator, and nothing checked the other fields either. Your team now judges every field of the body before anything is written.
An assistant wrote validate_profile_update(fields). It is in the editor. It has a bug. Find it and fix it.
Input and output:
fields: the body's fields, in order, each writtenkey=value.- Return one decision string per field, in order.
Rules the tests check. For each field, use the first rule that applies. In messages, <key> is the trimmed key as sent.
- Split the field at its first
=and trim the key. With no=, or an empty key:"reject <field> malformed", with the field exactly as given. - A key already used, exactly, by an earlier field that was not malformed:
"reject <key> duplicate". A key sent twice is ambiguous, so the later one is refused, whatever its value. - A key that, lowercased, is
role,isadmin,idorpermissions:"reject <key> forbidden". - A key other than exactly
displayNameorage:"reject <key> unknown". displayName: trim the value. If it is empty:"reject displayName empty". If it is longer than 50 characters:"reject displayName too_long". Otherwise:"accept displayName=<trimmed value>".age: the value, not trimmed, must be an optional-followed by one or more digits from 0 to 9, or the result is"reject age not_an_integer". With more than 9 digits:"reject age out_of_range". Otherwise read the number. Outside 13 to 120:"reject age out_of_range". Otherwise"accept age=<number>", written without leading zeros.
Examples
validate_profile_update(fields: list[str]) -> list[str]Example 1
Input
validate_profile_update(["displayName=Ada Lovelace", "age=31", "role=admin"])Output
["accept displayName=Ada Lovelace", "accept age=31", "reject role forbidden"]Example 2
Input
validate_profile_update(["age=old", "nickname=Ada"])Output
["reject age not_an_integer", "reject nickname unknown"]Example 3
Input
validate_profile_update([" displayName = Ada ", "age=031"])Output
["accept displayName=Ada", "accept age=31"]