|
| 1 | +"""Helpers for configuration-file parsing. |
| 2 | +
|
| 3 | +Extracts environment variables from ``docker-compose.yml`` and |
| 4 | +``.env.sample`` files, including commented-out lines. Also locates |
| 5 | +``config.yml.sample`` and scans for ``ChangeMe`` placeholder values. |
| 6 | +""" |
| 7 | + |
| 8 | +import re |
| 9 | +from dataclasses import dataclass |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +from connector_linter.models import ConnectorContext |
| 13 | + |
| 14 | + |
| 15 | +@dataclass |
| 16 | +class EnvVar: |
| 17 | + """A parsed environment variable.""" |
| 18 | + |
| 19 | + name: str |
| 20 | + value: str |
| 21 | + line: int |
| 22 | + file_path: Path |
| 23 | + is_commented: bool |
| 24 | + |
| 25 | + |
| 26 | +# --------------------------------------------------------------------------- |
| 27 | +# Regex: docker-compose.yml environment lines |
| 28 | +# |
| 29 | +# Matches lines like: |
| 30 | +# - OPENCTI_URL=http://localhost (uncommented) |
| 31 | +# # - OPENCTI_URL=http://localhost (commented out) |
| 32 | +# |
| 33 | +# Capture groups: |
| 34 | +# commented — leading "#" (present when the line is commented out) |
| 35 | +# name — uppercase env var name (e.g. OPENCTI_TOKEN) |
| 36 | +# value — everything after "=" up to an optional inline comment |
| 37 | +# |
| 38 | +# Trailing inline comments (# …) are stripped from the value. |
| 39 | +# --------------------------------------------------------------------------- |
| 40 | +_COMPOSE_ENV_RE = re.compile( |
| 41 | + r"^(?P<commented>\s*#)?\s*-\s*(?P<name>[A-Z][A-Z0-9_]*)=(?P<value>[^#\n]*?)(?:\s*#.*)?\s*$", |
| 42 | +) |
| 43 | + |
| 44 | +# --------------------------------------------------------------------------- |
| 45 | +# Regex: .env.sample (dotenv-style) lines |
| 46 | +# |
| 47 | +# Matches lines like: |
| 48 | +# OPENCTI_TOKEN=ChangeMe (uncommented) |
| 49 | +# # OPENCTI_TOKEN=ChangeMe (commented out) |
| 50 | +# |
| 51 | +# Same capture groups as _COMPOSE_ENV_RE (commented, name, value). |
| 52 | +# The difference is the absence of the YAML list marker "- ". |
| 53 | +# --------------------------------------------------------------------------- |
| 54 | +_DOTENV_RE = re.compile( |
| 55 | + r"^(?P<commented>\s*#)?\s*(?P<name>[A-Z][A-Z0-9_]*)=(?P<value>[^#\n]*?)(?:\s*#.*)?\s*$", |
| 56 | +) |
| 57 | + |
| 58 | + |
| 59 | +def _parse_lines( |
| 60 | + file_path: Path, |
| 61 | + lines: list[str], |
| 62 | + pattern: re.Pattern[str], |
| 63 | +) -> list[EnvVar]: |
| 64 | + """Extract EnvVar entries from raw lines. |
| 65 | +
|
| 66 | + Iterates line-by-line, applying the given regex ``pattern`` to each line. |
| 67 | + Both commented and uncommented matches are captured — the ``is_commented`` |
| 68 | + flag lets callers decide which to keep or skip. |
| 69 | + """ |
| 70 | + results: list[EnvVar] = [] |
| 71 | + for line_no, line in enumerate(lines, 1): |
| 72 | + m = pattern.match(line) |
| 73 | + if m: |
| 74 | + results.append( |
| 75 | + EnvVar( |
| 76 | + name=m.group("name"), |
| 77 | + value=m.group("value").strip(), |
| 78 | + line=line_no, |
| 79 | + file_path=file_path, |
| 80 | + is_commented=bool(m.group("commented")), |
| 81 | + ), |
| 82 | + ) |
| 83 | + return results |
| 84 | + |
| 85 | + |
| 86 | +def extract_env_vars_from_docker_compose(ctx: ConnectorContext) -> list[EnvVar]: |
| 87 | + """Extract environment variables from docker-compose.yml.""" |
| 88 | + compose_path = ctx.path / "docker-compose.yml" |
| 89 | + if not compose_path.is_file(): |
| 90 | + return [] |
| 91 | + with compose_path.open(encoding="utf-8") as f: |
| 92 | + return _parse_lines(compose_path, f.readlines(), _COMPOSE_ENV_RE) |
| 93 | + |
| 94 | + |
| 95 | +def extract_env_vars_from_env_sample(ctx: ConnectorContext) -> list[EnvVar]: |
| 96 | + """Extract environment variables from .env.sample.""" |
| 97 | + env_path = ctx.path / ".env.sample" |
| 98 | + if not env_path.is_file(): |
| 99 | + return [] |
| 100 | + with env_path.open(encoding="utf-8") as f: |
| 101 | + return _parse_lines(env_path, f.readlines(), _DOTENV_RE) |
| 102 | + |
| 103 | + |
| 104 | +def extract_all_env_vars(ctx: ConnectorContext) -> list[EnvVar]: |
| 105 | + """Extract env vars from docker-compose.yml and .env.sample.""" |
| 106 | + return extract_env_vars_from_docker_compose(ctx) + extract_env_vars_from_env_sample( |
| 107 | + ctx, |
| 108 | + ) |
| 109 | + |
| 110 | + |
| 111 | +def derive_connector_prefixes(ctx: ConnectorContext) -> list[str]: |
| 112 | + """Derive valid connector-specific prefixes from the directory name. |
| 113 | +
|
| 114 | + Examples: |
| 115 | + ``mandiant`` → ``["MANDIANT"]`` |
| 116 | + ``abuse-ssl`` → ``["ABUSE_SSL", "ABUSESSL"]`` |
| 117 | + ``recorded-future`` → ``["RECORDED_FUTURE", "RECORDEDFUTURE"]`` |
| 118 | +
|
| 119 | + """ |
| 120 | + dirname = ctx.path.name |
| 121 | + prefixes: set[str] = set() |
| 122 | + # Hyphen → underscore: "abuse-ssl" → "ABUSE_SSL" |
| 123 | + prefixes.add(dirname.upper().replace("-", "_")) |
| 124 | + # Hyphen removed: "abuse-ssl" → "ABUSESSL" |
| 125 | + # (Some legacy connectors use this convention.) |
| 126 | + prefixes.add(dirname.upper().replace("-", "")) |
| 127 | + return sorted(prefixes) |
| 128 | + |
| 129 | + |
| 130 | +def find_config_yml_sample(ctx: ConnectorContext) -> Path | None: |
| 131 | + """Locate config.yml.sample (root or src/).""" |
| 132 | + candidates = [ |
| 133 | + ctx.path / "config.yml.sample", |
| 134 | + ctx.path / "src" / "config.yml.sample", |
| 135 | + ] |
| 136 | + for path in candidates: |
| 137 | + if path.is_file(): |
| 138 | + return path |
| 139 | + return None |
| 140 | + |
| 141 | + |
| 142 | +def has_docker_compose_env(ctx: ConnectorContext) -> bool: |
| 143 | + """Return True if docker-compose.yml exists with environment variables.""" |
| 144 | + return bool(extract_env_vars_from_docker_compose(ctx)) |
| 145 | + |
| 146 | + |
| 147 | +def has_env_sample(ctx: ConnectorContext) -> bool: |
| 148 | + """Return True if .env.sample exists.""" |
| 149 | + return (ctx.path / ".env.sample").is_file() |
| 150 | + |
| 151 | + |
| 152 | +@dataclass |
| 153 | +class ChangeMeHit: |
| 154 | + """A ChangeMe value found in a config file with wrong case.""" |
| 155 | + |
| 156 | + file_path: Path |
| 157 | + line: int |
| 158 | + raw_value: str |
| 159 | + |
| 160 | + |
| 161 | +# --------------------------------------------------------------------------- |
| 162 | +# Regex: case-insensitive "ChangeMe" placeholder detector |
| 163 | +# |
| 164 | +# Matches the word "ChangeMe" regardless of case (CHANGEME, changeme, etc.) |
| 165 | +# appearing as a YAML value (after ":") or env value (after "="): |
| 166 | +# OPENCTI_TOKEN=changeme → matches "changeme" |
| 167 | +# token: 'CHANGEME' → matches "CHANGEME" |
| 168 | +# |
| 169 | +# Optional surrounding quotes (' or ") and trailing inline comments are |
| 170 | +# tolerated but not captured. |
| 171 | +# --------------------------------------------------------------------------- |
| 172 | +_CHANGEME_LINE_RE = re.compile( |
| 173 | + r"(?:^|[=:]\s*['\"]?)(?P<value>change\s*me)['\"]?\s*(?:#.*)?$", |
| 174 | + re.MULTILINE | re.IGNORECASE, |
| 175 | +) |
| 176 | + |
| 177 | + |
| 178 | +def find_bad_changeme_values(file_path: Path) -> list[ChangeMeHit]: |
| 179 | + """Find ChangeMe values with wrong case in any config file. |
| 180 | +
|
| 181 | + A "bad" value is any case variant of ChangeMe that is *not* the |
| 182 | + canonical form ``ChangeMe`` (e.g. ``CHANGEME``, ``changeme``). |
| 183 | +
|
| 184 | + Commented lines (starting with ``#``) are skipped because they are |
| 185 | + inactive — fixing their case would be noise, and some commented lines |
| 186 | + may intentionally use a different casing as documentation. |
| 187 | + """ |
| 188 | + if not file_path.is_file(): |
| 189 | + return [] |
| 190 | + with file_path.open(encoding="utf-8") as f: |
| 191 | + lines = f.readlines() |
| 192 | + |
| 193 | + hits: list[ChangeMeHit] = [] |
| 194 | + for line_no, line in enumerate(lines, 1): |
| 195 | + # Skip fully commented lines — only active values matter for casing |
| 196 | + stripped = line.lstrip() |
| 197 | + if stripped.startswith("#"): |
| 198 | + continue |
| 199 | + m = _CHANGEME_LINE_RE.search(line) |
| 200 | + if m: |
| 201 | + raw = m.group("value").strip() |
| 202 | + # Only flag if casing does not match the canonical "ChangeMe" |
| 203 | + if raw != "ChangeMe": |
| 204 | + hits.append(ChangeMeHit(file_path, line_no, raw)) |
| 205 | + return hits |
0 commit comments