|
| 1 | +import logging |
| 2 | +import re |
| 3 | + |
| 4 | +from typing_extensions import override |
| 5 | + |
| 6 | +from twyn.dependency_parser.parsers.abstract_parser import AbstractParser |
| 7 | +from twyn.dependency_parser.parsers.constants import DOCKERFILE |
| 8 | + |
| 9 | +logger = logging.getLogger("twyn") |
| 10 | + |
| 11 | + |
| 12 | +class DockerfileParser(AbstractParser): |
| 13 | + """Parser for Dockerfile dependencies (FROM instructions).""" |
| 14 | + |
| 15 | + # Pattern for variable substitution in Dockerfile |
| 16 | + VARIABLE_PATTERN = re.compile( |
| 17 | + r"\$\{(?P<name>[a-zA-Z_][a-zA-Z0-9_]*)(?::-(?P<default>[^}$]+))?\}|\$(?P<short_name>[a-zA-Z_][a-zA-Z0-9_]*)" |
| 18 | + ) |
| 19 | + |
| 20 | + def __init__(self, file_path: str = DOCKERFILE) -> None: |
| 21 | + super().__init__(file_path) |
| 22 | + |
| 23 | + @override |
| 24 | + def parse(self) -> set[str]: |
| 25 | + """Parse Dockerfile and return base image names from FROM instructions. |
| 26 | +
|
| 27 | + Handles variable substitution and excludes stage names from previous FROM instructions. |
| 28 | + """ |
| 29 | + with self.file_handler.open("r") as fp: |
| 30 | + lines = fp.readlines() |
| 31 | + |
| 32 | + # Handle line continuations (\) |
| 33 | + raw_instructions = self._handle_line_continuations(lines) |
| 34 | + |
| 35 | + # Parse instructions and resolve variables |
| 36 | + return self._extract_base_images(raw_instructions) |
| 37 | + |
| 38 | + def _handle_line_continuations(self, lines: list[str]) -> list[str]: |
| 39 | + """Handle Dockerfile line continuations with backslash.""" |
| 40 | + raw_instructions = [] |
| 41 | + buffer = "" |
| 42 | + |
| 43 | + for line in lines: |
| 44 | + line = line.strip() # noqa: PLW2901 |
| 45 | + if not line or line.startswith("#"): |
| 46 | + continue |
| 47 | + |
| 48 | + if line.endswith("\\"): |
| 49 | + buffer += line[:-1] + " " |
| 50 | + else: |
| 51 | + buffer += line |
| 52 | + raw_instructions.append(buffer) |
| 53 | + buffer = "" |
| 54 | + |
| 55 | + return raw_instructions |
| 56 | + |
| 57 | + def _extract_base_images(self, instructions: list[str]) -> set[str]: |
| 58 | + """Extract base images from Dockerfile instructions.""" |
| 59 | + env: dict[str, str] = {} |
| 60 | + images: set[str] = set() |
| 61 | + stages: set[str] = set() |
| 62 | + |
| 63 | + for instruction in instructions: |
| 64 | + parts = instruction.split(None, 1) |
| 65 | + if len(parts) < 2: |
| 66 | + continue |
| 67 | + |
| 68 | + cmd = parts[0].upper() |
| 69 | + args = parts[1] |
| 70 | + |
| 71 | + if cmd in ("ARG", "ENV"): |
| 72 | + self._parse_variable_assignment(args, env) |
| 73 | + elif cmd == "FROM": |
| 74 | + self._parse_from_instruction(args, env, images, stages) |
| 75 | + return images |
| 76 | + |
| 77 | + def _parse_variable_assignment(self, args: str, env: dict[str, str]) -> None: |
| 78 | + """Parse ARG or ENV instruction and update environment variables.""" |
| 79 | + if "=" in args: |
| 80 | + # Handle KEY=VALUE pairs |
| 81 | + for part in args.split(): |
| 82 | + if "=" in part: |
| 83 | + key, val = part.split("=", 1) |
| 84 | + env[key] = self._resolve_variables(val.strip("\"'"), env) |
| 85 | + else: |
| 86 | + # Handle KEY VALUE pairs (space-separated) |
| 87 | + parts = args.split(None, 1) |
| 88 | + if parts: |
| 89 | + key = parts[0] |
| 90 | + val = parts[1] if len(parts) > 1 else "" |
| 91 | + env[key] = self._resolve_variables(val.strip("\"'"), env) |
| 92 | + |
| 93 | + def _parse_from_instruction(self, args: str, env: dict[str, str], images: set[str], stages: set[str]) -> None: |
| 94 | + """Parse FROM instruction and extract base image.""" |
| 95 | + # Strip flags like --platform=... |
| 96 | + clean_args = re.sub(r"--\S+", "", args).strip().split() |
| 97 | + if not clean_args: |
| 98 | + return |
| 99 | + |
| 100 | + image_name = clean_args[0] |
| 101 | + resolved_image = self._resolve_variables(image_name, env) |
| 102 | + |
| 103 | + if resolved_image not in stages: |
| 104 | + image_name_only = self._extract_image_name(resolved_image) |
| 105 | + |
| 106 | + # Ignore the special 'scratch' no-op image |
| 107 | + if image_name_only.lower() != "scratch": |
| 108 | + images.add(image_name_only) |
| 109 | + |
| 110 | + for i, part in enumerate(clean_args): |
| 111 | + if part.lower() == "as" and i + 1 < len(clean_args): |
| 112 | + stages.add(clean_args[i + 1]) |
| 113 | + |
| 114 | + def _extract_image_name(self, image_with_tag: str) -> str: |
| 115 | + """Extract image name without tag/version/digest from a Docker image reference. |
| 116 | +
|
| 117 | + Examples: |
| 118 | + ubuntu:20.04 -> ubuntu |
| 119 | + node:16-alpine -> node |
| 120 | + registry.hub.docker.com/library/nginx:latest -> registry.hub.docker.com/library/nginx |
| 121 | + localhost:5000/myapp:v1.0 -> localhost:5000/myapp |
| 122 | + nginx@sha256:23q... -> nginx |
| 123 | + """ |
| 124 | + # Strip off the digest FIRST |
| 125 | + if "@" in image_with_tag: |
| 126 | + image_with_tag = image_with_tag.split("@")[0] |
| 127 | + |
| 128 | + # Find the last ':' in the string |
| 129 | + last_colon_idx = image_with_tag.rfind(":") |
| 130 | + |
| 131 | + if last_colon_idx == -1: |
| 132 | + # No colon found, return as-is |
| 133 | + return image_with_tag |
| 134 | + |
| 135 | + potential_tag = image_with_tag[last_colon_idx + 1 :] |
| 136 | + name_part = image_with_tag[:last_colon_idx] |
| 137 | + |
| 138 | + if ( |
| 139 | + potential_tag.isdigit() and "/" not in potential_tag and "/" not in name_part.split("/")[-1] |
| 140 | + if name_part |
| 141 | + else True |
| 142 | + ): |
| 143 | + # This looks like a registry with port, don't strip it |
| 144 | + return image_with_tag |
| 145 | + |
| 146 | + # Otherwise, strip the tag |
| 147 | + return name_part |
| 148 | + |
| 149 | + def _resolve_variables(self, text: str, env: dict[str, str]) -> str: |
| 150 | + """Resolve variable substitutions in text using environment variables.""" |
| 151 | + |
| 152 | + def replace(match: re.Match[str]) -> str: |
| 153 | + name = match.group("name") or match.group("short_name") |
| 154 | + default = match.group("default") |
| 155 | + return env.get(name, default if default is not None else match.group(0)) |
| 156 | + |
| 157 | + result = text |
| 158 | + iterations = 0 |
| 159 | + max_iterations = 20 # Circuit breaker for recursive variables like PATH=$PATH |
| 160 | + |
| 161 | + while iterations < max_iterations: |
| 162 | + new_result = self.VARIABLE_PATTERN.sub(replace, result) |
| 163 | + if new_result == result: |
| 164 | + break |
| 165 | + result = new_result |
| 166 | + iterations += 1 |
| 167 | + |
| 168 | + return result |
0 commit comments