jaaql-middleware-python 5.3.21__tar.gz → 5.3.22__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/PKG-INFO +1 -1
  2. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/constants.py +4 -1
  3. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/db/db_pg_interface.py +7 -4
  4. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/db/db_utils.py +10 -1
  5. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/db/db_utils_no_circ.py +4 -1
  6. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/mvc/handmade_queries.py +14 -0
  7. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/mvc/model.py +38 -12
  8. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/scripts/03.install_super_user.handwritten.sql +7 -0
  9. jaaql_middleware_python-5.3.22/jaaql/test/test_call_proc.py +214 -0
  10. jaaql_middleware_python-5.3.22/jaaql/test/test_execute.py +61 -0
  11. jaaql_middleware_python-5.3.22/jaaql/test/test_requested_database.py +130 -0
  12. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql_middleware_python.egg-info/PKG-INFO +1 -1
  13. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql_middleware_python.egg-info/SOURCES.txt +3 -0
  14. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/LICENSE.txt +0 -0
  15. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/README.md +0 -0
  16. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/__init__.py +0 -0
  17. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/config/__init__.py +0 -0
  18. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/config/config-docker.ini +0 -0
  19. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/config/config-test.ini +0 -0
  20. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/config/config.ini +0 -0
  21. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/config_constants.py +0 -0
  22. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/db/__init__.py +0 -0
  23. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/db/db_interface.py +0 -0
  24. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/documentation/__init__.py +0 -0
  25. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/documentation/documentation_internal.py +0 -0
  26. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/documentation/documentation_public.py +0 -0
  27. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/documentation/documentation_shared.py +0 -0
  28. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/email/__init__.py +0 -0
  29. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/email/email_manager.py +0 -0
  30. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/email/email_manager_service.py +0 -0
  31. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/email/patch_ems.py +0 -0
  32. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/exceptions/__init__.py +0 -0
  33. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/exceptions/custom_http_status.py +0 -0
  34. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/exceptions/http_status_exception.py +0 -0
  35. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/exceptions/jaaql_interpretable_handled_errors.py +0 -0
  36. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/exceptions/not_yet_implement_exception.py +0 -0
  37. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/generated_constants.py +0 -0
  38. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/interpreter/__init__.py +0 -0
  39. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/interpreter/interpret_jaaql.py +0 -0
  40. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/jaaql.py +0 -0
  41. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/migrations/__init__.py +0 -0
  42. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/migrations/migrations.py +0 -0
  43. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/mvc/__init__.py +0 -0
  44. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/mvc/base_controller.py +0 -0
  45. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/mvc/base_model.py +0 -0
  46. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/mvc/controller.py +0 -0
  47. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/mvc/controller_interface.py +0 -0
  48. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/mvc/exception_queries.py +0 -0
  49. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/mvc/generated_queries.py +0 -0
  50. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/mvc/model_interface.py +0 -0
  51. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/mvc/response.py +0 -0
  52. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/openapi/__init__.py +0 -0
  53. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/openapi/swagger_documentation.py +0 -0
  54. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/patch.py +0 -0
  55. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/scripts/01.install_domains.generated.sql +0 -0
  56. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/scripts/02.install_super_user.exceptions.sql +0 -0
  57. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/scripts/04.install_jaaql_data_structures.generated.sql +0 -0
  58. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/scripts/05.install_static_data.generated.sql +0 -0
  59. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/scripts/06.install_jaaql.exceptions.sql +0 -0
  60. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/scripts/ZZZZ.generated_functions_views_and_permissions.sql +0 -0
  61. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/scripts/ZZZZ.reset_references.sql +0 -0
  62. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/scripts/swagger_template.html +0 -0
  63. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/services/__init__.py +0 -0
  64. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/services/cached_canned_query_service.py +0 -0
  65. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/services/migrations_manager_service.py +0 -0
  66. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/services/patch_mms.py +0 -0
  67. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/services/patch_shared_var_service.py +0 -0
  68. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/services/shared_var_service.py +0 -0
  69. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/test/__init__.py +0 -0
  70. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/test/test_connection_lifecycle.py +0 -0
  71. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/test/test_timelines.py +0 -0
  72. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/utilities/__init__.py +0 -0
  73. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/utilities/bootstrap_secrets.py +0 -0
  74. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/utilities/cron.py +0 -0
  75. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/utilities/crypt_utils.py +0 -0
  76. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/utilities/options.py +0 -0
  77. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/utilities/utils.py +0 -0
  78. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/utilities/utils_no_project_imports.py +0 -0
  79. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql/utilities/vault.py +0 -0
  80. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql_middleware_python.egg-info/dependency_links.txt +0 -0
  81. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql_middleware_python.egg-info/requires.txt +0 -0
  82. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/jaaql_middleware_python.egg-info/top_level.txt +0 -0
  83. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/setup.cfg +0 -0
  84. {jaaql_middleware_python-5.3.21 → jaaql_middleware_python-5.3.22}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jaaql-middleware-python
3
- Version: 5.3.21
3
+ Version: 5.3.22
4
4
  Summary: The jaaql package, allowing for rapid development and deployment of RESTful HTTP applications
5
5
  Home-page: https://github.com/JAAQL/JAAQL-middleware-python
6
6
  Author: Software Quality Measurement and Improvement bv
@@ -63,6 +63,9 @@ CRON_dayOfWeek = "dayOfWeek"
63
63
 
64
64
  REGEX__dmbs_object_name = r'^[0-9a-zA-Z_]{1,63}$'
65
65
  REGEX__dmbs_procedure_name = r'^[0-9a-zA-Z_$-.\+]{1,63}$'
