Fix the field validator for a profile update

Review the AI's codeEasy12 min

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 written key=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.

  1. 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.
  2. 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.
  3. A key that, lowercased, is role, isadmin, id or permissions: "reject <key> forbidden".
  4. A key other than exactly displayName or age: "reject <key> unknown".
  5. 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>".
  6. 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
Inputvalidate_profile_update(["displayName=Ada Lovelace", "age=31", "role=admin"])
Output["accept displayName=Ada Lovelace", "accept age=31", "reject role forbidden"]
Example 2
Inputvalidate_profile_update(["age=old", "nickname=Ada"])
Output["reject age not_an_integer", "reject nickname unknown"]
Example 3
Inputvalidate_profile_update([" displayName = Ada ", "age=031"])
Output["accept displayName=Ada", "accept age=31"]