id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
9,900
mllp.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/channel/hl7/mllp.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Django from django import forms # Zato from zato.admin.web.forms import add_select, add_services, WithAuditLog from zato.common.api import HL7 # ################################################################################################################################ # ################################################################################################################################ _default = HL7.Default _address = f'{_default.channel_host}:{_default.channel_port}' # ################################################################################################################################ # ################################################################################################################################ class CreateForm(WithAuditLog): name = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) should_parse_on_input = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) should_validate = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) should_return_errors = forms.BooleanField(required=False, widget=forms.CheckboxInput()) should_log_messages = forms.BooleanField(required=False, widget=forms.CheckboxInput()) hl7_version = forms.ChoiceField(widget=forms.Select()) address = forms.CharField(initial=_address, widget=forms.TextInput(attrs={'style':'width:73%'})) service = forms.ChoiceField(widget=forms.Select(attrs={'class':'required', 'style':'width:100%'})) logging_level = forms.ChoiceField(widget=forms.Select()) data_encoding = forms.CharField(initial=_default.data_encoding, widget=forms.TextInput(attrs={'style':'width:16%'})) max_msg_size = forms.CharField(initial=_default.max_msg_size, widget=forms.TextInput(attrs={'style':'width:30%'})) read_buffer_size = forms.CharField(initial=_default.read_buffer_size, widget=forms.TextInput(attrs={'style':'width:15%'})) recv_timeout = forms.CharField(initial=_default.recv_timeout, widget=forms.TextInput(attrs={'style':'width:8%'})) start_seq = forms.CharField(initial=_default.start_seq, widget=forms.TextInput(attrs={'style':'width:35%'})) end_seq = forms.CharField(initial=_default.end_seq, widget=forms.TextInput(attrs={'style':'width:26%'})) def __init__(self, prefix=None, post_data=None, req=None): super(WithAuditLog, self).__init__(post_data, prefix=prefix) add_select(self, 'hl7_version', HL7.Const.Version(), needs_initial_select=False) add_select(self, 'logging_level', HL7.Const.LoggingLevel(), needs_initial_select=False) add_services(self, req) # ################################################################################################################################ # ################################################################################################################################ class EditForm(CreateForm): is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput()) # ################################################################################################################################ # ################################################################################################################################
3,567
Python
.py
44
77.340909
130
0.518392
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,901
imap.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/email/imap.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from imaplib import IMAP4_SSL_PORT # Django from django import forms # Zato from zato.common.api import EMAIL # ################################################################################################################################ # ################################################################################################################################ class CreateForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) server_type = forms.ChoiceField(widget=forms.Select()) host = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) port = forms.CharField(initial=IMAP4_SSL_PORT, widget=forms.TextInput(attrs={'style':'width:10%'})) timeout = forms.CharField(initial=EMAIL.DEFAULT.TIMEOUT, widget=forms.TextInput(attrs={'style':'width:6%'})) debug_level = forms.CharField(initial=EMAIL.DEFAULT.IMAP_DEBUG_LEVEL, widget=forms.TextInput(attrs={'style':'width:7%'})) username = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) mode = forms.ChoiceField(widget=forms.Select()) get_criteria = forms.CharField( initial=EMAIL.DEFAULT.GET_CRITERIA, widget=forms.Textarea(attrs={'style':'width:100%; height:4rem'} )) tenant_id = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) client_id = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) filter_criteria = forms.CharField( initial=EMAIL.DEFAULT.FILTER_CRITERIA, widget=forms.Textarea(attrs={'style':'width:100%; height:4rem'} )) def __init__(self, prefix=None, post_data=None): super(CreateForm, self).__init__(post_data, prefix=prefix) self.fields['mode'].choices = ((item, item) for item in EMAIL.IMAP.MODE()) self.fields['server_type'].choices = [] for key, value in EMAIL.IMAP.ServerTypeHuman.items(): self.fields['server_type'].choices.append([key, value]) # ################################################################################################################################ # ################################################################################################################################ class EditForm(CreateForm): is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput()) # ################################################################################################################################ # ################################################################################################################################
2,948
Python
.py
46
59.586957
130
0.516442
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,902
__init__.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/email/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals
238
Python
.py
6
38.166667
82
0.729258
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,903
smtp.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/email/smtp.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from smtplib import SMTP_PORT # Django from django import forms # Zato from zato.common.api import EMAIL class CreateForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'})) is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) host = forms.CharField(widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'})) port = forms.CharField(initial=SMTP_PORT, widget=forms.TextInput(attrs={'class':'required', 'style':'width:20%'})) timeout = forms.CharField(initial=EMAIL.DEFAULT.TIMEOUT, widget=forms.TextInput(attrs={'class':'required', 'style':'width:20%'})) is_debug = forms.BooleanField(required=False, widget=forms.CheckboxInput()) username = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) mode = forms.ChoiceField(widget=forms.Select()) ping_address = forms.CharField(initial=EMAIL.DEFAULT.PING_ADDRESS, widget=forms.TextInput(attrs={'style':'width:100%'})) def __init__(self, prefix=None, post_data=None): super(CreateForm, self).__init__(post_data, prefix=prefix) self.fields['mode'].choices = ((item, item) for item in EMAIL.SMTP.MODE()) class EditForm(CreateForm): is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput()) is_debug = forms.BooleanField(required=False, widget=forms.CheckboxInput())
1,739
Python
.py
29
56.275862
133
0.730588
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,904
cassandra.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/query/cassandra.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from operator import itemgetter # Django from django import forms # Python 2/3 compatibility from zato.common.ext.future.utils import iteritems class CreateForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'})) is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) def_id = forms.ChoiceField(widget=forms.Select()) value = forms.CharField(widget=forms.Textarea(attrs={'style':'width:100%', 'class':'required'})) def set_def_id(self, def_ids): self.fields['def_id'].choices = ((id, name) for (id, name) in sorted(iteritems(def_ids), key=itemgetter(1))) class EditForm(CreateForm): is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput())
1,105
Python
.py
22
47.181818
116
0.736499
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,905
__init__.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/query/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
154
Python
.py
5
29.4
64
0.687075
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,906
memcached.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/cache/memcached.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # Django from django import forms class CreateForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'})) is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) is_default = forms.BooleanField(required=False, widget=forms.CheckboxInput()) is_debug = forms.BooleanField(required=False, widget=forms.CheckboxInput()) servers = forms.CharField(widget=forms.Textarea(attrs={'style':'width:100%; height:80px'})) extra = forms.CharField(widget=forms.Textarea(attrs={'style':'width:100%%; height:80px'})) class EditForm(CreateForm): is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput()) is_default = forms.BooleanField(required=False, widget=forms.CheckboxInput()) is_debug = forms.BooleanField(required=False, widget=forms.CheckboxInput())
1,191
Python
.py
20
56.25
107
0.749356
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,907
__init__.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/cache/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
154
Python
.py
5
29.4
64
0.687075
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,908
entry.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/cache/builtin/entry.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # Django from django import forms # Zato from zato.common.api import CACHE from zato.admin.web.forms import add_select # ################################################################################################################################ class CreateForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput()) key = forms.CharField(widget=forms.Textarea(attrs={'class':'required', 'style':'width:100%; height:70px'})) value = forms.CharField(widget=forms.Textarea(attrs={'class':'required', 'style':'width:100%%; height:70px'})) expiry = forms.CharField(widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'}), initial=0) replace_existing = forms.BooleanField(required=False, widget=forms.CheckboxInput()) cache_id = forms.CharField(widget=forms.HiddenInput()) key_data_type = forms.ChoiceField(widget=forms.Select( attrs={'style':'width:100%'}), initial=CACHE.BUILTIN_KV_DATA_TYPE.STR.id) value_data_type = forms.ChoiceField(widget=forms.Select( attrs={'style':'width:100%'}), initial=CACHE.BUILTIN_KV_DATA_TYPE.STR.id) def __init__(self, post_data=None, req=None): super(CreateForm, self).__init__(post_data) add_select(self, 'key_data_type', CACHE.BUILTIN_KV_DATA_TYPE()) add_select(self, 'value_data_type', CACHE.BUILTIN_KV_DATA_TYPE()) # ################################################################################################################################ class EditForm(CreateForm): replace_existing = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) old_key = forms.CharField(widget=forms.Textarea(attrs={'class':'required', 'style':'display:none'})) # ################################################################################################################################
2,111
Python
.py
32
61.9375
130
0.582769
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,909
__init__.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/cache/builtin/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # Django from django import forms # Zato from zato.common.api import CACHE from zato.admin.web.forms import add_select # ################################################################################################################################ class CreateForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'})) is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) is_default = forms.BooleanField(required=False, widget=forms.CheckboxInput()) max_size = forms.CharField( initial=CACHE.DEFAULT.MAX_SIZE, widget=forms.TextInput(attrs={'class':'required', 'style':'width:15%'})) max_item_size = forms.CharField( initial=CACHE.DEFAULT.MAX_ITEM_SIZE, widget=forms.TextInput(attrs={'class':'required', 'style':'width:15%'})) extend_expiry_on_get = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) extend_expiry_on_set = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) sync_method = forms.ChoiceField(widget=forms.Select(attrs={'style':'width:50%'})) persistent_storage = forms.ChoiceField(widget=forms.Select(attrs={'style':'width:50%'})) cache_id = forms.CharField(widget=forms.HiddenInput()) def __init__(self, prefix=None, post_data=None, req=None): super(CreateForm, self).__init__(post_data, prefix=prefix) add_select(self, 'sync_method', CACHE.SYNC_METHOD()) add_select(self, 'persistent_storage', CACHE.PERSISTENT_STORAGE()) # ################################################################################################################################ class EditForm(CreateForm): is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput()) is_default = forms.BooleanField(required=False, widget=forms.CheckboxInput()) extend_expiry_on_get = forms.BooleanField(required=False, widget=forms.CheckboxInput()) extend_expiry_on_set = forms.BooleanField(required=False, widget=forms.CheckboxInput()) # ################################################################################################################################
2,549
Python
.py
37
64.783784
130
0.620552
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,910
topic.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/pubsub/topic.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # Django from django import forms # Zato from zato.common.api import PUBSUB from zato.admin.web.forms import add_select, add_pubsub_services class CreateForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'})) is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) has_gd = forms.BooleanField(required=False, widget=forms.CheckboxInput()) is_api_sub_allowed = forms.BooleanField(required=False, widget=forms.CheckboxInput()) hook_service_id = forms.ChoiceField(widget=forms.Select()) on_no_subs_pub = forms.ChoiceField(widget=forms.Select()) max_depth_gd = forms.CharField(widget=forms.TextInput( attrs={'class':'required', 'style':'width:20%'}), initial=PUBSUB.DEFAULT.TOPIC_MAX_DEPTH_GD) max_depth_non_gd = forms.CharField(widget=forms.TextInput( attrs={'class':'required', 'style':'width:20%'}), initial=PUBSUB.DEFAULT.TOPIC_MAX_DEPTH_NON_GD) depth_check_freq = forms.CharField(widget=forms.TextInput( attrs={'class':'required', 'style':'width:15%'}), initial=PUBSUB.DEFAULT.DEPTH_CHECK_FREQ) pub_buffer_size_gd = forms.CharField(widget=forms.HiddenInput(), initial=PUBSUB.DEFAULT.PUB_BUFFER_SIZE_GD) task_sync_interval = forms.CharField(widget=forms.TextInput( attrs={'class':'required', 'style':'width:20%'}), initial=PUBSUB.DEFAULT.TASK_SYNC_INTERVAL) task_delivery_interval = forms.CharField(widget=forms.TextInput( attrs={'class':'required', 'style':'width:15%'}), initial=PUBSUB.DEFAULT.TASK_DELIVERY_INTERVAL) limit_retention = forms.CharField(widget=forms.TextInput( attrs={'class':'required', 'style':'width:15%'}), initial=PUBSUB.DEFAULT.LimitTopicRetention) limit_message_expiry = forms.CharField(widget=forms.TextInput( attrs={'class':'required', 'style':'width:15%'}), initial=PUBSUB.DEFAULT.LimitMessageExpiry) limit_sub_inactivity = forms.CharField(widget=forms.TextInput( attrs={'class':'required', 'style':'width:15%'}), initial=PUBSUB.DEFAULT.LimitSubInactivity) def __init__(self, req, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) add_select(self, 'on_no_subs_pub', [ PUBSUB.ON_NO_SUBS_PUB.ACCEPT, PUBSUB.ON_NO_SUBS_PUB.DROP, ], False) add_pubsub_services(self, req, by_id=True) class EditForm(CreateForm): is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput())
2,816
Python
.py
44
58.545455
111
0.716981
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,911
endpoint.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/pubsub/endpoint.py
# -*- coding: utf-8 -*- """ Copyright (C) 2022, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Django from django import forms # Zato from zato.admin.web.forms import add_security_select, add_select from zato.common.api import PUBSUB, skip_endpoint_types # ################################################################################################################################ class CreateForm(forms.Form): # Common ones id = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'})) endpoint_type = forms.ChoiceField(widget=forms.Select()) is_internal = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) role = forms.ChoiceField(widget=forms.Select()) topic_patterns = forms.CharField(widget=forms.Textarea(attrs={ 'style':'width:100%; height:120px', 'placeholder':'pub=/*\nsub=/*', })) # REST/SOAP security_id = forms.ChoiceField(widget=forms.Select()) # Service service_id = forms.ChoiceField(widget=forms.Select()) # WebSockets ws_channel_id = forms.ChoiceField(widget=forms.Select()) def __init__(self, req, data_list, prefix=None, post_data=None): super(CreateForm, self).__init__(post_data, prefix=prefix) self.fields['role'].choices = [] self.fields['ws_channel_id'].choices = [] add_security_select(self, data_list.security_list, field_name='security_id', needs_no_security=False, needs_rbac=False) add_select(self, 'service_id', data_list.service_list) add_select(self, 'ws_channel_id', data_list.ws_channel_list) add_select(self, 'role', PUBSUB.ROLE()) add_select(self, 'endpoint_type', PUBSUB.ENDPOINT_TYPE().get_pub_types(), needs_initial_select=False, skip=skip_endpoint_types) # Let's assume the default type of pub/sub endpoint will be REST clients self.initial['endpoint_type'] = PUBSUB.ENDPOINT_TYPE.REST.id # ################################################################################################################################ class EditForm(CreateForm): is_internal = forms.BooleanField(required=False, widget=forms.CheckboxInput()) # ################################################################################################################################
2,477
Python
.py
44
51
130
0.586093
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,912
__init__.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/pubsub/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Django from django import forms # Zato from zato.admin.web.forms import add_select from zato.common.api import PUBSUB # ################################################################################################################################ class MsgForm(forms.Form): correl_id = forms.CharField(required=False, widget=forms.TextInput(attrs={'style':'width:100%'})) in_reply_to = forms.CharField(required=False, widget=forms.TextInput(attrs={'style':'width:100%'})) expiration = forms.CharField( widget=forms.TextInput(attrs={'class':'required', 'style':'width:50%'}), initial=PUBSUB.DEFAULT.EXPIRATION) exp_from_now = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) priority = forms.CharField(required=True, widget=forms.TextInput(attrs={'class':'required', 'style':'width:60%'}), initial=5) mime_type = forms.CharField(widget=forms.HiddenInput()) # ################################################################################################################################ class MsgPublishForm(MsgForm): topic_name = forms.ChoiceField(widget=forms.Select()) publisher_id = forms.ChoiceField(widget=forms.Select()) gd = forms.ChoiceField(widget=forms.Select()) ext_client_id = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) group_id = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) msg_id = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) position_in_group = forms.CharField(widget=forms.TextInput(attrs={'class':'required', 'style':'width:30%'})) select_changer_source = forms.CharField(widget=forms.Textarea(attrs={'style':'display:none'})) reply_to_sk = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%;margin-bottom:4px'})) deliver_to_sk = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) def __init__(self, req, select_changer_data, initial_topic_name, topic_list, initial_hook_service_name, publisher_list, *args, **kwargs): super(MsgPublishForm, self).__init__(*args, **kwargs) add_select(self, 'topic_name', topic_list) add_select(self, 'publisher_id', publisher_list) add_select(self, 'gd', PUBSUB.GD_CHOICE(), False) self.initial['topic_name'] = initial_topic_name self.initial['select_changer_source'] = select_changer_data # ################################################################################################################################
2,747
Python
.py
42
60.52381
130
0.604306
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,913
subscription.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/pubsub/subscription.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Django from django import forms # Zato from zato.common.api import CONNECTION, PUBSUB, skip_endpoint_types, URL_TYPE from zato.admin.web.forms import add_http_soap_select, add_select, add_select_from_service # ################################################################################################################################ class CreateForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput()) sub_key = forms.CharField(widget=forms.HiddenInput()) server_id = forms.ChoiceField(widget=forms.Select(), required=False) endpoint_type = forms.ChoiceField(widget=forms.Select()) endpoint_id = forms.ChoiceField(widget=forms.Select()) hook_serice_id = forms.ChoiceField(widget=forms.Select()) active_status = forms.ChoiceField(widget=forms.Select()) has_gd = forms.BooleanField(required=False, widget=forms.CheckboxInput()) is_staging_enabled = forms.BooleanField(required=False, widget=forms.CheckboxInput()) delivery_batch_size = forms.CharField(widget=forms.TextInput(attrs={'style':'width:15%'})) wrap_one_msg_in_list = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) delivery_max_retry = forms.CharField(widget=forms.TextInput(attrs={'style':'width:25%'})) delivery_err_should_block = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) wait_sock_err = forms.CharField(widget=forms.TextInput(attrs={'style':'width:15%'})) wait_non_sock_err = forms.CharField(widget=forms.TextInput(attrs={'style':'width:15%'})) delivery_method = forms.ChoiceField(widget=forms.Select()) delivery_data_format = forms.ChoiceField(widget=forms.Select()) # This is not shown to users - only holds ID of an underlying interval-based job, # if one is in use for a given subscription. out_job_id = forms.CharField(widget=forms.HiddenInput()) # REST rest_delivery_endpoint = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) out_rest_http_soap_id = forms.ChoiceField(widget=forms.Select()) out_http_method = forms.CharField(widget=forms.TextInput(attrs={'style':'width:30%'})) # SOAP soap_delivery_endpoint = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) out_soap_http_soap_id = forms.ChoiceField(widget=forms.Select()) # Service service_id = forms.ChoiceField(widget=forms.Select()) # WebSockets ws_channel_id = forms.ChoiceField(widget=forms.Select()) # AMQP out_amqp_id = forms.ChoiceField(widget=forms.Select()) amqp_exchange = forms.CharField(widget=forms.TextInput(attrs={'style':'width:49%'})) amqp_routing_key = forms.CharField(widget=forms.TextInput(attrs={'style':'width:50%'})) # Flat files files_directory_list = forms.CharField(widget=forms.Textarea(attrs={'style':'width:100%; height:60px'})) # FTP ftp_directory_list = forms.CharField(widget=forms.Textarea(attrs={'style':'width:100%; height:60px'})) # SMTP - Twilio sms_twilio_from = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) sms_twilio_to_list = forms.CharField(widget=forms.Textarea(attrs={'style':'width:100%; height:60px'})) # SMTP out_smtp_id = forms.ChoiceField(widget=forms.Select()) smtp_subject = forms.CharField(widget=forms.TextInput(attrs={'style':'width:100%'})) smtp_from = forms.CharField(widget=forms.TextInput(attrs={'style':'width:50%'})) smtp_to_list = forms.CharField(widget=forms.Textarea(attrs={'style':'width:100%; height:60px'})) smtp_body = forms.CharField(widget=forms.Textarea(attrs={'style':'width:100%; height:120px'})) smtp_is_html = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) topic_list_text = forms.CharField(widget=forms.Textarea(attrs={'style':'width:100%; height:120px'})) topic_list_json = forms.CharField(widget=forms.Textarea(attrs={'display':'none'})) def __init__(self, req, data_list, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) add_select(self, 'endpoint_type', PUBSUB.ENDPOINT_TYPE().get_pub_types(), needs_initial_select=False, skip=skip_endpoint_types + (PUBSUB.ENDPOINT_TYPE.WEB_SOCKETS.id,)) add_select(self, 'service_id', data_list.service_list) add_select(self, 'out_amqp_id', data_list.out_amqp_list) add_select(self, 'active_status', PUBSUB.QUEUE_ACTIVE_STATUS()) add_select(self, 'delivery_method', PUBSUB.DELIVERY_METHOD()) add_select(self, 'delivery_data_format', PUBSUB.DATA_FORMAT()) add_http_soap_select(self, 'out_rest_http_soap_id', req, CONNECTION.OUTGOING, URL_TYPE.PLAIN_HTTP) add_http_soap_select(self, 'out_soap_http_soap_id', req, CONNECTION.OUTGOING, URL_TYPE.SOAP) add_select_from_service(self, req, 'zato.server.get-list', 'server_id') self.initial['endpoint_type'] = PUBSUB.ENDPOINT_TYPE.REST.id self.initial['delivery_batch_size'] = PUBSUB.DEFAULT.DELIVERY_BATCH_SIZE self.initial['delivery_max_retry'] = PUBSUB.DEFAULT.DELIVERY_MAX_RETRY self.initial['wait_sock_err'] = PUBSUB.DEFAULT.WAIT_TIME_SOCKET_ERROR self.initial['wait_non_sock_err'] = PUBSUB.DEFAULT.WAIT_TIME_NON_SOCKET_ERROR self.initial['out_http_method'] = 'POST' # ################################################################################################################################ class EditForm(CreateForm): pass # ################################################################################################################################
5,839
Python
.py
86
62.255814
130
0.664743
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,914
es.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/search/es.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # Django from django import forms # Zato from zato.common.api import SEARCH class CreateForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'})) is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) hosts = forms.CharField( initial=SEARCH.ES.DEFAULTS.HOSTS, widget=forms.Textarea(attrs={'style':'width:100%', 'class':'required'})) timeout = forms.CharField(initial=90, widget=forms.TextInput(attrs={'class':'required', 'style':'width:15%'})) body_as = forms.CharField(initial=SEARCH.ES.DEFAULTS.BODY_AS, widget=forms.TextInput(attrs={'class':'required', 'style':'width:15%'})) class EditForm(CreateForm): is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput())
1,125
Python
.py
21
50.142857
114
0.729262
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,915
solr.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/search/solr.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # Django from django import forms # Zato from zato.common.api import SEARCH class CreateForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'})) is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'checked':'checked'})) address = forms.CharField(initial=SEARCH.SOLR.DEFAULTS.ADDRESS, widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'})) timeout = forms.CharField( initial=SEARCH.SOLR.DEFAULTS.TIMEOUT, widget=forms.TextInput(attrs={'class':'required', 'style':'width:15%'})) pool_size = forms.CharField( initial=SEARCH.SOLR.DEFAULTS.POOL_SIZE, widget=forms.TextInput(attrs={'class':'required', 'style':'width:15%'})) ping_path = forms.CharField( initial=SEARCH.SOLR.DEFAULTS.PING_PATH, widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'})) class EditForm(CreateForm): is_active = forms.BooleanField(required=False, widget=forms.CheckboxInput())
1,328
Python
.py
24
51.375
121
0.726291
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,916
__init__.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/search/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals
238
Python
.py
6
38.166667
82
0.729258
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,917
__init__.py
zatosource_zato/code/zato-web-admin/src/zato/admin/web/forms/groups/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Django from django import forms # ################################################################################################################################ class CreateForm(forms.Form): # Common ones id = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField(widget=forms.TextInput(attrs={'class':'required', 'style':'width:100%'})) # ################################################################################################################################ class EditForm(CreateForm): pass # ################################################################################################################################
827
Python
.py
16
49.125
130
0.369077
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,918
mode-python.js
zatosource_zato/code/zato-web-admin/src/zato/admin/static/ace-builds/src/mode-python.js
define("ace/mode/python_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var PythonHighlightRules = function() { var keywords = ( "and|as|assert|break|class|continue|def|del|elif|else|except|exec|" + "finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|" + "raise|return|try|while|with|yield|async|await|nonlocal" ); var builtinConstants = ( "True|False|None|NotImplemented|Ellipsis|__debug__" ); var builtinFunctions = ( "abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|" + "eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|" + "binfile|bin|iter|property|tuple|bool|filter|len|range|type|bytearray|" + "float|list|raw_input|unichr|callable|format|locals|reduce|unicode|" + "chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|" + "cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|" + "__import__|complex|hash|min|apply|delattr|help|next|setattr|set|" + "buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern|" + "ascii|breakpoint|bytes" ); var keywordMapper = this.createKeywordMapper({ "invalid.deprecated": "debugger", "support.function": builtinFunctions, "variable.language": "self|cls", "constant.language": builtinConstants, "keyword": keywords }, "identifier"); var strPre = "[uU]?"; var strRawPre = "[rR]"; var strFormatPre = "[fF]"; var strRawFormatPre = "(?:[rR][fF]|[fF][rR])"; var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var octInteger = "(?:0[oO]?[0-7]+)"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var binInteger = "(?:0[bB][01]+)"; var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")"; var exponent = "(?:[eE][+-]?\\d+)"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + exponent + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; var stringEscape = "\\\\(x[0-9A-Fa-f]{2}|[0-7]{3}|[\\\\abfnrtv'\"]|U[0-9A-Fa-f]{8}|u[0-9A-Fa-f]{4})"; this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "string", // multi line """ string start regex : strPre + '"{3}', next : "qqstring3" }, { token : "string", // " string regex : strPre + '"(?=.)', next : "qqstring" }, { token : "string", // multi line ''' string start regex : strPre + "'{3}", next : "qstring3" }, { token : "string", // ' string regex : strPre + "'(?=.)", next : "qstring" }, { token: "string", regex: strRawPre + '"{3}', next: "rawqqstring3" }, { token: "string", regex: strRawPre + '"(?=.)', next: "rawqqstring" }, { token: "string", regex: strRawPre + "'{3}", next: "rawqstring3" }, { token: "string", regex: strRawPre + "'(?=.)", next: "rawqstring" }, { token: "string", regex: strFormatPre + '"{3}', next: "fqqstring3" }, { token: "string", regex: strFormatPre + '"(?=.)', next: "fqqstring" }, { token: "string", regex: strFormatPre + "'{3}", next: "fqstring3" }, { token: "string", regex: strFormatPre + "'(?=.)", next: "fqstring" },{ token: "string", regex: strRawFormatPre + '"{3}', next: "rfqqstring3" }, { token: "string", regex: strRawFormatPre + '"(?=.)', next: "rfqqstring" }, { token: "string", regex: strRawFormatPre + "'{3}", next: "rfqstring3" }, { token: "string", regex: strRawFormatPre + "'(?=.)", next: "rfqstring" }, { token: "keyword.operator", regex: "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|@|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|=" }, { token: "punctuation", regex: ",|:|;|\\->|\\+=|\\-=|\\*=|\\/=|\\/\\/=|%=|@=|&=|\\|=|^=|>>=|<<=|\\*\\*=" }, { token: "paren.lparen", regex: "[\\[\\(\\{]" }, { token: "paren.rparen", regex: "[\\]\\)\\}]" }, { token: ["keyword", "text", "entity.name.function"], regex: "(def|class)(\\s+)([\\u00BF-\\u1FFF\\u2C00-\\uD7FF\\w]+)" }, { token: "text", regex: "\\s+" }, { include: "constants" }], "qqstring3": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", // multi line """ string end regex: '"{3}', next: "start" }, { defaultToken: "string" }], "qstring3": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", // multi line ''' string end regex: "'{3}", next: "start" }, { defaultToken: "string" }], "qqstring": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", regex: "\\\\$", next: "qqstring" }, { token: "string", regex: '"|$', next: "start" }, { defaultToken: "string" }], "qstring": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", regex: "\\\\$", next: "qstring" }, { token: "string", regex: "'|$", next: "start" }, { defaultToken: "string" }], "rawqqstring3": [{ token: "string", // multi line """ string end regex: '"{3}', next: "start" }, { defaultToken: "string" }], "rawqstring3": [{ token: "string", // multi line ''' string end regex: "'{3}", next: "start" }, { defaultToken: "string" }], "rawqqstring": [{ token: "string", regex: "\\\\$", next: "rawqqstring" }, { token: "string", regex: '"|$', next: "start" }, { defaultToken: "string" }], "rawqstring": [{ token: "string", regex: "\\\\$", next: "rawqstring" }, { token: "string", regex: "'|$", next: "start" }, { defaultToken: "string" }], "fqqstring3": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", // multi line """ string end regex: '"{3}', next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "fqstring3": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", // multi line ''' string end regex: "'{3}", next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "fqqstring": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", regex: "\\\\$", next: "fqqstring" }, { token: "string", regex: '"|$', next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "fqstring": [{ token: "constant.language.escape", regex: stringEscape }, { token: "string", regex: "'|$", next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "rfqqstring3": [{ token: "string", // multi line """ string end regex: '"{3}', next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "rfqstring3": [{ token: "string", // multi line ''' string end regex: "'{3}", next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "rfqqstring": [{ token: "string", regex: "\\\\$", next: "rfqqstring" }, { token: "string", regex: '"|$', next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "rfqstring": [{ token: "string", regex: "'|$", next: "start" }, { token: "paren.lparen", regex: "{", push: "fqstringParRules" }, { defaultToken: "string" }], "fqstringParRules": [{//TODO: nested {} token: "paren.lparen", regex: "[\\[\\(]" }, { token: "paren.rparen", regex: "[\\]\\)]" }, { token: "string", regex: "\\s+" }, { token: "string", regex: "'[^']*'" }, { token: "string", regex: '"[^"]*"' }, { token: "function.support", regex: "(!s|!r|!a)" }, { include: "constants" },{ token: 'paren.rparen', regex: "}", next: 'pop' },{ token: 'paren.lparen', regex: "{", push: "fqstringParRules" }], "constants": [{ token: "constant.numeric", // imaginary regex: "(?:" + floatNumber + "|\\d+)[jJ]\\b" }, { token: "constant.numeric", // float regex: floatNumber }, { token: "constant.numeric", // long integer regex: integer + "[lL]\\b" }, { token: "constant.numeric", // integer regex: integer + "\\b" }, { token: ["punctuation", "function.support"],// method regex: "(\\.)([a-zA-Z_]+)\\b" }, { token: keywordMapper, regex: "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }] }; this.normalizeRules(); }; oop.inherits(PythonHighlightRules, TextHighlightRules); exports.PythonHighlightRules = PythonHighlightRules; }); define("ace/mode/folding/pythonic",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(markers) { this.foldingStartMarker = new RegExp("([\\[{])(?:\\s*)$|(" + markers + ")(?:\\s*)(?:#.*)?$"); }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { if (match[1]) return this.openingBracketBlock(session, match[1], row, match.index); if (match[2]) return this.indentationBlock(session, row, match.index + match[2].length); return this.indentationBlock(session, row); } }; }).call(FoldMode.prototype); }); define("ace/mode/python",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/python_highlight_rules","ace/mode/folding/pythonic","ace/range"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var PythonHighlightRules = require("./python_highlight_rules").PythonHighlightRules; var PythonFoldMode = require("./folding/pythonic").FoldMode; var Range = require("../range").Range; var Mode = function() { this.HighlightRules = PythonHighlightRules; this.foldingRules = new PythonFoldMode("\\:"); this.$behaviour = this.$defaultBehaviour; }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "#"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[:]\s*$/); if (match) { indent += tab; } } return indent; }; var outdents = { "pass": 1, "return": 1, "raise": 1, "break": 1, "continue": 1 }; this.checkOutdent = function(state, line, input) { if (input !== "\r\n" && input !== "\r" && input !== "\n") return false; var tokens = this.getTokenizer().getLineTokens(line.trim(), state).tokens; if (!tokens) return false; do { var last = tokens.pop(); } while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/)))); if (!last) return false; return (last.type == "keyword" && outdents[last.value]); }; this.autoOutdent = function(state, doc, row) { row += 1; var indent = this.$getIndent(doc.getLine(row)); var tab = doc.getTabString(); if (indent.slice(-tab.length) == tab) doc.remove(new Range(row, indent.length-tab.length, row, indent.length)); }; this.$id = "ace/mode/python"; this.snippetFileId = "ace/snippets/python"; }).call(Mode.prototype); exports.Mode = Mode; }); (function() { window.require(["ace/mode/python"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
15,694
Python
.py
472
22.834746
197
0.457915
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,919
tippy.css
zatosource_zato/code/zato-web-admin/src/zato/admin/static/css/tippy.css
.tippy-box[data-animation=fade][data-state=hidden]{opacity:0}[data-tippy-root]{max-width:calc(100vw - 10px)}.tippy-box{position:relative;background-color:#333;color:#fff;border-radius:4px;font-size:14px;line-height:1.4;white-space:normal;outline:0;transition-property:transform,visibility,opacity}.tippy-box[data-placement^=top]>.tippy-arrow{bottom:0}.tippy-box[data-placement^=top]>.tippy-arrow:before{bottom:-7px;left:0;border-width:8px 8px 0;border-top-color:initial;transform-origin:center top}.tippy-box[data-placement^=bottom]>.tippy-arrow{top:0}.tippy-box[data-placement^=bottom]>.tippy-arrow:before{top:-7px;left:0;border-width:0 8px 8px;border-bottom-color:initial;transform-origin:center bottom}.tippy-box[data-placement^=left]>.tippy-arrow{right:0}.tippy-box[data-placement^=left]>.tippy-arrow:before{border-width:8px 0 8px 8px;border-left-color:initial;right:-7px;transform-origin:center left}.tippy-box[data-placement^=right]>.tippy-arrow{left:0}.tippy-box[data-placement^=right]>.tippy-arrow:before{left:-7px;border-width:8px 8px 8px 0;border-right-color:initial;transform-origin:center right}.tippy-box[data-inertia][data-state=visible]{transition-timing-function:cubic-bezier(.54,1.5,.38,1.11)}.tippy-arrow{width:16px;height:16px;color:#333}.tippy-arrow:before{content:"";position:absolute;border-color:transparent;border-style:solid}.tippy-content{position:relative;padding:5px 9px;z-index:1}.tippy-box[data-placement^=top]>.tippy-backdrop{transform-origin:0 25%;border-radius:40% 40% 0 0}.tippy-box[data-placement^=top]>.tippy-backdrop[data-state=visible]{transform:scale(1) translate(-50%,-55%)}.tippy-box[data-placement^=top]>.tippy-backdrop[data-state=hidden]{transform:scale(.2) translate(-50%,-45%)}.tippy-box[data-placement^=bottom]>.tippy-backdrop{transform-origin:0 -50%;border-radius:0 0 30% 30%}.tippy-box[data-placement^=bottom]>.tippy-backdrop[data-state=visible]{transform:scale(1) translate(-50%,-45%)}.tippy-box[data-placement^=bottom]>.tippy-backdrop[data-state=hidden]{transform:scale(.2) translate(-50%)}.tippy-box[data-placement^=left]>.tippy-backdrop{transform-origin:50% 0;border-radius:50% 0 0 50%}.tippy-box[data-placement^=left]>.tippy-backdrop[data-state=visible]{transform:scale(1) translate(-50%,-50%)}.tippy-box[data-placement^=left]>.tippy-backdrop[data-state=hidden]{transform:scale(.2) translate(-75%,-50%)}.tippy-box[data-placement^=right]>.tippy-backdrop{transform-origin:-50% 0;border-radius:0 50% 50% 0}.tippy-box[data-placement^=right]>.tippy-backdrop[data-state=visible]{transform:scale(1) translate(-50%,-50%)}.tippy-box[data-placement^=right]>.tippy-backdrop[data-state=hidden]{transform:scale(.2) translate(-25%,-50%)}.tippy-box[data-animatefill]{background-color:initial!important}.tippy-backdrop{position:absolute;background-color:#333;border-radius:50%;width:calc(110% + 32px);left:50%;top:50%;z-index:-1;transition:all cubic-bezier(.46,.1,.52,.98);-webkit-backface-visibility:hidden;backface-visibility:hidden}.tippy-backdrop[data-state=hidden]{opacity:0}.tippy-backdrop:after{content:"";float:left;padding-top:100%}.tippy-backdrop+.tippy-content{transition-property:opacity;will-change:opacity}.tippy-backdrop+.tippy-content[data-state=hidden]{opacity:0}.tippy-box[data-placement^=top]>.tippy-svg-arrow{bottom:0}.tippy-box[data-placement^=top]>.tippy-svg-arrow:after,.tippy-box[data-placement^=top]>.tippy-svg-arrow>svg{top:16px;transform:rotate(180deg)}.tippy-box[data-placement^=bottom]>.tippy-svg-arrow{top:0}.tippy-box[data-placement^=bottom]>.tippy-svg-arrow>svg{bottom:16px}.tippy-box[data-placement^=left]>.tippy-svg-arrow{right:0}.tippy-box[data-placement^=left]>.tippy-svg-arrow:after,.tippy-box[data-placement^=left]>.tippy-svg-arrow>svg{transform:rotate(90deg);top:calc(50% - 3px);left:11px}.tippy-box[data-placement^=right]>.tippy-svg-arrow{left:0}.tippy-box[data-placement^=right]>.tippy-svg-arrow:after,.tippy-box[data-placement^=right]>.tippy-svg-arrow>svg{transform:rotate(-90deg);top:calc(50% - 3px);right:11px}.tippy-svg-arrow{width:16px;height:16px;fill:#333;text-align:initial}.tippy-svg-arrow,.tippy-svg-arrow>svg{position:absolute}.tippy-box[data-theme~=light]{color:#26323d;box-shadow:0 0 20px 4px rgba(154,161,177,.15),0 4px 80px -8px rgba(36,40,47,.25),0 4px 4px -2px rgba(91,94,105,.15);background-color:#fff}.tippy-box[data-theme~=light][data-placement^=top]>.tippy-arrow:before{border-top-color:#fff}.tippy-box[data-theme~=light][data-placement^=bottom]>.tippy-arrow:before{border-bottom-color:#fff}.tippy-box[data-theme~=light][data-placement^=left]>.tippy-arrow:before{border-left-color:#fff}.tippy-box[data-theme~=light][data-placement^=right]>.tippy-arrow:before{border-right-color:#fff}.tippy-box[data-theme~=light]>.tippy-backdrop{background-color:#fff}.tippy-box[data-theme~=light]>.tippy-svg-arrow{fill:#fff}.tippy-box[data-theme~=light-border]{background-color:#fff;background-clip:padding-box;border:1px solid rgba(0,8,16,.15);color:#333;box-shadow:0 4px 14px -2px rgba(0,8,16,.08)}.tippy-box[data-theme~=light-border]>.tippy-backdrop{background-color:#fff}.tippy-box[data-theme~=light-border]>.tippy-arrow:after,.tippy-box[data-theme~=light-border]>.tippy-svg-arrow:after{content:"";position:absolute;z-index:-1}.tippy-box[data-theme~=light-border]>.tippy-arrow:after{border-color:transparent;border-style:solid}.tippy-box[data-theme~=light-border][data-placement^=top]>.tippy-arrow:before{border-top-color:#fff}.tippy-box[data-theme~=light-border][data-placement^=top]>.tippy-arrow:after{border-top-color:rgba(0,8,16,.2);border-width:7px 7px 0;top:17px;left:1px}.tippy-box[data-theme~=light-border][data-placement^=top]>.tippy-svg-arrow>svg{top:16px}.tippy-box[data-theme~=light-border][data-placement^=top]>.tippy-svg-arrow:after{top:17px}.tippy-box[data-theme~=light-border][data-placement^=bottom]>.tippy-arrow:before{border-bottom-color:#fff;bottom:16px}.tippy-box[data-theme~=light-border][data-placement^=bottom]>.tippy-arrow:after{border-bottom-color:rgba(0,8,16,.2);border-width:0 7px 7px;bottom:17px;left:1px}.tippy-box[data-theme~=light-border][data-placement^=bottom]>.tippy-svg-arrow>svg{bottom:16px}.tippy-box[data-theme~=light-border][data-placement^=bottom]>.tippy-svg-arrow:after{bottom:17px}.tippy-box[data-theme~=light-border][data-placement^=left]>.tippy-arrow:before{border-left-color:#fff}.tippy-box[data-theme~=light-border][data-placement^=left]>.tippy-arrow:after{border-left-color:rgba(0,8,16,.2);border-width:7px 0 7px 7px;left:17px;top:1px}.tippy-box[data-theme~=light-border][data-placement^=left]>.tippy-svg-arrow>svg{left:11px}.tippy-box[data-theme~=light-border][data-placement^=left]>.tippy-svg-arrow:after{left:12px}.tippy-box[data-theme~=light-border][data-placement^=right]>.tippy-arrow:before{border-right-color:#fff;right:16px}.tippy-box[data-theme~=light-border][data-placement^=right]>.tippy-arrow:after{border-width:7px 7px 7px 0;right:17px;top:1px;border-right-color:rgba(0,8,16,.2)}.tippy-box[data-theme~=light-border][data-placement^=right]>.tippy-svg-arrow>svg{right:11px}.tippy-box[data-theme~=light-border][data-placement^=right]>.tippy-svg-arrow:after{right:12px}.tippy-box[data-theme~=light-border]>.tippy-svg-arrow{fill:#fff}.tippy-box[data-theme~=light-border]>.tippy-svg-arrow:after{background-image:url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iNiIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJNMCA2czEuNzk2LS4wMTMgNC42Ny0zLjYxNUM1Ljg1MS45IDYuOTMuMDA2IDggMGMxLjA3LS4wMDYgMi4xNDguODg3IDMuMzQzIDIuMzg1QzE0LjIzMyA2LjAwNSAxNiA2IDE2IDZIMHoiIGZpbGw9InJnYmEoMCwgOCwgMTYsIDAuMikiLz48L3N2Zz4=);background-size:16px 6px;width:16px;height:6px}.tippy-box[data-theme~=material]{background-color:#505355;font-weight:600}.tippy-box[data-theme~=material][data-placement^=top]>.tippy-arrow:before{border-top-color:#505355}.tippy-box[data-theme~=material][data-placement^=bottom]>.tippy-arrow:before{border-bottom-color:#505355}.tippy-box[data-theme~=material][data-placement^=left]>.tippy-arrow:before{border-left-color:#505355}.tippy-box[data-theme~=material][data-placement^=right]>.tippy-arrow:before{border-right-color:#505355}.tippy-box[data-theme~=material]>.tippy-backdrop{background-color:#505355}.tippy-box[data-theme~=material]>.tippy-svg-arrow{fill:#505355}.tippy-box[data-theme~=translucent]{background-color:rgba(0,0,0,.7)}.tippy-box[data-theme~=translucent]>.tippy-arrow{width:14px;height:14px}.tippy-box[data-theme~=translucent][data-placement^=top]>.tippy-arrow:before{border-width:7px 7px 0;border-top-color:rgba(0,0,0,.7)}.tippy-box[data-theme~=translucent][data-placement^=bottom]>.tippy-arrow:before{border-width:0 7px 7px;border-bottom-color:rgba(0,0,0,.7)}.tippy-box[data-theme~=translucent][data-placement^=left]>.tippy-arrow:before{border-width:7px 0 7px 7px;border-left-color:rgba(0,0,0,.7)}.tippy-box[data-theme~=translucent][data-placement^=right]>.tippy-arrow:before{border-width:7px 7px 7px 0;border-right-color:rgba(0,0,0,.7)}.tippy-box[data-theme~=translucent]>.tippy-backdrop{background-color:rgba(0,0,0,.7)}.tippy-box[data-theme~=translucent]>.tippy-svg-arrow{fill:rgba(0,0,0,.7)}.tippy-box[data-animation=perspective][data-placement^=top]{transform-origin:bottom}.tippy-box[data-animation=perspective][data-placement^=top][data-state=visible]{transform:perspective(700px)}.tippy-box[data-animation=perspective][data-placement^=top][data-state=hidden]{transform:perspective(700px) translateY(8px) rotateX(60deg)}.tippy-box[data-animation=perspective][data-placement^=bottom]{transform-origin:top}.tippy-box[data-animation=perspective][data-placement^=bottom][data-state=visible]{transform:perspective(700px)}.tippy-box[data-animation=perspective][data-placement^=bottom][data-state=hidden]{transform:perspective(700px) translateY(-8px) rotateX(-60deg)}.tippy-box[data-animation=perspective][data-placement^=left]{transform-origin:right}.tippy-box[data-animation=perspective][data-placement^=left][data-state=visible]{transform:perspective(700px)}.tippy-box[data-animation=perspective][data-placement^=left][data-state=hidden]{transform:perspective(700px) translateX(8px) rotateY(-60deg)}.tippy-box[data-animation=perspective][data-placement^=right]{transform-origin:left}.tippy-box[data-animation=perspective][data-placement^=right][data-state=visible]{transform:perspective(700px)}.tippy-box[data-animation=perspective][data-placement^=right][data-state=hidden]{transform:perspective(700px) translateX(-8px) rotateY(60deg)}.tippy-box[data-animation=perspective][data-state=hidden]{opacity:0}.tippy-box[data-animation=perspective-subtle][data-placement^=top]{transform-origin:bottom}.tippy-box[data-animation=perspective-subtle][data-placement^=top][data-state=visible]{transform:perspective(700px)}.tippy-box[data-animation=perspective-subtle][data-placement^=top][data-state=hidden]{transform:perspective(700px) translateY(5px) rotateX(30deg)}.tippy-box[data-animation=perspective-subtle][data-placement^=bottom]{transform-origin:top}.tippy-box[data-animation=perspective-subtle][data-placement^=bottom][data-state=visible]{transform:perspective(700px)}.tippy-box[data-animation=perspective-subtle][data-placement^=bottom][data-state=hidden]{transform:perspective(700px) translateY(-5px) rotateX(-30deg)}.tippy-box[data-animation=perspective-subtle][data-placement^=left]{transform-origin:right}.tippy-box[data-animation=perspective-subtle][data-placement^=left][data-state=visible]{transform:perspective(700px)}.tippy-box[data-animation=perspective-subtle][data-placement^=left][data-state=hidden]{transform:perspective(700px) translateX(5px) rotateY(-30deg)}.tippy-box[data-animation=perspective-subtle][data-placement^=right]{transform-origin:left}.tippy-box[data-animation=perspective-subtle][data-placement^=right][data-state=visible]{transform:perspective(700px)}.tippy-box[data-animation=perspective-subtle][data-placement^=right][data-state=hidden]{transform:perspective(700px) translateX(-5px) rotateY(30deg)}.tippy-box[data-animation=perspective-subtle][data-state=hidden]{opacity:0}.tippy-box[data-animation=perspective-extreme][data-placement^=top]{transform-origin:bottom}.tippy-box[data-animation=perspective-extreme][data-placement^=top][data-state=visible]{transform:perspective(700px)}.tippy-box[data-animation=perspective-extreme][data-placement^=top][data-state=hidden]{transform:perspective(700px) translateY(10px) rotateX(90deg)}.tippy-box[data-animation=perspective-extreme][data-placement^=bottom]{transform-origin:top}.tippy-box[data-animation=perspective-extreme][data-placement^=bottom][data-state=visible]{transform:perspective(700px)}.tippy-box[data-animation=perspective-extreme][data-placement^=bottom][data-state=hidden]{transform:perspective(700px) translateY(-10px) rotateX(-90deg)}.tippy-box[data-animation=perspective-extreme][data-placement^=left]{transform-origin:right}.tippy-box[data-animation=perspective-extreme][data-placement^=left][data-state=visible]{transform:perspective(700px)}.tippy-box[data-animation=perspective-extreme][data-placement^=left][data-state=hidden]{transform:perspective(700px) translateX(10px) rotateY(-90deg)}.tippy-box[data-animation=perspective-extreme][data-placement^=right]{transform-origin:left}.tippy-box[data-animation=perspective-extreme][data-placement^=right][data-state=visible]{transform:perspective(700px)}.tippy-box[data-animation=perspective-extreme][data-placement^=right][data-state=hidden]{transform:perspective(700px) translateX(-10px) rotateY(90deg)}.tippy-box[data-animation=perspective-extreme][data-state=hidden]{opacity:.5}.tippy-box[data-animation=scale][data-placement^=top]{transform-origin:bottom}.tippy-box[data-animation=scale][data-placement^=bottom]{transform-origin:top}.tippy-box[data-animation=scale][data-placement^=left]{transform-origin:right}.tippy-box[data-animation=scale][data-placement^=right]{transform-origin:left}.tippy-box[data-animation=scale][data-state=hidden]{transform:scale(.5);opacity:0}.tippy-box[data-animation=scale-subtle][data-placement^=top]{transform-origin:bottom}.tippy-box[data-animation=scale-subtle][data-placement^=bottom]{transform-origin:top}.tippy-box[data-animation=scale-subtle][data-placement^=left]{transform-origin:right}.tippy-box[data-animation=scale-subtle][data-placement^=right]{transform-origin:left}.tippy-box[data-animation=scale-subtle][data-state=hidden]{transform:scale(.8);opacity:0}.tippy-box[data-animation=scale-extreme][data-placement^=top]{transform-origin:bottom}.tippy-box[data-animation=scale-extreme][data-placement^=bottom]{transform-origin:top}.tippy-box[data-animation=scale-extreme][data-placement^=left]{transform-origin:right}.tippy-box[data-animation=scale-extreme][data-placement^=right]{transform-origin:left}.tippy-box[data-animation=scale-extreme][data-state=hidden]{transform:scale(0);opacity:.25}.tippy-box[data-animation=shift-away][data-state=hidden]{opacity:0}.tippy-box[data-animation=shift-away][data-state=hidden][data-placement^=top]{transform:translateY(10px)}.tippy-box[data-animation=shift-away][data-state=hidden][data-placement^=bottom]{transform:translateY(-10px)}.tippy-box[data-animation=shift-away][data-state=hidden][data-placement^=left]{transform:translateX(10px)}.tippy-box[data-animation=shift-away][data-state=hidden][data-placement^=right]{transform:translateX(-10px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden]{opacity:0}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=top]{transform:translateY(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=bottom]{transform:translateY(-5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=left]{transform:translateX(5px)}.tippy-box[data-animation=shift-away-subtle][data-state=hidden][data-placement^=right]{transform:translateX(-5px)}.tippy-box[data-animation=shift-away-extreme][data-state=hidden]{opacity:0}.tippy-box[data-animation=shift-away-extreme][data-state=hidden][data-placement^=top]{transform:translateY(20px)}.tippy-box[data-animation=shift-away-extreme][data-state=hidden][data-placement^=bottom]{transform:translateY(-20px)}.tippy-box[data-animation=shift-away-extreme][data-state=hidden][data-placement^=left]{transform:translateX(20px)}.tippy-box[data-animation=shift-away-extreme][data-state=hidden][data-placement^=right]{transform:translateX(-20px)}.tippy-box[data-animation=shift-toward][data-state=hidden]{opacity:0}.tippy-box[data-animation=shift-toward][data-state=hidden][data-placement^=top]{transform:translateY(-10px)}.tippy-box[data-animation=shift-toward][data-state=hidden][data-placement^=bottom]{transform:translateY(10px)}.tippy-box[data-animation=shift-toward][data-state=hidden][data-placement^=left]{transform:translateX(-10px)}.tippy-box[data-animation=shift-toward][data-state=hidden][data-placement^=right]{transform:translateX(10px)}.tippy-box[data-animation=shift-toward-subtle][data-state=hidden]{opacity:0}.tippy-box[data-animation=shift-toward-subtle][data-state=hidden][data-placement^=top][data-state=hidden]{transform:translateY(-5px)}.tippy-box[data-animation=shift-toward-subtle][data-state=hidden][data-placement^=bottom][data-state=hidden]{transform:translateY(5px)}.tippy-box[data-animation=shift-toward-subtle][data-state=hidden][data-placement^=left][data-state=hidden]{transform:translateX(-5px)}.tippy-box[data-animation=shift-toward-subtle][data-state=hidden][data-placement^=right][data-state=hidden]{transform:translateX(5px)}.tippy-box[data-animation=shift-toward-extreme][data-state=hidden]{opacity:0}.tippy-box[data-animation=shift-toward-extreme][data-state=hidden][data-placement^=top]{transform:translateY(-20px)}.tippy-box[data-animation=shift-toward-extreme][data-state=hidden][data-placement^=bottom]{transform:translateY(20px)}.tippy-box[data-animation=shift-toward-extreme][data-state=hidden][data-placement^=left]{transform:translateX(-20px)}.tippy-box[data-animation=shift-toward-extreme][data-state=hidden][data-placement^=right]{transform:translateX(20px)} /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:initial;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:initial}abbr[title]{border-bottom:none;text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:initial}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:initial}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}[hidden],template{display:none}.animated{animation-duration:1s;animation-fill-mode:both}.animated.infinite{animation-iteration-count:infinite}.animated.delay-1s{animation-delay:1s}.animated.delay-2s{animation-delay:2s}.animated.delay-3s{animation-delay:3s}.animated.delay-4s{animation-delay:4s}.animated.delay-5s{animation-delay:5s}.animated.fast{animation-duration:.8s}.animated.faster{animation-duration:.5s}.animated.slow{animation-duration:2s}.animated.slower{animation-duration:3s}@media (prefers-reduced-motion:reduce),(print){.animated{animation-duration:1ms!important;transition-duration:1ms!important;animation-iteration-count:1!important}}@keyframes rubberBand{0%{transform:scaleX(1)}30%{transform:scale3d(1.25,.75,1)}40%{transform:scale3d(.75,1.25,1)}50%{transform:scale3d(1.15,.85,1)}65%{transform:scale3d(.95,1.05,1)}75%{transform:scale3d(1.05,.95,1)}to{transform:scaleX(1)}}.rubberBand{animation-name:rubberBand}@keyframes tada{0%{transform:scaleX(1)}10%,20%{transform:scale3d(.9,.9,.9) rotate(-3deg)}30%,50%,70%,90%{transform:scale3d(1.1,1.1,1.1) rotate(3deg)}40%,60%,80%{transform:scale3d(1.1,1.1,1.1) rotate(-3deg)}to{transform:scaleX(1)}}.tada{animation-name:tada}@keyframes wobble{0%{transform:translateZ(0)}15%{transform:translate3d(-25%,0,0) rotate(-5deg)}30%{transform:translate3d(20%,0,0) rotate(3deg)}45%{transform:translate3d(-15%,0,0) rotate(-3deg)}60%{transform:translate3d(10%,0,0) rotate(2deg)}75%{transform:translate3d(-5%,0,0) rotate(-1deg)}to{transform:translateZ(0)}}.wobble{animation-name:wobble}
21,327
Python
.py
2
10,662.5
17,993
0.793763
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,920
tippy.js
zatosource_zato/code/zato-web-admin/src/zato/admin/static/tippy/tippy.js
/** * https://unpkg.com/tippy.js@6.3.7/dist/tippy-bundle.umd.min.js - MIT License */ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("@popperjs/core")):"function"==typeof define&&define.amd?define(["@popperjs/core"],e):(t=t||self).tippy=e(t.Popper)}(this,(function(t){"use strict";var e="undefined"!=typeof window&&"undefined"!=typeof document,n=!!e&&!!window.msCrypto,r={passive:!0,capture:!0},o=function(){return document.body};function i(t,e,n){if(Array.isArray(t)){var r=t[e];return null==r?Array.isArray(n)?n[e]:n:r}return t}function a(t,e){var n={}.toString.call(t);return 0===n.indexOf("[object")&&n.indexOf(e+"]")>-1}function s(t,e){return"function"==typeof t?t.apply(void 0,e):t}function u(t,e){return 0===e?t:function(r){clearTimeout(n),n=setTimeout((function(){t(r)}),e)};var n}function p(t,e){var n=Object.assign({},t);return e.forEach((function(t){delete n[t]})),n}function c(t){return[].concat(t)}function f(t,e){-1===t.indexOf(e)&&t.push(e)}function l(t){return t.split("-")[0]}function d(t){return[].slice.call(t)}function v(t){return Object.keys(t).reduce((function(e,n){return void 0!==t[n]&&(e[n]=t[n]),e}),{})}function m(){return document.createElement("div")}function g(t){return["Element","Fragment"].some((function(e){return a(t,e)}))}function h(t){return a(t,"MouseEvent")}function b(t){return!(!t||!t._tippy||t._tippy.reference!==t)}function y(t){return g(t)?[t]:function(t){return a(t,"NodeList")}(t)?d(t):Array.isArray(t)?t:d(document.querySelectorAll(t))}function w(t,e){t.forEach((function(t){t&&(t.style.transitionDuration=e+"ms")}))}function x(t,e){t.forEach((function(t){t&&t.setAttribute("data-state",e)}))}function E(t){var e,n=c(t)[0];return null!=n&&null!=(e=n.ownerDocument)&&e.body?n.ownerDocument:document}function O(t,e,n){var r=e+"EventListener";["transitionend","webkitTransitionEnd"].forEach((function(e){t[r](e,n)}))}function C(t,e){for(var n=e;n;){var r;if(t.contains(n))return!0;n=null==n.getRootNode||null==(r=n.getRootNode())?void 0:r.host}return!1}var T={isTouch:!1},A=0;function L(){T.isTouch||(T.isTouch=!0,window.performance&&document.addEventListener("mousemove",D))}function D(){var t=performance.now();t-A<20&&(T.isTouch=!1,document.removeEventListener("mousemove",D)),A=t}function k(){var t=document.activeElement;if(b(t)){var e=t._tippy;t.blur&&!e.state.isVisible&&t.blur()}}var R=Object.assign({appendTo:o,aria:{content:"auto",expanded:"auto"},delay:0,duration:[300,250],getReferenceClientRect:null,hideOnClick:!0,ignoreAttributes:!1,interactive:!1,interactiveBorder:2,interactiveDebounce:0,moveTransition:"",offset:[0,10],onAfterUpdate:function(){},onBeforeUpdate:function(){},onCreate:function(){},onDestroy:function(){},onHidden:function(){},onHide:function(){},onMount:function(){},onShow:function(){},onShown:function(){},onTrigger:function(){},onUntrigger:function(){},onClickOutside:function(){},placement:"top",plugins:[],popperOptions:{},render:null,showOnCreate:!1,touch:!0,trigger:"mouseenter focus",triggerTarget:null},{animateFill:!1,followCursor:!1,inlinePositioning:!1,sticky:!1},{allowHTML:!1,animation:"fade",arrow:!0,content:"",inertia:!1,maxWidth:350,role:"tooltip",theme:"",zIndex:9999}),P=Object.keys(R);function j(t){var e=(t.plugins||[]).reduce((function(e,n){var r,o=n.name,i=n.defaultValue;o&&(e[o]=void 0!==t[o]?t[o]:null!=(r=R[o])?r:i);return e}),{});return Object.assign({},t,e)}function M(t,e){var n=Object.assign({},e,{content:s(e.content,[t])},e.ignoreAttributes?{}:function(t,e){return(e?Object.keys(j(Object.assign({},R,{plugins:e}))):P).reduce((function(e,n){var r=(t.getAttribute("data-tippy-"+n)||"").trim();if(!r)return e;if("content"===n)e[n]=r;else try{e[n]=JSON.parse(r)}catch(t){e[n]=r}return e}),{})}(t,e.plugins));return n.aria=Object.assign({},R.aria,n.aria),n.aria={expanded:"auto"===n.aria.expanded?e.interactive:n.aria.expanded,content:"auto"===n.aria.content?e.interactive?null:"describedby":n.aria.content},n}function V(t,e){t.innerHTML=e}function I(t){var e=m();return!0===t?e.className="tippy-arrow":(e.className="tippy-svg-arrow",g(t)?e.appendChild(t):V(e,t)),e}function S(t,e){g(e.content)?(V(t,""),t.appendChild(e.content)):"function"!=typeof e.content&&(e.allowHTML?V(t,e.content):t.textContent=e.content)}function B(t){var e=t.firstElementChild,n=d(e.children);return{box:e,content:n.find((function(t){return t.classList.contains("tippy-content")})),arrow:n.find((function(t){return t.classList.contains("tippy-arrow")||t.classList.contains("tippy-svg-arrow")})),backdrop:n.find((function(t){return t.classList.contains("tippy-backdrop")}))}}function N(t){var e=m(),n=m();n.className="tippy-box",n.setAttribute("data-state","hidden"),n.setAttribute("tabindex","-1");var r=m();function o(n,r){var o=B(e),i=o.box,a=o.content,s=o.arrow;r.theme?i.setAttribute("data-theme",r.theme):i.removeAttribute("data-theme"),"string"==typeof r.animation?i.setAttribute("data-animation",r.animation):i.removeAttribute("data-animation"),r.inertia?i.setAttribute("data-inertia",""):i.removeAttribute("data-inertia"),i.style.maxWidth="number"==typeof r.maxWidth?r.maxWidth+"px":r.maxWidth,r.role?i.setAttribute("role",r.role):i.removeAttribute("role"),n.content===r.content&&n.allowHTML===r.allowHTML||S(a,t.props),r.arrow?s?n.arrow!==r.arrow&&(i.removeChild(s),i.appendChild(I(r.arrow))):i.appendChild(I(r.arrow)):s&&i.removeChild(s)}return r.className="tippy-content",r.setAttribute("data-state","hidden"),S(r,t.props),e.appendChild(n),n.appendChild(r),o(t.props,t.props),{popper:e,onUpdate:o}}N.$$tippy=!0;var H=1,U=[],_=[];function z(e,a){var p,g,b,y,A,L,D,k,P=M(e,Object.assign({},R,j(v(a)))),V=!1,I=!1,S=!1,N=!1,z=[],F=u(wt,P.interactiveDebounce),W=H++,X=(k=P.plugins).filter((function(t,e){return k.indexOf(t)===e})),Y={id:W,reference:e,popper:m(),popperInstance:null,props:P,state:{isEnabled:!0,isVisible:!1,isDestroyed:!1,isMounted:!1,isShown:!1},plugins:X,clearDelayTimeouts:function(){clearTimeout(p),clearTimeout(g),cancelAnimationFrame(b)},setProps:function(t){if(Y.state.isDestroyed)return;at("onBeforeUpdate",[Y,t]),bt();var n=Y.props,r=M(e,Object.assign({},n,v(t),{ignoreAttributes:!0}));Y.props=r,ht(),n.interactiveDebounce!==r.interactiveDebounce&&(pt(),F=u(wt,r.interactiveDebounce));n.triggerTarget&&!r.triggerTarget?c(n.triggerTarget).forEach((function(t){t.removeAttribute("aria-expanded")})):r.triggerTarget&&e.removeAttribute("aria-expanded");ut(),it(),J&&J(n,r);Y.popperInstance&&(Ct(),At().forEach((function(t){requestAnimationFrame(t._tippy.popperInstance.forceUpdate)})));at("onAfterUpdate",[Y,t])},setContent:function(t){Y.setProps({content:t})},show:function(){var t=Y.state.isVisible,e=Y.state.isDestroyed,n=!Y.state.isEnabled,r=T.isTouch&&!Y.props.touch,a=i(Y.props.duration,0,R.duration);if(t||e||n||r)return;if(et().hasAttribute("disabled"))return;if(at("onShow",[Y],!1),!1===Y.props.onShow(Y))return;Y.state.isVisible=!0,tt()&&($.style.visibility="visible");it(),dt(),Y.state.isMounted||($.style.transition="none");if(tt()){var u=rt(),p=u.box,c=u.content;w([p,c],0)}L=function(){var t;if(Y.state.isVisible&&!N){if(N=!0,$.offsetHeight,$.style.transition=Y.props.moveTransition,tt()&&Y.props.animation){var e=rt(),n=e.box,r=e.content;w([n,r],a),x([n,r],"visible")}st(),ut(),f(_,Y),null==(t=Y.popperInstance)||t.forceUpdate(),at("onMount",[Y]),Y.props.animation&&tt()&&function(t,e){mt(t,e)}(a,(function(){Y.state.isShown=!0,at("onShown",[Y])}))}},function(){var t,e=Y.props.appendTo,n=et();t=Y.props.interactive&&e===o||"parent"===e?n.parentNode:s(e,[n]);t.contains($)||t.appendChild($);Y.state.isMounted=!0,Ct()}()},hide:function(){var t=!Y.state.isVisible,e=Y.state.isDestroyed,n=!Y.state.isEnabled,r=i(Y.props.duration,1,R.duration);if(t||e||n)return;if(at("onHide",[Y],!1),!1===Y.props.onHide(Y))return;Y.state.isVisible=!1,Y.state.isShown=!1,N=!1,V=!1,tt()&&($.style.visibility="hidden");if(pt(),vt(),it(!0),tt()){var o=rt(),a=o.box,s=o.content;Y.props.animation&&(w([a,s],r),x([a,s],"hidden"))}st(),ut(),Y.props.animation?tt()&&function(t,e){mt(t,(function(){!Y.state.isVisible&&$.parentNode&&$.parentNode.contains($)&&e()}))}(r,Y.unmount):Y.unmount()},hideWithInteractivity:function(t){nt().addEventListener("mousemove",F),f(U,F),F(t)},enable:function(){Y.state.isEnabled=!0},disable:function(){Y.hide(),Y.state.isEnabled=!1},unmount:function(){Y.state.isVisible&&Y.hide();if(!Y.state.isMounted)return;Tt(),At().forEach((function(t){t._tippy.unmount()})),$.parentNode&&$.parentNode.removeChild($);_=_.filter((function(t){return t!==Y})),Y.state.isMounted=!1,at("onHidden",[Y])},destroy:function(){if(Y.state.isDestroyed)return;Y.clearDelayTimeouts(),Y.unmount(),bt(),delete e._tippy,Y.state.isDestroyed=!0,at("onDestroy",[Y])}};if(!P.render)return Y;var q=P.render(Y),$=q.popper,J=q.onUpdate;$.setAttribute("data-tippy-root",""),$.id="tippy-"+Y.id,Y.popper=$,e._tippy=Y,$._tippy=Y;var G=X.map((function(t){return t.fn(Y)})),K=e.hasAttribute("aria-expanded");return ht(),ut(),it(),at("onCreate",[Y]),P.showOnCreate&&Lt(),$.addEventListener("mouseenter",(function(){Y.props.interactive&&Y.state.isVisible&&Y.clearDelayTimeouts()})),$.addEventListener("mouseleave",(function(){Y.props.interactive&&Y.props.trigger.indexOf("mouseenter")>=0&&nt().addEventListener("mousemove",F)})),Y;function Q(){var t=Y.props.touch;return Array.isArray(t)?t:[t,0]}function Z(){return"hold"===Q()[0]}function tt(){var t;return!(null==(t=Y.props.render)||!t.$$tippy)}function et(){return D||e}function nt(){var t=et().parentNode;return t?E(t):document}function rt(){return B($)}function ot(t){return Y.state.isMounted&&!Y.state.isVisible||T.isTouch||y&&"focus"===y.type?0:i(Y.props.delay,t?0:1,R.delay)}function it(t){void 0===t&&(t=!1),$.style.pointerEvents=Y.props.interactive&&!t?"":"none",$.style.zIndex=""+Y.props.zIndex}function at(t,e,n){var r;(void 0===n&&(n=!0),G.forEach((function(n){n[t]&&n[t].apply(n,e)})),n)&&(r=Y.props)[t].apply(r,e)}function st(){var t=Y.props.aria;if(t.content){var n="aria-"+t.content,r=$.id;c(Y.props.triggerTarget||e).forEach((function(t){var e=t.getAttribute(n);if(Y.state.isVisible)t.setAttribute(n,e?e+" "+r:r);else{var o=e&&e.replace(r,"").trim();o?t.setAttribute(n,o):t.removeAttribute(n)}}))}}function ut(){!K&&Y.props.aria.expanded&&c(Y.props.triggerTarget||e).forEach((function(t){Y.props.interactive?t.setAttribute("aria-expanded",Y.state.isVisible&&t===et()?"true":"false"):t.removeAttribute("aria-expanded")}))}function pt(){nt().removeEventListener("mousemove",F),U=U.filter((function(t){return t!==F}))}function ct(t){if(!T.isTouch||!S&&"mousedown"!==t.type){var n=t.composedPath&&t.composedPath()[0]||t.target;if(!Y.props.interactive||!C($,n)){if(c(Y.props.triggerTarget||e).some((function(t){return C(t,n)}))){if(T.isTouch)return;if(Y.state.isVisible&&Y.props.trigger.indexOf("click")>=0)return}else at("onClickOutside",[Y,t]);!0===Y.props.hideOnClick&&(Y.clearDelayTimeouts(),Y.hide(),I=!0,setTimeout((function(){I=!1})),Y.state.isMounted||vt())}}}function ft(){S=!0}function lt(){S=!1}function dt(){var t=nt();t.addEventListener("mousedown",ct,!0),t.addEventListener("touchend",ct,r),t.addEventListener("touchstart",lt,r),t.addEventListener("touchmove",ft,r)}function vt(){var t=nt();t.removeEventListener("mousedown",ct,!0),t.removeEventListener("touchend",ct,r),t.removeEventListener("touchstart",lt,r),t.removeEventListener("touchmove",ft,r)}function mt(t,e){var n=rt().box;function r(t){t.target===n&&(O(n,"remove",r),e())}if(0===t)return e();O(n,"remove",A),O(n,"add",r),A=r}function gt(t,n,r){void 0===r&&(r=!1),c(Y.props.triggerTarget||e).forEach((function(e){e.addEventListener(t,n,r),z.push({node:e,eventType:t,handler:n,options:r})}))}function ht(){var t;Z()&&(gt("touchstart",yt,{passive:!0}),gt("touchend",xt,{passive:!0})),(t=Y.props.trigger,t.split(/\s+/).filter(Boolean)).forEach((function(t){if("manual"!==t)switch(gt(t,yt),t){case"mouseenter":gt("mouseleave",xt);break;case"focus":gt(n?"focusout":"blur",Et);break;case"focusin":gt("focusout",Et)}}))}function bt(){z.forEach((function(t){var e=t.node,n=t.eventType,r=t.handler,o=t.options;e.removeEventListener(n,r,o)})),z=[]}function yt(t){var e,n=!1;if(Y.state.isEnabled&&!Ot(t)&&!I){var r="focus"===(null==(e=y)?void 0:e.type);y=t,D=t.currentTarget,ut(),!Y.state.isVisible&&h(t)&&U.forEach((function(e){return e(t)})),"click"===t.type&&(Y.props.trigger.indexOf("mouseenter")<0||V)&&!1!==Y.props.hideOnClick&&Y.state.isVisible?n=!0:Lt(t),"click"===t.type&&(V=!n),n&&!r&&Dt(t)}}function wt(t){var e=t.target,n=et().contains(e)||$.contains(e);"mousemove"===t.type&&n||function(t,e){var n=e.clientX,r=e.clientY;return t.every((function(t){var e=t.popperRect,o=t.popperState,i=t.props.interactiveBorder,a=l(o.placement),s=o.modifiersData.offset;if(!s)return!0;var u="bottom"===a?s.top.y:0,p="top"===a?s.bottom.y:0,c="right"===a?s.left.x:0,f="left"===a?s.right.x:0,d=e.top-r+u>i,v=r-e.bottom-p>i,m=e.left-n+c>i,g=n-e.right-f>i;return d||v||m||g}))}(At().concat($).map((function(t){var e,n=null==(e=t._tippy.popperInstance)?void 0:e.state;return n?{popperRect:t.getBoundingClientRect(),popperState:n,props:P}:null})).filter(Boolean),t)&&(pt(),Dt(t))}function xt(t){Ot(t)||Y.props.trigger.indexOf("click")>=0&&V||(Y.props.interactive?Y.hideWithInteractivity(t):Dt(t))}function Et(t){Y.props.trigger.indexOf("focusin")<0&&t.target!==et()||Y.props.interactive&&t.relatedTarget&&$.contains(t.relatedTarget)||Dt(t)}function Ot(t){return!!T.isTouch&&Z()!==t.type.indexOf("touch")>=0}function Ct(){Tt();var n=Y.props,r=n.popperOptions,o=n.placement,i=n.offset,a=n.getReferenceClientRect,s=n.moveTransition,u=tt()?B($).arrow:null,p=a?{getBoundingClientRect:a,contextElement:a.contextElement||et()}:e,c=[{name:"offset",options:{offset:i}},{name:"preventOverflow",options:{padding:{top:2,bottom:2,left:5,right:5}}},{name:"flip",options:{padding:5}},{name:"computeStyles",options:{adaptive:!s}},{name:"$$tippy",enabled:!0,phase:"beforeWrite",requires:["computeStyles"],fn:function(t){var e=t.state;if(tt()){var n=rt().box;["placement","reference-hidden","escaped"].forEach((function(t){"placement"===t?n.setAttribute("data-placement",e.placement):e.attributes.popper["data-popper-"+t]?n.setAttribute("data-"+t,""):n.removeAttribute("data-"+t)})),e.attributes.popper={}}}}];tt()&&u&&c.push({name:"arrow",options:{element:u,padding:3}}),c.push.apply(c,(null==r?void 0:r.modifiers)||[]),Y.popperInstance=t.createPopper(p,$,Object.assign({},r,{placement:o,onFirstUpdate:L,modifiers:c}))}function Tt(){Y.popperInstance&&(Y.popperInstance.destroy(),Y.popperInstance=null)}function At(){return d($.querySelectorAll("[data-tippy-root]"))}function Lt(t){Y.clearDelayTimeouts(),t&&at("onTrigger",[Y,t]),dt();var e=ot(!0),n=Q(),r=n[0],o=n[1];T.isTouch&&"hold"===r&&o&&(e=o),e?p=setTimeout((function(){Y.show()}),e):Y.show()}function Dt(t){if(Y.clearDelayTimeouts(),at("onUntrigger",[Y,t]),Y.state.isVisible){if(!(Y.props.trigger.indexOf("mouseenter")>=0&&Y.props.trigger.indexOf("click")>=0&&["mouseleave","mousemove"].indexOf(t.type)>=0&&V)){var e=ot(!1);e?g=setTimeout((function(){Y.state.isVisible&&Y.hide()}),e):b=requestAnimationFrame((function(){Y.hide()}))}}else vt()}}function F(t,e){void 0===e&&(e={});var n=R.plugins.concat(e.plugins||[]);document.addEventListener("touchstart",L,r),window.addEventListener("blur",k);var o=Object.assign({},e,{plugins:n}),i=y(t).reduce((function(t,e){var n=e&&z(e,o);return n&&t.push(n),t}),[]);return g(t)?i[0]:i}F.defaultProps=R,F.setDefaultProps=function(t){Object.keys(t).forEach((function(e){R[e]=t[e]}))},F.currentInput=T;var W=Object.assign({},t.applyStyles,{effect:function(t){var e=t.state,n={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(e.elements.popper.style,n.popper),e.styles=n,e.elements.arrow&&Object.assign(e.elements.arrow.style,n.arrow)}}),X={mouseover:"mouseenter",focusin:"focus",click:"click"};var Y={name:"animateFill",defaultValue:!1,fn:function(t){var e;if(null==(e=t.props.render)||!e.$$tippy)return{};var n=B(t.popper),r=n.box,o=n.content,i=t.props.animateFill?function(){var t=m();return t.className="tippy-backdrop",x([t],"hidden"),t}():null;return{onCreate:function(){i&&(r.insertBefore(i,r.firstElementChild),r.setAttribute("data-animatefill",""),r.style.overflow="hidden",t.setProps({arrow:!1,animation:"shift-away"}))},onMount:function(){if(i){var t=r.style.transitionDuration,e=Number(t.replace("ms",""));o.style.transitionDelay=Math.round(e/10)+"ms",i.style.transitionDuration=t,x([i],"visible")}},onShow:function(){i&&(i.style.transitionDuration="0ms")},onHide:function(){i&&x([i],"hidden")}}}};var q={clientX:0,clientY:0},$=[];function J(t){var e=t.clientX,n=t.clientY;q={clientX:e,clientY:n}}var G={name:"followCursor",defaultValue:!1,fn:function(t){var e=t.reference,n=E(t.props.triggerTarget||e),r=!1,o=!1,i=!0,a=t.props;function s(){return"initial"===t.props.followCursor&&t.state.isVisible}function u(){n.addEventListener("mousemove",f)}function p(){n.removeEventListener("mousemove",f)}function c(){r=!0,t.setProps({getReferenceClientRect:null}),r=!1}function f(n){var r=!n.target||e.contains(n.target),o=t.props.followCursor,i=n.clientX,a=n.clientY,s=e.getBoundingClientRect(),u=i-s.left,p=a-s.top;!r&&t.props.interactive||t.setProps({getReferenceClientRect:function(){var t=e.getBoundingClientRect(),n=i,r=a;"initial"===o&&(n=t.left+u,r=t.top+p);var s="horizontal"===o?t.top:r,c="vertical"===o?t.right:n,f="horizontal"===o?t.bottom:r,l="vertical"===o?t.left:n;return{width:c-l,height:f-s,top:s,right:c,bottom:f,left:l}}})}function l(){t.props.followCursor&&($.push({instance:t,doc:n}),function(t){t.addEventListener("mousemove",J)}(n))}function d(){0===($=$.filter((function(e){return e.instance!==t}))).filter((function(t){return t.doc===n})).length&&function(t){t.removeEventListener("mousemove",J)}(n)}return{onCreate:l,onDestroy:d,onBeforeUpdate:function(){a=t.props},onAfterUpdate:function(e,n){var i=n.followCursor;r||void 0!==i&&a.followCursor!==i&&(d(),i?(l(),!t.state.isMounted||o||s()||u()):(p(),c()))},onMount:function(){t.props.followCursor&&!o&&(i&&(f(q),i=!1),s()||u())},onTrigger:function(t,e){h(e)&&(q={clientX:e.clientX,clientY:e.clientY}),o="focus"===e.type},onHidden:function(){t.props.followCursor&&(c(),p(),i=!0)}}}};var K={name:"inlinePositioning",defaultValue:!1,fn:function(t){var e,n=t.reference;var r=-1,o=!1,i=[],a={name:"tippyInlinePositioning",enabled:!0,phase:"afterWrite",fn:function(o){var a=o.state;t.props.inlinePositioning&&(-1!==i.indexOf(a.placement)&&(i=[]),e!==a.placement&&-1===i.indexOf(a.placement)&&(i.push(a.placement),t.setProps({getReferenceClientRect:function(){return function(t){return function(t,e,n,r){if(n.length<2||null===t)return e;if(2===n.length&&r>=0&&n[0].left>n[1].right)return n[r]||e;switch(t){case"top":case"bottom":var o=n[0],i=n[n.length-1],a="top"===t,s=o.top,u=i.bottom,p=a?o.left:i.left,c=a?o.right:i.right;return{top:s,bottom:u,left:p,right:c,width:c-p,height:u-s};case"left":case"right":var f=Math.min.apply(Math,n.map((function(t){return t.left}))),l=Math.max.apply(Math,n.map((function(t){return t.right}))),d=n.filter((function(e){return"left"===t?e.left===f:e.right===l})),v=d[0].top,m=d[d.length-1].bottom;return{top:v,bottom:m,left:f,right:l,width:l-f,height:m-v};default:return e}}(l(t),n.getBoundingClientRect(),d(n.getClientRects()),r)}(a.placement)}})),e=a.placement)}};function s(){var e;o||(e=function(t,e){var n;return{popperOptions:Object.assign({},t.popperOptions,{modifiers:[].concat(((null==(n=t.popperOptions)?void 0:n.modifiers)||[]).filter((function(t){return t.name!==e.name})),[e])})}}(t.props,a),o=!0,t.setProps(e),o=!1)}return{onCreate:s,onAfterUpdate:s,onTrigger:function(e,n){if(h(n)){var o=d(t.reference.getClientRects()),i=o.find((function(t){return t.left-2<=n.clientX&&t.right+2>=n.clientX&&t.top-2<=n.clientY&&t.bottom+2>=n.clientY})),a=o.indexOf(i);r=a>-1?a:r}},onHidden:function(){r=-1}}}};var Q={name:"sticky",defaultValue:!1,fn:function(t){var e=t.reference,n=t.popper;function r(e){return!0===t.props.sticky||t.props.sticky===e}var o=null,i=null;function a(){var s=r("reference")?(t.popperInstance?t.popperInstance.state.elements.reference:e).getBoundingClientRect():null,u=r("popper")?n.getBoundingClientRect():null;(s&&Z(o,s)||u&&Z(i,u))&&t.popperInstance&&t.popperInstance.update(),o=s,i=u,t.state.isMounted&&requestAnimationFrame(a)}return{onMount:function(){t.props.sticky&&a()}}}};function Z(t,e){return!t||!e||(t.top!==e.top||t.right!==e.right||t.bottom!==e.bottom||t.left!==e.left)}return e&&function(t){var e=document.createElement("style");e.textContent=t,e.setAttribute("data-tippy-stylesheet","");var n=document.head,r=document.querySelector("head>style,head>link");r?n.insertBefore(e,r):n.appendChild(e)}('.tippy-box[data-animation=fade][data-state=hidden]{opacity:0}[data-tippy-root]{max-width:calc(100vw - 10px)}.tippy-box{position:relative;background-color:#333;color:#fff;border-radius:4px;font-size:14px;line-height:1.4;white-space:normal;outline:0;transition-property:transform,visibility,opacity}.tippy-box[data-placement^=top]>.tippy-arrow{bottom:0}.tippy-box[data-placement^=top]>.tippy-arrow:before{bottom:-7px;left:0;border-width:8px 8px 0;border-top-color:initial;transform-origin:center top}.tippy-box[data-placement^=bottom]>.tippy-arrow{top:0}.tippy-box[data-placement^=bottom]>.tippy-arrow:before{top:-7px;left:0;border-width:0 8px 8px;border-bottom-color:initial;transform-origin:center bottom}.tippy-box[data-placement^=left]>.tippy-arrow{right:0}.tippy-box[data-placement^=left]>.tippy-arrow:before{border-width:8px 0 8px 8px;border-left-color:initial;right:-7px;transform-origin:center left}.tippy-box[data-placement^=right]>.tippy-arrow{left:0}.tippy-box[data-placement^=right]>.tippy-arrow:before{left:-7px;border-width:8px 8px 8px 0;border-right-color:initial;transform-origin:center right}.tippy-box[data-inertia][data-state=visible]{transition-timing-function:cubic-bezier(.54,1.5,.38,1.11)}.tippy-arrow{width:16px;height:16px;color:#333}.tippy-arrow:before{content:"";position:absolute;border-color:transparent;border-style:solid}.tippy-content{position:relative;padding:5px 9px;z-index:1}'),F.setDefaultProps({plugins:[Y,G,K,Q],render:N}),F.createSingleton=function(t,e){var n;void 0===e&&(e={});var r,o=t,i=[],a=[],s=e.overrides,u=[],f=!1;function l(){a=o.map((function(t){return c(t.props.triggerTarget||t.reference)})).reduce((function(t,e){return t.concat(e)}),[])}function d(){i=o.map((function(t){return t.reference}))}function v(t){o.forEach((function(e){t?e.enable():e.disable()}))}function g(t){return o.map((function(e){var n=e.setProps;return e.setProps=function(o){n(o),e.reference===r&&t.setProps(o)},function(){e.setProps=n}}))}function h(t,e){var n=a.indexOf(e);if(e!==r){r=e;var u=(s||[]).concat("content").reduce((function(t,e){return t[e]=o[n].props[e],t}),{});t.setProps(Object.assign({},u,{getReferenceClientRect:"function"==typeof u.getReferenceClientRect?u.getReferenceClientRect:function(){var t;return null==(t=i[n])?void 0:t.getBoundingClientRect()}}))}}v(!1),d(),l();var b={fn:function(){return{onDestroy:function(){v(!0)},onHidden:function(){r=null},onClickOutside:function(t){t.props.showOnCreate&&!f&&(f=!0,r=null)},onShow:function(t){t.props.showOnCreate&&!f&&(f=!0,h(t,i[0]))},onTrigger:function(t,e){h(t,e.currentTarget)}}}},y=F(m(),Object.assign({},p(e,["overrides"]),{plugins:[b].concat(e.plugins||[]),triggerTarget:a,popperOptions:Object.assign({},e.popperOptions,{modifiers:[].concat((null==(n=e.popperOptions)?void 0:n.modifiers)||[],[W])})})),w=y.show;y.show=function(t){if(w(),!r&&null==t)return h(y,i[0]);if(!r||null!=t){if("number"==typeof t)return i[t]&&h(y,i[t]);if(o.indexOf(t)>=0){var e=t.reference;return h(y,e)}return i.indexOf(t)>=0?h(y,t):void 0}},y.showNext=function(){var t=i[0];if(!r)return y.show(0);var e=i.indexOf(r);y.show(i[e+1]||t)},y.showPrevious=function(){var t=i[i.length-1];if(!r)return y.show(t);var e=i.indexOf(r),n=i[e-1]||t;y.show(n)};var x=y.setProps;return y.setProps=function(t){s=t.overrides||s,x(t)},y.setInstances=function(t){v(!0),u.forEach((function(t){return t()})),o=t,v(!1),d(),l(),u=g(y),y.setProps({triggerTarget:a})},u=g(y),y},F.delegate=function(t,e){var n=[],o=[],i=!1,a=e.target,s=p(e,["target"]),u=Object.assign({},s,{trigger:"manual",touch:!1}),f=Object.assign({touch:R.touch},s,{showOnCreate:!0}),l=F(t,u);function d(t){if(t.target&&!i){var n=t.target.closest(a);if(n){var r=n.getAttribute("data-tippy-trigger")||e.trigger||R.trigger;if(!n._tippy&&!("touchstart"===t.type&&"boolean"==typeof f.touch||"touchstart"!==t.type&&r.indexOf(X[t.type])<0)){var s=F(n,f);s&&(o=o.concat(s))}}}}function v(t,e,r,o){void 0===o&&(o=!1),t.addEventListener(e,r,o),n.push({node:t,eventType:e,handler:r,options:o})}return c(l).forEach((function(t){var e=t.destroy,a=t.enable,s=t.disable;t.destroy=function(t){void 0===t&&(t=!0),t&&o.forEach((function(t){t.destroy()})),o=[],n.forEach((function(t){var e=t.node,n=t.eventType,r=t.handler,o=t.options;e.removeEventListener(n,r,o)})),n=[],e()},t.enable=function(){a(),o.forEach((function(t){return t.enable()})),i=!1},t.disable=function(){s(),o.forEach((function(t){return t.disable()})),i=!0},function(t){var e=t.reference;v(e,"touchstart",d,r),v(e,"mouseover",d),v(e,"focusin",d),v(e,"click",d)}(t)})),l},F.hideAll=function(t){var e=void 0===t?{}:t,n=e.exclude,r=e.duration;_.forEach((function(t){var e=!1;if(n&&(e=b(n)?t.reference===n:t.popper===n.popper),!e){var o=t.props.duration;t.setProps({duration:r}),t.hide(),t.state.isDestroyed||t.setProps({duration:o})}}))},F.roundArrow='<svg width="16" height="6" xmlns="http://www.w3.org/2000/svg"><path d="M0 6s1.796-.013 4.67-3.615C5.851.9 6.93.006 8 0c1.07-.006 2.148.887 3.343 2.385C14.233 6.005 16 6 16 6H0z"></svg>',F})); //# sourceMappingURL=tippy-bundle.umd.min.js.map
25,805
Python
.py
5
5,159.4
25,667
0.698515
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,921
message_publish.py
zatosource_zato/code/zato-web-admin/src/zato/admin/static/brython/zato/message_publish.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Brython from browser import document as doc # Zato from zato.common.json_internal import loads # ################################################################################################################################ class SelectChanger(object): """ Links two SELECT fields so that changing value in one re-populates the other with associated values. """ def __init__(self, select_source, select_target, data_source='id_select_changer_source'): self.data_source = data_source self.select_source = doc[select_source] self.select_target = doc[select_target] self.data = None def run(self): self.data = loads(doc[self.data_source].text) self.select_source.bind('change', self.on_source_change) def on_source_change(self, e): value = e.srcElement.value value = self.data[value] if value else '' self.select_target.set_value(value) # ################################################################################################################################ sc = SelectChanger('id_topic_name', 'id_hook_service_name') sc.run() # ################################################################################################################################
1,424
Python
.py
29
44.551724
130
0.496387
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,922
subscription.py
zatosource_zato/code/zato-web-admin/src/zato/admin/static/brython/zato/subscription.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ row_prefix = 'endpoint_row_id_' # ################################################################################################################################
451
Python
.py
8
54.75
130
0.280822
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,923
__init__.py
zatosource_zato/code/patches/passlib/utils/__init__.py
"""passlib.utils -- helpers for writing password hashes""" #============================================================================= # imports #============================================================================= from passlib.utils.compat import JYTHON # core from binascii import b2a_base64, a2b_base64, Error as _BinAsciiError from base64 import b64encode, b64decode import collections from codecs import lookup as _lookup_codec from functools import update_wrapper import itertools import inspect import logging; log = logging.getLogger(__name__) import math import os import sys import random import re if JYTHON: # pragma: no cover -- runtime detection # Jython 2.5.2 lacks stringprep module - # see http://bugs.jython.org/issue1758320 try: import stringprep except ImportError: stringprep = None _stringprep_missing_reason = "not present under Jython" else: import stringprep import time if stringprep: import unicodedata import types from warnings import warn # site # pkg from passlib.utils.binary import ( # [remove these aliases in 2.0] BASE64_CHARS, AB64_CHARS, HASH64_CHARS, BCRYPT_CHARS, Base64Engine, LazyBase64Engine, h64, h64big, bcrypt64, ab64_encode, ab64_decode, b64s_encode, b64s_decode ) from passlib.utils.decor import ( # [remove these aliases in 2.0] deprecated_function, deprecated_method, memoized_property, classproperty, hybrid_method, ) from passlib.exc import ExpectedStringError from passlib.utils.compat import (add_doc, join_bytes, join_byte_values, join_byte_elems, irange, imap, PY3, u, join_unicode, unicode, byte_elem_value, nextgetter, unicode_or_bytes_types, get_method_function, suppress_cause) # local __all__ = [ # constants 'JYTHON', 'sys_bits', 'unix_crypt_schemes', 'rounds_cost_values', # unicode helpers 'consteq', 'saslprep', # bytes helpers "xor_bytes", "render_bytes", # encoding helpers 'is_same_codec', 'is_ascii_safe', 'to_bytes', 'to_unicode', 'to_native_str', # host OS 'has_crypt', 'test_crypt', 'safe_crypt', 'tick', # randomness 'rng', 'getrandbytes', 'getrandstr', 'generate_password', # object type / interface tests 'is_crypt_handler', 'is_crypt_context', 'has_rounds_info', 'has_salt_info', ] #============================================================================= # constants #============================================================================= # bitsize of system architecture (32 or 64) sys_bits = int(math.log(sys.maxsize if PY3 else sys.maxint, 2) + 1.5) # list of hashes algs supported by crypt() on at least one OS. # XXX: move to .registry for passlib 2.0? unix_crypt_schemes = [ "sha512_crypt", "sha256_crypt", "sha1_crypt", "bcrypt", "md5_crypt", # "bsd_nthash", "bsdi_crypt", "des_crypt", ] # list of rounds_cost constants rounds_cost_values = [ "linear", "log2" ] # legacy import, will be removed in 1.8 from passlib.exc import MissingBackendError # internal helpers _BEMPTY = b'' _UEMPTY = u("") _USPACE = u(" ") # maximum password size which passlib will allow; see exc.PasswordSizeError MAX_PASSWORD_SIZE = int(os.environ.get("PASSLIB_MAX_PASSWORD_SIZE") or 4096) #============================================================================= # type helpers #============================================================================= class SequenceMixin(object): """ helper which lets result object act like a fixed-length sequence. subclass just needs to provide :meth:`_as_tuple()`. """ def _as_tuple(self): raise NotImplemented("implement in subclass") def __repr__(self): return repr(self._as_tuple()) def __getitem__(self, idx): return self._as_tuple()[idx] def __iter__(self): return iter(self._as_tuple()) def __len__(self): return len(self._as_tuple()) def __eq__(self, other): return self._as_tuple() == other def __ne__(self, other): return not self.__eq__(other) if PY3: # getargspec() is deprecated, use this under py3. # even though it's a lot more awkward to get basic info :| _VAR_KEYWORD = inspect.Parameter.VAR_KEYWORD _VAR_ANY_SET = set([_VAR_KEYWORD, inspect.Parameter.VAR_POSITIONAL]) def accepts_keyword(func, key): """test if function accepts specified keyword""" params = inspect.signature(get_method_function(func)).parameters if not params: return False arg = params.get(key) if arg and arg.kind not in _VAR_ANY_SET: return True # XXX: annoying what we have to do to determine if VAR_KWDS in use. return params[list(params)[-1]].kind == _VAR_KEYWORD else: def accepts_keyword(func, key): """test if function accepts specified keyword""" spec = inspect.getargspec(get_method_function(func)) return key in spec.args or spec.keywords is not None def update_mixin_classes(target, add=None, remove=None, append=False, before=None, after=None, dryrun=False): """ helper to update mixin classes installed in target class. :param target: target class whose bases will be modified. :param add: class / classes to install into target's base class list. :param remove: class / classes to remove from target's base class list. :param append: by default, prepends mixins to front of list. if True, appends to end of list instead. :param after: optionally make sure all mixins are inserted after this class / classes. :param before: optionally make sure all mixins are inserted before this class / classes. :param dryrun: optionally perform all calculations / raise errors, but don't actually modify the class. """ if isinstance(add, type): add = [add] bases = list(target.__bases__) # strip out requested mixins if remove: if isinstance(remove, type): remove = [remove] for mixin in remove: if add and mixin in add: continue if mixin in bases: bases.remove(mixin) # add requested mixins if add: for mixin in add: # if mixin already present (explicitly or not), leave alone if any(issubclass(base, mixin) for base in bases): continue # determine insertion point if append: for idx, base in enumerate(bases): if issubclass(mixin, base): # don't insert mixin after one of it's own bases break if before and issubclass(base, before): # don't insert mixin after any <before> classes. break else: # append to end idx = len(bases) elif after: for end_idx, base in enumerate(reversed(bases)): if issubclass(base, after): # don't insert mixin before any <after> classes. idx = len(bases) - end_idx assert bases[idx-1] == base break else: idx = 0 else: # insert at start idx = 0 # insert mixin bases.insert(idx, mixin) # modify class if not dryrun: target.__bases__ = tuple(bases) #============================================================================= # collection helpers #============================================================================= def batch(source, size): """ split iterable into chunks of <size> elements. """ if size < 1: raise ValueError("size must be positive integer") if isinstance(source, collections.Sequence): end = len(source) i = 0 while i < end: n = i + size yield source[i:n] i = n elif isinstance(source, collections.Iterable): itr = iter(source) while True: chunk_itr = itertools.islice(itr, size) try: first = next(chunk_itr) except StopIteration: break yield itertools.chain((first,), chunk_itr) else: raise TypeError("source must be iterable") #============================================================================= # unicode helpers #============================================================================= # XXX: should this be moved to passlib.crypto, or compat backports? def consteq(left, right): """Check two strings/bytes for equality. This function uses an approach designed to prevent timing analysis, making it appropriate for cryptography. a and b must both be of the same type: either str (ASCII only), or any type that supports the buffer protocol (e.g. bytes). Note: If a and b are of different lengths, or if an error occurs, a timing attack could theoretically reveal information about the types and lengths of a and b--but not their values. """ # NOTE: # resources & discussions considered in the design of this function: # hmac timing attack -- # http://rdist.root.org/2009/05/28/timing-attack-in-google-keyczar-library/ # python developer discussion surrounding similar function -- # http://bugs.python.org/issue15061 # http://bugs.python.org/issue14955 # validate types if isinstance(left, unicode): if not isinstance(right, unicode): raise TypeError("inputs must be both unicode or both bytes") is_py3_bytes = False elif isinstance(left, bytes): if not isinstance(right, bytes): raise TypeError("inputs must be both unicode or both bytes") is_py3_bytes = PY3 else: raise TypeError("inputs must be both unicode or both bytes") # do size comparison. # NOTE: the double-if construction below is done deliberately, to ensure # the same number of operations (including branches) is performed regardless # of whether left & right are the same size. same_size = (len(left) == len(right)) if same_size: # if sizes are the same, setup loop to perform actual check of contents. tmp = left result = 0 if not same_size: # if sizes aren't the same, set 'result' so equality will fail regardless # of contents. then, to ensure we do exactly 'len(right)' iterations # of the loop, just compare 'right' against itself. tmp = right result = 1 # run constant-time string comparision # TODO: use izip instead (but first verify it's faster than zip for this case) if is_py3_bytes: for l,r in zip(tmp, right): result |= l ^ r else: for l,r in zip(tmp, right): result |= ord(l) ^ ord(r) return result == 0 # keep copy of this around since stdlib's version throws error on non-ascii chars in unicode strings. # our version does, but suffers from some underlying VM issues. but something is better than # nothing for plaintext hashes, which need this. everything else should use consteq(), # since the stdlib one is going to be as good / better in the general case. str_consteq = consteq try: # for py3.3 and up, use the stdlib version from hmac import compare_digest as consteq except ImportError: pass # TODO: could check for cryptography package's version, # but only operates on bytes, so would need a wrapper, # or separate consteq() into a unicode & a bytes variant. # from cryptography.hazmat.primitives.constant_time import bytes_eq as consteq def splitcomma(source, sep=","): """split comma-separated string into list of elements, stripping whitespace. """ source = source.strip() if source.endswith(sep): source = source[:-1] if not source: return [] return [ elem.strip() for elem in source.split(sep) ] def saslprep(source, param="value"): """Normalizes unicode strings using SASLPrep stringprep profile. The SASLPrep profile is defined in :rfc:`4013`. It provides a uniform scheme for normalizing unicode usernames and passwords before performing byte-value sensitive operations such as hashing. Among other things, it normalizes diacritic representations, removes non-printing characters, and forbids invalid characters such as ``\\n``. Properly internationalized applications should run user passwords through this function before hashing. :arg source: unicode string to normalize & validate :param param: Optional noun identifying source parameter in error messages (Defaults to the string ``"value"``). This is mainly useful to make the caller's error messages make more sense contextually. :raises ValueError: if any characters forbidden by the SASLPrep profile are encountered. :raises TypeError: if input is not :class:`!unicode` :returns: normalized unicode string .. note:: This function is not available under Jython, as the Jython stdlib is missing the :mod:`!stringprep` module (`Jython issue 1758320 <http://bugs.jython.org/issue1758320>`_). .. versionadded:: 1.6 """ # saslprep - http://tools.ietf.org/html/rfc4013 # stringprep - http://tools.ietf.org/html/rfc3454 # http://docs.python.org/library/stringprep.html # validate type # XXX: support bytes (e.g. run through want_unicode)? # might be easier to just integrate this into cryptcontext. if not isinstance(source, unicode): raise TypeError("input must be unicode string, not %s" % (type(source),)) # mapping stage # - map non-ascii spaces to U+0020 (stringprep C.1.2) # - strip 'commonly mapped to nothing' chars (stringprep B.1) in_table_c12 = stringprep.in_table_c12 in_table_b1 = stringprep.in_table_b1 data = join_unicode( _USPACE if in_table_c12(c) else c for c in source if not in_table_b1(c) ) # normalize to KC form data = unicodedata.normalize('NFKC', data) if not data: return _UEMPTY # check for invalid bi-directional strings. # stringprep requires the following: # - chars in C.8 must be prohibited. # - if any R/AL chars in string: # - no L chars allowed in string # - first and last must be R/AL chars # this checks if start/end are R/AL chars. if so, prohibited loop # will forbid all L chars. if not, prohibited loop will forbid all # R/AL chars instead. in both cases, prohibited loop takes care of C.8. is_ral_char = stringprep.in_table_d1 if is_ral_char(data[0]): if not is_ral_char(data[-1]): raise ValueError("malformed bidi sequence in " + param) # forbid L chars within R/AL sequence. is_forbidden_bidi_char = stringprep.in_table_d2 else: # forbid R/AL chars if start not setup correctly; L chars allowed. is_forbidden_bidi_char = is_ral_char # check for prohibited output - stringprep tables A.1, B.1, C.1.2, C.2 - C.9 in_table_a1 = stringprep.in_table_a1 in_table_c21_c22 = stringprep.in_table_c21_c22 in_table_c3 = stringprep.in_table_c3 in_table_c4 = stringprep.in_table_c4 in_table_c5 = stringprep.in_table_c5 in_table_c6 = stringprep.in_table_c6 in_table_c7 = stringprep.in_table_c7 in_table_c8 = stringprep.in_table_c8 in_table_c9 = stringprep.in_table_c9 for c in data: # check for chars mapping stage should have removed assert not in_table_b1(c), "failed to strip B.1 in mapping stage" assert not in_table_c12(c), "failed to replace C.1.2 in mapping stage" # check for forbidden chars if in_table_a1(c): raise ValueError("unassigned code points forbidden in " + param) if in_table_c21_c22(c): raise ValueError("control characters forbidden in " + param) if in_table_c3(c): raise ValueError("private use characters forbidden in " + param) if in_table_c4(c): raise ValueError("non-char code points forbidden in " + param) if in_table_c5(c): raise ValueError("surrogate codes forbidden in " + param) if in_table_c6(c): raise ValueError("non-plaintext chars forbidden in " + param) if in_table_c7(c): # XXX: should these have been caught by normalize? # if so, should change this to an assert raise ValueError("non-canonical chars forbidden in " + param) if in_table_c8(c): raise ValueError("display-modifying / deprecated chars " "forbidden in" + param) if in_table_c9(c): raise ValueError("tagged characters forbidden in " + param) # do bidi constraint check chosen by bidi init, above if is_forbidden_bidi_char(c): raise ValueError("forbidden bidi character in " + param) return data # replace saslprep() with stub when stringprep is missing if stringprep is None: # pragma: no cover -- runtime detection def saslprep(source, param="value"): """stub for saslprep()""" raise NotImplementedError("saslprep() support requires the 'stringprep' " "module, which is " + _stringprep_missing_reason) #============================================================================= # bytes helpers #============================================================================= def render_bytes(source, *args): """Peform ``%`` formating using bytes in a uniform manner across Python 2/3. This function is motivated by the fact that :class:`bytes` instances do not support ``%`` or ``{}`` formatting under Python 3. This function is an attempt to provide a replacement: it converts everything to unicode (decoding bytes instances as ``latin-1``), performs the required formatting, then encodes the result to ``latin-1``. Calling ``render_bytes(source, *args)`` should function roughly the same as ``source % args`` under Python 2. """ if isinstance(source, bytes): source = source.decode("latin-1") result = source % tuple(arg.decode("latin-1") if isinstance(arg, bytes) else arg for arg in args) return result.encode("latin-1") if PY3: # new in py32 def bytes_to_int(value): return int.from_bytes(value, 'big') def int_to_bytes(value, count): return value.to_bytes(count, 'big') else: # XXX: can any of these be sped up? from binascii import hexlify, unhexlify def bytes_to_int(value): return int(hexlify(value),16) def int_to_bytes(value, count): return unhexlify(('%%0%dx' % (count<<1)) % value) add_doc(bytes_to_int, "decode byte string as single big-endian integer") add_doc(int_to_bytes, "encode integer as single big-endian byte string") def xor_bytes(left, right): """Perform bitwise-xor of two byte strings (must be same size)""" return int_to_bytes(bytes_to_int(left) ^ bytes_to_int(right), len(left)) def repeat_string(source, size): """repeat or truncate <source> string, so it has length <size>""" cur = len(source) if size > cur: mult = (size+cur-1)//cur return (source*mult)[:size] else: return source[:size] _BNULL = b"\x00" _UNULL = u("\x00") def right_pad_string(source, size, pad=None): """right-pad or truncate <source> string, so it has length <size>""" cur = len(source) if size > cur: if pad is None: pad = _UNULL if isinstance(source, unicode) else _BNULL return source+pad*(size-cur) else: return source[:size] #============================================================================= # encoding helpers #============================================================================= _ASCII_TEST_BYTES = b"\x00\n aA:#!\x7f" _ASCII_TEST_UNICODE = _ASCII_TEST_BYTES.decode("ascii") def is_ascii_codec(codec): """Test if codec is compatible with 7-bit ascii (e.g. latin-1, utf-8; but not utf-16)""" return _ASCII_TEST_UNICODE.encode(codec) == _ASCII_TEST_BYTES def is_same_codec(left, right): """Check if two codec names are aliases for same codec""" if left == right: return True if not (left and right): return False return _lookup_codec(left).name == _lookup_codec(right).name _B80 = b'\x80'[0] _U80 = u('\x80') def is_ascii_safe(source): """Check if string (bytes or unicode) contains only 7-bit ascii""" r = _B80 if isinstance(source, bytes) else _U80 return all(c < r for c in source) def to_bytes(source, encoding="utf-8", param="value", source_encoding=None): """Helper to normalize input to bytes. :arg source: Source bytes/unicode to process. :arg encoding: Target encoding (defaults to ``"utf-8"``). :param param: Optional name of variable/noun to reference when raising errors :param source_encoding: If this is specified, and the source is bytes, the source will be transcoded from *source_encoding* to *encoding* (via unicode). :raises TypeError: if source is not unicode or bytes. :returns: * unicode strings will be encoded using *encoding*, and returned. * if *source_encoding* is not specified, byte strings will be returned unchanged. * if *source_encoding* is specified, byte strings will be transcoded to *encoding*. """ assert encoding if isinstance(source, bytes): if source_encoding and not is_same_codec(source_encoding, encoding): return source.decode(source_encoding).encode(encoding) else: return source elif isinstance(source, unicode): return source.encode(encoding) else: raise ExpectedStringError(source, param) def to_unicode(source, encoding="utf-8", param="value"): """Helper to normalize input to unicode. :arg source: source bytes/unicode to process. :arg encoding: encoding to use when decoding bytes instances. :param param: optional name of variable/noun to reference when raising errors. :raises TypeError: if source is not unicode or bytes. :returns: * returns unicode strings unchanged. * returns bytes strings decoded using *encoding* """ assert encoding if isinstance(source, unicode): return source elif isinstance(source, bytes): return source.decode(encoding) else: raise ExpectedStringError(source, param) if PY3: def to_native_str(source, encoding="utf-8", param="value"): if isinstance(source, bytes): return source.decode(encoding) elif isinstance(source, unicode): return source else: raise ExpectedStringError(source, param) else: def to_native_str(source, encoding="utf-8", param="value"): if isinstance(source, bytes): return source elif isinstance(source, unicode): return source.encode(encoding) else: raise ExpectedStringError(source, param) add_doc(to_native_str, """Take in unicode or bytes, return native string. Python 2: encodes unicode using specified encoding, leaves bytes alone. Python 3: leaves unicode alone, decodes bytes using specified encoding. :raises TypeError: if source is not unicode or bytes. :arg source: source unicode or bytes string. :arg encoding: encoding to use when encoding unicode or decoding bytes. this defaults to ``"utf-8"``. :param param: optional name of variable/noun to reference when raising errors. :returns: :class:`str` instance """) @deprecated_function(deprecated="1.6", removed="1.7") def to_hash_str(source, encoding="ascii"): # pragma: no cover -- deprecated & unused """deprecated, use to_native_str() instead""" return to_native_str(source, encoding, param="hash") _true_set = set("true t yes y on 1 enable enabled".split()) _false_set = set("false f no n off 0 disable disabled".split()) _none_set = set(["", "none"]) def as_bool(value, none=None, param="boolean"): """ helper to convert value to boolean. recognizes strings such as "true", "false" """ assert none in [True, False, None] if isinstance(value, unicode_or_bytes_types): clean = value.lower().strip() if clean in _true_set: return True if clean in _false_set: return False if clean in _none_set: return none raise ValueError("unrecognized %s value: %r" % (param, value)) elif isinstance(value, bool): return value elif value is None: return none else: return bool(value) #============================================================================= # host OS helpers #============================================================================= try: from crypt import crypt as _crypt except ImportError: # pragma: no cover _crypt = None has_crypt = False def safe_crypt(secret, hash): return None else: has_crypt = True _NULL = '\x00' # some crypt() variants will return various constant strings when # an invalid/unrecognized config string is passed in; instead of # returning NULL / None. examples include ":", ":0", "*0", etc. # safe_crypt() returns None for any string starting with one of the # chars in this string... _invalid_prefixes = u("*:!") if PY3: def safe_crypt(secret, hash): if isinstance(secret, bytes): # Python 3's crypt() only accepts unicode, which is then # encoding using utf-8 before passing to the C-level crypt(). # so we have to decode the secret. orig = secret try: secret = secret.decode("utf-8") except UnicodeDecodeError: return None assert secret.encode("utf-8") == orig, \ "utf-8 spec says this can't happen!" if _NULL in secret: raise ValueError("null character in secret") if isinstance(hash, bytes): hash = hash.decode("ascii") result = _crypt(secret, hash) if not result or result[0] in _invalid_prefixes: return None return result else: def safe_crypt(secret, hash): if isinstance(secret, unicode): secret = secret.encode("utf-8") if _NULL in secret: raise ValueError("null character in secret") if isinstance(hash, unicode): hash = hash.encode("ascii") result = _crypt(secret, hash) if not result: return None result = result.decode("ascii") if result[0] in _invalid_prefixes: return None return result add_doc(safe_crypt, """Wrapper around stdlib's crypt. This is a wrapper around stdlib's :func:`!crypt.crypt`, which attempts to provide uniform behavior across Python 2 and 3. :arg secret: password, as bytes or unicode (unicode will be encoded as ``utf-8``). :arg hash: hash or config string, as ascii bytes or unicode. :returns: resulting hash as ascii unicode; or ``None`` if the password couldn't be hashed due to one of the issues: * :func:`crypt()` not available on platform. * Under Python 3, if *secret* is specified as bytes, it must be use ``utf-8`` or it can't be passed to :func:`crypt()`. * Some OSes will return ``None`` if they don't recognize the algorithm being used (though most will simply fall back to des-crypt). * Some OSes will return an error string if the input config is recognized but malformed; current code converts these to ``None`` as well. """) def test_crypt(secret, hash): """check if :func:`crypt.crypt` supports specific hash :arg secret: password to test :arg hash: known hash of password to use as reference :returns: True or False """ assert secret and hash return safe_crypt(secret, hash) == hash # pick best timer function to expose as "tick" - lifted from timeit module. if sys.platform == "win32": # On Windows, the best timer is time.clock() from time import time as timer else: # On most other platforms the best timer is time.time() from time import time as timer # legacy alias, will be removed in passlib 2.0 tick = timer def parse_version(source): """helper to parse version string""" m = re.search(r"(\d+(?:\.\d+)+)", source) if m: return tuple(int(elem) for elem in m.group(1).split(".")) return None #============================================================================= # randomness #============================================================================= #------------------------------------------------------------------------ # setup rng for generating salts #------------------------------------------------------------------------ # NOTE: # generating salts (e.g. h64_gensalt, below) doesn't require cryptographically # strong randomness. it just requires enough range of possible outputs # that making a rainbow table is too costly. so it should be ok to # fall back on python's builtin mersenne twister prng, as long as it's seeded each time # this module is imported, using a couple of minor entropy sources. try: os.urandom(1) has_urandom = True except NotImplementedError: # pragma: no cover has_urandom = False def genseed(value=None): """generate prng seed value from system resources""" from hashlib import sha512 if hasattr(value, "getstate") and hasattr(value, "getrandbits"): # caller passed in RNG as seed value try: value = value.getstate() except NotImplementedError: # this method throws error for e.g. SystemRandom instances, # so fall back to extracting 4k of state value = value.getrandbits(1 << 15) text = u("%s %s %s %.15f %.15f %s") % ( # if caller specified a seed value, mix it in value, # add current process id # NOTE: not available in some environments, e.g. GAE os.getpid() if hasattr(os, "getpid") else None, # id of a freshly created object. # (at least 1 byte of which should be hard to predict) id(object()), # the current time, to whatever precision os uses time.time(), time.clock(), # if urandom available, might as well mix some bytes in. os.urandom(32).decode("latin-1") if has_urandom else 0, ) # hash it all up and return it as int/long return int(sha512(text.encode("utf-8")).hexdigest(), 16) if has_urandom: rng = random.SystemRandom() else: # pragma: no cover -- runtime detection # NOTE: to reseed use ``rng.seed(genseed(rng))`` # XXX: could reseed on every call rng = random.Random(genseed()) #------------------------------------------------------------------------ # some rng helpers #------------------------------------------------------------------------ def getrandbytes(rng, count): """return byte-string containing *count* number of randomly generated bytes, using specified rng""" # NOTE: would be nice if this was present in stdlib Random class ###just in case rng provides this... ##meth = getattr(rng, "getrandbytes", None) ##if meth: ## return meth(count) if not count: return _BEMPTY def helper(): # XXX: break into chunks for large number of bits? value = rng.getrandbits(count<<3) i = 0 while i < count: yield value & 0xff value >>= 3 i += 1 return join_byte_values(helper()) def getrandstr(rng, charset, count): """return string containing *count* number of chars/bytes, whose elements are drawn from specified charset, using specified rng""" # NOTE: tests determined this is 4x faster than rng.sample(), # which is why that's not being used here. # check alphabet & count if count < 0: raise ValueError("count must be >= 0") letters = len(charset) if letters == 0: raise ValueError("alphabet must not be empty") if letters == 1: return charset * count # get random value, and write out to buffer def helper(): # XXX: break into chunks for large number of letters? value = rng.randrange(0, letters**count) i = 0 while i < count: yield charset[value % letters] value //= letters i += 1 if isinstance(charset, unicode): return join_unicode(helper()) else: return join_byte_elems(helper()) _52charset = '2346789ABCDEFGHJKMNPQRTUVWXYZabcdefghjkmnpqrstuvwxyz' @deprecated_function(deprecated="1.7", removed="2.0", replacement="passlib.pwd.genword() / passlib.pwd.genphrase()") def generate_password(size=10, charset=_52charset): """generate random password using given length & charset :param size: size of password. :param charset: optional string specified set of characters to draw from. the default charset contains all normal alphanumeric characters, except for the characters ``1IiLl0OoS5``, which were omitted due to their visual similarity. :returns: :class:`!str` containing randomly generated password. .. note:: Using the default character set, on a OS with :class:`!SystemRandom` support, this function should generate passwords with 5.7 bits of entropy per character. """ return getrandstr(rng, charset, size) #============================================================================= # object type / interface tests #============================================================================= _handler_attrs = ( "name", "setting_kwds", "context_kwds", "verify", "hash", "identify", ) def is_crypt_handler(obj): """check if object follows the :ref:`password-hash-api`""" # XXX: change to use isinstance(obj, PasswordHash) under py26+? return all(hasattr(obj, name) for name in _handler_attrs) _context_attrs = ( "needs_update", "genconfig", "genhash", "verify", "encrypt", "identify", ) def is_crypt_context(obj): """check if object appears to be a :class:`~passlib.context.CryptContext` instance""" # XXX: change to use isinstance(obj, CryptContext)? return all(hasattr(obj, name) for name in _context_attrs) ##def has_many_backends(handler): ## "check if handler provides multiple baceknds" ## # NOTE: should also provide get_backend(), .has_backend(), and .backends attr ## return hasattr(handler, "set_backend") def has_rounds_info(handler): """check if handler provides the optional :ref:`rounds information <rounds-attributes>` attributes""" return ('rounds' in handler.setting_kwds and getattr(handler, "min_rounds", None) is not None) def has_salt_info(handler): """check if handler provides the optional :ref:`salt information <salt-attributes>` attributes""" return ('salt' in handler.setting_kwds and getattr(handler, "min_salt_size", None) is not None) ##def has_raw_salt(handler): ## "check if handler takes in encoded salt as unicode (False), or decoded salt as bytes (True)" ## sc = getattr(handler, "salt_chars", None) ## if sc is None: ## return None ## elif isinstance(sc, unicode): ## return False ## elif isinstance(sc, bytes): ## return True ## else: ## raise TypeError("handler.salt_chars must be None/unicode/bytes") #============================================================================= # eof #=============================================================================
36,864
Python
.py
894
34.231544
134
0.608433
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,924
__init__.py
zatosource_zato/code/patches/butler/__init__.py
import warnings __version__ = "0.9111" __license__ = "BSD" __contact__ = "atmb4u at gmail dot com" class Butler(object): def __init__(self, obj): """ Initiates with the list or dict object obj """ self.obj = obj def __getitem__(self, path): """ Grab values inside nested dict and list if available, else returns None Returns None if looking up in string. keys: A list of names or ids >>> data1 = Butler({"key": "value"}) >>> data1.get(["key"]) 'value' >>> data2 = Butler([1, 2, 4, 5, [10, 20, 30, 40, 50]]) >>> data2.__getitem__([4, 3]) 40 >>> data2.get([4, 9]) >>> data3 = Butler("Hello world") >>> data3.get([6]) """ return_obj = self.obj for key in path: if isinstance(return_obj, (list, dict)): return_obj = return_obj[key] else: return None return return_obj def get(self, path, default=None): """ Grab values inside nested dict and list if available, else returns None Returns None if looking up in string. keys: A list of names or ids >>> data1 = Butler({"key": "value"}) >>> data1.get(["key"]) 'value' >>> data2 = Butler([1, 2, 4, 5, [10, 20, 30, 40, 50]]) >>> data2.get([4, 3]) 40 >>> data2.get([4, 9]) >>> data3 = Butler("Hello world") >>> data3.get([6]) >>> data2.get([4, 10], default="BLANK") 'BLANK' >>> data2.get([4, 42], 0) 0 """ try: return self[path] except (LookupError, TypeError): warnings.warn("Could not find the requested element", UserWarning) return default def path_exists(self, path): """ >>> data = {'a':1, 'b':2, 'c': {'d': 4, 'e': 5, 'f': [6, 7, 8], 'g':[{'h': 8, 'i': 9, 'j': 10}, {'a':11, ... 'b': 12, 'c': 13}]}, 'n': [14, 15, 16, 17, 18]} >>> quick = Butler(data) >>> quick.path_exists(['c','g',0,'k']) False >>> quick.path_exists(['c','g',0,'j']) True >>> Butler({'tricky': False}).path_exists(['tricky']) True """ try: self[path] return True except KeyError: return False def key_list(self, sub_dict=None, output=None): """ Flattens the sub_dict argument. Internal API used with find and findall functions. >>> data = {'a':10, 'b':[{'c':11, 'd': 13}, {'d':14, 'e':15}]} >>> quick = Butler(data) >>> quick.flatten(data) [('a', 10), ('b', [{'c': 11, 'd': 13}, {'e': 15, 'd': 14}]), (0, {'c': 11, 'd': 13}), ('c', 11), ('d', 13), (1, {'e': 15, 'd': 14}), ('e', 15), ('d', 14)] """ if not sub_dict: sub_dict = self.obj if not output: output = [] for key in sub_dict: if isinstance(sub_dict[key], dict): self.flatten(sub_dict[key], output) if isinstance(sub_dict[key], list): for sub_dic in sub_dict[key]: if isinstance(sub_dic, dict): self.flatten(sub_dic, output) output.append(key) return output def flatten(self, sub_dict=None, output=None): """ TODO: Make use of generators Flattens the sub_dict argument. Internal API used with find and findall functions. >>> data = {'a':10, 'b':[{'c':11, 'd': 13}, {'d':14, 'e':15}]} >>> quick = Butler(data) >>> quick.flatten(data) [('a', 10), ('b', [{'c': 11, 'd': 13}, {'e': 15, 'd': 14}]), (0, {'c': 11, 'd': 13}), ('c', 11), ('d', 13), (1, {'e': 15, 'd': 14}), ('e', 15), ('d', 14)] """ if not sub_dict: sub_dict = self.obj if not output: output = [] if isinstance(sub_dict, dict): for key in sub_dict: output.append((key, sub_dict[key],)) self.flatten(sub_dict[key], output) elif isinstance(sub_dict, list): for order, element in enumerate(sub_dict): output.append((order, element,)) self.flatten(element, output) return output def findall(self, key, find=False): """ >>> data = {'a':1, 'b':2, 'c': {'d': 4, 'e': 5, 'f': [6, 7, 8], 'g':[{'h': 8, 'i': 9, 'j': 10}, {'a':11, ... 'b': 12, 'c': 13}]}, 'n': [14, 15, 16, 17, 18]} >>> quick = Butler(data) >>> quick.findall('a') [1, 11] >>> new_list = [1, 2, 3, 4, [1,2,3,4], 5] >>> quick1 = Butler(new_list) >>> quick1.findall(4) [[1, 2, 3, 4]] >>> quick1.findall(5) [5] >>> Butler([{42: 'nope'}]).findall(42) ['nope'] """ return_list = [] if isinstance(self.obj, dict) or isinstance(self.obj, list): flat_list = self.flatten(self.obj) for item_key, data in flat_list: if item_key == key: if find: # API for find() to return the first result return data return_list.append(data) else: print("findall can be used only with dict or list objects") return return_list def find(self, key): """ Works only with dict, Input key: The key to be searched for >>> data = {'a':1, 'b':2, 'c': {'d': 4, 'e': 5, 'f': [6, 7, 8], 'g':[{'h': 8, 'i': 9, 'j': 10}, {'a':11, ... 'b': 12, 'c': 13}]}, 'n': [14, 15, 16, 17, 18]} >>> quick = Butler(data) >>> quick.find('a') 1 >>> quick.find('e') 5 >>> quick.find('w') >>> new_list = [1, 2, 3, 4, 5] >>> quick1 = Butler(new_list) >>> quick1.find(2) 3 """ data = self.findall(key, find=True) if data: return data return None def key_exists(self, key): """ Uses find function to see if the requested key is in the dictionary Returns: True or False >>> data = {'a':1, 'b':2, 'c': {'d': 4, 'e': 5, 'f': [6, 7, 8], 'g':[{'h': 8, 'i': 9, 'j': 10}, {'a':11, ... 'b': 12, 'c': 13}]}, 'n': [14, 15, 16, 17, 18]} >>> quick = Butler(data) >>> quick.key_exists('a') True >>> quick.key_exists('w') False >>> Butler({'name': False}).key_exists('name') True """ if key in self.key_list(self.obj): return True else: return False
6,735
Python
.py
185
26.367568
162
0.454559
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,925
geventserver.py
zatosource_zato/code/patches/ws4py/server/geventserver.py
# -*- coding: utf-8 -*- __doc__ = """ WSGI entities to support WebSocket from within gevent. Its usage is rather simple: .. code-block: python from gevent import monkey; monkey.patch_all() from ws4py.websocket import EchoWebSocket from ws4py.server.geventserver import WSGIServer from ws4py.server.wsgiutils import WebSocketWSGIApplication server = WSGIServer(('localhost', 9000), WebSocketWSGIApplication(handler_cls=EchoWebSocket)) server.serve_forever() """ import logging import gevent from gevent.pywsgi import WSGIHandler, WSGIServer as _WSGIServer from gevent.pool import Pool from ws4py import format_addresses from ws4py.server.wsgiutils import WebSocketWSGIApplication logger = logging.getLogger('ws4py') __all__ = ['WebSocketWSGIHandler', 'WSGIServer', 'GEventWebSocketPool'] class WebSocketWSGIHandler(WSGIHandler): """ A WSGI handler that will perform the :rfc:`6455` upgrade and handshake before calling the WSGI application. If the incoming request doesn't have a `'Upgrade'` header, the handler will simply fallback to the gevent builtin's handler and process it as per usual. """ def run_application(self): upgrade_header = self.environ.get('HTTP_UPGRADE', '').lower() if upgrade_header: # Build and start the HTTP response self.environ['ws4py.socket'] = self.socket or self.environ['wsgi.input'].rfile._sock self.result = self.application(self.environ, self.start_response) or [] self.process_result() del self.environ['ws4py.socket'] self.socket = None self.rfile.close() ws = self.environ.pop('ws4py.websocket', None) if ws: ws_greenlet = self.server.pool.track(ws) # issue #170 # in gevent 1.1 socket will be closed once application returns # so let's wait for websocket handler to finish ws_greenlet.join() else: gevent.pywsgi.WSGIHandler.run_application(self) class GEventWebSocketPool(Pool): """ Simple pool of bound websockets. Internally it uses a gevent group to track the websockets. The server should call the ``clear`` method to initiate the closing handshake when the server is shutdown. """ def track(self, websocket): return self.spawn(websocket.run) def clear(self): for greenlet in list(self): try: websocket = greenlet._run.im_self if websocket: websocket.close(1001, 'Server is shutting down') except: pass finally: self.discard(greenlet) class WSGIServer(_WSGIServer): handler_class = WebSocketWSGIHandler def __init__(self, *args, **kwargs): """ WSGI server that simply tracks websockets and send them a proper closing handshake when the server terminates. Other than that, the server is the same as its :class:`gevent.pywsgi.WSGIServer` base. """ _WSGIServer.__init__(self, *args, **kwargs) self.pool = GEventWebSocketPool() def stop(self, *args, **kwargs): self.pool.clear() _WSGIServer.stop(self, *args, **kwargs) if __name__ == '__main__': from ws4py import configure_logger configure_logger() from ws4py.websocket import EchoWebSocket server = WSGIServer(('127.0.0.1', 9000), WebSocketWSGIApplication(handler_cls=EchoWebSocket)) server.serve_forever()
3,639
Python
.py
91
31.923077
97
0.655966
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,926
core.py
zatosource_zato/code/patches/pg8000/core.py
from datetime import ( timedelta as Timedelta, datetime as Datetime, date, time) from warnings import warn import socket from struct import pack from hashlib import md5 from decimal import Decimal from collections import deque, defaultdict from itertools import count, islice from uuid import UUID from copy import deepcopy from calendar import timegm from distutils.version import LooseVersion from struct import Struct from time import localtime import pg8000 from json import loads, dumps from os import getpid from pg8000.pg_scram import Auth import enum from ipaddress import ( ip_address, IPv4Address, IPv6Address, ip_network, IPv4Network, IPv6Network) from datetime import timezone as Timezone # Copyright (c) 2007-2009, Mathieu Fenniak # Copyright (c) The Contributors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. __author__ = "Mathieu Fenniak" ZERO = Timedelta(0) BINARY = bytes class Interval(): """An Interval represents a measurement of time. In PostgreSQL, an interval is defined in the measure of months, days, and microseconds; as such, the pg8000 interval type represents the same information. Note that values of the :attr:`microseconds`, :attr:`days` and :attr:`months` properties are independently measured and cannot be converted to each other. A month may be 28, 29, 30, or 31 days, and a day may occasionally be lengthened slightly by a leap second. .. attribute:: microseconds Measure of microseconds in the interval. The microseconds value is constrained to fit into a signed 64-bit integer. Any attempt to set a value too large or too small will result in an OverflowError being raised. .. attribute:: days Measure of days in the interval. The days value is constrained to fit into a signed 32-bit integer. Any attempt to set a value too large or too small will result in an OverflowError being raised. .. attribute:: months Measure of months in the interval. The months value is constrained to fit into a signed 32-bit integer. Any attempt to set a value too large or too small will result in an OverflowError being raised. """ def __init__(self, microseconds=0, days=0, months=0): self.microseconds = microseconds self.days = days self.months = months def _setMicroseconds(self, value): if not isinstance(value, int): raise TypeError("microseconds must be an integer type") elif not (min_int8 < value < max_int8): raise OverflowError( "microseconds must be representable as a 64-bit integer") else: self._microseconds = value def _setDays(self, value): if not isinstance(value, int): raise TypeError("days must be an integer type") elif not (min_int4 < value < max_int4): raise OverflowError( "days must be representable as a 32-bit integer") else: self._days = value def _setMonths(self, value): if not isinstance(value, int): raise TypeError("months must be an integer type") elif not (min_int4 < value < max_int4): raise OverflowError( "months must be representable as a 32-bit integer") else: self._months = value microseconds = property(lambda self: self._microseconds, _setMicroseconds) days = property(lambda self: self._days, _setDays) months = property(lambda self: self._months, _setMonths) def __repr__(self): return "<Interval %s months %s days %s microseconds>" % ( self.months, self.days, self.microseconds) def __eq__(self, other): return other is not None and isinstance(other, Interval) and \ self.months == other.months and self.days == other.days and \ self.microseconds == other.microseconds def __neq__(self, other): return not self.__eq__(other) class PGType(): def __init__(self, value): self.value = value def encode(self, encoding): return str(self.value).encode(encoding) class PGEnum(PGType): def __init__(self, value): if isinstance(value, str): self.value = value else: self.value = value.value class PGJson(PGType): def encode(self, encoding): return dumps(self.value).encode(encoding) class PGJsonb(PGType): def encode(self, encoding): return dumps(self.value).encode(encoding) class PGTsvector(PGType): pass class PGVarchar(str): pass class PGText(str): pass def pack_funcs(fmt): struc = Struct('!' + fmt) return struc.pack, struc.unpack_from i_pack, i_unpack = pack_funcs('i') h_pack, h_unpack = pack_funcs('h') q_pack, q_unpack = pack_funcs('q') d_pack, d_unpack = pack_funcs('d') f_pack, f_unpack = pack_funcs('f') iii_pack, iii_unpack = pack_funcs('iii') ii_pack, ii_unpack = pack_funcs('ii') qii_pack, qii_unpack = pack_funcs('qii') dii_pack, dii_unpack = pack_funcs('dii') ihihih_pack, ihihih_unpack = pack_funcs('ihihih') ci_pack, ci_unpack = pack_funcs('ci') bh_pack, bh_unpack = pack_funcs('bh') cccc_pack, cccc_unpack = pack_funcs('cccc') min_int2, max_int2 = -2 ** 15, 2 ** 15 min_int4, max_int4 = -2 ** 31, 2 ** 31 min_int8, max_int8 = -2 ** 63, 2 ** 63 class Warning(Exception): """Generic exception raised for important database warnings like data truncations. This exception is not currently used by pg8000. This exception is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ pass class Error(Exception): """Generic exception that is the base exception of all other error exceptions. This exception is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ pass class InterfaceError(Error): """Generic exception raised for errors that are related to the database interface rather than the database itself. For example, if the interface attempts to use an SSL connection but the server refuses, an InterfaceError will be raised. This exception is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ pass class DatabaseError(Error): """Generic exception raised for errors that are related to the database. This exception is currently never raised by pg8000. This exception is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ pass class DataError(DatabaseError): """Generic exception raised for errors that are due to problems with the processed data. This exception is not currently raised by pg8000. This exception is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ pass class OperationalError(DatabaseError): """ Generic exception raised for errors that are related to the database's operation and not necessarily under the control of the programmer. This exception is currently never raised by pg8000. This exception is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ pass class IntegrityError(DatabaseError): """ Generic exception raised when the relational integrity of the database is affected. This exception is not currently raised by pg8000. This exception is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ pass class InternalError(DatabaseError): """Generic exception raised when the database encounters an internal error. This is currently only raised when unexpected state occurs in the pg8000 interface itself, and is typically the result of a interface bug. This exception is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ pass class ProgrammingError(DatabaseError): """Generic exception raised for programming errors. For example, this exception is raised if more parameter fields are in a query string than there are available parameters. This exception is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ pass class NotSupportedError(DatabaseError): """Generic exception raised in case a method or database API was used which is not supported by the database. This exception is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ pass class ArrayContentNotSupportedError(NotSupportedError): """ Raised when attempting to transmit an array where the base type is not supported for binary data transfer by the interface. """ pass class ArrayContentNotHomogenousError(ProgrammingError): """ Raised when attempting to transmit an array that doesn't contain only a single type of object. """ pass class ArrayDimensionsNotConsistentError(ProgrammingError): """ Raised when attempting to transmit an array that has inconsistent multi-dimension sizes. """ pass def Date(year, month, day): """Constuct an object holding a date value. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :rtype: :class:`datetime.date` """ return date(year, month, day) def Time(hour, minute, second): """Construct an object holding a time value. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :rtype: :class:`datetime.time` """ return time(hour, minute, second) def Timestamp(year, month, day, hour, minute, second): """Construct an object holding a timestamp value. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :rtype: :class:`datetime.datetime` """ return Datetime(year, month, day, hour, minute, second) def DateFromTicks(ticks): """Construct an object holding a date value from the given ticks value (number of seconds since the epoch). This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :rtype: :class:`datetime.date` """ return Date(*localtime(ticks)[:3]) def TimeFromTicks(ticks): """Construct an objet holding a time value from the given ticks value (number of seconds since the epoch). This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :rtype: :class:`datetime.time` """ return Time(*localtime(ticks)[3:6]) def TimestampFromTicks(ticks): """Construct an object holding a timestamp value from the given ticks value (number of seconds since the epoch). This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :rtype: :class:`datetime.datetime` """ return Timestamp(*localtime(ticks)[:6]) def Binary(value): """Construct an object holding binary data. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ return value FC_TEXT = 0 FC_BINARY = 1 def convert_paramstyle(style, query): # I don't see any way to avoid scanning the query string char by char, # so we might as well take that careful approach and create a # state-based scanner. We'll use int variables for the state. OUTSIDE = 0 # outside quoted string INSIDE_SQ = 1 # inside single-quote string '...' INSIDE_QI = 2 # inside quoted identifier "..." INSIDE_ES = 3 # inside escaped single-quote string, E'...' INSIDE_PN = 4 # inside parameter name eg. :name INSIDE_CO = 5 # inside inline comment eg. -- in_quote_escape = False in_param_escape = False placeholders = [] output_query = [] param_idx = map(lambda x: "$" + str(x), count(1)) state = OUTSIDE prev_c = None for i, c in enumerate(query): if i + 1 < len(query): next_c = query[i + 1] else: next_c = None if state == OUTSIDE: if c == "'": output_query.append(c) if prev_c == 'E': state = INSIDE_ES else: state = INSIDE_SQ elif c == '"': output_query.append(c) state = INSIDE_QI elif c == '-': output_query.append(c) if prev_c == '-': state = INSIDE_CO elif style == "qmark" and c == "?": output_query.append(next(param_idx)) elif style == "numeric" and c == ":" and next_c != ':' \ and prev_c != ':': # Treat : as beginning of parameter name if and only # if it's the only : around # Needed to properly process type conversions # i.e. sum(x)::float output_query.append("$") elif style == "named" and c == ":" and next_c != ':' \ and prev_c != ':': # Same logic for : as in numeric parameters state = INSIDE_PN placeholders.append('') elif style == "pyformat" and c == '%' and next_c == "(": state = INSIDE_PN placeholders.append('') elif style in ("format", "pyformat") and c == "%": style = "format" if in_param_escape: in_param_escape = False output_query.append(c) else: if next_c == "%": in_param_escape = True elif next_c == "s": state = INSIDE_PN output_query.append(next(param_idx)) else: raise InterfaceError( "Only %s and %% are supported in the query.") else: output_query.append(c) elif state == INSIDE_SQ: if c == "'": if in_quote_escape: in_quote_escape = False else: if next_c == "'": in_quote_escape = True else: state = OUTSIDE output_query.append(c) elif state == INSIDE_QI: if c == '"': state = OUTSIDE output_query.append(c) elif state == INSIDE_ES: if c == "'" and prev_c != "\\": # check for escaped single-quote state = OUTSIDE output_query.append(c) elif state == INSIDE_PN: if style == 'named': placeholders[-1] += c if next_c is None or (not next_c.isalnum() and next_c != '_'): state = OUTSIDE try: pidx = placeholders.index(placeholders[-1], 0, -1) output_query.append("$" + str(pidx + 1)) del placeholders[-1] except ValueError: output_query.append("$" + str(len(placeholders))) elif style == 'pyformat': if prev_c == ')' and c == "s": state = OUTSIDE try: pidx = placeholders.index(placeholders[-1], 0, -1) output_query.append("$" + str(pidx + 1)) del placeholders[-1] except ValueError: output_query.append("$" + str(len(placeholders))) elif c in "()": pass else: placeholders[-1] += c elif style == 'format': state = OUTSIDE elif state == INSIDE_CO: output_query.append(c) if c == '\n': state = OUTSIDE prev_c = c if style in ('numeric', 'qmark', 'format'): def make_args(vals): return vals else: def make_args(vals): return tuple(vals[p] for p in placeholders) return ''.join(output_query), make_args EPOCH = Datetime(2000, 1, 1) EPOCH_TZ = EPOCH.replace(tzinfo=Timezone.utc) EPOCH_SECONDS = timegm(EPOCH.timetuple()) INFINITY_MICROSECONDS = 2 ** 63 - 1 MINUS_INFINITY_MICROSECONDS = -1 * INFINITY_MICROSECONDS - 1 # data is 64-bit integer representing microseconds since 2000-01-01 def timestamp_recv_integer(data, offset, length): micros = q_unpack(data, offset)[0] try: return EPOCH + Timedelta(microseconds=micros) except OverflowError: if micros == INFINITY_MICROSECONDS: return 'infinity' elif micros == MINUS_INFINITY_MICROSECONDS: return '-infinity' else: return micros # data is double-precision float representing seconds since 2000-01-01 def timestamp_recv_float(data, offset, length): return Datetime.utcfromtimestamp(EPOCH_SECONDS + d_unpack(data, offset)[0]) # data is 64-bit integer representing microseconds since 2000-01-01 def timestamp_send_integer(v): return q_pack( int((timegm(v.timetuple()) - EPOCH_SECONDS) * 1e6) + v.microsecond) # data is double-precision float representing seconds since 2000-01-01 def timestamp_send_float(v): return d_pack(timegm(v.timetuple()) + v.microsecond / 1e6 - EPOCH_SECONDS) def timestamptz_send_integer(v): # timestamps should be sent as UTC. If they have zone info, # convert them. return timestamp_send_integer( v.astimezone(Timezone.utc).replace(tzinfo=None)) def timestamptz_send_float(v): # timestamps should be sent as UTC. If they have zone info, # convert them. return timestamp_send_float( v.astimezone(Timezone.utc).replace(tzinfo=None)) # return a timezone-aware datetime instance if we're reading from a # "timestamp with timezone" type. The timezone returned will always be # UTC, but providing that additional information can permit conversion # to local. def timestamptz_recv_integer(data, offset, length): micros = q_unpack(data, offset)[0] try: return EPOCH_TZ + Timedelta(microseconds=micros) except OverflowError: if micros == INFINITY_MICROSECONDS: return 'infinity' elif micros == MINUS_INFINITY_MICROSECONDS: return '-infinity' else: return micros def timestamptz_recv_float(data, offset, length): return timestamp_recv_float(data, offset, length).replace( tzinfo=Timezone.utc) def interval_send_integer(v): microseconds = v.microseconds try: microseconds += int(v.seconds * 1e6) except AttributeError: pass try: months = v.months except AttributeError: months = 0 return qii_pack(microseconds, v.days, months) def interval_send_float(v): seconds = v.microseconds / 1000.0 / 1000.0 try: seconds += v.seconds except AttributeError: pass try: months = v.months except AttributeError: months = 0 return dii_pack(seconds, v.days, months) def interval_recv_integer(data, offset, length): microseconds, days, months = qii_unpack(data, offset) if months == 0: seconds, micros = divmod(microseconds, 1e6) return Timedelta(days, seconds, micros) else: return Interval(microseconds, days, months) def interval_recv_float(data, offset, length): seconds, days, months = dii_unpack(data, offset) if months == 0: secs, microseconds = divmod(seconds, 1e6) return Timedelta(days, secs, microseconds) else: return Interval(int(seconds * 1000 * 1000), days, months) def int8_recv(data, offset, length): return q_unpack(data, offset)[0] def int2_recv(data, offset, length): return h_unpack(data, offset)[0] def int4_recv(data, offset, length): return i_unpack(data, offset)[0] def float4_recv(data, offset, length): return f_unpack(data, offset)[0] def float8_recv(data, offset, length): return d_unpack(data, offset)[0] def bytea_send(v): return v # bytea def bytea_recv(data, offset, length): return data[offset:offset + length] def uuid_send(v): return v.bytes def uuid_recv(data, offset, length): return UUID(bytes=data[offset:offset+length]) def bool_send(v): return b"\x01" if v else b"\x00" NULL = i_pack(-1) NULL_BYTE = b'\x00' def null_send(v): return NULL def int_in(data, offset, length): return int(data[offset: offset + length]) class Cursor(): """A cursor object is returned by the :meth:`~Connection.cursor` method of a connection. It has the following attributes and methods: .. attribute:: arraysize This read/write attribute specifies the number of rows to fetch at a time with :meth:`fetchmany`. It defaults to 1. .. attribute:: connection This read-only attribute contains a reference to the connection object (an instance of :class:`Connection`) on which the cursor was created. This attribute is part of a DBAPI 2.0 extension. Accessing this attribute will generate the following warning: ``DB-API extension cursor.connection used``. .. attribute:: rowcount This read-only attribute contains the number of rows that the last ``execute()`` or ``executemany()`` method produced (for query statements like ``SELECT``) or affected (for modification statements like ``UPDATE``). The value is -1 if: - No ``execute()`` or ``executemany()`` method has been performed yet on the cursor. - There was no rowcount associated with the last ``execute()``. - At least one of the statements executed as part of an ``executemany()`` had no row count associated with it. - Using a ``SELECT`` query statement on PostgreSQL server older than version 9. - Using a ``COPY`` query statement on PostgreSQL server version 8.1 or older. This attribute is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. .. attribute:: description This read-only attribute is a sequence of 7-item sequences. Each value contains information describing one result column. The 7 items returned for each column are (name, type_code, display_size, internal_size, precision, scale, null_ok). Only the first two values are provided by the current implementation. This attribute is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ def __init__(self, connection): self._c = connection self.arraysize = 1 self.ps = None self._row_count = -1 self._cached_rows = deque() def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() @property def connection(self): warn("DB-API extension cursor.connection used", stacklevel=3) return self._c @property def rowcount(self): return self._row_count description = property(lambda self: self._getDescription()) def _getDescription(self): if self.ps is None: return None row_desc = self.ps['row_desc'] if len(row_desc) == 0: return None columns = [] for col in row_desc: columns.append( (col["name"], col["type_oid"], None, None, None, None, None)) return columns ## # Executes a database operation. Parameters may be provided as a sequence # or mapping and will be bound to variables in the operation. # <p> # Stability: Part of the DBAPI 2.0 specification. def execute(self, operation, args=None, stream=None): """Executes a database operation. Parameters may be provided as a sequence, or as a mapping, depending upon the value of :data:`pg8000.paramstyle`. This method is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :param operation: The SQL statement to execute. :param args: If :data:`paramstyle` is ``qmark``, ``numeric``, or ``format``, this argument should be an array of parameters to bind into the statement. If :data:`paramstyle` is ``named``, the argument should be a dict mapping of parameters. If the :data:`paramstyle` is ``pyformat``, the argument value may be either an array or a mapping. :param stream: This is a pg8000 extension for use with the PostgreSQL `COPY <http://www.postgresql.org/docs/current/static/sql-copy.html>`_ command. For a COPY FROM the parameter must be a readable file-like object, and for COPY TO it must be writable. .. versionadded:: 1.9.11 """ try: self.stream = stream if not self._c.in_transaction and not self._c.autocommit: self._c.execute(self, "begin transaction", None) self._c.execute(self, operation, args) except AttributeError as e: if self._c is None: raise InterfaceError("Cursor closed") elif self._c._sock is None: raise InterfaceError("connection is closed") else: raise e def executemany(self, operation, param_sets): """Prepare a database operation, and then execute it against all parameter sequences or mappings provided. This method is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :param operation: The SQL statement to execute :param parameter_sets: A sequence of parameters to execute the statement with. The values in the sequence should be sequences or mappings of parameters, the same as the args argument of the :meth:`execute` method. """ rowcounts = [] for parameters in param_sets: self.execute(operation, parameters) rowcounts.append(self._row_count) self._row_count = -1 if -1 in rowcounts else sum(rowcounts) def fetchone(self): """Fetch the next row of a query result set. This method is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :returns: A row as a sequence of field values, or ``None`` if no more rows are available. """ try: return next(self) except StopIteration: return None except TypeError: raise ProgrammingError("attempting to use unexecuted cursor") except AttributeError: raise ProgrammingError("attempting to use unexecuted cursor") def fetchmany(self, num=None): """Fetches the next set of rows of a query result. This method is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :param size: The number of rows to fetch when called. If not provided, the :attr:`arraysize` attribute value is used instead. :returns: A sequence, each entry of which is a sequence of field values making up a row. If no more rows are available, an empty sequence will be returned. """ try: return tuple( islice(self, self.arraysize if num is None else num)) except TypeError: raise ProgrammingError("attempting to use unexecuted cursor") def fetchall(self): """Fetches all remaining rows of a query result. This method is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :returns: A sequence, each entry of which is a sequence of field values making up a row. """ try: return tuple(self) except TypeError: raise ProgrammingError("attempting to use unexecuted cursor") def close(self): """Closes the cursor. This method is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ self._c = None def __iter__(self): """A cursor object is iterable to retrieve the rows from a query. This is a DBAPI 2.0 extension. """ return self def setinputsizes(self, sizes): """This method is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_, however, it is not implemented by pg8000. """ pass def setoutputsize(self, size, column=None): """This method is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_, however, it is not implemented by pg8000. """ pass def __next__(self): try: return self._cached_rows.popleft() except IndexError: if self.ps is None: raise ProgrammingError("A query hasn't been issued.") elif len(self.ps['row_desc']) == 0: raise ProgrammingError("no result set") else: raise StopIteration() # Message codes NOTICE_RESPONSE = b"N" AUTHENTICATION_REQUEST = b"R" PARAMETER_STATUS = b"S" BACKEND_KEY_DATA = b"K" READY_FOR_QUERY = b"Z" ROW_DESCRIPTION = b"T" ERROR_RESPONSE = b"E" DATA_ROW = b"D" COMMAND_COMPLETE = b"C" PARSE_COMPLETE = b"1" BIND_COMPLETE = b"2" CLOSE_COMPLETE = b"3" PORTAL_SUSPENDED = b"s" NO_DATA = b"n" PARAMETER_DESCRIPTION = b"t" NOTIFICATION_RESPONSE = b"A" COPY_DONE = b"c" COPY_DATA = b"d" COPY_IN_RESPONSE = b"G" COPY_OUT_RESPONSE = b"H" EMPTY_QUERY_RESPONSE = b"I" BIND = b"B" PARSE = b"P" EXECUTE = b"E" FLUSH = b'H' SYNC = b'S' PASSWORD = b'p' DESCRIBE = b'D' TERMINATE = b'X' CLOSE = b'C' def _establish_ssl(_socket, ssl_params): if not isinstance(ssl_params, dict): ssl_params = {} try: import ssl as sslmodule keyfile = ssl_params.get('keyfile') certfile = ssl_params.get('certfile') ca_certs = ssl_params.get('ca_certs') if ca_certs is None: verify_mode = sslmodule.CERT_NONE else: verify_mode = sslmodule.CERT_REQUIRED # Int32(8) - Message length, including self. # Int32(80877103) - The SSL request code. _socket.sendall(ii_pack(8, 80877103)) resp = _socket.recv(1) if resp == b'S': return sslmodule.wrap_socket( _socket, keyfile=keyfile, certfile=certfile, cert_reqs=verify_mode, ca_certs=ca_certs) else: raise InterfaceError("Server refuses SSL") except ImportError: raise InterfaceError( "SSL required but ssl module not available in " "this python installation") def create_message(code, data=b''): return code + i_pack(len(data) + 4) + data FLUSH_MSG = create_message(FLUSH) SYNC_MSG = create_message(SYNC) TERMINATE_MSG = create_message(TERMINATE) COPY_DONE_MSG = create_message(COPY_DONE) EXECUTE_MSG = create_message(EXECUTE, NULL_BYTE + i_pack(0)) # DESCRIBE constants STATEMENT = b'S' PORTAL = b'P' # ErrorResponse codes RESPONSE_SEVERITY = "S" # always present RESPONSE_SEVERITY = "V" # always present RESPONSE_CODE = "C" # always present RESPONSE_MSG = "M" # always present RESPONSE_DETAIL = "D" RESPONSE_HINT = "H" RESPONSE_POSITION = "P" RESPONSE__POSITION = "p" RESPONSE__QUERY = "q" RESPONSE_WHERE = "W" RESPONSE_FILE = "F" RESPONSE_LINE = "L" RESPONSE_ROUTINE = "R" IDLE = b"I" IDLE_IN_TRANSACTION = b"T" IDLE_IN_FAILED_TRANSACTION = b"E" arr_trans = dict(zip(map(ord, "[] 'u"), list('{}') + [None] * 3)) class Connection(): # DBAPI Extension: supply exceptions as attributes on the connection Warning = property(lambda self: self._getError(Warning)) Error = property(lambda self: self._getError(Error)) InterfaceError = property(lambda self: self._getError(InterfaceError)) DatabaseError = property(lambda self: self._getError(DatabaseError)) OperationalError = property(lambda self: self._getError(OperationalError)) IntegrityError = property(lambda self: self._getError(IntegrityError)) InternalError = property(lambda self: self._getError(InternalError)) ProgrammingError = property(lambda self: self._getError(ProgrammingError)) NotSupportedError = property( lambda self: self._getError(NotSupportedError)) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def _getError(self, error): warn( "DB-API extension connection.%s used" % error.__name__, stacklevel=3) return error def __init__( self, user, host, unix_sock, port, database, password, ssl, timeout, application_name, max_prepared_statements, tcp_keepalive): self._client_encoding = "utf8" self._commands_with_count = ( b"INSERT", b"DELETE", b"UPDATE", b"MOVE", b"FETCH", b"COPY", b"SELECT") self.notifications = deque(maxlen=100) self.notices = deque(maxlen=100) self.parameter_statuses = deque(maxlen=100) self.max_prepared_statements = int(max_prepared_statements) if user is None: raise InterfaceError( "The 'user' connection parameter cannot be None") if isinstance(user, str): self.user = user.encode('utf8') else: self.user = user if isinstance(password, str): self.password = password.encode('utf8') else: self.password = password self.autocommit = False self._xid = None self._caches = {} try: if unix_sock is None and host is not None: self._usock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) elif unix_sock is not None: if not hasattr(socket, "AF_UNIX"): raise InterfaceError( "attempt to connect to unix socket on unsupported " "platform") self._usock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) else: raise ProgrammingError( "one of host or unix_sock must be provided") if timeout is not None: self._usock.settimeout(timeout) if unix_sock is None and host is not None: self._usock.connect((host, port)) elif unix_sock is not None: self._usock.connect(unix_sock) if ssl: self._usock = _establish_ssl(self._usock, ssl) self._sock = self._usock.makefile(mode="rwb") if tcp_keepalive: self._usock.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) except socket.error as e: self._usock.close() raise InterfaceError("communication error", e) self._flush = self._sock.flush self._read = self._sock.read self._write = self._sock.write self._backend_key_data = None def text_out(v): return v.encode(self._client_encoding) def enum_out(v): return str(v.value).encode(self._client_encoding) def time_out(v): return v.isoformat().encode(self._client_encoding) def date_out(v): return v.isoformat().encode(self._client_encoding) def unknown_out(v): return str(v).encode(self._client_encoding) trans_tab = dict(zip(map(ord, '{}'), '[]')) glbls = {'Decimal': Decimal} def array_in(data, idx, length): arr = [] prev_c = None for c in data[idx:idx+length].decode( self._client_encoding).translate( trans_tab).replace('NULL', 'None'): if c not in ('[', ']', ',', 'N') and prev_c in ('[', ','): arr.extend("Decimal('") elif c in (']', ',') and prev_c not in ('[', ']', ',', 'e'): arr.extend("')") arr.append(c) prev_c = c return eval(''.join(arr), glbls) def array_recv(data, idx, length): final_idx = idx + length dim, hasnull, typeoid = iii_unpack(data, idx) idx += 12 # get type conversion method for typeoid conversion = self.pg_types[typeoid][1] # Read dimension info dim_lengths = [] for i in range(dim): dim_lengths.append(ii_unpack(data, idx)[0]) idx += 8 # Read all array values values = [] while idx < final_idx: element_len, = i_unpack(data, idx) idx += 4 if element_len == -1: values.append(None) else: values.append(conversion(data, idx, element_len)) idx += element_len # at this point, {{1,2,3},{4,5,6}}::int[][] looks like # [1,2,3,4,5,6]. go through the dimensions and fix up the array # contents to match expected dimensions for length in reversed(dim_lengths[1:]): values = list(map(list, zip(*[iter(values)] * length))) return values def vector_in(data, idx, length): return eval('[' + data[idx:idx+length].decode( self._client_encoding).replace(' ', ',') + ']') def text_recv(data, offset, length): return str(data[offset: offset + length], self._client_encoding) def bool_recv(data, offset, length): return data[offset] == 1 def json_in(data, offset, length): return loads( str(data[offset: offset + length], self._client_encoding)) def time_in(data, offset, length): hour = int(data[offset:offset + 2]) minute = int(data[offset + 3:offset + 5]) sec = Decimal( data[offset + 6:offset + length].decode(self._client_encoding)) return time( hour, minute, int(sec), int((sec - int(sec)) * 1000000)) def date_in(data, offset, length): d = data[offset:offset+length].decode(self._client_encoding) try: return date(int(d[:4]), int(d[5:7]), int(d[8:10])) except ValueError: return d def numeric_in(data, offset, length): return Decimal( data[offset: offset + length].decode(self._client_encoding)) def numeric_out(d): return str(d).encode(self._client_encoding) self.pg_types = defaultdict( lambda: (FC_TEXT, text_recv), { 16: (FC_BINARY, bool_recv), # boolean 17: (FC_BINARY, bytea_recv), # bytea 19: (FC_BINARY, text_recv), # name type 20: (FC_BINARY, int8_recv), # int8 21: (FC_BINARY, int2_recv), # int2 22: (FC_TEXT, vector_in), # int2vector 23: (FC_BINARY, int4_recv), # int4 25: (FC_BINARY, text_recv), # TEXT type 26: (FC_TEXT, int_in), # oid 28: (FC_TEXT, int_in), # xid 114: (FC_TEXT, json_in), # json 700: (FC_BINARY, float4_recv), # float4 701: (FC_BINARY, float8_recv), # float8 705: (FC_BINARY, text_recv), # unknown 829: (FC_TEXT, text_recv), # MACADDR type 1000: (FC_BINARY, array_recv), # BOOL[] 1003: (FC_BINARY, array_recv), # NAME[] 1005: (FC_BINARY, array_recv), # INT2[] 1007: (FC_BINARY, array_recv), # INT4[] 1009: (FC_BINARY, array_recv), # TEXT[] 1014: (FC_BINARY, array_recv), # CHAR[] 1015: (FC_BINARY, array_recv), # VARCHAR[] 1016: (FC_BINARY, array_recv), # INT8[] 1021: (FC_BINARY, array_recv), # FLOAT4[] 1022: (FC_BINARY, array_recv), # FLOAT8[] 1042: (FC_BINARY, text_recv), # CHAR type 1043: (FC_BINARY, text_recv), # VARCHAR type 1082: (FC_TEXT, date_in), # date 1083: (FC_TEXT, time_in), 1114: (FC_BINARY, timestamp_recv_float), # timestamp w/ tz 1184: (FC_BINARY, timestamptz_recv_float), 1186: (FC_BINARY, interval_recv_integer), 1231: (FC_TEXT, array_in), # NUMERIC[] 1263: (FC_BINARY, array_recv), # cstring[] 1700: (FC_TEXT, numeric_in), # NUMERIC 2275: (FC_BINARY, text_recv), # cstring 2950: (FC_BINARY, uuid_recv), # uuid 3802: (FC_TEXT, json_in), # jsonb }) self.py_types = { type(None): (-1, FC_BINARY, null_send), # null bool: (16, FC_BINARY, bool_send), bytearray: (17, FC_BINARY, bytea_send), # bytea 20: (20, FC_BINARY, q_pack), # int8 21: (21, FC_BINARY, h_pack), # int2 23: (23, FC_BINARY, i_pack), # int4 PGText: (25, FC_TEXT, text_out), # text float: (701, FC_BINARY, d_pack), # float8 PGEnum: (705, FC_TEXT, enum_out), date: (1082, FC_TEXT, date_out), # date time: (1083, FC_TEXT, time_out), # time 1114: (1114, FC_BINARY, timestamp_send_integer), # timestamp # timestamp w/ tz PGVarchar: (1043, FC_TEXT, text_out), # varchar 1184: (1184, FC_BINARY, timestamptz_send_integer), PGJson: (114, FC_TEXT, text_out), PGJsonb: (3802, FC_TEXT, text_out), Timedelta: (1186, FC_BINARY, interval_send_integer), Interval: (1186, FC_BINARY, interval_send_integer), Decimal: (1700, FC_TEXT, numeric_out), # Decimal PGTsvector: (3614, FC_TEXT, text_out), UUID: (2950, FC_BINARY, uuid_send)} # uuid self.inspect_funcs = { Datetime: self.inspect_datetime, list: self.array_inspect, tuple: self.array_inspect, int: self.inspect_int} self.py_types[bytes] = (17, FC_BINARY, bytea_send) # bytea self.py_types[str] = (705, FC_TEXT, text_out) # unknown self.py_types[enum.Enum] = (705, FC_TEXT, enum_out) def inet_out(v): return str(v).encode(self._client_encoding) def inet_in(data, offset, length): inet_str = data[offset: offset + length].decode( self._client_encoding) if '/' in inet_str: return ip_network(inet_str, False) else: return ip_address(inet_str) self.py_types[IPv4Address] = (869, FC_TEXT, inet_out) # inet self.py_types[IPv6Address] = (869, FC_TEXT, inet_out) # inet self.py_types[IPv4Network] = (869, FC_TEXT, inet_out) # inet self.py_types[IPv6Network] = (869, FC_TEXT, inet_out) # inet self.pg_types[869] = (FC_TEXT, inet_in) # inet self.message_types = { NOTICE_RESPONSE: self.handle_NOTICE_RESPONSE, AUTHENTICATION_REQUEST: self.handle_AUTHENTICATION_REQUEST, PARAMETER_STATUS: self.handle_PARAMETER_STATUS, BACKEND_KEY_DATA: self.handle_BACKEND_KEY_DATA, READY_FOR_QUERY: self.handle_READY_FOR_QUERY, ROW_DESCRIPTION: self.handle_ROW_DESCRIPTION, ERROR_RESPONSE: self.handle_ERROR_RESPONSE, EMPTY_QUERY_RESPONSE: self.handle_EMPTY_QUERY_RESPONSE, DATA_ROW: self.handle_DATA_ROW, COMMAND_COMPLETE: self.handle_COMMAND_COMPLETE, PARSE_COMPLETE: self.handle_PARSE_COMPLETE, BIND_COMPLETE: self.handle_BIND_COMPLETE, CLOSE_COMPLETE: self.handle_CLOSE_COMPLETE, PORTAL_SUSPENDED: self.handle_PORTAL_SUSPENDED, NO_DATA: self.handle_NO_DATA, PARAMETER_DESCRIPTION: self.handle_PARAMETER_DESCRIPTION, NOTIFICATION_RESPONSE: self.handle_NOTIFICATION_RESPONSE, COPY_DONE: self.handle_COPY_DONE, COPY_DATA: self.handle_COPY_DATA, COPY_IN_RESPONSE: self.handle_COPY_IN_RESPONSE, COPY_OUT_RESPONSE: self.handle_COPY_OUT_RESPONSE} # Int32 - Message length, including self. # Int32(196608) - Protocol version number. Version 3.0. # Any number of key/value pairs, terminated by a zero byte: # String - A parameter name (user, database, or options) # String - Parameter value protocol = 196608 val = bytearray( i_pack(protocol) + b"user\x00" + self.user + NULL_BYTE) if database is not None: if isinstance(database, str): database = database.encode('utf8') val.extend(b"database\x00" + database + NULL_BYTE) if application_name is not None: if isinstance(application_name, str): application_name = application_name.encode('utf8') val.extend( b"application_name\x00" + application_name + NULL_BYTE) val.append(0) self._write(i_pack(len(val) + 4)) self._write(val) self._flush() self._cursor = self.cursor() code = self.error = None while code not in (READY_FOR_QUERY, ERROR_RESPONSE): code, data_len = ci_unpack(self._read(5)) self.message_types[code](self._read(data_len - 4), None) if self.error is not None: raise self.error self.in_transaction = False def handle_ERROR_RESPONSE(self, data, ps): msg = dict( ( s[:1].decode(self._client_encoding), s[1:].decode(self._client_encoding)) for s in data.split(NULL_BYTE) if s != b'') response_code = msg[RESPONSE_CODE] if response_code == '28000': cls = InterfaceError elif response_code == '23505': cls = IntegrityError else: cls = ProgrammingError self.error = cls(msg) def handle_EMPTY_QUERY_RESPONSE(self, data, ps): self.error = ProgrammingError("query was empty") def handle_CLOSE_COMPLETE(self, data, ps): pass def handle_PARSE_COMPLETE(self, data, ps): # Byte1('1') - Identifier. # Int32(4) - Message length, including self. pass def handle_BIND_COMPLETE(self, data, ps): pass def handle_PORTAL_SUSPENDED(self, data, cursor): pass def handle_PARAMETER_DESCRIPTION(self, data, ps): # Well, we don't really care -- we're going to send whatever we # want and let the database deal with it. But thanks anyways! # count = h_unpack(data)[0] # type_oids = unpack_from("!" + "i" * count, data, 2) pass def handle_COPY_DONE(self, data, ps): self._copy_done = True def handle_COPY_OUT_RESPONSE(self, data, ps): # Int8(1) - 0 textual, 1 binary # Int16(2) - Number of columns # Int16(N) - Format codes for each column (0 text, 1 binary) is_binary, num_cols = bh_unpack(data) # column_formats = unpack_from('!' + 'h' * num_cols, data, 3) if ps.stream is None: raise InterfaceError( "An output stream is required for the COPY OUT response.") def handle_COPY_DATA(self, data, ps): ps.stream.write(data) def handle_COPY_IN_RESPONSE(self, data, ps): # Int16(2) - Number of columns # Int16(N) - Format codes for each column (0 text, 1 binary) is_binary, num_cols = bh_unpack(data) # column_formats = unpack_from('!' + 'h' * num_cols, data, 3) if ps.stream is None: raise InterfaceError( "An input stream is required for the COPY IN response.") bffr = bytearray(8192) while True: bytes_read = ps.stream.readinto(bffr) if bytes_read == 0: break self._write(COPY_DATA + i_pack(bytes_read + 4)) self._write(bffr[:bytes_read]) self._flush() # Send CopyDone # Byte1('c') - Identifier. # Int32(4) - Message length, including self. self._write(COPY_DONE_MSG) self._write(SYNC_MSG) self._flush() def handle_NOTIFICATION_RESPONSE(self, data, ps): ## # A message sent if this connection receives a NOTIFY that it was # LISTENing for. # <p> # Stability: Added in pg8000 v1.03. When limited to accessing # properties from a notification event dispatch, stability is # guaranteed for v1.xx. backend_pid = i_unpack(data)[0] idx = 4 null = data.find(NULL_BYTE, idx) - idx condition = data[idx:idx + null].decode("ascii") idx += null + 1 null = data.find(NULL_BYTE, idx) - idx # additional_info = data[idx:idx + null] self.notifications.append((backend_pid, condition)) def cursor(self): """Creates a :class:`Cursor` object bound to this connection. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ return Cursor(self) def commit(self): """Commits the current database transaction. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ self.execute(self._cursor, "commit", None) def rollback(self): """Rolls back the current database transaction. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ if not self.in_transaction: return self.execute(self._cursor, "rollback", None) def close(self): """Closes the database connection. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ try: # Byte1('X') - Identifies the message as a terminate message. # Int32(4) - Message length, including self. self._write(TERMINATE_MSG) self._flush() self._sock.close() except AttributeError: raise InterfaceError("connection is closed") except ValueError: raise InterfaceError("connection is closed") except socket.error: pass finally: self._usock.close() self._sock = None def handle_AUTHENTICATION_REQUEST(self, data, cursor): # Int32 - An authentication code that represents different # authentication messages: # 0 = AuthenticationOk # 5 = MD5 pwd # 2 = Kerberos v5 (not supported by pg8000) # 3 = Cleartext pwd # 4 = crypt() pwd (not supported by pg8000) # 6 = SCM credential (not supported by pg8000) # 7 = GSSAPI (not supported by pg8000) # 8 = GSSAPI data (not supported by pg8000) # 9 = SSPI (not supported by pg8000) # Some authentication messages have additional data following the # authentication code. That data is documented in the appropriate # class. auth_code = i_unpack(data)[0] if auth_code == 0: pass elif auth_code == 3: if self.password is None: raise InterfaceError( "server requesting password authentication, but no " "password was provided") self._send_message(PASSWORD, self.password + NULL_BYTE) self._flush() elif auth_code == 5: ## # A message representing the backend requesting an MD5 hashed # password response. The response will be sent as # md5(md5(pwd + login) + salt). # Additional message data: # Byte4 - Hash salt. salt = b"".join(cccc_unpack(data, 4)) if self.password is None: raise InterfaceError( "server requesting MD5 password authentication, but no " "password was provided") pwd = b"md5" + md5( md5(self.password + self.user).hexdigest().encode("ascii") + salt).hexdigest().encode("ascii") # Byte1('p') - Identifies the message as a password message. # Int32 - Message length including self. # String - The password. Password may be encrypted. self._send_message(PASSWORD, pwd + NULL_BYTE) self._flush() elif auth_code == 10: # AuthenticationSASL mechanisms = [ m.decode('ascii') for m in data[4:-1].split(NULL_BYTE)] self.auth = Auth( mechanisms, self.user.decode('utf8'), self.password.decode('utf8')) init = self.auth.get_client_first_message().encode('utf8') # SASLInitialResponse self._write( create_message( PASSWORD, b'SCRAM-SHA-256' + NULL_BYTE + i_pack(len(init)) + init)) self._flush() elif auth_code == 11: # AuthenticationSASLContinue self.auth.set_server_first_message(data[4:].decode('utf8')) # SASLResponse msg = self.auth.get_client_final_message().encode('utf8') self._write(create_message(PASSWORD, msg)) self._flush() elif auth_code == 12: # AuthenticationSASLFinal self.auth.set_server_final_message(data[4:].decode('utf8')) elif auth_code in (2, 4, 6, 7, 8, 9): raise InterfaceError( "Authentication method " + str(auth_code) + " not supported by pg8000.") else: raise InterfaceError( "Authentication method " + str(auth_code) + " not recognized by pg8000.") def handle_READY_FOR_QUERY(self, data, ps): # Byte1 - Status indicator. self.in_transaction = data != IDLE def handle_BACKEND_KEY_DATA(self, data, ps): self._backend_key_data = data def inspect_datetime(self, value): if value.tzinfo is None: return self.py_types[1114] # timestamp else: return self.py_types[1184] # send as timestamptz def inspect_int(self, value): if min_int2 < value < max_int2: return self.py_types[21] if min_int4 < value < max_int4: return self.py_types[23] if min_int8 < value < max_int8: return self.py_types[20] def make_params(self, values): params = [] for value in values: typ = type(value) try: params.append(self.py_types[typ]) except KeyError: try: params.append(self.inspect_funcs[typ](value)) except KeyError as e: param = None for k, v in self.py_types.items(): try: if isinstance(value, k): param = v break except TypeError: pass if param is None: for k, v in self.inspect_funcs.items(): try: if isinstance(value, k): param = v(value) break except TypeError: pass except KeyError: pass if param is None: raise NotSupportedError( "type " + str(e) + " not mapped to pg type") else: params.append(param) return tuple(params) def handle_ROW_DESCRIPTION(self, data, cursor): count = h_unpack(data)[0] idx = 2 for i in range(count): name = data[idx:data.find(NULL_BYTE, idx)] idx += len(name) + 1 field = dict( zip(( "table_oid", "column_attrnum", "type_oid", "type_size", "type_modifier", "format"), ihihih_unpack(data, idx))) field['name'] = name idx += 18 cursor.ps['row_desc'].append(field) field['pg8000_fc'], field['func'] = \ self.pg_types[field['type_oid']] def execute(self, cursor, operation, vals): if vals is None: vals = () paramstyle = pg8000.paramstyle pid = getpid() try: cache = self._caches[paramstyle][pid] except KeyError: try: param_cache = self._caches[paramstyle] except KeyError: param_cache = self._caches[paramstyle] = {} try: cache = param_cache[pid] except KeyError: cache = param_cache[pid] = {'statement': {}, 'ps': {}} try: statement, make_args = cache['statement'][operation] except KeyError: statement, make_args = cache['statement'][operation] = \ convert_paramstyle(paramstyle, operation) args = make_args(vals) params = self.make_params(args) key = operation, params try: ps = cache['ps'][key] cursor.ps = ps except KeyError: statement_nums = [0] for style_cache in self._caches.values(): try: pid_cache = style_cache[pid] for csh in pid_cache['ps'].values(): statement_nums.append(csh['statement_num']) except KeyError: pass statement_num = sorted(statement_nums)[-1] + 1 statement_name = '_'.join( ("pg8000", "statement", str(pid), str(statement_num))) statement_name_bin = statement_name.encode('ascii') + NULL_BYTE ps = { 'statement_name_bin': statement_name_bin, 'pid': pid, 'statement_num': statement_num, 'row_desc': [], 'param_funcs': tuple(x[2] for x in params)} cursor.ps = ps param_fcs = tuple(x[1] for x in params) # Byte1('P') - Identifies the message as a Parse command. # Int32 - Message length, including self. # String - Prepared statement name. An empty string selects the # unnamed prepared statement. # String - The query string. # Int16 - Number of parameter data types specified (can be zero). # For each parameter: # Int32 - The OID of the parameter data type. val = bytearray(statement_name_bin) val.extend(statement.encode(self._client_encoding) + NULL_BYTE) val.extend(h_pack(len(params))) for oid, fc, send_func in params: # Parse message doesn't seem to handle the -1 type_oid for NULL # values that other messages handle. So we'll provide type_oid # 705, the PG "unknown" type. val.extend(i_pack(705 if oid == -1 else oid)) # Byte1('D') - Identifies the message as a describe command. # Int32 - Message length, including self. # Byte1 - 'S' for prepared statement, 'P' for portal. # String - The name of the item to describe. self._send_message(PARSE, val) self._send_message(DESCRIBE, STATEMENT + statement_name_bin) self._write(SYNC_MSG) try: self._flush() except AttributeError as e: if self._sock is None: raise InterfaceError("connection is closed") else: raise e self.handle_messages(cursor) # We've got row_desc that allows us to identify what we're # going to get back from this statement. output_fc = tuple( self.pg_types[f['type_oid']][0] for f in ps['row_desc']) ps['input_funcs'] = tuple(f['func'] for f in ps['row_desc']) # Byte1('B') - Identifies the Bind command. # Int32 - Message length, including self. # String - Name of the destination portal. # String - Name of the source prepared statement. # Int16 - Number of parameter format codes. # For each parameter format code: # Int16 - The parameter format code. # Int16 - Number of parameter values. # For each parameter value: # Int32 - The length of the parameter value, in bytes, not # including this length. -1 indicates a NULL parameter # value, in which no value bytes follow. # Byte[n] - Value of the parameter. # Int16 - The number of result-column format codes. # For each result-column format code: # Int16 - The format code. ps['bind_1'] = NULL_BYTE + statement_name_bin + \ h_pack(len(params)) + \ pack("!" + "h" * len(param_fcs), *param_fcs) + \ h_pack(len(params)) ps['bind_2'] = h_pack(len(output_fc)) + \ pack("!" + "h" * len(output_fc), *output_fc) if len(cache['ps']) > self.max_prepared_statements: for p in cache['ps'].values(): self.close_prepared_statement(p['statement_name_bin']) cache['ps'].clear() cache['ps'][key] = ps cursor._cached_rows.clear() cursor._row_count = -1 # Byte1('B') - Identifies the Bind command. # Int32 - Message length, including self. # String - Name of the destination portal. # String - Name of the source prepared statement. # Int16 - Number of parameter format codes. # For each parameter format code: # Int16 - The parameter format code. # Int16 - Number of parameter values. # For each parameter value: # Int32 - The length of the parameter value, in bytes, not # including this length. -1 indicates a NULL parameter # value, in which no value bytes follow. # Byte[n] - Value of the parameter. # Int16 - The number of result-column format codes. # For each result-column format code: # Int16 - The format code. retval = bytearray(ps['bind_1']) for value, send_func in zip(args, ps['param_funcs']): if value is None: val = NULL else: val = send_func(value) retval.extend(i_pack(len(val))) retval.extend(val) retval.extend(ps['bind_2']) self._send_message(BIND, retval) self.send_EXECUTE(cursor) self._write(SYNC_MSG) try: self._flush() self.handle_messages(cursor) except Exception as e: raise OperationalError(e.args[0]) def _send_message(self, code, data): try: self._write(code) self._write(i_pack(len(data) + 4)) self._write(data) self._write(FLUSH_MSG) except ValueError as e: if str(e) == "write to closed file": raise InterfaceError("connection is closed") else: raise e except AttributeError: raise InterfaceError("connection is closed") def send_EXECUTE(self, cursor): # Byte1('E') - Identifies the message as an execute message. # Int32 - Message length, including self. # String - The name of the portal to execute. # Int32 - Maximum number of rows to return, if portal # contains a query # that returns rows. # 0 = no limit. self._write(EXECUTE_MSG) self._write(FLUSH_MSG) def handle_NO_DATA(self, msg, ps): pass def handle_COMMAND_COMPLETE(self, data, cursor): values = data[:-1].split(b' ') command = values[0] if command in self._commands_with_count: row_count = int(values[-1]) if cursor._row_count == -1: cursor._row_count = row_count else: cursor._row_count += row_count if command in (b"ALTER", b"CREATE"): for scache in self._caches.values(): for pcache in scache.values(): for ps in pcache['ps'].values(): self.close_prepared_statement(ps['statement_name_bin']) pcache['ps'].clear() def handle_DATA_ROW(self, data, cursor): data_idx = 2 row = [] for func in cursor.ps['input_funcs']: vlen = i_unpack(data, data_idx)[0] data_idx += 4 if vlen == -1: row.append(None) else: row.append(func(data, data_idx, vlen)) data_idx += vlen cursor._cached_rows.append(row) def handle_messages(self, cursor): code = self.error = None while code != READY_FOR_QUERY: code, data_len = ci_unpack(self._read(5)) self.message_types[code](self._read(data_len - 4), cursor) if self.error is not None: raise self.error # Byte1('C') - Identifies the message as a close command. # Int32 - Message length, including self. # Byte1 - 'S' for prepared statement, 'P' for portal. # String - The name of the item to close. def close_prepared_statement(self, statement_name_bin): self._send_message(CLOSE, STATEMENT + statement_name_bin) self._write(SYNC_MSG) self._flush() self.handle_messages(self._cursor) # Byte1('N') - Identifier # Int32 - Message length # Any number of these, followed by a zero byte: # Byte1 - code identifying the field type (see responseKeys) # String - field value def handle_NOTICE_RESPONSE(self, data, ps): self.notices.append( dict((s[0:1], s[1:]) for s in data.split(NULL_BYTE))) def handle_PARAMETER_STATUS(self, data, ps): pos = data.find(NULL_BYTE) key, value = data[:pos], data[pos + 1:-1] self.parameter_statuses.append((key, value)) if key == b"client_encoding": encoding = value.decode("ascii").lower() self._client_encoding = pg_to_py_encodings.get(encoding, encoding) elif key == b"integer_datetimes": if value == b'on': self.py_types[1114] = (1114, FC_BINARY, timestamp_send_integer) self.pg_types[1114] = (FC_BINARY, timestamp_recv_integer) self.py_types[1184] = ( 1184, FC_BINARY, timestamptz_send_integer) self.pg_types[1184] = (FC_BINARY, timestamptz_recv_integer) self.py_types[Interval] = ( 1186, FC_BINARY, interval_send_integer) self.py_types[Timedelta] = ( 1186, FC_BINARY, interval_send_integer) self.pg_types[1186] = (FC_BINARY, interval_recv_integer) else: self.py_types[1114] = (1114, FC_BINARY, timestamp_send_float) self.pg_types[1114] = (FC_BINARY, timestamp_recv_float) self.py_types[1184] = (1184, FC_BINARY, timestamptz_send_float) self.pg_types[1184] = (FC_BINARY, timestamptz_recv_float) self.py_types[Interval] = ( 1186, FC_BINARY, interval_send_float) self.py_types[Timedelta] = ( 1186, FC_BINARY, interval_send_float) self.pg_types[1186] = (FC_BINARY, interval_recv_float) elif key == b"server_version": self._server_version = LooseVersion(value.decode('ascii')) if self._server_version < LooseVersion('8.2.0'): self._commands_with_count = ( b"INSERT", b"DELETE", b"UPDATE", b"MOVE", b"FETCH") elif self._server_version < LooseVersion('9.0.0'): self._commands_with_count = ( b"INSERT", b"DELETE", b"UPDATE", b"MOVE", b"FETCH", b"COPY") def array_inspect(self, value): # Check if array has any values. If empty, we can just assume it's an # array of strings first_element = array_find_first_element(value) if first_element is None: oid = 25 # Use binary ARRAY format to avoid having to properly # escape text in the array literals fc = FC_BINARY array_oid = pg_array_types[oid] else: # supported array output typ = type(first_element) if issubclass(typ, int): # special int array support -- send as smallest possible array # type typ = int int2_ok, int4_ok, int8_ok = True, True, True for v in array_flatten(value): if v is None: continue if min_int2 < v < max_int2: continue int2_ok = False if min_int4 < v < max_int4: continue int4_ok = False if min_int8 < v < max_int8: continue int8_ok = False if int2_ok: array_oid = 1005 # INT2[] oid, fc, send_func = (21, FC_BINARY, h_pack) elif int4_ok: array_oid = 1007 # INT4[] oid, fc, send_func = (23, FC_BINARY, i_pack) elif int8_ok: array_oid = 1016 # INT8[] oid, fc, send_func = (20, FC_BINARY, q_pack) else: raise ArrayContentNotSupportedError( "numeric not supported as array contents") else: try: oid, fc, send_func = self.make_params((first_element,))[0] # If unknown or string, assume it's a string array if oid in (705, 1043, 25): oid = 25 # Use binary ARRAY format to avoid having to properly # escape text in the array literals fc = FC_BINARY array_oid = pg_array_types[oid] except KeyError: raise ArrayContentNotSupportedError( "oid " + str(oid) + " not supported as array contents") except NotSupportedError: raise ArrayContentNotSupportedError( "type " + str(typ) + " not supported as array contents") if fc == FC_BINARY: def send_array(arr): # check that all array dimensions are consistent array_check_dimensions(arr) has_null = array_has_null(arr) dim_lengths = array_dim_lengths(arr) data = bytearray(iii_pack(len(dim_lengths), has_null, oid)) for i in dim_lengths: data.extend(ii_pack(i, 1)) for v in array_flatten(arr): if v is None: data += i_pack(-1) elif isinstance(v, typ): inner_data = send_func(v) data += i_pack(len(inner_data)) data += inner_data else: raise ArrayContentNotHomogenousError( "not all array elements are of type " + str(typ)) return data else: def send_array(arr): array_check_dimensions(arr) ar = deepcopy(arr) for a, i, v in walk_array(ar): if v is None: a[i] = 'NULL' elif isinstance(v, typ): a[i] = send_func(v).decode('ascii') else: raise ArrayContentNotHomogenousError( "not all array elements are of type " + str(typ)) return str(ar).translate(arr_trans).encode('ascii') return (array_oid, fc, send_array) def xid(self, format_id, global_transaction_id, branch_qualifier): """Create a Transaction IDs (only global_transaction_id is used in pg) format_id and branch_qualifier are not used in postgres global_transaction_id may be any string identifier supported by postgres returns a tuple (format_id, global_transaction_id, branch_qualifier)""" return (format_id, global_transaction_id, branch_qualifier) def tpc_begin(self, xid): """Begins a TPC transaction with the given transaction ID xid. This method should be called outside of a transaction (i.e. nothing may have executed since the last .commit() or .rollback()). Furthermore, it is an error to call .commit() or .rollback() within the TPC transaction. A ProgrammingError is raised, if the application calls .commit() or .rollback() during an active TPC transaction. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ self._xid = xid if self.autocommit: self.execute(self._cursor, "begin transaction", None) def tpc_prepare(self): """Performs the first phase of a transaction started with .tpc_begin(). A ProgrammingError is be raised if this method is called outside of a TPC transaction. After calling .tpc_prepare(), no statements can be executed until .tpc_commit() or .tpc_rollback() have been called. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ q = "PREPARE TRANSACTION '%s';" % (self._xid[1],) self.execute(self._cursor, q, None) def tpc_commit(self, xid=None): """When called with no arguments, .tpc_commit() commits a TPC transaction previously prepared with .tpc_prepare(). If .tpc_commit() is called prior to .tpc_prepare(), a single phase commit is performed. A transaction manager may choose to do this if only a single resource is participating in the global transaction. When called with a transaction ID xid, the database commits the given transaction. If an invalid transaction ID is provided, a ProgrammingError will be raised. This form should be called outside of a transaction, and is intended for use in recovery. On return, the TPC transaction is ended. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ if xid is None: xid = self._xid if xid is None: raise ProgrammingError( "Cannot tpc_commit() without a TPC transaction!") try: previous_autocommit_mode = self.autocommit self.autocommit = True if xid in self.tpc_recover(): self.execute( self._cursor, "COMMIT PREPARED '%s';" % (xid[1], ), None) else: # a single-phase commit self.commit() finally: self.autocommit = previous_autocommit_mode self._xid = None def tpc_rollback(self, xid=None): """When called with no arguments, .tpc_rollback() rolls back a TPC transaction. It may be called before or after .tpc_prepare(). When called with a transaction ID xid, it rolls back the given transaction. If an invalid transaction ID is provided, a ProgrammingError is raised. This form should be called outside of a transaction, and is intended for use in recovery. On return, the TPC transaction is ended. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ if xid is None: xid = self._xid if xid is None: raise ProgrammingError( "Cannot tpc_rollback() without a TPC prepared transaction!") try: previous_autocommit_mode = self.autocommit self.autocommit = True if xid in self.tpc_recover(): # a two-phase rollback self.execute( self._cursor, "ROLLBACK PREPARED '%s';" % (xid[1],), None) else: # a single-phase rollback self.rollback() finally: self.autocommit = previous_autocommit_mode self._xid = None def tpc_recover(self): """Returns a list of pending transaction IDs suitable for use with .tpc_commit(xid) or .tpc_rollback(xid). This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. """ try: previous_autocommit_mode = self.autocommit self.autocommit = True curs = self.cursor() curs.execute("select gid FROM pg_prepared_xacts") return [self.xid(0, row[0], '') for row in curs] finally: self.autocommit = previous_autocommit_mode # pg element oid -> pg array typeoid pg_array_types = { 16: 1000, 25: 1009, # TEXT[] 701: 1022, 1043: 1009, 1700: 1231, # NUMERIC[] } # PostgreSQL encodings: # http://www.postgresql.org/docs/8.3/interactive/multibyte.html # Python encodings: # http://www.python.org/doc/2.4/lib/standard-encodings.html # # Commented out encodings don't require a name change between PostgreSQL and # Python. If the py side is None, then the encoding isn't supported. pg_to_py_encodings = { # Not supported: "mule_internal": None, "euc_tw": None, # Name fine as-is: # "euc_jp", # "euc_jis_2004", # "euc_kr", # "gb18030", # "gbk", # "johab", # "sjis", # "shift_jis_2004", # "uhc", # "utf8", # Different name: "euc_cn": "gb2312", "iso_8859_5": "is8859_5", "iso_8859_6": "is8859_6", "iso_8859_7": "is8859_7", "iso_8859_8": "is8859_8", "koi8": "koi8_r", "latin1": "iso8859-1", "latin2": "iso8859_2", "latin3": "iso8859_3", "latin4": "iso8859_4", "latin5": "iso8859_9", "latin6": "iso8859_10", "latin7": "iso8859_13", "latin8": "iso8859_14", "latin9": "iso8859_15", "sql_ascii": "ascii", "win866": "cp886", "win874": "cp874", "win1250": "cp1250", "win1251": "cp1251", "win1252": "cp1252", "win1253": "cp1253", "win1254": "cp1254", "win1255": "cp1255", "win1256": "cp1256", "win1257": "cp1257", "win1258": "cp1258", "unicode": "utf-8", # Needed for Amazon Redshift } def walk_array(arr): for i, v in enumerate(arr): if isinstance(v, list): for a, i2, v2 in walk_array(v): yield a, i2, v2 else: yield arr, i, v def array_find_first_element(arr): for v in array_flatten(arr): if v is not None: return v return None def array_flatten(arr): for v in arr: if isinstance(v, list): for v2 in array_flatten(v): yield v2 else: yield v def array_check_dimensions(arr): if len(arr) > 0: v0 = arr[0] if isinstance(v0, list): req_len = len(v0) req_inner_lengths = array_check_dimensions(v0) for v in arr: inner_lengths = array_check_dimensions(v) if len(v) != req_len or inner_lengths != req_inner_lengths: raise ArrayDimensionsNotConsistentError( "array dimensions not consistent") retval = [req_len] retval.extend(req_inner_lengths) return retval else: # make sure nothing else at this level is a list for v in arr: if isinstance(v, list): raise ArrayDimensionsNotConsistentError( "array dimensions not consistent") return [] def array_has_null(arr): for v in array_flatten(arr): if v is None: return True return False def array_dim_lengths(arr): len_arr = len(arr) retval = [len_arr] if len_arr > 0: v0 = arr[0] if isinstance(v0, list): retval.extend(array_dim_lengths(v0)) return retval
84,100
Python
.py
1,971
32.157788
79
0.580056
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,927
models.py
zatosource_zato/code/patches/requests/models.py
# -*- coding: utf-8 -*- """ requests.models ~~~~~~~~~~~~~~~ This module contains the primary objects that power Requests. """ import datetime import sys # Import encoding now, to avoid implicit import later. # Implicit import within threads may cause LookupError when standard library is in a ZIP, # such as in Embedded Python. See https://github.com/psf/requests/issues/3578. import encodings.idna from urllib3.fields import RequestField from urllib3.filepost import encode_multipart_formdata from urllib3.util import parse_url from urllib3.exceptions import ( DecodeError, ReadTimeoutError, ProtocolError, LocationParseError) from io import UnsupportedOperation from .hooks import default_hooks from .structures import CaseInsensitiveDict from .auth import HTTPBasicAuth from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar from .exceptions import ( HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError, ContentDecodingError, ConnectionError, StreamConsumedError) from ._internal_utils import to_native_string, unicode_is_ascii from .utils import ( guess_filename, get_auth_from_url, requote_uri, stream_decode_response_unicode, to_key_val_list, parse_header_links, iter_slices, guess_json_utf, super_len, check_header_validity) from .compat import ( Callable, Mapping, cookielib, urlunparse, urlsplit, urlencode, str, bytes, is_py2, chardet, builtin_str, basestring) from .compat import json as complexjson from .status_codes import codes #: The set of HTTP status codes that indicate an automatically #: processable redirect. REDIRECT_STATI = ( codes.moved, # 301 codes.found, # 302 codes.other, # 303 codes.temporary_redirect, # 307 codes.permanent_redirect, # 308 ) DEFAULT_REDIRECT_LIMIT = 30 CONTENT_CHUNK_SIZE = 10 * 1024 ITER_CHUNK_SIZE = 512 class RequestEncodingMixin(object): @property def path_url(self): """Build the path URL to use.""" url = [] p = urlsplit(self.url) path = p.path if not path: path = '/' url.append(path) query = p.query if query: url.append('?') url.append(query) return ''.join(url) @staticmethod def _encode_params(data): """Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """ if isinstance(data, (str, bytes)): return data elif hasattr(data, 'read'): return data elif hasattr(data, '__iter__'): result = [] for k, vs in to_key_val_list(data): if isinstance(vs, basestring) or not hasattr(vs, '__iter__'): vs = [vs] for v in vs: if v is not None: result.append( (k.encode('utf-8') if isinstance(k, str) else k, v.encode('utf-8') if isinstance(v, str) else v)) return urlencode(result, doseq=True) else: return data @staticmethod def _encode_files(files, data): """Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). """ if (not files): raise ValueError("Files must be provided.") elif isinstance(data, basestring): raise ValueError("Data must not be a string.") new_fields = [] fields = to_key_val_list(data or {}) files = to_key_val_list(files or {}) for field, val in fields: if isinstance(val, basestring) or not hasattr(val, '__iter__'): val = [val] for v in val: if v is not None: # Don't call str() on bytestrings: in Py3 it all goes wrong. if not isinstance(v, bytes): v = str(v) new_fields.append( (field.decode('utf-8') if isinstance(field, bytes) else field, v.encode('utf-8') if isinstance(v, str) else v)) for (k, v) in files: # support for explicit filename ft = None fh = None if isinstance(v, (tuple, list)): if len(v) == 2: fn, fp = v elif len(v) == 3: fn, fp, ft = v else: fn, fp, ft, fh = v else: fn = guess_filename(v) or k fp = v if isinstance(fp, (str, bytes, bytearray)): fdata = fp elif hasattr(fp, 'read'): fdata = fp.read() elif fp is None: continue else: fdata = fp rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) rf.make_multipart(content_type=ft) new_fields.append(rf) body, content_type = encode_multipart_formdata(new_fields) return body, content_type class RequestHooksMixin(object): def register_hook(self, event, hook): """Properly register a hook.""" if event not in self.hooks and event != 'zato_pre_request': raise ValueError('Unsupported event specified, with event name "%s"' % (event)) if event == 'zato_pre_request': self.hooks[event] = [] if isinstance(hook, Callable): self.hooks[event].append(hook) elif hasattr(hook, '__iter__'): self.hooks[event].extend(h for h in hook if isinstance(h, Callable)) def deregister_hook(self, event, hook): """Deregister a previously registered hook. Returns True if the hook existed, False if not. """ try: self.hooks[event].remove(hook) return True except ValueError: return False class Request(RequestHooksMixin): """A user-created :class:`Request <Request>` object. Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server. :param method: HTTP method to use. :param url: URL to send. :param headers: dictionary of headers to send. :param files: dictionary of {filename: fileobject} files to multipart upload. :param data: the body to attach to the request. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param json: json for the body to attach to the request (if files or data is not specified). :param params: URL parameters to append to the URL. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param auth: Auth handler or (user, pass) tuple. :param cookies: dictionary or CookieJar of cookies to attach to this request. :param hooks: dictionary of callback hooks, for internal usage. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> req.prepare() <PreparedRequest [GET]> """ def __init__(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): # Default empty dicts for dict params. data = [] if data is None else data files = [] if files is None else files headers = {} if headers is None else headers params = {} if params is None else params hooks = {} if hooks is None else hooks self.hooks = default_hooks() for (k, v) in list(hooks.items()): self.register_hook(event=k, hook=v) self.method = method self.url = url self.headers = headers self.files = files self.data = data self.json = json self.params = params self.auth = auth self.cookies = cookies def __repr__(self): return '<Request [%s]>' % (self.method) def prepare(self): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, json=self.json, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, ) return p class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): """The fully mutable :class:`PreparedRequest <PreparedRequest>` object, containing the exact bytes that will be sent to the server. Instances are generated from a :class:`Request <Request>` object, and should not be instantiated manually; doing so may produce undesirable effects. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> r = req.prepare() >>> r <PreparedRequest [GET]> >>> s = requests.Session() >>> s.send(r) <Response [200]> """ def __init__(self): #: HTTP verb to send to the server. self.method = None #: HTTP URL to send the request to. self.url = None #: dictionary of HTTP headers. self.headers = None # The `CookieJar` used to create the Cookie header will be stored here # after prepare_cookies is called self._cookies = None #: request body to send to the server. self.body = None #: dictionary of callback hooks, for internal usage. self.hooks = default_hooks() #: integer denoting starting position of a readable file-like body. self._body_position = None def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): """Prepares the entire request with the given parameters.""" self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files, json) self.prepare_auth(auth, url) # Note that prepare_auth must be last to enable authentication schemes # such as OAuth to work on a fully prepared request. # This MUST go after prepare_auth. Authenticators could add a hook self.prepare_hooks(hooks) def __repr__(self): return '<PreparedRequest [%s]>' % (self.method) def copy(self): p = PreparedRequest() p.method = self.method p.url = self.url p.headers = self.headers.copy() if self.headers is not None else None p._cookies = _copy_cookie_jar(self._cookies) p.body = self.body p.hooks = self.hooks p._body_position = self._body_position return p def prepare_method(self, method): """Prepares the given HTTP method.""" self.method = method if self.method is not None: self.method = to_native_string(self.method.upper()) @staticmethod def _get_idna_encoded_host(host): import idna try: host = idna.encode(host, uts46=True).decode('utf-8') except idna.IDNAError: raise UnicodeError return host def prepare_url(self, url, params): """Prepares the given HTTP URL.""" #: Accept objects that have string representations. #: We're unable to blindly call unicode/str functions #: as this will include the bytestring indicator (b'') #: on python 3.x. #: https://github.com/psf/requests/pull/2238 if isinstance(url, bytes): url = url.decode('utf8') else: url = unicode(url) if is_py2 else str(url) # Remove leading whitespaces from url url = url.lstrip() # Don't do any URL preparation for non-HTTP schemes like `mailto`, # `data` etc to work around exceptions from `url_parse`, which # handles RFC 3986 only. if ':' in url and not url.lower().startswith('http'): self.url = url return # Support for unicode domain names and paths. try: scheme, auth, host, port, path, query, fragment = parse_url(url) except LocationParseError as e: raise InvalidURL(*e.args) if not scheme: error = ("Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?") error = error.format(to_native_string(url, 'utf8')) raise MissingSchema(error) if not host: raise InvalidURL("Invalid URL %r: No host supplied" % url) # In general, we want to try IDNA encoding the hostname if the string contains # non-ASCII characters. This allows users to automatically get the correct IDNA # behaviour. For strings containing only ASCII characters, we need to also verify # it doesn't start with a wildcard (*), before allowing the unencoded hostname. if not unicode_is_ascii(host): try: host = self._get_idna_encoded_host(host) except UnicodeError: raise InvalidURL('URL has an invalid label.') elif host.startswith(u'*'): raise InvalidURL('URL has an invalid label.') # Carefully reconstruct the network location netloc = auth or '' if netloc: netloc += '@' netloc += host if port: netloc += ':' + str(port) # Bare domains aren't valid URLs. if not path: path = '/' if is_py2: if isinstance(scheme, str): scheme = scheme.encode('utf-8') if isinstance(netloc, str): netloc = netloc.encode('utf-8') if isinstance(path, str): path = path.encode('utf-8') if isinstance(query, str): query = query.encode('utf-8') if isinstance(fragment, str): fragment = fragment.encode('utf-8') if isinstance(params, (str, bytes)): params = to_native_string(params) enc_params = self._encode_params(params) if enc_params: if query: query = '%s&%s' % (query, enc_params) else: query = enc_params url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment])) self.url = url def prepare_headers(self, headers): """Prepares the given HTTP headers.""" self.headers = CaseInsensitiveDict() if headers: for header in headers.items(): # Raise exception on invalid header value. check_header_validity(header) name, value = header self.headers[to_native_string(name)] = value def prepare_body(self, data, files, json=None): """Prepares the given HTTP body data.""" # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None if not data and json is not None: # urllib3 requires a bytes-like body. Python 2's json.dumps # provides this natively, but Python 3 gives a Unicode string. content_type = 'application/json' body = complexjson.dumps(json) if not isinstance(body, bytes): body = body.encode('utf-8') is_stream = all([ hasattr(data, '__iter__'), not isinstance(data, (basestring, list, tuple, Mapping)) ]) if is_stream: try: length = super_len(data) except (TypeError, AttributeError, UnsupportedOperation): length = None body = data if getattr(body, 'tell', None) is not None: # Record the current file position before reading. # This will allow us to rewind a file in the event # of a redirect. try: self._body_position = body.tell() except (IOError, OSError): # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body self._body_position = object() if files: raise NotImplementedError('Streamed bodies and files are mutually exclusive.') if length: self.headers['Content-Length'] = builtin_str(length) else: self.headers['Transfer-Encoding'] = 'chunked' else: # Multi-part file uploads. if files: (body, content_type) = self._encode_files(files, data) else: if data: body = self._encode_params(data) if isinstance(data, basestring) or hasattr(data, 'read'): content_type = None else: content_type = 'application/x-www-form-urlencoded' self.prepare_content_length(body) # Add content-type if it wasn't explicitly provided. if content_type and ('content-type' not in self.headers): self.headers['Content-Type'] = content_type self.body = body def prepare_content_length(self, body): """Prepare Content-Length header based on request method and body""" if body is not None: length = super_len(body) if length: # If length exists, set it. Otherwise, we fallback # to Transfer-Encoding: chunked. self.headers['Content-Length'] = builtin_str(length) elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None: # Set Content-Length to 0 for methods that can have a body # but don't provide one. (i.e. not GET or HEAD) self.headers['Content-Length'] = '0' def prepare_auth(self, auth, url=''): """Prepares the given HTTP auth data.""" # If no Auth is explicitly provided, extract it from the URL first. if auth is None: url_auth = get_auth_from_url(self.url) auth = url_auth if any(url_auth) else None if auth: if isinstance(auth, tuple) and len(auth) == 2: # special-case basic HTTP auth auth = HTTPBasicAuth(*auth) # Allow auth to make its changes. r = auth(self) # Update self to reflect the auth changes. self.__dict__.update(r.__dict__) # Recompute Content-Length self.prepare_content_length(self.body) def prepare_cookies(self, cookies): """Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls to ``prepare_cookies`` will have no actual effect, unless the "Cookie" header is removed beforehand. """ if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) if cookie_header is not None: self.headers['Cookie'] = cookie_header def prepare_hooks(self, hooks): """Prepares the given hooks.""" # hooks can be passed as None to the prepare method and to this # method. To prevent iterating over None, simply use an empty list # if hooks is False-y hooks = hooks or [] for event in hooks: self.register_hook(event, hooks[event]) class Response(object): """The :class:`Response <Response>` object, which contains a server's response to an HTTP request. """ __attrs__ = [ '_content', 'status_code', 'headers', 'url', 'history', 'encoding', 'reason', 'cookies', 'elapsed', 'request' ] def __init__(self): self._content = False self._content_consumed = False self._next = None #: Integer Code of responded HTTP Status, e.g. 404 or 200. self.status_code = None #: Case-insensitive Dictionary of Response Headers. #: For example, ``headers['content-encoding']`` will return the #: value of a ``'Content-Encoding'`` response header. self.headers = CaseInsensitiveDict() #: File-like object representation of response (for advanced usage). #: Use of ``raw`` requires that ``stream=True`` be set on the request. #: This requirement does not apply for use internally to Requests. self.raw = None #: Final URL location of Response. self.url = None #: Encoding to decode with when accessing r.text. self.encoding = None #: A list of :class:`Response <Response>` objects from #: the history of the Request. Any redirect responses will end #: up here. The list is sorted from the oldest to the most recent request. self.history = [] #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK". self.reason = None #: A CookieJar of Cookies the server sent back. self.cookies = cookiejar_from_dict({}) #: The amount of time elapsed between sending the request #: and the arrival of the response (as a timedelta). #: This property specifically measures the time taken between sending #: the first byte of the request and finishing parsing the headers. It #: is therefore unaffected by consuming the response content or the #: value of the ``stream`` keyword argument. self.elapsed = datetime.timedelta(0) #: The :class:`PreparedRequest <PreparedRequest>` object to which this #: is a response. self.request = None def __enter__(self): return self def __exit__(self, *args): self.close() def __getstate__(self): # Consume everything; accessing the content attribute makes # sure the content has been fully read. if not self._content_consumed: self.content return {attr: getattr(self, attr, None) for attr in self.__attrs__} def __setstate__(self, state): for name, value in state.items(): setattr(self, name, value) # pickled objects do not have .raw setattr(self, '_content_consumed', True) setattr(self, 'raw', None) def __repr__(self): return '<Response [%s]>' % (self.status_code) def __bool__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ return self.ok def __nonzero__(self): """Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ return self.ok def __iter__(self): """Allows you to use a response as an iterator.""" return self.iter_content(128) @property def ok(self): """Returns True if :attr:`status_code` is less than 400, False if not. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK``. """ try: self.raise_for_status() except HTTPError: return False return True @property def is_redirect(self): """True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`). """ return ('location' in self.headers and self.status_code in REDIRECT_STATI) @property def is_permanent_redirect(self): """True if this Response one of the permanent versions of redirect.""" return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect)) @property def next(self): """Returns a PreparedRequest for the next request in a redirect chain, if there is one.""" return self._next @property def apparent_encoding(self): """The apparent encoding, provided by the chardet library.""" return chardet.detect(self.content)['encoding'] def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. chunk_size must be of type int or None. A value of None will function differently depending on the value of `stream`. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk. If decode_unicode is True, content will be decoded using the best available encoding based on the response. """ def generate(): # Special case for urllib3. if hasattr(self.raw, 'stream'): try: for chunk in self.raw.stream(chunk_size, decode_content=True): yield chunk except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except ReadTimeoutError as e: raise ConnectionError(e) else: # Standard file-like object. while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk self._content_consumed = True if self._content_consumed and isinstance(self._content, bool): raise StreamConsumedError() elif chunk_size is not None and not isinstance(chunk_size, int): raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size)) # simulate reading small chunks of the content reused_chunks = iter_slices(self._content, chunk_size) stream_chunks = generate() chunks = reused_chunks if self._content_consumed else stream_chunks if decode_unicode: chunks = stream_decode_response_unicode(chunks, self) return chunks def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None): """Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. .. note:: This method is not reentrant safe. """ pending = None for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode): if pending is not None: chunk = pending + chunk if delimiter: lines = chunk.split(delimiter) else: lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None for line in lines: yield line if pending is not None: yield pending @property def content(self): """Content of the response, in bytes.""" if self._content is False: # Read the contents. if self._content_consumed: raise RuntimeError( 'The content for this response was already consumed') if self.status_code == 0 or self.raw is None: self._content = None else: self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b'' self._content_consumed = True # don't need to release the connection; that's been handled by urllib3 # since we exhausted the data. return self._content @property def text(self): """Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set ``r.encoding`` appropriately before accessing this property. """ # Try charset from content-type content = None encoding = self.encoding if not self.content: return str('') # Fallback to auto-detected encoding. if self.encoding is None: encoding = self.apparent_encoding # Decode unicode from given encoding. try: content = str(self.content, encoding, errors='replace') except (LookupError, TypeError): # A LookupError is raised if the encoding was not found which could # indicate a misspelling or similar mistake. # # A TypeError can be raised if encoding is None # # So we try blindly encoding. content = str(self.content, errors='replace') return content def json(self, **kwargs): r"""Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. :raises ValueError: If the response body does not contain valid json. """ if not self.encoding and self.content and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return complexjson.loads( self.content.decode(encoding), **kwargs ) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass return complexjson.loads(self.text, **kwargs) @property def links(self): """Returns the parsed header links of the response, if any.""" header = self.headers.get('link') # l = MultiDict() l = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel') or link.get('url') l[key] = link return l def raise_for_status(self): """Raises :class:`HTTPError`, if one occurred.""" http_error_msg = '' if isinstance(self.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn't utf-8, we fall back to iso-8859-1 for all other # encodings. (See PR #3538) try: reason = self.reason.decode('utf-8') except UnicodeDecodeError: reason = self.reason.decode('iso-8859-1') else: reason = self.reason if 400 <= self.status_code < 500: http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url) elif 500 <= self.status_code < 600: http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url) if http_error_msg: raise HTTPError(http_error_msg, response=self) def close(self): """Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.* """ if not self._content_consumed: self.raw.close() release_conn = getattr(self.raw, 'release_conn', None) if release_conn is not None: release_conn()
34,416
Python
.py
774
33.910853
119
0.598171
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,928
sessions.py
zatosource_zato/code/patches/requests/sessions.py
# -*- coding: utf-8 -*- """ requests.session ~~~~~~~~~~~~~~~~ This module provides a Session object to manage and persist settings across requests (cookies, auth, proxies). """ import os import sys import time from datetime import timedelta from collections import OrderedDict from .auth import _basic_auth_str from .compat import cookielib, is_py3, urljoin, urlparse, Mapping from .cookies import ( cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies) from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT from .hooks import default_hooks, dispatch_hook from ._internal_utils import to_native_string from .utils import to_key_val_list, default_headers, DEFAULT_PORTS from .exceptions import ( TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError) from .structures import CaseInsensitiveDict from .adapters import HTTPAdapter from .utils import ( requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies, get_auth_from_url, rewind_body ) from .status_codes import codes # formerly defined here, reexposed here for backward compatibility from .models import REDIRECT_STATI # Preferred clock, based on which one is more accurate on a given system. if sys.platform == 'win32': try: # Python 3.4+ preferred_clock = time.perf_counter except AttributeError: # Earlier than Python 3. preferred_clock = time.clock else: preferred_clock = time.time def merge_setting(request_setting, session_setting, dict_class=OrderedDict): """Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class` """ if session_setting is None: return request_setting if request_setting is None: return session_setting # Bypass if not a dictionary (e.g. verify) if not ( isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) ): return request_setting merged_setting = dict_class(to_key_val_list(session_setting)) merged_setting.update(to_key_val_list(request_setting)) # Remove keys that are set to None. Extract keys first to avoid altering # the dictionary during iteration. none_keys = [k for (k, v) in merged_setting.items() if v is None] for key in none_keys: del merged_setting[key] return merged_setting def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. """ if session_hooks is None or session_hooks.get('response') == []: return request_hooks if request_hooks is None or request_hooks.get('response') == []: return session_hooks return merge_setting(request_hooks, session_hooks, dict_class) class SessionRedirectMixin(object): def get_redirect_target(self, resp): """Receives a Response. Returns a redirect URI or ``None``""" # Due to the nature of how requests processes redirects this method will # be called at least once upon the original response and at least twice # on each subsequent redirect response (if any). # If a custom mixin is used to handle this logic, it may be advantageous # to cache the redirect location onto the response object as a private # attribute. if resp.is_redirect: location = resp.headers['location'] # Currently the underlying http module on py3 decode headers # in latin1, but empirical evidence suggests that latin1 is very # rarely used with non-ASCII characters in HTTP headers. # It is more likely to get UTF8 header rather than latin1. # This causes incorrect handling of UTF8 encoded location headers. # To solve this, we re-encode the location in latin1. if is_py3: location = location.encode('latin1') return to_native_string(location, 'utf8') return None def should_strip_auth(self, old_url, new_url): """Decide whether Authorization header should be removed when redirecting""" old_parsed = urlparse(old_url) new_parsed = urlparse(new_url) if old_parsed.hostname != new_parsed.hostname: return True # Special case: allow http -> https redirect when using the standard # ports. This isn't specified by RFC 7235, but is kept to avoid # breaking backwards compatibility with older versions of requests # that allowed any redirects on the same host. if (old_parsed.scheme == 'http' and old_parsed.port in (80, None) and new_parsed.scheme == 'https' and new_parsed.port in (443, None)): return False # Handle default port usage corresponding to scheme. changed_port = old_parsed.port != new_parsed.port changed_scheme = old_parsed.scheme != new_parsed.scheme default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) if (not changed_scheme and old_parsed.port in default_port and new_parsed.port in default_port): return False # Standard case: root URI must match return changed_port or changed_scheme def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs): """Receives a Response. Returns a generator of Responses or Requests.""" hist = [] # keep track of history url = self.get_redirect_target(resp) previous_fragment = urlparse(req.url).fragment while url: prepared_request = req.copy() # Update history and keep track of redirects. # resp.history must ignore the original request in this loop hist.append(resp) resp.history = hist[1:] try: resp.content # Consume socket so it can be released except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=False) if len(resp.history) >= self.max_redirects: raise TooManyRedirects('Exceeded {} redirects.'.format(self.max_redirects), response=resp) # Release the connection back into the pool. resp.close() # Handle redirection without scheme (see: RFC 1808 Section 4) if url.startswith('//'): parsed_rurl = urlparse(resp.url) url = ':'.join([to_native_string(parsed_rurl.scheme), url]) # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2) parsed = urlparse(url) if parsed.fragment == '' and previous_fragment: parsed = parsed._replace(fragment=previous_fragment) elif parsed.fragment: previous_fragment = parsed.fragment url = parsed.geturl() # Facilitate relative 'location' headers, as allowed by RFC 7231. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') # Compliant with RFC3986, we percent encode the url. if not parsed.netloc: url = urljoin(resp.url, requote_uri(url)) else: url = requote_uri(url) prepared_request.url = to_native_string(url) self.rebuild_method(prepared_request, resp) # https://github.com/psf/requests/issues/1084 if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect): # https://github.com/psf/requests/issues/3490 purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding') for header in purged_headers: prepared_request.headers.pop(header, None) prepared_request.body = None headers = prepared_request.headers headers.pop('Cookie', None) # Extract any cookies sent on the response to the cookiejar # in the new request. Because we've mutated our copied prepared # request, use the old one that we haven't yet touched. extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) merge_cookies(prepared_request._cookies, self.cookies) prepared_request.prepare_cookies(prepared_request._cookies) # Rebuild auth and proxy information. proxies = self.rebuild_proxies(prepared_request, proxies) self.rebuild_auth(prepared_request, resp) # A failed tell() sets `_body_position` to `object()`. This non-None # value ensures `rewindable` will be True, allowing us to raise an # UnrewindableBodyError, instead of hanging the connection. rewindable = ( prepared_request._body_position is not None and ('Content-Length' in headers or 'Transfer-Encoding' in headers) ) # Attempt to rewind consumed file-like object. if rewindable: rewind_body(prepared_request) # Override the original request. req = prepared_request if yield_requests: yield req else: resp = self.send( req, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, allow_redirects=False, **adapter_kwargs ) extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) # extract redirect url, if any, for the next loop url = self.get_redirect_target(resp) yield resp def rebuild_auth(self, prepared_request, response): """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ headers = prepared_request.headers url = prepared_request.url if 'Authorization' in headers and self.should_strip_auth(response.request.url, url): # If we get redirected to a new host, we should strip out any # authentication headers. del headers['Authorization'] # .netrc might have more auth for us on our new host. new_auth = get_netrc_auth(url) if self.trust_env else None if new_auth is not None: prepared_request.prepare_auth(new_auth) def rebuild_proxies(self, prepared_request, proxies): """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict """ proxies = proxies if proxies is not None else {} headers = prepared_request.headers url = prepared_request.url scheme = urlparse(url).scheme new_proxies = proxies.copy() no_proxy = proxies.get('no_proxy') bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy) if self.trust_env and not bypass_proxy: environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) proxy = environ_proxies.get(scheme, environ_proxies.get('all')) if proxy: new_proxies.setdefault(scheme, proxy) if 'Proxy-Authorization' in headers: del headers['Proxy-Authorization'] try: username, password = get_auth_from_url(new_proxies[scheme]) except KeyError: username, password = None, None if username and password: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return new_proxies def rebuild_method(self, prepared_request, response): """When being redirected we may want to change the method of the request based on certain specs or browser behavior. """ method = prepared_request.method # https://tools.ietf.org/html/rfc7231#section-6.4.4 if response.status_code == codes.see_other and method != 'HEAD': method = 'GET' # Do what the browsers do, despite standards... # First, turn 302s into GETs. if response.status_code == codes.found and method != 'HEAD': method = 'GET' # Second, if a POST is responded to with a 301, turn it into a GET. # This bizarre behaviour is explained in Issue 1704. if response.status_code == codes.moved and method == 'POST': method = 'GET' prepared_request.method = method class Session(SessionRedirectMixin): """A Requests session. Provides cookie persistence, connection-pooling, and configuration. Basic Usage:: >>> import requests >>> s = requests.Session() >>> s.get('https://httpbin.org/get') <Response [200]> Or as a context manager:: >>> with requests.Session() as s: ... s.get('https://httpbin.org/get') <Response [200]> """ __attrs__ = [ 'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify', 'cert', 'adapters', 'stream', 'trust_env', 'max_redirects', ] def __init__(self, pool_connections=300): #: A case-insensitive dictionary of headers to be sent on each #: :class:`Request <Request>` sent from this #: :class:`Session <Session>`. self.headers = default_headers() #: Default Authentication tuple or object to attach to #: :class:`Request <Request>`. self.auth = None #: Dictionary mapping protocol or protocol and host to the URL of the proxy #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to #: be used on each :class:`Request <Request>`. self.proxies = {} #: Event-handling hooks. self.hooks = default_hooks() #: Dictionary of querystring data to attach to each #: :class:`Request <Request>`. The dictionary values may be lists for #: representing multivalued query parameters. self.params = {} #: Stream response content default. self.stream = False #: SSL Verification default. #: Defaults to `True`, requiring requests to verify the TLS certificate at the #: remote end. #: If verify is set to `False`, requests will accept any TLS certificate #: presented by the server, and will ignore hostname mismatches and/or #: expired certificates, which will make your application vulnerable to #: man-in-the-middle (MitM) attacks. #: Only set this to `False` for testing. self.verify = True #: SSL client certificate default, if String, path to ssl client #: cert file (.pem). If Tuple, ('cert', 'key') pair. self.cert = None #: Maximum number of redirects allowed. If the request exceeds this #: limit, a :class:`TooManyRedirects` exception is raised. #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is #: 30. self.max_redirects = DEFAULT_REDIRECT_LIMIT #: Trust environment settings for proxy configuration, default #: authentication and similar. self.trust_env = True #: A CookieJar containing all currently outstanding cookies set on this #: session. By default it is a #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but #: may be any other ``cookielib.CookieJar`` compatible object. self.cookies = cookiejar_from_dict({}) # Default connection adapters. self.adapters = OrderedDict() self.mount('https://', HTTPAdapter(pool_connections=pool_connections, pool_maxsize=500)) self.mount('http://', HTTPAdapter(pool_connections=pool_connections, pool_maxsize=500)) def __enter__(self): return self def __exit__(self, *args): self.close() def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None): """Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. When set to ``False``, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to ``False`` may be useful during local development or testing. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response """ # Create the Request. req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { 'timeout': timeout, 'allow_redirects': allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs) def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('OPTIONS', url, **kwargs) def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) return self.request('HEAD', url, **kwargs) def post(self, url, data=None, json=None, **kwargs): r"""Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('POST', url, data=data, json=json, **kwargs) def put(self, url, data=None, **kwargs): r"""Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('PUT', url, data=data, **kwargs) def patch(self, url, data=None, **kwargs): r"""Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('PATCH', url, data=data, **kwargs) def delete(self, url, **kwargs): r"""Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('DELETE', url, **kwargs) def send(self, request, **kwargs): """Send a given PreparedRequest. :rtype: requests.Response """ # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the previous request. kwargs.setdefault('stream', self.stream) kwargs.setdefault('verify', self.verify) kwargs.setdefault('cert', self.cert) kwargs.setdefault('proxies', self.proxies) # It's possible that users might accidentally send a Request object. # Guard against that specific failure case. if isinstance(request, Request): raise ValueError('You can only send PreparedRequests.') # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop('allow_redirects', True) stream = kwargs.get('stream') hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) zato_pre_request_data = {'session':self, 'request':request, 'kwargs':kwargs} dispatch_hook('zato_pre_request', hooks, zato_pre_request_data) # Start time (approximately) of the request start = preferred_clock() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) elapsed = preferred_clock() - start r.elapsed = timedelta(seconds=elapsed) # Response manipulation hooks r = dispatch_hook('response', hooks, r, **kwargs) # Persist cookies if r.history: # If the hooks create history then we want those cookies too for resp in r.history: extract_cookies_to_jar(self.cookies, resp.request, resp.raw) extract_cookies_to_jar(self.cookies, request, r.raw) # Resolve redirects if allowed. if allow_redirects: # Redirect resolving generator. gen = self.resolve_redirects(r, request, **kwargs) history = [resp for resp in gen] else: history = [] # Shuffle things around if there's history. if history: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made r = history.pop() r.history = history # If redirects aren't being followed, store the response on the Request for Response.next(). if not allow_redirects: try: r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs)) except StopIteration: pass if not stream: r.content return r def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. no_proxy = proxies.get('no_proxy') if proxies is not None else None env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # Look for requests environment configuration and be compatible # with cURL. if verify is True or verify is None: verify = (os.environ.get('REQUESTS_CA_BUNDLE') or os.environ.get('CURL_CA_BUNDLE')) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {'verify': verify, 'proxies': proxies, 'stream': stream, 'cert': cert} def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema("No connection adapters were found for {!r}".format(url)) def close(self): """Closes all adapters and as such the session""" for v in self.adapters.values(): v.close() def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key) def __getstate__(self): state = {attr: getattr(self, attr, None) for attr in self.__attrs__} return state def __setstate__(self, state): for attr, value in state.items(): setattr(self, attr, value) def session(): """ Returns a :class:`Session` for context-management. .. deprecated:: 1.0.0 This method has been deprecated since version 1.0.0 and is only kept for backwards compatibility. New code should use :class:`~requests.sessions.Session` to create a session. This may be removed at a future date. :rtype: Session """ return Session()
30,417
Python
.py
621
38.966184
106
0.632707
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,929
HTTPNtlmAuthHandler.py
zatosource_zato/code/patches/ntlm/HTTPNtlmAuthHandler.py
# This library is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library. If not, see <http://www.gnu.org/licenses/> or <http://www.gnu.org/licenses/lgpl.txt>. import urllib2 import httplib, socket from urllib import addinfourl import ntlm import re class AbstractNtlmAuthHandler: def __init__(self, password_mgr=None, debuglevel=0): """Initialize an instance of a AbstractNtlmAuthHandler. Verify operation with all default arguments. >>> abstrct = AbstractNtlmAuthHandler() Verify "normal" operation. >>> abstrct = AbstractNtlmAuthHandler(urllib2.HTTPPasswordMgrWithDefaultRealm()) """ if password_mgr is None: password_mgr = urllib2.HTTPPasswordMgr() self.passwd = password_mgr self.add_password = self.passwd.add_password self._debuglevel = debuglevel def set_http_debuglevel(self, level): self._debuglevel = level def http_error_authentication_required(self, auth_header_field, req, fp, headers): auth_header_value = headers.get(auth_header_field, None) if auth_header_field: if auth_header_value is not None and 'ntlm' in auth_header_value.lower(): fp.close() return self.retry_using_http_NTLM_auth(req, auth_header_field, None, headers) def retry_using_http_NTLM_auth(self, req, auth_header_field, realm, headers): user, pw = self.passwd.find_user_password(realm, req.get_full_url()) if pw is not None: user_parts = user.split('\\', 1) if len(user_parts) == 1: UserName = user_parts[0] DomainName = '' type1_flags = ntlm.NTLM_TYPE1_FLAGS & ~ntlm.NTLM_NegotiateOemDomainSupplied else: DomainName = user_parts[0].upper() UserName = user_parts[1] type1_flags = ntlm.NTLM_TYPE1_FLAGS # ntlm secures a socket, so we must use the same socket for the complete handshake headers = dict(req.headers) headers.update(req.unredirected_hdrs) auth = 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(user, type1_flags) if req.headers.get(self.auth_header, None) == auth: return None headers[self.auth_header] = auth host = req.get_host() if not host: raise urllib2.URLError('no host given') h = None if req.get_full_url().startswith('https://'): h = httplib.HTTPSConnection(host) # will parse host:port else: h = httplib.HTTPConnection(host) # will parse host:port h.set_debuglevel(self._debuglevel) # we must keep the connection because NTLM authenticates the connection, not single requests headers["Connection"] = "Keep-Alive" headers = dict((name.title(), val) for name, val in headers.items()) h.request(req.get_method(), req.get_selector(), req.data, headers) r = h.getresponse() r.begin() r._safe_read(int(r.getheader('content-length'))) if r.getheader('set-cookie'): # this is important for some web applications that store authentication-related info in cookies (it took a long time to figure out) headers['Cookie'] = r.getheader('set-cookie') r.fp = None # remove the reference to the socket, so that it can not be closed by the response object (we want to keep the socket open) auth_header_value = r.getheader(auth_header_field, None) # some Exchange servers send two WWW-Authenticate headers, one with the NTLM challenge # and another with the 'Negotiate' keyword - make sure we operate on the right one m = re.match('(NTLM [A-Za-z0-9+\-/=]+)', auth_header_value) if m: auth_header_value, = m.groups() (ServerChallenge, NegotiateFlags) = ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value[5:]) auth = 'NTLM %s' % ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge, UserName, DomainName, pw, NegotiateFlags) headers[self.auth_header] = auth headers["Connection"] = "Close" headers = dict((name.title(), val) for name, val in headers.items()) try: h.request(req.get_method(), req.get_selector(), req.data, headers) # none of the configured handlers are triggered, for example redirect-responses are not handled! response = h.getresponse() def notimplemented(): raise NotImplementedError response.readline = notimplemented infourl = addinfourl(response, response.msg, req.get_full_url()) infourl.code = response.status infourl.msg = response.reason return infourl except socket.error as err: raise urllib2.URLError(err) else: return None class HTTPNtlmAuthHandler(AbstractNtlmAuthHandler, urllib2.BaseHandler): auth_header = 'Authorization' def http_error_401(self, req, fp, code, msg, headers): return self.http_error_authentication_required('www-authenticate', req, fp, headers) class ProxyNtlmAuthHandler(AbstractNtlmAuthHandler, urllib2.BaseHandler): """ CAUTION: this class has NOT been tested at all!!! use at your own risk """ auth_header = 'Proxy-authorization' def http_error_407(self, req, fp, code, msg, headers): return self.http_error_authentication_required('proxy-authenticate', req, fp, headers) if __name__ == "__main__": import doctest doctest.testmod() ### TODO: Move this to the ntlm examples directory. ##if __name__ == "__main__": ## url = "http://ntlmprotectedserver/securedfile.html" ## user = u'DOMAIN\\User' ## password = 'Password' ## ## passman = urllib2.HTTPPasswordMgrWithDefaultRealm() ## passman.add_password(None, url, user , password) ## auth_basic = urllib2.HTTPBasicAuthHandler(passman) ## auth_digest = urllib2.HTTPDigestAuthHandler(passman) ## auth_NTLM = HTTPNtlmAuthHandler(passman) ## ## # disable proxies (just for testing) ## proxy_handler = urllib2.ProxyHandler({}) ## ## opener = urllib2.build_opener(proxy_handler, auth_NTLM) #, auth_digest, auth_basic) ## ## urllib2.install_opener(opener) ## ## response = urllib2.urlopen(url) ## print(response.read())
7,060
Python
.py
138
42.333333
147
0.649036
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,930
topic.py
zatosource_zato/code/patches/pykafka/topic.py
""" Author: Keith Bourgoin, Emmett Butler """ __license__ = """ Copyright 2015 Parse.ly, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ __all__ = ["Topic"] import datetime as dt import logging from collections import defaultdict from .balancedconsumer import BalancedConsumer from .common import OffsetType, EPOCH from .exceptions import LeaderNotFoundError from .managedbalancedconsumer import ManagedBalancedConsumer from .partition import Partition from .producer import Producer from .protocol import PartitionOffsetRequest from .simpleconsumer import SimpleConsumer from .utils.compat import iteritems, itervalues try: from .handlers import GEventHandler except ImportError: GEventHandler = None log = logging.getLogger(__name__) try: from . import rdkafka log.info("Successfully loaded pykafka.rdkafka extension.") except ImportError: rdkafka = False log.info("Could not load pykafka.rdkafka extension.") class Topic(object): """ A Topic is an abstraction over the kafka concept of a topic. It contains a dictionary of partitions that comprise it. """ def __init__(self, cluster, topic_metadata): """Create the Topic from metadata. :param cluster: The Cluster to use :type cluster: :class:`pykafka.cluster.Cluster` :param topic_metadata: Metadata for all topics. :type topic_metadata: :class:`pykafka.protocol.TopicMetadata` """ self._name = topic_metadata.name self._cluster = cluster self._partitions = {} self.update(topic_metadata) def __repr__(self): return "<{module}.{classname} at {id_} (name={name})>".format( module=self.__class__.__module__, classname=self.__class__.__name__, id_=hex(id(self)), name=self._name ) @property def name(self): """The name of this topic""" return self._name @property def partitions(self): """A dictionary containing all known partitions for this topic""" return self._partitions def get_producer(self, use_rdkafka=False, **kwargs): """Create a :class:`pykafka.producer.Producer` for this topic. For a description of all available `kwargs`, see the Producer docstring. """ if not rdkafka and use_rdkafka: raise ImportError("use_rdkafka requires rdkafka to be installed") if GEventHandler and isinstance(self._cluster.handler, GEventHandler) and use_rdkafka: raise ImportError("use_rdkafka cannot be used with gevent") Cls = Producer if rdkafka and use_rdkafka: Cls = rdkafka.RdKafkaProducer kwargs.pop('block_on_queue_full', None) return Cls(self._cluster, self, **kwargs) def get_sync_producer(self, **kwargs): """Create a :class:`pykafka.producer.Producer` for this topic. The created `Producer` instance will have `sync=True`. For a description of all available `kwargs`, see the Producer docstring. """ return Producer(self._cluster, self, sync=True, **kwargs) def fetch_offset_limits(self, offsets_before, max_offsets=1): """Get information about the offsets of log segments for this topic The ListOffsets API, which this function relies on, primarily deals with topics in terms of their log segments. Its behavior can be summed up as follows: it returns some subset of starting message offsets for the log segments of each partition. The particular subset depends on this function's two arguments, filtering by timestamp and in certain cases, count. The documentation for this API is notoriously imprecise, so here's a little example to illustrate how it works. Take a topic with three partitions 0,1,2. 2665 messages have been produced to this topic, and the brokers' `log.segment.bytes` settings are configured such that each log segment contains roughly 530 messages. The two oldest log segments have been deleted due to log retention settings such as `log.retention.hours`. Thus, the `log.dirs` currently contains these files for partition 0: /var/local/kafka/data/test2-0/00000000000000001059.log /var/local/kafka/data/test2-0/00000000000000002119.log /var/local/kafka/data/test2-0/00000000000000001589.log /var/local/kafka/data/test2-0/00000000000000002649.log The numbers on these filenames indicate the offset of the earliest message contained within. The most recent message was written at 1523572215.69. Given this log state, a call to this function with offsets_before=OffsetType.LATEST and max_offsets=100 will result in a return value of [2665,2649,2119,1589,1059] for partition 0. The first value (2665) is the offset of the latest available message from the latest log segment. The other four offsets are those of the earliest messages from each log segment for the partition. Changing max_offsets to 3 will result in only the first three elements of this list being returned. A call to this function with offsets_before=OffsetType.EARLIEST will result in a value of [1059] - only the offset of the earliest message present in log segments for partition 0. In this case, the return value is not affected by max_offsets. A call to this function with offsets_before=(1523572215.69 * 1000) (the timestamp in milliseconds of the very last message written to the partition) will result in a value of [2649,2119,1589,1059]. This is the same list as with OffsetType.LATEST, but with the first element removed. This is because unlike the other elements, the message with this offset (2665) was not written *before* the given timestamp. In cases where there are no log segments fitting the given criteria for a partition, an empty list is returned. This applies if the given timestamp is before the write time of the oldest message in the partition, as well as if there are no log segments for the partition. Thanks to Andras Beni from the Kafka users mailing list for providing this example. :param offsets_before: Epoch timestamp in milliseconds or datetime indicating the latest write time for returned offsets. Only offsets of messages written before this timestamp will be returned. Permissible special values are `common.OffsetType.LATEST`, indicating that offsets from all available log segments should be returned, and `common.OffsetType.EARLIEST`, indicating that only the offset of the earliest available message should be returned. Deprecated::2.7,3.6: do not use int :type offsets_before: `datetime.datetime` or int :param max_offsets: The maximum number of offsets to return when more than one is available. In the case where `offsets_before == OffsetType.EARLIEST`, this parameter is meaningless since there is always either one or zero earliest offsets. In other cases, this parameter slices off the earliest end of the list, leaving the latest `max_offsets` offsets. :type max_offsets: int """ if isinstance(offsets_before, dt.datetime): offsets_before = round((offsets_before - EPOCH).total_seconds() * 1000) requests = defaultdict(list) # one request for each broker for part in itervalues(self.partitions): requests[part.leader].append(PartitionOffsetRequest( self.name, part.id, offsets_before, max_offsets )) output = {} for broker, reqs in iteritems(requests): res = broker.request_offset_limits(reqs) output.update(res.topics[self.name]) return output def earliest_available_offsets(self): """Get the earliest offset for each partition of this topic.""" return self.fetch_offset_limits(OffsetType.EARLIEST) def latest_available_offsets(self): """Fetch the next available offset Get the offset of the next message that would be appended to each partition of this topic. """ return self.fetch_offset_limits(OffsetType.LATEST) def update(self, metadata): """Update the Partitions with metadata about the cluster. :param metadata: Metadata for all topics :type metadata: :class:`pykafka.protocol.TopicMetadata` """ p_metas = metadata.partitions # Remove old partitions removed = set(self._partitions.keys()) - set(p_metas.keys()) if len(removed) > 0: log.info('Removing %d partitions', len(removed)) for id_ in removed: log.debug('Removing partition %s', self._partitions[id_]) self._partitions.pop(id_) # Add/update current partitions brokers = self._cluster.brokers if len(p_metas) > 0: log.info("Adding %d partitions", len(p_metas)) for id_, meta in iteritems(p_metas): if meta.leader not in brokers: raise LeaderNotFoundError() if meta.id not in self._partitions: log.debug('Adding partition %s/%s', self.name, meta.id) self._partitions[meta.id] = Partition( self, meta.id, brokers[meta.leader], # only add replicas that the cluster is aware of to avoid # KeyErrors here. inconsistencies will be automatically # resolved when `Cluster.update` is called. [brokers[b] for b in meta.replicas if b in brokers], [brokers[b] for b in meta.isr], ) else: self._partitions[id_].update(brokers, meta) def get_simple_consumer(self, consumer_group=None, use_rdkafka=False, **kwargs): """Return a SimpleConsumer of this topic :param consumer_group: The name of the consumer group to join :type consumer_group: bytes :param use_rdkafka: Use librdkafka-backed consumer if available :type use_rdkafka: bool """ if not rdkafka and use_rdkafka: raise ImportError("use_rdkafka requires rdkafka to be installed") if GEventHandler and isinstance(self._cluster.handler, GEventHandler) and use_rdkafka: raise ImportError("use_rdkafka cannot be used with gevent") Cls = (rdkafka.RdKafkaSimpleConsumer if rdkafka and use_rdkafka else SimpleConsumer) return Cls(self, self._cluster, consumer_group=consumer_group, **kwargs) def get_balanced_consumer(self, consumer_group, managed=False, **kwargs): """Return a BalancedConsumer of this topic :param consumer_group: The name of the consumer group to join :type consumer_group: bytes :param managed: If True, manage the consumer group with Kafka using the 0.9 group management api (requires Kafka >=0.9)) :type managed: bool """ if not managed: if "zookeeper_connect" not in kwargs and \ self._cluster._zookeeper_connect is not None: kwargs['zookeeper_connect'] = self._cluster._zookeeper_connect cls = BalancedConsumer else: cls = ManagedBalancedConsumer return cls(self, self._cluster, consumer_group, **kwargs)
12,310
Python
.py
241
41.726141
94
0.669854
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,931
static.py
zatosource_zato/code/patches/django/views/static.py
""" Views and functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ import mimetypes import posixpath from pathlib import Path from django.http import FileResponse, Http404, HttpResponse, HttpResponseNotModified from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils._os import safe_join from django.utils.http import http_date, parse_http_date from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy def serve(request, path, document_root=None, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: from django.views.static import serve path('<path:path>', serve, {'document_root': '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(path).lstrip("/") fullpath = Path(safe_join(document_root, path)) if fullpath.is_dir(): if show_indexes: return directory_index(path, fullpath) raise Http404(_("Directory indexes are not allowed here.")) if not fullpath.exists(): raise Http404(_("“%(path)s” does not exist") % {"path": fullpath}) # Respect the If-Modified-Since header. statobj = fullpath.stat() if not was_modified_since( request.META.get("HTTP_IF_MODIFIED_SINCE"), statobj.st_mtime ): return HttpResponseNotModified() content_type, encoding = mimetypes.guess_type(str(fullpath)) content_type = content_type or "application/octet-stream" # Explicitly set the content type for JSON resources. # Note that this needs to be combined with SECURE_CONTENT_TYPE_NOSNIFF=False in settings.py if fullpath.name.endswith('.js'): content_type = 'application/json' response = FileResponse(fullpath.open("rb"), content_type=content_type) response.headers["Last-Modified"] = http_date(statobj.st_mtime) if encoding: response.headers["Content-Encoding"] = encoding return response DEFAULT_DIRECTORY_INDEX_TEMPLATE = """ {% load i18n %} <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Language" content="en-us"> <meta name="robots" content="NONE,NOARCHIVE"> <title>{% blocktranslate %}Index of {{ directory }}{% endblocktranslate %}</title> </head> <body> <h1>{% blocktranslate %}Index of {{ directory }}{% endblocktranslate %}</h1> <ul> {% if directory != "/" %} <li><a href="../">../</a></li> {% endif %} {% for f in file_list %} <li><a href="{{ f|urlencode }}">{{ f }}</a></li> {% endfor %} </ul> </body> </html> """ template_translatable = gettext_lazy("Index of %(directory)s") def directory_index(path, fullpath): try: t = loader.select_template( [ "static/directory_index.html", "static/directory_index", ] ) except TemplateDoesNotExist: t = Engine(libraries={"i18n": "django.templatetags.i18n"}).from_string( DEFAULT_DIRECTORY_INDEX_TEMPLATE ) c = Context() else: c = {} files = [] for f in fullpath.iterdir(): if not f.name.startswith("."): url = str(f.relative_to(fullpath)) if f.is_dir(): url += "/" files.append(url) c.update( { "directory": path + "/", "file_list": files, } ) return HttpResponse(t.render(c)) def was_modified_since(header=None, mtime=0): """ Was something modified since the user last downloaded it? header This is the value of the If-Modified-Since header. If this is None, I'll just return True. mtime This is the modification time of the item we're talking about. """ try: if header is None: raise ValueError header_mtime = parse_http_date(header) if int(mtime) > header_mtime: raise ValueError except (ValueError, OverflowError): return True return False
4,554
Python
.py
121
31.38843
95
0.651632
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,932
boundfield.py
zatosource_zato/code/patches/django/forms/boundfield.py
import re from django.core.exceptions import ValidationError from django.forms.utils import pretty_name from django.forms.widgets import MultiWidget, Textarea, TextInput from django.utils.functional import cached_property from django.utils.html import format_html, html_safe from django.utils.translation import gettext_lazy as _ __all__ = ("BoundField",) @html_safe class BoundField: "A Field plus data" def __init__(self, form, field, name): self.form = form self.field = field self.name = name self.html_name = form.add_prefix(name) self.html_initial_name = form.add_initial_prefix(name) self.html_initial_id = form.add_initial_prefix(self.auto_id) if self.field.label is None: self.label = pretty_name(name) else: self.label = self.field.label self.help_text = field.help_text or "" def __str__(self): """Render this field as an HTML widget.""" if self.field.show_hidden_initial: return self.as_widget() + self.as_hidden(only_initial=True) return self.as_widget() @cached_property def subwidgets(self): """ Most widgets yield a single subwidget, but others like RadioSelect and CheckboxSelectMultiple produce one subwidget for each choice. This property is cached so that only one database query occurs when rendering ModelChoiceFields. """ id_ = self.field.widget.attrs.get("id") or self.auto_id attrs = {"id": id_} if id_ else {} attrs = self.build_widget_attrs(attrs) return [ BoundWidget(self.field.widget, widget, self.form.renderer) for widget in self.field.widget.subwidgets( self.html_name, self.value(), attrs=attrs ) ] def __bool__(self): # BoundField evaluates to True even if it doesn't have subwidgets. return True def __iter__(self): return iter(self.subwidgets) def __len__(self): return len(self.subwidgets) def __getitem__(self, idx): # Prevent unnecessary reevaluation when accessing BoundField's attrs # from templates. if not isinstance(idx, (int, slice)): raise TypeError( "BoundField indices must be integers or slices, not %s." % type(idx).__name__ ) return self.subwidgets[idx] @property def errors(self): """ Return an ErrorList (empty if there are no errors) for this field. """ return self.form.errors.get( self.name, self.form.error_class(renderer=self.form.renderer) ) def as_widget(self, widget=None, attrs=None, only_initial=False): """ Render the field by rendering the passed widget, adding any HTML attributes passed as attrs. If a widget isn't specified, use the field's default widget. """ widget = widget or self.field.widget if self.field.localize: widget.is_localized = True attrs = attrs or {} attrs = self.build_widget_attrs(attrs, widget) if self.auto_id and "id" not in widget.attrs: attrs.setdefault( "id", self.html_initial_id if only_initial else self.auto_id ) return widget.render( name=self.html_initial_name if only_initial else self.html_name, value=self.value(), attrs=attrs, renderer=self.form.renderer, ) def as_text(self, attrs=None, **kwargs): """ Return a string of HTML for representing this as an <input type="text">. """ return self.as_widget(TextInput(), attrs, **kwargs) def as_textarea(self, attrs=None, **kwargs): """Return a string of HTML for representing this as a <textarea>.""" return self.as_widget(Textarea(), attrs, **kwargs) def as_hidden(self, attrs=None, **kwargs): """ Return a string of HTML for representing this as an <input type="hidden">. """ return self.as_widget(self.field.hidden_widget(), attrs, **kwargs) @property def data(self): """ Return the data for this BoundField, or None if it wasn't given. """ return self.form._widget_data_value(self.field.widget, self.html_name) def value(self): """ Return the value for this BoundField, using the initial value if the form is not bound or the data otherwise. """ data = self.initial if self.form.is_bound: data = self.field.bound_data(self.data, data) return self.field.prepare_value(data) def _has_changed(self): field = self.field if field.show_hidden_initial: hidden_widget = field.hidden_widget() initial_value = self.form._widget_data_value( hidden_widget, self.html_initial_name, ) try: initial_value = field.to_python(initial_value) except ValidationError: # Always assume data has changed if validation fails. return True else: initial_value = self.initial return field.has_changed(initial_value, self.data) def label_tag(self, contents=None, attrs=None, label_suffix=None, tag=None): """ Wrap the given contents in a <label>, if the field has an ID attribute. contents should be mark_safe'd to avoid HTML escaping. If contents aren't given, use the field's HTML-escaped label. If attrs are given, use them as HTML attributes on the <label> tag. label_suffix overrides the form's label_suffix. """ contents = contents or self.label if label_suffix is None: label_suffix = ( self.field.label_suffix if self.field.label_suffix is not None else self.form.label_suffix ) # Only add the suffix if the label does not end in punctuation. # Translators: If found as last label character, these punctuation # characters will prevent the default label_suffix to be appended to the label if label_suffix and contents and contents[-1] not in _(":?.!"): contents = format_html("{}{}", contents, label_suffix) widget = self.field.widget id_ = widget.attrs.get("id") or self.auto_id if id_: id_for_label = widget.id_for_label(id_) if id_for_label: attrs = {**(attrs or {}), "for": id_for_label} if self.field.required and hasattr(self.form, "required_css_class"): attrs = attrs or {} if "class" in attrs: attrs["class"] += " " + self.form.required_css_class else: attrs["class"] = self.form.required_css_class context = { "field": self, "label": contents, "attrs": attrs, "use_tag": bool(id_), "tag": tag or "label", } return self.form.render(self.form.template_name_label, context) def legend_tag(self, contents=None, attrs=None, label_suffix=None): """ Wrap the given contents in a <legend>, if the field has an ID attribute. Contents should be mark_safe'd to avoid HTML escaping. If contents aren't given, use the field's HTML-escaped label. If attrs are given, use them as HTML attributes on the <legend> tag. label_suffix overrides the form's label_suffix. """ return self.label_tag(contents, attrs, label_suffix, tag="legend") def css_classes(self, extra_classes=None): """ Return a string of space-separated CSS classes for this field. """ if hasattr(extra_classes, "split"): extra_classes = extra_classes.split() extra_classes = set(extra_classes or []) if self.errors and hasattr(self.form, "error_css_class"): extra_classes.add(self.form.error_css_class) if self.field.required and hasattr(self.form, "required_css_class"): extra_classes.add(self.form.required_css_class) return " ".join(extra_classes) @property def is_hidden(self): """Return True if this BoundField's widget is hidden.""" return self.field.widget.is_hidden @property def auto_id(self): """ Calculate and return the ID attribute for this BoundField, if the associated Form has specified auto_id. Return an empty string otherwise. """ auto_id = self.form.auto_id # Boolean or string if auto_id and "%s" in str(auto_id): return auto_id % self.html_name elif auto_id: return self.html_name return "" @property def id_for_label(self): """ Wrapper around the field widget's `id_for_label` method. Useful, for example, for focusing on this field regardless of whether it has a single widget or a MultiWidget. """ widget = self.field.widget id_ = widget.attrs.get("id") or self.auto_id return widget.id_for_label(id_) @cached_property def initial(self): return self.form.get_initial_for_field(self.field, self.name) def build_widget_attrs(self, attrs, widget=None): widget = widget or self.field.widget attrs = dict(attrs) # Copy attrs to avoid modifying the argument. if ( widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute ): # MultiValueField has require_all_fields: if False, fall back # on subfields. if ( hasattr(self.field, "require_all_fields") and not self.field.require_all_fields and isinstance(self.field.widget, MultiWidget) ): for subfield, subwidget in zip(self.field.fields, widget.widgets): subwidget.attrs["required"] = ( subwidget.use_required_attribute(self.initial) and subfield.required ) else: # # Zato - Start # # Note that this in patch we make all the fields optional by default attrs["required"] = False # # Zato - End # if self.field.disabled: attrs["disabled"] = True return attrs @property def widget_type(self): return re.sub( r"widget$|input$", "", self.field.widget.__class__.__name__.lower() ) @property def use_fieldset(self): """ Return the value of this BoundField widget's use_fieldset attribute. """ return self.field.widget.use_fieldset @html_safe class BoundWidget: """ A container class used for iterating over widgets. This is useful for widgets that have choices. For example, the following can be used in a template: {% for radio in myform.beatles %} <label for="{{ radio.id_for_label }}"> {{ radio.choice_label }} <span class="radio">{{ radio.tag }}</span> </label> {% endfor %} """ def __init__(self, parent_widget, data, renderer): self.parent_widget = parent_widget self.data = data self.renderer = renderer def __str__(self): return self.tag(wrap_label=True) def tag(self, wrap_label=False): context = {"widget": {**self.data, "wrap_label": wrap_label}} return self.parent_widget._render(self.template_name, context, self.renderer) @property def template_name(self): if "template_name" in self.data: return self.data["template_name"] return self.parent_widget.template_name @property def id_for_label(self): return self.data["attrs"].get("id") @property def choice_label(self): return self.data["label"]
12,258
Python
.py
300
31.036667
86
0.600453
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,933
pg8000.py
zatosource_zato/code/patches/sqlalchemy/dialects/postgresql/pg8000.py
# postgresql/pg8000.py # Copyright (C) 2005-2020 the SQLAlchemy authors and contributors <see AUTHORS # file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php r""" .. dialect:: postgresql+pg8000 :name: pg8000 :dbapi: pg8000 :connectstring: postgresql+pg8000://user:password@host:port/dbname[?key=value&key=value...] :url: https://pythonhosted.org/pg8000/ .. note:: The pg8000 dialect is **not tested as part of SQLAlchemy's continuous integration** and may have unresolved issues. The recommended PostgreSQL dialect is psycopg2. .. _pg8000_unicode: Unicode ------- pg8000 will encode / decode string values between it and the server using the PostgreSQL ``client_encoding`` parameter; by default this is the value in the ``postgresql.conf`` file, which often defaults to ``SQL_ASCII``. Typically, this can be changed to ``utf-8``, as a more useful default:: #client_encoding = sql_ascii # actually, defaults to database # encoding client_encoding = utf8 The ``client_encoding`` can be overridden for a session by executing the SQL: SET CLIENT_ENCODING TO 'utf8'; SQLAlchemy will execute this SQL on all new connections based on the value passed to :func:`_sa.create_engine` using the ``client_encoding`` parameter:: engine = create_engine( "postgresql+pg8000://user:pass@host/dbname", client_encoding='utf8') .. _pg8000_isolation_level: pg8000 Transaction Isolation Level ------------------------------------- The pg8000 dialect offers the same isolation level settings as that of the :ref:`psycopg2 <psycopg2_isolation_level>` dialect: * ``READ COMMITTED`` * ``READ UNCOMMITTED`` * ``REPEATABLE READ`` * ``SERIALIZABLE`` * ``AUTOCOMMIT`` .. versionadded:: 0.9.5 support for AUTOCOMMIT isolation level when using pg8000. .. seealso:: :ref:`postgresql_isolation_level` :ref:`psycopg2_isolation_level` """ # noqa import decimal import re from .base import _DECIMAL_TYPES from .base import _FLOAT_TYPES from .base import _INT_TYPES from .base import PGCompiler from .base import PGDialect from .base import PGExecutionContext from .base import PGIdentifierPreparer from .base import UUID from .json import JSON from ... import exc from ... import processors from ... import types as sqltypes from ... import util from ...sql.elements import quoted_name try: from uuid import UUID as _python_UUID # noqa except ImportError: _python_UUID = None class _PGNumeric(sqltypes.Numeric): def result_processor(self, dialect, coltype): if self.asdecimal: if coltype in _FLOAT_TYPES: return processors.to_decimal_processor_factory( decimal.Decimal, self._effective_decimal_return_scale ) elif coltype in _DECIMAL_TYPES or coltype in _INT_TYPES: # pg8000 returns Decimal natively for 1700 return None else: raise exc.InvalidRequestError( "Unknown PG numeric type: %d" % coltype ) else: if coltype in _FLOAT_TYPES: # pg8000 returns float natively for 701 return None elif coltype in _DECIMAL_TYPES or coltype in _INT_TYPES: return processors.to_float else: raise exc.InvalidRequestError( "Unknown PG numeric type: %d" % coltype ) class _PGNumericNoBind(_PGNumeric): def bind_processor(self, dialect): return None class _PGJSON(JSON): def result_processor(self, dialect, coltype): if dialect._dbapi_version > (1, 10, 1): return None # Has native JSON else: return super(_PGJSON, self).result_processor(dialect, coltype) class _PGUUID(UUID): def bind_processor(self, dialect): if not self.as_uuid: def process(value): if value is not None: value = _python_UUID(value) return value return process def result_processor(self, dialect, coltype): if not self.as_uuid: def process(value): if value is not None: value = str(value) return value return process class PGExecutionContext_pg8000(PGExecutionContext): pass class PGCompiler_pg8000(PGCompiler): def visit_mod_binary(self, binary, operator, **kw): return ( self.process(binary.left, **kw) + " %% " + self.process(binary.right, **kw) ) def post_process_text(self, text): if "%%" in text: util.warn( "The SQLAlchemy postgresql dialect " "now automatically escapes '%' in text() " "expressions to '%%'." ) return text.replace("%", "%%") class PGIdentifierPreparer_pg8000(PGIdentifierPreparer): def _escape_identifier(self, value): value = value.replace(self.escape_quote, self.escape_to_quote) return value.replace("%", "%%") class PGDialect_pg8000(PGDialect): driver = "pg8000" supports_unicode_statements = True supports_unicode_binds = True default_paramstyle = "format" supports_sane_multi_rowcount = True execution_ctx_cls = PGExecutionContext_pg8000 statement_compiler = PGCompiler_pg8000 preparer = PGIdentifierPreparer_pg8000 description_encoding = "use_encoding" colspecs = util.update_copy( PGDialect.colspecs, { sqltypes.Numeric: _PGNumericNoBind, sqltypes.Float: _PGNumeric, JSON: _PGJSON, sqltypes.JSON: _PGJSON, UUID: _PGUUID, }, ) def __init__(self, client_encoding=None, **kwargs): PGDialect.__init__(self, **kwargs) self.client_encoding = client_encoding def initialize(self, connection): self.supports_sane_multi_rowcount = self._dbapi_version >= (1, 9, 14) super(PGDialect_pg8000, self).initialize(connection) @util.memoized_property def _dbapi_version(self): if self.dbapi and hasattr(self.dbapi, "__version__"): return tuple( [ int(x) for x in re.findall( r"(\d+)(?:[-\.]?|$)", self.dbapi.__version__ ) ] ) else: return (99, 99, 99) @classmethod def dbapi(cls): return __import__("pg8000") def create_connect_args(self, url): opts = url.translate_connect_args(username="user") if "port" in opts: opts["port"] = int(opts["port"]) opts.update(url.query) return ([], opts) def is_disconnect(self, e, connection, cursor): str_e = str(e) return 'connection is closed' in str_e or \ 'unpack_from requires a buffer of at least 5 bytes' in str_e or \ '[Errno 32] Broken pipe' in str_e def set_isolation_level(self, connection, level): level = level.replace("_", " ") # adjust for ConnectionFairy possibly being present if hasattr(connection, "connection"): connection = connection.connection if level == "AUTOCOMMIT": connection.autocommit = True elif level in self._isolation_lookup: connection.autocommit = False cursor = connection.cursor() cursor.execute( "SET SESSION CHARACTERISTICS AS TRANSACTION " "ISOLATION LEVEL %s" % level ) cursor.execute("COMMIT") cursor.close() else: raise exc.ArgumentError( "Invalid value '%s' for isolation_level. " "Valid isolation levels for %s are %s or AUTOCOMMIT" % (level, self.name, ", ".join(self._isolation_lookup)) ) def set_client_encoding(self, connection, client_encoding): # adjust for ConnectionFairy possibly being present if hasattr(connection, "connection"): connection = connection.connection cursor = connection.cursor() cursor.execute("SET CLIENT_ENCODING TO '" + client_encoding + "'") cursor.execute("COMMIT") cursor.close() def do_begin_twophase(self, connection, xid): connection.connection.tpc_begin((0, xid, "")) def do_prepare_twophase(self, connection, xid): connection.connection.tpc_prepare() def do_rollback_twophase( self, connection, xid, is_prepared=True, recover=False ): connection.connection.tpc_rollback((0, xid, "")) def do_commit_twophase( self, connection, xid, is_prepared=True, recover=False ): connection.connection.tpc_commit((0, xid, "")) def do_recover_twophase(self, connection): return [row[1] for row in connection.connection.tpc_recover()] def on_connect(self): fns = [] def on_connect(conn): conn.py_types[quoted_name] = conn.py_types[util.text_type] fns.append(on_connect) if self.client_encoding is not None: def on_connect(conn): self.set_client_encoding(conn, self.client_encoding) fns.append(on_connect) if self.isolation_level is not None: def on_connect(conn): self.set_isolation_level(conn, self.isolation_level) fns.append(on_connect) if len(fns) > 0: def on_connect(conn): for fn in fns: fn(conn) return on_connect else: return None dialect = PGDialect_pg8000
9,879
Python
.py
255
29.921569
95
0.618294
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,934
setup.py
zatosource_zato/code/zato-agent/setup.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # flake8: noqa from setuptools import setup, find_packages version = '3.2' setup( name = 'zato-agent', version = version, author = 'Zato Source s.r.o.', author_email = 'info@zato.io', url = 'https://zato.io', package_dir = {'':'src'}, packages = find_packages('src'), namespace_packages = ['zato'], zip_safe = False, )
534
Python
.py
19
23.789474
64
0.616601
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,935
__init__.py
zatosource_zato/code/zato-agent/src/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
154
Python
.py
5
29.4
64
0.687075
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,936
__init__.py
zatosource_zato/code/zato-agent/src/zato/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from pkgutil import extend_path __path__ = extend_path(__path__, __name__) # type: list[str] __import__('pkg_resources').declare_namespace(__name__)
306
Python
.py
8
36.75
64
0.676871
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,937
__init__.py
zatosource_zato/code/zato-agent/src/zato/agent/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from pkgutil import extend_path __path__ = extend_path(__path__, __name__) # type: list[str]
248
Python
.py
7
34
64
0.676471
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,938
client.py
zatosource_zato/code/zato-agent/src/zato/agent/load_balancer/client.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # Zato from zato.common.py23_.spring_ import ServerProxy, SSLClient class LoadBalancerAgentClient(ServerProxy): pass class TLSLoadBalancerAgentClient(SSLClient): pass
416
Python
.py
12
32.5
82
0.773869
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,939
config.py
zatosource_zato/code/zato-agent/src/zato/agent/load_balancer/config.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import logging from string import punctuation # PyParsing from pyparsing import Or, Word, Literal, nums, alphanums, alphas, restOfLine # Zato from zato.common.haproxy import http_log, Config # ################################################################################################################################ # ################################################################################################################################ if 0: from pyparsing import ParserElement ParserElement = ParserElement # ################################################################################################################################ # ################################################################################################################################ logger = logging.getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ # It's something Zato can understood and treat accordingly if such a token is # found on any HAProxy configuration file's line. zato_item_token = '# ZATO ' # PyParsing grammar for config values. uri = Word(alphanums + punctuation) backend_server = Literal('server').suppress() + Word(alphanums + '.-_') + \ Word(alphanums + '.-_') + Literal(':').suppress() + \ Word(nums) + restOfLine simple_option = Literal('option').suppress() + Word(alphas) frontend_bind = Literal('bind').suppress() + Or('*' | Word(alphanums + '.-_')) + Literal(':').suppress() + Word(nums) maxconn = Literal('maxconn').suppress() + Word(nums) timeout = Literal('timeout').suppress() + Word(alphas).suppress() + Word(nums) global_log = Literal('log').suppress() + Word(alphanums + '.-_') + Literal(':').suppress() + \ Word(nums) + Word(alphanums) + Word(alphanums) option_httpchk = Literal('option httpchk').suppress() + Word(alphas) + uri monitor_uri = Literal('monitor-uri').suppress() + uri stats_uri = Literal('stats uri').suppress() + uri stats_socket = Literal('stats socket').suppress() + uri # Config tokens recognized by the parser -> PyParsing grammar for their respective # values. config_tokens_grammar = { 'global:log':global_log, 'global:stats_socket':stats_socket, 'defaults:timeout connect':timeout, 'defaults:timeout client':timeout, 'defaults:timeout server':timeout, 'defaults:stats uri':stats_uri, 'backend bck_http_plain:server': backend_server, 'backend bck_http_plain:option httpchk': option_httpchk, 'frontend front_http_plain:monitor-uri':monitor_uri, 'frontend front_http_plain:option log-http-requests':simple_option, 'frontend front_http_plain:bind':frontend_bind, 'frontend front_http_plain:maxconn':maxconn, } backend_template = 'server {server_type}--{server_name} ' backend_template += '{address}:{port} {extra} ' backend_template += '{zato_item_token}backend {backend_type}:server--{server_name}' def config_from_string(data): """ Given a string representing a HAProxy configuration, returns a Config object representing it. """ config = Config() for line in data.split('\n'): if zato_item_token not in line: continue value, config_token_name = line.split(zato_item_token) value = value.strip() if value.startswith('#'): continue for token_name in config_tokens_grammar: if config_token_name.startswith(token_name): parser_elem = config_tokens_grammar[token_name] # type: ParserElement|None if parser_elem: result = parser_elem.parseString(value) config.set_value(token_name, result) return config def string_from_config(config, config_template): """ Given a Config object and the current HAProxy configuration returns a string representing the new HAProxy configuration, which can be validated by HAProxy and optionally saved. """ # Keys are HAProxy options understood by Zato. Values are two-element lists, # index 0 is a template to use for the new value and index 1 is the values # from the configuration to use in the template. Note that not all items # understood by Zato are given here, that's because not all of them are editable # by users and we simply won't receive them on input in the 'config' object. zato_item_dispatch = { 'global:log': ('log {host}:{port} {facility} {level}', config['global_']['log']), 'defaults:timeout connect': ('timeout connect {timeout_connect}', config['defaults']), 'defaults:timeout client': ('timeout client {timeout_client}', config['defaults']), 'defaults:timeout server': ('timeout server {timeout_server}', config['defaults']), 'frontend front_http_plain:monitor-uri': ('monitor-uri {monitor_uri}', config['frontend']['front_http_plain']), 'frontend front_http_plain:bind': ('bind {address}:{port}', config['frontend']['front_http_plain']['bind']), 'frontend front_http_plain:maxconn': ('maxconn {maxconn}', config['frontend']['front_http_plain']), # That below, it looks .. well you know what I mean. But that's the price of # using a generic dispatch dictionary. Basically, it boils down to # getting a value to use for logging but in the HAProxy format. We were # given a string representing an integer and we need to translate it # back to a format understood by HAProxy, so that '1' translates into 'nolog' etc. 'frontend front_http_plain:option log-http-requests': # noqa ('option {value}', dict(value=http_log[int(config['frontend']['front_http_plain']['log_http_requests'])][0])), # noqa } new_config = [] for line in config_template: # Make sure we don't accidentally overwrite something that's not ours. if zato_item_token in line: if 'bck_http' in line or [key for key in zato_item_dispatch if key in line]: # Let's see how much the line was indented in the template indent = len(line) - len(line.strip()) - 1 # -1 because of the \n new_line = ' ' * indent # Let's see to the simple options first.. for zato_item, (template, value) in zato_item_dispatch.items(): if zato_item_token + zato_item in line: new_line += template.format(**value) + ' ' + zato_item_token + zato_item # pylint: disable=not-a-mapping # .. and the more complex ones now. if zato_item_token + 'backend' in line and '--' in line: line = line.split(zato_item_token + 'backend') backend_info = line[1].split('--') backend_type, server_name = (backend_info[0].strip().split(':')[0], backend_info[1].strip()) server_type = backend_type.split('bck_')[1] backend_values = { 'backend_type': backend_type, 'server_name':server_name, 'server_type':server_type, 'zato_item_token': zato_item_token } backend_values.update(config['backend'][backend_type][server_name]) new_line += backend_template.format(**backend_values) else: for name in('begin', 'end'): prefix = '{}{}'.format(zato_item_token, name) if line.startswith(prefix): new_line += line new_line += '\n' new_config.append(new_line) else: new_config.append(line) else: new_config.append(line) return ''.join(new_config)
8,252
Python
.py
142
49.084507
130
0.56308
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,940
haproxy_stats.py
zatosource_zato/code/zato-agent/src/zato/agent/load_balancer/haproxy_stats.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import logging import socket from io import StringIO from time import time from traceback import format_exc # Python 2/3 compatibility from builtins import bytes # ################################################################################################################################ logger = logging.getLogger(__name__) # ################################################################################################################################ class HAProxyStats: """ Used for communicating with HAProxy through its local UNIX socket interface. """ socket_name: str def __init__(self, socket_name='<default>'): self.socket_name = socket_name def execute(self, command, extra='', timeout=200) -> str: """ Executes a HAProxy command by sending a message to a HAProxy's local UNIX socket and waiting up to 'timeout' milliseconds for the response. """ if extra: command = command + ' ' + extra buff = StringIO() end = time() + timeout client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: client.connect(self.socket_name) client.send((command + '\n').encode('utf8')) while time() <= end: data = client.recv(4096) if data: buff.write(data.decode('utf8') if isinstance(data, bytes) else data) else: break except Exception: logger.error('An error has occurred, e:`%s`', format_exc()) raise finally: client.close() return buff.getvalue() # ################################################################################################################################
1,953
Python
.py
47
34.085106
130
0.484656
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,941
main.py
zatosource_zato/code/zato-agent/src/zato/agent/load_balancer/main.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib import os, sys # ConcurrentLogHandler - updates stlidb's logging config on import so this needs to stay try: import cloghandler # type: ignore except ImportError: pass else: cloghandler = cloghandler # For pyflakes # Zato from zato.agent.load_balancer.server import LoadBalancerAgent, TLSLoadBalancerAgent from zato.common.util.api import get_lb_agent_json_config, parse_cmd_line_options, store_pidfile if __name__ == '__main__': repo_dir = sys.argv[1] component_dir = os.path.join(repo_dir, '..', '..') lba_config = get_lb_agent_json_config(repo_dir) # Store agent's pidfile only if we are not running in foreground options = parse_cmd_line_options(sys.argv[2]) if not options.get('fg', None): store_pidfile(component_dir, lba_config['pid_file']) lba_class = TLSLoadBalancerAgent if lba_config.get('is_tls_enabled', True) else LoadBalancerAgent lba = lba_class(repo_dir) lba.start_load_balancer() lba.serve_forever()
1,233
Python
.py
30
37.733333
101
0.728188
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,942
server.py
zatosource_zato/code/zato-agent/src/zato/agent/load_balancer/server.py
# -*- coding: utf-8 -*- """ Copyright (C) 2024, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import logging import logging.config import os import ssl from collections import Counter from datetime import datetime from http.client import OK from traceback import format_exc from typing import Callable # pytz from pytz import utc # YAML import yaml # Python 2/3 compatibility from zato.common.ext.future.moves.urllib.request import urlopen from six import PY2 # Zato from zato.agent.load_balancer.config import backend_template, config_from_string, string_from_config, zato_item_token from zato.agent.load_balancer.haproxy_stats import HAProxyStats from zato.common.api import HAProxy, MISC, TRACE1, ZATO_OK from zato.common.haproxy import haproxy_stats, validate_haproxy_config from zato.common.py23_.spring_ import RequestHandler, SimpleXMLRPCServer, SSLServer from zato.common.repo import RepoManager from zato.common.util.api import get_lb_agent_json_config, timeouting_popen from zato.common.util.open_ import open_r, open_w from zato.common.util.platform_ import is_linux public_method_prefix = '_lb_agent_' config_file = 'zato.config' logger = logging.getLogger('') logging.addLevelName(TRACE1, 'TRACE1') # All known HAProxy commands haproxy_commands = {} for _ignored_version, commands in haproxy_stats.items(): haproxy_commands.update(commands) # ################################################################################################################################ # ################################################################################################################################ class BaseLoadBalancerAgent: # This is implemented by children classes register_function: Callable def init_config(self, repo_dir): self.repo_dir = os.path.abspath(repo_dir) self.json_config = get_lb_agent_json_config(self.repo_dir) self.work_dir = os.path.abspath(os.path.join(self.repo_dir, self.json_config['work_dir'])) self.haproxy_command = self.json_config['haproxy_command'] self.verify_fields = self.json_config['verify_fields'] self.keyfile = os.path.abspath(os.path.join(self.repo_dir, self.json_config['keyfile'])) self.certfile = os.path.abspath(os.path.join(self.repo_dir, self.json_config['certfile'])) self.ca_certs = os.path.abspath(os.path.join(self.repo_dir, self.json_config['ca_certs'])) self.haproxy_pidfile = os.path.abspath(os.path.join(self.repo_dir, '../', '../', MISC.PIDFILE)) log_config = os.path.abspath(os.path.join(self.repo_dir, self.json_config['log_config'])) with open_r(log_config) as f: data = yaml.load(f, yaml.FullLoader) # type: dict logging.config.dictConfig(data) # pyright: reportGeneralTypeIssues=false self.config_path = os.path.join(self.repo_dir, config_file) self.config = self._read_config() self.start_time = datetime.utcnow().replace(tzinfo=utc).isoformat() self.haproxy_stats = HAProxyStats(self.config.global_['stats_socket']) RepoManager(self.repo_dir).ensure_repo_consistency() self.host = self.json_config['host'] self.port = self.json_config['port'] self.logger = logging.getLogger(self.__class__.__name__) # ################################################################################################################################ def _re_start_load_balancer(self, timeout_msg, rc_non_zero_msg, additional_params=None): """ A common method for (re-)starting HAProxy. """ additional_params = additional_params or [] command = [self.haproxy_command, '-D'] if is_linux: command.extend(['-m', HAProxy.Default_Memory_Limit]) command.extend(['-f', self.config_path, '-p', self.haproxy_pidfile]) command.extend(additional_params) timeouting_popen(command, 5.0, timeout_msg, rc_non_zero_msg) # ################################################################################################################################ def start_load_balancer(self): """ Starts the HAProxy load balancer in background. """ self._re_start_load_balancer("HAProxy didn't start in `{}` seconds. ", 'Failed to start HAProxy. ') # ################################################################################################################################ def restart_load_balancer(self): """ Restarts the HAProxy load balancer without disrupting existing connections. """ additional_params = [ '-sf', open_r(self.haproxy_pidfile).read().strip() ] self._re_start_load_balancer('Could not restart in `{}` seconds. ', 'Failed to restart HAProxy. ', additional_params) # ################################################################################################################################ def register_functions(self): """ All methods with the '_lb_agent_' prefix will be exposed through SSL XML-RPC after chopping off the prefix, so that self._lb_agent_ping becomes a 'ping' method, self._lb_agent_get_uptime_info -> 'get_uptime_info' etc. """ for item in sorted(dir(self)): if item.startswith(public_method_prefix): public_name = item.split(public_method_prefix)[1] attr = getattr(self, item) msg = 'Registering `{attr}` under public name `{public_name}`' logger.info(msg.format(attr=attr, public_name=public_name)) self.register_function(attr, public_name) # ################################################################################################################################ def _read_config_string(self): """ Returns the HAProxy config as a string. """ return open_r(self.config_path).read() # ################################################################################################################################ def _read_config(self): """ Read and parse the HAProxy configuration. """ return config_from_string(self._read_config_string()) # ################################################################################################################################ def _validate(self, config_string): validate_haproxy_config(config_string, self.haproxy_command) # ################################################################################################################################ def _save_config(self, config_string): """ Save a new HAProxy config file on disk. It is assumed the file has already been validated. """ f = open_w(self.config_path) f.write(config_string) f.close() self.config = self._read_config() # ################################################################################################################################ def _validate_save_config_string(self, config_string, save): """ Given a string representing the HAProxy config file it first validates it and then optionally saves it and restarts the load balancer. """ self._validate(config_string) if save: self._save_config(config_string) self.restart_load_balancer() return True # ################################################################################################################################ def _show_stat(self): stat = self.haproxy_stats.execute('show stat') for line in stat.splitlines(): if line.startswith('#') or not line.strip(): continue line = line.split(',') haproxy_name = line[0] haproxy_type_or_name = line[1] if haproxy_name.startswith('bck') and not haproxy_type_or_name == 'BACKEND': backend_name, state = line[1], line[17] # Do not count in backends other than Zato, e.g. perhaps someone added their own if not 'http_plain' in backend_name: continue access_type, server_name = backend_name.split('--') yield access_type, server_name, state # ################################################################################################################################ def _lb_agent_validate_save_source_code(self, source_code, save=False): """ Validate or validates & saves (if 'save' flag is True) an HAProxy configuration passed in as a string. Note that the validation step is always performed. """ return self._validate_save_config_string(source_code, save) # ################################################################################################################################ def _lb_agent_validate_save(self, lb_config, save=False): """ Validate or validates /and/ saves (if 'save' flag is True) an HAProxy configuration. Note that the validation step is always performed. """ config_string = string_from_config(lb_config, open_r(self.config_path).readlines()) return self._validate_save_config_string(config_string, save) # ################################################################################################################################ def _lb_agent_get_servers_state(self): """ Return a three-key dictionary describing the current state of all Zato servers as seen by HAProxy. Keys are "UP" for running servers, "DOWN" for those that are unavailable, and "MAINT" for servers in the maintenance mode. Values are dictionaries of access type -> names of servers. For instance, if there are three servers, one is UP, the second one is DOWN and the third one is MAINT, the result will be: { 'UP': {'http_plain': ['SERVER.1']}, 'DOWN': {'http_plain': ['SERVER.2']}, 'MAINT': {'http_plain': ['SERVER.3']}, } """ servers_state = { 'UP': {'http_plain':[]}, 'DOWN': {'http_plain':[]}, 'MAINT': {'http_plain':[]}, } for access_type, server_name, state in self._show_stat(): # Don't bail out when future HAProxy versions introduce states # we aren't currently aware of. if state not in servers_state: msg = 'Encountered unknown state [{state}], recognized ones are [{states}]' logger.warning(msg.format(state=state, states=str(sorted(servers_state)))) else: servers_state[state][access_type].append(server_name) return servers_state # ################################################################################################################################ def _lb_agent_get_server_data_dict(self, name=None): """ Returns a dictionary whose keys are server names and values are their access types and the server's status as reported by HAProxy. """ backend_config = self.config.backend['bck_http_plain'] servers = {} def _dict(access_type, state, server_name): return { 'access_type':access_type, 'state':state, 'address': '{}:{}'.format(backend_config[server_name]['address'], backend_config[server_name]['port']) } for access_type, server_name, state in self._show_stat(): if name: if name == server_name: servers[server_name] = _dict(access_type, state, server_name) else: servers[server_name] = _dict(access_type, state, server_name) return servers # ################################################################################################################################ def _lb_agent_rename_server(self, old_name, new_name): """ Renames the server, validates and saves the config. """ if old_name == new_name: msg = 'Skipped renaming, old_name:[{}] is the same as new_name:[{}]'.format(old_name, new_name) self.logger.warning(msg) return True new_config = [] config_string = self._read_config_string() old_servers = Counter() new_servers = Counter() def _get_lines(): for line in config_string.splitlines(): yield line old_server = '# ZATO backend bck_http_plain:server--{}'.format(old_name) new_server = '# ZATO backend bck_http_plain:server--{}'.format(new_name) for line in _get_lines(): if old_server in line: old_servers[old_name] += 1 if new_server in line: new_servers[new_name] += 1 if not old_servers[old_name]: raise Exception("old_name:[{}] not found in the load balancer's configuration".format(old_name)) if new_servers[new_name]: raise Exception('new_name:[{}] is not unique'.format(new_name)) for line in _get_lines(): if old_server in line: line = line.replace(old_name, new_name) new_config.append(line) self._validate_save_config_string('\n'.join(new_config), True) return True # ################################################################################################################################ def _lb_agent_add_remove_server(self, action, server_name): bck_http_plain = self.config.backend['bck_http_plain'] if action == 'remove': del bck_http_plain[server_name] elif action == 'add': bck_http_plain[server_name] = {} bck_http_plain[server_name]['extra'] = 'check inter 2s rise 2 fall 2' bck_http_plain[server_name]['address'] = '127.0.0.1' bck_http_plain[server_name]['port'] = '123456' else: raise Exception('Unrecognized action:[{}]'.format(action)) new_config = [] config_string = self._read_config_string() for line in config_string.splitlines(): if '# ZATO backend bck_http_plain' in line: continue else: backends = [] if '# ZATO begin backend bck_http_plain' in line: for server_name in bck_http_plain: data_dict = { 'server_type':'http_plain', 'server_name':server_name, 'address':bck_http_plain[server_name]['address'], 'port':bck_http_plain[server_name]['port'], 'extra':bck_http_plain[server_name]['extra'], 'zato_item_token':zato_item_token, 'backend_type':'bck_http_plain', } backends.append(backend_template.format(**data_dict)) line += ('\n' * 2) + '\n'.join(backends) new_config.append(line.rstrip()) self._validate_save_config_string('\n'.join(new_config), True) return True # ################################################################################################################################ def _lb_agent_execute_command(self, command, timeout, extra=''): """ Execute an HAProxy command through its UNIX socket interface. """ command = haproxy_commands[int(command)][0] timeout = int(timeout) result = self.haproxy_stats.execute(command, extra, timeout) # Special-case the request for describing the commands available. # There's no 'describe commands' command in HAProxy but HAProxy is # nice enough to return a usage info when it encounters an unknown # command which we parse and return to the caller. if command == 'ZATO_DESCRIBE_COMMANDS': result = '\n\n' + '\n'.join(result.splitlines()[1:]) return result # ################################################################################################################################ def _lb_agent_haproxy_version_info(self): """ Return a three-element tuple describing HAProxy's version, similar to what stdlib's sys.version_info does. """ # 'show info' is always available and we use it for determining the HAProxy version. info = self.haproxy_stats.execute('show info') for line in info.splitlines(): if line.startswith('Version:'): version = line.split('Version:')[1] return version.strip().split('.') # ################################################################################################################################ def _lb_agent_ping(self): """ Always return ZATO_OK. """ return ZATO_OK # ################################################################################################################################ def _lb_agent_get_config(self): """ Return those pieces of an HAProxy configuration that are understood by Zato. """ return self.config # ################################################################################################################################ def _lb_agent_get_config_source_code(self): """ Return the HAProxy configuration file's source. """ return self._read_config_string() # ################################################################################################################################ def _lb_agent_get_uptime_info(self): """ Return the agent's (not HAProxy's) uptime info, currently returns only the time it was started at. """ return self.start_time # ################################################################################################################################ def _lb_agent_is_haproxy_alive(self, lb_use_tls): """ Invoke HAProxy through HTTP monitor_uri and return ZATO_OK if HTTP status code is 200. Raise Exception otherwise. """ host = self.config.frontend['front_http_plain']['bind']['address'] port = self.config.frontend['front_http_plain']['bind']['port'] path = self.config.frontend['front_http_plain']['monitor_uri'] url = 'http{}://{}:{}{}'.format('s' if lb_use_tls else '', host, port, path) try: conn = urlopen(url) except Exception: msg = 'Could not open URL `{}`, e:`{}`'.format(url, format_exc()) logger.error(msg) raise Exception(msg) else: try: code = conn.getcode() if code == OK: return ZATO_OK else: msg = 'Could not open URL [{url}], HTTP code:[{code}]'.format(url=url, code=code) logger.error(msg) raise Exception(msg) finally: conn.close() # ################################################################################################################################ def _lb_agent_get_work_config(self): """ Return the agent's basic configuration. """ return {'work_dir':self.work_dir, 'haproxy_command':self.haproxy_command, # noqa 'keyfile':self.keyfile, 'certfile':self.certfile, # noqa 'ca_certs':self.ca_certs, 'verify_fields':self.verify_fields} # noqa # ################################################################################################################################ # ################################################################################################################################ class LoadBalancerAgent(BaseLoadBalancerAgent, SimpleXMLRPCServer): def __init__(self, repo_dir): self.init_config(repo_dir) if PY2: SimpleXMLRPCServer.__init__(self, (self.host, self.port), requestHandler=RequestHandler) else: SimpleXMLRPCServer.__init__(self, (self.host, self.port)) self.register_functions() # ################################################################################################################################ # ################################################################################################################################ class TLSLoadBalancerAgent(BaseLoadBalancerAgent, SSLServer): def __init__(self, repo_dir): self.init_config(repo_dir) SSLServer.__init__(self, host=self.host, port=self.port, keyfile=self.keyfile, certfile=self.certfile, ca_certs=self.ca_certs, cert_reqs=ssl.CERT_REQUIRED, verify_fields=self.verify_fields) self.register_functions() # ################################################################################################################################ # ################################################################################################################################
21,355
Python
.py
382
46.442408
130
0.49161
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,943
setup.py
zatosource_zato/code/zato-sso/setup.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # flake8: noqa from setuptools import setup, find_packages version = '3.2' setup( name = 'zato-sso', version = version, author = 'Zato Source s.r.o.', author_email = 'info@zato.io', url = 'https://zato.io', package_dir = {'':'src'}, packages = find_packages('src'), namespace_packages = ['zato'], zip_safe = False, )
532
Python
.py
19
23.684211
64
0.615079
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,944
__init__.py
zatosource_zato/code/zato-sso/test/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals
238
Python
.py
6
38.166667
82
0.729258
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,945
test_password_reset.py
zatosource_zato/code/zato-sso/test/zato/test_password_reset.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from unittest import main # Zato from base import BaseTest from zato.common.crypto.api import CryptoManager from zato.common.odb.model import SSOPasswordReset, SSOUser from zato.common.test.config import TestConfig from zato.common.typing_ import cast_ # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import stranydict stranydict = stranydict # ################################################################################################################################ # ################################################################################################################################ class FlowPRTTestCase(BaseTest): # ################################################################################################################################ def get_random_prt_info(self, session): q = session.query( SSOUser.user_id, SSOPasswordReset.token, ).\ filter(SSOUser.user_id == SSOPasswordReset.user_id).\ filter(SSOPasswordReset.has_been_accessed.is_(False)).\ limit(1).\ one() return q # ################################################################################################################################ def test_user_reset_password(self): # Generated in each test password = CryptoManager.generate_password(to_str=True) # Request a new PRT .. self.post('/zato/sso/password/reset', { 'credential': TestConfig.super_user_name, }) # .. above, we never receive the PRT so we know there will be at least one PRT # when we look it up along with user_id in the ODB .. odb_session = self.get_odb_session() prt_info = self.get_random_prt_info(odb_session) # .. make it easier to access the information received .. prt_info = prt_info._asdict() # type: ignore prt_info = cast_('stranydict', prt_info) # .. extract the details .. user_id = prt_info['user_id'] token = prt_info['token'] # .. access the PRT received .. response = self.patch('/zato/sso/password/reset', { 'token': token, }) # .. read the reset key received from the .patch call .. reset_key = response.reset_key # .. change the password now .. response = self.delete('/zato/sso/password/reset', { 'token': token, 'reset_key': reset_key, 'password': password }) # .. confirm the status .. self.assertEqual(response.status, 'ok') # .. change the password back to the old one .. self.patch('/zato/sso/user/password', { 'ust': self.ctx.super_user_ust, 'user_id': user_id, 'old_password': password, 'new_password': TestConfig.super_user_password }) # .. confirm that we can log in using the old password. self._login_super_user() # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
3,848
Python
.py
78
41.987179
130
0.417312
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,946
test_user.py
zatosource_zato/code/zato-sso/test/zato/test_user.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from datetime import datetime from unittest import main # Zato from base import BaseTest from zato.common.test.config import TestConfig from zato.sso import const, status_code # ################################################################################################################################ # ################################################################################################################################ class UserCreateTestCase(BaseTest): def test_user_create(self): now = datetime.utcnow() username = self._get_random_username() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'email': 'myemail@example.com', 'is_rate_limit_active': True, 'rate_limit_def': '*=1/d', }) self.assertTrue(response.is_approval_needed) self._assert_default_user_data(response, now) # ################################################################################################################################ def test_user_create_with_auto_approve(self): now = datetime.utcnow() username = self._get_random_username() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'auto_approve': True }) self.assertFalse(response.is_approval_needed) self._assert_default_user_data(response, now, const.approval_status.approved) # ################################################################################################################################ # ################################################################################################################################ class UserSignupTestCase(BaseTest): def test_user_signup(self): response = self.post('/zato/sso/user/signup', { 'username': self._get_random_username(), 'password': self._get_random_data(), 'app_list': [TestConfig.current_app] }) self.assertIsNotNone(response.confirm_token) # ################################################################################################################################ # ################################################################################################################################ class UserConfirmSignupTestCase(BaseTest): def test_confirm_signup(self): response = self.post('/zato/sso/user/signup', { 'username': self._get_random_username(), 'password': self._get_random_data(), 'app_list': [TestConfig.current_app] }) confirm_token = response.confirm_token response = self.patch('/zato/sso/user/signup', { 'confirm_token': confirm_token, }) # ################################################################################################################################ # ################################################################################################################################ class UserSearchTestCase(BaseTest): def test_search(self): username1 = self._get_random_username() username2 = self._get_random_username() random_data = self._get_random_data() display_name1 = 'display' + random_data display_name2 = 'display' + random_data email1 = self._get_random_data() email2 = self._get_random_data() now = datetime.utcnow() self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username1, 'display_name': display_name1, 'email': email1, }) self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username2, 'display_name': display_name2, 'email': email2, }) response = self.get('/zato/sso/user/search', { 'ust': self.ctx.super_user_ust, 'display_name': random_data, 'is_name_exact': False, }) self.assertEqual(response.cur_page, 1) self.assertEqual(response.num_pages, 1) self.assertEqual(response.has_next_page, False) self.assertEqual(response.has_prev_page, False) self.assertEqual(response.page_size, const.search.page_size) self.assertEqual(response.total, 2) self.assertEqual(len(response.result), 2) user1 = response.result[0] self._assert_default_user_data(user1, now) user2 = response.result[1] self._assert_default_user_data(user2, now) # ################################################################################################################################ # ################################################################################################################################ class UserApproveTestCase(BaseTest): def test_approve(self): response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'current_app': TestConfig.current_app, 'username': self._get_random_username(), }) user_id = response.user_id self.post('/zato/sso/user/approve', { 'ust': self.ctx.super_user_ust, 'user_id': user_id }) response = self.get('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'user_id': user_id }) self.assertEqual(response.approval_status, const.approval_status.approved) # ################################################################################################################################ # ################################################################################################################################ class UserRejectTestCase(BaseTest): def test_reject(self): response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': self._get_random_username(), }) user_id = response.user_id self.post('/zato/sso/user/reject', { 'ust': self.ctx.super_user_ust, 'user_id': user_id }) response = self.get('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'user_id': user_id }) self.assertEqual(response.approval_status, const.approval_status.rejected) # ################################################################################################################################ # ################################################################################################################################ class UserLoginValidTestCase(BaseTest): def test_user_login(self): self.patch('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'is_totp_enabled': False, }) response = self.post('/zato/sso/user/login', { 'username': TestConfig.super_user_name, 'password': TestConfig.super_user_password, }) self.assertIsNotNone(response.ust) # ################################################################################################################################ # ################################################################################################################################ class UserLoginInvalidUsernameTestCase(BaseTest): def test_user_login_invalid_username(self): response = self.post('/zato/sso/user/login', { 'username': self._get_random_username(), 'password': TestConfig.super_user_password, }, expect_ok=False) self.assertEqual(response.status, status_code.error) self.assertListEqual(response.sub_status, [status_code.auth.not_allowed]) self.assertNotIn('ust', response) # ################################################################################################################################ def test_user_login_empty_username_string(self): response = self.post('/zato/sso/user/login', { 'username': '', 'password': TestConfig.super_user_password, }, expect_ok=False) self.assertEqual(response.status, status_code.error) self.assertListEqual(response.sub_status, [status_code.auth.not_allowed]) self.assertNotIn('ust', response) # ################################################################################################################################ def test_user_login_empty_username_none(self): response = self.post('/zato/sso/user/login', { 'username': None, 'password': TestConfig.super_user_password, }, expect_ok=False) self.assertEqual(response.status, status_code.error) self.assertListEqual(response.sub_status, [status_code.auth.not_allowed]) self.assertNotIn('ust', response) # ################################################################################################################################ def test_user_login_no_username(self): response = self.post('/zato/sso/user/login', { 'password': TestConfig.super_user_password, }, expect_ok=False) self.assertEqual(response.result, 'Error') self.assertEqual(response.details, 'Bad request') self.assertIn('cid', response) self.assertNotIn('ust', response) # ################################################################################################################################ # ################################################################################################################################ class UserLoginInvalidPasswordTestCase(BaseTest): def test_user_login_invalid_password(self): response = self.post('/zato/sso/user/login', { 'username': TestConfig.super_user_name, 'password': self._get_random_data(), }, expect_ok=False) self.assertEqual(response.status, status_code.error) self.assertListEqual(response.sub_status, [status_code.auth.not_allowed]) self.assertNotIn('ust', response) # ################################################################################################################################ def test_user_login_empty_password_string(self): response = self.post('/zato/sso/user/login', { 'username': TestConfig.super_user_name, 'password': '', }, expect_ok=False) self.assertEqual(response.status, status_code.error) self.assertListEqual(response.sub_status, [status_code.auth.not_allowed]) self.assertNotIn('ust', response) # ################################################################################################################################ def test_user_login_empty_username_none(self): response = self.post('/zato/sso/user/login', { 'username': None, 'password': TestConfig.super_user_password, }, expect_ok=False) self.assertEqual(response.status, status_code.error) self.assertListEqual(response.sub_status, [status_code.auth.not_allowed]) self.assertNotIn('ust', response) # ################################################################################################################################ def test_user_login_no_password(self): response = self.post('/zato/sso/user/login', { 'username': TestConfig.super_user_name, }, expect_ok=False) self.assertEqual(response.result, 'Error') self.assertEqual(response.details, 'Bad request') self.assertIn('cid', response) self.assertNotIn('ust', response) # ################################################################################################################################ # ################################################################################################################################ class UserLogoutTestCase(BaseTest): def test_user_logout(self): self.patch('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'is_totp_enabled': False, }) ust = self.post('/zato/sso/user/login', { 'username': TestConfig.super_user_name, 'password': TestConfig.super_user_password, }).ust self.post('/zato/sso/user/logout', { 'ust': ust, }) # ################################################################################################################################ # ################################################################################################################################ class UserGetTestCase(BaseTest): def test_user_get_by_user_id(self): username = self._get_random_username() password_must_change = True display_name = self._get_random_data() first_name = self._get_random_data() middle_name = self._get_random_data() last_name = self._get_random_data() email = self._get_random_data() is_locked = True is_totp_enabled = True totp_label = self._get_random_data() sign_up_status = const.signup_status.before_confirmation response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'password_must_change': password_must_change, 'display_name': display_name, 'first_name': first_name, 'middle_name': middle_name, 'last_name': last_name, 'email': email, 'is_locked': is_locked, 'is_totp_enabled': is_totp_enabled, 'totp_label': totp_label, 'sign_up_status': sign_up_status, }) user_id = response.user_id response = self.get('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'user_id': user_id, }) self.assertEqual(response.status, status_code.ok) self.assertEqual(response.username, username) self.assertEqual(response.display_name, display_name) self.assertEqual(response.first_name, first_name) self.assertEqual(response.middle_name, middle_name) self.assertEqual(response.last_name, last_name) self.assertEqual(response.email, email) self.assertEqual(response.sign_up_status, sign_up_status) self.assertIs(response.password_must_change, password_must_change) self.assertIs(response.is_locked, is_locked) self.assertIs(response.is_totp_enabled, is_totp_enabled) self.assertEqual(response.totp_label, totp_label) # ################################################################################################################################ def test_user_get_by_ust(self): now = datetime.utcnow() response = self.get('/zato/sso/user', { 'ust': self.ctx.super_user_ust, }) self.assertEqual(response.approval_status, const.approval_status.approved) self.assertEqual(response.approval_status_mod_by, 'auto') self.assertEqual(response.username, TestConfig.super_user_name) self.assertEqual(response.sign_up_status, const.signup_status.final) self.assertFalse(response.is_approval_needed) self.assertTrue(response.is_super_user) self.assertTrue(response.password_is_set) self.assertFalse(response.is_internal) self.assertFalse(response.is_locked) self.assertFalse(response.password_must_change) self._assert_user_dates(response, now, True) # ################################################################################################################################ # ################################################################################################################################ class UserUpdateTestCase(BaseTest): def test_user_update_self(self): username = self._get_random_username() password = self._get_random_data() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'password': password, }) user_id = response.user_id response = self.post('/zato/sso/user/approve', { 'ust': self.ctx.super_user_ust, 'user_id': user_id }) self.assertEqual(response.status, status_code.ok) response = self.post('/zato/sso/user/login', { 'username': username, 'password': password }) ust = response.ust display_name = self._get_random_data() first_name = self._get_random_data() middle_name = self._get_random_data() last_name = self._get_random_data() email = self._get_random_data() response = self.patch('/zato/sso/user', { 'ust': ust, 'display_name': display_name, 'first_name': first_name, 'middle_name': middle_name, 'last_name': last_name, 'email': email, }) response = self.get('/zato/sso/user', { 'ust': ust, }) invalid = object() # This is a regular user so these attributes should not exist self.assertIs(response.get('is_active', invalid), invalid) self.assertIs(response.get('is_approval_needed', invalid), invalid) self.assertIs(response.get('is_internal', invalid), invalid) self.assertIs(response.get('is_locked', invalid), invalid) self.assertIs(response.get('is_super_user', invalid), invalid) self.assertEqual(response.display_name, display_name) self.assertEqual(response.email, email) self.assertEqual(response.first_name, first_name) self.assertEqual(response.last_name, last_name) self.assertEqual(response.middle_name, middle_name) self.assertEqual(response.username, username) # ################################################################################################################################ def test_user_update_self_username(self): # Test data username1 = self._get_random_username() password1 = self._get_random_data() username2 = self._get_random_username() password2 = self._get_random_data() new_username = self._get_random_username() # Create test users self._create_and_approve_user(username1, password1) self._create_and_approve_user(username2, password2) # Log in the first user response1 = self.post('/zato/sso/user/login', { 'username': username1, 'password': password1 }) # The first user should be able to set the new user name response = self.patch('/zato/sso/user', { 'ust': response1.ust, 'username': new_username, }) self.assertEqual(response.status, status_code.ok) # Log in the second user response2 = self.post('/zato/sso/user/login', { 'username': username2, 'password': password2 }) # The second user should be able to use the same username as the first one has already used patch_response2 = self.patch('/zato/sso/user', { 'ust': response2.ust, 'username': new_username, }, expect_ok=False) self.assertEqual(patch_response2.status, status_code.error) self.assertEqual(patch_response2.sub_status, [status_code.username.exists]) # ################################################################################################################################ def test_user_update_by_id(self): username = self._get_random_username() password = self._get_random_data() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'password': password, }) user_id = response.user_id display_name = self._get_random_data() first_name = self._get_random_data() middle_name = self._get_random_data() last_name = self._get_random_data() email = self._get_random_data() is_approved = True is_locked = True password_expiry = '2345-12-27T11:22:33' password_must_change = True sign_up_status = const.signup_status.final approval_status = const.approval_status.rejected response = self.patch('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'user_id': user_id, 'display_name': display_name, 'first_name': first_name, 'middle_name': middle_name, 'last_name': last_name, 'email': email, 'is_approved': is_approved, 'is_locked': is_locked, 'password_expiry': password_expiry, 'password_must_change': password_must_change, 'sign_up_status': sign_up_status, 'approval_status': approval_status, }) response = self.get('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'user_id': user_id, }) self.assertEqual(response.user_id, user_id) self.assertEqual(response.display_name, display_name) self.assertEqual(response.email, email) self.assertEqual(response.first_name, first_name) self.assertEqual(response.last_name, last_name) self.assertEqual(response.middle_name, middle_name) self.assertEqual(response.username, username) self.assertEqual(response.is_locked, is_locked) self.assertEqual(response.password_expiry, password_expiry) self.assertEqual(response.password_must_change, password_must_change) self.assertEqual(response.sign_up_status, sign_up_status) self.assertEqual(response.approval_status, approval_status) # ################################################################################################################################ # ################################################################################################################################ class UserDeleteTestCase(BaseTest): def test_user_delete_by_super_user(self): response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': self._get_random_username(), }) user_id = response.user_id response = self.get('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'user_id': user_id, }) self.assertEqual(response.status, status_code.ok) response = self.delete('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'user_id': user_id, }) self.assertEqual(response.status, status_code.ok) response = self.get('/zato/sso/user/search', { 'ust': self.ctx.super_user_ust, 'user_id': user_id, }) self.assertEqual(response.total, 0) # ################################################################################################################################ def test_user_delete_by_regular_user(self): response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': self._get_random_username(), }) self.assertEqual(response.status, status_code.ok) user_id1 = response.user_id response = self.get('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'user_id': user_id1, }) username = self._get_random_username() password = self._get_random_data() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'password': password, }) user_id2 = response.user_id self.post('/zato/sso/user/approve', { 'ust': self.ctx.super_user_ust, 'user_id': user_id1 }) self.post('/zato/sso/user/approve', { 'ust': self.ctx.super_user_ust, 'user_id': user_id2 }) response = self.post('/zato/sso/user/login', { 'username': username, 'password': password, }) ust = response.ust response = self.delete('/zato/sso/user', { 'ust': ust, 'user_id': user_id1, }, False) self.assertEqual(response.status, status_code.error) self.assertListEqual(response.sub_status, [status_code.auth.not_allowed]) # ################################################################################################################################ # ################################################################################################################################ class UserChangePasswordTestCase(BaseTest): def test_user_change_password_self(self): username = self._get_random_username() password = self._get_random_data() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'password': password, }) user_id = response.user_id self.post('/zato/sso/user/approve', { 'ust': self.ctx.super_user_ust, 'user_id': user_id }) response = self.post('/zato/sso/user/login', { 'username': username, 'password': password, }) self.assertIsNotNone(response.ust) ust = response.ust new_pasword = self._get_random_data() response = self.patch('/zato/sso/user/password', { 'ust': ust, 'user_id': user_id, 'old_password': password, 'new_password': new_pasword }) response = self.post('/zato/sso/user/login', { 'username': username, 'password': password, }, False) self.assertEqual(response.status, status_code.error) self.assertListEqual(response.sub_status, [status_code.auth.not_allowed]) response = self.post('/zato/sso/user/login', { 'username': username, 'password': new_pasword, }) self.assertEqual(response.status, status_code.ok) self.assertIsNotNone(response.ust) # ################################################################################################################################ def test_user_change_password_super_user(self): username = self._get_random_username() password = self._get_random_data() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'password': password, }) user_id = response.user_id self.post('/zato/sso/user/approve', { 'ust': self.ctx.super_user_ust, 'user_id': user_id }) response = self.post('/zato/sso/user/login', { 'username': username, 'password': password, }) self.assertIsNotNone(response.ust) new_pasword = self._get_random_data() password_expiry = 1 must_change = True response = self.patch('/zato/sso/user/password', { 'ust': self.ctx.super_user_ust, 'user_id': user_id, 'old_password': password, 'new_password': new_pasword, 'password_expiry': password_expiry, 'password_must_change': must_change, }) response = self.post('/zato/sso/user/login', { 'username': username, 'password': password, }, False) self.assertEqual(response.status, status_code.error) self.assertListEqual(response.sub_status, [status_code.auth.not_allowed]) response = self.post('/zato/sso/user/login', { 'username': username, 'password': new_pasword, }, False) self.assertEqual(response.status, status_code.warning) self.assertListEqual(response.sub_status, [status_code.password.w_about_to_exp]) self.assertIsNotNone(response.ust) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
29,024
Python
.py
594
39.47138
130
0.483379
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,947
test_session_attr_exists.py
zatosource_zato/code/zato-sso/test/zato/test_session_attr_exists.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # Zato from base import BaseTest # ################################################################################################################################ # ################################################################################################################################ class SessionAttrExistsTestCase(BaseTest): # ################################################################################################################################ def test_exists(self): name = self._get_random_data() value = self._get_random_data() expiration = 900 self.post('/zato/sso/session/attr', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': value, 'expiration': expiration }) response = self.get('/zato/sso/session/attr/exists', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, 'name': name, }) self.assertTrue(response.result) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
1,863
Python
.py
37
44.054054
130
0.344199
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,948
test_login_totp.py
zatosource_zato/code/zato-sso/test/zato/test_login_totp.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from unittest import main # Zato from base import BaseTest from zato.common.api import SEC_DEF_TYPE from zato.common.crypto.totp_ import TOTPManager from zato.sso import status_code # For Pyflakes SEC_DEF_TYPE = SEC_DEF_TYPE # ################################################################################################################################ basic_auth_user_name = 'pubapi' # ################################################################################################################################ # ################################################################################################################################ class TOTPTestCase(BaseTest): # ################################################################################################################################ def test_user_login_totp_valid(self): self.patch('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'is_totp_enabled': True, 'totp_key': self.ctx.config.super_user_totp_key, }) response = self.post('/zato/sso/user/login', { 'username': self.ctx.config.super_user_name, 'password': self.ctx.config.super_user_password, 'totp_code': TOTPManager.get_current_totp_code(self.ctx.config.super_user_totp_key), }) self.assertIsNotNone(response.ust) # ################################################################################################################################ def test_user_login_totp_invalid(self): self.patch('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'is_totp_enabled': True, 'totp_key': self.ctx.config.super_user_totp_key, }) response = self.post('/zato/sso/user/login', { 'username': self.ctx.config.super_user_name, 'password': self.ctx.config.super_user_password, 'totp_code': 'invalid' }, False) self.assertEqual(response.status, status_code.error) self.assertListEqual(response.sub_status, [status_code.auth.not_allowed]) # ################################################################################################################################ def test_user_login_totp_missing(self): self.patch('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'is_totp_enabled': True, 'totp_key': self.ctx.config.super_user_totp_key, }) response = self.post('/zato/sso/user/login', { 'username': self.ctx.config.super_user_name, 'password': self.ctx.config.super_user_password, }, False) self.assertEqual(response.status, status_code.error) self.assertListEqual(response.sub_status, [status_code.auth.totp_missing]) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
3,430
Python
.py
64
46.609375
130
0.409404
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,949
test_user_attr_delete.py
zatosource_zato/code/zato-sso/test/zato/test_user_attr_delete.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # Zato from base import BaseTest # ################################################################################################################################ # ################################################################################################################################ class UserAttrDeleteTestCase(BaseTest): # ################################################################################################################################ def test_delete(self): name = self._get_random_data() value = self._get_random_data() expiration = 900 self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': value, 'expiration': expiration }) self.delete('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, }) response = self.get('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, }) self.assertFalse(response.found) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
1,950
Python
.py
41
40.780488
130
0.338795
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,950
test_user_attr_update.py
zatosource_zato/code/zato-sso/test/zato/test_user_attr_update.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # Zato from base import BaseTest from zato.sso import status_code # ################################################################################################################################ # ################################################################################################################################ class UserAttrUpdateTestCase(BaseTest): # ################################################################################################################################ def test_update(self): name = self._get_random_data() value = self._get_random_data() expiration = 900 new_value = self._get_random_data() new_expiration = 123 self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': value, 'expiration': expiration }) self.patch('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': new_value, 'expiration': new_expiration }) # ################################################################################################################################ def test_update_for_another_user_by_super_user(self): username = self._get_random_username() password = self._get_random_data() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'password': password, }) user_id = response.user_id self._approve(user_id) name = self._get_random_data() value = self._get_random_data() expiration = 900 self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': user_id, 'name': name, 'value': value, 'expiration': expiration }) new_value = self._get_random_data() new_expiration = 123 self.patch('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': user_id, 'name': name, 'value': new_value, 'expiration': new_expiration }) # ################################################################################################################################ def test_update_for_another_user_by_regular_user(self): username1 = self._get_random_username() password1 = self._get_random_data() username2 = self._get_random_username() password2 = self._get_random_data() response1 = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username1, 'password': password1, }) response2 = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username2, 'password': password2, }) user_id1 = response1.user_id self._approve(user_id1) user_id2 = response2.user_id self._approve(user_id2) response = self.post('/zato/sso/user/login', { 'username': username1, 'password': password1, }) ust = response.ust name = self._get_random_data() value = self._get_random_data() expiration = 900 self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': user_id2, 'name': name, 'value': value, 'expiration': expiration }) new_value = self._get_random_data() new_expiration = 123 response = self.patch('/zato/sso/user/attr', { 'ust': ust, 'user_id': user_id2, 'name': name, 'value': new_value, 'expiration': new_expiration }, False) self.assertEqual(response.status, status_code.error) self.assertEqual(response.sub_status, [status_code.auth.not_allowed]) # ################################################################################################################################ def test_update_many(self): name1 = self._get_random_data() name2 = self._get_random_data() value1 = self._get_random_data() value2 = self._get_random_data() new_value1 = self._get_random_data() new_value2 = self._get_random_data() data = [ {'name': name1, 'value': value1}, {'name': name2, 'value': value2}, ] new_data = [ {'name': name1, 'value': new_value1}, {'name': name2, 'value': new_value2}, ] self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'data': data, }) self.patch('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'data': new_data, }) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
5,888
Python
.py
142
32.06338
130
0.427418
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,951
test_session.py
zatosource_zato/code/zato-sso/test/zato/test_session.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from datetime import datetime from unittest import main # ciso8601 try: from zato.common.util.api import parse_datetime except ImportError: from dateutil.parser import parse as parse_datetime # Zato from base import BaseTest from zato.sso import status_code # ################################################################################################################################ # ################################################################################################################################ class SessionVerifyTestCase(BaseTest): # ################################################################################################################################ def test_verify_self(self): response = self.post('/zato/sso/user/session', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, }) self.assertTrue(response.is_valid) # ################################################################################################################################ def xtest_verify_another_user(self): username = self._get_random_username() password = self._get_random_data() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'password': password, }) user_id = response.user_id self._approve(user_id) response = self.post('/zato/sso/user/login', { 'username': username, 'password': password, }) ust = response.ust response = self.post('/zato/sso/user/session', { 'current_ust': self.ctx.super_user_ust, 'target_ust': ust, }) self.assertTrue(response.is_valid) response = self.post('/zato/sso/user/logout', { 'ust': ust, }) response = self.post('/zato/sso/user/session', { 'current_ust': self.ctx.super_user_ust, 'target_ust': ust, }) self.assertFalse(response.is_valid) # ################################################################################################################################ def xtest_verify_not_super_user(self): username1 = self._get_random_username() password1 = self._get_random_data() username2 = self._get_random_username() password2 = self._get_random_data() response1 = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username1, 'password': password1, }) response2 = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username2, 'password': password2, }) user_id1 = response1.user_id user_id2 = response2.user_id self._approve(user_id1) self._approve(user_id2) response1 = self.post('/zato/sso/user/login', { 'username': username1, 'password': password1, }) response2 = self.post('/zato/sso/user/login', { 'username': username1, 'password': password1, }) ust1 = response1.ust ust2 = response2.ust response1 = self.post('/zato/sso/user/session', { 'current_ust': ust1, 'target_ust': ust2, }, False) response2 = self.post('/zato/sso/user/session', { 'current_ust': ust2, 'target_ust': ust1, }, False) response3 = self.post('/zato/sso/user/session', { 'current_ust': ust1, 'target_ust': ust1, }, False) response4 = self.post('/zato/sso/user/session', { 'current_ust': ust2, 'target_ust': ust2, }, False) response5 = self.post('/zato/sso/user/session', { 'current_ust': ust1, 'target_ust': self.ctx.super_user_ust, }, False) response6 = self.post('/zato/sso/user/session', { 'current_ust': ust1, 'target_ust': self.ctx.super_user_ust, }, False) self.assertEqual(response1.status, status_code.error) self.assertListEqual(response1.sub_status, [status_code.auth.not_allowed]) self.assertEqual(response2.status, status_code.error) self.assertListEqual(response2.sub_status, [status_code.auth.not_allowed]) self.assertEqual(response3.status, status_code.error) self.assertListEqual(response3.sub_status, [status_code.auth.not_allowed]) self.assertEqual(response4.status, status_code.error) self.assertListEqual(response4.sub_status, [status_code.auth.not_allowed]) self.assertEqual(response5.status, status_code.error) self.assertListEqual(response5.sub_status, [status_code.auth.not_allowed]) self.assertEqual(response6.status, status_code.error) self.assertListEqual(response6.sub_status, [status_code.auth.not_allowed]) # ################################################################################################################################ # ################################################################################################################################ class SessionRenewTestCase(BaseTest): def xtest_renew(self): now = datetime.utcnow() response = self.patch('/zato/sso/user/session', { 'ust': self.ctx.super_user_ust, }) self.assertGreater(parse_datetime(response.expiration_time), now) # ################################################################################################################################ # ################################################################################################################################ class SessionGetTestCase(BaseTest): # ################################################################################################################################ def xtest_get_regular_user(self): username = self._get_random_username() password = self._get_random_data() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'password': password, }) user_id = response.user_id self._approve(user_id) response = self.post('/zato/sso/user/login', { 'username': username, 'password': password, }) ust = response.ust response = self.get('/zato/sso/user/session', { 'current_ust': ust, 'target_ust': self.ctx.super_user_ust, }, False) self.assertEqual(response.status, status_code.error) self.assertListEqual(response.sub_status, [status_code.auth.not_allowed]) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
7,565
Python
.py
161
38.31677
130
0.462723
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,952
test_user_attr_create.py
zatosource_zato/code/zato-sso/test/zato/test_user_attr_create.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # Zato from base import BaseTest from zato.sso import status_code # ################################################################################################################################ # ################################################################################################################################ class UserAttrCreateTestCase(BaseTest): # ################################################################################################################################ def test_create(self): name = self._get_random_data() value = self._get_random_data() expiration = 900 self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': value, 'expiration': expiration }) # ################################################################################################################################ def test_create_already_exists(self): name = self._get_random_data() value = self._get_random_data() response1 = self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': value, }) response2 = self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': value, }, False) self.assertEqual(response1.status, status_code.ok) self.assertEqual(response2.status, status_code.error) self.assertListEqual(response2.sub_status, [status_code.attr.already_exists]) # ################################################################################################################################ def test_create_for_another_user_by_super_user(self): username = self._get_random_username() password = self._get_random_data() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'password': password, }) user_id = response.user_id self._approve(user_id) name = self._get_random_data() value = self._get_random_data() expiration = 900 response = self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': user_id, 'name': name, 'value': value, 'expiration': expiration }) self.assertEqual(response.status, status_code.ok) # ################################################################################################################################ def test_create_for_another_user_by_regular_user(self): username1 = self._get_random_username() password1 = self._get_random_data() username2 = self._get_random_username() password2 = self._get_random_data() response1 = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username1, 'password': password1, }) response2 = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username2, 'password': password2, }) user_id1 = response1.user_id self._approve(user_id1) user_id2 = response2.user_id self._approve(user_id2) response = self.post('/zato/sso/user/login', { 'username': username1, 'password': password1, }) ust = response.ust name = self._get_random_data() value = self._get_random_data() expiration = 900 response = self.post('/zato/sso/user/attr', { 'ust': ust, 'user_id': user_id2, 'name': name, 'value': value, 'expiration': expiration }, False) self.assertEqual(response.status, status_code.error) self.assertEqual(response.sub_status, [status_code.auth.not_allowed]) # ################################################################################################################################ def test_create_many(self): data = [ {'name': self._get_random_data(), 'value': self._get_random_data()}, {'name': self._get_random_data(), 'value': self._get_random_data()}, ] response = self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'data': data, }) self.assertEqual(response.status, status_code.ok) # ################################################################################################################################ def test_create_many_already_exists(self): data = [ {'name': self._get_random_data(), 'value': self._get_random_data()}, {'name': self._get_random_data(), 'value': self._get_random_data()}, ] response1 = self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'data': data, }) response2 = self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'data': data, }, False) self.assertEqual(response1.status, status_code.ok) self.assertEqual(response2.status, status_code.error) self.assertListEqual(response2.sub_status, [status_code.attr.already_exists]) # ################################################################################################################################ def test_create_many_for_another_user_by_super_user(self): username = self._get_random_username() password = self._get_random_data() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'password': password, }) user_id = response.user_id self._approve(user_id) data = [ {'name': self._get_random_data(), 'value': self._get_random_data()}, {'name': self._get_random_data(), 'value': self._get_random_data()}, ] response = self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': user_id, 'data': data, }) self.assertEqual(response.status, status_code.ok) # ################################################################################################################################ def test_create_many_for_another_user_by_regular_user(self): username1 = self._get_random_username() password1 = self._get_random_data() username2 = self._get_random_username() password2 = self._get_random_data() response1 = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username1, 'password': password1, }) response2 = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username2, 'password': password2, }) user_id1 = response1.user_id self._approve(user_id1) user_id2 = response2.user_id self._approve(user_id2) response = self.post('/zato/sso/user/login', { 'username': username1, 'password': password1, }) ust = response.ust data = [ {'name': self._get_random_data(), 'value': self._get_random_data()}, {'name': self._get_random_data(), 'value': self._get_random_data()}, ] response = self.post('/zato/sso/user/attr', { 'ust': ust, 'user_id': user_id2, 'data': data }, False) self.assertEqual(response.status, status_code.error) self.assertEqual(response.sub_status, [status_code.auth.not_allowed]) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
8,920
Python
.py
197
35.766497
130
0.45052
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,953
test_session_list.py
zatosource_zato/code/zato-sso/test/zato/test_session_list.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # Zato from base import BaseTest from zato.sso import status_code # ################################################################################################################################ # ################################################################################################################################ class SessionGetListTestCase(BaseTest): # ################################################################################################################################ def test_get_list_self_super_user(self): self.post('/zato/sso/user/session', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, }) self.patch('/zato/sso/user/session', { 'ust': self.ctx.super_user_ust, }) response = self.get('/zato/sso/user/session/list', { 'ust': self.ctx.super_user_ust, }) self.assertEqual(response.status, status_code.ok) self.assertTrue(len(response.result) > 0) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
1,751
Python
.py
33
47.939394
130
0.347826
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,954
__init__.py
zatosource_zato/code/zato-sso/test/zato/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals
238
Python
.py
6
38.166667
82
0.729258
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,955
test_command_line.py
zatosource_zato/code/zato-sso/test/zato/test_command_line.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from unittest import main # Zato from base import BaseTest from zato.common.util.cli import CommandLineServiceInvoker # ################################################################################################################################ # ################################################################################################################################ class CommandLineTestCase(BaseTest): def test_command_line(self) -> 'None': # stdlib import os if not os.environ.get('ZATO_TEST_SSO'): return service = 'zato.sso.sso-test-service' invoker = CommandLineServiceInvoker() invoker.invoke_and_test(service) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################ # ################################################################################################################################
1,435
Python
.py
27
49.148148
130
0.296774
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,956
base.py
zatosource_zato/code/zato-sso/test/zato/base.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import logging from datetime import datetime from itertools import count # Bunch # ciso8601 try: from zato.common.util.api import parse_datetime except ImportError: from dateutil.parser import parse as parse_datetime # sh import sh # Zato from zato.common.util.api import get_odb_session_from_server_dir from zato.common.crypto.totp_ import TOTPManager from zato.common.test.config import TestConfig from zato.common.test.rest_client import RESTClientTestCase from zato.common.test import rand_string from zato.common.typing_ import cast_ from zato.sso import const, status_code from zato.sso.odb.query import get_user_by_name # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import any_ any_ = any_ # ################################################################################################################################ # ################################################################################################################################ logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s') logger = logging.getLogger(__name__) # ################################################################################################################################ # ################################################################################################################################ class NotGiven: pass # ################################################################################################################################ # ################################################################################################################################ class TestCtx: def __init__(self): self.reset() def reset(self): self.super_user_ust = None # type: str self.super_user_id = None # type: str self.config = TestConfig # ################################################################################################################################ # ################################################################################################################################ class BaseTest(RESTClientTestCase): # ################################################################################################################################ def setUp(self): # stdlib import os if not os.environ.get('ZATO_TEST_SSO'): self.ctx = cast_('any_', None) return # Zato from zato.common.util.cli import get_zato_sh_command try: # Create the test user if the account does not already exist .. odb_session = self.get_odb_session() if not get_user_by_name(odb_session, TestConfig.super_user_name, False): command = get_zato_sh_command() # .. create the user .. command('sso', 'create-super-user', TestConfig.server_location, TestConfig.super_user_name, '--password', TestConfig.super_user_password, '--email', 'test@example.com', '--verbose') # .. and set the TOTP .. command('sso', 'reset-totp-key', TestConfig.server_location, TestConfig.super_user_name, '--key', TestConfig.super_user_totp_key, '--verbose') except Exception as e: # .. but ignore it if such a user already exists. if not 'User already exists' in e.args[0]: if isinstance(e, sh.ErrorReturnCode): logger.warning('Shell exception %s', e.stderr) raise # Create a new context object for each test self.ctx = TestCtx() self._login_super_user() # A new counter for random data self.rand_counter = count() # ################################################################################################################################ def tearDown(self): if self.ctx: self.ctx.reset() # ################################################################################################################################ def get_odb_session(self): return get_odb_session_from_server_dir(TestConfig.server_location) # ################################################################################################################################ def _get_random(self, prefix, _utcnow=datetime.utcnow): return prefix.format(_utcnow().isoformat(), next(self.rand_counter)) + '.' + rand_string()[:10] # ################################################################################################################################ def _get_random_username(self): return self._get_random(TestConfig.username_prefix) # ################################################################################################################################ def _get_random_data(self): return self._get_random(TestConfig.random_prefix) # ################################################################################################################################ def _login_super_user(self): response = self.post('/zato/sso/user/login', { 'username': TestConfig.super_user_name, 'password': TestConfig.super_user_password, 'totp_code': TOTPManager.get_current_totp_code(TestConfig.super_user_totp_key), }) self.ctx.super_user_ust = response.ust response = self.get('/zato/sso/user', { 'ust': self.ctx.super_user_ust, }) self.ctx.super_user_id = response.user_id # ################################################################################################################################ def _assert_default_user_data(self, response, now, approval_status=None): self.assertEqual(response.approval_status, approval_status or const.approval_status.before_decision) self.assertEqual(response.sign_up_status, const.signup_status.final) self.assertTrue(response.is_active) self.assertTrue(response.password_is_set) self.assertTrue(response.user_id.startswith('zusr')) self.assertTrue(response.username.startswith('test.')) self.assertFalse(response.is_internal) self.assertFalse(response.is_locked) self.assertFalse(response.is_super_user) self.assertFalse(response.password_must_change) self.assertIsNotNone(response.approval_status_mod_by) self._assert_user_dates(response, now) # ################################################################################################################################ def _assert_user_dates(self, response, now, is_default_user=False): now = now.isoformat() func = self.assertGreater if is_default_user else self.assertLess func(now, parse_datetime(response.approval_status_mod_time).isoformat() + '.999999') func(now, parse_datetime(response.password_last_set).isoformat() + '.999999') func(now, parse_datetime(response.sign_up_time).isoformat() + '.999999') self.assertLess(now, parse_datetime(response.password_expiry).isoformat() + '.999999') # ################################################################################################################################ def _approve(self, user_id): self.post('/zato/sso/user/approve', { 'ust': self.ctx.super_user_ust, 'user_id': user_id }) # ################################################################################################################################ def _create_and_approve_user(self, username=None, password=None): username = username or self._get_random_username() password = password or self._get_random_data() response = self.post('/zato/sso/user', { 'ust': self.ctx.super_user_ust, 'username': username, 'password': password, }) self.assertEqual(response.status, status_code.ok) response = self.post('/zato/sso/user/approve', { 'ust': self.ctx.super_user_ust, 'user_id': response.user_id }) self.assertEqual(response.status, status_code.ok) # ################################################################################################################################ # ################################################################################################################################
8,991
Python
.py
158
49.329114
130
0.425165
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,957
test_user_attr_names.py
zatosource_zato/code/zato-sso/test/zato/test_user_attr_names.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # Zato from base import BaseTest # ################################################################################################################################ # ################################################################################################################################ class UserAttrExistsTestCase(BaseTest): # ################################################################################################################################ def test_exists(self): name1 = self._get_random_data() value1 = self._get_random_data() name2 = self._get_random_data() value2 = self._get_random_data() data = [ {'name':name1, 'value':value1}, {'name':name2, 'value':value2}, ] self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'data': data }) response = self.get('/zato/sso/user/attr/names', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, }) self.assertIn(name1, response.result) self.assertIn(name2, response.result) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
1,916
Python
.py
39
42.846154
130
0.344809
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,958
test_session_attr_get.py
zatosource_zato/code/zato-sso/test/zato/test_session_attr_get.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # ciso8601 try: from zato.common.util.api import parse_datetime except ImportError: from dateutil.parser import parse as parse_datetime # Zato from base import BaseTest # ################################################################################################################################ # ################################################################################################################################ class SessionAttrGetTestCase(BaseTest): # ################################################################################################################################ def test_get(self): name = self._get_random_data() value = self._get_random_data() expiration = 900 self.post('/zato/sso/session/attr', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': value, 'expiration': expiration }) response = self.get('/zato/sso/session/attr', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, 'name': name, }) self.assertTrue(response.found) self.assertEqual(response.name, name) self.assertEqual(response.value, value) # Will raise an exception if date parsing fails parse_datetime(response.creation_time) parse_datetime(response.last_modified) parse_datetime(response.expiration_time) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
2,288
Python
.py
48
41.375
130
0.416292
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,959
test_session_attr_create.py
zatosource_zato/code/zato-sso/test/zato/test_session_attr_create.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # Zato from base import BaseTest # ################################################################################################################################ # ################################################################################################################################ class SessionAttrCreateTestCase(BaseTest): # ################################################################################################################################ def test_create(self): name = self._get_random_data() value = self._get_random_data() expiration = 900 self.post('/zato/sso/session/attr', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': value, 'expiration': expiration }) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
1,617
Python
.py
31
46.83871
130
0.312341
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,960
test_user_attr_exists.py
zatosource_zato/code/zato-sso/test/zato/test_user_attr_exists.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # Zato from base import BaseTest # ################################################################################################################################ # ################################################################################################################################ class UserAttrExistsTestCase(BaseTest): # ################################################################################################################################ def test_exists(self): name1 = self._get_random_data() value1 = self._get_random_data() name2 = self._get_random_data() value2 = self._get_random_data() data = [ {'name':name1, 'value':value1}, {'name':name2, 'value':value2}, ] self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'data': data }) response = self.get('/zato/sso/user/attr/exists', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name1, }) self.assertTrue(response.result) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
1,893
Python
.py
39
42.153846
130
0.336057
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,961
test_linked_auth.py
zatosource_zato/code/zato-sso/test/zato/test_linked_auth.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # Zato from base import BaseTest from zato.common.api import SEC_DEF_TYPE # For Pyflakes SEC_DEF_TYPE = SEC_DEF_TYPE # ################################################################################################################################ basic_auth_user_name = 'pubapi' # ################################################################################################################################ # ################################################################################################################################ class LinkedAuthTestCase(BaseTest): def test_create(self): self.post('/zato/sso/user/linked', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'auth_type': SEC_DEF_TYPE.BASIC_AUTH, 'auth_username': basic_auth_user_name, 'is_active': True, }) self.get('/zato/sso/user/linked', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id }) response = self.delete('/zato/sso/user/linked', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'auth_type': SEC_DEF_TYPE.BASIC_AUTH, 'auth_username': basic_auth_user_name, }) self.assertEqual(response.status, 'ok') # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
2,061
Python
.py
42
42.97619
130
0.373313
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,962
test_user_attr_get.py
zatosource_zato/code/zato-sso/test/zato/test_user_attr_get.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # ciso8601 try: from zato.common.util.api import parse_datetime except ImportError: from dateutil.parser import parse as parse_datetime # Zato from base import BaseTest # ################################################################################################################################ # ################################################################################################################################ class UserAttrGetTestCase(BaseTest): # ################################################################################################################################ def test_get(self): name = self._get_random_data() value = self._get_random_data() expiration = 900 self.post('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': value, 'expiration': expiration }) response = self.get('/zato/sso/user/attr', { 'ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, }) self.assertTrue(response.found) self.assertEqual(response.name, name) self.assertEqual(response.value, value) # Will raise an exception if date parsing fails parse_datetime(response.creation_time) parse_datetime(response.last_modified) parse_datetime(response.expiration_time) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
2,208
Python
.py
47
40.829787
130
0.405973
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,963
test_session_attr_delete.py
zatosource_zato/code/zato-sso/test/zato/test_session_attr_delete.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # Zato from base import BaseTest # ################################################################################################################################ # ################################################################################################################################ class SessionAttrDeleteTestCase(BaseTest): # ################################################################################################################################ def test_delete(self): name = self._get_random_data() value = self._get_random_data() expiration = 900 new_value = self._get_random_data() new_expiration = 123 self.post('/zato/sso/session/attr', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': value, 'expiration': expiration }) self.delete('/zato/sso/session/attr', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': new_value, 'expiration': new_expiration }) response = self.get('/zato/sso/session/attr', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, 'name': name, }) self.assertFalse(response.found) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
2,239
Python
.py
47
40.212766
130
0.373045
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,964
test_session_attr_names.py
zatosource_zato/code/zato-sso/test/zato/test_session_attr_names.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # Zato from base import BaseTest # ################################################################################################################################ # ################################################################################################################################ class SessionAttrNamesTestCase(BaseTest): # ################################################################################################################################ def test_names(self): name1 = self._get_random_data() value1 = self._get_random_data() name2 = self._get_random_data() value2 = self._get_random_data() data = [ {'name':name1, 'value':value1}, {'name':name2, 'value':value2}, ] self.post('/zato/sso/session/attr', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'data': data }) response = self.get('/zato/sso/session/attr/names', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, }) self.assertIn(name1, response.result) self.assertIn(name2, response.result) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
2,041
Python
.py
41
43.170732
130
0.36226
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,965
test_session_attr_update.py
zatosource_zato/code/zato-sso/test/zato/test_session_attr_update.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from unittest import main # Zato from base import BaseTest # ################################################################################################################################ # ################################################################################################################################ class SessionAttrUpdateTestCase(BaseTest): # ################################################################################################################################ def test_update(self): name = self._get_random_data() value = self._get_random_data() expiration = 900 new_value = self._get_random_data() new_expiration = 123 self.post('/zato/sso/session/attr', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': value, 'expiration': expiration }) self.patch('/zato/sso/session/attr', { 'current_ust': self.ctx.super_user_ust, 'target_ust': self.ctx.super_user_ust, 'user_id': self.ctx.super_user_id, 'name': name, 'value': new_value, 'expiration': new_expiration }) # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
1,999
Python
.py
41
41.902439
130
0.352214
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,966
__init__.py
zatosource_zato/code/zato-sso/src/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals
238
Python
.py
6
38.166667
82
0.729258
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,967
__init__.py
zatosource_zato/code/zato-sso/src/zato/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from pkgutil import extend_path __path__ = extend_path(__path__, __name__) __import__('pkg_resources').declare_namespace(__name__)
287
Python
.py
8
34.375
64
0.683636
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,968
totp_.py
zatosource_zato/code/zato-sso/src/zato/sso/totp_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from datetime import datetime from logging import getLogger # Zato from zato.common.audit import audit_pii from zato.common.crypto.totp_ import TOTPManager from zato.sso import InvalidTOTPError, status_code, ValidationError # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.odb.model import SSOUser from zato.common.typing_ import anydict, callable_ from zato.sso.api import SSOAPI from zato.sso.model import RequestCtx # ################################################################################################################################ # ################################################################################################################################ logger = getLogger('zato') logger_audit_pii = getLogger('zato_audit_pii') # ################################################################################################################################ # ################################################################################################################################ class TOTPAPI: """ An object through which TOTP tokens can be validated and manipulated. """ def __init__(self, sso_api:'SSOAPI', sso_conf:'anydict', decrypt_func:'callable_') -> 'None': self.sso_api = sso_api self.sso_conf = sso_conf self.decrypt_func = decrypt_func # ################################################################################################################################ def _ensure_code_is_valid( self, req_ctx, # type: RequestCtx *, code='', # type: str user_totp_key, # type: str ): """ Checks whether input TOTP token matches the user TOTP key. """ # This may be potentially encrypted .. user_totp_key = self.decrypt_func(user_totp_key) # .. finally, verify the code .. if TOTPManager.verify_totp_code(user_totp_key, code): logger_audit_pii.info('TOTP code accepted; cid `%s`', req_ctx.cid) # .. the code was invalid .. else: # .. this goes to logs .. msg = 'Invalid TOTP code; cid `%s`' logger.warning(msg, req_ctx.cid) logger_audit_pii.warning(msg, req_ctx.cid) # .. and this specific exception is raised if the code was invalid, # .. note, however, that the status code is a generic one because # .. this is what will be likely returned to the user. raise InvalidTOTPError(status_code.auth.not_allowed, False) # ################################################################################################################################ def _ensure_code_exists(self, req_ctx:'RequestCtx', code:'str') -> 'None': # We expect to have a code on input .. if not code: # This goes to logs .. msg = 'Missing TOTP code; cid `%s`' logger.warning(msg, req_ctx.cid) logger_audit_pii.warning(msg, req_ctx.cid) # .. this goes to the user and which status code it is, # .. will depend on the configuration found in sso.conf. if self.sso_conf.login.get('inform_if_totp_missing', False): _code = status_code.auth.totp_missing _return_status = True else: _code = status_code.auth.not_allowed _return_status = False # Notify the caller that TOTP validation failed raise ValidationError(_code, _return_status) # ################################################################################################################################ def validate_code_for_user( self, req_ctx, # type: RequestCtx *, code, # type: str user, # type: SSOUser ) -> 'None': """ Checks whether input TOTP token is valid for a user object. """ # PII audit comes first audit_pii.info(req_ctx.cid, 'totp_api.validate_code_for_user', extra={ 'current_app':req_ctx.current_app, 'remote_addr':req_ctx.remote_addr, 'has_code': bool(code), 'has_user': bool(user), }) # Raises an exception if code is missing self._ensure_code_exists(req_ctx, code) # Raises an exception if the input code is invalid self._ensure_code_is_valid(req_ctx, code=code, user_totp_key=user.totp_key) # ################################################################################################################################ def validate_code( self, req_ctx, # type: RequestCtx *, code, # type: str ust='', # type: str username='' # type: str ) -> 'None': """ Checks whether input TOTP token is valid for a UST or username. """ # PII audit comes first audit_pii.info(req_ctx.cid, 'totp_api.validate_code', extra={ 'current_app': req_ctx.current_app, 'remote_addr': req_ctx.remote_addr, 'has_code': bool(code), 'has_ust': bool(ust), 'has_username': bool(username), }) # Basic validation .. if not (ust or username): raise ValueError('Exactly one of ust or username is required on input') # .. basic validation continued .. if ust and username: raise ValueError('Cannot provide both ust and username on input') # Raises an exception if code is missing self._ensure_code_exists(req_ctx, code) # # Now, we can look up our the user object needed. # # If we have a UST, we first need to find the corresponding session, # which will point us to the underlying username .. if ust: # This may be potentially encrypted ust = self.decrypt_func(ust) session = self.sso_api.user.session.get_session_by_ust(ust, datetime.utcnow()) username = session.username # .. either through an input parameter or via UST, at this point we have a username user = self.sso_api.user.get_user_by_username(req_ctx.cid, username) # type: SSOUser # Raises an exception if the input code is invalid self.validate_code_for_user(req_ctx, code=code, user=user) # ################################################################################################################################ # ################################################################################################################################
7,068
Python
.py
139
42.28777
130
0.464586
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,969
util.py
zatosource_zato/code/zato-sso/src/zato/sso/util.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from contextlib import closing from datetime import datetime, timedelta from logging import getLogger from uuid import uuid4 # Base32 Crockford from base32_crockford import encode as crockford_encode # ipaddress from ipaddress import ip_network # SQLAlchemy from sqlalchemy import update # zxcvbn from zxcvbn import zxcvbn # Zato from zato.common.crypto.api import CryptoManager from zato.common.odb.model import SSOUser as UserModel from zato.sso import const, status_code, ValidationError from zato.sso.common import LoginCtx # ################################################################################################################################ if 0: from bunch import Bunch from zato.common.odb.model import SSOUser from zato.common.typing_ import any_, anylist, boolnone, callable_, callnone, intnone SSOUser = SSOUser # ################################################################################################################################ # ################################################################################################################################ logger = getLogger('zato') # ################################################################################################################################ _gen_secret = CryptoManager.generate_secret # ################################################################################################################################ _utcnow = datetime.utcnow UserModelTable = UserModel.__table__ # ################################################################################################################################ def _new_id(prefix:'str', _uuid4:'callable_'=uuid4, _crockford_encode:'callable_'=crockford_encode) -> 'str': return '%s%s' % (prefix, _crockford_encode(_uuid4().int).lower()) # ################################################################################################################################ def new_confirm_token(_gen_secret:'callable_'=_gen_secret) -> 'str': return _gen_secret(192) # ################################################################################################################################ def new_user_id(_new_id:'callable_'=_new_id) -> 'str': return _new_id('zusr') # ################################################################################################################################ def new_user_session_token(_new_id:'callable_'=_new_id) -> 'str': return _new_id('zust') # ################################################################################################################################ def new_prt(_new_id:'callable_'=_new_id) -> 'str': # Note that these tokens are to be publicly visible and this is why we prefer # not to be conspicuous about the prefix. return _new_id('') # ################################################################################################################################ def new_prt_reset_key(_new_id:'callable_'=_new_id) -> 'str': return _new_id('zprtrkey') # ################################################################################################################################ def validate_password(sso_conf:'Bunch', password:'str') -> 'None': """ Raises ValidationError if password is invalid, e.g. it is too simple. """ # This is optional min_complexity = int(sso_conf.password.get('min_complexity', 4)) if min_complexity: result = zxcvbn(password) if result['score'] < min_complexity: raise ValidationError(status_code.password.not_complex_enough, sso_conf.password.inform_if_invalid) # Password may not be too short if len(password) < sso_conf.password.min_length: raise ValidationError(status_code.password.too_short, sso_conf.password.inform_if_invalid) # Password may not be too long if len(password) > sso_conf.password.max_length: raise ValidationError(status_code.password.too_long, sso_conf.password.inform_if_invalid) # Password's default complexity (i.e. the reject list) is checked case-insensitively password = password.lower() # Password may not contain most commonly used ones for elem in sso_conf.password.reject_list: if elem in password: logger.warning('Password rejected because it contains a disallowed pattern from sso.conf -> password.reject_list') raise ValidationError(status_code.password.invalid, sso_conf.password.inform_if_invalid) # ################################################################################################################################ def make_data_secret(data:'str', encrypt_func:'callable_'=None, hash_func:'callable_'=None) -> 'bytes': """ Turns data into a secret by hashing it (stretching) and then encrypting the result. """ # E.g. PBKDF2-SHA512 if hash_func: data = hash_func(data) data = data.encode('utf8') if isinstance(data, str) else data # E.g. Fernet (AES-128) if encrypt_func: data = encrypt_func(data) return data # ################################################################################################################################ def make_password_secret( password, # type: str encrypt_password, # type: callable_ encrypt_func=None, # type: callnone hash_func=None # type: callnone ) -> 'bytes': """ Encrypts and hashes a user password. """ return make_data_secret(password, encrypt_func if encrypt_password else None, hash_func) # ################################################################################################################################ def normalize_password_reject_list(sso_conf:'Bunch') -> 'None': """ Turns a multi-line string with passwords to be rejected into a set. """ reject = set() for line in sso_conf.password.get('reject_list', '').strip().splitlines(): line = str(line.strip().lower()) reject.add(line) sso_conf.password.reject_list = reject # ################################################################################################################################ def set_password( odb_session_func, # type: callable_ encrypt_func, # type: callable_ hash_func, # type: callable_ sso_conf, # type: Bunch user_id, # type: str password, # type: str must_change=None, # type: boolnone password_expiry=None, # type: intnone _utcnow=_utcnow # type: callable_ ) -> 'None': """ Sets a new password for user. """ # Just to be doubly sure, validate the password before saving it to DB. # Will raise ValidationError if anything is wrong. validate_password(sso_conf, password) now = _utcnow() password = make_password_secret(password, sso_conf.main.encrypt_password, encrypt_func, hash_func) password_expiry = password_expiry or sso_conf.password.expiry new_values = { 'password': password, 'password_is_set': True, 'password_last_set': now, 'password_expiry': now + timedelta(days=password_expiry), } # Must be a boolean because the underlying SQL column is a bool if must_change is not None: if not isinstance(must_change, bool): raise ValueError('Expected for must_change to be a boolean instead of `{}`, `{}`'.format( type(must_change), repr(must_change))) else: new_values['password_must_change'] = must_change with closing(odb_session_func()) as session: session.execute( update(UserModelTable).\ values(new_values).\ where(UserModelTable.c.user_id==user_id) ) session.commit() # ################################################################################################################################ def check_credentials( decrypt_func, # type: callable_ verify_hash_func, # type: callable_ stored_password, # type: str input_password # type: str ) -> 'bool': """ Checks that an incoming password is equal to the one that is stored in the database. """ password_decrypted = decrypt_func(stored_password) # At this point it is decrypted but still hashed return verify_hash_func(input_password, password_decrypted) # ################################################################################################################################ def normalize_sso_config(sso_conf:'Bunch') -> 'None': # Lower-case elements that must not be substrings in usernames .. reject_username = sso_conf.user_validation.get('reject_username', []) reject_username = [elem.strip().lower() for elem in reject_username] sso_conf.user_validation.reject_username = reject_username # .. and emails too. reject_email = sso_conf.user_validation.get('reject_email', []) reject_email = [elem.strip().lower() for elem in reject_email] sso_conf.user_validation.reject_email = reject_email # Construct a set of common passwords to reject out of a multi-line list normalize_password_reject_list(sso_conf) # Turn all app lists into sets to make lookups faster apps_all = sso_conf.apps.all apps_signup_allowed = sso_conf.apps.signup_allowed apps_login_allowed = sso_conf.apps.login_allowed apps_all = apps_all if isinstance(apps_all, list) else [apps_all] apps_signup_allowed = apps_signup_allowed if isinstance(apps_signup_allowed, list) else [apps_signup_allowed] apps_login_allowed = apps_login_allowed if isinstance(apps_login_allowed, list) else [apps_login_allowed] sso_conf.apps.all = set(apps_all) sso_conf.apps.signup_allowed = set(apps_signup_allowed) sso_conf.apps.login_allowed = set(apps_login_allowed) # There may be a single service in a relevant part of configuration # so for ease of use we always turn tjem into lists. usr_valid_srv = sso_conf.user_validation.service usr_valid_srv = usr_valid_srv if isinstance(usr_valid_srv, list) else [usr_valid_srv] sso_conf.user_validation.service = usr_valid_srv # Convert all white/black-listed IP addresses to sets of network objects # which will let serviced in run-time efficiently check for membership of an address in that network. user_address_list = sso_conf.user_address_list for username, ip_allowed in user_address_list.items(): if ip_allowed: ip_allowed = user_address_list if isinstance(ip_allowed, list) else [ip_allowed] ip_allowed = [ip_network(elem.decode('utf8')) for elem in ip_allowed if elem != '*'] else: ip_allowed = [] user_address_list[username] = ip_allowed # Make sure signup service list is a list callback_service_list = sso_conf.signup.callback_service_list or [] if callback_service_list: callback_service_list = callback_service_list if isinstance(callback_service_list, list) else [callback_service_list] sso_conf.signup.callback_service_list = callback_service_list # ################################################################################################################################ def check_remote_app_exists(current_app:'str', apps_all:'anylist', logger) -> 'bool': if current_app not in apps_all: logger.warning('Invalid current_app `%s`, not among `%s', current_app, apps_all) raise ValidationError(status_code.app_list.invalid) else: return True # ################################################################################################################################ # ################################################################################################################################ class UserChecker: """ Checks whether runtime information about the user making a request is valid. """ def __init__( self, decrypt_func, # type: callable_ verify_hash_func, # type: callable_ sso_conf # type: Bunch ) -> 'None': self.decrypt_func = decrypt_func self.verify_hash_func = verify_hash_func self.sso_conf = sso_conf # ################################################################################################################################ def check_credentials(self, ctx:'LoginCtx', user_password:'str') -> 'bool': return check_credentials(self.decrypt_func, self.verify_hash_func, user_password, ctx.input['password']) # ################################################################################################################################ def check_remote_app_exists(self, ctx:'LoginCtx') -> 'bool': return check_remote_app_exists(ctx.input['current_app'], self.sso_conf.apps.all, logger) # ################################################################################################################################ def check_login_to_app_allowed(self, ctx:'LoginCtx') -> 'bool': if ctx.input['current_app'] not in self.sso_conf.apps.login_allowed: if self.sso_conf.apps.inform_if_app_invalid: raise ValidationError(status_code.app_list.invalid, True) else: raise ValidationError(status_code.auth.not_allowed, True) else: return True # ################################################################################################################################ def check_remote_ip_allowed(self, ctx:'LoginCtx', user:'SSOUser', _invalid:'any_'=object()) -> 'bool': ip_allowed = self.sso_conf.user_address_list.get(user.username, _invalid) # Shortcut in the simplest case if ip_allowed == '*': return True # Do not continue if user is not whitelisted but is required to if ip_allowed is _invalid: if self.sso_conf.login.reject_if_not_listed: return else: # We are not to reject users if they are not listed, in other words, # we are to accept them even if they are not so we return a success flag. return True # User was found in configuration so now we need to check IPs allowed .. else: # .. but if there are no IPs configured for user, it means the person may not log in # regardless of reject_if_not_whitelisted, which is why it is checked separately. if not ip_allowed: return # There is at least one address or pattern to check again .. else: # .. but if no remote address was sent, we cannot continue. if not ctx.remote_addr: return False else: for _remote_addr in ctx.remote_addr: for _ip_allowed in ip_allowed: if _remote_addr in _ip_allowed: return True # OK, there was at least that one match so we report success # If we get here, it means that none of remote addresses from input matched # so we can return False to be explicit. return False # ################################################################################################################################ def check_user_not_locked(self, user:'SSOUser') -> 'bool': if user.is_locked: if self.sso_conf.login.inform_if_locked: raise ValidationError(status_code.auth.locked, True) else: return True # ################################################################################################################################ def check_signup_status(self, user:'SSOUser') -> 'bool': if user.sign_up_status != const.signup_status.final: if self.sso_conf.login.inform_if_not_confirmed: raise ValidationError(status_code.auth.invalid_signup_status, True) else: return True # ################################################################################################################################ def check_is_approved(self, user:'SSOUser') -> 'bool': if not user.approval_status == const.approval_status.approved: if self.sso_conf.login.inform_if_not_approved: raise ValidationError(status_code.auth.invalid_signup_status, True) else: return True # ################################################################################################################################ def check_password_expired(self, user:'SSOUser', _now:'callable_'=datetime.utcnow) -> 'bool': if _now() > user.password_expiry: if self.sso_conf.password.inform_if_expired: raise ValidationError(status_code.password.expired, True) else: return True # ################################################################################################################################ def check_password_about_to_expire( self, user, # type: SSOUser _now=datetime.utcnow, # type: callable_ _timedelta=timedelta # type: timedelta ) -> 'bool': # Find time after which the password is considered to be about to expire threshold_time = user.password_expiry - _timedelta(days=self.sso_conf.password.about_to_expire_threshold) # .. check if current time is already past that threshold .. if _now() > threshold_time: # .. if it is, we may either return a warning and continue .. if self.sso_conf.password.inform_if_about_to_expire: return status_code.warning # .. or it can considered an error, which rejects the request. else: return status_code.error # No approaching expiry, we may continue else: return True # ################################################################################################################################ def check_must_send_new_password(self, ctx:'LoginCtx', user:'SSOUser') -> 'bool': if user.password_must_change and not ctx.input.get('new_password'): if self.sso_conf.password.inform_if_must_be_changed: raise ValidationError(status_code.password.must_send_new, True) else: return True # ################################################################################################################################ def check_login_metadata_allowed(self, ctx:'LoginCtx') -> 'bool': if ctx.has_remote_addr or ctx.has_user_agent: if ctx.input['current_app'] not in self.sso_conf.apps.login_metadata_allowed: raise ValidationError(status_code.metadata.not_allowed, False) return True # ################################################################################################################################ def check(self, ctx, user:'LoginCtx', check_if_password_expired:'bool'=True) -> 'None': """ Runs a series of checks for incoming request and user. """ # Move checks to UserChecker in tools # Input application must have been previously defined if not self.check_remote_app_exists(ctx): raise ValidationError(status_code.auth.not_allowed, True) # If applicable, requests must originate in a white-listed IP address if not self.check_remote_ip_allowed(ctx, user): raise ValidationError(status_code.auth.not_allowed, True) # User must not have been locked out of the auth system if not self.check_user_not_locked(user): raise ValidationError(status_code.auth.not_allowed, True) # If applicable, user must be fully signed up, including account creation's confirmation if not self.check_signup_status(user): raise ValidationError(status_code.auth.not_allowed, True) # If applicable, user must be approved by a super-user if not self.check_is_approved(user): raise ValidationError(status_code.auth.not_allowed, True) # Password must not have expired, but only if input flag tells us to, # it may be possible that a user's password has already expired # and that person wants to change it in this very call, in which case # we cannot reject it on the basis that it is expired - no one would be able # to change expired passwords then. if check_if_password_expired: if not self.check_password_expired(user): raise ValidationError(status_code.auth.not_allowed, True) # Current application must be allowed to send login metadata if not self.check_login_metadata_allowed(ctx): raise ValidationError(status_code.auth.not_allowed, True) # ################################################################################################################################ # ################################################################################################################################
21,403
Python
.py
367
50.877384
130
0.519845
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,970
user.py
zatosource_zato/code/zato-sso/src/zato/sso/user.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from contextlib import closing from copy import deepcopy from datetime import datetime, timedelta from logging import getLogger from traceback import format_exc from uuid import uuid4 # gevent from gevent.lock import RLock # SQLAlchemy from sqlalchemy import and_ as sql_and, update as sql_update from sqlalchemy.exc import IntegrityError # Zato from zato.common.api import RATE_LIMIT, SEC_DEF_TYPE, TOTP from zato.common.audit import audit_pii from zato.common.crypto.api import CryptoManager from zato.common.crypto.totp_ import TOTPManager from zato.common.exception import BadRequest from zato.common.json_internal import dumps from zato.common.odb.model import SSOLinkedAuth as LinkedAuth, SSOSession as SessionModel, SSOUser as UserModel from zato.sso import const, not_given, status_code, User as UserEntity, ValidationError from zato.sso.attr import AttrAPI from zato.sso.odb.query import get_linked_auth_list, get_sign_up_status_by_token, get_user_by_id, get_user_by_linked_sec, \ get_user_by_name, get_user_by_ust from zato.sso.session import LoginCtx, SessionAPI from zato.sso.user_search import SSOSearch from zato.sso.util import check_credentials, check_remote_app_exists, make_data_secret, make_password_secret, new_confirm_token, \ set_password, validate_password # ################################################################################################################################ if 0: from zato.common.odb.model import SSOSession from zato.common.typing_ import anydict, callable_, callnone from zato.server.base.parallel import ParallelServer from zato.sso.totp_ import TOTPAPI # ################################################################################################################################ logger = getLogger('zato') logger_audit_pii = getLogger('zato_audit_pii') # ################################################################################################################################ linked_auth_supported = SEC_DEF_TYPE.BASIC_AUTH, SEC_DEF_TYPE.JWT # ################################################################################################################################ sso_search = SSOSearch() sso_search.set_up() # ################################################################################################################################ _utcnow = datetime.utcnow LinkedAuthTable = LinkedAuth.__table__ LinkedAuthTableDelete = LinkedAuthTable.delete SessionModelTable = SessionModel.__table__ SessionModelTableDelete = SessionModelTable.delete UserModelTable = UserModel.__table__ UserModelTableDelete = UserModelTable.delete UserModelTableUpdate = UserModelTable.update # ################################################################################################################################ # Attributes accessible to both account owner and super-users regular_attrs = { 'username': None, 'email': b'', 'display_name': '', 'first_name': '', 'middle_name': '', 'last_name': '', 'is_totp_enabled': False, 'totp_label': '', } # Attributes accessible only to super-users super_user_attrs = { 'user_id': None, 'is_active': False, 'is_approval_needed': None, 'is_internal': False, 'is_super_user': False, 'is_locked': True, 'locked_time': None, 'creation_ctx': '', 'locked_by': None, 'approval_status': None, 'approval_status_mod_by': None, 'approval_status_mod_time': None, 'password_expiry': 0, 'password_is_set': False, 'password_must_change': True, 'password_last_set': None, 'sign_up_status': None, 'sign_up_time': None, 'is_rate_limit_active': None, 'rate_limit_def': None, 'rate_limit_type': None, 'rate_limit_check_parent_def': None, } # This can be only changed but never read _write_only = { 'password': None, } # If any of these attributes exists on input to .update, its uppercased counterpart must also be updated _name_attrs = { 'display_name': 'display_name_upper', 'first_name': 'first_name_upper', 'middle_name': 'middle_name_upper', 'last_name': 'last_name_upper' } _all_super_user_attrs = {} _all_super_user_attrs.update(regular_attrs) _all_super_user_attrs.update(super_user_attrs) _all_attrs = deepcopy(_all_super_user_attrs) _all_attrs.update(_write_only) # ################################################################################################################################ _no_such_value = object() # ################################################################################################################################ class update: # Accessible to regular users only regular_attrs = {'username', 'email', 'display_name', 'first_name', 'middle_name', 'last_name', 'is_totp_enabled', 'totp_label'} # Accessible to super-users only super_user_attrs = {'is_locked', 'password_expiry', 'password_must_change', 'sign_up_status', 'approval_status'} # All updateable attributes all_update_attrs = regular_attrs.union(super_user_attrs) # All updateable attributes + user_id all_attrs = all_update_attrs.union({'user_id'}) # There cannot be more than this many attributes on input max_len_attrs = len(all_update_attrs) # All boolean attributes boolean_attrs = ('is_locked', 'password_must_change') # All datetime attributes datetime_attrs = ('password_expiry',) # All attributes that may be set to None / NULL none_allowed = set(regular_attrs) - {'username'} # ################################################################################################################################ class change_password: # Accessible to regular users only regular_attrs = {'old_password', 'new_password'} # Accessible to super-users only super_user_attrs = {'new_password', 'password_expiry', 'password_must_change'} # This is used only for input validation which is why it is not called 'all_update_attrs' all_attrs = regular_attrs.union(super_user_attrs).union({'user_id'}) # There cannot be more than this many attributes on input max_len_attrs = len(all_attrs) # ################################################################################################################################ class Forbidden(Exception): def __init__(self, message='You are not authorized to access this resource'): super(Forbidden, self).__init__(message) # ################################################################################################################################ class User: """ A user entity representing a person in SSO. """ __slots__ = _all_attrs.keys() def __init__(self, **kwargs): for kwarg_name, kwarg_value in kwargs.items(): setattr(self, kwarg_name, kwarg_value) for attr_name, attr_value in _all_attrs.items(): if attr_name not in kwargs: setattr(self, attr_name, attr_value) # ################################################################################################################################ class CreateUserCtx: """ A business object to carry user creation configuration around. """ __slots__ = ('data', 'is_active', 'is_internal', 'is_super_user', 'password_expiry', 'encrypt_password', 'encrypt_email', 'encrypt_func', 'hash_func', 'new_user_id_func', 'confirm_token', 'sign_up_status') def __init__(self, data=None): self.data = data self.is_active = None self.is_internal = None self.is_super_user = None self.password_expiry = None self.encrypt_password = None self.encrypt_email = None self.new_user_id_func = None self.confirm_token = None self.sign_up_status = None # ################################################################################################################################ class UserAPI: """ The main object through SSO users are managed. """ def __init__( self, server, # type: ParallelServer sso_conf, # type: anydict totp, # type: TOTPAPI odb_session_func, # type: callable_ encrypt_func, # type: callable_ decrypt_func, # type: callable_ hash_func, # type: callable_ verify_hash_func, # type: callable_ new_user_id_func, # type: callnone ) -> 'None': self.server = server self.sso_conf = sso_conf self.totp = totp self.odb_session_func = odb_session_func self.is_sqlite = None self.encrypt_func = encrypt_func self.decrypt_func = decrypt_func self.hash_func = hash_func self.verify_hash_func = verify_hash_func self.new_user_id_func = new_user_id_func self.encrypt_email = self.sso_conf.main.encrypt_email self.encrypt_password = self.sso_conf.main.encrypt_password self.password_expiry = self.sso_conf.password.expiry self.lock = RLock() # To look up auth_user_id by auth_username or the other way around self.user_id_auth_type_func = {} self.user_id_auth_type_func_by_id = {} # In-RAM maps of auth IDs to SSO user IDs self.auth_id_link_map = { 'zato.{}'.format(SEC_DEF_TYPE.BASIC_AUTH): {}, 'zato.{}'.format(SEC_DEF_TYPE.JWT): {} } # For convenience, sessions are accessible through user API. self.session = SessionAPI(self.server, self.sso_conf, self.totp, self.encrypt_func, self.decrypt_func, self.hash_func, self.verify_hash_func) # ################################################################################################################################ def post_configure(self, func, is_sqlite, needs_auth_link=True): self.odb_session_func = func self.is_sqlite = is_sqlite self.session.post_configure(func, is_sqlite) if needs_auth_link: # Maps all auth types that SSO users can be linked with to their server definitions self.auth_link_map = { SEC_DEF_TYPE.BASIC_AUTH: self.server.worker_store.request_dispatcher.url_data.basic_auth_config, SEC_DEF_TYPE.JWT: self.server.worker_store.request_dispatcher.url_data.jwt_config, } # This cannot be done in __init__ because it references the worker store self.user_id_auth_type_func[SEC_DEF_TYPE.BASIC_AUTH] = self.server.worker_store.basic_auth_get self.user_id_auth_type_func[SEC_DEF_TYPE.JWT] = self.server.worker_store.jwt_get self.user_id_auth_type_func_by_id[SEC_DEF_TYPE.BASIC_AUTH] = self.server.worker_store.basic_auth_get_by_id self.user_id_auth_type_func_by_id[SEC_DEF_TYPE.JWT] = self.server.worker_store.jwt_get_by_id # Load in initial mappings of SSO users and concrete security definitions with closing(self.odb_session_func()) as session: linked_auth_list = get_linked_auth_list(session) for item in linked_auth_list: # type: LinkedAuth self._add_user_id_to_linked_auth(item.auth_type, item.auth_id, item.user_id) # ################################################################################################################################ def _get_encrypted_email(self, email): email = email or b'' email = email.encode('utf8') if isinstance(email, str) else email return make_data_secret(email, self.encrypt_func) # ################################################################################################################################ def _create_sql_user(self, ctx, _utcnow=_utcnow, _timedelta=timedelta): # Always in UTC now = _utcnow() # Normalize input ctx.data['display_name'] = ctx.data.get('display_name', '').strip() ctx.data['first_name'] = ctx.data.get('first_name', '').strip() ctx.data['middle_name'] = ctx.data.get('middle_name', '').strip() ctx.data['last_name'] = ctx.data.get('last_name', '').strip() # If display_name is given on input, this will be the final value of that attribute .. if ctx.data['display_name']: display_name = ctx.data['display_name'].strip() # .. otherwise, display_name is a concatenation of first, middle and last name. else: display_name = '' if ctx.data['first_name']: display_name += ctx.data['first_name'] display_name += ' ' if ctx.data['middle_name']: display_name += ctx.data['middle_name'] display_name += ' ' if ctx.data['last_name']: display_name += ctx.data['last_name'] display_name = display_name.strip() # If we still don't have any names, turn them all into NULLs for attr_name, attr_name_upper in _name_attrs.items(): if not ctx.data[attr_name]: ctx.data[attr_name] = None ctx.data[attr_name_upper] = None user_model = UserModel() user_model.user_id = ctx.data.get('user_id') or self.new_user_id_func() user_model.is_active = ctx.is_active user_model.is_internal = ctx.is_internal user_model.is_locked = ctx.data.get('is_locked') or False user_model.is_super_user = ctx.is_super_user user_model.creation_ctx = dumps(ctx.data.get('creation_ctx')) # Generate a strong password if one is not given on input .. if not ctx.data.get('password'): ctx.data['password'] = CryptoManager.generate_password() # .. and if it is, make sure it gets past validation. else: self.validate_password(ctx.data['password']) # Passwords must be strong and are always at least hashed and possibly encrypted too .. password = make_password_secret( ctx.data['password'], self.encrypt_password, self.encrypt_func, self.hash_func) # .. take into account the fact that emails are optional too .. email = ctx.data.get('email') # .. emails are only encrypted, and whether to do it is optional .. if email and self.encrypt_email: email = self._get_encrypted_email(email) user_model.username = ctx.data['username'] user_model.email = email user_model.password = password user_model.password_is_set = True user_model.password_last_set = now user_model.password_must_change = ctx.data.get('password_must_change') or False user_model.password_expiry = now + timedelta(days=self.password_expiry) totp_key = ctx.data.get('totp_key') or TOTPManager.generate_totp_key() totp_label = ctx.data.get('totp_label') or TOTP.default_label user_model.is_totp_enabled = ctx.data.get('is_totp_enabled') user_model.totp_key = self.encrypt_func(totp_key.encode('utf8')) user_model.totp_label = self.encrypt_func(totp_label.encode('utf8')) user_model.sign_up_status = ctx.data.get('sign_up_status') user_model.sign_up_time = now user_model.sign_up_confirm_token = ctx.data.get('sign_up_confirm_token') or new_confirm_token() user_model.approval_status = ctx.data['approval_status'] user_model.approval_status_mod_time = now user_model.approval_status_mod_by = ctx.data['approval_status_mod_by'] user_model.display_name = display_name user_model.first_name = ctx.data['first_name'] user_model.middle_name = ctx.data['middle_name'] user_model.last_name = ctx.data['last_name'] user_model.is_rate_limit_active = ctx.data.get('is_rate_limit_active', False) user_model.rate_limit_type = ctx.data.get('rate_limit_type', RATE_LIMIT.TYPE.EXACT.id) user_model.rate_limit_def = ctx.data.get('rate_limit_def') user_model.rate_limit_check_parent_def = ctx.data.get('rate_limit_check_parent_def', False) # Uppercase any and all names for indexing purposes. for attr_name, attr_name_upper in _name_attrs.items(): value = ctx.data[attr_name] if value: setattr(user_model, attr_name_upper, value.upper()) return user_model # ################################################################################################################################ def _require_super_user(self, cid, ust, current_app, remote_addr): """ Raises an exception if either current user session token does not belong to a super user. """ return self._get_current_session(cid, ust, current_app, remote_addr, needs_super_user=True) # ################################################################################################################################ def _create_user(self, ctx, cid, is_super_user, ust=None, current_app=None, remote_addr=None, require_super_user=True, auto_approve=False): """ Creates a new regular or super-user out of initial user data. """ with closing(self.odb_session_func()) as session: if require_super_user: current_session = self._require_super_user(cid, ust, current_app, remote_addr) current_user = current_session.user_id else: current_user = 'auto' ctx.data['approval_status_mod_by'] = current_user if auto_approve: approval_status = const.approval_status.approved else: if self.sso_conf.signup.is_approval_needed: approval_status = const.approval_status.before_decision else: approval_status = const.approval_status.approved ctx.data['approval_status'] = approval_status # The only field always required if not ctx.data.get('username'): logger.warning('Missing `username` on input') raise ValidationError(status_code.username.invalid, True) # Make sure the username is unique if get_user_by_name(session, ctx.data['username'], needs_approved=False): logger.warning('Username `%s` already exists', ctx.data['username']) raise ValidationError(status_code.username.exists, False) ctx.is_active = True ctx.is_internal = False ctx.is_super_user = is_super_user ctx.confirm_token = None if not ctx.data.get('sign_up_status', None): ctx.data['sign_up_status'] = const.signup_status.final user = self._create_sql_user(ctx) # Note that externally visible .id is .user_id on SQL level, # this is on purpose because internally SQL .id is used only for joins. ctx.data['user_id'] = user.user_id ctx.data['display_name'] = user.display_name ctx.data['first_name'] = user.first_name ctx.data['middle_name'] = user.middle_name ctx.data['last_name'] = user.last_name ctx.data['is_active'] = user.is_active ctx.data['is_internal'] = user.is_internal ctx.data['approval_status'] = approval_status ctx.data['approval_status_mod_time'] = user.approval_status_mod_time ctx.data['approval_status_mod_by'] = user.approval_status_mod_by ctx.data['is_approval_needed'] = approval_status != const.approval_status.approved ctx.data['is_locked'] = user.is_locked ctx.data['is_super_user'] = user.is_super_user ctx.data['password_is_set'] = user.password_is_set ctx.data['password_last_set'] = user.password_last_set ctx.data['password_must_change'] = user.password_must_change ctx.data['password_expiry'] = user.password_expiry ctx.data['sign_up_status'] = user.sign_up_status ctx.data['sign_up_time'] = user.sign_up_time ctx.data['is_totp_enabled'] = user.is_totp_enabled ctx.data['totp_label'] = user.totp_label # This one we do not want to reveal back ctx.data.pop('password', None) session.add(user) session.commit() user_id = user.user_id return user_id # ################################################################################################################################ def create_user(self, cid, data, ust=None, current_app=None, remote_addr=None, require_super_user=True, auto_approve=False): """ Creates a new regular user. """ # PII audit comes first audit_pii.info(cid, 'user.create_user', extra={'current_app':current_app, 'remote_addr':remote_addr}) return self._create_user(CreateUserCtx(data), cid, False, ust, current_app, remote_addr, require_super_user, auto_approve) # ################################################################################################################################ def create_super_user(self, cid, data, ust=None, current_app=None, remote_addr=None, require_super_user=True, auto_approve=False): """ Creates a new super-user. """ # PII audit comes first audit_pii.info(cid, 'user.create_super_user', extra={'current_app':current_app, 'remote_addr':remote_addr}) # Super-users don't need to confirmation their own creation data['sign_up_status'] = const.signup_status.final return self._create_user(CreateUserCtx(data), cid, True, ust, current_app, remote_addr, require_super_user, auto_approve) # ################################################################################################################################ def signup(self, cid, ctx, current_app, remote_addr): """ Signs up a user with SSO, assuming that all validation services confirm correctness of input data. On success, invokes callback services interested in the signup process. """ # PII audit comes first audit_pii.info(cid, 'user.signup', extra={'current_app':current_app, 'remote_addr':remote_addr}) # There is no current user so we cannot do more than only confirm that current_app truly exists. self._ensure_app_exists(current_app) # Used to confirm by users that an account should be really opened confirm_token = new_confirm_token() # Neeed in a couple of places below ctx_dict = ctx.to_dict() ctx_dict['sign_up_confirm_token'] = confirm_token for name in self.sso_conf.user_validation.service: validation_response = self.server.invoke(name, ctx_dict, serialize=False) if not validation_response['is_valid']: raise ValidationError(validation_response['sub_status']) # None of validation services returned an error so we can create the user now self.create_user(cid, ctx_dict, current_app=current_app, remote_addr=remote_addr, require_super_user=False) # Invoke all callback services interested in the event of user's signup for name in self.sso_conf.signup.callback_service_list: self.server.invoke(name, ctx_dict) return confirm_token # ################################################################################################################################ def confirm_signup(self, cid, confirm_token, current_app, remote_addr, _utcnow=_utcnow): """ Invoked when users want to confirm their signup with the system. """ # PII audit comes first audit_pii.info(cid, 'user.confirm_signup', extra={'current_app':current_app, 'remote_addr':remote_addr}) # There is no current user so we cannot do more than only confirm that current_app truly exists. self._ensure_app_exists(current_app) with closing(self.odb_session_func()) as session: sign_up_status = get_sign_up_status_by_token(session, confirm_token) # No such token, raise an exception then .. if not sign_up_status: raise ValidationError(status_code.auth.no_such_sign_up_token) # .. cannot confirm signup processes that are not before confirmation .. elif sign_up_status[0] != const.signup_status.before_confirmation: raise ValidationError(status_code.auth.sign_up_confirmed) # .. OK, found a valid token .. else: # .. set signup metadata .. session.execute( UserModelTableUpdate().values({ 'sign_up_status': const.signup_status.final, 'sign_up_confirm_time': _utcnow(), }).where( UserModelTable.c.sign_up_confirm_token==confirm_token )) # .. and commit it to DB. session.commit() # ################################################################################################################################ def get_user_by_username(self, cid, username, needs_approved=True): """ Returns a user object by username or None, if there is no such username. """ # PII audit comes first audit_pii.info(cid, 'user.get_user_by_username', extra={'username':username}) with closing(self.odb_session_func()) as session: return get_user_by_name(session, username, needs_approved=needs_approved) # ################################################################################################################################ def _get_current_session( self, cid, # type: str current_ust, # type: str current_app, # type: str remote_addr, # type: str needs_super_user, # type: bool ) -> 'SSOSession': """ Returns current session info or raises an exception if it could not be found. Optionally, requires that a super-user be owner of current_ust. """ return self.session.get_current_session(cid, current_ust, current_app, remote_addr, needs_super_user) # ################################################################################################################################ def _get_user(self, cid, func, query_criteria, current_ust, current_app, remote_addr, _needs_super_user, queries_current_session, return_all_attrs, _utcnow=_utcnow): """ Returns a user by a specific function and business value. """ with closing(self.odb_session_func()) as session: # Validate and get session current_session = self._get_current_session(cid, current_ust, current_app, remote_addr, _needs_super_user) # If func was to query current session, we can just re-use what we have fetched above, # so as to have one SQL query less in a piece of code that will be likely used very often. if queries_current_session: info = current_session else: info = func(session, query_criteria, _utcnow()) # Input UST is invalid for any reason (perhaps it has just expired), raise an exception in that case if not info: raise ValidationError(status_code.auth.not_allowed, True) # UST is valid, let's return data then else: # Main user entity out = UserEntity() out.is_current_super_user = current_session.is_super_user access_msg = 'Cid:%s. Accessing %s user attrs (s:%d, r:%d).' if current_session.is_super_user or return_all_attrs: logger_audit_pii.info(access_msg, cid, 'all', current_session.is_super_user, return_all_attrs) # This will suffice for 99% of purposes .. attrs = _all_super_user_attrs # .. but to return this, it does not suffice to be a super-user, # .. we need to be requested to do it explicitly via this flag. if return_all_attrs: attrs['totp_key'] = None out.is_approval_needed = self.sso_conf.signup.is_approval_needed else: logger_audit_pii.info(access_msg, cid, 'regular', current_session.is_super_user, return_all_attrs) attrs = regular_attrs for key in attrs: value = getattr(info, key, None) if key == 'is_approval_needed': value = value or False if isinstance(value, datetime): value = value.isoformat() # This will be encrypted .. elif key in ('totp_key', 'totp_label'): value = self.decrypt_func(value) # .. do not return our internal constant if no label has been assign to TOTP. if key == 'totp_label': if value == TOTP.default_label: value = '' setattr(out, key, value) if out.email: if self.sso_conf.main.encrypt_email: try: out.email = self.decrypt_func(out.email) except Exception: logger.warning('Could not decrypt email, user_id:`%s` (%s)', out.user_id, format_exc()) # Custom attributes out.attr = AttrAPI(cid, current_session.user_id, current_session.is_super_user, current_app, remote_addr, self.odb_session_func, self.is_sqlite, self.encrypt_func, self.decrypt_func, info.user_id) return out # ################################################################################################################################ def get_current_user(self, cid, current_ust, current_app, remote_addr, return_all_attrs=False): """ Returns a user object by that person's current UST. """ # PII audit comes first audit_pii.info(cid, 'user.get_current_user', extra={'current_app':current_app, 'remote_addr':remote_addr}) return self._get_user( cid, get_user_by_ust, self.decrypt_func(current_ust), current_ust, current_app, remote_addr, _needs_super_user=False, queries_current_session=True, return_all_attrs=return_all_attrs ) # ################################################################################################################################ def get_user_by_id(self, cid, user_id, current_ust, current_app, remote_addr, return_all_attrs=False): """ Returns a user object by that person's ID. """ # PII audit comes first audit_pii.info(cid, 'user.get_user_by_id', target_user=user_id, extra={'current_app':current_app, 'remote_addr':remote_addr}) return self._get_user(cid, get_user_by_id, user_id, current_ust, current_app, remote_addr, _needs_super_user=True, queries_current_session=False, return_all_attrs=return_all_attrs ) # ################################################################################################################################ def get_user_by_linked_auth(self, cid, sec_type, sec_username, current_ust, current_app, remote_addr, return_all_attrs=False): """ Returns a user object by that person's linked security name, e.g. maps a Basic Auth username to an SSO user. """ # PII audit comes first audit_pii.info(cid, 'user.get_user_by_linked_sec', target_user=sec_username, extra={'current_app':current_app, 'remote_addr':remote_addr, 'sec_type': sec_type}) return self._get_user( cid, get_user_by_linked_sec, (sec_type, sec_username), current_ust, current_app, remote_addr, _needs_super_user=False, queries_current_session=True, return_all_attrs=return_all_attrs ) # ################################################################################################################################ def validate_password(self, password): return validate_password(self.sso_conf, password) # ################################################################################################################################ def _delete_user(self, cid, user_id, username, current_ust, current_app, remote_addr, skip_sec=False): """ Deletes a user by ID or username. """ if not skip_sec: current_session = self._get_current_session(cid, current_ust, current_app, remote_addr, needs_super_user=False) if not current_session.is_super_user: raise ValidationError(status_code.auth.not_allowed, False) if not(user_id or username): raise ValueError('Exactly one of user_id and username is required') else: if user_id and username: raise ValueError('Cannot provide both user_id and username on input') with closing(self.odb_session_func()) as session: # Make sure user_id actually exists .. if user_id: user = get_user_by_id(session, user_id) where = UserModelTable.c.user_id==user_id # .. or use username if this is what was given on input. elif username: user = get_user_by_name(session, username, needs_approved=False) where = UserModelTable.c.username==username user_id = user.user_id # Make sure the user exists at all if not user: raise ValidationError(status_code.common.invalid_operation, False) # Users cannot delete themselves if not skip_sec: if user_id == current_session.user_id: raise ValidationError(status_code.common.invalid_operation, False) rows_matched = session.execute( UserModelTableDelete().\ where(where) ).rowcount session.commit() if rows_matched != 1: msg = 'Expected for rows_matched to be 1 instead of %d, user_id:`%s`, username:`%s`' logger.warning(msg, rows_matched, user_id, username) # After deleting the user from ODB, we can remove a reference to this account # from the map of linked accounts. for auth_id_link_map in self.auth_id_link_map.values(): # type: dict to_delete = set() for sso_user_id in auth_id_link_map.values(): if user_id == sso_user_id: to_delete.add(user_id) for user_id in to_delete: del auth_id_link_map[user_id] # ################################################################################################################################ def delete_user_by_id(self, cid, user_id, current_ust, current_app, remote_addr, skip_sec=False): """ Deletes a user by that person's ID. """ # PII audit comes first audit_pii.info(cid, 'user.delete_user_by_id', target_user=user_id, extra={'current_app':current_app, 'remote_addr':remote_addr}) return self._delete_user(cid, user_id, None, current_ust, current_app, remote_addr, skip_sec) # ################################################################################################################################ def delete_user_by_username(self, cid, username, current_ust, current_app, remote_addr, skip_sec=False): """ Deletes a user by that person's username. """ # PII audit comes first audit_pii.info(cid, 'user.delete_user_by_username', extra={'current_app':current_app, 'remote_addr':remote_addr}) return self._delete_user(cid, None, username, current_ust, current_app, remote_addr, skip_sec) # ################################################################################################################################ def lock_user(self, cid, user_id, current_ust=None, current_app=None, remote_addr=None, require_super_user=True, current_user=None): """ Locks an existing user. It is acceptable to lock an already lock user. """ # type: (str, str, str, str, str, bool, str) # PII audit comes first audit_pii.info(cid, 'user.lock_user', extra={'current_app':current_app, 'remote_addr':remote_addr}) return self._lock_user(user_id, True, cid, current_ust, current_app, remote_addr, require_super_user, current_user) # ################################################################################################################################ def unlock_user(self, cid, user_id, current_ust=None, current_app=None, remote_addr=None, require_super_user=True, current_user=None): """ Unlocks an existing user. It is acceptable to unlock a user that is not locked. """ # type: (str, str, str, str, str, bool, str) # PII audit comes first audit_pii.info(cid, 'user.lock_user', extra={'current_app':current_app, 'remote_addr':remote_addr}) return self._lock_user(user_id, False, cid, current_ust, current_app, remote_addr, require_super_user, current_user) # ################################################################################################################################ def _lock_user(self, user_id, is_locked, cid=None, current_ust=None, current_app=None, remote_addr=None, require_super_user=True, current_user=None): """ An internal method to lock or unlock users. """ # type: (str, bool, str, str, str, str, bool, str) if require_super_user: current_session = self._require_super_user(cid, current_ust, current_app, remote_addr) current_user = current_session.user_id else: current_user = current_user if current_user else 'auto' # We have all that is needed to so we can actually issue the SQL call. # Note that we always populate locked_time and locked_by even if is_locked is False # to keep track of both who locked and unlocked the user. with closing(self.odb_session_func()) as session: session.execute( sql_update(UserModelTable).\ values({ 'is_locked': is_locked, 'locked_time': datetime.utcnow(), 'locked_by': current_user, }).\ where(UserModelTable.c.user_id==user_id) ) session.commit() # ################################################################################################################################ def login(self, cid, username, password, current_app, remote_addr, user_agent=None, has_remote_addr=False, has_user_agent=False, new_password='', totp_code=None, skip_sec=False): """ Logs a user in if username and password are correct, returning a user session token (UST) on success, or a ValidationError on error. """ # PII audit comes first audit_pii.info(cid, 'user.login', target_user=username, extra={ 'current_app': current_app, 'remote_addr': remote_addr, 'user_agent': user_agent, 'new_password': bool(new_password) # To store information if a new password was sent or not }) ctx_input = { 'username': username, 'password': password, 'current_app': current_app, 'new_password': new_password, 'totp_code': totp_code, } login_ctx = LoginCtx(cid, remote_addr, user_agent, ctx_input) return self.session.login(login_ctx, is_logged_in_ext=False, skip_sec=skip_sec) # ################################################################################################################################ def logout(self, cid, ust, current_app, remote_addr, skip_sec=False): """ Logs a user out of SSO. """ # PII audit comes first audit_pii.info(cid, 'user.logout', extra={'current_app':current_app, 'remote_addr':remote_addr}) return self.session.logout(ust, current_app, remote_addr, skip_sec=skip_sec) # ################################################################################################################################ def _ensure_app_exists(self, app): """ Raises an exception if input does not exist in SSO configuration. """ check_remote_app_exists(app, self.sso_conf.apps.all, logger) # ################################################################################################################################ def _ensure_no_unknown_update_attrs(self, attrs_allowed, data): """ Makes sure that update data contains only attributes explicitly allowed. """ unexpected = [] for attr in data: if attr not in attrs_allowed: unexpected.append(attr) if unexpected: logger.warning('Unexpected data on input %s', unexpected) raise ValidationError(status_code.common.invalid_input, False) # ################################################################################################################################ def _check_basic_update_attrs(self, data, max_len_attrs, all_update_attrs): """ Checks basic validity of user attributes that are about to be changed. """ # Double-check we have data to update a user with .. if not data: raise ValidationError(status_code.common.missing_input, False) else: # .. and that no one attempts to overload us with it .. if len(data) > max_len_attrs: logger.warning('Too many data arguments %d > %d', len(data), max_len_attrs) raise ValidationError(status_code.common.invalid_input, False) # .. also, make sure that, no matter what kind of user this is, only supported arguments are given on input. # Later on we will fine-check it again to take the user's role into account, but we want to want to check it here # first on a rough level so as to avoid an SQL query in case of an error at this early stage. else: self._ensure_no_unknown_update_attrs(all_update_attrs, data) # ################################################################################################################################ def _update_user(self, cid, data, current_ust, current_app, remote_addr, user_id=None, update_self=None): """ Low-level implementation of user updates. """ if not(user_id or update_self): logger.warning('At least one of user_id or update_self is required') raise ValidationError(status_code.common.invalid_input, False) # Basic checks first self._check_basic_update_attrs(data, update.max_len_attrs, update.all_update_attrs) with closing(self.odb_session_func()) as session: current_session = self._get_current_session(cid, current_ust, current_app, remote_addr, needs_super_user=False) # We will be updating our own account or another user, depending on input flags/parameters. _user_id = current_session.user_id if update_self else user_id # Super-users may update the whole set of attributes in existence. if current_session.is_super_user: attrs_allowed = update.all_update_attrs else: # If current session belongs to a regular user yet a user_id was given on input, # we may not continue because only super-users may update other users if user_id and user_id != current_session.user_id: logger.warning('Current user `%s` is not a super-user, cannot update user `%s`', current_session.user_id, user_id) raise ValidationError(status_code.common.invalid_input, False) # Regular users may change only basic attributes attrs_allowed = update.regular_attrs # Make sure current user provided only these attributes that have been explicitly allowed self._ensure_no_unknown_update_attrs(attrs_allowed, data) # If username is to be changed, we need to ensure that such a username is not used by another user username = data.get('username') # type: str # We have a username in put .. if username: # .. now, we can check whether that username is already in use .. existing_user = get_user_by_name(session, username, False) # type: UserModel # .. if it does .. if existing_user: # .. and if the other user is not the same that we are editing .. if existing_user.user_id != _user_id: # .. we need to reject the new username. logger.warning('Username `%s` already exists (update)',username) raise ValidationError(status_code.username.exists, False) # If sign_up_status was given on input, it must be among allowed values sign_up_status = data.get('sign_up_status') if sign_up_status and sign_up_status not in const.signup_status(): logger.warning('Invalid sign_up_status `%s`', sign_up_status) raise ValidationError(status_code.common.invalid_input, False) # All booleans must be actually booleans for attr in update.boolean_attrs: value = data.get(attr, _no_such_value) if value is not _no_such_value: if not isinstance(value, bool): logger.warning('Expected for `%s` to be a boolean instead of `%r` (%s)', attr, value, type(value)) raise ValidationError(status_code.common.invalid_input, False) # All datetime objects must be actual Python datetime objects for attr in update.datetime_attrs: value = data.get(attr, _no_such_value) if value is not _no_such_value: if not isinstance(value, datetime): logger.warning('Expected for `%s` to be a datetime instead of `%r` (%s)', attr, value, type(value)) raise ValidationError(status_code.common.invalid_input, False) # Only certain attributes may be set to None / NULL for key, value in data.items(): if value is None: if key not in update.none_allowed: logger.warning('Key `%s` must not be None', key) raise ValidationError(status_code.common.invalid_input, False) # If approval_status is on input, it must be of correct value # and if it is, its related attributes need to bet set along with it. if 'approval_status' in data: value = data['approval_status'] if value not in const.approval_status(): logger.warning('Invalid approval_status `%s`', value) raise ValidationError(status_code.common.invalid_input, False) else: data['approval_status_mod_by'] = current_session.user_id data['approval_status_mod_time'] = _utcnow() # Uppercase or remove attributes that are later on used for search for attr_name, attr_name_upper in _name_attrs.items(): if attr_name in data: if attr_name is None: data[attr_name_upper] = None else: if attr_name and isinstance(data[attr_name], str): data[attr_name_upper] = data[attr_name].upper() # Email may be optionally encrypted if self.encrypt_email: email = data.get('email') if email: data['email'] = self._get_encrypted_email(email) # Everything is validated - we can save the data now with closing(self.odb_session_func()) as session: session.execute( sql_update(UserModelTable).\ values(data).\ where(UserModelTable.c.user_id==_user_id) ) session.commit() # ################################################################################################################################ def update_current_user(self, cid, data, current_ust, current_app, remote_addr): """ Updates current user as identified by current_ust. """ # PII audit comes first audit_pii.info(cid, 'user.update_current_user', extra={'current_app':current_app, 'remote_addr':remote_addr}) return self._update_user(cid, data, current_ust, current_app, remote_addr, update_self=True) # ################################################################################################################################ def update_user_by_id(self, cid, user_id, data, current_ust, current_app, remote_addr): """ Updates current user as identified by ID. """ # PII audit comes first audit_pii.info(cid, 'user.update_user_by_id', target_user=user_id, extra={'current_app':current_app, 'remote_addr':remote_addr}) return self._update_user(cid, data, current_ust, current_app, remote_addr, user_id=user_id) # ################################################################################################################################ def set_password(self, cid, user_id, password, must_change, password_expiry, current_app, remote_addr, details=None): """ Sets a new password for user. """ # PII audit comes first extra = {'current_app':current_app, 'remote_addr':remote_addr} if details: extra.update(details) audit_pii.info(cid, 'user.set_password', target_user=user_id, extra=extra) set_password(self.odb_session_func, self.encrypt_func, self.hash_func, self.sso_conf, user_id, password, must_change, password_expiry) # ################################################################################################################################ def reset_totp_key(self, cid, current_ust, user_id, key, key_label, current_app, remote_addr, skip_sec=False): """ Saves a new TOTP key for user, either using the one provided on input or a newly generated one. In the latter case, it is also returned on output. """ # PII audit comes first audit_pii.info(cid, 'user.reset_totp_key', target_user=user_id, extra={ 'current_app': current_app, 'remote_addr': remote_addr, 'skip_sec': skip_sec, 'user_id': user_id, }) key = key or CryptoManager.generate_totp_key() key_label = key_label or TOTP.default_label # Flag skip_sec will be True if we are being called from CLI, # in which case we are allowed to set the key for any user. # Otherwise, regular users may change their own keys only # while super-users may change any other user's key. if skip_sec: _user_id = user_id else: # Get current session by its UST .. current_session = self._get_current_session(cid, current_ust, current_app, remote_addr, needs_super_user=False) # .. if user_id is given, reject the request if it does not belong to a super-user .. if user_id: # A non-super-user tries to reset TOTP key of another user if not current_session.is_super_user: logger.warning('Current user `%s` is not a super-user, cannot reset TOTP key for user `%s`', current_session.user_id, user_id) raise ValidationError(status_code.common.invalid_input, False) # This is good, it is a super-user resetting the TOTP key else: # We need to confirm that such a user exists if not self.get_user_by_id(cid, user_id, current_ust, current_app, remote_addr): logger.warning('No such user `%s`', user_id) raise ValidationError(status_code.common.invalid_input, False) # Input user actually exists else: _user_id = user_id # .. no user_id given on input, which means we reset the current user's TOTP key else: _user_id = current_session.user_id # Data to be saved comprises the TOTP key in an encrypted form # along with its label, alco encrypted. data = { 'totp_key': self.encrypt_func(key.encode('utf8')), 'totp_label': self.encrypt_func(key_label.encode('utf8')), } # Everything is ready - we can save the data now with closing(self.odb_session_func()) as session: session.execute( sql_update(UserModelTable).\ values(data).\ where(UserModelTable.c.user_id==_user_id) ) session.commit() return key # ################################################################################################################################ def change_password(self, cid, data, current_ust, current_app, remote_addr, _no_user_id='no-user-id.{}'.format(uuid4().hex)): """ Changes a user's password. Super-admins may also set its expiration and whether the user must set it to a new one on next login. """ # Basic checks first self._check_basic_update_attrs(data, change_password.max_len_attrs, change_password.all_attrs) # Get current user's session .. current_session = self._get_current_session(cid, current_ust, current_app, remote_addr, needs_super_user=False) # . only super-users may send user_id on input .. user_id = data.get('user_id', _no_user_id) # PII audit goes here, once we know the target user's ID audit_pii.info( cid, 'user.change_password', target_user=user_id, extra={'current_app':current_app, 'remote_addr':remote_addr}) # .. so if it is sent .. if user_id != _no_user_id: # .. and we are not changing our own password .. if current_session.user_id != user_id: # .. we must confirm we have a super-user's session. if not current_session.is_super_user: logger.warning('Current user `%s` is not a super-user, cannot change password for user `%s`', current_session.user_id, user_id) raise ValidationError(status_code.common.invalid_input, False) # .. if ID is not given on input, we change current user's password. else: user_id = current_session.user_id # If current user is a super-user we can just set the new password immediately .. if current_session.is_super_user: # .. but only if the user changes another user's password .. if current_session.user_id != user_id: self.set_password(cid, user_id, data['new_password'], data.get('must_change'), data.get('password_expiry'), current_app, remote_addr) # All done, another user's password has been changed return # .. otherwise, if we are a regular user or a super-user changing his or her own password, # so we must check first if the old password is correct. if not check_credentials(self.decrypt_func, self.verify_hash_func, current_session.password, data['old_password']): logger.warning('Password verification failed, user_id:`%s`', current_session.user_id) raise ValidationError(status_code.auth.not_allowed, True) else: # At this point we know that the user provided a correct old password so we are free to set the new one .. # .. but we still need to consider regular vs. super-users and make sure that the former does not # provide attributes that only the latter may use. # Super-users may provide these optionally .. if current_session.is_super_user: must_change = data.get('must_change') password_expiry = data.get('password_expiry') # .. but regular ones never. else: must_change = None password_expiry = None # All done, we can set the new password now. try: self.set_password(cid, user_id, data['new_password'], must_change, password_expiry, current_app, remote_addr) except Exception: logger.warning('Could not set a new password for user_id:`%s`, e:`%s`', current_session.user_id, format_exc()) raise ValidationError(status_code.auth.not_allowed, True) # ################################################################################################################################ def _change_approval_status(self, cid, user_id, new_value, current_ust, current_app, remote_addr): """ Changes a given user's approval_status to 'value'. """ return self._update_user(cid, {'approval_status': new_value}, current_ust, current_app, remote_addr, user_id=user_id) # ################################################################################################################################ def approve_user(self, cid, user_id, current_ust, current_app, remote_addr): """ Changes a user's approval_status to 'approved'. Must be called with a UST pointing to a super-user. """ # PII audit comes first audit_pii.info(cid, 'user.approve_user', target_user=user_id, extra={'current_app':current_app, 'remote_addr':remote_addr}) return self._change_approval_status(cid, user_id, const.approval_status.approved, current_ust, current_app, remote_addr) # ################################################################################################################################ def reject_user(self, cid, user_id, current_ust, current_app, remote_addr): """ Changes a user's approval_status to 'approved'. Must be called with a UST pointing to a super-user. """ # PII audit comes first audit_pii.info(cid, 'user.reject_user', target_user=user_id, extra={'current_app':current_app, 'remote_addr':remote_addr}) return self._change_approval_status(cid, user_id, const.approval_status.rejected, current_ust, current_app, remote_addr) # ################################################################################################################################ def get_linked_auth_list(self, cid, ust, current_app, remote_addr, user_id=None): """ Returns a list of linked auth accounts for input user, either current or another one. """ # PII audit comes first audit_pii.info(cid, 'user.get_linked_auth_list', extra={'current_app':current_app, 'remote_addr':remote_addr}) # Get current user, which may be possibly the one that we will return accounts for user = self.get_current_user(cid, ust, current_app, remote_addr) # We are to return linked accounts for another user .. if user_id: # .. in which case this will raise an exception if current caller is not a super-user self._require_super_user(cid, ust, current_app, remote_addr) else: # No user_id given on input = we need to get accounts for current one user_id = user.user_id try: with closing(self.odb_session_func()) as session: out = [] auth_list = get_linked_auth_list(session, user_id) for item in auth_list: item = item._asdict() item['auth_type'] = item['auth_type'].replace('zato.', '', 1) auth_func = self.user_id_auth_type_func_by_id[item['auth_type']] auth_config = auth_func(item['auth_id']) auth_username = auth_config['username'] item['auth_username'] = auth_username out.append(item) return out except Exception: logger.warning('Could not return linked accounts, e:`%s`', format_exc()) # ################################################################################################################################ def _check_linked_auth_call(self, call_name, cid, ust, user_id, auth_type, auth_id, current_app, remote_addr, _linked_auth_supported=linked_auth_supported): # PII audit comes first audit_pii.info(cid, call_name, extra={'current_app':current_app, 'remote_addr':remote_addr}) # Only super-users may link auth accounts self._require_super_user(cid, ust, current_app, remote_addr) if auth_type not in self.auth_link_map: raise ValueError('Invalid auth_type:`{}`'.format(auth_type)) for item in self.auth_link_map[auth_type].values(): # type: dict config = item['config'] if config['id'] == auth_id: break else: raise ValueError('Invalid auth_id:`{}`'.format(auth_id)) # ################################################################################################################################ def _get_auth_username_by_id(self, cid, auth_type, auth_username, _linked_auth_supported=linked_auth_supported): # Confirm that input auth_type if of the allowed type if auth_type not in _linked_auth_supported: raise BadRequest(cid, 'Invalid auth_type `{}`'.format(auth_type)) # Input auth_username is the linked account's username # and we need to translate it into its underlying auth_id # which is what the SSO API expects. func = self.user_id_auth_type_func[auth_type] auth_config = func(auth_username) if not auth_config: raise BadRequest(cid, 'Invalid auth_username ({})'.format(auth_type)) else: auth_user_id = auth_config['config']['id'] return auth_user_id # ################################################################################################################################ def create_linked_auth(self, cid, ust, user_id, auth_type, auth_username, is_active, current_app, remote_addr, _linked_auth_supported=linked_auth_supported): """ Creates a link between input user and a security account. """ # Convert auth_username to auth_id, if it exists auth_id = self._get_auth_username_by_id(cid, auth_type, auth_username) # Validate input self._check_linked_auth_call('user.create_linked_auth', cid, ust, user_id, auth_type, auth_id, current_app, remote_addr) # We have validated everything and a link can be saved to the database now now = datetime.utcnow() auth_type = 'zato.{}'.format(auth_type) with closing(self.odb_session_func()) as session: instance = LinkedAuth() instance.auth_id = auth_id instance.auth_type = auth_type instance.creation_time = now instance.last_modified = now instance.is_internal = False instance.is_active = is_active instance.user_id = user_id # Reserved for future use instance.has_ext_principal = False instance.auth_principal = 'reserved' instance.auth_source = 'reserved' session.add(instance) try: session.commit() except IntegrityError: logger.warning('Could not add auth link e:`%s`', format_exc()) raise ValueError('Auth link could not be added') else: self._add_user_id_to_linked_auth(auth_type, auth_id, user_id) return instance.user_id, auth_id # ################################################################################################################################ def delete_linked_auth(self, cid, ust, user_id, auth_type, auth_username, current_app, remote_addr, _linked_auth_supported=linked_auth_supported): """ Creates a link between input user and a security account. """ # Convert auth_username to auth_id, if it exists auth_id = self._get_auth_username_by_id(cid, auth_type, auth_username) # Validate input self._check_linked_auth_call('user.delete_linked_auth', cid, ust, user_id, auth_type, auth_id, current_app, remote_addr) # All internal auth types have this prefix zato_auth_type = 'zato.{}'.format(auth_type) with closing(self.odb_session_func()) as session: # First, confirm that such a mapping exists at all .. existing = session.query(LinkedAuth).\ filter(LinkedAuth.auth_type==zato_auth_type).\ filter(LinkedAuth.auth_id==auth_id).\ filter(LinkedAuth.user_id==user_id).\ first() if not existing: raise ValueError('No such auth link found') # .. delete it now, knowing that it does .. session.execute(LinkedAuthTableDelete().\ where(sql_and( LinkedAuthTable.c.auth_type==zato_auth_type, LinkedAuthTable.c.auth_id==auth_id, LinkedAuthTable.c.user_id==user_id, )) ) # .. delete any sessions possibly existing for this link .. session.execute(SessionModelTableDelete().\ where(sql_and( SessionModelTable.c.ext_session_id.startswith('{}.{}'.format(auth_type, auth_id)), )) ) session.commit() return auth_id # ################################################################################################################################ def _add_user_id_to_linked_auth(self, auth_type, auth_id, user_id): self.auth_id_link_map[auth_type].setdefault(auth_id, user_id) # ################################################################################################################################ def on_broker_msg_SSO_LINK_AUTH_CREATE(self, auth_type, auth_id, user_id): with self.lock: self._add_user_id_to_linked_auth(auth_type, auth_id, user_id) # ################################################################################################################################ def on_broker_msg_SSO_LINK_AUTH_DELETE(self, auth_type, auth_id): auth_type = 'zato.{}'.format(auth_type) with self.lock: auth_id_link_map = self.auth_id_link_map[auth_type] try: del auth_id_link_map[auth_id] except KeyError: # It is fine, the user had not linked accounts pass # ################################################################################################################################ def _on_broker_msg_sec_delete(self, sec_type, auth_id): auth_id_link_map = self.auth_id_link_map['zato.{}'.format(sec_type)] try: del auth_id_link_map[auth_id] except KeyError: # It is fine, the account had no associated SSO users pass # ################################################################################################################################ def on_broker_msg_SECURITY_BASIC_AUTH_DELETE(self, auth_id): with self.lock: self._on_broker_msg_sec_delete(SEC_DEF_TYPE.BASIC_AUTH, auth_id) # ################################################################################################################################ def on_broker_msg_SECURITY_JWT_DELETE(self, auth_id): with self.lock: self._on_broker_msg_sec_delete(SEC_DEF_TYPE.JWT, auth_id) # ################################################################################################################################ def search(self, cid, ctx, current_ust, current_app, remote_addr, serialize_dt=False, _all_super_user_attrs=_all_super_user_attrs, _dt=('sign_up_time', 'password_expiry', 'approv_rej_time', 'locked_time', 'approval_status_mod_time')): """ Looks up users by specific search criteria from the SearchCtx ctx object. Must be called with a UST belonging to a super-user. """ # PII audit comes first audit_pii.info(cid, 'user.search', extra={'current_app':current_app, 'remote_addr':remote_addr}) # Will raise an exception if current user is not an admin current_session = self._get_current_session(cid, current_ust, current_app, remote_addr, needs_super_user=True) if ctx.cur_page < 1: ctx.cur_page = 1 if (not ctx.page_size) or (ctx.page_size < 1): ctx.page_size = self.sso_conf.search.default_page_size elif ctx.page_size > self.sso_conf.search.max_page_size: ctx.page_size = self.sso_conf.search.max_page_size # Local alias, useful in decryption of emails later on is_email_encrypted = self.sso_conf.main.encrypt_email config = { 'paginate': ctx.paginate, 'page_size': ctx.page_size, 'cur_page': ctx.cur_page, 'email_search_enabled': not is_email_encrypted, 'name_op': ctx.name_op, 'is_name_exact': ctx.is_name_exact, } # User ID has priority over everything .. if ctx.user_id is not not_given: config['user_id'] = ctx.user_id # .. followed up by username .. elif ctx.username is not not_given: config['username'] = ctx.username # .. and only then goes everything else. else: for name in SSOSearch.name_columns: value = getattr(ctx, name) if value is not not_given: name_key = config.setdefault('name', {}) name_key[name] = value for name in SSOSearch.non_name_column_op: value = getattr(ctx, name) if value is not not_given: config[name] = value with closing(self.odb_session_func()) as session: # Output dictionary with all the data found, if any, along with pagination metadata out = { 'total': None, 'num_pages': None, 'page_size': None, 'cur_page': None, 'has_next_page': None, 'has_prev_page': None, 'next_page': None, 'prev_page': None, 'result': [] } # Get data from SQL .. sql_result = sso_search.search(session, config) # .. attach metadata .. out['total'] = sql_result.total out['num_pages'] = sql_result.num_pages out['page_size'] = sql_result.page_size out['cur_page'] = sql_result.cur_page out['has_next_page'] = sql_result.has_next_page out['has_prev_page'] = sql_result.has_prev_page out['next_page'] = sql_result.next_page out['prev_page'] = sql_result.prev_page # .. and append any data found. for sql_item in sql_result.result: sql_item = sql_item._asdict() # Main user entity item = UserEntity() # Custom attributes item.attr = AttrAPI(cid, current_session.user_id, current_session.is_super_user, current_app, remote_addr, self.odb_session_func, self.is_sqlite, self.encrypt_func, self.decrypt_func, sql_item['user_id']) # Write out all super-user accessible attributes for each output row for name in sorted(_all_super_user_attrs): value = sql_item.get(name) # Serialize datetime objects to string, if needed if serialize_dt and isinstance(value, datetime): value = value.isoformat() # Decrypt email, if needed if name == 'email': if is_email_encrypted: value = self.decrypt_func(value) setattr(item, name, value) out['result'].append(item.to_dict()) return out # ################################################################################################################################
74,080
Python
.py
1,256
47.725318
130
0.543765
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,971
attr.py
zatosource_zato/code/zato-sso/src/zato/sso/attr.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from contextlib import closing from datetime import datetime, timedelta from logging import getLogger from traceback import format_exc # SQLAlchemy from sqlalchemy import and_ from sqlalchemy.exc import IntegrityError # Python 2/3 compatibility from zato.common.py23_.past.builtins import basestring # Zato from zato.common.audit import audit_pii from zato.common.json_internal import dumps, loads from zato.common.odb.model import SSOAttr as AttrModel, SSOSession from zato.sso import status_code, ValidationError # ################################################################################################################################ logger = getLogger(__name__) # ################################################################################################################################ _utcnow = datetime.utcnow _default_expiration = datetime(year=9999, month=12, day=31) AttrModelTable = AttrModel.__table__ AttrModelTableDelete = AttrModelTable.delete AttrModelTableUpdate = AttrModelTable.update SSOSessionTable = SSOSession.__table__ # ################################################################################################################################ class AttrEntity: """ Holds information about a particular attribute. """ __slots__ = ('name', 'value', 'creation_time', 'last_modified', 'expiration_time', 'is_encrypted', '_is_session_attr') def __init__(self, name, value, creation_time, last_modified, expiration_time, is_encrypted, _is_session_attr): self.name = name self.value = value self.creation_time = creation_time self.last_modified = last_modified self.expiration_time = expiration_time self.is_encrypted = is_encrypted self._is_session_attr = _is_session_attr # ################################################################################################################################ def to_dict(self): """ Serializes this attribute to a Python dictionary. """ # Note that we do not serialize _is_session_attr - this is internal only return { 'name': self.name, 'value': self.value, 'creation_time': self.creation_time, 'last_modified': self.last_modified, 'expiration_time': self.expiration_time, 'is_encrypted': self.is_encrypted, } # ################################################################################################################################ @staticmethod def from_sql(item, needs_decrypt, decrypt_func, serialize_dt): """ Builds a new AttrEntity out of an SQL row. """ return AttrEntity(item.name, decrypt_func(loads(item.value)) if (needs_decrypt and item.is_encrypted) else loads(item.value), item.creation_time.isoformat() if serialize_dt else item.creation_time, item.last_modified.isoformat() if serialize_dt else item.last_modified, item.expiration_time.isoformat() if serialize_dt else item.expiration_time, item.is_encrypted, item.is_session_attr) # ################################################################################################################################ class AttrAPI: """ A base class for both user and session SSO attributes. """ def __init__(self, cid, current_user_id, is_super_user, current_app, remote_addr, odb_session_func, is_sqlite, encrypt_func, decrypt_func, user_id, ust=None): self.cid = cid self.current_user_id = current_user_id self.is_super_user = is_super_user self.current_app = current_app self.remote_addr = remote_addr self.odb_session_func = odb_session_func self.is_sqlite = is_sqlite self.encrypt_func = encrypt_func self.decrypt_func = decrypt_func self.user_id = user_id self.ust = ust self.is_session_attr = bool(ust) # ################################################################################################################################ def _require_correct_user(self, op, target_user_id): """ Makes sure that during current operation self.current_user_id is the same as target_user_id (which means that a person accesses his or her own attribute) or that current operation is performed by a super-user. """ if self.is_super_user or self.current_user_id == target_user_id: result = status_code.ok log_func = audit_pii.info else: result = status_code.error log_func = audit_pii.warn log_func(self.cid, '_require_correct_user', self.current_user_id, target_user_id, result, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr, 'op':op, 'is_super_user':self.is_super_user}) if result != status_code.ok: raise ValidationError(status_code.auth.not_allowed) # ################################################################################################################################ def _ensure_ust_is_not_expired(self, session, ust, now): return session.query(SSOSessionTable.c.ust).\ filter(SSOSessionTable.c.ust==ust).\ filter(SSOSessionTable.c.expiration_time > now).\ first() # ################################################################################################################################ def _create(self, session, name, value, expiration=None, encrypt=False, user_id=None, needs_commit=True, _utcnow=_utcnow): """ A low-level implementation of self.create which expects an SQL session on input. """ # Audit comes first audit_pii.info(self.cid, 'attr._create', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr, 'name':name, 'expiration':expiration, 'encrypt':encrypt, 'is_super_user':self.is_super_user}) # Default to current user unless overridden on input user_id = user_id or self.user_id self._require_correct_user('_create', user_id) now = _utcnow() attr_model = AttrModel() attr_model.user_id = user_id attr_model.ust = self.ust attr_model._ust_string = self.ust or '' # Cannot, and will not be, NULL, check the comment in the model for details attr_model.is_session_attr = self.is_session_attr attr_model.name = name attr_model.value = dumps(self.encrypt_func(value.encode('utf8')) if encrypt else value) attr_model.is_encrypted = encrypt attr_model.creation_time = now attr_model.last_modified = now # Expiration is optional attr_model.expiration_time = now + timedelta(seconds=expiration) if expiration else _default_expiration session.add(attr_model) if needs_commit: session.commit() # ################################################################################################################################ def create(self, name, value, expiration=None, encrypt=False, user_id=None): """ Creates a new named attribute, raising an exception if it already exists. """ # Audit comes first audit_pii.info(self.cid, 'attr.create', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('create', user_id) with closing(self.odb_session_func()) as session: try: return self._create(session, name, value, expiration, encrypt, user_id) except IntegrityError: logger.warning(format_exc()) raise ValidationError(status_code.attr.already_exists) # ################################################################################################################################ def _set(self, session, name, value, expiration=None, encrypt=False, user_id=None, needs_commit=True): """ A low-level implementation of self.set which expects an SQL session on input. """ # Audit comes first audit_pii.info(self.cid, 'attr._set', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr, 'name':name, 'expiration':expiration, 'encrypt':encrypt, 'is_super_user':self.is_super_user}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('_set', user_id) # Check if the attribute exists .. if self._exists(session, name, user_id): # .. it does, so we need to set its new value. self._update(session, name, value, expiration, encrypt, user_id, needs_commit) # .. does not exist, so we need to create it else: self._create(session, name, value, expiration, encrypt, user_id, needs_commit) # ################################################################################################################################ def set(self, name, value, expiration=None, encrypt=False, user_id=None): """ Set value of a named attribute, creating it if it does not already exist. """ # Audit comes first audit_pii.info(self.cid, 'attr.set', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('set', user_id) with closing(self.odb_session_func()) as session: self._set(session, name, value, expiration, encrypt) # ################################################################################################################################ def _update(self, session, name, value=None, expiration=None, encrypt=False, user_id=None, needs_commit=True, _utcnow=_utcnow): """ A low-level implementation of self.update which expects an SQL session on input. """ # Audit comes first audit_pii.info(self.cid, 'attr._update', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr, 'name':name, 'expiration':expiration, 'encrypt':encrypt, 'is_super_user':self.is_super_user}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('_update', user_id) now = _utcnow() values = { 'last_modified': now } if value: values['value'] = dumps(self.encrypt_func(value.encode('utf8')) if encrypt else value) if expiration: values['expiration_time'] = now + timedelta(seconds=expiration) and_condition = [ AttrModelTable.c.user_id==(user_id), AttrModelTable.c.ust==self.ust, AttrModelTable.c.name==name, AttrModelTable.c.expiration_time > now, ] if self.ust: # SQLite needs to be treated in a special way, otherwise we get an exception from SQLAlchemy # NotImplementedError: This backend does not support multiple-table criteria within UPDATE # which means that on SQLite we need an additional query. if self.is_sqlite: result = self._ensure_ust_is_not_expired(session, self.ust, now) if not result: raise ValidationError(status_code.session.no_such_session) else: and_condition.extend([ AttrModelTable.c.ust==SSOSessionTable.c.ust, SSOSessionTable.c.expiration_time > now ]) session.execute( AttrModelTableUpdate().\ values(values).\ where(and_(*and_condition))) if needs_commit: session.commit() # ################################################################################################################################ def update(self, name, value, expiration=None, encrypt=False, user_id=None): """ Updates an existing attribute, raising an exception if it does not already exist. """ # Audit comes first audit_pii.info(self.cid, 'attr.update', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('update', user_id) with closing(self.odb_session_func()) as session: return self._update(session, name, value, expiration, encrypt, user_id) # ################################################################################################################################ def _get(self, session, data, decrypt, serialize_dt, user_id=None, columns=AttrModel, exists_only=False, _utcnow=_utcnow): """ A low-level implementation of self.get which knows how to return one or more named attributes. """ # Audit comes first audit_pii.info(self.cid, 'attr._get', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr, 'data':data, 'is_super_user':self.is_super_user}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('_get', user_id) data = [data] if isinstance(data, basestring) else data out = dict.fromkeys(data, None) now = _utcnow() q = session.query(columns).\ filter(AttrModel.user_id==(user_id)).\ filter(AttrModel.ust==self.ust).\ filter(AttrModel.name.in_(data)).\ filter(AttrModel.expiration_time > now) if self.ust: q = q.\ filter(AttrModel.ust==SSOSession.ust).\ filter(SSOSession.expiration_time > now) result = q.all() for item in result: out[item.name] = True if exists_only else AttrEntity.from_sql(item, decrypt, self.decrypt_func, serialize_dt) # Explicitly convert None to False to satisfy the requirement of returning a boolean value # if we are being called from self.exist (otherwise, None is fine). if exists_only: for key, value in out.items(): if value is None: out[key] = False if len(data) == 1: return out[data[0]] else: return out # ################################################################################################################################ def get(self, data, decrypt=True, serialize_dt=False, user_id=None): """ Returns a named attribute. """ # Audit comes first audit_pii.info(self.cid, 'attr.get/get_many', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('get', user_id) with closing(self.odb_session_func()) as session: return self._get(session, data, decrypt, serialize_dt, user_id) # Same as .get but a list/tuple/set is given on input instead of a single name get_many = get # ################################################################################################################################ def _exists(self, session, data, user_id=None): """ A low-level implementation of self.exists which expects an SQL session on input. """ # Audit comes first audit_pii.info(self.cid, 'attr._exists', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr, 'is_super_user':self.is_super_user}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('_exists', user_id) return self._get(session, data, False, False, user_id, AttrModel.name, True) # ################################################################################################################################ def names(self, user_id=None, _utcnow=_utcnow): """ Returns names of all attributes as a list (unsorted). """ # Audit comes first audit_pii.info(self.cid, 'attr.names', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr, 'is_super_user':self.is_super_user}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('names', user_id) now = _utcnow() with closing(self.odb_session_func()) as session: q = session.query(AttrModel.name).\ filter(AttrModel.user_id==(user_id)).\ filter(AttrModel.ust==self.ust).\ filter(AttrModel.expiration_time > now) if self.ust: q = q.\ filter(AttrModel.ust==SSOSession.ust).\ filter(SSOSession.expiration_time > now) result = q.all() return [item.name for item in result] # ################################################################################################################################ def exists(self, data, user_id=None): """ Returns a boolean flag to indicate if input attribute(s) exist(s) or not. """ # Audit comes first audit_pii.info(self.cid, 'attr.exists/exists_many', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('exists', user_id) with closing(self.odb_session_func()) as session: return self._exists(session, data, user_id) # Same API for both calls ('exist' could be another name but its exists_many for consistence with other methods) exists_many = exists # ################################################################################################################################ def delete(self, data, user_id=None, _utcnow=_utcnow): """ Deletes one or more names attributes. """ # Audit comes first audit_pii.info(self.cid, 'attr.delete/delete_many', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr, 'data':data, 'is_super_user':self.is_super_user}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('delete', user_id) now = _utcnow() data = [data] if isinstance(data, basestring) else data and_condition = [ AttrModelTable.c.user_id==(user_id), AttrModelTable.c.ust==self.ust, AttrModelTable.c.name.in_(data), AttrModelTable.c.expiration_time > now, ] with closing(self.odb_session_func()) as session: if self.ust: # Check comment in self._update for a comment why the below is needed if self.is_sqlite: result = self._ensure_ust_is_not_expired(session, self.ust, now) if not result: raise ValidationError(status_code.session.no_such_session) else: and_condition.extend([ AttrModelTable.c.ust==SSOSessionTable.c.ust, SSOSessionTable.c.expiration_time > now ]) session.execute( AttrModelTableDelete().\ where(and_(*and_condition))) session.commit() # One method can handle both calls delete_many = delete # ################################################################################################################################ def _set_expiry(self, session, name, expiration, user_id=None, needs_commit=True): """ A low-level implementation of self.set_expiry which expects an SQL session on input. """ # Audit comes first audit_pii.info(self.cid, 'attr._set_expiry', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr, 'is_super_user':self.is_super_user}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('_set_expiry', user_id) return self._update(session, name, expiration=expiration, user_id=user_id, needs_commit=needs_commit) # ################################################################################################################################ def set_expiry(self, name, expiration, user_id=None): """ Sets expiration for a named attribute. """ # Audit comes first audit_pii.info(self.cid, 'attr.set_expiry', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('set_expiry', user_id) with closing(self.odb_session_func()) as session: return self._set_expiry(session, name, expiration, user_id) # ################################################################################################################################ def _call_many(self, func, data, expiration=None, encrypt=False, user_id=None): """ A reusable method for manipulation of multiple attributes at a time. """ # Audit comes first audit_pii.info(self.cid, 'attr._call_many', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr, 'is_super_user':self.is_super_user, 'func':func.__func__.__name__}) # Default to current user unless overridden on input user_id = user_id or self.user_id with closing(self.odb_session_func()) as session: for item in data: # Check access permissions to that user's attributes _user_id = item.get('user_id', user_id) self._require_correct_user('_call_many', _user_id) func(session, item['name'], item['value'], item.get('expiration', expiration), item.get('encrypt', encrypt), _user_id, needs_commit=False) # Commit now everything added to session thus far try: session.commit() except IntegrityError: logger.warning(format_exc()) raise ValidationError(status_code.attr.already_exists) # ################################################################################################################################ def create_many(self, data, expiration=None, encrypt=False, user_id=None): """ Creates multiple attributes in one call. """ # Default to current user unless overridden on input user_id = user_id or self.user_id # Audit comes first audit_pii.info(self.cid, 'attr.create_many', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr}) # Check access permissions to that user's attributes self._require_correct_user('create_many', user_id) self._call_many(self._create, data, expiration, encrypt, user_id) # ################################################################################################################################ def update_many(self, data, expiration=None, encrypt=False, user_id=None): """ Update multiple attributes in one call. """ # Audit comes first audit_pii.info(self.cid, 'attr.update_many', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('update_many', user_id) self._call_many(self._update, data, expiration, encrypt, user_id) # ################################################################################################################################ def set_many(self, data, expiration=None, encrypt=False, user_id=None): """ Sets values of multiple attributes in one call. """ # Audit comes first audit_pii.info(self.cid, 'attr.set_many', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr}) # Default to current user unless overridden on input user_id = user_id or self.user_id # Check access permissions to that user's attributes self._require_correct_user('set_many', user_id) self._call_many(self._set, data, expiration, encrypt, user_id) # ################################################################################################################################ def set_expiry_many(self, data, expiration=None, user_id=None): """ Sets expiry for multiple attributes in one call. """ # Audit comes first audit_pii.info(self.cid, 'attr.set_expiry_many', self.current_user_id, user_id, extra={'current_app':self.current_app, 'remote_addr':self.remote_addr}) # Default to current user unless overridden on input user_id = user_id or self.user_id with closing(self.odb_session_func()) as session: for item in data: # Check access permissions to that user's attributes _user_id = item.get('user_id', user_id) self._require_correct_user('set_expiry_many', _user_id) # Check OK self._set_expiry(session, item['name'], item.get('expiration', expiration), _user_id, needs_commit=False) # Commit now everything added to session thus far session.commit() # ################################################################################################################################ def to_dict(self, decrypt=True, value_to_dict=False, serialize_dt=False, user_id=None, _utcnow=_utcnow): """ Returns a list of all attributes. """ # Default to current user unless overridden on input user_id = user_id or self.user_id out = {} now = _utcnow() with closing(self.odb_session_func()) as session: q = session.query(AttrModel).\ filter(AttrModel.user_id==(user_id)).\ filter(AttrModel.ust==self.ust).\ filter(AttrModel.expiration_time > now) if self.ust: q = q.\ filter(AttrModel.ust==SSOSession.ust).\ filter(SSOSession.expiration_time > now) result = q.all() for item in result: value = AttrEntity.from_sql(item, decrypt, self.decrypt_func, serialize_dt) out[item.name] = value.to_dict() if value_to_dict else value return out # ################################################################################################################################
29,298
Python
.py
515
46.899029
130
0.546255
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,972
api.py
zatosource_zato/code/zato-sso/src/zato/sso/api.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Zato from zato.sso import const, status_code, ValidationError from zato.sso.password_reset import PasswordResetAPI from zato.sso.user import Forbidden, User, UserAPI from zato.sso.totp_ import TOTPAPI # For flake8 const = const Forbidden = Forbidden status_code = status_code User = User ValidationError = ValidationError # ################################################################################################################################ # ################################################################################################################################ if 0: from bunch import Bunch from zato.common.typing_ import callable_, callnone from zato.server.base.parallel import ParallelServer # ################################################################################################################################ # ################################################################################################################################ class SSOAPI: """ An object through which user management and SSO-related functionality is accessed. """ server: 'ParallelServer' sso_conf: 'Bunch' odb_session_func: 'callable_' encrypt_func: 'callable_' decrypt_func: 'callable_' hash_func: 'callable_' verify_hash_func: 'callable_' new_user_id_func: 'callnone' = None encrypt_email: 'bool' encrypt_password: 'bool' password_expiry: 'int' totp: 'TOTPAPI' user: 'UserAPI' password_reset: 'PasswordResetAPI' def __init__( self, server, # type: ParallelServer sso_conf, # type: Bunch odb_session_func, # type: callable_ encrypt_func, # type: callable_ decrypt_func, # type: callable_ hash_func, # type: callable_ verify_hash_func, # type: callable_ new_user_id_func=None # type: callnone ) -> 'None': self.server = server self.sso_conf = sso_conf self.odb_session_func = odb_session_func self.encrypt_func = encrypt_func self.decrypt_func = decrypt_func self.hash_func = hash_func self.verify_hash_func = verify_hash_func self.new_user_id_func = new_user_id_func self.encrypt_email = self.sso_conf.main.encrypt_email self.encrypt_password = self.sso_conf.main.encrypt_password self.password_expiry = self.sso_conf.password.expiry # Management of TOTP tokens self.totp = TOTPAPI(self, self.sso_conf, self.decrypt_func) # User management, including passwords self.user = UserAPI(server, sso_conf, self.totp, odb_session_func, encrypt_func, decrypt_func, hash_func, verify_hash_func, new_user_id_func) # Management of Password reset tokens (PRT) self.password_reset = PasswordResetAPI(server, sso_conf, odb_session_func, decrypt_func, verify_hash_func) # ################################################################################################################################ def post_configure(self, func:'callable_', is_sqlite:'bool') -> 'None': self.odb_session_func = func self.user.post_configure(func, is_sqlite) self.password_reset.post_configure(func, is_sqlite) # ################################################################################################################################ # ################################################################################################################################
3,708
Python
.py
77
42.61039
130
0.50346
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,973
password_reset.py
zatosource_zato/code/zato-sso/src/zato/sso/password_reset.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from contextlib import closing from dataclasses import dataclass from datetime import datetime, timedelta from logging import getLogger # Bunch from bunch import Bunch # SQLAlchemy from sqlalchemy import and_ # Zato from zato.common import GENERIC, SMTPMessage from zato.common.api import SSO as CommonSSO from zato.common.json_internal import json_dumps from zato.common.odb.model import SSOPasswordReset as FlowPRTModel from zato.common.typing_ import cast_ from zato.sso import const, Default, status_code, ValidationError from zato.sso.common import SSOCtx from zato.sso.model import PasswordResetNotifCtx from zato.sso.odb.query import get_user_by_email, get_user_by_name, get_user_by_name_or_email, get_user_by_prt, \ get_user_by_prt_and_reset_key from zato.sso.util import new_prt, new_prt_reset_key, UserChecker # ################################################################################################################################ if 0: from typing import Callable from zato.common.odb.model import SSOUser from zato.common.typing_ import anydict, anylist, callable_ from zato.server.base.parallel import ParallelServer from zato.server.connection.email import SMTPConnection Callable = Callable ParallelServer = ParallelServer SMTPConnection = SMTPConnection SSOUser = SSOUser # ################################################################################################################################ # ################################################################################################################################ logger = getLogger('zato') # ################################################################################################################################ # ################################################################################################################################ FlowPRTModelTable = FlowPRTModel.__table__ FlowPRTModelInsert = FlowPRTModelTable.insert FlowPRTModelUpdate = FlowPRTModelTable.update # ################################################################################################################################ # ################################################################################################################################ @dataclass class AccessTokenCtx: user: 'anydict' reset_key: 'str' # ################################################################################################################################ # ################################################################################################################################ # Maps configuration keys to functions that look up users in the database. user_search_by_map = { 'username': get_user_by_name, 'email': get_user_by_email, 'username_or_email': get_user_by_name_or_email, } # ################################################################################################################################ # ################################################################################################################################ class PasswordResetAPI: """ Message flow around password-reset tokens (PRT). """ def __init__( self, server, # type: ParallelServer sso_conf, # type: Bunch odb_session_func, # type: callable_ decrypt_func, # type: callable_ verify_hash_func # type: callable_ ) -> 'None': self.server = server self.sso_conf = sso_conf self.odb_session_func = odb_session_func self.decrypt_func = decrypt_func self.verify_hash_func = verify_hash_func self.is_sqlite = None # PRT runtime configuration prt_config = sso_conf.get('prt', {}) # type: dict # For how long PRTs are valid (in seconds) valid_for = prt_config.get('valid_for') valid_for = valid_for or Default.prt_valid_for self.valid_for = int(valid_for) # For how long the one-off session to change the password will last (in minutes) duration = prt_config.get('password_change_session_duration') duration = duration or Default.prt_password_change_session_duration self.password_change_session_duration = int(duration) # By what credential to look up users in the database user_search_by = prt_config.get('user_search_by') user_search_by = user_search_by or Default.prt_user_search_by self.user_search_by_func = user_search_by_map[user_search_by] # Checks user context when a PRT is being accessed self.user_checker = UserChecker(self.decrypt_func, self.verify_hash_func, self.sso_conf) # Name of the site, e.g. the environemnt the SSO servers in self.site_name = self.sso_conf.main.get('site_name') or 'site' # Convert minutes to hours as it is hours that are sent in notification emails self.expiration_time_hours = int(self.sso_conf.password_reset.valid_for) // 60 # Name of an outgoing SMTP connections to send notifications through self.smtp_conn_name = sso_conf.main.smtp_conn # type: str # Name of a service to send out emails through self.email_service = sso_conf.main.get('email_service', '') # type: str # From who the SMTP messages will be sent self.email_from = sso_conf.password_reset.email_from # ################################################################################################################################ def post_configure(self, func:'callable_', is_sqlite:'bool') -> 'None': self.odb_session_func = func self.is_sqlite = is_sqlite # ################################################################################################################################ def create_token( self, cid, # type: str credential, # type: str current_app, # type: str remote_addr, # type: anylist user_agent, # type: str _utcnow=datetime.utcnow, # type: callable_ ) -> 'None': # Validate input if not credential: logger.warning('SSO credential missing on input to PasswordResetAPI.create_token (%r)', credential) return # For later use sso_ctx = self._build_sso_ctx(cid, remote_addr, user_agent, current_app) # Look up the user in the database .. with closing(self.odb_session_func()) as session: user = self.user_search_by_func(session, credential) # type: SSOUser # .. make sure the user exists .. if not user: logger.warning('No such SSO user `%s` (%s)', credential, self.user_search_by_func) return # .. the user exists so we can now generate a new PRT .. prt = new_prt() # .. timestamp metadata .. creation_time = _utcnow() expiration_time = creation_time + timedelta(minutes=self.valid_for) # .. these are the same so be explicit about it .. reset_key_exp_time = expiration_time # .. reset key used along with the PRT to reset the password .. reset_key = new_prt_reset_key() # .. insert it into the database .. session.execute( FlowPRTModelInsert().values({ 'creation_time': creation_time, 'expiration_time': expiration_time, 'reset_key_exp_time': reset_key_exp_time, 'user_id': user.user_id, 'token': prt, 'type_': const.password_reset.token_type, 'reset_key': reset_key, 'creation_ctx': json_dumps({ 'remote_addr': [elem.exploded for elem in sso_ctx.remote_addr], 'user_agent': sso_ctx.user_agent, 'has_remote_addr': sso_ctx.has_remote_addr, 'has_user_agent': sso_ctx.has_user_agent, }), GENERIC.ATTR_NAME: json_dumps(None) })) # .. commit the operation. session.commit() # Now, we canot notify the user (note that we are doing it outside the "with" block above # so as not to block the SQL connection). self.send_notification(user, prt) # ################################################################################################################################ def access_token( self, cid, # type: str token, # type: str current_app, # type: str remote_addr, # type: anylist user_agent, # type: str _utcnow=datetime.utcnow, # type: callable_ ) -> 'AccessTokenCtx': # For later use now = _utcnow() sso_ctx = self._build_sso_ctx(cid, remote_addr, user_agent, current_app) # We need an SQL session .. with closing(self.odb_session_func()) as session: # .. try to look up the user by the incoming PRT which must exist and not to have expired, # or otherwise have been invalidated (e.g. already accessed) .. user_info = get_user_by_prt(session, token, now) # .. no data matching the PRT, we need to reject the request .. if not user_info: msg = 'Token rejected. No valid PRT matched input `%s` (now: %s)' logger.warning(msg, token, now) raise ValidationError(status_code.password_reset.could_not_access, False) # .. now, check if the user is still allowed to access the system; # we make an assuption that it is true (the user is still allowed), # which is why we conduct this check under the same SQL session .. self.user_checker.check(sso_ctx, user_info, check_if_password_expired=False) # .. if we are here, it means that the user checks above succeeded, # which means that we can modify the state to indicate that the token # has been accessed and we can return an encrypted access token # to the caller to let the user update the password .. session.execute(FlowPRTModelUpdate().where( FlowPRTModelTable.c.token==token ).values({ 'has_been_accessed': True, 'access_time': now, 'access_ctx': json_dumps({ 'remote_addr': [elem.exploded for elem in sso_ctx.remote_addr], 'user_agent': user_agent, 'has_remote_addr': sso_ctx.has_remote_addr, 'has_user_agent': sso_ctx.has_user_agent, }) })) # .. commit the operation. session.commit() # Now, outside the SQL block, encrypt the reset key to be returned it to the caller # so that the user can provide it in the subsequent call to reset the password. reset_key = self.server.encrypt(user_info.reset_key, prefix='') reset_key = cast_('str', reset_key) return AccessTokenCtx( user=user_info._asdict(), reset_key=reset_key ) # ################################################################################################################################ def change_password( self, cid, # type: str new_password, # type: str token, # type: str reset_key, # type: str current_app, # type: str remote_addr, # type: anylist user_agent, # type: str _utcnow=datetime.utcnow, # type: callable_ ) -> 'None': # For later use now = _utcnow() sso_ctx = self._build_sso_ctx(cid, remote_addr, user_agent, current_app) # This will be encrypted on input so we need to get a clear-text version of it reset_key = self.server.decrypt_no_prefix(reset_key) # We need an SQL session .. with closing(self.odb_session_func()) as session: # .. try to look up the user by the incoming PRT and reset key which must exist and not to have expired, # or otherwise have been invalidated (e.g. already accessed) .. user_info = get_user_by_prt_and_reset_key(session, token, reset_key, now) # .. no data matching the PRT, we need to reject the request .. if not user_info: msg = 'Token or reset key rejected. No valid PRT or reset key matched input `%s` `%s` (now: %s)' logger.warning(msg, token, reset_key, now) raise ValidationError(status_code.password_reset.could_not_access, False) # .. now, check if the user is still allowed to access the system; # we make an assuption that it is true (the user is still allowed), # which is why we conduct this check under the same SQL session .. self.user_checker.check(sso_ctx, user_info, check_if_password_expired=False) # .. if we are here, it means that the user checks above succeeded # and we can update the user's password too .. self.server.sso_api.user.set_password( cid, user_info.user_id, new_password, must_change=False, password_expiry=None, current_app=current_app, remote_addr=remote_addr, details={ 'user_agent': user_agent, 'has_remote_addr': sso_ctx.has_remote_addr, 'has_user_agent': sso_ctx.has_user_agent, }) # # .. the password above was accepted and set which means that we can # modify the state to indicate that the reset key has been accessed # and that the password is changed .. # session.execute(FlowPRTModelUpdate().where(and_( FlowPRTModelTable.c.token==token, FlowPRTModelTable.c.reset_key==reset_key, )).values({ 'is_password_reset': True, 'password_reset_time': now, 'password_reset_ctx': json_dumps({ 'remote_addr': [elem.exploded for elem in sso_ctx.remote_addr], 'user_agent': sso_ctx.user_agent, 'has_remote_addr': sso_ctx.has_remote_addr, 'has_user_agent': sso_ctx.has_user_agent, }) })) # .. commit the operation. session.commit() # This is everything, we have just updated the user's password. # ################################################################################################################################ def _send_notification( self, user, # type: SSOUser token, # type: str smtp_message # type: SMTPMessage ) -> 'None': # If there is a user-defined service to send out emails, make use of it here # and do not proceed further on our end .. if self.email_service: # .. prepare all the details for the custom service .. ctx = PasswordResetNotifCtx() ctx.user = user._asdict() ctx.token = token ctx.smtp_message = smtp_message # .. and invoke it. self.server.invoke(self.email_service, ctx) # .. otherwise, we send the notification ourselves .. else: # .. make sure there is an SMTP connection to send an email through .. if not self.smtp_conn_name: msg = 'Could not notify user `%s`, SSO SMTP connection not configured in sso.conf (main.smtp_conn)' logger.warning(msg, user.user_id) return # .. get a handle to an SMTP connection .. smtp_conn = self.server.worker_store.email_smtp_api.get(self.smtp_conn_name).conn # type: SMTPConnection # .. and send it to the user. smtp_conn.send(smtp_message) # ################################################################################################################################ def send_notification(self, user, token, _template_name=CommonSSO.EmailTemplate.PasswordResetLink): # type: (SSOUser, str, str) -> None # Decrypt email for later user user_email = self.decrypt_func(user.email) # Make sure an email is associated with the user if not user_email: logger.warning('Could not notify user `%s` (no email found)', user.user_id) return # When user preferences, including the preferred language, are added, # we can look it up here. pref_lang = Default.prt_locale # All email templates for the preferred language pref_lang_templates = self.server.static_config.sso.email.get(pref_lang) # type: Bunch # Make sure we have the correct templates prepared if not pref_lang_templates: msg = 'Could not send a password reset notification to `%s`. Language `%s` not found among `%s``' logger.warning(msg, user.user_id, pref_lang, sorted(self.server.static_config.sso.email)) return # Template with the body to send template = pref_lang_templates.get(_template_name) # Make sure we have the correct templates prepared if not template: msg = 'Could not send a password reset notification to `%s`. Template `%s` not found among `%s`.' logger.warning(msg, user.user_id, _template_name, sorted(pref_lang_templates)) return # Prepare the details for the template .. template_params = { 'username': user.username, 'site_name': self.site_name, 'token': token, 'expiration_time_hours': self.expiration_time_hours } # .. fill it in .. msg_body = template.format(**template_params) # .. create a new message .. smtp_message = SMTPMessage() smtp_message.is_html = True # .. provide metadata .. smtp_message.subject = self.sso_conf.password_reset.get('email_title_' + pref_lang) or 'Password reset' smtp_message.to = user_email smtp_message.from_ = self.email_from # .. attach payload .. smtp_message.body = msg_body # .. and send the message to the user. self._send_notification(user, token, smtp_message) # ################################################################################################################################ def _build_sso_ctx( self, cid, # type: str remote_addr, # type: anylist user_agent, # type: str current_app # type: str ) -> 'SSOCtx': ctx = SSOCtx( cid=cid, remote_addr=remote_addr, user_agent=user_agent, input=Bunch({ 'current_app': current_app, }), sso_conf=self.sso_conf, ) # type: ignore return ctx # ################################################################################################################################ # ################################################################################################################################
19,759
Python
.py
377
42.103448
130
0.518511
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,974
__init__.py
zatosource_zato/code/zato-sso/src/zato/sso/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import stranydict, strlistnone, strnone # ################################################################################################################################ # ################################################################################################################################ not_given = object() # ################################################################################################################################ # ################################################################################################################################ class Default: prt_valid_for = 1440 # In minutes = 1 day prt_password_change_session_duration=1800 # In seconds = 30 minutes prt_user_search_by = 'username' # User notifications are sent in this language by default prt_locale = 'en_GB' # ################################################################################################################################ # ################################################################################################################################ class status_code: """ Reason codes pointing to specific API validation errors. """ ok = 'ok' error = 'error' warning = 'warning' class username: invalid = 'E001001' exists = 'E001002' too_long = 'E001003' has_whitespace = 'E001004' class user_id: invalid = 'E001100' class email: invalid = 'E002001' exists = 'E002002' too_long = 'E002003' has_whitespace = 'E002004' missing = 'E002005' class password: invalid = 'E003001' too_short = 'E003002' too_long = 'E003003' expired = 'E003004' w_about_to_exp = 'W003005' e_about_to_exp = 'E003006' must_send_new = 'E003007' not_complex_enough = 'E003008' class app_list: invalid = 'E004001' no_signup = 'E004002' class auth: not_allowed = 'E005001' # Generic 'You are not allowed to access this resource' locked = 'E005002' invalid_signup_status = 'E005003' not_approved = 'E005004' super_user_required = 'E005005' no_such_sign_up_token = 'E005006' sign_up_confirmed = 'E005007' totp_missing = 'E005008' class metadata: not_allowed = 'E006001' class session: no_such_session = 'E007001' expired = 'E007002' class common: invalid_operation = 'E008001' invalid_input = 'E008002' missing_input = 'E008003' internal_error = 'E008004' class attr: already_exists = 'E009001' no_such_attr = 'E009002' class password_reset: could_not_access = 'E010001' # ################################################################################################################################ # ################################################################################################################################ class const: """ Constants used in SSO. """ class signup_status: before_confirmation = 'before_confirmation' final = 'final' def __iter__(self): return iter([self.before_confirmation, self.final]) class approval_status: approved = 'approved' rejected = 'rejected' before_decision = 'before_decision' def __iter__(self): return iter([self.approved, self.rejected, self.before_decision]) class search: and_ = 'and' or_ = 'or' page_size = 50 def __iter__(self): return iter([self.and_, self.or_]) class auth_type: basic_auth = 'basic_auth' default = 'default' jwt = 'jwt' class password_reset: token_type = 'prt' # ################################################################################################################################ # ################################################################################################################################ class ValidationError(Exception): """ Raised if any input SSO data is invalid, subcode contains details of what was rejected. """ def __init__(self, sub_status, return_status=False, status=status_code.error): super(ValidationError, self).__init__('{} {}'.format(status, sub_status)) self.sub_status = sub_status if isinstance(sub_status, list) else [sub_status] self.return_status = return_status self.status = status # ################################################################################################################################ # ################################################################################################################################ class InvalidTOTPError(ValidationError): """ Raised if any input TOTP code is invalid for user. """ # ################################################################################################################################ # ################################################################################################################################ class SearchCtx: """ A container for SSO user search parameters. """ # Query criteria user_id: 'str | object' = not_given username: 'str | object' = not_given email: 'str | object' = not_given display_name: 'str | object' = not_given first_name: 'str | object' = not_given middle_name: 'str | object' = not_given last_name: 'str | object' = not_given sign_up_status: 'str | object' = not_given approval_status: 'str | object' = not_given # Query config paginate: 'bool' = True cur_page: 'int' = 1 page_size: 'strnone' = None name_op: 'str' = const.search.and_ is_name_exact: 'bool' = True # ################################################################################################################################ # ################################################################################################################################ class SignupCtx: """ A container for SSO user signup parameters. """ username: 'str' = '' email: 'str' = '' password: 'str' = '' current_app: 'str' = None app_list: 'strlistnone' = None sign_up_status: 'str' = const.signup_status.before_confirmation def to_dict(self) -> 'stranydict': return { 'username': self.username, 'email': self.email, 'password': self.password, 'current_app': self.current_app, 'app_list': self.app_list, 'sign_up_status': self.sign_up_status } # ################################################################################################################################ # ################################################################################################################################ class User: """ Represents a user managed by SSO. """ __slots__ = ('approval_status', 'approval_status_mod_by', 'approval_status_mod_time','attr', 'creation_ctx', 'display_name', 'email', 'first_name', 'is_active', 'is_approval_needed', 'is_internal', 'is_locked', 'is_super_user', 'last_name', 'locked_by', 'locked_time', 'middle_name', 'password_expiry', 'password_is_set', 'password_last_set', 'password_must_change', 'sign_up_status', 'sign_up_time', 'user_id', 'username', 'is_rate_limit_active', 'rate_limit_def', 'rate_limit_type', 'rate_limit_check_parent_def', 'is_totp_enabled', 'totp_key', 'totp_label', 'status', 'is_current_super_user') def __init__(self): self.approval_status = None self.approval_status_mod_by = None self.approval_status_mod_time = None self.attr = None self.creation_ctx = None self.display_name = None self.email = None self.first_name = None self.is_active = None self.is_approval_needed = None self.is_internal = None self.is_locked = None self.is_super_user = None self.last_name = None self.locked_by = None self.locked_time = None self.middle_name = None self.password_expiry = None self.password_is_set = None self.password_last_set = None self.password_must_change = None self.sign_up_status = None self.sign_up_time = None self.user_id = None self.username = None self.is_rate_limit_active = None self.rate_limit_def = None self.rate_limit_type = None self.rate_limit_check_parent_def = None self.is_totp_enabled = None self.totp_key = None self.totp_label = None self.status = None # Set to True if the user whose session created this object is a super-user self.is_current_super_user = False def to_dict(self): return {name: getattr(self, name) for name in self.__slots__ if name != 'attr'} # ################################################################################################################################ # ################################################################################################################################ class Session: """ Represents a session opened by a particular SSO user. """ __slots__ = ('attr', 'creation_time', 'expiration_time', 'remote_addr', 'user_agent') def __init__(self): self.attr = None self.creation_time = None self.expiration_time = None self.remote_addr = None self.user_agent = None def to_dict(self): return {name: getattr(self, name) for name in self.__slots__ if name != 'attr'} # ################################################################################################################################ # ################################################################################################################################
10,810
Python
.py
226
41.10177
130
0.41191
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,975
user_search.py
zatosource_zato/code/zato-sso/src/zato/sso/user_search.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # SQALchemy from sqlalchemy import asc, desc from sqlalchemy.sql import and_ as sql_and, or_ as sql_or # Python 2/3 compatibility from zato.common.py23_.past.builtins import basestring # Zato from zato.common.odb.model import SSOUser from zato.common.odb.query import query_wrapper from zato.common.util.sql import search as util_search from zato.sso import const from zato.sso.odb.query import _user_basic_columns # ################################################################################################################################ _does_not_exist = object() # ################################################################################################################################ name_op_allowed = set(const.search()) name_op_sa = { const.search.and_: sql_and, const.search.or_: sql_or, } # ################################################################################################################################ class OrderBy: """ Defaults for the SQL ORDER BY clause. """ def __init__(self): self.asc = 'asc' self.desc = 'desc' # All ORDER BY directions allowed self.dir_allowed = {self.asc, self.desc} # All columns that results may be ordered by self.out_columns_allowed = {'display_name', 'username', 'sign_up_time', 'user_id'} # How results will be sorted if no user-defined order is given self.default = ( asc('display_name'), asc('username'), asc('sign_up_time'), asc('user_id'), ) # ################################################################################################################################ class SSOSearch: """ SSO search functions, constants and defaults. """ # Maps publicly visible column names to SQL ones name_columns = { 'display_name': SSOUser.display_name_upper, 'first_name': SSOUser.first_name_upper, 'middle_name': SSOUser.middle_name_upper, 'last_name': SSOUser.last_name_upper, } # Maps columns and exactness flags to sqlalchemy-level functions that look up data name_column_op = { (SSOUser.display_name_upper, True): SSOUser.display_name_upper.__eq__, # noqa: E203 (SSOUser.first_name_upper, True) : SSOUser.first_name_upper.__eq__, # noqa: E203 (SSOUser.middle_name_upper, True) : SSOUser.middle_name_upper.__eq__, # noqa: E203 (SSOUser.last_name_upper, True) : SSOUser.last_name_upper.__eq__, # noqa: E203 (SSOUser.display_name_upper, False): SSOUser.display_name_upper.contains, # noqa: E203 (SSOUser.first_name_upper, False) : SSOUser.first_name_upper.contains, # noqa: E203 (SSOUser.middle_name_upper, False) : SSOUser.middle_name_upper.contains, # noqa: E203 (SSOUser.last_name_upper, False) : SSOUser.last_name_upper.contains, # noqa: E203 } # What columns to use for non-name criteria non_name_column_op = { 'email': SSOUser.email.__eq__, 'sign_up_status': SSOUser.sign_up_status.__eq__, 'approval_status': SSOUser.approval_status.__eq__, } # What columns to use for user ID and username user_id_op = SSOUser.user_id.__eq__ username_op = SSOUser.username.__eq__ def __init__(self): self.out_columns = [] self.order_by = OrderBy() # ################################################################################################################################ def set_up(self): for column in _user_basic_columns: self.out_columns.append(getattr(SSOUser, column.name)) # ################################################################################################################################ @query_wrapper def sql_search_func(self, session, ignored_cluster_id, order_by, where, needs_columns=False): # Build a basic query q = session.query(*self.out_columns) # SQL WHERE parameters are optional if (where != '') and (where is not None): q = q.filter(where) # These are always given q = q.order_by(*order_by) # We can return the result now return q # ################################################################################################################################ def _get_order_by(self, order_by): """ Constructs an ORDER BY clause for the user search query. """ out = [] for item in order_by: items = item.items() if len(items) != 1 or len(items[0]) != 2: raise ValueError('Invalid order_by config `{}`'.format(items)) else: column, dir = items[0] if column not in self.order_by.columns_allowed: raise ValueError('Invalid order_by column `{}`'.format(column)) if dir not in self.order_by.dir_allowed: raise ValueError('Invalid order_by dir `{}`'.format(dir)) # Columns and directions are valid, we can construct the ORDER BY clause now func = asc if dir == self.order_by.asc else desc out.append(func(column)) return out # ################################################################################################################################ def _get_where_user_id(self, user_id): """ Constructs a WHERE clause to look up users by user_id (will return at most one row). """ return self.user_id_op(user_id) # ################################################################################################################################ def _get_where_username(self, username): """ Constructs a WHERE clause to look up users by username (will return at most one row). """ return self.username_op(username) # ################################################################################################################################ def _get_where_name(self, name, name_exact, name_op, name_op_allowed=name_op_allowed, name_op_sa=name_op_sa): """ Constructs a WHERE clause to look up users by display/first/middle or last name. """ name_criteria_raw = [] name_criteria = [] name_where = None # Name must be a dict of columns if not isinstance(name, dict): raise ValueError('Invalid name `{}`'.format(name)) # Validate that only allowed columns and values of expected type are passed to the name filter for column_key, value in name.items(): if column_key not in self.name_columns: raise ValueError('Invalid name key `{}`'.format(column_key)) elif not isinstance(value, basestring): raise ValueError('Invalid value `{}`'.format(value)) else: value = value.strip() if not value: raise ValueError('Value must not be empty, key `{}`'.format(column_key)) name_criteria_raw.append((self.name_columns[column_key], value.upper())) # Name operator is needed only if name is given on input if name_op: if name_op not in name_op_allowed: raise ValueError('Invalid name_op `{}`'.format(name_op)) else: name_op = const.search.and_ # Convert a label to an actual SQALchemy-level function name_op = name_op_sa[name_op] # We need to have a reference to a Python-level function # At this point we know all name-related input is correct and we have both criteria # and an operator to joined them with. if name_criteria_raw: for column, value in name_criteria_raw: func = self.name_column_op[(column, name_exact)] name_criteria.append(func(value)) name_where = name_op(*name_criteria) return name_where # ################################################################################################################################ def _get_where_non_name(self, config): """ Constructs a WHERE clause for criteria other than display-related names. """ # We can search by email only if emails are not encrypted email = config.get('email') if email: if not config.get('email_search_enabled'): raise ValueError('Cannot look up users by email') non_name_where = None non_name_criteria = [] for non_name in self.non_name_column_op: value = config.get(non_name, _does_not_exist) if value is not _does_not_exist: if value is not None: if not isinstance(value, basestring): raise ValueError('Invalid value `{}`'.format(value)) non_name_criteria.append(self.non_name_column_op[non_name](value)) if non_name_criteria: non_name_where = sql_and(*non_name_criteria) return non_name_where # ################################################################################################################################ def _get_where(self, config): """ Creates the WHERE part of a user search query. """ # Check shorter paths first username = config.get('username') user_id = config.get('user_id') # If either username or user_id are given on input, we cut it short and ignore # other parameters - this is because both of them are unique in the DB so any other # parameter would have no influence over results .. # .. also, if both of them are given on input, we only take user_id into account. if username or user_id: if user_id: return self._get_where_user_id(user_id) else: return self._get_where_username(username) # If we are here it means there was neither user_id nor username on input # Should we search by any name? name_where = None # Should we search by any non-name criteria? non_name_where = None # Get all name-related criteria if 'name' in config: name_where = self._get_where_name(config.get('name'), config['is_name_exact'], config['name_op']) # Get all non-name related criteria non_name_where = self._get_where_non_name(config) # Now we have both name-related and non-name related WHERE conditions, yet both possibly empty, # but even if they are empty we can construct the final AND-joined WHERE condition now. # Names are given .. if name_where is not None: # .. but other attributes are not, in this case WHERE will be names only. if non_name_where is None: where = name_where # .. there are both names and non-names. else: where = sql_and(name_where, non_name_where) # .. there are only non-names. elif non_name_where is not None: where = non_name_where else: where = '' return where # ################################################################################################################################ def search(self, session, config): """ Looks up users with the configuration given on input. """ # WHERE clause where = self._get_where(config) # ORDER BY clause order_by = config.get('order_by') order_by = self._get_order_by(order_by) if order_by else self.order_by.default return util_search(self.sql_search_func, config, [], session, None, order_by, where, False) # ################################################################################################################################
12,179
Python
.py
234
42.944444
130
0.520101
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,976
model.py
zatosource_zato/code/zato-sso/src/zato/sso/model.py
# -*- coding: utf-8 -*- """ Copyright (C) 2021, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from dataclasses import dataclass # Zato from zato.common.marshal_.api import Model from zato.common.typing_ import strnone # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common import SMTPMessage from zato.common.typing_ import anydict from zato.sso.common import BaseRequestCtx # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class RequestCtx(Model): cid: 'str' current_ust: 'strnone' current_app: 'strnone' remote_addr: 'strnone' user_agent: 'strnone' @staticmethod def from_ctx(ctx:'BaseRequestCtx') -> 'RequestCtx': req_ctx = RequestCtx() req_ctx.cid = ctx.cid req_ctx.remote_addr = ctx.remote_addr req_ctx.user_agent = ctx.user_agent return req_ctx # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class PasswordResetNotifCtx(Model): user: 'anydict' token: 'str' smtp_message: 'SMTPMessage' @staticmethod def from_ctx(ctx:'BaseRequestCtx') -> 'RequestCtx': req_ctx = RequestCtx() req_ctx.cid = ctx.cid req_ctx.remote_addr = ctx.remote_addr req_ctx.user_agent = ctx.user_agent return req_ctx # ################################################################################################################################ # ################################################################################################################################
2,289
Python
.py
48
43.458333
130
0.363881
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,977
common.py
zatosource_zato/code/zato-sso/src/zato/sso/common.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from datetime import datetime # ipaddress from ipaddress import ip_address # Zato from zato.common.api import GENERIC from zato.common.ext.dataclasses import dataclass, field from zato.common.json_internal import dumps from zato.common.odb.model import SSOSession as SessionModel from zato.sso import const # ################################################################################################################################ # ################################################################################################################################ if 0: from zato.common.typing_ import any_, anydict, anylist, strlist, strnone # ################################################################################################################################ # ################################################################################################################################ SessionModelTable = SessionModel.__table__ SessionModelInsert = SessionModelTable.insert # ################################################################################################################################ # ################################################################################################################################ @dataclass class BaseRequestCtx: cid: 'str' remote_addr: 'str | strlist' user_agent: 'str' input: 'anydict' has_remote_addr: 'bool' = field(init=False, default=False) has_user_agent: 'bool' = field(init=False, default=False) def __post_init__(self) -> 'None': self.has_remote_addr = bool(self.input.get('remote_addr')) self.has_user_agent = bool(self.input.get('user_agent')) if isinstance(self.remote_addr, str): remote_addr = [elem.strip() for elem in self.remote_addr.strip().split(',')] remote_addr = [ip_address(elem) for elem in remote_addr] self.remote_addr = remote_addr # ################################################################################################################################ # ################################################################################################################################ @dataclass class SSOCtx(BaseRequestCtx): """ A set of attributes describing current SSO request. """ sso_conf: 'anydict' # ################################################################################################################################ # ################################################################################################################################ @dataclass class LoginCtx(BaseRequestCtx): """ A set of data about a login request. """ ext_session_id: 'str' = field(init=False) def __post_init__(self) -> 'None': super().__post_init__() self.ext_session_id = '' # ################################################################################################################################ # ################################################################################################################################ @dataclass(init=False) class SessionInsertCtx: ust: 'str' creation_time: 'datetime' expiration_time: 'datetime' user_id: 'int' auth_type: 'str' auth_principal: 'str' remote_addr: 'str' user_agent: 'str' ctx_source: 'str' ext_session_id: 'strnone' interaction_max_len: 'int' # ################################################################################################################################ # ################################################################################################################################ class VerifyCtx: """ Wraps information about a verification request. """ __slots__ = ('ust', 'remote_addr', 'input', 'has_remote_addr', 'has_user_agent', 'current_app') def __init__( self, ust, # type: str remote_addr, # type: str current_app, # type: str has_remote_addr=False, # type: bool has_user_agent=False # type: bool ) -> 'None': self.ust = ust self.remote_addr = remote_addr self.has_remote_addr = has_remote_addr self.has_user_agent = has_user_agent self.current_app = current_app self.input = { 'current_app': current_app } # ################################################################################################################################ # ################################################################################################################################ def insert_sso_session(sql_session:'any_', insert_ctx:'SessionInsertCtx', needs_commit:'bool'=True) -> 'None': # Create current interaction details for this SSO session .. session_state_change_list = update_session_state_change_list( [], insert_ctx.interaction_max_len, insert_ctx.remote_addr, insert_ctx.user_agent, insert_ctx.ctx_source, insert_ctx.creation_time, ) # .. convert interaction details into an opaque attribute .. opaque = dumps({ 'session_state_change_list': session_state_change_list }) # .. run the SQL insert statement .. sql_session.execute( SessionModelInsert().values({ 'ust': insert_ctx.ust, 'creation_time': insert_ctx.creation_time, 'expiration_time': insert_ctx.expiration_time, 'user_id': insert_ctx.user_id, 'auth_type': insert_ctx.auth_type or const.auth_type.default, 'auth_principal': insert_ctx.auth_principal, 'remote_addr': ', '.join(str(elem) for elem in insert_ctx.remote_addr), 'user_agent': insert_ctx.user_agent, 'ext_session_id': insert_ctx.ext_session_id, GENERIC.ATTR_NAME: opaque })) # .. and commit the SQL state. if needs_commit: sql_session.commit() # ################################################################################################################################ # ################################################################################################################################ def update_session_state_change_list( current_state, # type: anylist interaction_max_len, # type: int remote_addr, # type: str | anylist user_agent, # type: str ctx_source, # type: any_ now # type: datetime ) -> 'None': """ Adds information about a user interaction with SSO, keeping the history of such interactions to up to max_len entries. """ if current_state: idx = current_state[-1]['idx'] else: idx = 0 remote_addr = remote_addr if isinstance(remote_addr, list) else [remote_addr] if len(remote_addr) == 1: remote_addr = str(remote_addr[0]) else: remote_addr = [str(elem) for elem in remote_addr] current_state.append({ 'remote_addr': remote_addr, 'user_agent': user_agent, 'timestamp_utc': now.isoformat(), 'ctx_source': ctx_source, 'idx': idx + 1 }) if len(current_state) > interaction_max_len: current_state.pop(0) return current_state # ################################################################################################################################
7,672
Python
.py
160
42.2875
130
0.418384
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,978
session.py
zatosource_zato/code/zato-sso/src/zato/sso/session.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from contextlib import closing from datetime import datetime, timedelta from hashlib import sha256 from logging import getLogger from traceback import format_exc from uuid import uuid4 # Zato from zato.common.api import GENERIC, SEC_DEF_TYPE from zato.common.audit import audit_pii from zato.common.json_internal import dumps from zato.common.odb.model import SSOSession as SessionModel from zato.common.model.sso import ExpiryHookInput from zato.common.typing_ import cast_ from zato.sso import status_code, Session as SessionEntity, ValidationError from zato.sso.attr import AttrAPI from zato.sso.odb.query import get_session_by_ext_id, get_session_by_ust, get_session_list_by_user_id, get_user_by_id, \ get_user_by_name from zato.sso.common import insert_sso_session, LoginCtx, SessionInsertCtx, \ update_session_state_change_list as _update_session_state_change_list, VerifyCtx from zato.sso.model import RequestCtx from zato.sso.util import new_user_session_token, set_password, UserChecker, validate_password # ################################################################################################################################ if 0: from typing import Callable from bunch import Bunch from zato.common.odb.model import SSOUser from zato.common.typing_ import anylist, anytuple, boolnone, callable_, dtnone, list_, stranydict, strnone from zato.server.base.parallel import ParallelServer from zato.sso.totp_ import TOTPAPI from zato.sso.user import User Bunch = Bunch Callable = Callable SSOUser = SSOUser User = User boolnone = boolnone strnone = strnone # ################################################################################################################################ logger = getLogger('zato') # ################################################################################################################################ SessionModelTable = SessionModel.__table__ SessionModelUpdate = SessionModelTable.update SessionModelDelete = SessionModelTable.delete # ################################################################################################################################ _dummy_password='dummy.{}'.format(uuid4().hex) _ext_sec_type_supported = SEC_DEF_TYPE.BASIC_AUTH, SEC_DEF_TYPE.JWT # ################################################################################################################################ class SessionInfo: """ Details about an individual session. """ ust: 'strnone' = None user_id: 'strnone' = None username: 'strnone' = None creation_time: 'dtnone' = None expiration_time: 'dtnone' = None has_w_about_to_exp: 'boolnone' = None def to_dict(self, serialize_dt:'bool'=True) -> 'stranydict': if self.creation_time: creation_time = self.creation_time.isoformat() if serialize_dt else self.creation_time else: creation_time = self.creation_time if self.expiration_time: expiration_time = self.expiration_time.isoformat() if serialize_dt else self.expiration_time else: expiration_time = self.expiration_time return { 'username': self.username, 'user_id': self.user_id, 'ust': self.ust, 'creation_time': creation_time, 'expiration_time': expiration_time, 'has_w_about_to_exp': self.has_w_about_to_exp } # ################################################################################################################################ class SessionAPI: """ Logs a user in or out, provided that all authentication and authorization checks succeed, or returns details about already existing sessions. """ def __init__( self, server, # type: ParallelServer sso_conf, # type: Bunch totp, # type: TOTPAPI encrypt_func, # type: 'callable_' decrypt_func, # type: 'callable_' hash_func, # type: 'callable_' verify_hash_func, # type: 'callable_' ) -> 'None': self.server = server self.sso_conf = sso_conf self.totp = totp self.encrypt_func = encrypt_func self.decrypt_func = decrypt_func self.hash_func = hash_func self.verify_hash_func = verify_hash_func self.odb_session_func = None self.is_sqlite = None self.interaction_max_len = 100 self.user_checker = UserChecker(self.decrypt_func, self.verify_hash_func, self.sso_conf) # ################################################################################################################################ def post_configure(self, func:'callable_', is_sqlite:'bool') -> 'None': self.odb_session_func = func self.is_sqlite = is_sqlite # ################################################################################################################################ def _format_ext_session_id( self, sec_type, # type: str sec_def_id, # type: int ext_session_id, # type: str | bytes _ext_sec_type_supported=_ext_sec_type_supported, # type: anytuple _bearer=b'Bearer ' # type: bytes ) -> 'str': """ Turns information about a security definition and potential external session ID into a format that can be used in SQL. """ # Make sure we let in only allowed security definitions if sec_type in _ext_sec_type_supported: # This is always required _ext_session_id = '{}.{}'.format(sec_type, sec_def_id) # JWT tokens need to be included if this is the security type used if sec_type == SEC_DEF_TYPE.JWT: if isinstance(ext_session_id, str): ext_session_id = cast_('bytes', ext_session_id.encode('utf8')) # type: ignore ext_session_id = ext_session_id.replace(_bearer, b'') _ext_session_id += '.{}'.format(sha256(ext_session_id).hexdigest()) # Return the reformatted external session ID return _ext_session_id else: raise NotImplementedError('Unrecognized sec_type `{}`'.format(sec_type)) # ################################################################################################################################ def on_external_auth_succeeded( self, cid, # type: str sec_type, # type: str sec_def_id, # type: int sec_def_username, # type: str user_id, # type: str ext_session_id, # type: str totp_code, # type: str current_app, # type: str remote_addr, # type: str | bytes user_agent=None, # type: str | None _utcnow=datetime.utcnow, # type: callable_ ) -> 'SessionInfo': """ Invoked when a user succeeded in authentication via means external to default SSO credentials, e.g. through Basic Auth or JWT. Creates an SSO session related to that event or renews an existing one. """ remote_addr = remote_addr if isinstance(remote_addr, str) else remote_addr.decode('utf8') # PII audit comes first audit_pii.info(cid, 'session.on_external_auth_succeeded', extra={ 'current_app':current_app, 'remote_addr':remote_addr, 'sec.sec_type': sec_type, 'sec.id': sec_def_id, 'sec.username': sec_def_username, }) existing_ust = '' # type: str ext_session_id = self._format_ext_session_id(sec_type, sec_def_id, ext_session_id) # Check if there is already a session associated with this external one sso_session = self._get_session_by_ext_id(sec_type, sec_def_id, ext_session_id) if sso_session: existing_ust = sso_session.ust # .. if there is, renew it .. if existing_ust: expiration_time = self.renew(cid, existing_ust, current_app, remote_addr, user_agent, False) session_info = SessionInfo() session_info.ust = existing_ust session_info.expiration_time = expiration_time return session_info # .. otherwise, create a new one. else: ctx = LoginCtx() ctx.cid = cid ctx.remote_addr = remote_addr ctx.user_agent = user_agent ctx.ext_session_id = ext_session_id ctx.input = { 'user_id': user_id, 'current_app': current_app, 'totp_code': totp_code, 'sec_type': sec_type, } return self.login(ctx, is_logged_in_ext=True) # ################################################################################################################################ def _needs_totp_login_check( self, user, # type: User is_logged_in_ext, # type: bool sec_type, # type: str _basic_auth=SEC_DEF_TYPE.BASIC_AUTH # type: str ) -> 'bool': """ Returns True TOTP should be checked for user during logging in or False otherwise. """ # If TOTP is enabled for user then return True unless the user is already # logged in externally via Basic Auth in which case it is never required # because Basic Auth itself does not have any means to relay current TOTP code # (short of adding custom Zato-specific HTTP headers or similar parameters). if is_logged_in_ext and sec_type == _basic_auth: return False else: return user.is_totp_enabled # ################################################################################################################################ def login( self, ctx, # type: LoginCtx _ok=status_code.ok, # type: str _now=datetime.utcnow, # type: callable_ _timedelta=timedelta, # type: callable_ _dummy_password=_dummy_password, # type: str is_logged_in_ext=False, # type: bool skip_sec=False # type: bool ) -> 'SessionInfo': """ Logs a user in, returning session info on success or raising ValidationError on any error. """ # Look up user and raise exception if not found by username with closing(self.odb_session_func()) as session: if ctx.input.get('username'): user = get_user_by_name(session, ctx.input['username']) # type: SSOUser else: user = get_user_by_id(session, ctx.input.get('user_id')) # type: SSOUser # If we do not have a user object here, it means that the input was invalid and there is no such user if not user: logger.warning('User not found; username:`%s`, user_id:`%s`', ctx.input.get('username'), ctx.input.get('user_id')) raise ValidationError(status_code.auth.not_allowed, False) if not skip_sec: # If the user is already logged in externally, this flag will be True, # in which case we do not check the credentials - we already know they are valid # because they were checked externally and user_id is the SSO user linked to the # already validated external credentials. if not is_logged_in_ext: # Local alias input_password = ctx.input['password'] # Make sure we have a password on input if not input_password: logger.warning('Password missing on input; user_id:`%s`', user.user_id) raise ValidationError(status_code.auth.not_allowed, False) # This may have been encrypted by SIO ctx.input['password'] = self.decrypt_func(ctx.input['password']) # Check credentials first to make sure that attackers do not learn about any sort # of metadata (e.g. is the account locked) if they do not know username and password. if not self.user_checker.check_credentials(ctx, user.password if user else _dummy_password): raise ValidationError(status_code.auth.not_allowed, False) # Check input TOTP key if two-factor authentication is enabled .. if self._needs_totp_login_check(user, is_logged_in_ext, ctx.input.get('sec_type')): # Build a request context object here until we start to receive them on input .. req_ctx = RequestCtx.from_ctx(ctx) req_ctx.current_app = ctx.input['current_app'] # .. this will raise an exception if input TOTP code is invalid. self.totp.validate_code_for_user( req_ctx, code=ctx.input.get('totp_code'), user=user) # We assume that we will not have to warn about an approaching password expiry has_w_about_to_exp = False if not skip_sec: # It must be possible to log into the application requested (CRM above) _ = self.user_checker.check_login_to_app_allowed(ctx) # Common auth checks self.user_checker.check(ctx, user) # If applicable, password may be about to expire (this must be after checking that it has not already). # Note that it may return a specific status to return (warning or error) _about_status = self.user_checker.check_password_about_to_expire(user) if _about_status is not True: if _about_status == status_code.warning: has_w_about_to_exp = True else: raise ValidationError(status_code.password.e_about_to_exp, False, _about_status) # If password is marked as requiring a change upon next login but a new one was not sent, reject the request. _ = self.user_checker.check_must_send_new_password(ctx, user) # If new password is required, we need to validate and save it before session can be created. # Note that at this point we already know that the old password was correct so it is safe to set the new one # if it is confirmed to be valid. We also know that there is some new password on input because otherwise # the check above would have raised a ValidationError. if not skip_sec: if user.password_must_change: try: validate_password(self.sso_conf, ctx.input.get('new_password')) except ValidationError as e: if e.return_status: raise ValidationError(e.sub_status, e.return_status, e.status) else: set_password(self.odb_session_func, self.encrypt_func, self.hash_func, self.sso_conf, user.user_id, ctx.input['new_password'], False) # All validated, we can create a session object now creation_time = _now() session_expiry = self._get_session_expiry_delta(cast_('str', ctx.input['current_app']), user.username) expiration_time = creation_time + timedelta(minutes=session_expiry) ust = new_user_session_token() # All the data needed to insert a new session into the database .. insert_ctx = SessionInsertCtx() insert_ctx.ust = ust insert_ctx.interaction_max_len = self.interaction_max_len insert_ctx.remote_addr = ctx.remote_addr insert_ctx.user_agent = ctx.user_agent insert_ctx.ctx_source = 'login' insert_ctx.creation_time = creation_time insert_ctx.expiration_time = expiration_time insert_ctx.user_id = user.id insert_ctx.auth_type = ctx.input.get('sec_type') # or const.auth_type.default insert_ctx.auth_principal = user.username insert_ctx.ext_session_id = ctx.ext_session_id # .. insert the session into the SQL database now. insert_sso_session(session, insert_ctx) info = SessionInfo() info.username = user.username info.user_id = user.user_id info.ust = self.encrypt_func(ust.encode('utf8')) info.creation_time = creation_time info.expiration_time = expiration_time info.has_w_about_to_exp = has_w_about_to_exp return info # ################################################################################################################################ def _get_session_by_ust(self, session, ust, now) -> 'SessionModel | Bunch': """ Low-level implementation of self.get_session_by_ust. """ # type: (object, str, datetime) -> object return get_session_by_ust(session, ust, now) # ################################################################################################################################ def get_session_by_ust(self, ust, now) -> 'SessionModel': """ Returns details of an SSO session by its UST. """ # type: (str, datetime) -> object with closing(self.odb_session_func()) as session: return self._get_session_by_ust(session, ust, now) # ################################################################################################################################ def _get_session_by_ext_id(self, sec_type, sec_def_id, ext_session_id=None, _utcnow=datetime.utcnow) -> 'SessionModel': with closing(self.odb_session_func()) as session: return get_session_by_ext_id(session, ext_session_id, _utcnow()) # ################################################################################################################################ def get_session_by_ext_id(self, sec_type, sec_def_id, ext_session_id=None) -> 'SessionModel': ext_session_id = self._format_ext_session_id(sec_type, sec_def_id, ext_session_id) result = self._get_session_by_ext_id(sec_type, sec_def_id, ext_session_id) if result: out = { 'session_state_change_list': self._extract_session_state_change_list(result) } for name in 'ust', 'creation_time', 'remote_addr', 'user_agent', 'auth_type': out[name] = getattr(result, name) return out # ################################################################################################################################ def _extract_session_state_change_list(self, session_data, _opaque=GENERIC.ATTR_NAME) -> 'anylist': opaque = getattr(session_data, _opaque) or {} return opaque.get('session_state_change_list', []) # ################################################################################################################################ def update_session_state_change_list(self, current_state, remote_addr, user_agent, ctx_source, now) -> 'anylist | None': """ Adds information about a user interaction with SSO, keeping the history of such interactions to up to max_len entries. """ # type: (list, str, str, str, datetime) return _update_session_state_change_list( current_state, self.interaction_max_len, remote_addr, user_agent, ctx_source, now ) # ################################################################################################################################ def _get_session_expiry_delta(self, current_app:'str', username:'str') -> 'int': """ Returns an integer indicating for how many minutes to extend a user session. """ # This will be used if, for any reason, we cannot invoke the hook service default_expiry = cast_('int', self.sso_conf.session.expiry) # This is what we are returning unless a hook says otherwise out = default_expiry # Try to see if there is an expiry hook service defined .. expiry_hook = self.sso_conf.session.get('expiry_hook') # .. if not, we can return the default expiry immediately .. if not expiry_hook: return default_expiry # .. otherwise, try to invoke the hook service .. try: request = ExpiryHookInput() request.username = username request.current_app = current_app request.default_expiry = default_expiry out = self.server.invoke(expiry_hook, request=request.to_dict(), serialize=False) out = out['expiry'] out = int(out) except Exception: logger.info('Caught an exception when invoking expiry hook service `%s` -> `%s`', expiry_hook, format_exc()) finally: return out # ################################################################################################################################ def _get(self, session, ust, current_app, remote_addr, ctx_source, needs_decrypt=True, renew=False, needs_attrs=False, user_agent=None, check_if_password_expired=True, _now=datetime.utcnow, _opaque=GENERIC.ATTR_NAME, skip_sec=False) -> 'SessionModel | bool': """ Verifies if input user session token is valid and if the user is allowed to access current_app. On success, if renew is True, renews the session. Returns all session attributes or True, depending on needs_attrs's value. """ # type: (object, str, str, bool, bool, bool, bool, datetime, str) -> object now = _now() ctx = VerifyCtx(self.decrypt_func(ust) if needs_decrypt else ust, remote_addr, current_app) # Look up user and raise exception if not found by input UST sso_info = self._get_session_by_ust(session, ctx.ust, now) # Invalid UST or the session has already expired but in either case # we can not access it. if not sso_info: raise ValidationError(status_code.session.no_such_session, False) if skip_sec: return sso_info if needs_attrs else True else: # Common auth checks self.user_checker.check(ctx, sso_info, check_if_password_expired) # Everything is validated, we can renew the session, if told to. if renew: # Update current interaction details for this session opaque = getattr(sso_info, _opaque) or {} session_state_change_list = self._extract_session_state_change_list(sso_info) _ = self.update_session_state_change_list(session_state_change_list, remote_addr, user_agent, ctx_source, now) opaque['session_state_change_list'] = session_state_change_list # Set a new expiration time session_expiry = self._get_session_expiry_delta(ctx.current_app, sso_info.username) expiration_time = now + timedelta(minutes=session_expiry) session.execute( SessionModelUpdate().values({ 'expiration_time': expiration_time, GENERIC.ATTR_NAME: dumps(opaque), }).where( SessionModelTable.c.ust==ctx.ust )) return expiration_time else: # Indicate success return sso_info if needs_attrs else True # ################################################################################################################################ def verify(self, cid, target_ust, current_ust, current_app, remote_addr, user_agent=None) -> 'bool': """ Verifies a user session without renewing it. """ # PII audit comes first audit_pii.info(cid, 'session.verify', extra={'current_app':current_app, 'remote_addr':remote_addr}) _ = self.require_super_user(cid, current_ust, current_app, remote_addr) try: with closing(self.odb_session_func()) as session: return self._get(session, target_ust, current_app, remote_addr, 'verify', renew=False, user_agent=user_agent) except Exception: logger.warning('Could not verify UST, e:`%s`', format_exc()) return False # ################################################################################################################################ def renew(self, cid, ust, current_app, remote_addr, user_agent=None, needs_decrypt=True) -> 'datetime': """ Renew timelife of a user session, if it is valid, and returns its new expiration time in UTC. """ # PII audit comes first audit_pii.info(cid, 'session.renew', extra={'current_app':current_app, 'remote_addr':remote_addr}) with closing(self.odb_session_func()) as session: expiration_time = self._get( session, ust, current_app, remote_addr, 'renew', needs_decrypt=needs_decrypt, renew=True, user_agent=user_agent, check_if_password_expired=True) session.commit() return expiration_time # ################################################################################################################################ def get(self, cid, target_ust, current_ust, current_app, remote_addr, user_agent=None, check_if_password_expired=True) -> 'SessionEntity': """ Gets details of a session given by its UST on input, without renewing it. Must be called by a super-user. """ # PII audit comes first audit_pii.info(cid, 'session.get', extra={'current_app':current_app, 'remote_addr':remote_addr}) # Only super-users are allowed to call us current_session = self.require_super_user(cid, current_ust, current_app, remote_addr) # This returns all attributes .. session = self._get_session( target_ust, current_app, remote_addr, 'get', check_if_password_expired, user_agent=user_agent) # .. and we need to build a session entity with a few selected ones only out = SessionEntity() out.creation_time = session.creation_time out.expiration_time = session.expiration_time out.remote_addr = session.remote_addr out.user_agent = session.user_agent out.attr = AttrAPI(cid, current_session.user_id, current_session.is_super_user, current_app, remote_addr, self.odb_session_func, self.is_sqlite, self.encrypt_func, self.decrypt_func, session.user_id, session.ust) return out # ################################################################################################################################ def _get_session(self, ust, current_app, remote_addr, ctx_source, check_if_password_expired=True, user_agent=None) -> 'SessionEntity': """ An internal wrapper around self.get which optionally does not require super-user rights. """ with closing(self.odb_session_func()) as session: return self._get(session, ust, current_app, remote_addr, ctx_source, renew=False, needs_attrs=True, check_if_password_expired=check_if_password_expired, user_agent=user_agent) # ################################################################################################################################ def get_current_session(self, cid, current_ust, current_app, remote_addr, needs_super_user) -> 'SessionEntity': """ Returns current session info or raises an exception if it could not be found. Optionally, requires that a super-user be owner of current_ust. """ # PII audit comes first audit_pii.info(cid, 'session.get_current_session', extra={'current_app':current_app, 'remote_addr':remote_addr}) # Verify current session's very existence first .. current_session = self._get_session(current_ust, current_app, remote_addr, 'get_current_session') if not current_session: logger.warning('Could not verify session `%s` `%s` `%s` `%s`', current_ust, current_app, remote_addr, format_exc()) raise ValidationError(status_code.auth.not_allowed, True) # .. the session exists but it may be still the case that we require a super-user on input. if needs_super_user: if not current_session.is_super_user: logger.warning( 'Current UST does not belong to a super-user, cannot continue (session.get_current_session), ' + \ 'current user is `%s` `%s`', current_session.user_id, current_session.username) raise ValidationError(status_code.auth.not_allowed, True) return current_session # ################################################################################################################################ def _get_session_list_by_user_id(self, user_id, now=None) -> 'list_[SessionModel]': with closing(self.odb_session_func()) as session: result = get_session_list_by_user_id(session, user_id, now or datetime.utcnow()) for item in result: item.pop(GENERIC.ATTR_NAME, None) return result # ################################################################################################################################ def _get_session_list_by_ust(self, ust) -> 'list_[SessionModel]': now = datetime.utcnow() session = self.get_session_by_ust(ust, now) return self._get_session_list_by_user_id(session.user_id, now) # ################################################################################################################################ def get_list(self, cid, ust, target_ust, current_ust, current_app, remote_addr, _unused_user_agent=None) -> 'list_[SessionModel]': """ Returns a list of sessions. Regular users may receive basic information about their own sessions only whereas super-users may look up any other user's session list. """ # PII audit comes first audit_pii.info(cid, 'session.get_list', extra={'current_app':current_app, 'remote_addr':remote_addr}) # Local aliases has_ust = bool(ust) current_ust_elem = ust if has_ust else current_ust current_session = self.get_current_session(cid, current_ust_elem, current_app, remote_addr, False) # We return a list of sessions for currently logged in user if has_ust: return self._get_session_list_by_user_id(current_session.user_id) else: # If we are to return a list of sessions for another UST, we need to be a super-user if not current_session.is_super_user: logger.warning( 'Current UST does not belong to a super-user, cannot continue (session.get_list), current user is ' + \ '`%s` `%s`', current_session.user_id, current_session.username) raise ValidationError(status_code.auth.not_allowed, True) # If we are here, it means that we are a super-user and we are to return sessions # by another person's UST but there is still a chance that this other person is actually us. if current_ust == target_ust: return self._get_session_list_by_user_id(current_session.user_id) else: return self._get_session_list_by_ust(target_ust) # ################################################################################################################################ def require_super_user(self, cid, current_ust, current_app, remote_addr) -> 'SessionModel': """ Makes sure that current_ust belongs to a super-user or raises an exception if it does not. """ # PII audit comes first audit_pii.info(cid, 'session.require_super_user', extra={'current_app':current_app, 'remote_addr':remote_addr}) return self.get_current_session(cid, current_ust, current_app, remote_addr, True) # ################################################################################################################################ def logout(self, ust, current_app, remote_addr, skip_sec=False) -> 'None': """ Logs a user out of an SSO session. """ ust = self.decrypt_func(ust) with closing(self.odb_session_func()) as session: # Check that the session and user exist .. if self._get(session, ust, current_app, remote_addr, 'logout', needs_decrypt=False, renew=False, skip_sec=skip_sec): # .. and if so, delete the session now. session.execute( SessionModelDelete().\ where(SessionModelTable.c.ust==ust) ) session.commit() # ################################################################################################################################
33,579
Python
.py
568
48.373239
142
0.544921
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,979
__init__.py
zatosource_zato/code/zato-sso/src/zato/sso/odb/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
154
Python
.py
5
29.4
64
0.687075
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,980
query.py
zatosource_zato/code/zato-sso/src/zato/sso/odb/query.py
# -*- coding: utf-8 -*- """ Copyright (C) 2023, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from datetime import datetime # Bunch from bunch import bunchify # SQLAlchemy from sqlalchemy import or_ # Zato from zato.common.api import GENERIC from zato.common.json_internal import loads from zato.common.odb.model import SecurityBase, SSOPasswordReset, SSOLinkedAuth, SSOSession, SSOUser from zato.common.util.sql import elems_with_opaque from zato.sso import const # ################################################################################################################################ _utcnow = datetime.utcnow # ################################################################################################################################ _skip_user_columns = 'first_name_upper', 'middle_name_upper', 'last_name_upper', 'opaque1' _skip_session_list_columns = 'id', 'user_id' _user_id_column = [SSOUser.user_id] _user_basic_columns = [elem for elem in SSOUser.__table__.c if elem.name not in _skip_user_columns] _user_exists_columns = [SSOUser.user_id, SSOUser.username, SSOUser.email] _session_columns = [elem for elem in SSOSession.__table__.c] _session_list_columns = [elem for elem in SSOSession.__table__.c if elem.name not in _skip_session_list_columns] _session_columns_with_user = _session_columns + _user_basic_columns _approved = const.approval_status.approved # ################################################################################################################################ def _session_with_opaque(session, _opaque_attr=GENERIC.ATTR_NAME): if session: opaque = getattr(session, _opaque_attr, None) if opaque: opaque = loads(opaque) session = session._asdict() session[_opaque_attr] = opaque return bunchify(session) return session # ################################################################################################################################ def user_exists(session, username, email, check_email): """ Returns a boolean flag indicating whether user exists by username or email. """ if check_email: condition = or_(SSOUser.username==username, SSOUser.email==email) else: condition = SSOUser.username==username return session.query(*_user_exists_columns).\ filter(condition).\ first() # ################################################################################################################################ def _get_model(session, columns): return session.query(*columns) # ################################################################################################################################ def get_user_by_id(session, user_id, *ignored_args): return _get_model(session, _user_basic_columns).\ filter(SSOUser.user_id==user_id).\ first() # ################################################################################################################################ def _get_user_base_query(session, needs_approved=True, _approved=_approved): q = _get_model(session, _user_basic_columns) if needs_approved: q = q.filter(SSOUser.approval_status==_approved) return q # ################################################################################################################################ def get_user_by_name(session, username, needs_approved=True): # Get the base query .. q = _get_user_base_query(session, needs_approved) # .. filter by username .. q = q.filter(SSOUser.username==username) # .. and return the result. return q.first() # ################################################################################################################################ def get_user_by_email(session, email, needs_approved=True): # Get the base query .. q = _get_user_base_query(session, needs_approved) # .. filter by email .. q = q.filter(SSOUser.email==email) # .. and return the result. return q.first() # ################################################################################################################################ def get_user_by_name_or_email(session, credential, needs_approved=True): # Get the base query .. q = _get_user_base_query(session, needs_approved) # .. filter by username or email.. q = q.filter(or_( SSOUser.username==credential, SSOUser.email==credential, )) # .. and return the result. return q.first() # ################################################################################################################################ def _get_user_by_prt(session, prt, now): # Get the base query .. return session.query( SSOUser.user_id, SSOUser.password_expiry, SSOUser.username, SSOUser.is_locked, SSOUser.sign_up_status, SSOUser.approval_status, SSOUser.password_expiry, SSOUser.password_must_change, SSOPasswordReset.reset_key, ).\ filter(SSOPasswordReset.token == prt).\ filter(SSOUser.user_id == SSOPasswordReset.user_id).\ filter(SSOPasswordReset.expiration_time > now).\ filter(SSOPasswordReset.reset_key_exp_time > now) # ################################################################################################################################ def get_user_by_prt(session, prt, now): # Get the base query .. q = _get_user_by_prt(session, prt, now) # .. at this point, the password is still not reset # and we need to ensure that the PRT has not been accessed either .. q = q.\ filter(SSOPasswordReset.has_been_accessed.is_(False)).\ filter(SSOPasswordReset.is_password_reset.is_(False)) # .. and return the result. return q.first() # ################################################################################################################################ def get_user_by_prt_and_reset_key(session, prt, reset_key, now): # Get the base query .. q = _get_user_by_prt(session, prt, now) q = q.\ filter(SSOPasswordReset.reset_key == reset_key).\ filter(SSOPasswordReset.has_been_accessed.is_(True)).\ filter(SSOPasswordReset.is_password_reset.is_(False)) # .. and return the result. return q.first() # ################################################################################################################################ def get_user_by_linked_sec(session, query_criteria, *ignored_args): auth_type, auth_name = query_criteria q = session.query( *_user_basic_columns ).\ filter(SSOUser.user_id==SSOLinkedAuth.user_id).\ filter(SSOLinkedAuth.auth_type=='zato.{}'.format(auth_type)).\ filter(SecurityBase.name==auth_name).\ filter(SecurityBase.id==SSOLinkedAuth.auth_id) return q.first() # ################################################################################################################################ def _get_session(session, now, _columns=_session_columns_with_user, _approved=_approved): return _get_model(session, _columns).\ filter(SSOSession.user_id==SSOUser.id).\ filter(SSOUser.approval_status==_approved).\ filter(SSOSession.expiration_time > now) # ################################################################################################################################ def get_session_by_ext_id(session, ext_session_id, now): # type: (object, object, object) -> SSOSession result = _get_session(session, now).\ filter(SSOSession.ext_session_id==ext_session_id).\ first() return _session_with_opaque(result) # ################################################################################################################################ def _get_session_by_ust(session, ust, now): return _get_session(session, now).\ filter(SSOSession.ust==ust) # ################################################################################################################################ def get_session_list_by_user_id(session, user_id, now, _columns=_session_list_columns): return elems_with_opaque(_get_session(session, now, _columns).\ filter(SSOUser.user_id==user_id).\ all()) # ################################################################################################################################ def get_session_by_ust(session, ust, now): session = _get_session_by_ust(session, ust, now).\ first() return _session_with_opaque(session) get_user_by_ust = get_session_by_ust # ################################################################################################################################ def is_super_user_by_ust(session, ust, now=None): return _get_session_by_ust(session, ust, now or _utcnow(), _user_id_column).\ filter(SSOUser.is_super_user==True).\ first() # noqa: E712 # ################################################################################################################################ def get_sign_up_status_by_token(session, confirm_token): return session.query(SSOUser.sign_up_status).\ filter(SSOUser.sign_up_confirm_token==confirm_token).\ first() # ################################################################################################################################ def get_linked_auth_list(session, user_id=None, auth_id=None): q = session.query( SSOLinkedAuth.user_id, SSOLinkedAuth.is_active, SSOLinkedAuth.is_internal, SSOLinkedAuth.creation_time, SSOLinkedAuth.has_ext_principal, SSOLinkedAuth.auth_type, SSOLinkedAuth.auth_id, SSOLinkedAuth.auth_principal, SSOLinkedAuth.auth_source, ) if user_id: q = q.filter(SSOLinkedAuth.user_id==user_id) if auth_id: q = q.filter(SSOLinkedAuth.auth_id==auth_id) return q.all() # ################################################################################################################################ def get_rate_limiting_info(session): return session.query( SSOUser.user_id, SSOUser.rate_limit_def ).\ filter(SSOUser.is_rate_limit_active==True).\ all() # noqa: E712 # ################################################################################################################################
10,567
Python
.py
206
45.946602
130
0.472809
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,981
setup.py
zatosource_zato/code/zato-hl7/setup.py
# -*- coding: utf-8 -*- """ Copyright (C) 2019, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # flake8: noqa from setuptools import find_packages, setup from setuptools import setup, find_packages version = '3.2' setup( name = 'zato-hl7', version = version, author = 'Zato Source s.r.o.', author_email = 'info@zato.io', url = 'https://zato.io', package_dir = {'':'src'}, packages = find_packages('src'), namespace_packages = ['zato'], zip_safe = False, )
576
Python
.py
20
24.65
64
0.634369
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,982
__init__.py
zatosource_zato/code/zato-hl7/test/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
148
Python
.py
5
28.2
64
0.687943
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,983
__init__.py
zatosource_zato/code/zato-hl7/test/zato/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
148
Python
.py
5
28.2
64
0.687943
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,984
test_parser.py
zatosource_zato/code/zato-hl7/test/zato/hl7/test_parser.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from unittest import TestCase # Zato from zato.common.api import HL7 from zato.common.test.hl7_ import test_data from zato.hl7.parser import get_payload_from_request # ################################################################################################################################ # ################################################################################################################################ class ParserTestCase(TestCase): def test_get_payload_from_request(self): version = HL7.Const.Version.v2.id data_encoding = 'utf8' json_path = None should_parse_on_input = True should_validate = True result = get_payload_from_request(test_data, data_encoding, version, json_path, should_parse_on_input, should_validate) # # Check MSH # msh = result.MSH self.assertEqual(msh.field_separator.value, '|') # # Check EVN # evn = result.EVN self.assertEqual(evn.recorded_date_time.value, '200605290901') # # Check PID # pid = result.PID self.assertEqual(pid.patient_address.city.value, 'BIRMINGHAM') # # Check PV1 # pv1 = result.PV1 self.assertEqual(pv1.assigned_patient_location.facility.value, 'UABH') # ################################################################################################################################ # ################################################################################################################################
1,801
Python
.py
43
35.534884
130
0.437931
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,985
__init__.py
zatosource_zato/code/zato-hl7/test/zato/hl7/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
148
Python
.py
5
28.2
64
0.687943
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,986
__init__.py
zatosource_zato/code/zato-hl7/src/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
148
Python
.py
5
28.2
64
0.687943
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,987
__init__.py
zatosource_zato/code/zato-hl7/src/zato/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from pkgutil import extend_path __path__ = extend_path(__path__, __name__) __import__('pkg_resources').declare_namespace(__name__)
281
Python
.py
8
33.625
64
0.684015
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,988
__init__.py
zatosource_zato/code/zato-hl7/src/zato/hl7/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from pkgutil import extend_path __path__ = extend_path(__path__, __name__) __import__('pkg_resources').declare_namespace(__name__)
281
Python
.py
8
33.625
64
0.684015
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,989
parser.py
zatosource_zato/code/zato-hl7/src/zato/hl7/parser.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from logging import getLogger from traceback import format_exc # hl7apy from hl7apy.parser import parse_message as hl7apy_parse_message # Zato from zato.common.api import HL7 from zato.common.hl7 import HL7Exception # ################################################################################################################################ # ################################################################################################################################ if 0: from hl7apy.core import Message from zato.common.typing_ import any_, boolnone # ################################################################################################################################ # ################################################################################################################################ logger = getLogger('zato') logger_hl7 = getLogger('zato_hl7') # ################################################################################################################################ # ################################################################################################################################ # Maps HL7 versions and implementation classes to parse functions. _parse_func_map = { HL7.Const.Version.v2.id: { HL7.Const.ImplClass.hl7apy: hl7apy_parse_message } } _impl_class = HL7.Const.ImplClass.hl7apy # ################################################################################################################################ # ################################################################################################################################ def get_payload_from_request( data, # type: str data_encoding, # type: str hl7_version, # type: str _ignored_json_path, # type: boolnone _ignored_should_parse_on_input, # type: boolnone should_validate # type: bool ) -> 'Message': """ Parses a channel message into an HL7 one. """ try: # We always require str objects .. if isinstance(data, bytes): data = data.decode(data_encoding) # .. now, parse and return the result. return parse(data, _impl_class, hl7_version, should_validate) except Exception as e: msg = 'Caught an HL7 exception while handling data:`%s` (%s); e:`%s`' logger.warning(msg, repr(data), repr(data_encoding), format_exc()) raise HL7Exception('HL7 exception', data, e) # ################################################################################################################################ def parse( data, # type: str impl_class, # type: any_ hl7_version, # type: str should_validate # type: bool ) -> 'Message': """ Parses input data in the specified HL7 version using implementation pointed to be impl_class. """ impl_dict = _parse_func_map[hl7_version] # type: dict parse_func = impl_dict[impl_class] return parse_func(data, force_validation=should_validate) # ################################################################################################################################ # ################################################################################################################################
3,481
Python
.py
67
48.134328
130
0.387268
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,990
common.py
zatosource_zato/code/zato-hl7/src/zato/hl7/common.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # Zato from zato.common.api import HL7 # ################################################################################################################################ # ################################################################################################################################ impl_class_all = {HL7.Const.ImplClass.hl7apy, HL7.Const.ImplClass.zato} impl_class_current = {HL7.Const.ImplClass.hl7apy} # ################################################################################################################################ # ################################################################################################################################
841
Python
.py
13
63.230769
130
0.270073
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,991
client.py
zatosource_zato/code/zato-hl7/src/zato/hl7/mllp/client.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib import socket from logging import getLogger from traceback import format_exc # Zato from zato.common.util.api import new_cid from zato.common.util.tcp import parse_address, read_from_socket, SocketReaderCtx # ################################################################################################################################ if 0: from socket import AddressFamily, socket as Socket, SocketKind from bunch import Bunch from zato.common.typing_ import any_, type_ # ################################################################################################################################ # ################################################################################################################################ logger = getLogger('zato') # ################################################################################################################################ # ################################################################################################################################ class HL7MLLPClient: """ An HL7 MLLP client for sending data to remote endpoints. """ config: 'Bunch' name: 'str' address: 'str' max_wait_time: 'int' max_msg_size: 'int' read_buffer_size: 'int' recv_timeout: 'float' should_log_messages: 'bool' host: 'str' port: 'str' def __init__(self, config:'any_') -> 'None': # Zato from zato.common.util.api import hex_sequence_to_bytes self.config = config self.name = config.name self.address = config.address self.max_wait_time = int(config.max_wait_time) self.max_msg_size = int(config.max_msg_size) self.read_buffer_size = int(config.read_buffer_size) self.recv_timeout = int(config.recv_timeout) / 1000.0 self.should_log_messages = config.should_log_messages self.start_seq = hex_sequence_to_bytes(config.start_seq) self.end_seq = hex_sequence_to_bytes(config.end_seq) self.host, self.port = parse_address(self.address) # ################################################################################################################################ def send( self, data, # type: bytes | str _socket_socket=socket.socket, # type: type_[Socket] _family=socket.AF_INET, # type: AddressFamily _type=socket.SOCK_STREAM # type: SocketKind ) -> 'bytes': try: data = data if isinstance(data, bytes) else data.encode('utf8') # Wrap the message in an MLLP envelope msg = self.start_seq + data + self.end_seq # This will auto-close the socket .. with _socket_socket(_family, _type) as sock: # .. connect to the remote end .. sock.connect((self.host, self.port)) # .. send our data .. _ = sock.send(msg) # .. encapsulate configuration for our socket reader function .. ctx = SocketReaderCtx( new_cid(), sock, self.max_wait_time, self.max_msg_size, self.read_buffer_size, self.recv_timeout, self.should_log_messages ) # .. wait for the response .. response = read_from_socket(ctx) if self.should_log_messages: logger.info('Response received `%s`', response) return response except Exception: logger.warning('Client caught an exception while sending HL7 MLLP data to `%s (%s)`; e:`%s`', self.name, self.address, format_exc()) raise # ################################################################################################################################ # ################################################################################################################################ def send_data(address:'str', data:'bytes') -> 'bytes': """ Sends input data to a remote address by its configuration. """ # Bunch from bunch import bunchify config = bunchify({ 'name': 'My HL7MLLPClient', 'address': address, 'start_seq': '0b', 'end_seq': '1c 0d', 'max_wait_time': 3, 'max_msg_size': 2_000_000, 'read_buffer_size': 2048, 'recv_timeout': 250, 'should_log_messages': True, }) client = HL7MLLPClient(config) response = client.send(data) return response # ################################################################################################################################ # ################################################################################################################################ if __name__ == '__main__': import logging from zato.common.api import HL7 from zato.common.test.hl7_ import test_data log_level = logging.DEBUG log_format = '%(asctime)s - %(levelname)s - %(process)d:%(threadName)s - %(name)s:%(lineno)d - %(message)s' logging.basicConfig(level=log_level, format=log_format) logger = logging.getLogger(__name__) channel_port = HL7.Default.channel_port address = f'localhost:{channel_port}' logger.info('Sending HL7v2 to %s', address) _ = send_data(address, test_data) # ################################################################################################################################ # ################################################################################################################################
5,874
Python
.py
123
39.739837
130
0.434303
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,992
api.py
zatosource_zato/code/zato-hl7/src/zato/hl7/mllp/api.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
148
Python
.py
5
28.2
64
0.687943
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,993
__init__.py
zatosource_zato/code/zato-hl7/src/zato/hl7/mllp/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
148
Python
.py
5
28.2
64
0.687943
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,994
server.py
zatosource_zato/code/zato-hl7/src/zato/hl7/mllp/server.py
# -*- coding: utf-8 -*- """ Copyright (C) Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # stdlib from logging import DEBUG, getLevelName, getLogger from socket import timeout as SocketTimeoutException from time import sleep from traceback import format_exc # hl7apy from hl7apy.core import Message # Zato from zato.common.api import GENERIC, HL7 from zato.common.audit_log import DataReceived, DataSent from zato.common.typing_ import cast_ from zato.common.util.api import new_cid from zato.common.util.tcp import get_fqdn_by_ip, ZatoStreamServer # ################################################################################################################################ # ################################################################################################################################ if 0: from logging import Logger from socket import socket as Socket from bunch import Bunch from zato.common.audit_log import AuditLog from zato.common.typing_ import any_, anydict, anylist, anytuple, boolnone, byteslist, bytesnone, callable_, type_ # ################################################################################################################################ # ################################################################################################################################ conn_type = GENERIC.CONNECTION.TYPE.CHANNEL_HL7_MLLP server_type = 'HL7 MLLP' # ################################################################################################################################ def new_conn_id( pattern='zhc{}', # type: str id_len=5, # type: int _new_cid=new_cid # type: callable_ ) -> 'str': return pattern.format(_new_cid(id_len)) # ################################################################################################################################ def new_msg_id( pattern='zhl7{}', # type: str id_len=6, # type: int _new_cid=new_cid # type: callable_ ) -> 'str': return pattern.format(_new_cid(id_len)) class HandleCompleteMessageArgs: _buffer: 'anylist' _buffer_join_func: 'callable_' conn_ctx: 'ConnCtx' request_ctx: 'RequestCtx' _socket_send: 'callable_' _run_callback: 'callable_' _request_ctx_reset: 'callable_' # ################################################################################################################################ # ################################################################################################################################ class ConnCtx: """ Details of an individual remote connection to a server. """ conn_id: 'str' conn_name: 'str' socket: 'Socket' peer_ip: 'str' peer_port: 'str' peer_fqdn: 'str' local_ip: 'str' local_port: 'int' local_fqdn: 'str' stats_per_msg_type: 'anydict' total_message_packets_received: 'int' total_messages_received: 'int' def __init__( self, conn_name, # type: str socket, # type: Socket peer_address, # type: anytuple _new_conn_id=new_conn_id # type: callable_ ) -> 'None': self.conn_id = _new_conn_id() self.conn_name = conn_name self.socket = socket self.peer_ip = peer_address[0] self.peer_port = peer_address[1] # Statistics broken down by each message type, e.g. ADT self.stats_per_msg_type = {} # Total message packets received self.total_message_packets_received = 0 # Total full messages received, no matter their type self.total_messages_received = 0 self.peer_fqdn = get_fqdn_by_ip(self.peer_ip, 'peer', server_type) self.local_ip, self.local_port, self.local_fqdn = self._get_local_conn_info('local') # ################################################################################################################################ def get_conn_pretty_info(self): return '{}; `{}:{}` ({}) to `{}:{}` ({}) ({})'.format( self.conn_id, self.peer_ip, self.peer_port, self.peer_fqdn, self.local_ip, self.local_port, self.local_fqdn, self.conn_name, ) # ################################################################################################################################ def _get_local_conn_info(self, default_local_fqdn:'str') -> 'anytuple': local_ip, local_port = self.socket.getsockname() local_fqdn = get_fqdn_by_ip(local_ip, default_local_fqdn, server_type) return local_ip, local_port, local_fqdn # ################################################################################################################################ # ################################################################################################################################ class RequestCtx: """ Details of an individual request message received from a remote connection. """ __slots__ = 'msg_id', 'conn_id', 'msg_size', 'data', 'meta', 'response' msg_id: 'str' conn_id: 'str' msg_size: 'int' data: 'bytes' meta: 'anydict' response: 'ResponseCtx' # ################################################################################################################################ def __init__(self): self.conn_id = '<conn-id-not-given>' self.data = b'' self.meta = {} self.reset() # ################################################################################################################################ def reset( self, _new_msg_id=new_msg_id # type: callable_ ) -> 'None': self.msg_id = _new_msg_id() self.msg_size = 0 self.data = b'' self.meta['has_start_seq'] = False self.meta['has_end_seq'] = False # ################################################################################################################################ def to_dict(self): return { 'conn_id': self.conn_id, 'msg_id': self.msg_id, 'msg_size': self.msg_size, 'data': self.data, } # ################################################################################################################################ # ################################################################################################################################ class ResponseCtx: pass # ################################################################################################################################ # ################################################################################################################################ class HL7MLLPServer: """ Each instance of this class handles an individual HL7 MLLP connection in handle_connection. """ config: 'Bunch' callback_func: 'callable_' # We will never read less than that many bytes from client sockets min_read_buffer_size: 'int' = 2048 # This is configurable by users read_buffer_size: 'int' object_id: 'str' name: 'str' address: 'str' service_name: 'str' audit_log: 'AuditLog' should_log_messages: 'bool' start_seq: 'str' start_seq_len: 'int' start_seq_len_eq_one: 'bool' end_seq: 'str' end_seq_len: 'int' is_audit_log_sent_active: 'bool' is_audit_log_received_active: 'bool' keep_running: 'bool' impl: 'ZatoStreamServer' logger_zato: 'Logger' logger_hl7: 'Logger' _logger_info: 'callable_' _logger_warn: 'callable_' _logger_debug: 'callable_' _has_debug_log: 'bool' def __init__( self, config, # type: Bunch callback_func, # type: callable_ audit_log # type: AuditLog ) -> 'None': self.config = config self.callback_func = callback_func self.object_id = config.id self.audit_log = audit_log self.address = config.address self.name = config.name self.service_name = config.service_name self.should_log_messages = config.should_log_messages self.read_buffer_size = int(cast_('str', config.read_buffer_size)) self.start_seq = cast_('str', config.start_seq) self.start_seq_len = len(self.start_seq) self.start_seq_len_eq_one = self.start_seq_len == 1 self.end_seq = cast_('str', config.end_seq) self.end_seq_len = len(self.end_seq) self.is_audit_log_sent_active = config.get('is_audit_log_sent_active') or False self.is_audit_log_received_active = config.get('is_audit_log_received_active') or False self.keep_running = True self.logger_zato = getLogger('zato') self.logger_hl7 = getLogger('zato_hl7') self.logger_hl7.setLevel(getLevelName(cast_('str', config.logging_level))) self._logger_info = self.logger_hl7.info self._logger_warn = self.logger_hl7.warn self._logger_debug = self.logger_hl7.debug self._has_debug_log = self.logger_hl7.isEnabledFor(DEBUG) # ################################################################################################################################ def _log_start_stop(self, is_start:'bool') -> 'None': msg = 'Starting' if is_start else 'Stopping' pattern = '%s %s connection `%s` (%s)' args = (msg, server_type, self.name, self.address) self._logger_info(pattern, *args) self.logger_zato.info(pattern, *args) # ################################################################################################################################ def start(self): # Create a new server connection .. self.impl = ZatoStreamServer(self.address, self.handle) # .. log info that we are starting .. self._log_start_stop(True) # .. and start to serve. self.impl.serve_forever() # ################################################################################################################################ def stop(self): # Log info that we are stopping .. self._log_start_stop(False) # .. and actually stop. self.keep_running = False self.impl.stop() # ################################################################################################################################ def handle(self, socket:'Socket', peer_address:'anytuple') -> 'None': try: self._handle(socket, peer_address) except Exception: self.logger_hl7.warning('Exception in %s (%s %s); e:`%s`', self._handle, socket, peer_address, format_exc()) raise # ################################################################################################################################ def _handle(self, socket:'Socket', peer_address:'anytuple') -> 'None': # Wraps all the metadata about the connection conn_ctx = ConnCtx(self.name, socket, peer_address) self._logger_info('Waiting for HL7 MLLP data from %s', conn_ctx.get_conn_pretty_info()) # Current message whose contents we are accumulating _buffer = [] # Details of the current message request_ctx = RequestCtx() request_ctx.conn_id = conn_ctx.conn_id # To indicate if message header is already checked or not _needs_header_check = True # To make fewer namespace lookups _max_msg_size = int(cast_('str', self.config.max_msg_size)) _recv_timeout = self.config.recv_timeout # type: float # We do not want for this to be too small _read_buffer_size = max(self.read_buffer_size, self.min_read_buffer_size) _has_debug_log = self._has_debug_log _log_debug = self._logger_debug _run_callback = self._run_callback _check_header = self._check_header _close_connection = self._close_connection _request_ctx_reset = request_ctx.reset _buffer_append = _buffer.append _buffer_len = _buffer.__len__ _buffer_join_func = b''.join _socket_recv = conn_ctx.socket.recv _socket_send = conn_ctx.socket.send _socket_settimeout = conn_ctx.socket.settimeout _handle_complete_message_args = HandleCompleteMessageArgs() _handle_complete_message_args._buffer = _buffer _handle_complete_message_args._buffer_join_func = _buffer_join_func _handle_complete_message_args.conn_ctx = conn_ctx _handle_complete_message_args.request_ctx = request_ctx _handle_complete_message_args._socket_send = _socket_send _handle_complete_message_args._run_callback = _run_callback _handle_complete_message_args._request_ctx_reset = _request_ctx_reset # Run the main loop while self.keep_running: try: # In each iteration, assume that no data was received data = None # Check whether reading the data would not exceed our message size limit new_size = request_ctx.msg_size + _read_buffer_size if new_size > _max_msg_size: reason = 'message would exceed max. size allowed `{}` > `{}`'.format(new_size, _max_msg_size) _close_connection(conn_ctx, reason) return # Receive data from the other end _socket_settimeout(_recv_timeout) # Try to receive some data from the socket .. try: # .. read data in .. data = _socket_recv(_read_buffer_size) # .. update counters .. conn_ctx.total_message_packets_received += 1 if _has_debug_log: _log_debug('HL7 MLLP data received by `%s` (%d) -> `%s`', conn_ctx.conn_id, len(data), data) # .. catch timeouts here but no other exception type .. except SocketTimeoutException: # That is fine, we simply did not get any data in this iteration pass # .. no timeout = we may have received some data from the socket .. else: # .. something was received so we can append it to our buffer .. if data: # If we are here, it means that the recv call succeeded so we can increase the message size # by how many bytes were actually read from the socket. request_ctx.msg_size += len(data) # At this point we either do not have all the bytes required to check the header # or the header is already checked, so we can just append data to our current buffer .. _buffer_append(data) # The first byte may be a header and we need to check whether we require it or not at this stage of parsing. # This method will close the connection if anything to do with header parsing is invalid. if _needs_header_check: # If we have a single-byte header, we can check it immediately. This is because # we received some data, which means one byte at the very least, so we can go ahead # with checking the header .. if self.start_seq_len_eq_one: if not _check_header(conn_ctx, request_ctx, data): return else: _needs_header_check = False # .. but if we have a multi-byte header, we need to ensure we have already # read as many bytes as there are in the expected header. We do it by iterating # over the buffer of bytes received so far and concatenating them until we have # at least as many bytes as there are in the header to check. else: to_check_buffer = [] # type: byteslist to_check_len = 0 # Go through each, potentially multi-byte, element in the buffer so far .. for elem in _buffer: elem = cast_('bytes', elem) # .. break if we have already all the bytes that we need .. if to_check_len >= self.start_seq_len: break # .. otherwise, append bytes from the current element # and increase the bytes read so far counter. else: to_check_buffer.append(elem) to_check_len += len(elem) # We still need to check if we have the full header worth of bytes already .. if to_check_len >= self.start_seq_len: # .. and if we do, we can look up the header now. to_check = b''.join(to_check_buffer) if not _check_header(conn_ctx, request_ctx, to_check): return else: _needs_header_check = False else: # .. otherwise, if we do not have enough bytes, # we do nothing and this block is added to make it explicit that it is the case. pass # .. the line that have just received may have been part of a trailer # or the trailer itself so we need to check it .. # .. but we need to take into account the fact that the trailer has been split into two or more # segments. For instance, the previous segment of bytes returned by _socket_recv # ended with the first byte of end_seq and now we have received the second byte. # E.g. our _read_buffer_size is 2048 and if the overall message happens to be 2049 bytes # then the first byte of end_seq will be in the buffer already and the data currently # received contains the second byte. Note that if someone uses end_seq longer than two bytes # this will still work because our _read_buffer_size is always at least 2048 bytes # so end_seq may be split across two segments at most (unless someone uses a multi-kilobyte end_seq, # which is not something to be expected). # First, try to check if data currently received ends in end_seq .. if self._points_to_full_message(data): # .. even if it does, make sure we have a header already and reject the message otherwise .. if _needs_header_check: reason = 'end bytes `{}` received without a preceeding header `{}` (#1)'.format( self.end_seq, self.start_seq) self._close_connection(conn_ctx, reason) return # .. it is a match so it means that data was the last part of a message that we can already process .. self._handle_complete_message(_handle_complete_message_args) # .. otherwise, try to check if in combination with the previous segment, # the data received now points to a full message. However, for this to work # we require that there be at least one previous segment - otherwise we are the first one # and if we were the ending one we would have been caught in the if above .. else: if _buffer_len() > 1: # Index -1 is our own segment (data) previously appended, # which is why we use -2 to get the segment preceeding it. last_data = _buffer[-2] # type: bytes concatenated = last_data + data # .. now that we have it concatenated, check if that indicates that a full message # is already received. if self._points_to_full_message(concatenated): # Again, even if it does but have not received the header yet, # we need to reject the whole message. if _needs_header_check: reason = 'end bytes `{}` received without a preceeding header `{}` (#2)'.format( self.end_seq, self.start_seq) self._close_connection(conn_ctx, reason) return self._handle_complete_message(_handle_complete_message_args) # No data received = remote end is no longer connected. else: reason = 'remote end disconnected; `{}`'.format(data) _close_connection(conn_ctx, reason) return # This covers the whole body of the 'while' block, # catching everything that was raised in a given loop's iteration. except Exception: # Log the exception .. exc = format_exc() self.logger_hl7.warning(exc) # .. and sleep for a while in case we cannot re-enter the loop immediately. sleep(2) # ################################################################################################################################ def _points_to_full_message(self, data:'bytes') -> 'bool': """ Returns True if input bytes indicate that we have a full message from the socket. """ # Get as many bytes from data as we expected for our end_seq to be the length of .. data_last_bytes = data[-self.end_seq_len:] # .. return True if the last bytes point to our having a complete message to process. return data_last_bytes == self.end_seq # ################################################################################################################################ def _handle_complete_message(self, args:'HandleCompleteMessageArgs') -> 'None': # Produce the message to invoke the callback with .. _buffer_data = args._buffer_join_func(args._buffer) # .. remove the header and trailer .. _buffer_data = _buffer_data[self.start_seq_len:-self.end_seq_len] # .. asign the actual business data to message .. args.request_ctx.data = _buffer_data # .. update our runtime metadata first (data received) .. if self.is_audit_log_received_active: self._store_data_received(args.request_ctx) # .. update counters .. args.conn_ctx.total_messages_received += 1 # .. invoke the callback .. response = args._run_callback(args.conn_ctx, args.request_ctx) or b'' # .. optionally, log what we are about to send .. if self.should_log_messages: self._logger_info('Sending HL7 MLLP response to `%s` -> `%s` (c:%s; s=%d)', args.request_ctx.msg_id, response, args.conn_ctx.conn_id, len(response)) # .. write the response back .. args._socket_send(response) # .. update our runtime metadata first (data sent) .. if self.is_audit_log_sent_active: self._store_data_sent(args.request_ctx, response) # .. and reset the message to make it possible to handle a new one. args._request_ctx_reset() # ################################################################################################################################ def _store_data( self, request_ctx, # type: RequestCtx _DataEventClass, # type: type_[DataSent | DataReceived] response=None, # type: bytes | None _conn_type=conn_type # type: str ) -> 'None': # Create and fill out details of the new event .. data_event = _DataEventClass() data_event.data = response or request_ctx.data data_event.type_ = _conn_type data_event.object_id = self.object_id data_event.conn_id = request_ctx.conn_id data_event.msg_id = request_ctx.msg_id # .. and store it in our log. self.audit_log.store_data(data_event) # ################################################################################################################################ def _store_data_received(self, request_ctx:'RequestCtx', event_class:'type_[DataReceived]'=DataReceived): self._store_data(request_ctx, event_class) # ################################################################################################################################ def _store_data_sent(self, request_ctx:'RequestCtx', response:'bytes', event_class:'type_[DataSent]'=DataSent): self._store_data(request_ctx, event_class, response) # ################################################################################################################################ def _run_callback(self, conn_ctx:'ConnCtx', request_ctx:'RequestCtx', _hl7_v2:'str'=HL7.Const.Version.v2.id) -> 'bytesnone': pattern = 'Handling new HL7 MLLP message (%s; m:%s (s=%s), c:%s, p:%s; %s); `%r`' log_request = request_ctx.to_dict() if self.should_log_messages else '<masked>' self._logger_info( pattern, conn_ctx.conn_id, request_ctx.msg_id, request_ctx.msg_size, conn_ctx.total_messages_received, conn_ctx.total_message_packets_received, self.service_name, log_request ) try: response = self.callback_func( self.config.service_name, request_ctx.data, data_format = _hl7_v2, zato_ctx = { 'zato.channel_item': { 'data_encoding': 'utf8', 'hl7_version': _hl7_v2, 'json_path': None, 'should_parse_on_input': True, 'should_validate': True, 'hl7_mllp_conn_ctx': conn_ctx, } } ) except Exception: self._logger_warn('Error while invoking `%s` with msg_id `%s`; e:`%s`', self.service_name, request_ctx.msg_id, format_exc()) else: # Convert high-level objects to bytes .. if isinstance(response, Message): response = response.to_er7() # .. and make sure we actually do use bytes objects .. if not isinstance(response, bytes): response = response.encode('utf8') # .. and return the response to our caller. return response # ################################################################################################################################ def _close_connection(self, conn_ctx:'ConnCtx', reason:'str') -> 'None': self._logger_info('Closing connection; %s; %s', reason, conn_ctx.get_conn_pretty_info()) conn_ctx.socket.close() # ################################################################################################################################ def _check_meta( self, conn_ctx, # type: ConnCtx request_ctx, # type: RequestCtx data, # type: bytes bytes_to_check, # type: bytes meta_attr, # type: str has_meta_attr, # type: str meta_seq # type: str ) -> 'boolnone': # If we already have the meta element then we do not expect another one # while we are still processing the same message and if one is found, we close the connection. if request_ctx.meta[has_meta_attr]: if bytes_to_check == meta_seq: reason = 'unexpected {} found `{!r}` == `{!r}` in data `{!r}`'.format(meta_attr, bytes_to_check, meta_seq, data) self._close_connection(conn_ctx, reason) return # If we do not have the element, it must be a new message that we are receiving. # In such a case, we expect for it to begin with a header. Otherwise, we reject the entire connection. else: if bytes_to_check != meta_seq: reason = '{} mismatch `{!r}` != `{!r}` in data `{!r}`'.format(meta_attr, bytes_to_check, meta_seq, data) self._close_connection(conn_ctx, reason) return # If we are here, it means that the meta attribute is correct request_ctx.meta[has_meta_attr] = True return True # ################################################################################################################################ def _check_header(self, conn_ctx:'ConnCtx', request_ctx:'RequestCtx', data:'bytes') -> 'boolnone': bytes_to_check = data[:self.start_seq_len] meta_attr = 'header' has_meta_attr = 'has_start_seq' meta_seq = self.start_seq return self._check_meta(conn_ctx, request_ctx, data, bytes_to_check, meta_attr, has_meta_attr, meta_seq) # ################################################################################################################################ # ################################################################################################################################ def main(): # stdlib import logging from time import sleep # Bunch from bunch import bunchify # Zato from zato.common.api import HL7 from zato.common.audit_log import AuditLog, LogContainerConfig log_level = logging.DEBUG log_format = '%(asctime)s - %(levelname)s - %(process)d:%(threadName)s - %(name)s:%(lineno)d - %(message)s' logging.basicConfig(level=log_level, format=log_format) logger = logging.getLogger(__name__) def on_message(*args:'any_', **kwargs:'any_') -> 'str': logger.info('Args: %s', args) logger.info('Kwargs: %s', kwargs) return 'Hello from HL7v2' channel_port = HL7.Default.channel_port address = f'0.0.0.0:{channel_port}' config = bunchify({ 'id': '123', 'name': 'Hello HL7 MLLP', 'address': address, 'service_name': 'pub.zato.ping', 'max_msg_size': 1_000_000, 'read_buffer_size': 2048, 'recv_timeout': 0.25, 'logging_level': 'DEBUG', 'should_log_messages': True, 'start_seq': b'\x0b', 'end_seq': b'\x1c\x0d', }) log_container_config = LogContainerConfig() audit_log = AuditLog() audit_log.create_container(log_container_config) server = HL7MLLPServer(config, on_message, audit_log) server.start() while True: print(1) sleep(1) # ################################################################################################################################ if __name__ == '__main__': _ = main() # ################################################################################################################################
32,285
Python
.py
583
43.111492
132
0.476893
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,995
setup.py
zatosource_zato/code/zato-testing/setup.py
# -*- coding: utf-8 -*- """ Copyright (C) 2020, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ # flake8: noqa from setuptools import setup, find_packages version = '3.2' setup( name = 'zato-testing', version = version, author = 'Zato Source s.r.o.', author_email = 'info@zato.io', url = 'https://zato.io', package_dir = {'':'src'}, packages = find_packages('src'), namespace_packages = ['zato'], zip_safe = False, )
536
Python
.py
19
23.894737
64
0.61811
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,996
__init__.py
zatosource_zato/code/zato-testing/src/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2020, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """
154
Python
.py
5
29.4
64
0.687075
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,997
__init__.py
zatosource_zato/code/zato-testing/src/zato/__init__.py
# -*- coding: utf-8 -*- """ Copyright (C) 2020, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from pkgutil import extend_path __path__ = extend_path(__path__, __name__) __import__('pkg_resources').declare_namespace(__name__)
287
Python
.py
8
34.375
64
0.683636
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,998
vault_.py
zatosource_zato/code/zato-testing/src/zato/testing/vault_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2020, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # ################################################################################################################################ # ################################################################################################################################
501
Python
.py
8
61.125
130
0.341513
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)
9,999
requests_.py
zatosource_zato/code/zato-testing/src/zato/testing/requests_.py
# -*- coding: utf-8 -*- """ Copyright (C) 2020, Zato Source s.r.o. https://zato.io Licensed under AGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # Bunch from bunch import bunchify # Zato from zato.url_dispatcher import Matcher # ################################################################################################################################ # ################################################################################################################################ class Response: def __init__(self, data): self.data = data self.status_code = 200 def json(self): return self.data # ################################################################################################################################ # ################################################################################################################################ class RequestsAdapter: def __init__(self): self._get_handlers = [] self._post_handlers = [] # ################################################################################################################################ def _on_request(self, path, config, args, kwargs): # type: (str, list) -> Response for item in config: matcher = item['matcher'] # type: Matcher if matcher.match(path) is not None: func = item['func'] data = func(path, args=args, kwargs=bunchify(kwargs)) return Response(data) else: raise KeyError(path) # ################################################################################################################################ def get(self, path, *args, **kwargs): # type: (...) -> Response return self._on_request(path, self._get_handlers, args, kwargs) # ################################################################################################################################ def post(self, path, *args, **kwargs): # type: (...) -> Response return self._on_request(path, self._post_handlers, args, kwargs) # ################################################################################################################################ def _add_handler(self, path, func, config): # type: (str, object, list) config.append({ 'path': path, 'matcher': Matcher(path), 'func': func, }) # ################################################################################################################################ def add_get_handler(self, path, func): self._add_handler(path, func, self._get_handlers) # ################################################################################################################################ def add_post_handler(self, path, func): self._add_handler(path, func, self._post_handlers) # ################################################################################################################################ # ################################################################################################################################
3,299
Python
.py
59
49.559322
130
0.307836
zatosource/zato
1,096
239
0
AGPL-3.0
9/5/2024, 5:10:54 PM (Europe/Amsterdam)