66
+ # An explicit type is spliced into the SQL after '::', so it must be a type name as FIESTA writes one and nothing more (use
67
+ # fullmatch): a realm name, or a Postgres datatype with an optional modifier, such as integer, numeric(4,2) or character varying(64)
68
+ REGEX__dmbs_type_name = r'(?:[A-Za-z_][A-Za-z0-9_]{0,62}|character varying)(?:\(\d{1,8}(?:,\d{1,8})?\))?'
66
69
 
67
70
  # The optional request key KEY__timelines ({"<timeline>": "<ISO-8601 moment>" | null}) sets, for the request's transaction
68
71
  # only, the moment each timeline is viewed at. A moment becomes the transaction-local setting GUC__timeline_prefix + name,
@@ -236,5 +239,5 @@ ROLE__dba = "dba"
236
239
 
237
240
  PROTOCOL__postgres = "postgresql://"
238
241
 
239
- VERSION = "5.3.21"
242
+ VERSION = "5.3.22"
240
243
 
@@ -3,6 +3,7 @@ import uuid
3
3
 
4
4
  import psycopg
5
5
  from psycopg import OperationalError
6
+ from psycopg.conninfo import make_conninfo
6
7
  from psycopg.pq import TransactionStatus
7
8
  from psycopg_pool import ConnectionPool, PoolClosed
8
9
  import queue
@@ -286,15 +287,17 @@ class DBPGInterface(DBInterface):
286
287
 
287
288
  if password is not None:
288
289
  try:
289
- conn_str = "user=" + username + " password=" + password + " dbname=" + db_name
290
+ conn_params = {"user": username, "password": password, "dbname": db_name}
290
291
  # Important we don't list the host as this will force a unix socket
291
292
  if host is not None and host not in ['localhost', '127.0.0.1']:
292
- conn_str += " host=" + host
293
+ conn_params["host"] = host
293
294
 
294
295
  if str(port) != "5432":
295
- conn_str += " port=" + str(port)
296
+ conn_params["port"] = str(port)
296
297
 
297
- conn_str += CONN_STR__keepalives
298
+ # make_conninfo quotes every value, so no value can add a setting of its own (a database named
299
+ # "x host=elsewhere" would otherwise send the superuser credentials to that host)
300
+ conn_str = make_conninfo(CONN_STR__keepalives.strip(), **conn_params)
298
301
 
299
302
  self.conn_str = conn_str
300
303
 
@@ -1,7 +1,8 @@
1
1
  from jaaql.exceptions.http_status_exception import HttpStatusException, HttpSingletonStatusException, ConnectionLostError
2
2
  from jaaql.interpreter.interpret_jaaql import InterpretJAAQL
3
- from jaaql.constants import ENCODING__utf, VAULT_KEY__super_db_credentials
3
+ from jaaql.constants import ENCODING__utf, VAULT_KEY__super_db_credentials, REGEX__dmbs_object_name
4
4
  from typing import Union
5
+ import re
5
6
  import jaaql.utilities.crypt_utils as crypt_utils
6
7
  from jaaql.db.db_pg_interface import DBPGInterface
7
8
  from jaaql.db.db_interface import DBInterface
@@ -15,6 +16,7 @@ ERR__duplicated_encryption_salt = "Duplicated value in encryption_salts list"
15
16
  ERR__expected_single_row = "Expected single row response but received '%d' rows"
16
17
  ERR__unsupported_interface = "Unsupported interface '%s'. We only support %s"
17
18
  ERR__schema_invalid = "Schema invalid!"
19
+ ERR__database_name_unsafe = "Unsafe database name"
18
20
 
19
21
  # A lost connection persisted nothing, so a self-contained statement is re-run on a fresh connection.
20
22
  # Bounded so a genuinely-down database still surfaces an error rather than looping.
