Dockerfile review: catch a container running as root

Python data engineering interview problem. Difficulty: intermediate. Pattern: Strings. About 12 minutes. Part of the Pro drill bank.

Production ticket: A Dockerfile with no USER instruction runs as root by default. Detect it from the text, the way a review bot would. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

A platform security reviewer files a ticket: some container images may run as root in production. If a process in such a container is compromised, the attacker gets root permissions inside it. A Dockerfile runs as root unless its last stage has a USER line for a different user. Look only at the last stage, that is, the lines after the last line that starts with FROM. Return True if the last stage has no USER instruction for a non-root user, otherwise False. A line USER root still counts as root. A USER line in an earlier stage does not protect the last stage. Write runs_as_root(dockerfile: str) -> bool. A Dockerfile with FROM, RUN pip install and CMD but no USER returns True. One with RUN useradd -m app and then USER app returns False. The starter file already has the function and the print lines at the bottom. Keep them, because the grader reads what they print.

Requirements

  • Split the Dockerfile into lines.
  • Find the last line that starts with FROM.
  • Check the USER lines after it.
  • Return True unless a USER names a non-root user.

Constraints

  • dockerfile is a multi-line string.
  • USER root counts as root.
  • Only the last stage matters.

Examples

Input: runs_as_root("FROM python:3.12-slim\nRUN pip install -r requirements.txt\nCMD [\"python\", \"ingest.py\"]") Output: True No USER instruction at all after the FROM - the container runs as root.

Topics: docker, infra, security.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Dockerfile review: catch a container running as root

Production ticket: A Dockerfile with no USER instruction runs as root by default. Detect it from the text, the way a review bot would.

A container security review flags images that run as root. A Dockerfile runs as root unless it has a `USER` instruction (other than `USER root`) *after* its last `FROM`. Write `runs_as_root(dockerfile: str) -> bool` that returns `True` if the last stage has no non-root `USER` line. Split on newlines, find the last line starting with `FROM`, then check every `USER` line after it. Keep the prints at the bottom. The grader reads stdout.