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
|
# SPDX-License-Identifier: GPL-3.0-or-later
# Policies for resolving HTTP requests with local resources.
#
# This file is part of Hydrilla&Haketilo.
#
# Copyright (C) 2022 Wojtek Kosior
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
#
# I, Wojtek Kosior, thereby promise not to sue for violation of this
# file's license. Although I request that you do not make use this code
# in a proprietary program, I am not going to enforce this in court.
"""
.....
We make file resources available to HTTP clients by mapping them
at:
http(s)://<pattern-matching_origin>/<pattern_path>/<token>/
where <token> is a per-session secret unique for every mapping.
For example, a payload with pattern like the following:
http*://***.example.com/a/b/**
Could cause resources to be mapped (among others) at each of:
https://example.com/a/b/**/Da2uiF2UGfg/
https://www.example.com/a/b/**/Da2uiF2UGfg/
http://gnome.vs.kde.example.com/a/b/**/Da2uiF2UGfg/
Unauthorized web pages running in the user's browser are exected to be
unable to guess the secret. This way we stop them from spying on the
user and from interfering with Haketilo's normal operation.
This is only a soft prevention method. With some mechanisms
(e.g. service workers), under certain scenarios, it might be possible
to bypass it. Thus, to make the risk slightly smaller, we also block
the unauthorized accesses that we can detect.
Since a web page authorized to access the resources may only be served
when the corresponding mapping is enabled (or AUTO mode is on), we
consider accesses to non-enabled mappings' resources a security breach
and block them by responding with 403 Not Found.
"""
# Enable using with Python 3.7.
from __future__ import annotations
import dataclasses as dc
import typing as t
from ...translations import smart_gettext as _
from .. import state
from . import base
from .payload import PayloadAwarePolicy, PayloadAwarePolicyFactory
@dc.dataclass(frozen=True)
class PayloadResourcePolicy(PayloadAwarePolicy):
"""...."""
process_request: t.ClassVar[bool] = True
priority: t.ClassVar[base.PolicyPriority] = base.PolicyPriority._THREE
def _make_file_resource_response(self, path: tuple[str, ...]) \
-> base.ProducedResponse:
"""...."""
try:
file_data = self.payload_data.payload_ref.get_file_data(
self.haketilo_state,
path
)
except state.MissingItemError:
return resource_blocked_response
if file_data is None:
return base.ProducedResponse(
404,
[(b'Content-Type', b'text/plain; charset=utf-8')],
_('api.file_not_found').encode()
)
return base.ProducedResponse(
200,
((b'Content-Type', file_data.type.encode()),),
file_data.contents
)
def consume_request(self, request_info: base.RequestInfo) \
-> base.ProducedResponse:
"""...."""
# Payload resource pattern has path of the form:
# "/some/arbitrary/segments/<per-session_token>/***"
#
# Corresponding requests shall have path of the form:
# "/some/arbitrary/segments/<per-session_token>/actual/resource/path"
#
# Here we need to extract the "/actual/resource/path" part.
segments_to_drop = len(self.payload_data.pattern.path_segments) + 1
resource_path = request_info.url.path_segments[segments_to_drop:]
if resource_path == ():
return resource_blocked_response
elif resource_path[0] == 'static':
return self._make_file_resource_response(resource_path[1:])
elif resource_path[0] == 'api':
# TODO: implement Haketilo APIs
return resource_blocked_response
else:
return resource_blocked_response
resource_blocked_response = base.ProducedResponse(
403,
[(b'Content-Type', b'text/plain; charset=utf-8')],
_('api.resource_not_enabled_for_access').encode()
)
@dc.dataclass(frozen=True)
class BlockedResponsePolicy(base.Policy):
"""...."""
process_request: t.ClassVar[bool] = True
priority: t.ClassVar[base.PolicyPriority] = base.PolicyPriority._THREE
def consume_request(self, request_info: base.RequestInfo) \
-> base.ProducedResponse:
"""...."""
return resource_blocked_response
@dc.dataclass(frozen=True, unsafe_hash=True) # type: ignore[misc]
class PayloadResourcePolicyFactory(PayloadAwarePolicyFactory):
"""...."""
def make_policy(self, haketilo_state: state.HaketiloState) \
-> t.Union[PayloadResourcePolicy, BlockedResponsePolicy]:
"""...."""
try:
payload_data = self.payload_ref.get_data(haketilo_state)
except state.MissingItemError:
return BlockedResponsePolicy()
if not payload_data.explicitly_enabled and \
haketilo_state.get_settings().mapping_use_mode != \
state.MappingUseMode.AUTO:
return BlockedResponsePolicy()
return PayloadResourcePolicy(haketilo_state, payload_data)
|