base-api-utils 1.1.123__tar.gz → 1.1.124__tar.gz
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.
- {base_api_utils-1.1.123/src/base_api_utils.egg-info → base_api_utils-1.1.124}/PKG-INFO +1 -1
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/pyproject.toml +1 -1
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/__init__.py +7 -1
- base_api_utils-1.1.124/src/base_api_utils/utils/log_redaction.py +275 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124/src/base_api_utils.egg-info}/PKG-INFO +1 -1
- base_api_utils-1.1.124/tests/test_log_redaction.py +691 -0
- base_api_utils-1.1.123/src/base_api_utils/utils/log_redaction.py +0 -112
- base_api_utils-1.1.123/tests/test_log_redaction.py +0 -269
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/LICENSE +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/README.md +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/setup.cfg +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/commands/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/commands/failed_task_management_mixin.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/domain/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/domain/event_message.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/domain/event_message_factory.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/domain/events.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/domain/exceptions.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/dtos/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/dtos/authz_user.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/fields/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/fields/email_list_field.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/filters/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/filters/base_filter.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/filters/custom_ordering_filter.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/filters/filter_utils_mixin.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/handlers/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/handlers/base_event_handler.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/handlers/sponsor_event_handler.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/handlers/sponsorship_addon_event_handler.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/handlers/sponsorship_event_handler.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/handlers/summit_event_handler.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/ioc/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/ioc/container.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/models/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/models/item_image.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/security/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/security/abstract_access_token_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/security/abstract_oauth2_api_client.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/security/access_token_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/security/check_sponsor_user_permissions.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/security/group_required.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/security/oauth2_authentication.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/security/oauth2_client_factory.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/security/oauth2_scope_required.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/security/permission_event_handler.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/security/shared.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/security/user_permissions_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/base_model_serializer.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/email_list_char_field.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/nullable_slug_related_field.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/serializers_registry.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/task_result_serializer.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/timestamp_field.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/v2/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/v2/abstract_serializer.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/v2/base_model_serializer.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/v2/expands.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/v2/query_params.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/serializers/v2/spectacular.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/abstract_domain_events_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/abstract_event_dispatcher.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/abstract_images_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/abstract_sponsor_metadata_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/abstract_storage_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/abstract_summit_metadata_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/amqp_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/celery_failed.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/event_dispatcher.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/images_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/s3_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/strategies/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/strategies/abstract_task_runner_strategy.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/services/strategies/publish_domain_event_strategy.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/tests/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/tests/test_failed_celery_task_management.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/tests/test_task_status_endpoints.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/urls.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/admin_groups.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/async_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/circuit_breaker.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/config.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/custom_auto_schema.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/db_connection_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/debounce_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/enums.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/env_var_eval.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/exceptions.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/expand_queryset_optimization_mixin.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/external_errors.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/file_lock.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/fingerprint_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/http_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/inject_job.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/look_up_value_mixin.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/model_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/oauth2_custom_schema_base.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/pagination.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/rate_utils.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/read_write_serializer_mixin.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/serializers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/service_utils.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/string.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/utils/tests.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/views/__init__.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/views/base_view.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/views/parent_children_crud.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/views/root_entity_crud.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils/views/tasks_result_view.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils.egg-info/SOURCES.txt +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils.egg-info/dependency_links.txt +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils.egg-info/requires.txt +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/src/base_api_utils.egg-info/top_level.txt +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/tests/test_amqp_service.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/tests/test_check_sponsor_user_permissions.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/tests/test_circuit_breaker.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/tests/test_db_connection_helpers.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/tests/test_file_lock.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/tests/test_is_admin.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/tests/test_lazy_imports.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/tests/test_oauth2_scope_required.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/tests/test_retryable_event_propagation.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/tests/test_timestamp_field.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/tests/test_token_logging.py +0 -0
- {base_api_utils-1.1.123 → base_api_utils-1.1.124}/tests/test_v2_abstract_serializer.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: base-api-utils
|
|
3
|
-
Version: 1.1.
|
|
3
|
+
Version: 1.1.124
|
|
4
4
|
Summary: Django Rest Framework micro services common utilities
|
|
5
5
|
Author-email: Román Gutierrez <roman@tipit.net>, Sebastian Marcet <sebastian@tipit.net>
|
|
6
6
|
Project-URL: Homepage, https://github.com/fntechgit/base-api-utils
|
|
@@ -19,7 +19,13 @@ from .fingerprint_helpers import (
|
|
|
19
19
|
)
|
|
20
20
|
from .http_helpers import raise_for_auth_errors, raise_for_external_catch, raise_for_status_codes
|
|
21
21
|
from .inject_job import inject_job
|
|
22
|
-
from .log_redaction import
|
|
22
|
+
from .log_redaction import (
|
|
23
|
+
RedactingHandlerMixin,
|
|
24
|
+
describe_token_info,
|
|
25
|
+
redact_log_record,
|
|
26
|
+
redact_secrets,
|
|
27
|
+
token_fingerprint,
|
|
28
|
+
)
|
|
23
29
|
from .look_up_value_mixin import LookupValueMixin
|
|
24
30
|
from .model_helpers import get_or_not_found
|
|
25
31
|
from .pagination import LargeResultsSetPagination
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""Keep credentials out of log lines.
|
|
2
|
+
|
|
3
|
+
A log line may say which token a request carried, never the token itself: logs are read by
|
|
4
|
+
more people, and kept for longer, than a token is valid.
|
|
5
|
+
|
|
6
|
+
- ``token_fingerprint`` names a token so its lines can be told apart from another token's.
|
|
7
|
+
- ``describe_token_info`` says who a token belongs to, from an allow-list of fields.
|
|
8
|
+
- ``redact_secrets`` removes credentials from text built elsewhere, such as the message of a
|
|
9
|
+
``requests`` exception, which contains the URL and with it ``?access_token=``.
|
|
10
|
+
- ``redact_log_record`` and ``RedactingHandlerMixin`` apply ``redact_secrets`` to a whole log
|
|
11
|
+
record on its way to a handler that ships it off the process (the OTLP exporter), whoever
|
|
12
|
+
wrote the line: Django, urllib3 and requests_oauthlib log URLs and requests too.
|
|
13
|
+
|
|
14
|
+
``redact_secrets`` knows the shapes listed below and nothing else: of a credential that stands
|
|
15
|
+
alone in a sentence it finds only a long value after the word "token". Where the value is known,
|
|
16
|
+
log its fingerprint instead of passing the text through it. When in doubt it redacts: a hidden
|
|
17
|
+
word is the cheaper mistake.
|
|
18
|
+
"""
|
|
19
|
+
import copy
|
|
20
|
+
import hashlib
|
|
21
|
+
import logging
|
|
22
|
+
import re
|
|
23
|
+
|
|
24
|
+
REDACTED = '[REDACTED]'
|
|
25
|
+
|
|
26
|
+
_FINGERPRINT_LENGTH = 12
|
|
27
|
+
|
|
28
|
+
# A name is a credential's when it holds one of these words: access_token, client_secret,
|
|
29
|
+
# service_token, accessToken, api_key. The name is a whole word, taken in one piece: the second
|
|
30
|
+
# lookahead captures it and the back-reference repeats it, so a match that fails after the name
|
|
31
|
+
# does not try the name again one character shorter. On a long text that kept the time linear.
|
|
32
|
+
_CREDENTIAL_WORDS = r'(?:token|secret|password|passwd|api[_-]?key)'
|
|
33
|
+
_NAME = (rf'(?<![\w-])(?=[\w-]*?{_CREDENTIAL_WORDS})'
|
|
34
|
+
r'(?=(?P<word>[\w-]+))(?P=word)')
|
|
35
|
+
|
|
36
|
+
# name=value, name: value, "name": "value", 'name': b'value'. A quoted value ends at the quote
|
|
37
|
+
# it began with, whatever it holds; backslashes before a quote are JSON inside a JSON string.
|
|
38
|
+
# A value with no quotes ends at a space or at the next query-string parameter.
|
|
39
|
+
# Inside the quotes a backslash is read one way only, as the start of an escape: with two ways
|
|
40
|
+
# to read it, a quote that never closes made the pattern try every split of a run of backslashes.
|
|
41
|
+
# A quote that never closes takes the rest of its line. Giving up there and taking the first
|
|
42
|
+
# word instead left the rest of the value in the text, and read the line again, to its end, from
|
|
43
|
+
# every name on it: a request path of token=\'& repeated made one log call take seconds.
|
|
44
|
+
# A fingerprint is not a credential: token=sha256:2e6a931d428f, as describe_token_info writes it,
|
|
45
|
+
# is left as it is. Only when the fingerprint is the whole value: a value that begins like one
|
|
46
|
+
# and goes on is redacted.
|
|
47
|
+
_FINGERPRINT = rf'sha256:[0-9a-f]{{{_FINGERPRINT_LENGTH}}}'
|
|
48
|
+
_FINGERPRINT_VALUE = rf'''["']?{_FINGERPRINT}(?=[\s&,;"')}}\]]|$)'''
|
|
49
|
+
_ASSIGNMENT_RE = re.compile(
|
|
50
|
+
rf'''(?i)(?P<name>{_NAME})(?P<separator>\\*["']?\s*[=:]\s*)(?![=:])(?!{_FINGERPRINT_VALUE})'''
|
|
51
|
+
r'''(?:(?P<open>b?\\*(?P<quote>["']))(?:\\.|(?!(?P=quote))[^\\\n])*(?:(?P<close>(?P=quote))|[^\n]*)'''
|
|
52
|
+
r'''|[^\s&]+)'''
|
|
53
|
+
)
|
|
54
|
+
# name%3Dvalue: a URL carried inside another URL's parameter.
|
|
55
|
+
_ENCODED_ASSIGNMENT_RE = re.compile(rf'(?i)(?P<name>{_NAME})%3D(?:(?!%26)[^&\s])+')
|
|
56
|
+
# Authorization, as a header or a dict entry, up to its value. The spaces after the separator are
|
|
57
|
+
# read once: the second run belongs to an opening quote and is tried only when there is one.
|
|
58
|
+
# Two runs side by side made a long gap take quadratic time.
|
|
59
|
+
_AUTHORIZATION = r'''authorization\\*["']?\s*[:=]\s*(?:\\*["']\s*)?'''
|
|
60
|
+
# Authorization: Digest username="...", response="...": every parameter, to the end of the line.
|
|
61
|
+
_DIGEST_RE = re.compile(rf'(?i)\b({_AUTHORIZATION}digest\s+)[^\r\n]+')
|
|
62
|
+
# Authorization: Bearer <token>, Authorization: Basic <base64 of id:secret>.
|
|
63
|
+
_AUTHORIZATION_RE = re.compile(
|
|
64
|
+
rf'(?i)\b({_AUTHORIZATION}(?:(?:bearer|basic|negotiate|token)\s+)?)'
|
|
65
|
+
r'''(?!digest\s)[^\s"',;&]+'''
|
|
66
|
+
)
|
|
67
|
+
# Bearer <token> on its own. The length keeps "bearer header" in a sentence as it is.
|
|
68
|
+
_BEARER_RE = re.compile(r'(?i)\b(bearer\s+)[A-Za-z0-9\-._~+/]{12,}=*')
|
|
69
|
+
# "Access token <token> is expired!": a token named in a sentence, as OpenStackID writes it.
|
|
70
|
+
# The length keeps "token revoked" and a fingerprint (sha256:...) as they are.
|
|
71
|
+
_TOKEN_IN_A_SENTENCE_RE = re.compile(r'(?i)\b(token\s+)[A-Za-z0-9\-._~+/]{20,}=*')
|
|
72
|
+
# scheme://user:password@host. The user may be empty (redis://:password@host), and the password
|
|
73
|
+
# runs to the last @ before the path, because it may hold one.
|
|
74
|
+
_URL_PASSWORD_RE = re.compile(r'(?i)\b([a-z][a-z0-9+.-]{1,20}://[^/\s:@?#]*:)[^\s/?#]*(?=@)')
|
|
75
|
+
|
|
76
|
+
# The fields of a token_info that say who is calling. Anything else, the token and the user's
|
|
77
|
+
# name and email included, is left out.
|
|
78
|
+
_TOKEN_INFO_FIELDS = ('client_id', 'application_type', 'user_id', 'error_code')
|
|
79
|
+
# An OAuth2 error code (invalid_token, invalid_grant). Free text is not one.
|
|
80
|
+
_ERROR_CODE_RE = re.compile(r'[a-z_]{1,40}')
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def token_fingerprint(token) -> str:
|
|
84
|
+
"""A short name for ``token`` that cannot be turned back into it.
|
|
85
|
+
|
|
86
|
+
The first hex characters of its SHA-256, so every line about one token carries the same
|
|
87
|
+
value and lines about another token carry a different one.
|
|
88
|
+
"""
|
|
89
|
+
if not token:
|
|
90
|
+
return 'none'
|
|
91
|
+
raw = token if isinstance(token, bytes) else str(token).encode('utf-8')
|
|
92
|
+
return f'sha256:{hashlib.sha256(raw).hexdigest()[:_FINGERPRINT_LENGTH]}'
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _redact_assignment(match) -> str:
|
|
96
|
+
if match.group('quote'):
|
|
97
|
+
close = match.group('close') or ''
|
|
98
|
+
return f"{match.group('name')}{match.group('separator')}{match.group('open')}{REDACTED}{close}"
|
|
99
|
+
return f"{match.group('name')}{match.group('separator')}{REDACTED}"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def redact_secrets(value) -> str:
|
|
103
|
+
"""``str(value)`` with the credentials it can recognise replaced. Text with none is unchanged."""
|
|
104
|
+
text = str(value)
|
|
105
|
+
text = _DIGEST_RE.sub(lambda match: f'{match.group(1)}{REDACTED}', text)
|
|
106
|
+
text = _AUTHORIZATION_RE.sub(lambda match: f'{match.group(1)}{REDACTED}', text)
|
|
107
|
+
text = _ASSIGNMENT_RE.sub(_redact_assignment, text)
|
|
108
|
+
text = _ENCODED_ASSIGNMENT_RE.sub(lambda match: f"{match.group('name')}%3D{REDACTED}", text)
|
|
109
|
+
text = _BEARER_RE.sub(lambda match: f'{match.group(1)}{REDACTED}', text)
|
|
110
|
+
text = _TOKEN_IN_A_SENTENCE_RE.sub(lambda match: f'{match.group(1)}{REDACTED}', text)
|
|
111
|
+
return _URL_PASSWORD_RE.sub(lambda match: f'{match.group(1)}{REDACTED}', text)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def describe_token_info(token_info) -> str:
|
|
115
|
+
"""What may be logged about a token_info: who is calling and the token's fingerprint.
|
|
116
|
+
|
|
117
|
+
For a refusal, its status and its error code. The IDP's description of a refusal is never
|
|
118
|
+
logged: OpenStackID writes the refused token into it.
|
|
119
|
+
"""
|
|
120
|
+
if not isinstance(token_info, dict):
|
|
121
|
+
return 'None' if token_info is None else f'<{type(token_info).__name__}>'
|
|
122
|
+
described = {name: token_info[name] for name in _TOKEN_INFO_FIELDS if name in token_info}
|
|
123
|
+
error = token_info.get('error')
|
|
124
|
+
if error:
|
|
125
|
+
described['error'] = error if isinstance(error, str) and _ERROR_CODE_RE.fullmatch(error) else REDACTED
|
|
126
|
+
if 'access_token' in token_info:
|
|
127
|
+
described['token'] = token_fingerprint(token_info['access_token'])
|
|
128
|
+
return ', '.join(f'{name}={value}' for name, value in described.items())
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# The attributes every LogRecord has. Any other attribute of a record was passed as ``extra`` or
|
|
132
|
+
# added by a record factory. A plain LogRecord is asked and not logging.makeLogRecord, which goes
|
|
133
|
+
# through the factory in place when this module is imported: what that factory adds would count
|
|
134
|
+
# as an attribute every record has, and would never be redacted.
|
|
135
|
+
_RECORD_ATTRIBUTES = frozenset(vars(logging.LogRecord('', 0, '', 0, '', (), None))) | {'message', 'asctime'}
|
|
136
|
+
_KEPT_AS_THEY_ARE = (bool, int, float, type(None))
|
|
137
|
+
# An exception chain is followed this far. A longer one is cut there, not read to its end.
|
|
138
|
+
_MAX_CHAIN_LINKS = 100
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _text(value, unprintable=None) -> str:
|
|
142
|
+
"""``str(value)``, or a note in its place when the value's own ``__str__`` raises.
|
|
143
|
+
|
|
144
|
+
Such a value costs its own text and not the record: the message and the stacktrace next to
|
|
145
|
+
it are still exported.
|
|
146
|
+
"""
|
|
147
|
+
try:
|
|
148
|
+
return str(value)
|
|
149
|
+
except Exception:
|
|
150
|
+
return unprintable or f'<{type(value).__name__}: str() failed>'
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# An ``extra`` with one of these in its name holds a credential, whatever its value looks like:
|
|
154
|
+
# the words that make a name a credential's in a text, and the Authorization header.
|
|
155
|
+
_CREDENTIAL_EXTRA_RE = re.compile(rf'(?i){_CREDENTIAL_WORDS}|authorization')
|
|
156
|
+
_FINGERPRINT_RE = re.compile(_FINGERPRINT)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _redact_extra(name, value):
|
|
160
|
+
if isinstance(value, _KEPT_AS_THEY_ARE):
|
|
161
|
+
return value
|
|
162
|
+
if _CREDENTIAL_EXTRA_RE.search(name):
|
|
163
|
+
# The name is what says it is a credential: a token on its own has no shape to find.
|
|
164
|
+
return value if isinstance(value, str) and _FINGERPRINT_RE.fullmatch(value) else REDACTED
|
|
165
|
+
if isinstance(value, (list, tuple)) and all(isinstance(item, (str, *_KEPT_AS_THEY_ARE)) for item in value):
|
|
166
|
+
# A plain tuple or list, never the value's own class: a named tuple takes one argument
|
|
167
|
+
# per field, and other subclasses are built from more than their items.
|
|
168
|
+
plain = tuple if isinstance(value, tuple) else list
|
|
169
|
+
return plain(item if isinstance(item, _KEPT_AS_THEY_ARE) else redact_secrets(_text(item)) for item in value)
|
|
170
|
+
return redact_secrets(_text(value))
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _redacted_exception(exc, seen):
|
|
174
|
+
"""A stand-in for ``exc``: same type name, traceback and chain, every message redacted.
|
|
175
|
+
|
|
176
|
+
The chain is followed for ``_MAX_CHAIN_LINKS`` exceptions and cut there.
|
|
177
|
+
"""
|
|
178
|
+
if exc is None or id(exc) in seen or len(seen) >= _MAX_CHAIN_LINKS:
|
|
179
|
+
return None
|
|
180
|
+
seen.add(id(exc))
|
|
181
|
+
exc_class = type(exc)
|
|
182
|
+
stand_in_class = type(exc_class.__name__, (Exception,),
|
|
183
|
+
{'__module__': exc_class.__module__, '__qualname__': exc_class.__qualname__})
|
|
184
|
+
stand_in = stand_in_class(redact_secrets(_text(exc, '<exception str() failed>')))
|
|
185
|
+
stand_in.__traceback__ = exc.__traceback__
|
|
186
|
+
stand_in.__cause__ = _redacted_exception(exc.__cause__, seen)
|
|
187
|
+
stand_in.__context__ = _redacted_exception(exc.__context__, seen)
|
|
188
|
+
stand_in.__suppress_context__ = exc.__suppress_context__
|
|
189
|
+
return stand_in
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def redact_log_record(record: logging.LogRecord) -> logging.LogRecord:
|
|
193
|
+
"""A copy of ``record`` with the credentials removed from everything a handler can export.
|
|
194
|
+
|
|
195
|
+
The message is rendered with its arguments and redacted. Every ``extra`` that is not a
|
|
196
|
+
number, a bool or None is replaced by its redacted text, and a list or tuple of texts stays
|
|
197
|
+
one, as a plain list or tuple whatever its class: OpenTelemetry's LoggingHandler exports
|
|
198
|
+
every ``extra`` as an attribute, and from SDK 1.39 it exports an object such as the
|
|
199
|
+
``request`` Django passes on every 4xx and 5xx response as ``str(request)``, query string
|
|
200
|
+
included. An ``extra`` named after a credential (``access_token``, ``authorization``) is
|
|
201
|
+
replaced whole, unless it is a number, a bool, None or a fingerprint: a token on its own has
|
|
202
|
+
no shape to find. The exception keeps its type name, traceback and chain, with each message
|
|
203
|
+
redacted. A value whose ``__str__`` raises is replaced by a note that says so.
|
|
204
|
+
|
|
205
|
+
``record`` itself is left unchanged, so the other handlers still get the request object and
|
|
206
|
+
the original exception (Django's mail_admins handler reads ``request.META``).
|
|
207
|
+
"""
|
|
208
|
+
redacted = copy.copy(record)
|
|
209
|
+
try:
|
|
210
|
+
message = record.getMessage()
|
|
211
|
+
except Exception: # arguments that do not fit the message: logging reports it in emit()
|
|
212
|
+
message = _text(record.msg)
|
|
213
|
+
redacted.msg = redact_secrets(message)
|
|
214
|
+
redacted.args = None
|
|
215
|
+
if 'message' in vars(record):
|
|
216
|
+
redacted.message = redacted.msg
|
|
217
|
+
for name, value in vars(record).items():
|
|
218
|
+
if name not in _RECORD_ATTRIBUTES:
|
|
219
|
+
setattr(redacted, name, _redact_extra(name, value))
|
|
220
|
+
if record.exc_info and record.exc_info[1] is not None:
|
|
221
|
+
stand_in = _redacted_exception(record.exc_info[1], set())
|
|
222
|
+
redacted.exc_info = (type(stand_in), stand_in, record.exc_info[2])
|
|
223
|
+
if record.exc_text:
|
|
224
|
+
redacted.exc_text = redact_secrets(record.exc_text)
|
|
225
|
+
if record.stack_info:
|
|
226
|
+
redacted.stack_info = redact_secrets(record.stack_info)
|
|
227
|
+
return redacted
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _withheld(record: logging.LogRecord, error: Exception) -> logging.LogRecord:
|
|
231
|
+
"""What a handler gets in place of a record that could not be redacted.
|
|
232
|
+
|
|
233
|
+
It says where and when the record was written and names the type of the error. It holds
|
|
234
|
+
nothing of the record's message, arguments, extras or exception, and nothing of the error's
|
|
235
|
+
own message: any of them may be what holds the credential.
|
|
236
|
+
"""
|
|
237
|
+
withheld = logging.LogRecord(
|
|
238
|
+
record.name, record.levelno, record.pathname, record.lineno,
|
|
239
|
+
f'log record withheld: redaction failed ({type(error).__name__})', None, None, record.funcName)
|
|
240
|
+
withheld.created, withheld.msecs, withheld.relativeCreated = record.created, record.msecs, record.relativeCreated
|
|
241
|
+
return withheld
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
class RedactingHandlerMixin:
|
|
245
|
+
"""Hands the handler a redacted copy of every record; see ``redact_log_record``.
|
|
246
|
+
|
|
247
|
+
Mix it in before the handler class::
|
|
248
|
+
|
|
249
|
+
class RedactingLoggingHandler(RedactingHandlerMixin, LoggingHandler):
|
|
250
|
+
pass
|
|
251
|
+
|
|
252
|
+
Written the other way round, the handler class would answer ``emit`` first and every record
|
|
253
|
+
would be exported as it was, so such a class is refused when it is defined.
|
|
254
|
+
|
|
255
|
+
The other handlers of the same logger keep receiving the original record.
|
|
256
|
+
|
|
257
|
+
A record that cannot be redacted is never handed on as it was, and the failure never leaves
|
|
258
|
+
the logging call: the handler gets a line that says a record was withheld.
|
|
259
|
+
"""
|
|
260
|
+
|
|
261
|
+
def __init_subclass__(cls, **kwargs):
|
|
262
|
+
super().__init_subclass__(**kwargs)
|
|
263
|
+
# The class whose emit() a record reaches first.
|
|
264
|
+
first = next(klass for klass in cls.__mro__ if 'emit' in vars(klass))
|
|
265
|
+
if not issubclass(first, RedactingHandlerMixin):
|
|
266
|
+
raise TypeError(
|
|
267
|
+
f'{cls.__name__}: RedactingHandlerMixin must come before {first.__name__} in its bases, '
|
|
268
|
+
'or records are exported without redaction')
|
|
269
|
+
|
|
270
|
+
def emit(self, record):
|
|
271
|
+
try:
|
|
272
|
+
redacted = redact_log_record(record)
|
|
273
|
+
except Exception as error:
|
|
274
|
+
redacted = _withheld(record, error)
|
|
275
|
+
super().emit(redacted)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: base-api-utils
|
|
3
|
-
Version: 1.1.
|
|
3
|
+
Version: 1.1.124
|
|
4
4
|
Summary: Django Rest Framework micro services common utilities
|
|
5
5
|
Author-email: Román Gutierrez <roman@tipit.net>, Sebastian Marcet <sebastian@tipit.net>
|
|
6
6
|
Project-URL: Homepage, https://github.com/fntechgit/base-api-utils
|