git-asgi 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
git_asgi/middleware.py ADDED
@@ -0,0 +1,1797 @@
1
+ import sys
2
+ from asyncio import (
3
+ Event,
4
+ StreamWriter,
5
+ create_subprocess_exec,
6
+ sleep,
7
+ wait_for,
8
+ )
9
+ from asyncio.subprocess import PIPE, Process
10
+ from contextlib import asynccontextmanager, contextmanager
11
+ from contextvars import ContextVar
12
+ from dataclasses import dataclass
13
+ from http import HTTPMethod, HTTPStatus
14
+ from logging import (
15
+ INFO,
16
+ NOTSET,
17
+ Formatter,
18
+ Logger,
19
+ LogRecord,
20
+ StreamHandler,
21
+ getLevelName,
22
+ getLevelNamesMapping,
23
+ getLogger,
24
+ )
25
+ from pathlib import Path
26
+ from re import Pattern
27
+ from typing import (
28
+ TYPE_CHECKING,
29
+ AsyncGenerator,
30
+ Generator,
31
+ Iterable,
32
+ Literal,
33
+ NotRequired,
34
+ TypedDict,
35
+ )
36
+
37
+ from asgiref.compatibility import guarantee_single_callable
38
+ from asgiref.typing import (
39
+ ASGI3Application,
40
+ ASGIApplication,
41
+ ASGIReceiveCallable,
42
+ ASGISendCallable,
43
+ HTTPScope,
44
+ LifespanScope,
45
+ Scope,
46
+ )
47
+ from typing_extensions import TypeIs
48
+
49
+ from git_asgi.pktline import Pkt, Service, Version
50
+ from git_asgi.utils import check_base, check_git_executable, regex
51
+
52
+
53
+ class GitScope(HTTPScope):
54
+ """
55
+ Typed ASGI `http` scope for the smart Git HTTP protocol.
56
+ """
57
+
58
+
59
+ SCOPE: ContextVar[GitScope] = ContextVar("scope")
60
+ """
61
+ The context variable holding the request scope.
62
+ """
63
+
64
+
65
+ def log_scope(record: LogRecord) -> bool:
66
+ """
67
+ A log filter injecting the Git HTTP scope from the current context.
68
+
69
+ Arguments:
70
+ record: the log record to be emitted.
71
+
72
+ Returns:
73
+ `True` as every log record passes.
74
+ """
75
+ scope = SCOPE.get(None)
76
+
77
+ if scope is not None:
78
+ for key, value in scope.items():
79
+ setattr(record, key, value)
80
+
81
+ return True
82
+
83
+
84
+ @contextmanager
85
+ def extra(scope: GitScope) -> Generator[None, None, None]:
86
+ """
87
+ Set the Git HTTP scope in the `SCOPE` context variable.
88
+
89
+ Arguments:
90
+ scope: the Git HTTP scope.
91
+
92
+ Yields:
93
+ `None`.
94
+ """
95
+ token = SCOPE.set(scope)
96
+
97
+ try:
98
+ yield
99
+ finally:
100
+ SCOPE.reset(token)
101
+
102
+
103
+ LOGGER: Literal["git"] = "git"
104
+ """
105
+ The default logger name.
106
+ """
107
+
108
+ LEVEL: int = INFO
109
+ """
110
+ The default logging level.
111
+ """
112
+
113
+ FORMAT: Literal["{levelname}: {message}"] = "{levelname}: {message}"
114
+ """
115
+ The default logging format.
116
+ """
117
+
118
+
119
+ def is_git_scope(scope: Scope) -> TypeIs[GitScope]:
120
+ """
121
+ Type narrowing function for distinguishing an ASGI `http` scope for Git
122
+ from others.
123
+
124
+ Arguments:
125
+ scope: the ASGI scope to check.
126
+
127
+ Returns:
128
+ `True` when the scope is an ASGI `http` scope for Git, else `False`.
129
+ """
130
+ return scope["type"] == "http" and scope["method"] in (
131
+ HTTPMethod.GET,
132
+ HTTPMethod.POST,
133
+ )
134
+
135
+
136
+ def is_lifespan_scope(scope: Scope) -> TypeIs[LifespanScope]:
137
+ """
138
+ Type narrowing function for distinguishing ASGI `lifespan` scopes
139
+ from others.
140
+
141
+ Arguments:
142
+ scope: the ASGI scope to check.
143
+
144
+ Returns:
145
+ `True` when the scope is an HTTP ASGI scope for Git, else `False`.
146
+ """
147
+ return scope["type"] == "lifespan"
148
+
149
+
150
+ EOF: Literal[b""] = b""
151
+ """
152
+ End-of-file marker.
153
+ """
154
+
155
+
156
+ async def response(
157
+ send: ASGISendCallable,
158
+ status: HTTPStatus = HTTPStatus.OK,
159
+ headers: Iterable[tuple[bytes, bytes]] = (),
160
+ trailers: bool = False,
161
+ ) -> AsyncGenerator[None, bytes]:
162
+ """
163
+ Send an HTTP response down the ASGI send callable.
164
+
165
+ Returns a generator to which the response bodies can be sent in an
166
+ `async for` loop:
167
+
168
+ ```python
169
+ out = response(send, status=..., headers=...)
170
+
171
+ # `out` only yields `None`
172
+ async for _ in out:
173
+ await out.asend(...)
174
+ ```
175
+
176
+ The `async for` approach is preferrable over the
177
+ manual `asend/anext` style:
178
+
179
+ 1. automatic priming with `await out.asend(None)`,
180
+ 2. automatic handling of `StopAsyncIteration` exceptions,
181
+ 3. included `break` condition on received EOF, i.e. `b""`.
182
+
183
+ If `trailers` is set to `True`, `http.response.trailers` must be
184
+ handled manually after the generator returned.
185
+
186
+ Arguments:
187
+ send: the ASGI send callable to put the response messages in.
188
+ status: the HTTP response status.
189
+ headers: the HTTP response headers.
190
+
191
+ Yields:
192
+ `None`.
193
+
194
+ Receives:
195
+ the response body chunk as `bytes` or EOF, i.e. `b""`.
196
+ """
197
+ # start
198
+ await send(
199
+ {
200
+ "type": "http.response.start",
201
+ "status": status,
202
+ "headers": headers,
203
+ "trailers": trailers,
204
+ }
205
+ )
206
+
207
+ # body chunks
208
+ while True:
209
+ chunk = yield
210
+ yield
211
+
212
+ await send(
213
+ {
214
+ "type": "http.response.body",
215
+ "body": chunk,
216
+ "more_body": bool(chunk),
217
+ }
218
+ )
219
+
220
+ if chunk == EOF:
221
+ break
222
+
223
+
224
+ def reader(message: bytes) -> Generator[bytes, None, None]:
225
+ """
226
+ A generator yielding an EOF, i.e. `b""`, after a given message.
227
+
228
+ Arguments:
229
+ message: the message to yield.
230
+
231
+ Yields:
232
+ the message first and an EOF, i.e. `b""`, afterwards if the message
233
+ itself was not empty and thereby an EOF.
234
+ """
235
+ yield message
236
+
237
+ if message != EOF:
238
+ yield EOF
239
+
240
+
241
+ async def simple(
242
+ send: ASGISendCallable,
243
+ message: str | bytes,
244
+ status: HTTPStatus = HTTPStatus.OK,
245
+ headers: Iterable[tuple[bytes, bytes]] = (),
246
+ ) -> None:
247
+ """
248
+ Send a single HTTP response body message down the ASGI send callable.
249
+
250
+ Arguments:
251
+ send: the ASGI send callable.
252
+ message: the reponse body message.
253
+ status: the HTTP response status.
254
+ """
255
+ # ASGI response generator
256
+ out = response(send, status=status, headers=headers)
257
+
258
+ # encode the message if necessary
259
+ if isinstance(message, str):
260
+ message = message.encode()
261
+
262
+ # set up a simple reader
263
+ messages = reader(message)
264
+
265
+ # generate the response messages
266
+ async for _ in out:
267
+ await out.asend(next(messages))
268
+
269
+
270
+ async def forbidden(send: ASGISendCallable, message: str) -> None:
271
+ """
272
+ Send a `FORBIDDEN` HTTP response with a given message.
273
+
274
+ Arguments:
275
+ send: the ASGI send callable.
276
+ message: the reponse body message.
277
+ """
278
+ await simple(send, message, status=HTTPStatus.FORBIDDEN)
279
+
280
+
281
+ async def bad_request(send: ASGISendCallable, message: str) -> None:
282
+ """
283
+ Send a `BAD REQUEST` HTTP response with a given message.
284
+
285
+ Arguments:
286
+ send: the ASGI send callable.
287
+ message: the reponse body message.
288
+ """
289
+ await simple(send, message, status=HTTPStatus.BAD_REQUEST)
290
+
291
+
292
+ async def not_found(send: ASGISendCallable, message: str) -> None:
293
+ """
294
+ Send a `BAD REQUEST` HTTP response with a given message.
295
+
296
+ Arguments:
297
+ send: the ASGI send callable.
298
+ message: the reponse body message.
299
+ """
300
+ await simple(send, message, status=HTTPStatus.NOT_FOUND)
301
+
302
+
303
+ async def conflict(send: ASGISendCallable, message: str) -> None:
304
+ """
305
+ Send a `CONFLICT` HTTP response with a given message.
306
+
307
+ Arguments:
308
+ send: the ASGI send callable.
309
+ message: the reponse body message.
310
+ """
311
+ await simple(send, message, status=HTTPStatus.CONFLICT)
312
+
313
+
314
+ async def unsupported_media_type(send: ASGISendCallable, message: str) -> None:
315
+ """
316
+ Send a `CONFLICT` HTTP response with a given message.
317
+
318
+ Arguments:
319
+ send: the ASGI send callable.
320
+ message: the reponse body message.
321
+ """
322
+ await simple(send, message, status=HTTPStatus.UNSUPPORTED_MEDIA_TYPE)
323
+
324
+
325
+ async def request_timeout(send: ASGISendCallable, message: str) -> None:
326
+ """
327
+ Send a `REQUEST TIMEOUT` HTTP response with a given message.
328
+
329
+ Arguments:
330
+ send: the ASGI send callable.
331
+ message: the reponse body message.
332
+ """
333
+ await simple(send, message, status=HTTPStatus.REQUEST_TIMEOUT)
334
+
335
+
336
+ async def internal_server_error(send: ASGISendCallable, message: str) -> None:
337
+ """
338
+ Send a `SERVICE UNAVAILABLE` HTTP response with a given message.
339
+
340
+ Arguments:
341
+ send: the ASGI send callable.
342
+ message: the reponse body message.
343
+ """
344
+ await simple(send, message, status=HTTPStatus.INTERNAL_SERVER_ERROR)
345
+
346
+
347
+ async def service_unavailable(send: ASGISendCallable, message: str) -> None:
348
+ """
349
+ Send a `SERVICE UNAVAILABLE` HTTP response with a given message.
350
+
351
+ Arguments:
352
+ send: the ASGI send callable.
353
+ message: the reponse body message.
354
+ """
355
+ await simple(send, message, status=HTTPStatus.SERVICE_UNAVAILABLE)
356
+
357
+
358
+ def is_git_protocol_header(header: tuple[bytes, bytes]) -> bool:
359
+ """
360
+ Filter function for extracting `Git-Protocol` headers from
361
+ ASGI `http` scopes.
362
+
363
+ Arguments:
364
+ header:
365
+ a tuple of header name and value as given by the
366
+ `scope["headers"]` key.
367
+
368
+ Returns:
369
+ `True` if the header is a `Git-Protocol` header, else `False`.
370
+ """
371
+ return header[0] == b"git-protocol"
372
+
373
+
374
+ def is_content_type_header(header: tuple[bytes, bytes]) -> bool:
375
+ """
376
+ Filter function for extracting `Content-Type` headers from
377
+ ASGI `http` scopes.
378
+
379
+ Arguments:
380
+ header:
381
+ a tuple of header name and value as given by
382
+ the `scope["headers"]` key.
383
+
384
+ Returns:
385
+ `True` if the header is a `Content-Type` header, else `False`.
386
+ """
387
+ return header[0] == b"content-type"
388
+
389
+
390
+ REQUEST_TIMEOUT: int = 600
391
+ """
392
+ HTTP request timeout in seconds.
393
+ """
394
+
395
+ OVERLOAD_TIMEOUT: int = 10
396
+ """
397
+ Server overload timeout in seconds.
398
+ """
399
+
400
+ CHUNK_SIZE: int = 1024
401
+ """
402
+ Chunk size of HTTP response bodies in bytes.
403
+ """
404
+
405
+ INFO_REFS: Path = Path("info/refs")
406
+ """
407
+ Relative path to the server reference info file.
408
+ """
409
+
410
+ GIT_SUFFIX: Literal[".git"] = ".git"
411
+ """
412
+ Suffix for bare git repository directories.
413
+
414
+ - https://git-scm.com/docs/gitrepository-layout/#_description
415
+ """
416
+
417
+ # TODO: check for the expanded range of allowed characters
418
+ GIT_PROTOCOL: Pattern = regex(rb"^([\w\s]+(=[\w\s]+)?(:(?!$))?)*$")
419
+ """
420
+ Regular expression pattern for Extra Paramters in
421
+ the `GIT_PROTOCOL` environment variable and
422
+ the `Git-Protocol` HTTP request header.
423
+
424
+ Their value is supposed to be a colon-separated (`:`) list of
425
+ `<key>` or `<key>=<value>` entries.
426
+
427
+ `GIT_PROTOCOL` environment variable:
428
+
429
+ - https://git-scm.com/docs/pack-protocol#_extra_parameters
430
+ - https://git-scm.com/docs/git#Documentation/git.txt-GITPROTOCOL
431
+
432
+ `Git-Protocol` header:
433
+
434
+ - https://git-scm.com/docs/http-protocol#_smart_clients
435
+ - https://git-scm.com/docs/git-http-backend#_environment
436
+
437
+ Currently, only the `version` Extra Parameter is defined.
438
+
439
+ - https://git-scm.com/docs/pack-protocol#_extra_parameters
440
+ """
441
+
442
+ VERSION: Pattern = regex(b"version=(?P<version>1|2)")
443
+ """
444
+ Regular expression for the `version` Extra Parameter in
445
+ the `GIT_PROTOCOL` environment variable or
446
+ the `Git-Protocol` HTTP request header.
447
+
448
+ Currently, only versions 1 and 2 exist.
449
+
450
+ - https://git-scm.com/docs/pack-protocol#_extra_parameters
451
+ """
452
+
453
+ CONTENT_TYPE = regex(
454
+ (
455
+ r"application/"
456
+ f"x-({Service.UPLOAD}|{Service.RECEIVE}|{Service.ARCHIVE})-request"
457
+ ).encode()
458
+ )
459
+ """
460
+ Regular expression for the POST request `Content-Type` header.
461
+
462
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_upload_pack
463
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_receive_pack
464
+ - https://github.com/git/git/blob/0ffa3e35c7c82ab8d0de226149fb03b3f7674d05/http-backend.c#L666-L667
465
+ - https://github.com/git/git/blob/0ffa3e35c7c82ab8d0de226149fb03b3f7674d05/remote-curl.c#L1494-L1497
466
+ """
467
+
468
+ GET_PATH = regex("/(?P<repo>.*)/info/refs")
469
+ """
470
+ The path pattern of a smart Git HTTP GET request.
471
+ """
472
+
473
+ GET_QUERY = regex(
474
+ f"service=(?P<service>{Service.UPLOAD}|{Service.RECEIVE})".encode()
475
+ )
476
+ """
477
+ The query pattern of a smart Git HTTP GET request.
478
+ """
479
+
480
+ POST_PATH = regex(
481
+ r"/(?P<repo>.*)/"
482
+ f"(?P<service>{Service.UPLOAD}|{Service.RECEIVE}|{Service.ARCHIVE})"
483
+ )
484
+ """
485
+ The path pattern of a smart Git HTTP POST request.
486
+
487
+ - https://github.com/git/git/blob/0ffa3e35c7c82ab8d0de226149fb03b3f7674d05/http-backend.c#L744-L746
488
+ """
489
+
490
+ DUMB_PATH = regex(
491
+ r"/(?P<repo>.*)/(?P<file>HEAD|"
492
+ r"info/refs|"
493
+ r"objects/(info/[^/]+|"
494
+ r"[0-9a-f]{2}/([0-9a-f]{38}|[0-9a-f]{62})|"
495
+ r"pack/pack-([0-9a-f]{40}|[0-9a-f]{64})\.(pack|idx)))"
496
+ )
497
+ """
498
+ The path patterns of a dumb Git HTTP GET request.
499
+
500
+ Supports both SHA1 and SHA256 hashed objects.
501
+
502
+ - https://git-scm.com/docs/gitweb#_single_url_for_gitweb_and_for_fetching
503
+ - https://git-scm.com/docs/git-http-backend#_examples
504
+ - https://git-scm.com/docs/hash-function-transition#_choice_of_hash
505
+ - https://github.com/git/git/blob/0ffa3e35c7c82ab8d0de226149fb03b3f7674d05/http-backend.c#L732-L742
506
+ """
507
+
508
+
509
+ class Request(TypedDict):
510
+ """
511
+ Generic Git HTTP request data.
512
+ """
513
+
514
+ method: HTTPMethod
515
+ """
516
+ The request method.
517
+ """
518
+
519
+ path: str
520
+ """
521
+ The request path.
522
+ """
523
+
524
+ query: bytes
525
+ """
526
+ The request query.
527
+ """
528
+
529
+ headers: Iterable[tuple[bytes, bytes]]
530
+ """
531
+ The request headers.
532
+ """
533
+
534
+ scope: GitScope
535
+ """
536
+ The request ASGI `http` scope.
537
+ """
538
+
539
+ repo_pattern: Pattern[str]
540
+ """
541
+ The pattern for the requested repository path.
542
+ """
543
+
544
+ repo: NotRequired[Path]
545
+ """
546
+ The value of the requested repository path.
547
+ """
548
+
549
+ service_pattern: NotRequired[Pattern[str | bytes]]
550
+ """
551
+ The pattern for the requested Git service.
552
+ """
553
+
554
+ service_target: NotRequired[str | bytes]
555
+ """
556
+ The target value to match against the Git service pattern.
557
+ """
558
+
559
+ service: NotRequired[Service]
560
+ """
561
+ The value of the requested Git service.
562
+ """
563
+
564
+ git_protocol: NotRequired[bytes]
565
+ """
566
+ The sent `Git-Protocol` header for the `GIT_PROTOCOL` environment variable.
567
+ """
568
+
569
+ version: NotRequired[Version | None]
570
+ """
571
+ The smart Git HTTP protocol version specified in the `Git-Protocol` header.
572
+ """
573
+
574
+
575
+ def from_scope(
576
+ scope: GitScope,
577
+ *,
578
+ repo_pattern: Pattern[str],
579
+ **kwargs,
580
+ ) -> Request:
581
+ """
582
+ Construct the request data from a given Git HTTP scope
583
+ along the needed repository and service patterns.
584
+
585
+ Arguments:
586
+ scope: the Git HTTP scope.
587
+ repo_pattern: the pattern to get the repository path from.
588
+ kwargs: additional keyword arguments included in the `Request`.
589
+
590
+ Returns:
591
+ the initialized request data.
592
+ """
593
+ return Request(
594
+ method=HTTPMethod(scope["method"]),
595
+ path=scope["path"],
596
+ query=scope["query_string"],
597
+ headers=scope["headers"],
598
+ scope=scope,
599
+ repo_pattern=repo_pattern,
600
+ **kwargs,
601
+ )
602
+
603
+
604
+ def dumb(scope: GitScope) -> Request:
605
+ """
606
+ Construct the request data for a dumb Git HTTP `GET` request.
607
+
608
+ Arguments:
609
+ scope: the Git HTTP scope.
610
+
611
+ Returns:
612
+ the initialized `GET` request data.
613
+ """
614
+ return from_scope(
615
+ scope,
616
+ repo_pattern=DUMB_PATH,
617
+ )
618
+
619
+
620
+ def get(scope: GitScope) -> Request:
621
+ """
622
+ Construct the request data for a smart Git HTTP `GET` request.
623
+
624
+ Arguments:
625
+ scope: the Git HTTP scope.
626
+
627
+ Returns:
628
+ the initialized `GET` request data.
629
+ """
630
+ return from_scope(
631
+ scope,
632
+ repo_pattern=GET_PATH,
633
+ service_pattern=GET_QUERY,
634
+ service_target=scope["query_string"],
635
+ )
636
+
637
+
638
+ def post(scope: GitScope) -> Request:
639
+ """
640
+ Construct the request data for a smart Git HTTP `POST` request.
641
+
642
+ Arguments:
643
+ scope: the Git HTTP scope.
644
+
645
+ Returns:
646
+ the initialized `POST` request data.
647
+ """
648
+ return from_scope(
649
+ scope,
650
+ repo_pattern=POST_PATH,
651
+ service_pattern=POST_PATH,
652
+ service_target=scope["path"],
653
+ )
654
+
655
+
656
+ @dataclass(init=False)
657
+ class GitMiddleware:
658
+ """
659
+ ASGI middleware for serving Git repositories over HTTP.
660
+ """
661
+
662
+ app: ASGI3Application
663
+ """
664
+ The ASGI application to wrap.
665
+ """
666
+
667
+ base: Path
668
+ """
669
+ The path holding the served repositories.
670
+ """
671
+
672
+ logger: str
673
+ """
674
+ The status logger name.
675
+ """
676
+
677
+ level: int
678
+ """
679
+ The logging level.
680
+ """
681
+
682
+ fmt: str | None
683
+ """
684
+ The access logging format.
685
+ """
686
+
687
+ setup: bool
688
+ """
689
+ Flag for having completed the setup in the lifespan.
690
+ """
691
+
692
+ log: Logger
693
+ """
694
+ The logger instance.
695
+ """
696
+
697
+ smart: bool
698
+ """
699
+ Enable or disable the smart Git HTTP protocol.
700
+ """
701
+
702
+ dumb: bool
703
+ """
704
+ Enable or disable the dumb Git HTTP protocol.
705
+ """
706
+
707
+ allowed: dict[Service, bool]
708
+ """
709
+ Mapping of services to their respective permission flags.
710
+ """
711
+
712
+ request: int
713
+ """
714
+ The HTTP request timeout in seconds.
715
+ """
716
+
717
+ overload: int
718
+ """
719
+ The server overload timeout in seconds.
720
+ """
721
+
722
+ chunk: int
723
+ """
724
+ The chunk size of HTTP response bodies in bytes.
725
+ """
726
+
727
+ def __init__(
728
+ self,
729
+ app: ASGIApplication,
730
+ base: str | Path,
731
+ logger: str | None,
732
+ level: int | str | None = None,
733
+ fmt: str | None = None,
734
+ smart: bool = True,
735
+ dumb: bool = False,
736
+ upload: bool = True,
737
+ receive: bool = True,
738
+ archive: bool = False,
739
+ request: int | None = None,
740
+ overload: int | None = None,
741
+ chunk: int | None = None,
742
+ ) -> None:
743
+ """
744
+ Arguments:
745
+ app: the ASGI application to wrap.
746
+ base: the path holding the served repositories.
747
+ logger: the base logger name.
748
+ level: the logging level.
749
+ fmt: the format for logged request messages in `str.format` formatting.
750
+ smart: enable or disable the smart Git HTTP protocol.
751
+ dumb: enable or disable the dumb Git HTTP protocol.
752
+ upload: enable or disable the `git-upload-pack` service.
753
+ receive: enable or disable the `git-receive-pack` service.
754
+ archive: enable or disable the `git-upload-archive` service.
755
+ request: the HTTP request timeout in seconds.
756
+ overload: the server overload timeout in seconds.
757
+ chunk: the chunk size of HTTP response bodies in bytes.
758
+
759
+ Raises:
760
+ RuntimeError: on missing `git` executable or invalid base path.
761
+ ValueError: if both smart and dumb Git HTTP protocols are disabled.
762
+ """
763
+ # whether `git` is available
764
+ check_git_executable()
765
+
766
+ # guarantee the `base` attribute to be ready for operation
767
+ self.base = check_base(base)
768
+
769
+ # compatibility with ASGI 3
770
+ self.app = guarantee_single_callable(app)
771
+
772
+ # logging
773
+ if logger is not None:
774
+ # attach to parent
775
+ logger = f"{logger}.{LOGGER}"
776
+
777
+ if level is None:
778
+ # inherit from parent
779
+ level = NOTSET
780
+ else:
781
+ logger = LOGGER
782
+
783
+ if level is None:
784
+ level = LEVEL
785
+
786
+ if isinstance(level, str):
787
+ # get the integer code of the given level
788
+ level = getLevelNamesMapping()[level]
789
+
790
+ self.logger = logger
791
+ self.level = level
792
+ self.fmt = fmt
793
+
794
+ # setup
795
+ self.setup = False
796
+
797
+ # toggle smart and dumb HTTP protocol
798
+ if not smart and not dumb:
799
+ raise ValueError(
800
+ "either smart or dumb Git HTTP protocol must be enabled"
801
+ )
802
+
803
+ self.smart = smart
804
+ self.dumb = dumb
805
+
806
+ # services
807
+ self.allowed = {
808
+ Service.UPLOAD: upload,
809
+ Service.RECEIVE: receive,
810
+ Service.ARCHIVE: archive,
811
+ }
812
+
813
+ # timeouts
814
+ self.request = request if request is not None else REQUEST_TIMEOUT
815
+ self.overload = overload if overload is not None else OVERLOAD_TIMEOUT
816
+
817
+ # chunk size
818
+ self.chunk = chunk if chunk is not None else CHUNK_SIZE
819
+
820
+ # initialize overload flag
821
+ self.free = Event()
822
+ self.free.set()
823
+
824
+ def _setup(self) -> None:
825
+ """
826
+ Initialize logging.
827
+ """
828
+ # status logger
829
+ status = getLogger(self.logger)
830
+ status.setLevel(self.level)
831
+
832
+ if not status.hasHandlers():
833
+ # there are no handlers to propagate messages to
834
+ formatter = Formatter(fmt=FORMAT, style="{")
835
+
836
+ handler = StreamHandler(sys.stderr)
837
+ handler.setFormatter(formatter)
838
+
839
+ status.addHandler(handler)
840
+
841
+ status.info(f"set default logging handler for {self.logger} log")
842
+ else:
843
+ # `status` logger messages are propagated to the parent logger
844
+ status.info(f"use existing logging handler for {self.logger} log")
845
+
846
+ # request logger
847
+ request = f"{self.logger}.request"
848
+
849
+ self.log = getLogger(request)
850
+ self.log.setLevel(self.level)
851
+
852
+ self.log.addFilter(log_scope)
853
+
854
+ if self.fmt is not None:
855
+ # a custom format was passed
856
+ formatter = Formatter(fmt=self.fmt, style="{")
857
+
858
+ handler = StreamHandler(sys.stderr)
859
+ handler.setFormatter(formatter)
860
+
861
+ self.log.addHandler(handler)
862
+
863
+ # don't pass messages to the `status` logger
864
+ self.log.propagate = False
865
+
866
+ status.info(f"set custom logging handler for {request} log")
867
+ else:
868
+ # `request` logger messages are propagated to the `status` logger
869
+ status.info(f"use existing logging handler for {request} log")
870
+
871
+ # print attributes
872
+ for description, value in (
873
+ ("logger", f"{self.logger}, {request}"),
874
+ ("log level", getLevelName(self.level)),
875
+ ("base path", self.base),
876
+ ("smart Git HTTP protocol", self.smart),
877
+ ("dumb Git HTTP protocol", self.dumb),
878
+ (Service.UPLOAD, self.allowed[Service.UPLOAD]),
879
+ (Service.RECEIVE, self.allowed[Service.RECEIVE]),
880
+ (Service.ARCHIVE, self.allowed[Service.ARCHIVE]),
881
+ ("request timeout [s]", self.request),
882
+ ("overload timeout [s]", self.overload),
883
+ ("chunk size [B]", self.chunk),
884
+ ):
885
+ status.info(f"{description: <24}: {value}")
886
+
887
+ @asynccontextmanager
888
+ async def wait(self) -> AsyncGenerator[None, None]:
889
+ """
890
+ Wait on enter for the overload flag to be set and set it on exit.
891
+
892
+ Returns:
893
+ an asynchronous generator.
894
+ """
895
+ self.log.debug("wait for free resources")
896
+ # |
897
+ await self.free.wait()
898
+
899
+ try:
900
+ yield
901
+ finally:
902
+ self.log.debug("signal free resources")
903
+ # |
904
+ self.free.set()
905
+
906
+ async def run(
907
+ self,
908
+ command: tuple[str | Path | Service, ...],
909
+ git_protocol: bytes | None = None,
910
+ stdin: int | None = None,
911
+ cwd: str | Path | None = None,
912
+ ) -> Process:
913
+ """
914
+ Run a smart Git HTTP service command.
915
+
916
+ Arguments:
917
+ command: the command and its arguments to run.
918
+ git_protocol: the value of the `GIT_PROTOCOL` environment variable.
919
+ stdin: indicator whether to open a `STDIN` pipe to the command.
920
+
921
+ Raises:
922
+ TimeoutError: when the overload flag was not set in time.
923
+
924
+ Returns:
925
+ the running subprocess instance.
926
+ """
927
+ # pass the 'Git-Protocol' Extra Parameters to the service environment
928
+ if git_protocol:
929
+ self.log.debug(f"set GIT_PROTOCOL to {git_protocol}")
930
+ # |
931
+ env = {"GIT_PROTOCOL": git_protocol}
932
+ else:
933
+ env = {}
934
+
935
+ _command = " ".join(str(arg) for arg in command)
936
+
937
+ while True:
938
+ try:
939
+ # create the service command process
940
+ process = await create_subprocess_exec(
941
+ *command,
942
+ stdin=stdin,
943
+ stdout=PIPE,
944
+ stderr=PIPE,
945
+ env=env,
946
+ cwd=cwd,
947
+ )
948
+
949
+ self.log.debug(f"run {_command}")
950
+ except OSError as exc:
951
+ # assuming too many open files
952
+ self.log.warning(f"{_command}: {str(exc)}")
953
+ # |
954
+ self.free.clear()
955
+
956
+ # wait for commands to finish
957
+ self.log.warning(f"{_command}: wait for free resources")
958
+ # |
959
+ await wait_for(self.free.wait(), timeout=self.overload)
960
+ else:
961
+ return process
962
+
963
+ async def update_server_info(self, repo: Path) -> None:
964
+ """
965
+ Update the service info file `$REPOSITORY/info/refs`.
966
+
967
+ Arguments:
968
+ repo: the path to the repository.
969
+
970
+ Raises:
971
+ ValueError: when the command failed.
972
+ """
973
+ # define
974
+ command = ("git", "update-server-info")
975
+
976
+ async with self.wait():
977
+ # try to run under the current load
978
+ process = await self.run(command, cwd=repo)
979
+
980
+ # wait for finishing
981
+ _, stderr = await process.communicate()
982
+
983
+ # check the returncode
984
+ rc = process.returncode
985
+
986
+ if rc is not None and rc > 0:
987
+ _command = " ".join(command)
988
+ _stderr = stderr.decode(errors="replace")
989
+
990
+ msg = f"{_command} in {repo}: {_stderr}"
991
+
992
+ raise ValueError(msg)
993
+
994
+ async def _app(
995
+ self,
996
+ scope: Scope,
997
+ receive: ASGIReceiveCallable,
998
+ send: ASGISendCallable,
999
+ ) -> None:
1000
+ """
1001
+ Pass the scope to the wrapped ASGI app and log a corresponding message.
1002
+
1003
+ Arguments:
1004
+ scope: the ASGI application scope.
1005
+ receive: the receive callable returning events.
1006
+ send: the send callable sending given events.
1007
+ """
1008
+ self.log.debug("pass scope")
1009
+ # |
1010
+ await self.app(scope, receive, send)
1011
+
1012
+ async def __call__(
1013
+ self,
1014
+ scope: Scope,
1015
+ receive: ASGIReceiveCallable,
1016
+ send: ASGISendCallable,
1017
+ ) -> None:
1018
+ """
1019
+ ASGI application coroutine for Git over HTTP.
1020
+
1021
+ Arguments:
1022
+ scope: the ASGI application scope.
1023
+ receive: the receive callable returning events.
1024
+ send: the send callable sending given events.
1025
+ """
1026
+ if is_git_scope(scope):
1027
+ with extra(scope):
1028
+ await self._init(scope, receive, send)
1029
+ elif is_lifespan_scope(scope):
1030
+ await self._lifespan(scope, receive, send)
1031
+ else:
1032
+ await self.app(scope, receive, send)
1033
+
1034
+ async def _lifespan(
1035
+ self,
1036
+ scope: LifespanScope,
1037
+ receive: ASGIReceiveCallable,
1038
+ send: ASGISendCallable,
1039
+ ) -> None:
1040
+ """
1041
+ Handle a lifespan scope.
1042
+
1043
+ At first, a `lifespan.startup` is sent to the application when
1044
+ the server is ready to startup and receive connections, but
1045
+ before it has started to do so.
1046
+
1047
+ - https://asgi.readthedocs.io/en/latest/specs/lifespan.html#startup-receive-event
1048
+
1049
+ Thereby, the setup within a running server is executed upon first
1050
+ occurence of a `lifespan` scope.
1051
+
1052
+ Arguments:
1053
+ scope: the lifespan scope.
1054
+ receive: the receive callable returning events.
1055
+ send: the send callable sending given events.
1056
+ """
1057
+ if not self.setup:
1058
+ self._setup()
1059
+ self.setup = True
1060
+
1061
+ await self.app(scope, receive, send)
1062
+
1063
+ async def _init(
1064
+ self,
1065
+ scope: GitScope,
1066
+ receive: ASGIReceiveCallable,
1067
+ send: ASGISendCallable,
1068
+ ) -> None:
1069
+ """
1070
+ Initialize the Git request data if applicable.
1071
+
1072
+ Arguments:
1073
+ scope: the git scope.
1074
+ receive: the receive callable returning events.
1075
+ send: the send callable sending given events.
1076
+ """
1077
+ self.log.debug("handle scope")
1078
+ # |
1079
+ method = scope["method"]
1080
+
1081
+ if method == HTTPMethod.GET:
1082
+ if self.smart:
1083
+ request = get(scope)
1084
+ else:
1085
+ request = dumb(scope)
1086
+ elif method == HTTPMethod.POST:
1087
+ if self.smart:
1088
+ request = post(scope)
1089
+ else:
1090
+ await self._app(scope, receive, send)
1091
+ return
1092
+
1093
+ self.log.debug("handle git scope")
1094
+ # |
1095
+ await self._repo(request, receive, send)
1096
+
1097
+ async def _repo(
1098
+ self,
1099
+ request: Request,
1100
+ receive: ASGIReceiveCallable,
1101
+ send: ASGISendCallable,
1102
+ ) -> None:
1103
+ """
1104
+ Check the given repository path.
1105
+
1106
+ Arguments:
1107
+ request: the Git request data.
1108
+ receive: the receive callable returning events.
1109
+ send: the send callable sending given events.
1110
+ """
1111
+ self.log.debug("match repository path")
1112
+ # |
1113
+ match = request["repo_pattern"].fullmatch(request["path"])
1114
+
1115
+ if match is None:
1116
+ await self._app(request["scope"], receive, send)
1117
+ return
1118
+
1119
+ self.log.debug("validate repository path")
1120
+ # |
1121
+ try:
1122
+ repo = Path(match["repo"])
1123
+ except ValueError:
1124
+ await bad_request(send, "malformed path")
1125
+ return
1126
+
1127
+ if not repo.suffixes or repo.suffixes[-1] != GIT_SUFFIX:
1128
+ self.log.debug("rename repository path")
1129
+ # |
1130
+ repo = repo.with_suffix(repo.suffix + GIT_SUFFIX)
1131
+
1132
+ self.log.debug("find repository path")
1133
+ # |
1134
+ full = self.base / repo
1135
+
1136
+ if not full.exists():
1137
+ await self._app(request["scope"], receive, send)
1138
+ return
1139
+
1140
+ self.log.debug(f"set repository path to {full}")
1141
+ # |
1142
+ request["repo"] = full
1143
+
1144
+ if self.smart:
1145
+ await self._service(request, receive, send)
1146
+ else:
1147
+ await self._dumb(request, receive, send)
1148
+
1149
+ async def _service(
1150
+ self,
1151
+ request: Request,
1152
+ receive: ASGIReceiveCallable,
1153
+ send: ASGISendCallable,
1154
+ ) -> None:
1155
+ """
1156
+ Check the given Git service.
1157
+
1158
+ If the service is not recognized or disabled, the server
1159
+ MUST respond with a `403 FORBIDDEN` HTTP status.
1160
+
1161
+ - https://git-scm.com/docs/http-protocol#_smart_server_response
1162
+
1163
+ Arguments:
1164
+ request: the Git request data.
1165
+ receive: the receive callable returning events.
1166
+ send: the send callable sending given events.
1167
+ """
1168
+ self.log.debug("match service")
1169
+ # |
1170
+ match = request["service_pattern"].fullmatch(request["service_target"])
1171
+
1172
+ if match is None:
1173
+ if self.dumb:
1174
+ self.log.debug("fall back to dumb protocol")
1175
+
1176
+ # patch the request data for the new path template
1177
+ request["repo_pattern"] = DUMB_PATH
1178
+
1179
+ await self._dumb(request, receive, send)
1180
+ else:
1181
+ await forbidden(send, "malformed query")
1182
+ return
1183
+
1184
+ self.log.debug("verify service")
1185
+ # |
1186
+ service = match["service"]
1187
+
1188
+ if isinstance(service, bytes):
1189
+ service = service.decode()
1190
+
1191
+ # this always works as it was only explicitely specified in
1192
+ # the regular expression
1193
+ service = Service(service)
1194
+
1195
+ self.log.debug("verify service permission")
1196
+ # |
1197
+ if not self.allowed[service]:
1198
+ await forbidden(send, f"{service} not allowed")
1199
+ return
1200
+
1201
+ self.log.debug(f"set service to {service}")
1202
+ # |
1203
+ request["service"] = service
1204
+
1205
+ await self._content_type(request, receive, send)
1206
+
1207
+ async def _content_type(
1208
+ self,
1209
+ request: Request,
1210
+ receive: ASGIReceiveCallable,
1211
+ send: ASGISendCallable,
1212
+ ) -> None:
1213
+ """
1214
+ Check the given `Content-Type` header.
1215
+
1216
+ This is only done for HTTP `POST` and not for HTTP `GET` requests.
1217
+
1218
+ - https://git-scm.com/docs/http-protocol#_smart_clients
1219
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_upload_pack
1220
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_receive_pack
1221
+ - https://github.com/git/git/blob/47fdf220/http-backend.c#L635-L652
1222
+
1223
+ As in `git http-backend`, a wrong content type results in a
1224
+ `415 UNSUPPORTED MEDIA TYPE` HTTP response.
1225
+
1226
+ - https://github.com/git/git/blob/47fdf220/http-backend.c#L635-L652
1227
+
1228
+ Arguments:
1229
+ request: the Git request data.
1230
+ receive: the receive callable returning events.
1231
+ send: the send callable sending given events.
1232
+ """
1233
+ if request["method"] == HTTPMethod.POST:
1234
+ self.log.debug("validate content type")
1235
+ # |
1236
+ headers = filter(is_content_type_header, request["headers"])
1237
+ values = tuple(value for _, value in headers)
1238
+
1239
+ if len(values) > 1:
1240
+ await bad_request(send, "multiple 'Content-Type' headers")
1241
+ return
1242
+
1243
+ if not values:
1244
+ await bad_request(send, "missing 'Content-Type' header")
1245
+ return
1246
+
1247
+ self.log.debug("verify content type")
1248
+ # |
1249
+ # unpack the single-value tuple
1250
+ (content_type,) = values
1251
+
1252
+ match = CONTENT_TYPE.fullmatch(content_type)
1253
+
1254
+ if match is None:
1255
+ await unsupported_media_type(send, "unsupported content type")
1256
+ return
1257
+
1258
+ await self._git_protocol(request, receive, send)
1259
+
1260
+ async def _git_protocol(
1261
+ self,
1262
+ request: Request,
1263
+ receive: ASGIReceiveCallable,
1264
+ send: ASGISendCallable,
1265
+ ) -> None:
1266
+ """
1267
+ Check the given `Git-Protocol` header.
1268
+
1269
+ See the `GIT_PROTOCOL` module attribute for further details.
1270
+
1271
+ Arguments:
1272
+ request: the Git request data.
1273
+ receive: the receive callable returning events.
1274
+ send: the send callable sending given events.
1275
+ """
1276
+ self.log.debug("validate git protocol header")
1277
+ # |
1278
+ headers = filter(is_git_protocol_header, request["headers"])
1279
+ values = tuple(value for _, value in headers)
1280
+
1281
+ if len(values) > 1:
1282
+ await bad_request(send, "multiple 'Git-Protocol' headers")
1283
+ return
1284
+
1285
+ if values:
1286
+ self.log.debug("verify git protocol header")
1287
+ # |
1288
+ # unpack the single-value tuple
1289
+ (git_protocol,) = values
1290
+
1291
+ match = GIT_PROTOCOL.fullmatch(git_protocol)
1292
+
1293
+ if match is None:
1294
+ await bad_request(send, "malformed 'Git-Protocol' header")
1295
+ return
1296
+ else:
1297
+ self.log.debug("no git protocol header found")
1298
+ # |
1299
+ git_protocol = b""
1300
+
1301
+ self.log.debug(f"set git protocol to {git_protocol}")
1302
+ # |
1303
+ request["git_protocol"] = git_protocol
1304
+
1305
+ await self._version(request, receive, send)
1306
+
1307
+ async def _version(
1308
+ self,
1309
+ request: Request,
1310
+ receive: ASGIReceiveCallable,
1311
+ send: ASGISendCallable,
1312
+ ) -> None:
1313
+ """
1314
+ Check the given Git HTTP protocol version.
1315
+
1316
+ See the `VERSION` module attribute for further details.
1317
+
1318
+ Arguments:
1319
+ request: the Git request data.
1320
+ receive: the receive callable returning events.
1321
+ send: the send callable sending given events.
1322
+ """
1323
+ self.log.debug("validate git protocol version")
1324
+ # |
1325
+ match = VERSION.match(request["git_protocol"])
1326
+
1327
+ if match is None:
1328
+ self.log.debug("no version found")
1329
+ # |
1330
+ version = None
1331
+ else:
1332
+ self.log.debug("verify git protocol version")
1333
+ # |
1334
+ version = Version(int(match["version"]))
1335
+
1336
+ self.log.debug(f"set version to {version}")
1337
+ # |
1338
+ request["version"] = version
1339
+
1340
+ if request["method"] == HTTPMethod.GET:
1341
+ await self._get(request, receive, send)
1342
+ elif request["method"] == HTTPMethod.POST:
1343
+ await self._post(request, receive, send)
1344
+
1345
+ async def _get(
1346
+ self,
1347
+ request: Request,
1348
+ receive: ASGIReceiveCallable,
1349
+ send: ASGISendCallable,
1350
+ ) -> None:
1351
+ """
1352
+ Answer a smart Git HTTP GET request.
1353
+
1354
+ Smart HTTP clients MUST discover references by making a
1355
+ parameterized request for the `info/refs` file, the request MUST
1356
+ contain exactly one query parameter `service=$service` and
1357
+ the request MUST NOT contain additional query parameters.
1358
+
1359
+ - https://git-scm.com/docs/http-protocol#_smart_clients
1360
+
1361
+ The response results from the command
1362
+
1363
+ ```sh
1364
+ $service --http-backend-info-refs $repository
1365
+ ```
1366
+
1367
+ where `$service` will be `git-upload-pack` for `git pull` as well as
1368
+ `git archive --remote` or `git-receive-pack` for `git push`.
1369
+
1370
+ - https://git-scm.com/docs/gitprotocol-http#_smart_clients
1371
+ - https://git-scm.com/docs/protocol-v2#_http_transport
1372
+ - https://git-scm.com/docs/git-upload-pack#Documentation/git-upload-pack.txt---http-backend-info-refs
1373
+ - https://git-scm.com/docs/git-receive-pack#Documentation/git-receive-pack.txt---http-backend-info-refs
1374
+
1375
+ Clients MUST parse the entire response as a sequence of
1376
+ pkt-line records.
1377
+
1378
+ For the smart Git HTTP protocol v0 and v1, clients MUST verify the
1379
+ first pkt-line to be `# service=$service` and servers MUST set
1380
+ `$service` to be the request parameter value,
1381
+
1382
+ - https://git-scm.com/docs/http-protocol#_smart_server_response
1383
+
1384
+ For the smart Git HTTP protocol v2, there is no `$service` pktline.
1385
+
1386
+ - https://git-scm.com/docs/protocol-v2#_http_transport
1387
+
1388
+ The `Content-Type` header MUST be
1389
+ `application/x-$service-advertisement`, as given in the
1390
+ `Accept` header of the client request.
1391
+
1392
+ - https://git-scm.com/docs/http-protocol#_smart_server_response
1393
+
1394
+ Servers MUST include sufficient `Cache-Control` headers to prevent
1395
+ caching of the response.
1396
+
1397
+ - https://git-scm.com/docs/http-protocol#_smart_clients
1398
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_upload_pack
1399
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_receive_pack
1400
+ Servers SHOULD support chunked encoding for request bodies.
1401
+ Servers SHOULD support chunked encoding for response bodies.
1402
+
1403
+ - https://git-scm.com/docs/http-protocol#_general_request_processing
1404
+
1405
+ Arguments:
1406
+ request: the Git request data.
1407
+ receive: the ASGI receive callable.
1408
+ send: the ASGI send callable.
1409
+ """
1410
+ self.log.debug("handle smart GET request")
1411
+
1412
+ # alias
1413
+ service = request["service"]
1414
+
1415
+ # define the service command
1416
+ command = (service, "--http-backend-info-refs", request["repo"])
1417
+
1418
+ async with self.wait():
1419
+ # run the command
1420
+ try:
1421
+ process = await self.run(
1422
+ command,
1423
+ git_protocol=request["git_protocol"],
1424
+ )
1425
+ except TimeoutError:
1426
+ msg = "server overload"
1427
+
1428
+ self.log.error(msg)
1429
+
1430
+ await service_unavailable(send, msg)
1431
+ return
1432
+
1433
+ # returns pkt-lines on STDOUT
1434
+ stdout, stderr = await process.communicate()
1435
+
1436
+ # non-zero return code indicates failure
1437
+ rc = process.returncode
1438
+
1439
+ if rc is not None and rc > 0:
1440
+ _stderr = stderr.decode(errors="replace").rstrip()
1441
+
1442
+ msg = f"{service} failed: {_stderr}"
1443
+
1444
+ self.log.warning(msg)
1445
+
1446
+ # TODO: check for removal as in _post
1447
+ await conflict(send, msg)
1448
+ return
1449
+
1450
+ # add the `# service=$service` pktline
1451
+ data = b"".join(
1452
+ (
1453
+ service.pktline + Pkt.FLUSH.pktline
1454
+ if request["version"] != Version.V2 # could be None, Version.V1
1455
+ else b"",
1456
+ stdout,
1457
+ )
1458
+ )
1459
+
1460
+ # set content type matching the `Accept` header
1461
+ content_type = f"application/x-{service}-advertisement"
1462
+
1463
+ # set headers
1464
+ headers = (
1465
+ (b"content-type", content_type.encode()),
1466
+ (b"cache-control", b"no-cache"),
1467
+ )
1468
+
1469
+ # respond
1470
+ # TODO: check for chunked response
1471
+ await simple(send, data, headers=headers)
1472
+
1473
+ async def _write_to_process(
1474
+ self,
1475
+ process: Process,
1476
+ receive: ASGIReceiveCallable,
1477
+ ) -> None:
1478
+ """
1479
+ Write from the ASGI receive callable to the process stdin.
1480
+
1481
+ Arguments:
1482
+ process: the subprocess instance.
1483
+ receive: the ASGI receive callable.
1484
+ """
1485
+ # type narrowing
1486
+ # TODO: remove once https://github.com/python/typeshed/issues/13714
1487
+ # is resolved
1488
+ if TYPE_CHECKING:
1489
+ assert isinstance(process.stdin, StreamWriter)
1490
+
1491
+ self.log.debug("pipe from request to process")
1492
+
1493
+ # stream the request body in chunks to the process's `stdin`
1494
+ while True:
1495
+ event = await receive()
1496
+
1497
+ if event["type"] == "http.disconnect":
1498
+ self.log.debug("terminate process after disconnect")
1499
+ # wait for the process to terminate as
1500
+ # there is no client available to respond to
1501
+ process.terminate()
1502
+ await process.wait()
1503
+
1504
+ return
1505
+
1506
+ if event["type"] != "http.request":
1507
+ continue
1508
+
1509
+ process.stdin.write(event["body"])
1510
+
1511
+ # recommended to use after `write`;
1512
+ # see `asyncio.StreamWriter.write`
1513
+ await process.stdin.drain()
1514
+
1515
+ # yield to the event loop as `drain` might not do it;
1516
+ # see `asyncio.StreamWriter.drain`
1517
+ await sleep(0)
1518
+
1519
+ if not event["more_body"]:
1520
+ # close stdin explicitely in case of incomplete request data
1521
+ self.log.debug("close process stdin")
1522
+ # |
1523
+ process.stdin.close()
1524
+
1525
+ # should be waited for closing;
1526
+ # see `asyncio.StreamWriter.close`
1527
+ await process.stdin.wait_closed()
1528
+
1529
+ break
1530
+
1531
+ async def _post(
1532
+ self,
1533
+ request: Request,
1534
+ receive: ASGIReceiveCallable,
1535
+ send: ASGISendCallable,
1536
+ ) -> None:
1537
+ """
1538
+ Answer a smart Git HTTP POST request.
1539
+
1540
+ A smart Git HTTP client sends a POST request to `$GIT_URL/$service`.
1541
+
1542
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_upload_pack
1543
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_receive_pack
1544
+
1545
+ For the service `git-upload-pack` and `git-receive-pack`, the
1546
+ response results from the command
1547
+
1548
+ ```sh
1549
+ $service --stateless-rpc $repository
1550
+ ```
1551
+
1552
+ The option `--stateless-rpc` is needed for a single read-write cycle
1553
+ and thus enables the server to be stateless.
1554
+
1555
+ - https://git-scm.com/docs/gitprotocol-v2#_description
1556
+ - https://git-scm.com/docs/gitprotocol-http#_session_state
1557
+
1558
+ The option `--stateless-rpc` is a public option for `git-upload-pack`,
1559
+ but a hidden one for `git-receive-pack`.
1560
+
1561
+ - https://git-scm.com/docs/git-upload-pack#Documentation/git-upload-pack.txt---stateless-rpc
1562
+ - https://git-scm.com/docs/git-receive-pack#_options
1563
+ - https://github.com/git/git/blob/34f06850c16c7f7ac822b1adc71354f11b0f2ca3/builtin/receive-pack.c#L2507
1564
+
1565
+ For the service `git-upload-archive`, the response results from the
1566
+ command
1567
+
1568
+ ```sh
1569
+ git upload-archive $repository
1570
+ ```
1571
+
1572
+ only if the smart Git HTTP protocol version is set to 2.
1573
+
1574
+ - https://git-scm.com/docs/git-http-backend#Documentation/git-http-backend.txt-httpuploadarchive
1575
+
1576
+ Servers MUST wait until it has received the client’s entire request
1577
+ before issuing a response.
1578
+
1579
+ - https://git-scm.com/docs/protocol-v2#_command_request
1580
+
1581
+ The `Content-Type` header MUST be `application/x-$service-result`, as
1582
+ written in the `Accept` header of the client's HTTP request.
1583
+
1584
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_upload_pack
1585
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_receive_pack
1586
+ - https://github.com/git/git/blob/0ffa3e35c7c82ab8d0de226149fb03b3f7674d05/remote-curl.c#L1497
1587
+
1588
+ Servers MUST include sufficient `Cache-Control` headers to prevent
1589
+ caching of the response.
1590
+
1591
+ - https://git-scm.com/docs/http-protocol#_smart_clients
1592
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_upload_pack
1593
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_receive_pack
1594
+ Servers SHOULD support chunked encoding for request bodies.
1595
+
1596
+ - https://git-scm.com/docs/http-protocol#_general_request_processing
1597
+
1598
+ Servers MUST NOT include additional pkt-lines in POST responses;
1599
+
1600
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_upload_pack
1601
+ - https://git-scm.com/docs/http-protocol#_smart_service_git_receive_pack
1602
+ Arguments:
1603
+ request: the Git request data.
1604
+ receive: the ASGI receive callable.
1605
+ send: the ASGI send callable.
1606
+ """
1607
+ self.log.debug("handle smart POST request")
1608
+
1609
+ # alias
1610
+ service = request["service"]
1611
+
1612
+ # define service command
1613
+ if service in (Service.UPLOAD, Service.RECEIVE):
1614
+ command = (service, "--stateless-rpc", request["repo"])
1615
+ elif service == Service.ARCHIVE:
1616
+ self.log.debug(f"verify git protocol version for {service}")
1617
+ # |
1618
+ if request["version"] != Version.V2:
1619
+ await forbidden(
1620
+ send,
1621
+ "archive only supported with smart Git HTTP protocol v2",
1622
+ )
1623
+ return
1624
+
1625
+ # split the command on first hyphen `-`, otherwise the error
1626
+ # `upload-archive--writer: no such file or directory` arises
1627
+ command = ("git", "upload-archive", request["repo"])
1628
+
1629
+ async with self.wait():
1630
+ # run the command
1631
+ try:
1632
+ process = await self.run(
1633
+ command,
1634
+ git_protocol=request["git_protocol"],
1635
+ stdin=PIPE,
1636
+ )
1637
+ except TimeoutError:
1638
+ msg = "server overload"
1639
+
1640
+ self.log.error(msg)
1641
+
1642
+ await service_unavailable(send, msg)
1643
+ return
1644
+
1645
+ # write from the request to the process
1646
+ try:
1647
+ await wait_for(
1648
+ self._write_to_process(process, receive),
1649
+ timeout=self.request,
1650
+ )
1651
+ except TimeoutError:
1652
+ # terminate the process manually and wait for it to terminate
1653
+ process.terminate()
1654
+ await process.wait()
1655
+
1656
+ # send response
1657
+ await request_timeout(send, "")
1658
+ return
1659
+ else:
1660
+ rc = process.returncode
1661
+
1662
+ if rc is not None and rc < 0:
1663
+ # process was actively terminated with some signal;
1664
+ # see `asyncio.subprocess.Process.returncode`
1665
+ return
1666
+
1667
+ # returns pkt-lines on STDOUT
1668
+ stdout, stderr = await process.communicate()
1669
+
1670
+ # non-zero return code indicates failure
1671
+ rc = process.returncode
1672
+
1673
+ if rc is not None and rc > 0:
1674
+ # the stdout contains the error message for the client,
1675
+ # hide server internals
1676
+ stdout = stdout.replace(
1677
+ str(request["repo"]).encode(), str(self.base).encode()
1678
+ )
1679
+
1680
+ # clean error message
1681
+ _stderr = stderr.decode(errors="replace").rstrip()
1682
+
1683
+ # warning instead of error because it could be either side's fault
1684
+ self.log.warning(f"{service} failed: {_stderr}")
1685
+
1686
+ # update the `info/refs` file if dumb HTTP protocol shall be supported,
1687
+ # only `git-receive-pack` is writing and thus introducing changes
1688
+ if (
1689
+ self.dumb
1690
+ and rc is not None
1691
+ and rc == 0
1692
+ and service == Service.RECEIVE
1693
+ ):
1694
+ try:
1695
+ await self.update_server_info(request["repo"])
1696
+ except ValueError as exc:
1697
+ self.log.error(str(exc))
1698
+
1699
+ # set content type matching the `Accept` header
1700
+ content_type = f"application/x-{service}-result"
1701
+
1702
+ # set headers
1703
+ headers = (
1704
+ (b"content-type", content_type.encode()),
1705
+ (b"cache-control", b"no-cache"),
1706
+ )
1707
+
1708
+ # respond
1709
+ # TODO: check for chunked response
1710
+ await simple(send, stdout, headers=headers)
1711
+
1712
+ async def _dumb(
1713
+ self,
1714
+ request: Request,
1715
+ receive: ASGIReceiveCallable,
1716
+ send: ASGISendCallable,
1717
+ ) -> None:
1718
+ """
1719
+ Respond with a dumb request.
1720
+
1721
+ Dumb HTTP clients MUST make a GET request to $GIT_URL/info/refs,
1722
+ without any search/query parameters.
1723
+ As smart clients SHOULD fall back to the dumb protocol if another
1724
+ content type than `application/x-$service-advertisement` in a
1725
+ `GET` response is returned, the query should likewise be gracefully
1726
+ handled, i.e. ignored, when the server falls back from a smart to a
1727
+ dumb `GET` response.
1728
+
1729
+ - https://git-scm.com/docs/http-protocol#_dumb_clients
1730
+
1731
+ The content type SHOULD be UTF-8 encoded plain text and chaching
1732
+ MAY be disabled.
1733
+
1734
+ - https://git-scm.com/docs/http-protocol#_dumb_clients
1735
+
1736
+ Servers SHOULD support chunked encoding for request bodies.
1737
+
1738
+ - https://git-scm.com/docs/http-protocol#_general_request_processing
1739
+
1740
+ Arguments:
1741
+ request: the Git request data.
1742
+ receive: the ASGI receive callable.
1743
+ send: the ASGI send callable.
1744
+ """
1745
+ self.log.debug("match file path")
1746
+ # |
1747
+ match = request["repo_pattern"].fullmatch(request["path"])
1748
+
1749
+ if match is None:
1750
+ await self._app(request["scope"], receive, send)
1751
+ return
1752
+
1753
+ self.log.debug("validate file path")
1754
+ # |
1755
+ try:
1756
+ _file = Path(match["file"])
1757
+ except ValueError:
1758
+ await bad_request(send, "malformed path")
1759
+ return
1760
+
1761
+ # attach to the repo path
1762
+ file = request["repo"] / _file
1763
+
1764
+ self.log.debug("find file path")
1765
+ # |
1766
+ if not file.exists():
1767
+ if _file == INFO_REFS:
1768
+ try:
1769
+ # self-heal
1770
+ await self.update_server_info(request["repo"])
1771
+ except ValueError as exc:
1772
+ self.log.error(str(exc))
1773
+
1774
+ # the repo was not properly configured for dumb HTTP
1775
+ await internal_server_error(send, "")
1776
+ return
1777
+ else:
1778
+ await not_found(send, "no such file")
1779
+ return
1780
+
1781
+ self.log.debug(f"set file path to {file}")
1782
+
1783
+ # respond
1784
+ # TODO: handle conditional HTTP requests with 304 NOT MODIFIED
1785
+ self.log.debug("handle dumb GET request")
1786
+ # |
1787
+ headers = (
1788
+ (b"content-type", b"text/plain; charset=utf-8"),
1789
+ (b"cache-control", b"no-cache"),
1790
+ )
1791
+
1792
+ # stream file
1793
+ with file.open("rb") as fd:
1794
+ out = response(send, headers=headers)
1795
+
1796
+ async for _ in out:
1797
+ await out.asend(fd.read(self.chunk))