beware 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.
beware/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from ._unsafe import Unsafe, unsafe, unsafe_context
2
+ from .sanitization import sanitizes, sanitize_context
3
+
4
+ __all__ = ["Unsafe", "sanitizes", "sanitize_context", "unsafe", "unsafe_context"]
@@ -0,0 +1,4 @@
1
+ from ._context import unsafe_context
2
+ from ._descriptor import unsafe, Unsafe, UnsafeReferenceException
3
+
4
+ __all__ = ["unsafe_context", "unsafe", "Unsafe", "UnsafeReferenceException"]
@@ -0,0 +1,48 @@
1
+ from collections.abc import Generator
2
+ from contextlib import contextmanager
3
+
4
+ from .._unsafe._context_vars import inside_unsafe_context
5
+ from .._unsafe._descriptor import Unsafe
6
+
7
+
8
+ @contextmanager
9
+ def unsafe_context(*attrs: Unsafe) -> Generator[None, None, None]:
10
+ """Enable the unsafe access of the specified attributes inside the context.
11
+
12
+ Parameters
13
+ ----------
14
+ attrs : tuple[Unsafe, ...]
15
+ arguments that can be acessed without raising UnsafeReadException,
16
+
17
+
18
+ Raises
19
+ ------
20
+ TypeError
21
+ If the given attrs are not Unsafe descriptors
22
+
23
+
24
+ Examples
25
+ --------
26
+ >>> class MyClass:
27
+ ... a = unsafe()
28
+ >>> obj = MyClass()
29
+ >>> with unsafe_context(MyClass.a):
30
+ ... print(instance.a) # won't raise an exception, even if it is not sanitized
31
+ """
32
+
33
+ for attr in attrs:
34
+ if not isinstance(attr, Unsafe):
35
+ raise TypeError(
36
+ f"Invalid argument with type {type(attr)} expected Unsafe type"
37
+ )
38
+
39
+ token = inside_unsafe_context.set(True)
40
+ try:
41
+ for attr in attrs:
42
+ attr._read_by_context = True
43
+
44
+ yield
45
+ finally:
46
+ inside_unsafe_context.reset(token)
47
+ for attr in attrs:
48
+ attr._read_by_context = False
@@ -0,0 +1,5 @@
1
+ from contextvars import ContextVar
2
+
3
+ inside_unsafe_context: ContextVar[bool] = ContextVar(
4
+ "inside_unsafe_context", default=False
5
+ )
@@ -0,0 +1,114 @@
1
+ """
2
+ This module contains the Unsafe descriptor class and the factory function for returning
3
+ descriptor instances
4
+ """
5
+
6
+ from typing import Any, overload
7
+
8
+ from beware._unsafe._context_vars import inside_unsafe_context
9
+ from beware.exceptions import NameAssignmentException, UnsafeReferenceException
10
+
11
+ # sentinel value to check if the default was provided
12
+ _MISSING_DEFAULT = object()
13
+
14
+
15
+ class Unsafe:
16
+ """Descriptor class used to control unsafe variables access"""
17
+
18
+ __slots__: tuple[str, ...] = (
19
+ "_read_by_context",
20
+ "_default",
21
+ "_sanitize_on_assignment",
22
+ "_sanitize_flag", # pyright: ignore[reportUninitializedInstanceVariable]
23
+ "_owner", # pyright: ignore[reportUninitializedInstanceVariable]
24
+ "_private_name", # pyright: ignore[reportUninitializedInstanceVariable]
25
+ "_public_name", # pyright: ignore[reportUninitializedInstanceVariable]
26
+ )
27
+
28
+ def __init__(self, default: Any | None = _MISSING_DEFAULT) -> None:
29
+
30
+ self._read_by_context: bool = False
31
+ """
32
+ Determine if the attribute read should check the inside_unsafe_context ContextVar
33
+ """
34
+
35
+ self._sanitize_on_assignment: bool = False
36
+ """
37
+ When it is True, calling __set__ will make the variable sanitized
38
+ """
39
+
40
+ self._default: Any | None = default
41
+ """
42
+ Default values are used when the related object have not modified the
43
+ corresponding attribute of the descriptor field
44
+ """
45
+
46
+ def __set_name__(self, owner: type[object], name: str):
47
+ if getattr(self, "_owner", None):
48
+ raise NameAssignmentException(
49
+ f"Descriptor already binded to '{self._public_name}' attribute in {self._owner}"
50
+ )
51
+
52
+ self._owner: type[object] = owner
53
+ self._public_name: str = name
54
+ self._private_name: str = f"_{name}_beware"
55
+ self._sanitize_flag: str = f"{self._private_name}_sanitized"
56
+
57
+ @overload
58
+ def __get__(self, obj: None, objtype: None) -> "Unsafe": ...
59
+
60
+ @overload
61
+ def __get__(self, obj: object, objtype: type[object]) -> Any: ...
62
+
63
+ def __get__(self, obj: Any, objtype: type[object] | None = None) -> "Unsafe|Any":
64
+ if obj is None:
65
+ return self
66
+
67
+ read_allowed = inside_unsafe_context.get() if self._read_by_context else False
68
+
69
+ # if the descriptor has a default value and it was not overriden, it should be
70
+ # returned.
71
+ # If not, the descriptor field tries to resolve the instance attribute
72
+
73
+ # default values don't need sanitization
74
+ val = getattr(obj, self._private_name, self._default)
75
+
76
+ if val is _MISSING_DEFAULT:
77
+ raise AttributeError(
78
+ f" '{type(obj).__name__}' object has no attribute {self._public_name}"
79
+ )
80
+ elif self._default == val:
81
+ return self._default
82
+ else:
83
+ if getattr(obj, self._sanitize_flag, False) or read_allowed:
84
+ return val
85
+ else:
86
+ raise UnsafeReferenceException
87
+
88
+ def __set__(self, obj: object, value: Any) -> None:
89
+ setattr(obj, self._private_name, value)
90
+ if self._sanitize_on_assignment:
91
+ setattr(obj, self._sanitize_flag, True)
92
+
93
+ def __delete__(self, instance: object):
94
+ try:
95
+ delattr(instance, self._private_name)
96
+ delattr(instance, self._sanitize_flag)
97
+ except AttributeError:
98
+ pass
99
+
100
+
101
+ def unsafe(default: Any | None = _MISSING_DEFAULT) -> Any:
102
+ """Factory function for Unsafe descriptors
103
+
104
+ Parameters
105
+ -----
106
+ default: Any
107
+ The default value of the field, can be accessed in any context
108
+
109
+ Warnings
110
+ -----
111
+ Default values can be accessed normally
112
+ """
113
+
114
+ return Unsafe(default=default)
@@ -0,0 +1,6 @@
1
+ class UnsafeReferenceException(Exception):
2
+ """Raised when an attribute is referenced without being sanitized first"""
3
+
4
+
5
+ class NameAssignmentException(AttributeError):
6
+ """Raised when a descriptor instance is assigned to two different attributes on one or more classes"""
@@ -0,0 +1,4 @@
1
+ from ._context import sanitize_context
2
+ from ._decorator import sanitizes
3
+
4
+ __all__ = ["sanitize_context", "sanitizes"]
@@ -0,0 +1,36 @@
1
+ from contextlib import contextmanager
2
+ from typing import Any
3
+
4
+ from beware._unsafe import unsafe_context
5
+
6
+
7
+ @contextmanager
8
+ def sanitize_context(*attrs: Any):
9
+ """Context manager for marking the specified attributes as sanitized after assignment
10
+
11
+ Parameters
12
+ ----------
13
+ attrs : tuple[Unsafe, ...]
14
+ arguments that are sanitized after an assignment
15
+
16
+ Examples
17
+ --------
18
+ >>> class MyClass:
19
+ ... a = unsafe()
20
+ >>> obj = MyClass()
21
+ >>> with sanitize_context(MyClass.a):
22
+ ... instance.a = "sanitized"
23
+ >>> instance.a # can be accessed outside an unsafe_context
24
+ "sanitized"
25
+ """
26
+
27
+ with unsafe_context(*attrs):
28
+ try:
29
+ for attr in attrs:
30
+ attr._sanitize_on_assignment = True
31
+
32
+ yield
33
+
34
+ finally:
35
+ for attr in attrs:
36
+ attr._sanitize_on_assignment = False
@@ -0,0 +1,84 @@
1
+ import inspect
2
+ from functools import wraps
3
+ from typing import Callable, ParamSpec, TypeVar, cast
4
+
5
+ from beware._unsafe import Unsafe
6
+ from ._context import sanitize_context
7
+
8
+ P = ParamSpec("P")
9
+ R = TypeVar("R")
10
+
11
+
12
+ def sanitizes(
13
+ *attrs: Unsafe,
14
+ ) -> Callable[[Callable[P, R]], Callable[P, R]]:
15
+ """Decorator factory that marks all given attrs as safe after the function executes without
16
+ exceptions.
17
+
18
+ Parameters
19
+ ----------
20
+ attrs : tuple[Unsafe, ...]
21
+ arguments that are sanitized on attribution,
22
+
23
+
24
+ Returns
25
+ -------
26
+ A decorated function that will sanitize all given unsafe attributes when modified
27
+ inside the function
28
+
29
+
30
+ Examples
31
+ --------
32
+ >>> class MyClass:
33
+ ... a = unsafe()
34
+ ...
35
+ >>> @sanitizes(MyClass.a)
36
+ ... def sanitize_a(instance:MyClass):
37
+ ... instance.a = "sanitized"
38
+ ...
39
+ >>> obj = MyClass()
40
+ >>> sanitize_a(MyClass.a):
41
+ ... instance.a = "sanitized"
42
+ ...
43
+ >>> sanitize_a(obj)
44
+ >>> obj.a # can be accessed outside of an unsafe context
45
+ "sanitized"
46
+ """
47
+
48
+ def decorator(func: Callable[P, R]) -> Callable[P, R]:
49
+
50
+ # mypy can't resolve the return type correctly when using functool.wraps, thus the casts
51
+ # Full thread: https://stackoverflow.com/questions/78807798/mypy-1-10-reports-error-when-functools-wraps-is-used-on-a-generic-function
52
+
53
+ if inspect.iscoroutinefunction(func):
54
+
55
+ @wraps(func)
56
+ async def a_inner_function(*args: P.args, **kwargs: P.kwargs):
57
+ try:
58
+ with sanitize_context(*attrs):
59
+ result = await func(*args, **kwargs)
60
+
61
+ return result
62
+ except:
63
+ raise
64
+
65
+ return cast(Callable[P, R], a_inner_function)
66
+
67
+ elif callable(func):
68
+
69
+ @wraps(func)
70
+ def inner_function(*args: P.args, **kwargs: P.kwargs):
71
+ try:
72
+ with sanitize_context(*attrs):
73
+ result = func(*args, **kwargs)
74
+
75
+ return result
76
+ except:
77
+ raise
78
+
79
+ return cast(Callable[P, R], inner_function)
80
+
81
+ else:
82
+ raise TypeError # pyright: ignore[reportUnreachable]
83
+
84
+ return decorator
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: beware
3
+ Version: 0.1.0
4
+ Summary: A pure python package with zero dependencies that provides functions to track the usage of unsafe attributes on the code and perform sanitization.
5
+ License: LGPLv3+
6
+ License-File: LICENSE
7
+ Keywords: sanitization,security
8
+ Author: João Pedro
9
+ Author-email: joaopedroph.dev@gmail.com
10
+ Requires-Python: >=3.10
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Programming Language :: Python :: Implementation :: CPython
17
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
18
+ Project-URL: Repository, https://github.com/Joao-Pedro-P-Holanda/beware
19
+ Description-Content-Type: text/markdown
20
+
21
+ # Beware
22
+ ![PyPI Version](https://img.shields.io/pypi/v/beware)
23
+ ![PyPI Python Versions](https://img.shields.io/pypi/pyversions/beware)
24
+
25
+ Beware is a pure python package with zero dependencies that provides functions to track the usage of
26
+ unsafe attributes on the code and perform sanitization.
27
+
28
+ ## Features
29
+
30
+ - Define attributes that need to be sanitized with Python descriptors
31
+ - Declare functions or blocks of code to perform sanitization
32
+
33
+
34
+ ## Alternatives
35
+
36
+ - [ItsDangerous](https://itsdangerous.palletsprojects.com/en/stable/): use it if you need to transmit data through an unsafe medium and guarantee that it is not tampered
37
+
38
+ ## Roadmap
39
+
40
+ - [ ] Publish code documentation
41
+ - [ ] Add doctests for docstrings
42
+ - [ ] Define a pytest plugin to allow easier checks of unsafe access without modifying the source code
43
+
44
+
@@ -0,0 +1,13 @@
1
+ beware/__init__.py,sha256=euD8BndOHbzK5RFlNa1AMly3_KwiVRMuHn1oYwLA5ic,189
2
+ beware/_unsafe/__init__.py,sha256=NIfBgldgRi4kZuPiL46njTK9hje47jSspHvKdc0cMA4,181
3
+ beware/_unsafe/_context.py,sha256=Wlr4qW0-YPiLES9R6ivFUQhG9MZ3gmMyhML72NpeGmE,1258
4
+ beware/_unsafe/_context_vars.py,sha256=zYD5tXB-qFXrRGcDDzBUX8nw-PXhs5oeIEq1MalTKZI,135
5
+ beware/_unsafe/_descriptor.py,sha256=WshXoaZA2Pmt4Pp0w3OHuN6FNyZ5S8vr1AqDeNKImHg,3798
6
+ beware/exceptions/__init__.py,sha256=NR40c8JOOqZkUVkJomzcVOLYAP6RsWWmF2jDhovd4to,278
7
+ beware/sanitization/__init__.py,sha256=VuRdktzHoldEwQxiDISsHcesznI0hWCITDuFEWNUqlo,118
8
+ beware/sanitization/_context.py,sha256=q5dg77hAbWCDO5KP0NO0l819NjeQ9LKqPoWlRLnbdSE,886
9
+ beware/sanitization/_decorator.py,sha256=bQ_3J_1kAzybcES9r_ZoOcf3hNsdGMBodHEHEq8mH78,2300
10
+ beware-0.1.0.dist-info/METADATA,sha256=LM1-lwJQtDLov91sz-bonG1ka6CCqIa1hFfxP_-1dhs,1682
11
+ beware-0.1.0.dist-info/WHEEL,sha256=EGEvSphFYqXKs23-kQBeyNoJP1nrT8ZJKQoi5p5DYL8,88
12
+ beware-0.1.0.dist-info/licenses/LICENSE,sha256=46mU2C5kSwOnkqkw9XQAJlhBL2JAf1_uCD8lVcXyMRg,7652
13
+ beware-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.4.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.