aboutsummaryrefslogtreecommitdiffstats
path: root/paste/__init__.py
blob: 1536f02cdda0cd7352474e08b92dc1bce09ca75a (plain)
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
import binascii
import sys
import traceback
import urllib.parse
from base64 import b64decode, b64encode
from collections.abc import Callable
from functools import wraps
from typing import Any, Optional
from wsgiref.util import application_uri, request_uri

from . import db
from .store import Auth, Store
from .types import (
    App,
    Closable,
    Env,
    Middleware,
    ProtoMiddleware,
    Response,
    StartResponse,
)

DB_PATH = "paste.sqlite3"


def simple_response(
    start_response: StartResponse,
    status: str,
    extra_headers: list[tuple[str, str]] = list(),
    exc_info: Optional[tuple[Any, Any, Any]] = None,
) -> Response:
    body = (status + "\n").encode()
    start_response(
        status,
        [
            ("Content-Type", "text/plain"),
            ("Content-Length", str(len(body))),
            *extra_headers,
        ],
        exc_info,
    )
    return [body]


def middleware(f: ProtoMiddleware) -> Middleware:
    @wraps(f)
    def outer(app: App):
        @wraps(app)
        def inner(environ: Env, start_response: StartResponse):
            return f(app, environ, start_response)

        return inner

    return outer


@middleware
def catch_exceptions(app: App, environ: Env, start_response: StartResponse) -> Response:
    try:
        return app(environ, start_response)
    except Exception as e:
        print("".join(traceback.format_exception(type(e), e, e.__traceback__)))
        return simple_response(
            start_response, "500 Internal Server Error", exc_info=sys.exc_info()
        )


@middleware
def validate_method(app: App, environ: Env, start_response: StartResponse) -> Response:
    if environ["REQUEST_METHOD"] in {"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"}:
        return app(environ, start_response)
    if environ["REQUEST_METHOD"] in {"CONNECT", "TRACE", "PATCH"}:
        return simple_response(start_response, "405 Method Not Allowed")
    return simple_response(start_response, "501 Not Implemented")


@middleware
def if_none_match(app: App, environ: Env, start_response: StartResponse) -> Response:
    if "HTTP_IF_NONE_MATCH" not in environ:
        return app(environ, start_response)
    if_none_match = environ["HTTP_IF_NONE_MATCH"]
    del environ["HTTP_IF_NONE_MATCH"]
    if environ["REQUEST_METHOD"] not in {"GET", "HEAD"}:
        return app(environ, start_response)
    head_env = environ.copy()
    head_env["REQUEST_METHOD"] = "HEAD"
    etag = None

    def head_start_response(
        status: str,
        headers: list[tuple[str, str]],
        exc_info: Optional[tuple[Any, Any, Any]] = None,
    ) -> Callable[[bytes], object]:
        _, _ = status, exc_info
        nonlocal etag
        for key, value in headers:
            if key == "ETag":
                etag = value[1:-1]
        return lambda _: None

    resp = app(head_env, head_start_response)
    if isinstance(resp, Closable):
        resp.close()

    if not isinstance(etag, str):
        return app(environ, start_response)

    if if_none_match == "*":
        start_response("304 Not Modified", [("ETag", f'"{etag}"')])
        return []

    etags = if_none_match.split(",")
    etags = {e.strip(" \t").removeprefix("W/") for e in etags}
    for e in etags:
        if e[0] != '"' or e[-1] != '"':
            return simple_response(start_response, "400 Bad Request")
    etags = {e[1:-1] for e in etags}
    if isinstance(etag, str) and etag in etags:
        start_response("304 Not Modified", [("ETag", f'"{etag}"')])
        return []
    return app(environ, start_response)


@middleware
def options(app: App, environ: Env, start_response: StartResponse) -> Response:
    if environ["REQUEST_METHOD"] != "OPTIONS":
        return app(environ, start_response)
    start_response(
        "204 No Content",
        [
            ("Allow", "GET, HEAD, POST, PUT, DELETE, OPTIONS"),
        ],
    )
    return []


