Fix the runtime user check for container images

Review the AI's codeEasy10 min

Your task

An assistant's Dockerfile for a FastAPI service had no USER line, so the app ran as root inside the container. Any exploit in the app would then have root. The team now checks every Dockerfile for the user its final command runs as.

An assistant wrote effective_runtime_user(instructions). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • instructions: the Dockerfile's lines in order, one string each, as <op>|<argument>. The list can be empty.
  • Return the user name the final command runs as, a string.

Rules the tests check:

  • Split each line at its first |. A line with no | is all op, with an empty argument. Ops are case sensitive.
  • Start as "root". A Dockerfile with no USER line runs as root.
  • from|<image> starts a new stage. Any user set before it is forgotten, and the user becomes the base image's default user.
  • The base image's default user is "nonroot" when the image's tag, the text after its last :, is exactly nonroot, as in gcr.io/distroless/static:nonroot. Otherwise it is "root". An image with no : has no tag.
  • user|<name> sets the user. In the uid:gid form, such as 1000:1000, keep only the part before the first :. If that part is empty, ignore the line.
  • Any other op, such as run, copy or cmd, does not change the user.
  • Return the user after the last line.

Examples

effective_runtime_user(instructions: list[str]) -> str
Example 1
Inputeffective_runtime_user(["from|python:3.12", "copy|requirements.txt", "run|pip install -r requirements.txt", "copy|.", "cmd|uvicorn"])
Output"root"
Example 2
Inputeffective_runtime_user(["from|python:3.12-slim", "run|useradd -m app", "user|app", "cmd|uvicorn"])
Output"app"
Example 3
Inputeffective_runtime_user(["from|python:3.12", "user|builder", "from|python:3.12-slim", "copy|--from=0 /app /app", "cmd|uvicorn"])
Output"root"