-
Notifications
You must be signed in to change notification settings - Fork 21
/
passgithelper.py
executable file
·467 lines (374 loc) · 15 KB
/
passgithelper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#!/usr/bin/env python3
"""Implementation of the pass-git-helper utility.
.. codeauthor:: Johannes Wienke
"""
import abc
import argparse
import configparser
import fnmatch
import logging
import os
import os.path
from pathlib import Path
import re
import subprocess
import sys
from typing import Dict, IO, Mapping, Optional, Pattern, Sequence, Text
import xdg.BaseDirectory
LOGGER = logging.getLogger()
CONFIG_FILE_NAME = "git-pass-mapping.ini"
DEFAULT_CONFIG_FILE = (
Path(xdg.BaseDirectory.save_config_path("pass-git-helper")) / CONFIG_FILE_NAME
)
def parse_arguments(argv: Optional[Sequence[str]] = None) -> argparse.Namespace:
"""Parse the command line arguments.
Args:
argv:
If not ``None``, use the provided command line arguments for
parsing. Otherwise, extract them automatically.
Returns:
The argparse object representing the parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Git credential helper using pass as the data source.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-m",
"--mapping",
type=argparse.FileType("r"),
metavar="MAPPING_FILE",
default=None,
help="A mapping file to be used, specifying how hosts "
"map to pass entries. Overrides the default mapping files from "
"XDG config locations, usually: {config_file}".format(
config_file=DEFAULT_CONFIG_FILE
),
)
parser.add_argument(
"-l",
"--logging",
action="store_true",
default=False,
help="Print debug messages on stderr. Might include sensitive information",
)
parser.add_argument(
"action",
type=str,
metavar="ACTION",
help="Action to perform as specified in the git credential API",
)
return parser.parse_args(argv)
def parse_mapping(mapping_file: Optional[IO]) -> configparser.ConfigParser:
"""Parse the file containing the mappings from hosts to pass entries.
Args:
mapping_file:
Name of the file to parse. If ``None``, the default file from the
XDG location is used.
"""
LOGGER.debug("Parsing mapping file. Command line: %s", mapping_file)
def parse(mapping_file: IO) -> configparser.ConfigParser:
config = configparser.ConfigParser()
config.read_file(mapping_file)
return config
# give precedence to the user-specified file
if mapping_file is not None:
LOGGER.debug("Parsing command line mapping file")
return parse(mapping_file)
# fall back on XDG config location
xdg_config_dir = xdg.BaseDirectory.load_first_config("pass-git-helper")
if xdg_config_dir is None:
raise RuntimeError(
"No mapping configured so far at any XDG config location. "
"Please create {config_file}".format(config_file=DEFAULT_CONFIG_FILE)
)
default_file = Path(xdg_config_dir) / CONFIG_FILE_NAME
LOGGER.debug("Parsing mapping file %s", mapping_file)
with default_file.open("r") as file_handle:
return parse(file_handle)
def parse_request() -> Dict[str, str]:
"""Parse the request of the git credential API from stdin.
Returns:
A dictionary with all key-value pairs of the request
"""
in_lines = sys.stdin.readlines()
LOGGER.debug('Received request "%s"', in_lines)
request = {}
for line in in_lines:
# skip empty lines to be a bit resilient against protocol errors
if not line.strip():
continue
parts = line.split("=", 1)
assert len(parts) == 2
request[parts[0].strip()] = parts[1].strip()
return request
class DataExtractor(abc.ABC):
"""Interface for classes that extract values from pass entries."""
def __init__(self, option_suffix: Text = "") -> None:
"""Create a new instance.
Args:
option_suffix:
Suffix to put behind names of configuration keys for this
instance. Subclasses must use this for their own options.
"""
self._option_suffix = option_suffix
@abc.abstractmethod
def configure(self, config: configparser.SectionProxy) -> None:
"""Configure the extractor from the mapping section.
Args:
config:
configuration section for the entry
"""
@abc.abstractmethod
def get_value(
self, entry_name: Text, entry_lines: Sequence[Text]
) -> Optional[Text]:
"""Return the extracted value.
Args:
entry_name:
Name of the pass entry the value shall be extracted from
entry_lines:
The entry contents as a sequence of text lines
Returns:
The extracted value or ``None`` if nothing applicable can be found
in the entry.
"""
class SkippingDataExtractor(DataExtractor):
"""Extracts data from a pass entry and optionally strips a prefix.
The prefix is a fixed amount of characters.
"""
def __init__(self, prefix_length: int, option_suffix: Text = "") -> None:
"""Create a new instance.
Args:
prefix_length:
Amount of characters to skip at the beginning of the entry
option_suffix:
Suffix to put behind names of configuration keys for this
instance. Subclasses must use this for their own options.
"""
super().__init__(option_suffix)
self._prefix_length = prefix_length
@abc.abstractmethod
def configure(self, config: configparser.SectionProxy) -> None:
"""Configure the amount of characters to skip."""
self._prefix_length = config.getint(
"skip{suffix}".format(suffix=self._option_suffix),
fallback=self._prefix_length,
)
@abc.abstractmethod
def _get_raw(self, entry_name: Text, entry_lines: Sequence[Text]) -> Optional[Text]:
pass
def get_value(
self, entry_name: Text, entry_lines: Sequence[Text]
) -> Optional[Text]:
"""See base class method."""
raw_value = self._get_raw(entry_name, entry_lines)
if raw_value is not None:
return raw_value[self._prefix_length :]
else:
return None
class SpecificLineExtractor(SkippingDataExtractor):
"""Extracts a specific line number from an entry."""
def __init__(self, line: int, prefix_length: int, option_suffix: Text = "") -> None:
"""Create a new instance.
Args:
line:
the line to extract, counting from zero
prefix_length:
Amount of characters to skip at the beginning of the line
option_suffix:
Suffix for each configuration option
"""
super().__init__(prefix_length, option_suffix)
self._line = line
def configure(self, config: configparser.SectionProxy) -> None:
"""See base class method."""
super().configure(config)
self._line = config.getint(
"line{suffix}".format(suffix=self._option_suffix), fallback=self._line
)
def _get_raw(
self, entry_name: Text, entry_lines: Sequence[Text] # noqa: ARG002
) -> Optional[Text]:
if len(entry_lines) > self._line:
return entry_lines[self._line]
else:
return None
class RegexSearchExtractor(DataExtractor):
"""Extracts data using a regular expression with capture group."""
def __init__(self, regex: str, option_suffix: str) -> None:
"""Create a new instance.
Args:
regex:
The regular expression describing the entry line to match. The
first matching line is selected. The expression must contain a
single capture group that contains the data to return.
option_suffix:
Suffix for each configuration option
"""
super().__init__(option_suffix)
self._regex = self._build_matcher(regex)
def _build_matcher(self, regex: str) -> Pattern:
matcher = re.compile(regex)
if matcher.groups != 1:
raise ValueError(
'Provided regex "{regex}" must contain a single '
"capture group for the value to return.".format(regex=regex)
)
return matcher
def configure(self, config: configparser.SectionProxy) -> None:
"""See base class method."""
self._regex = self._build_matcher(
config.get(
"regex{suffix}".format(suffix=self._option_suffix),
fallback=self._regex.pattern,
)
)
def get_value(
self, entry_name: Text, entry_lines: Sequence[Text] # noqa: ARG002
) -> Optional[Text]:
"""See base class method."""
# Search through all lines and return the first matching one
for line in entry_lines:
match = self._regex.match(line)
if match:
return match.group(1)
# nothing matched
return None
class EntryNameExtractor(DataExtractor):
"""Return the last path fragment of the pass entry as the desired value."""
def configure(self, config: configparser.SectionProxy) -> None:
"""Configure nothing."""
def get_value(
self, entry_name: Text, entry_lines: Sequence[Text] # noqa: ARG002
) -> Optional[Text]:
"""See base class method."""
return os.path.split(entry_name)[1]
_line_extractor_name = "specific_line"
_username_extractors = {
_line_extractor_name: SpecificLineExtractor(1, 0, option_suffix="_username"),
"regex_search": RegexSearchExtractor(
r"^username: +(.*)$", option_suffix="_username"
),
"entry_name": EntryNameExtractor(option_suffix="_username"),
}
def find_mapping_section(
mapping: configparser.ConfigParser, request_header: str
) -> configparser.SectionProxy:
"""Select the mapping entry matching the request header."""
LOGGER.debug('Searching mapping to match against header "%s"', request_header)
for section in mapping.sections():
if fnmatch.fnmatch(request_header, section):
LOGGER.debug(
'Section "%s" matches requested header "%s"', section, request_header
)
return mapping[section]
raise ValueError(
f"No mapping section in {mapping.sections()} matches request {request_header}"
)
def get_request_section_header(request: Mapping[str, str]) -> str:
"""Return the canonical host + optional path for section header matching."""
if "host" not in request:
LOGGER.error("host= entry missing in request. Cannot query without a host")
raise ValueError("Request lacks host entry")
host = request["host"]
if "path" in request:
host = "/".join([host, request["path"]])
return host
def define_pass_target(
section: configparser.SectionProxy, request: Mapping[str, str]
) -> str:
"""Determine the pass target by filling in potentially used variables."""
pass_target = section.get("target").replace("${host}", request["host"])
if "username" in request:
pass_target = pass_target.replace("${username}", request["username"])
if "protocol" in request:
pass_target = pass_target.replace("${protocol}", request["protocol"])
return pass_target
def compute_pass_environment(section: configparser.SectionProxy) -> Mapping[str, str]:
environment = os.environ.copy()
password_store_dir = section.get("password_store_dir")
if password_store_dir:
LOGGER.debug('Setting PASSWORD_STORE_DIR to "%s"', password_store_dir)
environment["PASSWORD_STORE_DIR"] = password_store_dir
return environment
def get_password(
request: Mapping[str, str], mapping: configparser.ConfigParser
) -> None:
"""Resolve the given credential request in the provided mapping definition.
The result is printed automatically.
Args:
request:
The credential request specified as a dict of key-value pairs.
mapping:
The mapping configuration as a ConfigParser instance.
"""
LOGGER.debug('Received request "%s"', request)
header = get_request_section_header(request)
section = find_mapping_section(mapping, header)
pass_target = define_pass_target(section, request)
password_extractor = SpecificLineExtractor(0, 0, option_suffix="_password")
password_extractor.configure(section)
username_extractor_name = section.get(
"username_extractor", fallback=_line_extractor_name
)
username_extractor = _username_extractors.get(username_extractor_name)
if username_extractor is None:
raise ValueError(
f"A username_extractor of type '{username_extractor_name}' does not exist"
)
username_extractor.configure(section)
environment = compute_pass_environment(section)
LOGGER.debug('Requesting entry "%s" from pass', pass_target)
# silence the subprocess injection warnings as it is the user's
# responsibility to provide a safe mapping and execution environment
output = subprocess.check_output(
["pass", "show", pass_target], env=environment
).decode(section.get("encoding", "UTF-8"))
lines = output.splitlines()
password = password_extractor.get_value(pass_target, lines)
username = username_extractor.get_value(pass_target, lines)
if password:
print("password={password}".format(password=password)) # noqa: T201
if "username" not in request and username:
print("username={username}".format(username=username)) # noqa: T201
def handle_skip() -> None:
"""Terminate the process if skipping is requested via an env variable."""
if "PASS_GIT_HELPER_SKIP" in os.environ:
LOGGER.info("Skipping processing as requested via environment variable")
sys.exit(1)
def main(argv: Optional[Sequence[str]] = None) -> None:
"""Start the pass-git-helper script.
Args:
argv:
If not ``None``, use the provided command line arguments for
parsing. Otherwise, extract them automatically.
"""
args = parse_arguments(argv=argv)
if args.logging:
logging.basicConfig(level=logging.DEBUG)
handle_skip()
action = args.action
request = parse_request()
LOGGER.debug("Received action %s with request:\n%s", action, request)
try:
mapping = parse_mapping(args.mapping)
except Exception as error: # ok'ish for the main function
LOGGER.critical("Unable to parse mapping file", exc_info=True)
print( # noqa: T201
"Unable to parse mapping file: {error}".format(error=error), file=sys.stderr
)
sys.exit(1)
if action == "get":
try:
get_password(request, mapping)
except Exception as error: # ok'ish for the main function
print( # noqa: T201
"Unable to retrieve entry: {error}".format(error=error), file=sys.stderr
)
sys.exit(1)
else:
LOGGER.info("Action %s is currently not supported", action)
sys.exit(1)
if __name__ == "__main__":
main()