@middleware
def open_database(app: App, environ: Env, start_response: StartResponse) -> Response:
    db_path = environ.get("PASTE_DB", DB_PATH)
    with db.connect(db_path) as conn:
        environ["paste.db_conn"] = conn
        return app(environ, start_response)


def authenticate(get_auth: Callable[[Env], Auth]) -> Middleware:
    @middleware
    def authenticate(app: App, environ: Env, start_response: StartResponse) -> Response:
        def check_auth():
            value = environ.get("HTTP_AUTHORIZATION")
            if not isinstance(value, str):
                return False
            if not value.startswith("APIKey "):
                return False
            value = value.removeprefix("APIKey ")
            try:
                value = b64decode(value.encode(), validate=True)
            except (binascii.Error, UnicodeEncodeError):
                return False
            return get_auth(environ).check_token(value)

        if environ["REQUEST_METHOD"] in {"GET", "HEAD"} or check_auth():
            return app(environ, start_response)
        return simple_response(
            start_response,
            "401 Unauthorized",
            extra_headers=[("WWW-Authenticate", "APIKey")],
        )

    return authenticate


def paste_application(
    environ: Env,
    start_response: StartResponse,
    get_store: Callable[[Env], Store] = lambda environ: Store(environ["paste.db_conn"]),
    /,
) -> Response:
    store = get_store(environ)
    name = environ["PATH_INFO"]
    if environ["REQUEST_METHOD"] == "GET":
        row = store.get(name)
        if not row:
            return simple_response(start_response, "404 Not Found")
        content_type, content_hash, content = row
        start_response(
            "200 OK",
            [
                ("Content-Type", content_type),
                ("Content-Length", str(len(content))),
                ("ETag", f'"{b64encode(content_hash).decode()}"'),
            ],
        )
        return [content]
    elif environ["REQUEST_METHOD"] == "HEAD":
        row = store.head(name)
        if not row:
            return simple_response(start_response, "404 Not Found")
        content_type, content_hash, content_length = row
        start_response(
            "200 OK",
            [
                ("Content-Type", content_type),
                ("Content-Length", str(content_length)),
                ("ETag", f'"{b64encode(content_hash).decode()}"'),
            ],
        )
        return []
    elif environ["REQUEST_METHOD"] == "PUT":
        content_type = environ.get("CONTENT_TYPE", "text/plain")
        content_length = int(environ["CONTENT_LENGTH"])
        content = environ["wsgi.input"].read(content_length)
        created, content_hash = store.put(name, content, content_type)
        start_response(
            "201 Created" if created else "204 No Content",
            [
                ("Location", request_uri(environ)),
                ("ETag", f'"{b64encode(content_hash).decode()}"'),
            ],
        )
        return []
    elif environ["REQUEST_METHOD"] == "POST":
        content_type = environ.get("CONTENT_TYPE", "text/plain")
        content_length = int(environ["CONTENT_LENGTH"])
        content = environ["wsgi.input"].read(content_length)
        path, content_hash = store.post(name, content, content_type)
        uri = application_uri(environ)
        path = urllib.parse.quote(path)
        if uri[-1] == "/" and path[:1] == "/":
            uri += path[1:]
        else:
            uri += path
        if environ.get("QUERY_STRING"):
            uri += "?" + environ["QUERY_STRING"]
        start_response(
            "201 Created",
            [("Location", uri), ("ETag", f'"{b64encode(content_hash).decode()}"')],
        )
        return []
    elif environ["REQUEST_METHOD"] == "DELETE":
        if store.delete(name):
            start_response("204 No Content", [])
            return []
        return simple_response(start_response, "404 Not Found")
    return simple_response(start_response, "500 Internal Server Error")


middlewares = [
    catch_exceptions,
    validate_method,
    options,
    if_none_match,
    open_database,
    authenticate(lambda environ: Auth(environ["paste.db_conn"])),
]

application: App = paste_application
for m in reversed(middlewares):
    application = m(application)