pytrat-django 0.1.0__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.
- pytrat/django/__init__.py +50 -0
- pytrat/django/_http.py +201 -0
- pytrat/django/_runtime.py +126 -0
- pytrat/django/_settings.py +111 -0
- pytrat/django/apps.py +36 -0
- pytrat/django/checks.py +88 -0
- pytrat/django/decorators.py +248 -0
- pytrat/django/middleware.py +63 -0
- pytrat/django/py.typed +0 -0
- pytrat_django-0.1.0.dist-info/METADATA +79 -0
- pytrat_django-0.1.0.dist-info/RECORD +13 -0
- pytrat_django-0.1.0.dist-info/WHEEL +4 -0
- pytrat_django-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""PyTraT Django integration: Transaction Token enforcement for Django views.
|
|
2
|
+
|
|
3
|
+
Add ``"pytrat.django"`` to ``INSTALLED_APPS`` and configure::
|
|
4
|
+
|
|
5
|
+
PYTRAT = {
|
|
6
|
+
"ENFORCER": "myproject.security.build_enforcer", # zero-arg -> TransactionEnforcer
|
|
7
|
+
"POLICY": "policy.yaml", # optional YAML policy
|
|
8
|
+
"PROTECTED_PREFIXES": ["/internal/"],
|
|
9
|
+
"DEBUG_ERRORS": False,
|
|
10
|
+
}
|
|
11
|
+
MIDDLEWARE = [..., "pytrat.django.middleware.TransactionMiddleware"]
|
|
12
|
+
|
|
13
|
+
then decorate views::
|
|
14
|
+
|
|
15
|
+
@require_transaction(scope="payments.transfer", bind_fields=["amount_minor", "currency"])
|
|
16
|
+
def transfer(request):
|
|
17
|
+
txn = request.transaction
|
|
18
|
+
...
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from pytrat.django._http import (
|
|
22
|
+
BodyValidationError,
|
|
23
|
+
RequestDataError,
|
|
24
|
+
UnsupportedBodyError,
|
|
25
|
+
inbound_request,
|
|
26
|
+
problem_response,
|
|
27
|
+
)
|
|
28
|
+
from pytrat.django._runtime import Runtime, get_enforcer, get_runtime
|
|
29
|
+
from pytrat.django._settings import PyTraTSettings, parse_settings
|
|
30
|
+
from pytrat.django.checks import check_routes
|
|
31
|
+
from pytrat.django.decorators import TransactionGuard, exempt, require_transaction
|
|
32
|
+
from pytrat.django.middleware import TransactionMiddleware
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"BodyValidationError",
|
|
36
|
+
"PyTraTSettings",
|
|
37
|
+
"RequestDataError",
|
|
38
|
+
"Runtime",
|
|
39
|
+
"TransactionGuard",
|
|
40
|
+
"TransactionMiddleware",
|
|
41
|
+
"UnsupportedBodyError",
|
|
42
|
+
"check_routes",
|
|
43
|
+
"exempt",
|
|
44
|
+
"get_enforcer",
|
|
45
|
+
"get_runtime",
|
|
46
|
+
"inbound_request",
|
|
47
|
+
"parse_settings",
|
|
48
|
+
"problem_response",
|
|
49
|
+
"require_transaction",
|
|
50
|
+
]
|
pytrat/django/_http.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Adapting Django requests and responses to the framework-agnostic pipeline (private)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import ClassVar, Final
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ValidationError
|
|
9
|
+
|
|
10
|
+
from django.http import HttpRequest, HttpResponse, JsonResponse
|
|
11
|
+
from django.http.request import RawPostDataException
|
|
12
|
+
from pytrat.core import (
|
|
13
|
+
InboundRequest,
|
|
14
|
+
PyTraTError,
|
|
15
|
+
RequestError,
|
|
16
|
+
problem_details,
|
|
17
|
+
strict_loads,
|
|
18
|
+
)
|
|
19
|
+
from pytrat.core.constants import TXN_TOKEN_HEADER
|
|
20
|
+
from pytrat.policy import CompiledPolicy
|
|
21
|
+
|
|
22
|
+
PROBLEM_CONTENT_TYPE: Final = "application/problem+json"
|
|
23
|
+
JSON_CONTENT_TYPE: Final = "application/json"
|
|
24
|
+
|
|
25
|
+
# CGI/WSGI META keys for headers that do not carry the ``HTTP_`` prefix.
|
|
26
|
+
_UNPREFIXED_HEADERS: Final = {"CONTENT_TYPE": "Content-Type", "CONTENT_LENGTH": "Content-Length"}
|
|
27
|
+
_TXN_TOKEN_META_KEY: Final = "HTTP_" + TXN_TOKEN_HEADER.upper().replace("-", "_")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class RequestDataError(RequestError):
|
|
31
|
+
"""The request body or parameters cannot be turned into unambiguous request data."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class UnsupportedBodyError(RequestDataError):
|
|
35
|
+
"""A body must be bound but is not ``application/json``."""
|
|
36
|
+
|
|
37
|
+
http_status: ClassVar[int] = 415
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class BodyValidationError(RequestDataError):
|
|
41
|
+
"""The JSON body failed validation against the view's ``body_model``."""
|
|
42
|
+
|
|
43
|
+
http_status: ClassVar[int] = 422
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def inbound_request(request: HttpRequest) -> InboundRequest:
|
|
47
|
+
"""Convert a Django request into the transport facts the enforcer needs.
|
|
48
|
+
|
|
49
|
+
Header names are reconstructed from ``request.META`` (``HTTP_TXN_TOKEN`` -> ``Txn-Token``)
|
|
50
|
+
and ``peer`` is ``REMOTE_ADDR``.
|
|
51
|
+
|
|
52
|
+
WSGI (PEP 3333) and Django's ASGI handler join repeated headers with a comma. A compact JWS
|
|
53
|
+
never contains one, so a comma in ``Txn-Token`` means the header was repeated; the value is
|
|
54
|
+
split back apart so the enforcer's single-token check (txn-tokens-11 §12.1) rejects it as
|
|
55
|
+
``TOKEN_MALFORMED``.
|
|
56
|
+
"""
|
|
57
|
+
meta = _meta(request)
|
|
58
|
+
headers: list[tuple[str, str]] = []
|
|
59
|
+
for key, value in meta.items():
|
|
60
|
+
if not isinstance(value, str):
|
|
61
|
+
continue
|
|
62
|
+
if key == _TXN_TOKEN_META_KEY:
|
|
63
|
+
# txn-tokens-11 §12.1
|
|
64
|
+
headers.extend((TXN_TOKEN_HEADER, part) for part in value.split(","))
|
|
65
|
+
elif key in _UNPREFIXED_HEADERS:
|
|
66
|
+
headers.append((_UNPREFIXED_HEADERS[key], value))
|
|
67
|
+
elif key.startswith("HTTP_"):
|
|
68
|
+
headers.append((_header_name(key[5:]), value))
|
|
69
|
+
peer = meta.get("REMOTE_ADDR")
|
|
70
|
+
return InboundRequest(tuple(headers), peer if isinstance(peer, str) and peer else None)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def request_data(
|
|
74
|
+
request: HttpRequest,
|
|
75
|
+
url_kwargs: Mapping[str, object],
|
|
76
|
+
policy: CompiledPolicy,
|
|
77
|
+
body_model: type[BaseModel] | None,
|
|
78
|
+
) -> tuple[dict[str, object], BaseModel | None]:
|
|
79
|
+
"""Build the data compared against ``tctx``: JSON body, URL kwargs and query parameters.
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
The merged request data and the validated body model instance (if ``body_model`` is set).
|
|
83
|
+
With a ``body_model`` the body part is ``model_dump(mode="python")`` of the validated
|
|
84
|
+
instance, so the values compared are exactly the values the view receives.
|
|
85
|
+
|
|
86
|
+
Raises:
|
|
87
|
+
RequestDataError: Duplicate JSON keys, a non-object body, a repeated query parameter, or a
|
|
88
|
+
name present in more than one source (400).
|
|
89
|
+
UnsupportedBodyError: A body that must be bound is not ``application/json`` (415).
|
|
90
|
+
BodyValidationError: The body does not validate against ``body_model`` (422).
|
|
91
|
+
"""
|
|
92
|
+
body, validated = _body_data(request, policy, body_model)
|
|
93
|
+
merged: dict[str, object] = dict(body)
|
|
94
|
+
_merge(merged, url_kwargs, "URL parameter")
|
|
95
|
+
_merge(merged, _query_data(request), "query parameter")
|
|
96
|
+
return merged, validated
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def problem_response(
|
|
100
|
+
error: PyTraTError, *, transaction_id: str | None = None, debug: bool = False
|
|
101
|
+
) -> HttpResponse:
|
|
102
|
+
"""Render ``error`` as an RFC 9457 ``application/problem+json`` response.
|
|
103
|
+
|
|
104
|
+
The document comes from :func:`pytrat.core.problem_details`, shared with every integration.
|
|
105
|
+
``transaction_id`` fills in the verified ``txn`` for errors raised by the view itself. 401
|
|
106
|
+
responses carry ``WWW-Authenticate: Txn-Token``.
|
|
107
|
+
"""
|
|
108
|
+
if error.transaction_id is None and transaction_id is not None:
|
|
109
|
+
error.transaction_id = transaction_id
|
|
110
|
+
body = problem_details(error, include_detail=debug)
|
|
111
|
+
response: HttpResponse = JsonResponse(
|
|
112
|
+
body, status=error.http_status, content_type=PROBLEM_CONTENT_TYPE
|
|
113
|
+
)
|
|
114
|
+
if error.http_status == 401:
|
|
115
|
+
response["WWW-Authenticate"] = TXN_TOKEN_HEADER
|
|
116
|
+
return response
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _header_name(meta_suffix: str) -> str:
|
|
120
|
+
return "-".join(part.capitalize() for part in meta_suffix.split("_"))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _meta(request: HttpRequest) -> Mapping[str, object]:
|
|
124
|
+
meta: object = request.META
|
|
125
|
+
if not isinstance(meta, Mapping): # pragma: no cover - Django always provides a dict
|
|
126
|
+
raise TypeError("request.META is not a mapping")
|
|
127
|
+
return meta
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _raw_body(request: HttpRequest) -> bytes | None:
|
|
131
|
+
"""The raw body, or None if Django already consumed the stream (e.g. multipart parsing)."""
|
|
132
|
+
try:
|
|
133
|
+
body: object = request.body
|
|
134
|
+
except RawPostDataException:
|
|
135
|
+
return None
|
|
136
|
+
return body if isinstance(body, bytes) else None
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _content_type(request: HttpRequest) -> str:
|
|
140
|
+
content_type: object = request.content_type
|
|
141
|
+
return content_type.lower() if isinstance(content_type, str) else ""
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _body_data(
|
|
145
|
+
request: HttpRequest, policy: CompiledPolicy, body_model: type[BaseModel] | None
|
|
146
|
+
) -> tuple[Mapping[str, object], BaseModel | None]:
|
|
147
|
+
raw_body = _raw_body(request)
|
|
148
|
+
is_json = _content_type(request) == JSON_CONTENT_TYPE
|
|
149
|
+
if body_model is None and raw_body == b"":
|
|
150
|
+
return {}, None
|
|
151
|
+
if not is_json:
|
|
152
|
+
if body_model is not None or policy.binding.rules:
|
|
153
|
+
raise UnsupportedBodyError("a bound request body must be application/json")
|
|
154
|
+
# Nothing is bound, so a non-JSON body (e.g. a form) is the view's business.
|
|
155
|
+
return {}, None
|
|
156
|
+
parsed = _parse_json_object(raw_body)
|
|
157
|
+
if body_model is None:
|
|
158
|
+
return parsed, None
|
|
159
|
+
try:
|
|
160
|
+
validated = body_model.model_validate(parsed)
|
|
161
|
+
except ValidationError:
|
|
162
|
+
raise BodyValidationError("request body failed validation") from None
|
|
163
|
+
return validated.model_dump(mode="python"), validated
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _parse_json_object(raw_body: bytes | None) -> Mapping[str, object]:
|
|
167
|
+
if raw_body is None:
|
|
168
|
+
raise RequestDataError("request body is unavailable")
|
|
169
|
+
try:
|
|
170
|
+
parsed = strict_loads(raw_body)
|
|
171
|
+
except ValueError:
|
|
172
|
+
# Includes DuplicateKeyError: parsers disagree on duplicates, so they are never accepted.
|
|
173
|
+
raise RequestDataError("request body is not strict JSON") from None
|
|
174
|
+
if not isinstance(parsed, dict):
|
|
175
|
+
raise RequestDataError("request body must be a JSON object")
|
|
176
|
+
return parsed
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _query_data(request: HttpRequest) -> dict[str, object]:
|
|
180
|
+
query: object = request.GET
|
|
181
|
+
data: dict[str, object] = {}
|
|
182
|
+
for key in _keys(query):
|
|
183
|
+
values: object = query.getlist(key) # type: ignore[attr-defined] # Django QueryDict
|
|
184
|
+
if not isinstance(values, list) or len(values) != 1:
|
|
185
|
+
raise RequestDataError("query parameter appears more than once")
|
|
186
|
+
data[key] = values[0]
|
|
187
|
+
return data
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _keys(query: object) -> list[str]:
|
|
191
|
+
if not isinstance(query, Mapping): # pragma: no cover - QueryDict is always a mapping
|
|
192
|
+
raise TypeError("request.GET is not a mapping")
|
|
193
|
+
return [key for key in query if isinstance(key, str)]
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _merge(target: dict[str, object], source: Mapping[str, object], label: str) -> None:
|
|
197
|
+
for key, value in source.items():
|
|
198
|
+
if key in target:
|
|
199
|
+
# Ambiguity about which value was authorized is an attack surface; refuse it.
|
|
200
|
+
raise RequestDataError(f"{label} collides with another request field")
|
|
201
|
+
target[key] = value
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Startup resolution of the enforcer and policy, cached on the app config (private)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Final
|
|
8
|
+
|
|
9
|
+
from django.apps import apps
|
|
10
|
+
from django.conf import settings
|
|
11
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
12
|
+
from django.utils.module_loading import import_string
|
|
13
|
+
from pytrat.core import ConfigurationError, ReplayStore
|
|
14
|
+
from pytrat.django._settings import SETTINGS_NAME, PyTraTSettings, parse_settings
|
|
15
|
+
from pytrat.policy import AgentDirectory, PolicySet, TransactionEnforcer, load_policy
|
|
16
|
+
|
|
17
|
+
APP_LABEL: Final = "pytrat_django"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class Runtime:
|
|
22
|
+
"""Everything the integration resolved at startup.
|
|
23
|
+
|
|
24
|
+
Attributes:
|
|
25
|
+
settings: The validated ``PYTRAT`` setting.
|
|
26
|
+
enforcer: The enforcer every protected view uses.
|
|
27
|
+
policies: The compiled YAML policy, if ``POLICY`` is configured.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
settings: PyTraTSettings
|
|
31
|
+
enforcer: TransactionEnforcer
|
|
32
|
+
policies: PolicySet | None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load_runtime() -> Runtime:
|
|
36
|
+
"""Read ``settings.PYTRAT``, build the enforcer and compile the YAML policy.
|
|
37
|
+
|
|
38
|
+
Raises:
|
|
39
|
+
ImproperlyConfigured: If the setting is invalid, a factory cannot be imported or returns
|
|
40
|
+
the wrong type, or the policy fails to load. The process should refuse to start.
|
|
41
|
+
"""
|
|
42
|
+
parsed = parse_settings(getattr(settings, SETTINGS_NAME, None))
|
|
43
|
+
enforcer = _build(parsed.enforcer, "ENFORCER", TransactionEnforcer)
|
|
44
|
+
policies: PolicySet | None = None
|
|
45
|
+
if parsed.policy is not None:
|
|
46
|
+
replay_store = _optional(parsed.replay_store, "REPLAY_STORE")
|
|
47
|
+
directory = _optional(parsed.agent_directory, "AGENT_DIRECTORY")
|
|
48
|
+
try:
|
|
49
|
+
policies = load_policy(
|
|
50
|
+
parsed.policy,
|
|
51
|
+
replay_store=_as_replay_store(replay_store),
|
|
52
|
+
agent_directory=_as_directory(directory),
|
|
53
|
+
)
|
|
54
|
+
except ConfigurationError as exc:
|
|
55
|
+
raise ImproperlyConfigured(f"PYTRAT['POLICY'] is invalid: {exc.detail}") from exc
|
|
56
|
+
return Runtime(settings=parsed, enforcer=enforcer, policies=policies)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def get_runtime() -> Runtime:
|
|
60
|
+
"""The runtime cached by :class:`~pytrat.django.apps.PyTraTConfig`.
|
|
61
|
+
|
|
62
|
+
Raises:
|
|
63
|
+
ImproperlyConfigured: If ``pytrat.django`` is not installed or not yet ready.
|
|
64
|
+
"""
|
|
65
|
+
try:
|
|
66
|
+
config: object = apps.get_app_config(APP_LABEL)
|
|
67
|
+
except LookupError:
|
|
68
|
+
raise ImproperlyConfigured("pytrat.django is not in INSTALLED_APPS") from None
|
|
69
|
+
runtime = getattr(config, "runtime", None)
|
|
70
|
+
if not isinstance(runtime, Runtime):
|
|
71
|
+
raise ImproperlyConfigured("pytrat.django has not been initialised")
|
|
72
|
+
return runtime
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def get_enforcer() -> TransactionEnforcer:
|
|
76
|
+
"""The :class:`TransactionEnforcer` configured by ``PYTRAT['ENFORCER']``.
|
|
77
|
+
|
|
78
|
+
Raises:
|
|
79
|
+
ImproperlyConfigured: If the integration is not installed or not initialised.
|
|
80
|
+
"""
|
|
81
|
+
return get_runtime().enforcer
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _build[T](path: str, key: str, expected: type[T]) -> T:
|
|
85
|
+
instance = _call_factory(path, key)
|
|
86
|
+
if not isinstance(instance, expected):
|
|
87
|
+
raise ImproperlyConfigured(
|
|
88
|
+
f"PYTRAT['{key}'] factory must return a {expected.__name__}, "
|
|
89
|
+
f"got {type(instance).__name__}"
|
|
90
|
+
)
|
|
91
|
+
return instance
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _optional(path: str | None, key: str) -> object:
|
|
95
|
+
return None if path is None else _call_factory(path, key)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _call_factory(path: str, key: str) -> object:
|
|
99
|
+
try:
|
|
100
|
+
factory: object = import_string(path)
|
|
101
|
+
except ImportError as exc:
|
|
102
|
+
raise ImproperlyConfigured(f"PYTRAT['{key}'] cannot be imported: {path}") from exc
|
|
103
|
+
if not callable(factory):
|
|
104
|
+
raise ImproperlyConfigured(f"PYTRAT['{key}'] is not callable: {path}")
|
|
105
|
+
call: Callable[[], object] = factory
|
|
106
|
+
return call()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _as_replay_store(value: object) -> ReplayStore | None:
|
|
110
|
+
if value is None:
|
|
111
|
+
return None
|
|
112
|
+
if not callable(getattr(value, "record_once", None)):
|
|
113
|
+
raise ImproperlyConfigured("PYTRAT['REPLAY_STORE'] factory must return a ReplayStore")
|
|
114
|
+
store: ReplayStore = value # type: ignore[assignment] # checked structurally above
|
|
115
|
+
return store
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _as_directory(value: object) -> AgentDirectory | None:
|
|
119
|
+
if value is None:
|
|
120
|
+
return None
|
|
121
|
+
if not callable(getattr(value, "is_registered", None)):
|
|
122
|
+
raise ImproperlyConfigured(
|
|
123
|
+
"PYTRAT['AGENT_DIRECTORY'] factory must return an AgentDirectory"
|
|
124
|
+
)
|
|
125
|
+
directory: AgentDirectory = value # type: ignore[assignment] # checked structurally above
|
|
126
|
+
return directory
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Parsing and validation of the ``PYTRAT`` Django setting (private)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Final
|
|
9
|
+
|
|
10
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
11
|
+
|
|
12
|
+
SETTINGS_NAME: Final = "PYTRAT"
|
|
13
|
+
|
|
14
|
+
_KNOWN_KEYS: Final = frozenset(
|
|
15
|
+
{
|
|
16
|
+
"ENFORCER",
|
|
17
|
+
"POLICY",
|
|
18
|
+
"PROTECTED_PREFIXES",
|
|
19
|
+
"DEBUG_ERRORS",
|
|
20
|
+
"REPLAY_STORE",
|
|
21
|
+
"AGENT_DIRECTORY",
|
|
22
|
+
}
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class PyTraTSettings:
|
|
28
|
+
"""The validated ``PYTRAT`` setting.
|
|
29
|
+
|
|
30
|
+
Attributes:
|
|
31
|
+
enforcer: Dotted path to a zero-argument factory returning a ``TransactionEnforcer``.
|
|
32
|
+
policy: Path to a YAML policy file, or None if every view declares its policy inline.
|
|
33
|
+
protected_prefixes: URL path prefixes whose views must declare a transaction policy.
|
|
34
|
+
debug_errors: Include the failed check's ``detail`` in error responses.
|
|
35
|
+
replay_store: Dotted path to a zero-argument ``ReplayStore`` factory for YAML policies.
|
|
36
|
+
agent_directory: Dotted path to a zero-argument ``AgentDirectory`` factory for YAML
|
|
37
|
+
policies.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
enforcer: str
|
|
41
|
+
policy: str | None = None
|
|
42
|
+
protected_prefixes: tuple[str, ...] = ()
|
|
43
|
+
debug_errors: bool = False
|
|
44
|
+
replay_store: str | None = None
|
|
45
|
+
agent_directory: str | None = None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def parse_settings(raw: object) -> PyTraTSettings:
|
|
49
|
+
"""Validate the raw ``PYTRAT`` setting.
|
|
50
|
+
|
|
51
|
+
Unknown keys are rejected so that a typo cannot silently drop a protection.
|
|
52
|
+
|
|
53
|
+
Raises:
|
|
54
|
+
ImproperlyConfigured: If the setting is missing or invalid.
|
|
55
|
+
"""
|
|
56
|
+
if raw is None:
|
|
57
|
+
raise _improper("the PYTRAT setting is required when pytrat.django is installed")
|
|
58
|
+
if not isinstance(raw, Mapping):
|
|
59
|
+
raise _improper("PYTRAT must be a dict")
|
|
60
|
+
unknown = sorted(str(key) for key in raw if key not in _KNOWN_KEYS)
|
|
61
|
+
if unknown:
|
|
62
|
+
raise _improper(f"PYTRAT has unknown keys: {', '.join(unknown)}")
|
|
63
|
+
return PyTraTSettings(
|
|
64
|
+
enforcer=_dotted_path(raw, "ENFORCER", required=True) or "",
|
|
65
|
+
policy=_policy_path(raw.get("POLICY")),
|
|
66
|
+
protected_prefixes=_prefixes(raw.get("PROTECTED_PREFIXES", ())),
|
|
67
|
+
debug_errors=_flag(raw.get("DEBUG_ERRORS", False)),
|
|
68
|
+
replay_store=_dotted_path(raw, "REPLAY_STORE"),
|
|
69
|
+
agent_directory=_dotted_path(raw, "AGENT_DIRECTORY"),
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _dotted_path(raw: Mapping[object, object], key: str, *, required: bool = False) -> str | None:
|
|
74
|
+
value = raw.get(key)
|
|
75
|
+
if value is None and not required:
|
|
76
|
+
return None
|
|
77
|
+
if not isinstance(value, str) or "." not in value:
|
|
78
|
+
raise _improper(f"PYTRAT['{key}'] must be a dotted import path")
|
|
79
|
+
return value
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _policy_path(value: object) -> str | None:
|
|
83
|
+
if value is None:
|
|
84
|
+
return None
|
|
85
|
+
if isinstance(value, os.PathLike):
|
|
86
|
+
value = os.fspath(value)
|
|
87
|
+
if not isinstance(value, str) or not value:
|
|
88
|
+
raise _improper("PYTRAT['POLICY'] must be a file path or None")
|
|
89
|
+
return value
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _prefixes(value: object) -> tuple[str, ...]:
|
|
93
|
+
if not isinstance(value, list | tuple):
|
|
94
|
+
raise _improper("PYTRAT['PROTECTED_PREFIXES'] must be a list of path prefixes")
|
|
95
|
+
prefixes: list[str] = []
|
|
96
|
+
for item in value:
|
|
97
|
+
if not isinstance(item, str) or not item.startswith("/"):
|
|
98
|
+
raise _improper("each protected prefix must be a string starting with '/'")
|
|
99
|
+
prefixes.append(item)
|
|
100
|
+
return tuple(prefixes)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _flag(value: object) -> bool:
|
|
104
|
+
if not isinstance(value, bool):
|
|
105
|
+
raise _improper("PYTRAT['DEBUG_ERRORS'] must be a bool")
|
|
106
|
+
return value
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _improper(message: str) -> ImproperlyConfigured:
|
|
110
|
+
error: ImproperlyConfigured = ImproperlyConfigured(message)
|
|
111
|
+
return error
|
pytrat/django/apps.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Django application config: resolves and validates the configuration once, at startup."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from django.apps import AppConfig
|
|
6
|
+
from django.core import checks
|
|
7
|
+
from pytrat.django._runtime import APP_LABEL, Runtime, load_runtime
|
|
8
|
+
from pytrat.django.checks import check_routes
|
|
9
|
+
|
|
10
|
+
__all__ = ["PyTraTConfig"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class PyTraTConfig(AppConfig): # type: ignore[misc] # django ships no type stubs
|
|
14
|
+
"""Builds the enforcer and compiles the YAML policy in :meth:`ready`.
|
|
15
|
+
|
|
16
|
+
Invalid configuration raises ``ImproperlyConfigured`` here, so the process refuses to start
|
|
17
|
+
instead of failing (or worse, passing) on the first request.
|
|
18
|
+
|
|
19
|
+
Attributes:
|
|
20
|
+
runtime: The resolved configuration, cached for the life of the app registry.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
name = "pytrat.django"
|
|
24
|
+
label = APP_LABEL
|
|
25
|
+
verbose_name = "PyTraT Transaction Tokens"
|
|
26
|
+
|
|
27
|
+
runtime: Runtime | None = None
|
|
28
|
+
|
|
29
|
+
def ready(self) -> None:
|
|
30
|
+
"""Resolve ``settings.PYTRAT`` and register the system checks.
|
|
31
|
+
|
|
32
|
+
Raises:
|
|
33
|
+
ImproperlyConfigured: If the configuration is invalid.
|
|
34
|
+
"""
|
|
35
|
+
checks.register(check_routes, checks.Tags.security, checks.Tags.urls)
|
|
36
|
+
self.runtime = load_runtime()
|
pytrat/django/checks.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Django system checks: every view under a protected prefix declares a policy."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator, Sequence
|
|
6
|
+
from typing import Final
|
|
7
|
+
|
|
8
|
+
from django.conf import settings
|
|
9
|
+
from django.core import checks
|
|
10
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
11
|
+
from django.urls import URLPattern, URLResolver, get_resolver
|
|
12
|
+
from pytrat.django._runtime import Runtime, get_runtime
|
|
13
|
+
from pytrat.django.decorators import guard_of, is_exempt
|
|
14
|
+
from pytrat.django.middleware import is_protected_path
|
|
15
|
+
|
|
16
|
+
__all__ = ["check_routes"]
|
|
17
|
+
|
|
18
|
+
MIDDLEWARE_PATH: Final = "pytrat.django.middleware.TransactionMiddleware"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def check_routes(app_configs: object = None, **kwargs: object) -> list[checks.CheckMessage]:
|
|
22
|
+
"""Report misconfigured transaction protection.
|
|
23
|
+
|
|
24
|
+
* ``pytrat.E001``: a view under a protected prefix has neither ``@require_transaction`` nor
|
|
25
|
+
``@exempt`` (the middleware would deny it at runtime; this surfaces it at startup).
|
|
26
|
+
* ``pytrat.E002``: a view's ``policy_id`` is not in the YAML policy.
|
|
27
|
+
* ``pytrat.W001``: protected prefixes are configured but ``TransactionMiddleware`` is not.
|
|
28
|
+
"""
|
|
29
|
+
try:
|
|
30
|
+
runtime = get_runtime()
|
|
31
|
+
except ImproperlyConfigured as exc:
|
|
32
|
+
return [checks.Error(str(exc), id="pytrat.E000")]
|
|
33
|
+
messages: list[checks.CheckMessage] = []
|
|
34
|
+
prefixes = runtime.settings.protected_prefixes
|
|
35
|
+
if prefixes and MIDDLEWARE_PATH not in _middleware():
|
|
36
|
+
messages.append(
|
|
37
|
+
checks.Warning(
|
|
38
|
+
"PYTRAT['PROTECTED_PREFIXES'] is set but TransactionMiddleware is not installed",
|
|
39
|
+
hint=f"add {MIDDLEWARE_PATH!r} to MIDDLEWARE",
|
|
40
|
+
id="pytrat.W001",
|
|
41
|
+
)
|
|
42
|
+
)
|
|
43
|
+
for route, view in _walk(get_resolver().url_patterns, "/"):
|
|
44
|
+
messages.extend(_check_view(route, view, prefixes, runtime))
|
|
45
|
+
return messages
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _check_view(
|
|
49
|
+
route: str, view: object, prefixes: Sequence[str], runtime: Runtime
|
|
50
|
+
) -> Iterator[checks.CheckMessage]:
|
|
51
|
+
guard = guard_of(view)
|
|
52
|
+
if guard is None:
|
|
53
|
+
if is_protected_path(route, prefixes) and not is_exempt(view):
|
|
54
|
+
yield checks.Error(
|
|
55
|
+
f"view for {route!r} is under a protected prefix but has no transaction policy",
|
|
56
|
+
hint="decorate it with @require_transaction(...) or @exempt",
|
|
57
|
+
obj=view,
|
|
58
|
+
id="pytrat.E001",
|
|
59
|
+
)
|
|
60
|
+
return
|
|
61
|
+
try:
|
|
62
|
+
guard.resolve(runtime)
|
|
63
|
+
except ImproperlyConfigured as exc:
|
|
64
|
+
yield checks.Error(str(exc), obj=view, id="pytrat.E002")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _walk(patterns: Sequence[object], prefix: str) -> Iterator[tuple[str, object]]:
|
|
68
|
+
for entry in patterns:
|
|
69
|
+
route = prefix + _route_text(entry)
|
|
70
|
+
if isinstance(entry, URLResolver):
|
|
71
|
+
yield from _walk(entry.url_patterns, route)
|
|
72
|
+
elif isinstance(entry, URLPattern):
|
|
73
|
+
yield route, entry.callback
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _route_text(entry: object) -> str:
|
|
77
|
+
# Best effort for regex routes: drop anchors so the literal prefix can be compared.
|
|
78
|
+
text = str(getattr(entry, "pattern", ""))
|
|
79
|
+
return text.removeprefix("^").removesuffix("$")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _middleware() -> Sequence[str]:
|
|
83
|
+
configured: object = getattr(settings, "MIDDLEWARE", None) or ()
|
|
84
|
+
return (
|
|
85
|
+
[item for item in configured if isinstance(item, str)]
|
|
86
|
+
if isinstance(configured, list | tuple)
|
|
87
|
+
else []
|
|
88
|
+
)
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""View decorators: ``@require_transaction`` and ``@exempt``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
import inspect
|
|
7
|
+
from collections.abc import Awaitable, Callable, Iterable, Iterator, Mapping, Sequence
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import Final
|
|
11
|
+
|
|
12
|
+
from pydantic import BaseModel
|
|
13
|
+
|
|
14
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
15
|
+
from django.http import HttpRequest, HttpResponse
|
|
16
|
+
from pytrat.client.context import bind_transaction
|
|
17
|
+
from pytrat.core import ConfigurationError, PyTraTError, ReplayStore
|
|
18
|
+
from pytrat.django._http import inbound_request, problem_response, request_data
|
|
19
|
+
from pytrat.django._runtime import Runtime, get_runtime
|
|
20
|
+
from pytrat.policy import AgentDirectory, AgentRequirements, CompiledPolicy, Transaction
|
|
21
|
+
|
|
22
|
+
__all__ = ["TransactionGuard", "exempt", "guard_of", "is_exempt", "require_transaction"]
|
|
23
|
+
|
|
24
|
+
GUARD_ATTRIBUTE: Final = "pytrat_transaction_guard"
|
|
25
|
+
EXEMPT_ATTRIBUTE: Final = "pytrat_exempt"
|
|
26
|
+
|
|
27
|
+
type SyncView = Callable[..., HttpResponse]
|
|
28
|
+
type AsyncView = Callable[..., Awaitable[HttpResponse]]
|
|
29
|
+
type View = SyncView | AsyncView
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class TransactionGuard:
|
|
34
|
+
"""The policy attached to one decorated view.
|
|
35
|
+
|
|
36
|
+
Exactly one of ``policy`` (inline, compiled at decoration time) and ``policy_id`` (looked up
|
|
37
|
+
in the YAML policy configured by ``PYTRAT['POLICY']``) is set.
|
|
38
|
+
|
|
39
|
+
Attributes:
|
|
40
|
+
policy: The inline policy.
|
|
41
|
+
policy_id: The YAML resource name.
|
|
42
|
+
body_model: Pydantic model the JSON body is validated against, if any.
|
|
43
|
+
operation: Operation name passed to the policy (used by agent constraints).
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
policy: CompiledPolicy | None
|
|
47
|
+
policy_id: str | None
|
|
48
|
+
body_model: type[BaseModel] | None = field(default=None)
|
|
49
|
+
operation: str | None = None
|
|
50
|
+
|
|
51
|
+
def resolve(self, runtime: Runtime) -> CompiledPolicy:
|
|
52
|
+
"""The policy to enforce.
|
|
53
|
+
|
|
54
|
+
Raises:
|
|
55
|
+
ImproperlyConfigured: If ``policy_id`` names a resource that is not in the YAML
|
|
56
|
+
policy, or no YAML policy is configured. Fails closed: the view never runs.
|
|
57
|
+
"""
|
|
58
|
+
if self.policy is not None:
|
|
59
|
+
return self.policy
|
|
60
|
+
if runtime.policies is None:
|
|
61
|
+
raise ImproperlyConfigured(
|
|
62
|
+
f"view uses policy_id={self.policy_id!r} but PYTRAT['POLICY'] is not set"
|
|
63
|
+
)
|
|
64
|
+
for _, candidate in runtime.policies.routes:
|
|
65
|
+
if candidate.policy_id == self.policy_id:
|
|
66
|
+
return candidate
|
|
67
|
+
raise ImproperlyConfigured(f"policy_id={self.policy_id!r} is not in PYTRAT['POLICY']")
|
|
68
|
+
|
|
69
|
+
def authorize(self, request: HttpRequest, url_kwargs: dict[str, object]) -> Transaction | None:
|
|
70
|
+
"""Run the enforcement pipeline for ``request`` and attach the results to it.
|
|
71
|
+
|
|
72
|
+
Sets ``request.transaction`` (and ``request.validated_body`` when ``body_model`` is set).
|
|
73
|
+
|
|
74
|
+
Raises:
|
|
75
|
+
PyTraTError: Any denial, from request-data parsing or the enforcer.
|
|
76
|
+
ImproperlyConfigured: The integration or this view's policy is misconfigured.
|
|
77
|
+
"""
|
|
78
|
+
runtime = get_runtime()
|
|
79
|
+
policy = self.resolve(runtime)
|
|
80
|
+
data, validated = request_data(request, url_kwargs, policy, self.body_model)
|
|
81
|
+
transaction = runtime.enforcer.enforce(
|
|
82
|
+
policy, inbound_request(request), data, operation=self.operation
|
|
83
|
+
)
|
|
84
|
+
request.transaction = transaction
|
|
85
|
+
if self.body_model is not None:
|
|
86
|
+
request.validated_body = validated
|
|
87
|
+
return transaction
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def require_transaction(
|
|
91
|
+
*,
|
|
92
|
+
scope: str | Iterable[str] | None = None,
|
|
93
|
+
bind_fields: Sequence[str] | Mapping[str, str] = (),
|
|
94
|
+
allowed_callers: Iterable[str] | None = None,
|
|
95
|
+
require_workload_identity: bool = True,
|
|
96
|
+
single_use: bool = False,
|
|
97
|
+
agents: AgentRequirements | None = None,
|
|
98
|
+
policy_id: str | None = None,
|
|
99
|
+
body_model: type[BaseModel] | None = None,
|
|
100
|
+
operation: str | None = None,
|
|
101
|
+
replay_store: ReplayStore | None = None,
|
|
102
|
+
agent_directory: AgentDirectory | None = None,
|
|
103
|
+
) -> Callable[[View], View]:
|
|
104
|
+
"""Require an authorized Transaction Token for a Django view (sync or async).
|
|
105
|
+
|
|
106
|
+
Inline arguments compile to a :class:`CompiledPolicy` once, at decoration time; alternatively
|
|
107
|
+
``policy_id`` names a resource in the YAML policy (``PYTRAT['POLICY']``). Per request the
|
|
108
|
+
decorator builds request data (strict JSON body, URL kwargs and query parameters; a name in two
|
|
109
|
+
sources is a 400), runs the configured :class:`TransactionEnforcer`, sets
|
|
110
|
+
``request.transaction`` and binds the token while the view runs so outbound
|
|
111
|
+
``TransactionClient`` calls propagate it. Any :class:`PyTraTError`, including one the view
|
|
112
|
+
raises, becomes an RFC 9457 problem response.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
scope: Allowed scopes (space-delimited string or tokens). Required unless ``policy_id``.
|
|
116
|
+
bind_fields: Request fields bound to ``tctx`` (paths, or a request-path → tctx-path map).
|
|
117
|
+
allowed_callers: Permitted calling workloads; None allows any authenticated caller.
|
|
118
|
+
require_workload_identity: Require an authenticated calling workload.
|
|
119
|
+
single_use: Reject reuse of the same ``txn``; requires ``replay_store``.
|
|
120
|
+
agents: Agent constraints.
|
|
121
|
+
policy_id: Use this YAML resource instead of inline arguments.
|
|
122
|
+
body_model: Validate the JSON body with this Pydantic model, expose the instance as
|
|
123
|
+
``request.validated_body`` and bind its ``model_dump(mode="python")``.
|
|
124
|
+
operation: Operation name passed to the policy.
|
|
125
|
+
replay_store: Replay store for ``single_use``.
|
|
126
|
+
agent_directory: Directory for ``agents.require_verified_agent``.
|
|
127
|
+
|
|
128
|
+
Raises:
|
|
129
|
+
ImproperlyConfigured: At decoration time, if both inline arguments and ``policy_id`` are
|
|
130
|
+
given, neither is, or the inline policy fails compilation.
|
|
131
|
+
"""
|
|
132
|
+
inline_given = (
|
|
133
|
+
scope is not None
|
|
134
|
+
or bool(bind_fields)
|
|
135
|
+
or allowed_callers is not None
|
|
136
|
+
or not require_workload_identity
|
|
137
|
+
or single_use
|
|
138
|
+
or agents is not None
|
|
139
|
+
)
|
|
140
|
+
if policy_id is not None and inline_given:
|
|
141
|
+
raise ImproperlyConfigured("pass either policy_id or inline policy arguments, not both")
|
|
142
|
+
if policy_id is None and scope is None:
|
|
143
|
+
raise ImproperlyConfigured("require_transaction needs scope= or policy_id=")
|
|
144
|
+
|
|
145
|
+
def decorate(view: View) -> View:
|
|
146
|
+
policy: CompiledPolicy | None = None
|
|
147
|
+
if policy_id is None:
|
|
148
|
+
try:
|
|
149
|
+
policy = CompiledPolicy.build(
|
|
150
|
+
policy_id=_view_name(view),
|
|
151
|
+
allowed_scopes=scope or (),
|
|
152
|
+
bind_context=bind_fields,
|
|
153
|
+
allowed_callers=allowed_callers,
|
|
154
|
+
require_workload_identity=require_workload_identity,
|
|
155
|
+
single_use=single_use,
|
|
156
|
+
agents=agents,
|
|
157
|
+
replay_store=replay_store,
|
|
158
|
+
agent_directory=agent_directory,
|
|
159
|
+
)
|
|
160
|
+
except ConfigurationError as exc:
|
|
161
|
+
raise ImproperlyConfigured(f"invalid transaction policy: {exc.detail}") from exc
|
|
162
|
+
guard = TransactionGuard(
|
|
163
|
+
policy=policy, policy_id=policy_id, body_model=body_model, operation=operation
|
|
164
|
+
)
|
|
165
|
+
result: View
|
|
166
|
+
if inspect.iscoroutinefunction(view):
|
|
167
|
+
result = _wrap_async(view, guard)
|
|
168
|
+
else:
|
|
169
|
+
result = _wrap_sync(view, guard)
|
|
170
|
+
setattr(result, GUARD_ATTRIBUTE, guard)
|
|
171
|
+
return result
|
|
172
|
+
|
|
173
|
+
return decorate
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def exempt[V: View](view: V) -> V:
|
|
177
|
+
"""Mark a view under a protected prefix as deliberately not requiring a transaction."""
|
|
178
|
+
setattr(view, EXEMPT_ATTRIBUTE, True)
|
|
179
|
+
return view
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def guard_of(view: object) -> TransactionGuard | None:
|
|
183
|
+
"""The :class:`TransactionGuard` attached by ``@require_transaction``, if any."""
|
|
184
|
+
guard = getattr(view, GUARD_ATTRIBUTE, None)
|
|
185
|
+
return guard if isinstance(guard, TransactionGuard) else None
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def is_exempt(view: object) -> bool:
|
|
189
|
+
"""Whether the view was marked with ``@exempt``."""
|
|
190
|
+
return getattr(view, EXEMPT_ATTRIBUTE, False) is True
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _wrap_sync(view: SyncView, guard: TransactionGuard) -> SyncView:
|
|
194
|
+
@functools.wraps(view)
|
|
195
|
+
def wrapper(request: HttpRequest, *args: object, **kwargs: object) -> HttpResponse:
|
|
196
|
+
debug = _debug_errors()
|
|
197
|
+
try:
|
|
198
|
+
transaction = guard.authorize(request, kwargs)
|
|
199
|
+
except PyTraTError as error:
|
|
200
|
+
return problem_response(error, debug=debug)
|
|
201
|
+
with _bound(transaction):
|
|
202
|
+
try:
|
|
203
|
+
return view(request, *args, **kwargs)
|
|
204
|
+
except PyTraTError as error:
|
|
205
|
+
return problem_response(error, transaction_id=_txn_id(transaction), debug=debug)
|
|
206
|
+
|
|
207
|
+
return wrapper
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _wrap_async(view: AsyncView, guard: TransactionGuard) -> AsyncView:
|
|
211
|
+
# The enforcer does no I/O, so it runs inline rather than in a thread.
|
|
212
|
+
@functools.wraps(view)
|
|
213
|
+
async def wrapper(request: HttpRequest, *args: object, **kwargs: object) -> HttpResponse:
|
|
214
|
+
debug = _debug_errors()
|
|
215
|
+
try:
|
|
216
|
+
transaction = guard.authorize(request, kwargs)
|
|
217
|
+
except PyTraTError as error:
|
|
218
|
+
return problem_response(error, debug=debug)
|
|
219
|
+
with _bound(transaction):
|
|
220
|
+
try:
|
|
221
|
+
return await view(request, *args, **kwargs)
|
|
222
|
+
except PyTraTError as error:
|
|
223
|
+
return problem_response(error, transaction_id=_txn_id(transaction), debug=debug)
|
|
224
|
+
|
|
225
|
+
return wrapper
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
@contextmanager
|
|
229
|
+
def _bound(transaction: Transaction | None) -> Iterator[None]:
|
|
230
|
+
if transaction is None:
|
|
231
|
+
yield
|
|
232
|
+
return
|
|
233
|
+
with bind_transaction(transaction.token):
|
|
234
|
+
yield
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _txn_id(transaction: Transaction | None) -> str | None:
|
|
238
|
+
return transaction.id if transaction is not None else None
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _view_name(view: object) -> str:
|
|
242
|
+
module = getattr(view, "__module__", None) or "view"
|
|
243
|
+
name = getattr(view, "__qualname__", None) or type(view).__qualname__
|
|
244
|
+
return f"{module}.{name}"
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _debug_errors() -> bool:
|
|
248
|
+
return get_runtime().settings.debug_errors
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""``TransactionMiddleware``: fail closed for forgotten decorators under protected prefixes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
6
|
+
|
|
7
|
+
from asgiref.sync import iscoroutinefunction, markcoroutinefunction
|
|
8
|
+
|
|
9
|
+
from django.http import HttpRequest, HttpResponse
|
|
10
|
+
from pytrat.core import AuthorizationError, ReasonCode
|
|
11
|
+
from pytrat.django._http import problem_response
|
|
12
|
+
from pytrat.django._runtime import get_runtime
|
|
13
|
+
from pytrat.django.decorators import guard_of, is_exempt
|
|
14
|
+
|
|
15
|
+
__all__ = ["TransactionMiddleware", "is_protected_path"]
|
|
16
|
+
|
|
17
|
+
type GetResponse = Callable[[HttpRequest], HttpResponse | Awaitable[HttpResponse]]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TransactionMiddleware:
|
|
21
|
+
"""Denies requests under ``PYTRAT['PROTECTED_PREFIXES']`` whose view declares no policy.
|
|
22
|
+
|
|
23
|
+
A view counts as covered if it is decorated with ``@require_transaction`` or ``@exempt``.
|
|
24
|
+
Anything else under a protected prefix gets 403 ``POLICY_NOT_FOUND`` before the view runs.
|
|
25
|
+
The decorator performs enforcement; this middleware only makes a forgotten decorator fail
|
|
26
|
+
closed. Works under WSGI and ASGI.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
sync_capable = True
|
|
30
|
+
async_capable = True
|
|
31
|
+
|
|
32
|
+
def __init__(self, get_response: GetResponse) -> None:
|
|
33
|
+
self.get_response = get_response
|
|
34
|
+
self._is_async = iscoroutinefunction(get_response)
|
|
35
|
+
if self._is_async:
|
|
36
|
+
markcoroutinefunction(self)
|
|
37
|
+
|
|
38
|
+
def __call__(self, request: HttpRequest) -> HttpResponse | Awaitable[HttpResponse]:
|
|
39
|
+
"""Pass the request on; the check happens in :meth:`process_view`."""
|
|
40
|
+
return self.get_response(request)
|
|
41
|
+
|
|
42
|
+
def process_view(
|
|
43
|
+
self,
|
|
44
|
+
request: HttpRequest,
|
|
45
|
+
view_func: object,
|
|
46
|
+
view_args: Sequence[object],
|
|
47
|
+
view_kwargs: Mapping[str, object],
|
|
48
|
+
) -> HttpResponse | None:
|
|
49
|
+
"""Return a 403 problem response for an uncovered view under a protected prefix."""
|
|
50
|
+
settings = get_runtime().settings
|
|
51
|
+
if not is_protected_path(str(request.path_info), settings.protected_prefixes):
|
|
52
|
+
return None
|
|
53
|
+
if guard_of(view_func) is not None or is_exempt(view_func):
|
|
54
|
+
return None
|
|
55
|
+
error = AuthorizationError(
|
|
56
|
+
ReasonCode.POLICY_NOT_FOUND, "view under a protected prefix declares no policy"
|
|
57
|
+
)
|
|
58
|
+
return problem_response(error, debug=settings.debug_errors)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def is_protected_path(path: str, prefixes: Sequence[str]) -> bool:
|
|
62
|
+
"""Whether ``path`` starts with any protected prefix."""
|
|
63
|
+
return any(path.startswith(prefix) for prefix in prefixes)
|
pytrat/django/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pytrat-django
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Django integration for PyTraT Transaction Tokens.
|
|
5
|
+
Project-URL: Homepage, https://github.com/roshanlam/pytrat
|
|
6
|
+
Project-URL: Documentation, https://github.com/roshanlam/pytrat/tree/main/docs
|
|
7
|
+
Project-URL: Source, https://github.com/roshanlam/pytrat
|
|
8
|
+
Project-URL: Issues, https://github.com/roshanlam/pytrat/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/roshanlam/pytrat/blob/main/CHANGELOG.md
|
|
10
|
+
Author-email: Roshan Lamichhane <roshanlamichhanenepali@gmail.com>
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: ai-agents,authorization,jwt,microservices,oauth,transaction-tokens,txn-token,zero-trust
|
|
14
|
+
Classifier: Development Status :: 3 - Alpha
|
|
15
|
+
Classifier: Framework :: Django
|
|
16
|
+
Classifier: Framework :: Django :: 5.1
|
|
17
|
+
Classifier: Intended Audience :: Developers
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
24
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
25
|
+
Classifier: Topic :: Security
|
|
26
|
+
Classifier: Typing :: Typed
|
|
27
|
+
Requires-Python: >=3.12
|
|
28
|
+
Requires-Dist: django>=5.1
|
|
29
|
+
Requires-Dist: pytrat-client<0.2,>=0.1.0
|
|
30
|
+
Requires-Dist: pytrat-core<0.2,>=0.1.0
|
|
31
|
+
Requires-Dist: pytrat-policy<0.2,>=0.1.0
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
# pytrat-django
|
|
35
|
+
|
|
36
|
+
Django integration for PyTraT (OAuth Transaction Tokens): a
|
|
37
|
+
`@require_transaction` view decorator (sync and async views), fail-closed middleware for protected
|
|
38
|
+
path prefixes, and system checks.
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install pytrat-django
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Configure and decorate
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
# settings.py
|
|
48
|
+
INSTALLED_APPS = [..., "pytrat.django"]
|
|
49
|
+
MIDDLEWARE = [..., "pytrat.django.middleware.TransactionMiddleware"]
|
|
50
|
+
PYTRAT = {
|
|
51
|
+
"ENFORCER": "ledger.security.build_enforcer", # zero-arg factory -> TransactionEnforcer
|
|
52
|
+
"PROTECTED_PREFIXES": ["/internal/"],
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
# views.py
|
|
58
|
+
from pytrat.django import require_transaction
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@require_transaction(
|
|
62
|
+
scope="payments.transfer",
|
|
63
|
+
bind_fields=["source_account", "destination_account", "amount_minor", "currency"],
|
|
64
|
+
allowed_callers=["payment-service"],
|
|
65
|
+
)
|
|
66
|
+
def record_entry(request):
|
|
67
|
+
txn = request.transaction # verified; the token is bound for outbound calls
|
|
68
|
+
...
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Undecorated views under a protected prefix are denied before they run (`403 POLICY_NOT_FOUND`) and
|
|
72
|
+
reported by `manage.py check` (`pytrat.E001`). Unknown `PYTRAT` keys are rejected at startup.
|
|
73
|
+
|
|
74
|
+
## Documentation
|
|
75
|
+
|
|
76
|
+
PyTraT documentation: *Django* and the `pytrat.django` API reference (sources in `docs/` of the
|
|
77
|
+
repository).
|
|
78
|
+
|
|
79
|
+
Apache-2.0.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
pytrat/django/__init__.py,sha256=kZRan3_IKJVKf8YQSFCBiOqQDvCecLSDenJHFBrf-3A,1513
|
|
2
|
+
pytrat/django/_http.py,sha256=H7RgIatakWlsPlgAKMZyYaq1qO9kWd0DIbI1RHJNmGA,7984
|
|
3
|
+
pytrat/django/_runtime.py,sha256=yMqY9EGENWqyTTooDmXGO6p1c3JSo7HsTGZoPMY7Mrc,4613
|
|
4
|
+
pytrat/django/_settings.py,sha256=Ar6rinPmM1TQNbYecrvvcaET7FWlbT0ylTUNPaBoBZs,3784
|
|
5
|
+
pytrat/django/apps.py,sha256=RPp2Mb5hcr1ChlMkf9q1hliCtDQm8N42T6MNrbZ_ZuY,1213
|
|
6
|
+
pytrat/django/checks.py,sha256=jITxq4isSds5Z-NuXvvBxYkb2t8nJ6W0GJ_Rk9eThnw,3382
|
|
7
|
+
pytrat/django/decorators.py,sha256=UV2los-UUdF19Ji4D1N-wu2tHipgj-HZbn6p3n-4DPA,10137
|
|
8
|
+
pytrat/django/middleware.py,sha256=MklO0BXgqpkg5u7XlUMnjH6T6FETPh_xWqjzwSfQrKs,2551
|
|
9
|
+
pytrat/django/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
pytrat_django-0.1.0.dist-info/METADATA,sha256=Oin1xlE_BykSrQGNXodKLn2d6jKpU17p5IVOnDnIaSE,2722
|
|
11
|
+
pytrat_django-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
12
|
+
pytrat_django-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
13
|
+
pytrat_django-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|