@@ -194,6 +196,13 @@ def execute_supplied_statements(db_interface, queries: Union[str, list],
194
196
  return data
195
197
 
196
198
 
199
+ def requested_database(database) -> str:
200
+ # A database named by the request itself: a plain name, as every database JAAQL uses has one
201
+ if not isinstance(database, str) or re.fullmatch(REGEX__dmbs_object_name, database) is None:
202
+ raise HttpStatusException(ERR__database_name_unsafe)
203
+ return database
204
+
205
+
197
206
  def create_interface_for_db(vault, config, user_id: str, database: str, sub_role: str = None, session_settings: dict = None):
198
207
  jaaql_uri = vault.get_obj(VAULT_KEY__super_db_credentials)
199
208
  address, port, _, username, password = DBInterface.fracture_uri(jaaql_uri)
@@ -4,7 +4,8 @@ from http import HTTPStatus
4
4
  from jaaql.mvc.exception_queries import QUERY__fetch_application_schemas, KG__application_schema__application, KG__application__is_live, \
5
5
  KG__application_schema__name, KEY__is_default
6
6
  from queue import Queue
7
- from jaaql.db.db_utils import execute_supplied_statement, create_interface_for_db, ERR__schema_invalid, CONN_LOST__max_attempts
7
+ from jaaql.db.db_utils import execute_supplied_statement, create_interface_for_db, ERR__schema_invalid, CONN_LOST__max_attempts, \
8
+ requested_database
8
9
  from jaaql.exceptions.http_status_exception import HttpStatusException, ConnectionLostError
9
10
  from jaaql.interpreter.interpret_jaaql import InterpretJAAQL, KEY_autocommit
10
11
  from jaaql.constants import KEY__application, KEY__database, KEY__schema, KEY__role, DB__jaaql, \
@@ -122,6 +123,8 @@ def get_required_db(vault, config, jaaql_connection: DBInterface, inputs: dict,
122
123
  raise HttpStatusException(ERR__schema_invalid)
123
124
 
124
125
  inputs[KEY__database] = found_db
126
+ elif KEY__database in inputs:
127
+ requested_database(inputs[KEY__database])
125
128
 
126
129
  if KEY__database not in inputs:
127
130
  inputs[KEY__database] = DB__jaaql
@@ -24,3 +24,17 @@ def count_succeeded_for_security_event(
24
24
  KG__security_event__account: account,
25
25
  }, as_objects=True
26
26
  )[KEY__count]
27
+
28
+
29
+ QUERY__is_federation_procedure = "SELECT name FROM federation_procedure WHERE name = :name"
30
+
31
+
32
+ def is_federation_procedure(
33
+ connection: DBInterface,
34
+ name: str
35
+ ):
36
+ return len(execute_supplied_statement(
37
+ connection, QUERY__is_federation_procedure, {
38
+ KG__federation_procedure__name: name
39
+ }, as_objects=True
40
+ )) != 0
@@ -30,11 +30,11 @@ from jaaql.mvc.base_model import BaseJAAQLModel, VAULT_KEY__jwt_crypt_key
30
30
  from jaaql.utilities.bootstrap_secrets import get_or_seed_vault_secret
31
31
  from jaaql.exceptions.http_status_exception import HttpStatusException, ERR__already_installed, HttpSingletonStatusException
32
32
  from os.path import join
33
- from jaaql.interpreter.interpret_jaaql import KEY_query, KEY_parameters
33
+ from jaaql.interpreter.interpret_jaaql import KEY_query, KEY_parameters, KEY_store
34
34
  from jaaql.constants import *
35
35
  from jaaql.utilities.cron import check_if_should_fire_cron
36
36
  from jaaql.utilities.utils import get_jaaql_root, get_base_url
37
- from jaaql.db.db_utils import create_interface, jaaql__encrypt, create_interface_for_db, jaaql__decrypt
37
+ from jaaql.db.db_utils import create_interface, jaaql__encrypt, create_interface_for_db, jaaql__decrypt, requested_database
38
38
  from jaaql.db.db_utils_no_circ import submit, get_required_db, objectify
39
39
  from jaaql.utilities import crypt_utils
40
40
  from jaaql.utilities.utils_no_project_imports import get_cookie_attrs, COOKIE_JAAQL_AUTH, COOKIE_OIDC, COOKIE_OIDC_RETURN, \
@@ -172,6 +172,21 @@ def _keycloak_backchannel_origin(discovery_url: str) -> str:
172
172
  return f"{parsed.scheme}://{parsed.netloc}"
173
173
 
174
174
 
175
+ def _explicit_type(explicit_types, parameter_key: str):
176
+ # The request's type for a parameter, which the caller splices into the SQL as '::<type>'. Anything but one bare
177
+ # identifier is refused, as it would be SQL of the caller's choosing (outside PREVENT_ARBITRARY_QUERIES)
178
+ if explicit_types is None:
179
+ return None
180
+ if not isinstance(explicit_types, dict):
181
+ raise HttpStatusException("Expected explicit_types to be an object")
182
+ explicit_type = explicit_types.get(parameter_key)
183
+ if explicit_type is None or explicit_type == "":
184
+ return None
185
+ if not isinstance(explicit_type, str) or re.fullmatch(REGEX__dmbs_type_name, explicit_type) is None:
186
+ raise HttpStatusException("Unsafe explicit type for parameter " + parameter_key)
187
+ return explicit_type
188
+
189
+
175
190
  class JAAQLModel(BaseJAAQLModel):
176
191
  VERIFICATION_QUEUE = None
177
192
 
@@ -368,7 +383,7 @@ class JAAQLModel(BaseJAAQLModel):
368
383
  return columns
369
384
 
370
385
  def fetch_domains(self, inputs: dict, account_id: str):
371
- db_connection = create_interface_for_db(self.vault, self.config, account_id, inputs[KEY__database], None)
386
+ db_connection = create_interface_for_db(self.vault, self.config, account_id, requested_database(inputs[KEY__database]), None)
372
387
  self.is_dba(db_connection)
373
388
 
374
389
  domains_query = """
@@ -397,7 +412,7 @@ ORDER BY
397
412
 
398
413
  def prepare_queries(self, inputs: dict, account_id: str):
399
414
  cost_only = inputs.get("cost_only", False)
400
- db_connection = create_interface_for_db(self.vault, self.config, account_id, inputs[KEY__database], None)
415
+ db_connection = create_interface_for_db(self.vault, self.config, account_id, requested_database(inputs[KEY__database]), None)
401
416
 
402
417
  self.is_dba(db_connection)
403
418
 
@@ -942,12 +957,12 @@ WHERE
942
957
  db_params[claim_name] = id_payload.get(claim_name, "")
943
958
 
944
959
  procedure_name = database_user_registry[KG__database_user_registry__federation_procedure]
945
- if re.match(REGEX__dmbs_procedure_name, procedure_name) is None:
960
+ if re.fullmatch(REGEX__dmbs_procedure_name, procedure_name) is None:
946
961
  raise HttpStatusException("Unsafe data federation procedure")
947
962
 
948
963
  procedure_params = []
949
964
  for key, _ in db_params.items():
950
- if re.match(REGEX__dmbs_object_name, key) is None:
965
+ if re.fullmatch(REGEX__dmbs_object_name, key) is None:
951
966
  raise HttpStatusException("Unsafe data federation parameter " + key)
952
967
  procedure_params.append(f"{key} => :{key}")
953
968
 
@@ -2026,7 +2041,7 @@ WHERE
2026
2041
  def _gate_run_singleton(self, inputs: dict, account_id: str, security_event: dict) -> Any:
2027
2042
  # Fetch configured procedure
2028
2043
  proc_name = security_event[KG__security_event__database_procedure]
2029
- if re.match(REGEX__dmbs_procedure_name, proc_name) is None:
2044
+ if re.fullmatch(REGEX__dmbs_procedure_name, proc_name) is None:
2030
2045
  raise HttpStatusException(
2031
2046
  "Unsafe " + KG__security_event__database_procedure + " specified for security event"
2032
2047
  )
@@ -2035,14 +2050,14 @@ WHERE
2035
2050
  params = inputs[KEY__parameters]
2036
2051
  explicit_types = inputs.get("explicit_types", {})
2037
2052
  for k in params.keys():
2038
- if re.match(REGEX__dmbs_object_name, k) is None:
2053
+ if re.fullmatch(REGEX__dmbs_object_name, k) is None:
2039
2054
  raise HttpStatusException("Unsafe parameter specified for database procedure")
2040
2055
 
2041
2056
  # Build SELECT * FROM proc(arg => :arg::<type>, ...)
2042
2057
  introduced = False
2043
2058
  query = f"SELECT * FROM \"{proc_name}\"("
2044
2059
  for k in params.keys():
2045
- explicit_type = explicit_types.get(k)
2060
+ explicit_type = _explicit_type(explicit_types, k)
2046
2061
  v = params[k]
2047
2062
 
2048
2063
  if introduced:
@@ -2496,10 +2511,16 @@ WHERE
2496
2511
 
2497
2512
  for key, val in inputs["query"].items():
2498
2513
  if isinstance(val, dict):
2514
+ # A store query runs its other keys as SQL text, which would be the caller's own SQL here
2515
+ if KEY_store in val:
2516
+ raise HttpStatusException("/execute does not run store queries; call a procedure instead")
2499
2517
  val["query"] = self._lookup_cached_query(val["query"].strip())
2500
2518
  else:
2501
2519
  inputs["query"][key] = self._lookup_cached_query(val.strip())
2502
2520
 
2521
+ # The compiled queries belong to the configured application: they run in its databases, never in one the request names
2522
+ inputs[KEY__application] = self.query_caches["application"]
2523
+
2503
2524
  # Queries here come from the compiled application query cache (server-authored, single
2504
2525
  # statements), so let postgres execute them as prepared statements
2505
2526
  return submit(self.vault, self.config, self.get_db_crypt_key(), self.jaaql_lookup_connection, inputs, account_id, verification_hook,
@@ -2508,7 +2529,7 @@ WHERE
2508
2529
  def call_proc(self, inputs: dict, account_id: str, verification_hook: Queue = None, as_objects: bool = False, singleton: bool = False):
2509
2530
  parameters = inputs["parameters"]
2510
2531
  query_name = inputs["query"]
2511
- if re.match(REGEX__dmbs_procedure_name, query_name) is None:
2532
+ if re.fullmatch(REGEX__dmbs_procedure_name, query_name) is None:
2512
2533
  raise HttpStatusException("Unsafe procedure name " + query_name)
2513
2534
  query = "SELECT * FROM \"" + query_name + "\"("
2514
2535
 
@@ -2519,9 +2540,9 @@ WHERE
2519
2540
  absent = ""
2520
2541
 
2521
2542
  for parameter_key in parameter_keys:
2522
- if re.match(REGEX__dmbs_object_name, parameter_key) is None:
2543
+ if re.fullmatch(REGEX__dmbs_object_name, parameter_key) is None:
2523
2544
  raise HttpStatusException("Unsafe parameter key " + parameter_key)
2524
- explicit_type = explicit_types.get(parameter_key)
2545
+ explicit_type = _explicit_type(explicit_types, parameter_key)
2525
2546
  parameter_value = parameters[parameter_key]
2526
2547
 
2527
2548
  if introduced:
@@ -2536,6 +2557,11 @@ WHERE
2536
2557
 
2537
2558
  query += " )"
2538
2559
 
2560
+ # A federation procedure links an account to the application's users from the claims JAAQL vouches for, so
2561
+ # only JAAQL may run it (as the jaaql role); a login calling it could link itself to someone else
2562
+ if is_federation_procedure(self.jaaql_lookup_connection, query_name):
2563
+ raise HttpStatusException("A federation procedure cannot be called directly", HTTPStatus.FORBIDDEN)
2564
+
2539
2565
  inputs["query"] = {
2540
2566
  "_jaaql_procedure": query
2541
2567
  }
@@ -25,6 +25,13 @@ BEGIN
25
25
  PERFORM dblink_exec('dbname=' || database, 'GRANT USAGE ON SCHEMA jaaql_extension TO PUBLIC;');
26
26
  PERFORM dblink_exec('dbname=' || database, 'CREATE EXTENSION IF NOT EXISTS jaaql;');
27
27
 
28
+ -- Only dba may create temporary objects. pg_temp is searched before every other schema, so a login could
29
+ -- otherwise create a temp view named like an application view and have the SECURITY DEFINER functions read
30
+ -- it instead (search_path cannot stop this: a login may set its own). dba keeps the right for /prepare and
31
+ -- for the procedures, which run as dba
32
+ PERFORM dblink_exec('dbname=' || database, 'REVOKE TEMPORARY ON DATABASE ' || quote_ident(database) || ' FROM PUBLIC;');
33
+ PERFORM dblink_exec('dbname=' || database, 'GRANT TEMPORARY ON DATABASE ' || quote_ident(database) || ' TO dba;');
34
+
28
35
  -- Federation schema: stores OIDC identity linkage for federated/invited users
29
36
  PERFORM dblink_exec('dbname=' || database, 'CREATE SCHEMA IF NOT EXISTS federation;');
30
37
  -- The public-schema copies are kept for backwards compatibility with code that
@@ -0,0 +1,214 @@
1
+ """
2
+ The SQL that /call-proc and a security event's procedure call build from the request: names, parameter keys and explicit types;
3
+ and /call-proc's refusal of federation procedures.
4
+
5
+ python -m unittest jaaql.test.test_call_proc
6
+
7
+ Needs only the package's requirements: submit and the federation procedure lookup are replaced, so no database is reached
8
+ """
9
+ import unittest
10
+ from http import HTTPStatus
11
+ from types import SimpleNamespace
12
+ from unittest import mock
13
+
14
+ from jaaql.exceptions.http_status_exception import HttpStatusException
15
+ from jaaql.mvc import handmade_queries, model
16
+ from jaaql.mvc.model import JAAQLModel, _explicit_type
17
+
18
+ # The explicit types of the generated __dbms__.ts of 41 projects: a FIESTA realm name for the generated table functions, and
19
+ # the Postgres datatype FIESTA writes for a realm (weaver_output.c) for the parameters of hand-written procedures
20
+ TYPES__generated = ["project_code", "_datetime", "_string", "boolean", "jsonb", "postgres_user_id", "position_", "value_",
21
+ "full_url_allowing_anchor_and_parameters", "kadastraal_registratienummer", "iso_weeknummer",
22
+ "integer", "smallint", "bigint", "bool", "date", "text", "timestamptz", "timestamp", "uuid", "bytea", "numeric",
23
+ "numeric(12)", "numeric(4,2)", "numeric(5,2)", "character varying(16)", "character varying(64)",
24
+ "character varying(4096)"]
25
+
26
+ TYPES__unsafe = [
27
+ "text) , other => (SELECT 1",
28
+ "text||(SELECT email FROM person LIMIT 1)::int",
29
+ "int; DROP TABLE person",
30
+ "numeric(5,2)) , other => (SELECT 1",
31
+ "character varying(64) , other => (SELECT 1)",
32
+ "text--",
33
+ "text/**/",
34
+ "text\n",
35
+ "numeric(4,2)\n",
36
+ " text",
37
+ "text ",
38
+ "character varying(64)",
39
+ "character varying (64)",
40
+ "numeric(4, 2)",
41
+ "numeric(4,2,1)",
42
+ "numeric(a)",
43
+ "numeric()",
44
+ "text[]",
45
+ "public.text",
46
+ "\"text\"",
47
+ "1text",
48
+ "x" * 64,
49
+ ]
50
+
51
+
52
+ def stub_model():
53
+ return SimpleNamespace(vault=None, config=None, get_db_crypt_key=lambda: b"key", jaaql_lookup_connection=None,
54
+ cached_canned_query_service=None)
55
+
56
+
57
+ class TestExplicitType(unittest.TestCase):
58
+
59
+ def assertUnsafe(self, explicit_types, parameter_key="p"):
60
+ with self.assertRaises(HttpStatusException) as caught:
61
+ _explicit_type(explicit_types, parameter_key)
62
+ self.assertEqual(HTTPStatus.UNPROCESSABLE_ENTITY, caught.exception.response_code)
63
+
64
+ def test_generated_types_are_accepted_unchanged(self):
65
+ for explicit_type in TYPES__generated:
66
+ self.assertEqual(explicit_type, _explicit_type({"p": explicit_type}, "p"))
67
+
68
+ def test_the_longest_postgres_identifier_is_accepted(self):
69
+ self.assertEqual("x" * 63, _explicit_type({"p": "x" * 63}, "p"))
70
+
71
+ def test_absent_types_give_none(self):
72
+ self.assertIsNone(_explicit_type(None, "p"))
73
+ self.assertIsNone(_explicit_type({}, "p"))
74
+ self.assertIsNone(_explicit_type({"p": None}, "p"))
75
+ self.assertIsNone(_explicit_type({"p": ""}, "p"))
76
+ self.assertIsNone(_explicit_type({"q": "text) , x => (SELECT 1"}, "p"))
77
+
78
+ def test_anything_but_one_bare_identifier_is_refused(self):
79
+ for explicit_type in TYPES__unsafe:
80
+ with self.subTest(explicit_type=explicit_type):
81
+ self.assertUnsafe({"p": explicit_type})
82
+
83
+ def test_values_that_are_not_strings_are_refused(self):
84
+ for explicit_type in [1, ["text"], {"text": 1}, True]:
85
+ with self.subTest(explicit_type=explicit_type):
86
+ self.assertUnsafe({"p": explicit_type})
87
+
88
+ def test_explicit_types_must_be_an_object(self):
89
+ for explicit_types in [["text"], "text", 1]:
90
+ with self.subTest(explicit_types=explicit_types):
91
+ self.assertUnsafe(explicit_types)
92
+
93
+
94
+ class TestCallProc(unittest.TestCase):
95
+
96
+ def call_proc(self, inputs, federation_procedures=()):
97
+ with mock.patch.object(model, "submit", return_value="submitted") as submitted, \
98
+ mock.patch.object(model, "is_federation_procedure", side_effect=lambda _, name: name in federation_procedures) as looked_up:
99
+ self.looked_up = looked_up
100
+ result = JAAQLModel.call_proc(stub_model(), inputs, "account")
101
+ return result, submitted
102
+
103
+ def test_a_federation_procedure_is_refused(self):
104
+ with mock.patch.object(model, "submit") as submitted, \
105
+ mock.patch.object(model, "is_federation_procedure", return_value=True) as looked_up:
106
+ with self.assertRaises(HttpStatusException) as caught:
107
+ JAAQLModel.call_proc(stub_model(), {"query": "_system.federate", "parameters": {
108
+ "account_id": "attacker", "email": "victim@example.com"}}, "attacker")
109
+ self.assertEqual(HTTPStatus.FORBIDDEN, caught.exception.response_code)
110
+ looked_up.assert_called_once_with(None, "_system.federate")
111
+ submitted.assert_not_called()
112
+
113
+ def test_other_procedures_are_looked_up_by_their_exact_name_and_called(self):
114
+ result, submitted = self.call_proc({"query": "project.federate_single_policy", "parameters": {"a": 1}},
115
+ federation_procedures=("_system.federate",))
116
+ self.assertEqual("submitted", result)
117
+ self.looked_up.assert_called_once_with(None, "project.federate_single_policy")
118
+
119
+ def test_a_trailing_newline_does_not_pass_the_name_or_key_checks(self):
120
+ # Postgres truncates identifiers to 63 bytes, so "<63 characters>\n" would resolve to the procedure "<63 characters>"
121
+ for inputs in [{"query": "a" * 63 + "\n", "parameters": {}}, {"query": "x", "parameters": {"a\n": 1}}]:
122
+ with self.subTest(inputs=inputs):
123
+ with self.assertRaises(HttpStatusException) as caught:
124
+ self.call_proc(inputs, federation_procedures=("a" * 63,))
125
+ self.assertEqual(HTTPStatus.UNPROCESSABLE_ENTITY, caught.exception.response_code)
126
+ self.looked_up.assert_not_called()
127
+
128
+ def test_a_bad_request_is_refused_before_the_lookup(self):
129
+ with self.assertRaises(HttpStatusException):
130
+ self.call_proc({"query": "_system.federate", "parameters": {"a": "1"}, "explicit_types": {"a": "text--"}},
131
+ federation_procedures=("_system.federate",))
132
+ self.looked_up.assert_not_called()
133
+
134
+ def test_a_generated_call_builds_the_same_sql_as_before(self):
135
+ result, submitted = self.call_proc({
136
+ "application": "app",
137
+ "query": "person.update",
138
+ "parameters": {"number": 1, "email": "a@b.nl", "note": None, "start": "2026-10-06T10:00:00"},
139
+ "explicit_types": {"number": "person_number", "email": "_email", "note": "comment", "start": "_datetime"}
140
+ })
141
+ self.assertEqual("submitted", result)
142
+ self.assertEqual({"_jaaql_procedure": "SELECT * FROM \"person.update\"("
143
+ "\n\tnumber => :number::person_number,"
144
+ "\n\temail => :email,"
145
+ "\n\tnote => :note,"
146
+ "\n\tstart => :start )"},
147
+ submitted.call_args.args[4]["query"])
148
+
149
+ def test_a_hand_written_procedure_call_builds_the_same_sql_as_before(self):
150
+ # LesBij's generated client for its lesson.save procedure
151
+ _, submitted = self.call_proc({
152
+ "application": "app",
153
+ "query": "lesson.save",
154
+ "parameters": {"number": 1, "location": "Almere", "start": 9.25, "is_kwaliteitsles": True, "comment": None},
155
+ "explicit_types": {"number": "integer", "location": "character varying(64)", "start": "numeric(4,2)",
156
+ "is_kwaliteitsles": "bool", "comment": "text"}
157
+ })
158
+ self.assertEqual({"_jaaql_procedure": "SELECT * FROM \"lesson.save\"("
159
+ "\n\tnumber => :number::integer,"
160
+ "\n\tlocation => :location::character varying(64),"
161
+ "\n\tstart => :start::numeric(4,2),"
162
+ "\n\tis_kwaliteitsles => :is_kwaliteitsles::bool,"
163
+ "\n\tcomment => :comment )"},
164
+ submitted.call_args.args[4]["query"])
165
+
166
+ def test_a_call_without_explicit_types_is_unchanged(self):
167
+ for inputs in [{"query": "x", "parameters": {"a": 1}}, {"query": "x", "parameters": {"a": 1}, "explicit_types": None}]:
168
+ with self.subTest(inputs=inputs):
169
+ _, submitted = self.call_proc(inputs)
170
+ self.assertEqual({"_jaaql_procedure": "SELECT * FROM \"x\"(\n\ta => :a )"}, submitted.call_args.args[4]["query"])
171
+
172
+ def test_an_unsafe_type_is_refused_before_anything_is_submitted(self):
173
+ for explicit_type in TYPES__unsafe:
174
+ with self.subTest(explicit_type=explicit_type):
175
+ with self.assertRaises(HttpStatusException):
176
+ self.call_proc({"query": "x", "parameters": {"a": "1"}, "explicit_types": {"a": explicit_type}})
177
+
178
+ def test_an_unsafe_type_is_refused_even_for_a_null_value(self):
179
+ with self.assertRaises(HttpStatusException):
180
+ self.call_proc({"query": "x", "parameters": {"a": None}, "explicit_types": {"a": "text) , b => (SELECT 1"}})
181
+
182
+
183
+ class TestIsFederationProcedure(unittest.TestCase):
184
+
185
+ def test_the_registered_name_is_looked_up_exactly(self):
186
+ for rows, expected in [([{"name": "_system.federate"}], True), ([], False)]:
187
+ with self.subTest(rows=rows):
188
+ with mock.patch.object(handmade_queries, "execute_supplied_statement", return_value=rows) as executed:
189
+ self.assertIs(expected, handmade_queries.is_federation_procedure("connection", "_system.federate"))
190
+ executed.assert_called_once_with("connection", "SELECT name FROM federation_procedure WHERE name = :name",
191
+ {"name": "_system.federate"}, as_objects=True)
192
+
193
+
194
+ class TestSecurityEventProcedure(unittest.TestCase):
195
+
196
+ def run_singleton(self, parameters, explicit_types):
197
+ with mock.patch.object(model, "submit", return_value="submitted") as submitted:
198
+ JAAQLModel._gate_run_singleton(stub_model(), {"application": "app", "parameters": parameters, "explicit_types": explicit_types},
199
+ "account", {"database_procedure": "person.add_user"})
200
+ return submitted.call_args.args[4]["query"]
201
+
202
+ def test_a_generated_call_builds_the_same_sql_as_before(self):
203
+ self.assertEqual("SELECT * FROM \"person.add_user\"(\n\temail => :email::email,\n\tname => :name\n)",
204
+ self.run_singleton({"email": "a@b.nl", "name": "A"}, {"email": "email", "name": "_string"}))
205
+
206
+ def test_an_unsafe_type_is_refused(self):
207
+ for explicit_type in TYPES__unsafe:
208
+ with self.subTest(explicit_type=explicit_type):
209
+ with self.assertRaises(HttpStatusException):
210
+ self.run_singleton({"email": "a@b.nl"}, {"email": explicit_type})
211
+
212
+
213
+ if __name__ == "__main__":
214
+ unittest.main()
@@ -0,0 +1,61 @@
1
+ """
2
+ /execute runs only the application's compiled queries, in the application's databases: the query a request names is replaced by its
3
+ compiled text, and a store query, whose other keys would be run as SQL text, is refused.
4
+
5
+ python -m unittest jaaql.test.test_execute
6
+
7
+ Needs only the package's requirements: submit and the query cache are replaced, so no database is reached
8
+ """
9
+ import unittest
10
+ from http import HTTPStatus
11
+ from types import SimpleNamespace
12
+ from unittest import mock
13
+
14
+ from jaaql.exceptions.http_status_exception import HttpStatusException
15
+ from jaaql.mvc import model
16
+ from jaaql.mvc.model import JAAQLModel
17
+
18
+ COMPILED = {"frame:0": "SELECT number FROM person WHERE number = :number"}
19
+
20
+
21
+ def stub_model():
22
+ return SimpleNamespace(query_caches={"application": "app"}, db_cache={}, vault=None, config=None, get_db_crypt_key=lambda: b"key",
23
+ jaaql_lookup_connection=None, cached_canned_query_service=None,
24
+ _lookup_cached_query=mock.Mock(side_effect=lambda name: COMPILED[name]))
25
+
26
+
27
+ class TestExecute(unittest.TestCase):
28
+
29
+ def execute(self, inputs):
30
+ stub = stub_model()
31
+ with mock.patch.object(model, "submit", return_value="submitted") as submitted:
32
+ result = JAAQLModel.execute(stub, inputs, "account")
33
+ return result, submitted, stub
34
+
35
+ def test_a_compiled_query_is_run_by_its_compiled_text(self):
36
+ for query in ["frame:0", {"query": "frame:0", "parameters": {"number": 1}}]:
37
+ with self.subTest(query=query):
38
+ result, submitted, _ = self.execute({"application": "app", "query": {"person": query}})
39
+ self.assertEqual("submitted", result)
40
+ sent = submitted.call_args.args[4]["query"]["person"]
41
+ self.assertEqual(COMPILED["frame:0"], sent if isinstance(sent, str) else sent["query"])
42
+
43
+ def test_the_queries_run_in_the_configured_application_whatever_the_request_names(self):
44
+ for extra in [{}, {"database": "jaaql"}, {"application": "other", "database": "postgres"}]:
45
+ with self.subTest(extra=extra):
46
+ _, submitted, _ = self.execute({"query": {"person": "frame:0"}, **extra})
47
+ self.assertEqual("app", submitted.call_args.args[4]["application"])
48
+
49
+ def test_a_store_query_is_refused_before_anything_is_submitted(self):
50
+ stub = stub_model()
51
+ with mock.patch.object(model, "submit") as submitted:
52
+ with self.assertRaises(HttpStatusException) as caught:
53
+ JAAQLModel.execute(stub, {"application": "app", "query": {"rows": {
54
+ "query": "frame:0", "store": "rows", "own_sql": "SELECT email FROM person"}},
55
+ "parameters": {"rows": [{"_state": "own_sql"}]}}, "account")
56
+ self.assertEqual(HTTPStatus.UNPROCESSABLE_ENTITY, caught.exception.response_code)
57
+ submitted.assert_not_called()
58
+
59
+
60
+ if __name__ == "__main__":
61
+ unittest.main()
@@ -0,0 +1,130 @@
1
+ """
2
+ A database named by the request (a request without an application, /domains, /prepare) and the connection string built for it.
3
+
4
+ python -m unittest jaaql.test.test_requested_database
5
+
6
+ Needs only the package's requirements: connections, pools and the vault are replaced, so no database is reached
7
+ """
8
+ import unittest
9
+ from http import HTTPStatus
10
+ from types import SimpleNamespace
11
+ from unittest import mock
12
+
13
+ from psycopg.conninfo import conninfo_to_dict
14
+
15
+ from jaaql.constants import DB__jaaql
16
+ from jaaql.db import db_pg_interface, db_utils_no_circ
17
+ from jaaql.db.db_pg_interface import DBPGInterface
18
+ from jaaql.db.db_utils import requested_database
19
+ from jaaql.db.db_utils_no_circ import get_required_db
20
+ from jaaql.exceptions.http_status_exception import HttpStatusException
21
+ from jaaql.mvc import model
22
+ from jaaql.mvc.model import JAAQLModel
23
+
24
+ CONFIG = {"DEBUG": {"output_query_exceptions": "false"}, "DATABASE": {"interface": "postgres"}, "SYSTEM": {"logging": False}}
25
+
26
+ NAMES__plain = ["database", "jaaql", "postgres", "jaaql_test_lifecycle", "x" * 63]
27
+ NAMES__unsafe = ["x host=attacker.example", "x host=attacker.example port=5433", "database options='-csession_replication_role=replica'",
28
+ "dbname=x", "x' host='y", "database\n", " database", "", "x" * 64, "my-app", "a.b"]
29
+
30
+
31
+ class TestRequestedDatabase(unittest.TestCase):
32
+
33
+ def test_plain_names_are_accepted(self):
34
+ for name in NAMES__plain:
35
+ self.assertEqual(name, requested_database(name))
36
+
37
+ def test_anything_else_is_refused(self):
38
+ for name in NAMES__unsafe + [None, 1, ["database"], {"dbname": "x"}]:
39
+ with self.subTest(name=name):
40
+ with self.assertRaises(HttpStatusException) as caught:
41
+ requested_database(name)
42
+ self.assertEqual(HTTPStatus.UNPROCESSABLE_ENTITY, caught.exception.response_code)
43
+
44
+
45
+ class TestGetRequiredDb(unittest.TestCase):
46
+
47
+ def required_db(self, inputs):
48
+ with mock.patch.object(db_utils_no_circ, "create_interface_for_db", return_value="interface") as created:
49
+ result = get_required_db(None, CONFIG, None, inputs, "account")
50
+ return result, created
51
+
52
+ def test_a_request_naming_an_unsafe_database_never_connects(self):
53
+ for name in NAMES__unsafe:
54
+ with self.subTest(name=name):
55
+ with mock.patch.object(db_utils_no_circ, "create_interface_for_db") as created:
56
+ with self.assertRaises(HttpStatusException):
57
+ get_required_db(None, CONFIG, None, {"database": name, "query": "SELECT 1"}, "account")
58
+ created.assert_not_called()
59
+
60
+ def test_a_plain_database_is_connected_to(self):
61
+ result, created = self.required_db({"database": "postgres", "query": "SELECT 1"})
62
+ self.assertEqual("interface", result)
63
+ self.assertEqual("postgres", created.call_args.args[3])
64
+
65
+ def test_no_application_and_no_database_is_the_jaaql_database(self):
66
+ _, created = self.required_db({"query": "SELECT 1"})
67
+ self.assertEqual(DB__jaaql, created.call_args.args[3])
68
+
69
+
70
+ class FakePool:
71
+
72
+ def __init__(self, conninfo, **kwargs):
73
+ self.conninfo = conninfo
74
+ FakePool.made.append(self)
75
+
76
+ def getconn(self, timeout=None):
77
+ return None
78
+
79
+ def close(self):
80
+ pass
81
+
82
+
83
+ class TestConnectionString(unittest.TestCase):
84
+
85
+ def conninfo(self, host, port, db_name, password):
86
+ FakePool.made = []
87
+ user = "jaaql_test_conninfo_user"
88
+ try:
89
+ with mock.patch.object(db_pg_interface, "ConnectionPool", FakePool), mock.patch.object(db_pg_interface.threading, "Thread"):
90
+ DBPGInterface(CONFIG, host, port, db_name, user, password=password)
91
+ finally:
92
+ DBPGInterface.HOST_POOLS.pop(user, None)
93
+ DBPGInterface.HOST_POOLS_QUEUES.pop(user, None)
94
+ self.assertEqual(1, len(FakePool.made))
95
+ return conninfo_to_dict(FakePool.made[0].conninfo)
96
+
97
+ def test_a_database_name_cannot_add_settings(self):
98
+ for db_name in NAMES__unsafe[:5]:
99
+ with self.subTest(db_name=db_name):
100
+ parsed = self.conninfo("localhost", 5432, db_name, "secret")
101
+ self.assertEqual({"keepalives": "1", "keepalives_idle": "10", "keepalives_interval": "5", "keepalives_count": "3",
102
+ "user": "jaaql_test_conninfo_user", "password": "secret", "dbname": db_name}, parsed)
103
+
104
+ def test_a_password_with_spaces_and_quotes_stays_one_value(self):
105
+ self.assertEqual("p w'x \\ host=y", self.conninfo("localhost", 5432, "database", "p w'x \\ host=y")["password"])
106
+
107
+ def test_a_remote_host_and_another_port_are_kept(self):
108
+ parsed = self.conninfo("db.example", 5435, "database", "secret")
109
+ self.assertEqual(("db.example", "5435", "database"), (parsed["host"], parsed["port"], parsed["dbname"]))
110
+
111
+ def test_localhost_on_the_default_port_names_neither(self):
112
+ parsed = self.conninfo("127.0.0.1", 5432, "database", "secret")
113
+ self.assertNotIn("host", parsed)
114
+ self.assertNotIn("port", parsed)
115
+
116
+
117
+ class TestDbaEndpoints(unittest.TestCase):
118
+
119
+ def test_domains_and_prepare_refuse_an_unsafe_database_before_connecting(self):
120
+ stub = SimpleNamespace(vault=None, config=CONFIG, is_dba=lambda connection: None)
121
+ for method in [JAAQLModel.fetch_domains, JAAQLModel.prepare_queries]:
122
+ with self.subTest(method=method.__name__):
123
+ with mock.patch.object(model, "create_interface_for_db") as created:
124
+ with self.assertRaises(HttpStatusException):
125
+ method(stub, {"database": "x host=attacker.example", "queries": []}, "account")
126
+ created.assert_not_called()
127
+
128
+
129
+ if __name__ == "__main__":
130
+ unittest.main()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jaaql-middleware-python
3
- Version: 5.3.21
3
+ Version: 5.3.22
4
4
  Summary: The jaaql package, allowing for rapid development and deployment of RESTful HTTP applications
5
5
  Home-page: https://github.com/JAAQL/JAAQL-middleware-python
6
6
  Author: Software Quality Measurement and Improvement bv
@@ -62,7 +62,10 @@ jaaql/services/patch_mms.py
62
62
  jaaql/services/patch_shared_var_service.py
63
63
  jaaql/services/shared_var_service.py
64
64
  jaaql/test/__init__.py
65
+ jaaql/test/test_call_proc.py
65
66
  jaaql/test/test_connection_lifecycle.py
67
+ jaaql/test/test_execute.py
68
+ jaaql/test/test_requested_database.py
66
69
  jaaql/test/test_timelines.py
67
70
  jaaql/utilities/__init__.py
68
71
  jaaql/utilities/bootstrap_secrets.py