soap-failover-proxy 2.0.2__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.
@@ -0,0 +1,184 @@
1
+ Metadata-Version: 2.4
2
+ Name: soap-failover-proxy
3
+ Version: 2.0.2
4
+ Summary: Dynamic failover proxy routing middleware for SOAP and WSGI web services
5
+ Requires-Python: >=3.7
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: cryptography>=42.0.0
8
+
9
+ # SOAP FAILOVER PROXY
10
+
11
+ ## 1.0 Administration
12
+
13
+ ### 1.1 CHANGE LOG
14
+
15
+ ```text
16
+ |Version | Date | Author | Description |
17
+ |--------|-------------|----------|---------------|
18
+ | 1.0 | 11 Oct 2026 | Sarna, J.| First Draft |
19
+ ```
20
+
21
+ ## 2.0 DESCRIPTION
22
+ When compiled into an assembly and imported by SOAP webservices, allows dynamic reconfiguration.
23
+
24
+ The application uses Python 3.12.1. It was designed to work with Spyne SOAP Python Servers, but can work with REST Python Servers too. Packages have been frozen in requirements.txt via cmd 'pip freeze > requirements.txt'
25
+
26
+
27
+ ### 3.1 How to install
28
+
29
+ #### 3.1.1 LOCAL
30
+
31
+ ##### 3.1.1.1 Create Assembly
32
+
33
+ ###### When adding new version
34
+ Once, I changed the version to 2.0.0. Even, when 'pip install -e .' passes, the package could not be located (cmd 'python -c "import soap_failover_proxy; print('SUCCESS!')"' failed).
35
+
36
+ This was resolved via running a Force clean reinstall of local folder:
37
+
38
+ ```bash
39
+ pip install -e . --force-reinstall
40
+ ```
41
+
42
+ ##### 3.1.1.2 Unit test the assembly process:
43
+
44
+ ```bash
45
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>python -c "import soap_failover_proxy; print('Transliteration app successfully grabbed it!')"
46
+ Transliteration app successfully grabbed it!
47
+ ```
48
+
49
+
50
+
51
+ ### 3.2 HOW to Test
52
+
53
+
54
+ #### 3.2.1 Import into webservice, which has a like for like duplicate/backup
55
+
56
+ Since, the folder holding the webservice, and the soap-service is different, provide location:
57
+
58
+ ```bash
59
+
60
+ C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>venv\Scripts\activate
61
+
62
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>pip install -e ../../eclipse-my-workspace/Soap-failover-proxy/. --force-reinstall
63
+ Obtaining file:///C:/Users/moose/eclipse-my-workspace/Soap-failover-proxy
64
+ Installing build dependencies ... done
65
+ Checking if build backend supports build_editable ... done
66
+ Getting requirements to build editable ... done
67
+ Preparing editable metadata (pyproject.toml) ... done
68
+ Requirement already satisfied: cryptography>=42.0.0 in c:\users\moose\eclipse-workspace\transliteration.systematicdefence.tech\venv\lib\site-packages (from soap-failover-proxy==2.0.1) (50.0.2)
69
+ Requirement already satisfied: cffi>=2.0.0 in c:\users\moose\eclipse-workspace\transliteration.systematicdefence.tech\venv\lib\site-packages (from cryptography>=42.0.0->soap-failover-proxy==2.0.1) (2.1.1)
70
+ Requirement already satisfied: pycparser in c:\users\moose\eclipse-workspace\transliteration.systematicdefence.tech\venv\lib\site-packages (from cffi>=2.0.0->cryptography>=42.0.0->soap-failover-proxy==2.0.1) (3.11)
71
+ Building wheels for collected packages: soap-failover-proxy
72
+ Building editable for soap-failover-proxy (pyproject.toml) ... done
73
+ Created wheel for soap-failover-proxy: filename=soap_failover_proxy-2.0.1-0.editable-py3-none-any.whl size=3178 sha256=48dfe3a350343c2023b89d64c16c58d13f5ce65af12ec2f3017ecd7f0f212b0c
74
+ Stored in directory: C:\Users\moose\AppData\Local\Temp\pip-ephem-wheel-cache-11lhnhsp\wheels\7d\21\47\83dbedb8aef8b572caa0e369eca420685dfe13015ff98b7cc6
75
+ Successfully built soap-failover-proxy
76
+ Installing collected packages: soap-failover-proxy
77
+ Attempting uninstall: soap-failover-proxy
78
+ Found existing installation: soap-failover-proxy 2.0.0
79
+ Uninstalling soap-failover-proxy-2.0.0:
80
+ Successfully uninstalled soap-failover-proxy-2.0.0
81
+ Successfully installed soap-failover-proxy-2.0.1
82
+
83
+ [notice] A new release of pip is available: 24.0 -> 26.2.2
84
+ [notice] To update, run: python.exe -m pip install --upgrade pip
85
+
86
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>python -c "import soap_failover_proxy; print('Transliteration app successfully grabbed it')"
87
+ Transliteration app successfully grabbed it
88
+
89
+ ```
90
+
91
+ #### 3.2.2 Add vendor supplied 'ecryption key' and 'admin key' to webservice's .env
92
+
93
+ ```text
94
+ ADMIN_API_KEY=<redacted>
95
+ MY_AES_SECRET_KEY=<redacted>
96
+ ```
97
+
98
+ #### 3.2.3 Create encrypted string
99
+
100
+ ![Create encrypted string as admin key](./CustomerKeyGenTool.png)
101
+
102
+
103
+ #### 3.2.4 Ensure both candidate web services are turned on
104
+
105
+ ##### 3.2.4.1 Calc Webservice
106
+
107
+ ```bash
108
+ C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>rmdir /s /q venv
109
+
110
+ C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>py -3.11 -m venv venv
111
+
112
+ C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>venv\Scripts\activate
113
+
114
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>pip install -r requirements.txt
115
+
116
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>waitress-serve --host=127.0.0.1 --port=8000 passenger_wsgi:application
117
+ INFO:waitress:Serving on http://127.0.0.1:8000
118
+
119
+ ```
120
+
121
+ ##### 3.2.4.2 Calc Backup Webservice
122
+
123
+ ```bash
124
+ (venv) C:\Users\moose\eclipse-workspace\transliteration-backup.systematicdefence.tech>waitress-serve --host=127.0.0.1 --port=8080 passenger_wsgi:application
125
+ INFO:waitress:Serving on http://127.0.0.1:8080
126
+ ```
127
+
128
+ #### 3.2.5 Make Request
129
+
130
+ ##### 3.2.5.1 Switch to backup
131
+
132
+ ![SWITCH_TO_BACKUP](./SWITCH_TO_BACKUP_WORKS.png)
133
+
134
+ ##### 3.2.5.2 Switch from backup
135
+
136
+ ![SWITCH_TO_LOCAL](./SWITCH_TO_LOCAL_WORKS.png)
137
+
138
+ ## Versions
139
+
140
+ ### Version 1.0 Operational
141
+
142
+ 11 Oct 2026 Sunday 15:43
143
+
144
+ See tests/EndtoEndSmokeTest.md and tests/UnitTests.md for current functionality.
145
+
146
+ ### Version 1.0.1 Post Quantum protection added
147
+ 11 Oct 2026 Sunday 16:59
148
+
149
+ Added Shared Secret to keep Admin key protected from Post Quantam attacks. Updated tests.
150
+
151
+ ### Version 2.0.0 Post Quantum protection tests pass
152
+
153
+ 11 Oct 2026 Sunday 18:22
154
+
155
+ Post Quantum protection and dependency in assembly. See test/UnitTests.md for evidence.
156
+
157
+ ### Version 2.0.1 Add facility of testing endpoint, when all service endpoints redirected
158
+
159
+ 24 Oct 2026 Sunday 17:00
160
+
161
+ Now the assembly provides facility to enable testing even when it is being redirected to backup. It does so via a token it generates at runtime. This needs to be provided to the webservice in the header. This token is stored in Maintenance.lock, and is returned as part of the 'switch-to-backup' method. Unit Tests all pass. See UnitTests.md for details. Here is an example
162
+
163
+ ```bash
164
+ PS C:\Users\moose> curl -X POST http://127.0.0.1:8000/ `
165
+ >> -H "Content-Type: text/xml; charset=utf-8" `
166
+ >> -H "X-BYPASS-TOKEN: 3698e1add5287563cd4c03e06da9ce37" `
167
+ >> -d $xmlData
168
+ <?xml version='1.0' encoding='UTF-8'?>
169
+ <soap11env:Envelope xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="spyne.examples.hello"><soap11env:Body><tns:add_numbersResponse><tns:add_numbersResult>12</tns:add_numbersResult></tns:add_numbersResponse></soap11env:Body></soap11env:Envelope>
170
+ ```
171
+
172
+ ### Version 2.0.2 Updated to ensure that incorrect header provided for testing endpoint is handled gracefully
173
+
174
+ 29 Oct 2026 Thursday 21:30
175
+
176
+ Negative scenario setup to ensure test url:
177
+
178
+ ```bash
179
+ PS C:\Users\moose> curl -X POST http://127.0.0.1:8000/ `
180
+ >> -H "Content-Type: text/xml; charset=utf-8" `
181
+ >> -H "X-BYPASS-TOKEN: asd" `
182
+ >> -d $xmlData
183
+ 403 Forbidden: Invalid maintenance bypass token validation parameter.
184
+ ```
@@ -0,0 +1,176 @@
1
+ # SOAP FAILOVER PROXY
2
+
3
+ ## 1.0 Administration
4
+
5
+ ### 1.1 CHANGE LOG
6
+
7
+ ```text
8
+ |Version | Date | Author | Description |
9
+ |--------|-------------|----------|---------------|
10
+ | 1.0 | 11 Oct 2026 | Sarna, J.| First Draft |
11
+ ```
12
+
13
+ ## 2.0 DESCRIPTION
14
+ When compiled into an assembly and imported by SOAP webservices, allows dynamic reconfiguration.
15
+
16
+ The application uses Python 3.12.1. It was designed to work with Spyne SOAP Python Servers, but can work with REST Python Servers too. Packages have been frozen in requirements.txt via cmd 'pip freeze > requirements.txt'
17
+
18
+
19
+ ### 3.1 How to install
20
+
21
+ #### 3.1.1 LOCAL
22
+
23
+ ##### 3.1.1.1 Create Assembly
24
+
25
+ ###### When adding new version
26
+ Once, I changed the version to 2.0.0. Even, when 'pip install -e .' passes, the package could not be located (cmd 'python -c "import soap_failover_proxy; print('SUCCESS!')"' failed).
27
+
28
+ This was resolved via running a Force clean reinstall of local folder:
29
+
30
+ ```bash
31
+ pip install -e . --force-reinstall
32
+ ```
33
+
34
+ ##### 3.1.1.2 Unit test the assembly process:
35
+
36
+ ```bash
37
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>python -c "import soap_failover_proxy; print('Transliteration app successfully grabbed it!')"
38
+ Transliteration app successfully grabbed it!
39
+ ```
40
+
41
+
42
+
43
+ ### 3.2 HOW to Test
44
+
45
+
46
+ #### 3.2.1 Import into webservice, which has a like for like duplicate/backup
47
+
48
+ Since, the folder holding the webservice, and the soap-service is different, provide location:
49
+
50
+ ```bash
51
+
52
+ C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>venv\Scripts\activate
53
+
54
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>pip install -e ../../eclipse-my-workspace/Soap-failover-proxy/. --force-reinstall
55
+ Obtaining file:///C:/Users/moose/eclipse-my-workspace/Soap-failover-proxy
56
+ Installing build dependencies ... done
57
+ Checking if build backend supports build_editable ... done
58
+ Getting requirements to build editable ... done
59
+ Preparing editable metadata (pyproject.toml) ... done
60
+ Requirement already satisfied: cryptography>=42.0.0 in c:\users\moose\eclipse-workspace\transliteration.systematicdefence.tech\venv\lib\site-packages (from soap-failover-proxy==2.0.1) (50.0.2)
61
+ Requirement already satisfied: cffi>=2.0.0 in c:\users\moose\eclipse-workspace\transliteration.systematicdefence.tech\venv\lib\site-packages (from cryptography>=42.0.0->soap-failover-proxy==2.0.1) (2.1.1)
62
+ Requirement already satisfied: pycparser in c:\users\moose\eclipse-workspace\transliteration.systematicdefence.tech\venv\lib\site-packages (from cffi>=2.0.0->cryptography>=42.0.0->soap-failover-proxy==2.0.1) (3.11)
63
+ Building wheels for collected packages: soap-failover-proxy
64
+ Building editable for soap-failover-proxy (pyproject.toml) ... done
65
+ Created wheel for soap-failover-proxy: filename=soap_failover_proxy-2.0.1-0.editable-py3-none-any.whl size=3178 sha256=48dfe3a350343c2023b89d64c16c58d13f5ce65af12ec2f3017ecd7f0f212b0c
66
+ Stored in directory: C:\Users\moose\AppData\Local\Temp\pip-ephem-wheel-cache-11lhnhsp\wheels\7d\21\47\83dbedb8aef8b572caa0e369eca420685dfe13015ff98b7cc6
67
+ Successfully built soap-failover-proxy
68
+ Installing collected packages: soap-failover-proxy
69
+ Attempting uninstall: soap-failover-proxy
70
+ Found existing installation: soap-failover-proxy 2.0.0
71
+ Uninstalling soap-failover-proxy-2.0.0:
72
+ Successfully uninstalled soap-failover-proxy-2.0.0
73
+ Successfully installed soap-failover-proxy-2.0.1
74
+
75
+ [notice] A new release of pip is available: 24.0 -> 26.2.2
76
+ [notice] To update, run: python.exe -m pip install --upgrade pip
77
+
78
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>python -c "import soap_failover_proxy; print('Transliteration app successfully grabbed it')"
79
+ Transliteration app successfully grabbed it
80
+
81
+ ```
82
+
83
+ #### 3.2.2 Add vendor supplied 'ecryption key' and 'admin key' to webservice's .env
84
+
85
+ ```text
86
+ ADMIN_API_KEY=<redacted>
87
+ MY_AES_SECRET_KEY=<redacted>
88
+ ```
89
+
90
+ #### 3.2.3 Create encrypted string
91
+
92
+ ![Create encrypted string as admin key](./CustomerKeyGenTool.png)
93
+
94
+
95
+ #### 3.2.4 Ensure both candidate web services are turned on
96
+
97
+ ##### 3.2.4.1 Calc Webservice
98
+
99
+ ```bash
100
+ C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>rmdir /s /q venv
101
+
102
+ C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>py -3.11 -m venv venv
103
+
104
+ C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>venv\Scripts\activate
105
+
106
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>pip install -r requirements.txt
107
+
108
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>waitress-serve --host=127.0.0.1 --port=8000 passenger_wsgi:application
109
+ INFO:waitress:Serving on http://127.0.0.1:8000
110
+
111
+ ```
112
+
113
+ ##### 3.2.4.2 Calc Backup Webservice
114
+
115
+ ```bash
116
+ (venv) C:\Users\moose\eclipse-workspace\transliteration-backup.systematicdefence.tech>waitress-serve --host=127.0.0.1 --port=8080 passenger_wsgi:application
117
+ INFO:waitress:Serving on http://127.0.0.1:8080
118
+ ```
119
+
120
+ #### 3.2.5 Make Request
121
+
122
+ ##### 3.2.5.1 Switch to backup
123
+
124
+ ![SWITCH_TO_BACKUP](./SWITCH_TO_BACKUP_WORKS.png)
125
+
126
+ ##### 3.2.5.2 Switch from backup
127
+
128
+ ![SWITCH_TO_LOCAL](./SWITCH_TO_LOCAL_WORKS.png)
129
+
130
+ ## Versions
131
+
132
+ ### Version 1.0 Operational
133
+
134
+ 11 Oct 2026 Sunday 15:43
135
+
136
+ See tests/EndtoEndSmokeTest.md and tests/UnitTests.md for current functionality.
137
+
138
+ ### Version 1.0.1 Post Quantum protection added
139
+ 11 Oct 2026 Sunday 16:59
140
+
141
+ Added Shared Secret to keep Admin key protected from Post Quantam attacks. Updated tests.
142
+
143
+ ### Version 2.0.0 Post Quantum protection tests pass
144
+
145
+ 11 Oct 2026 Sunday 18:22
146
+
147
+ Post Quantum protection and dependency in assembly. See test/UnitTests.md for evidence.
148
+
149
+ ### Version 2.0.1 Add facility of testing endpoint, when all service endpoints redirected
150
+
151
+ 24 Oct 2026 Sunday 17:00
152
+
153
+ Now the assembly provides facility to enable testing even when it is being redirected to backup. It does so via a token it generates at runtime. This needs to be provided to the webservice in the header. This token is stored in Maintenance.lock, and is returned as part of the 'switch-to-backup' method. Unit Tests all pass. See UnitTests.md for details. Here is an example
154
+
155
+ ```bash
156
+ PS C:\Users\moose> curl -X POST http://127.0.0.1:8000/ `
157
+ >> -H "Content-Type: text/xml; charset=utf-8" `
158
+ >> -H "X-BYPASS-TOKEN: 3698e1add5287563cd4c03e06da9ce37" `
159
+ >> -d $xmlData
160
+ <?xml version='1.0' encoding='UTF-8'?>
161
+ <soap11env:Envelope xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="spyne.examples.hello"><soap11env:Body><tns:add_numbersResponse><tns:add_numbersResult>12</tns:add_numbersResult></tns:add_numbersResponse></soap11env:Body></soap11env:Envelope>
162
+ ```
163
+
164
+ ### Version 2.0.2 Updated to ensure that incorrect header provided for testing endpoint is handled gracefully
165
+
166
+ 29 Oct 2026 Thursday 21:30
167
+
168
+ Negative scenario setup to ensure test url:
169
+
170
+ ```bash
171
+ PS C:\Users\moose> curl -X POST http://127.0.0.1:8000/ `
172
+ >> -H "Content-Type: text/xml; charset=utf-8" `
173
+ >> -H "X-BYPASS-TOKEN: asd" `
174
+ >> -d $xmlData
175
+ 403 Forbidden: Invalid maintenance bypass token validation parameter.
176
+ ```
@@ -0,0 +1,17 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "soap-failover-proxy"
7
+ version = "2.0.2"
8
+ description = "Dynamic failover proxy routing middleware for SOAP and WSGI web services"
9
+ readme = "README.md"
10
+ requires-python = ">=3.7"
11
+ dependencies = [
12
+ "cryptography>=42.0.0"
13
+ ]
14
+
15
+ [project.scripts]
16
+ soap-proxy = "soap_failover_proxy.cli:main"
17
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,45 @@
1
+ #####################################################################################
2
+ # Author: Jay Sarna
3
+ # Date: 1 Oct 2026
4
+ # Description: This serves as the Engine for interactive CLI & Help Documentation Engine, inorder to:
5
+ # - Aid system maintainability
6
+ # Essentially, it is an automated user documentation layer embedded inside the package CLI
7
+ #####################################################################################
8
+
9
+ import argparse
10
+ import sys
11
+
12
+ def main():
13
+
14
+ # -- info flag
15
+ parser = argparse.ArgumentParser(
16
+ description="🚀 SOAP Failover Proxy Engine 2.0.0 — Developer Toolkit",
17
+ formatter_class=argparse.RawDescriptionHelpFormatter,
18
+ epilog="""
19
+ Example Remote API Switch Commands:
20
+ Switch to Backup (Default Configs):
21
+ curl -H "X-Admin-API-Key: your_key" -H "X-Proxy-Command: SWITCH_TO_BACKUP" http://your-soap-app.com
22
+
23
+ Switch to a Custom Overridden Backup Endpoint URL:
24
+ curl -H "X-Admin-API-Key: your_key" -H "X-Proxy-Command: SWITCH_TO_BACKUP" -H "X-Proxy-Backup-Url: backup-server.com" http://your-soap-app.com
25
+
26
+ Switch back to Local Environment:
27
+ curl -H "X-Admin-API-Key: your_key" -H "X-Proxy-Command: SWITCH_TO_LOCAL" http://your-soap-app.com
28
+ """
29
+ )
30
+ parser.add_argument('--info', action='store_true', help='Show system ingestion instructions.')
31
+
32
+ # --help flag
33
+ if len(sys.argv) == 1:
34
+ parser.print_help()
35
+ sys.exit(0)
36
+
37
+ args = parser.parse_args()
38
+ if args.info:
39
+ print("\nHow to inject this package into your application:")
40
+ print("-" * 50)
41
+ print("from soap_failover_proxy import SoapProxyMiddleware")
42
+ print("application = SoapProxyMiddleware(local_soap_application)\n")
43
+
44
+ if __name__ == '__main__':
45
+ main()
@@ -0,0 +1,218 @@
1
+ import os
2
+ import base64
3
+ import urllib.request
4
+ import secrets # Industry standard for secure token generation
5
+ from urllib.error import URLError, HTTPError
6
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
7
+
8
+ class SoapProxyMiddleware:
9
+
10
+ def __init__(self, app, api_key_env_var="ADMIN_API_KEY", aes_key_env_var="MY_AES_SECRET_KEY", lock_filename="maintenance.lock"):
11
+ self.app = app
12
+
13
+ # Load your baseline admin validation key from your server environment
14
+ self.api_key = os.getenv(api_key_env_var)
15
+
16
+ # Load your 32-byte secret encryption key from your environment
17
+ secret_key_str = os.getenv(aes_key_env_var)
18
+
19
+ if not secret_key_str:
20
+ raise RuntimeError(f"CRITICAL ERROR: Environment variable '{aes_key_env_var}' is missing!")
21
+
22
+ self.aes_gcm_key = secret_key_str.encode('utf-8')
23
+ self.lock_path = os.path.join(os.getcwd(), lock_filename)
24
+
25
+ def _decrypt_aes_256_gcm(self, encrypted_base64_payload):
26
+ """
27
+ Decrypts an AES-256-GCM payload structured as:
28
+ Base64( 12-byte IV + Ciphertext + 16-byte Tag )
29
+ """
30
+ try:
31
+ # 1. Decode the complete Base64 payload from the user interface
32
+ raw_payload = base64.b64decode(encrypted_base64_payload)
33
+
34
+ # 2. Extract the 12-byte IV from the very front
35
+ iv = raw_payload[:12]
36
+
37
+ # 3. Extract the ciphertext and tag (AESGCM in Python expects them combined)
38
+ ciphertext_and_tag = raw_payload[12:]
39
+
40
+ # 4. Decrypt using the built-in AESGCM module
41
+ aesgcm = AESGCM(self.aes_gcm_key)
42
+ plaintext_bytes = aesgcm.decrypt(iv, ciphertext_and_tag, associated_data=None)
43
+
44
+ return plaintext_bytes.decode('utf-8')
45
+
46
+ except Exception as e:
47
+ # Fail silently to avoid leaking details to malicious clients
48
+ return None # FIXED: Capitalized to valid Python None
49
+
50
+ # 2. WSGI Interceptor Entry Point - Handles every incoming HTTP request transaction
51
+ def __call__(self, environ, start_response):
52
+ # Read the payload arriving from the client header
53
+ encrypted_client_key = environ.get('HTTP_X_ADMIN_API_KEY')
54
+
55
+ if encrypted_client_key:
56
+ client_api_key = self._decrypt_aes_256_gcm(encrypted_client_key)
57
+ else:
58
+ client_api_key = None
59
+
60
+ # 2.1 Administrative Intercept & Reconfiguration Engine - invoked via client's api call
61
+ if self.api_key and client_api_key == self.api_key:
62
+ command = environ.get('HTTP_X_PROXY_COMMAND', '').upper()
63
+ custom_url = environ.get('HTTP_X_PROXY_BACKUP_URL', '').strip()
64
+
65
+ # Write dynamic lock state parameters to intercept operational logic
66
+ if command == "SWITCH_TO_BACKUP":
67
+
68
+ # Generate a secure 16-byte hex token (e.g., 'a1b2c3d4e5f6..')
69
+ bypass_token = secrets.token_hex(16)
70
+
71
+ # State layout inside file: active | backup_url| bypass_token
72
+ lock_content = f"active|{custom_url}|{bypass_token}" if custom_url else f"active||{bypass_token}"
73
+ with open(self.lock_path, "w") as f:
74
+ f.write(lock_content)
75
+
76
+ # Expose the token back to the testing harness via standard JSON/Plaintext
77
+ msg = f"Proxy switched to BACKUP mode. Bypass token:{bypass_token}; Backup url: {custom_url if custom_url else 'Default URL'}"
78
+
79
+ msg = f"OK|{bypass_token}"
80
+ start_response("200 OK", [
81
+ ("Content-Type", "text/plain"),
82
+ ("X-Testing-Token", bypass_token) # Double delivery via header for convenience
83
+ ])
84
+ #msg = f"Proxy switched to BACKUP mode. Target: {custom_url if custom_url else 'Default URL'}"
85
+ #start_response("200 OK", [("Content-Type", "text/plain")])
86
+ return [msg.encode('utf-8')]
87
+
88
+ # Flush existing lock state metadata to restore target pipelines
89
+ elif command == "SWITCH_TO_LOCAL":
90
+ if os.path.exists(self.lock_path):
91
+ os.remove(self.lock_path)
92
+ start_response("200 OK", [("Content-Type", "text/plain")])
93
+ return [b"Proxy restored to LOCAL application mode."]
94
+
95
+ # 2.2 Operational Routing Framework - if maintenance.lock present or exception at runtime, forward request to backup
96
+ if os.path.exists(self.lock_path):
97
+ backup_url, bypass_token = self._parse_lock_file()
98
+
99
+ # Extract incoming token from custom header or query string parameter
100
+ client_token = environ.get('HTTP_X_BYPASS_TOKEN', '')
101
+ if not client_token and 'QUERY_STRING' in environ:
102
+ from sys import version_info
103
+ #lightweight query parsing fallback to avoid external dependencies - key value pair
104
+ params = dict(kv.split('=', 1) for kv in environ['QUERY_STRING'].split('&') if '=' in kv)
105
+ client_token = params.get('token', '')
106
+ # Execute validation check strictly if a bypass token is configured in the lock file
107
+ if bypass_token:
108
+ # SCENARIO A: Token matches perfectly -> run locally, without redirecting
109
+ if secrets.compare_digest(client_token, bypass_token):
110
+ try:
111
+ return self.app(environ, start_response)
112
+ except Exception:
113
+ return self.forward_to_backup(environ, start_response, backup_url)
114
+
115
+ # SCENARIO B: A token was provided but it's WRONG -> 403 Block
116
+ elif client_token:
117
+ #return self.forward_to_backup(environ, start_response, backup_url)
118
+ # Alternatively, this completely prevents them from touching your local app OR your backup app.
119
+ status = '403 Forbidden'
120
+ response_headers = [('Content-Type', 'text/plain; charset=utf-8')]
121
+ start_response(status, response_headers)
122
+ return [b"403 Forbidden: Invalid maintenance bypass token validation parameter."]
123
+
124
+ # SCENARIO C: No token provided at all -> Forward to backup. ALternatively, if the lockfile exists but has no bypass token, route to backup by default
125
+ else:
126
+ return self.forward_to_backup(environ, start_response, backup_url)
127
+
128
+ # 3. Default Path: Runs natively if the system is in standard local mode
129
+ try:
130
+ return self.app(environ, start_response)
131
+ except Exception:
132
+ backup_url, _ = self._parse_lock_file()
133
+ return self.forward_to_backup(environ, start_response, backup_url)
134
+
135
+ # 3. Request Forwarding Forwarder - Handles downstream payload streams to target systems
136
+ # Note: backup_url added as an optional positional/keyword argument matching all execution paths cleanly
137
+ def forward_to_backup(self, environ, start_response, backup_url=None):
138
+
139
+
140
+ # 3.1 Custom Lock Parameter Resolution - if content exists in the maintenance.lock file, retrieve it as backup_url
141
+
142
+ if not backup_url and os.path.exists(self.lock_path):
143
+ with open(self.lock_path, "r") as f:
144
+ content = f.read().strip().split('|')
145
+ if len(content) > 1 and content [1]:
146
+ backup_url = content[1]
147
+
148
+ # 3.2 Environment Parameter Fallback - if maintenance.lock is empty, load backup_url from .env file
149
+ if not backup_url:
150
+ is_production = os.getenv('IS_PRODUCTION', 'True') == 'True'
151
+ if is_production:
152
+ backup_url = os.getenv('PROD_BACKUP_URL')
153
+ else:
154
+ url = os.getenv('LOCAL_BACKUP_URL', 'localhost')
155
+ port = os.getenv('LOCAL_BACKUP_URL_PORT', '8080')
156
+ backup_url = f"{url}:{port}"
157
+
158
+ # 3.3 Safety Validation Check - If .env is missing environment variables to compose backup_url
159
+ if not backup_url:
160
+ start_response("500 Internal Server Error", [("Content-Type", "text/plain")])
161
+ return [b"Configuration Error: No fallback backup URL available."]
162
+
163
+ # 3.4 Raw Payload Ingestion - Reads incoming byte arrays cleanly without mutating the WSGI stream
164
+ try:
165
+ request_body_size = int(environ.get('CONTENT_LENGTH', 0))
166
+ request_body = environ['wsgi.input'].read(request_body_size)
167
+ except (ValueError, KeyError):
168
+ request_body = b""
169
+
170
+ # 3.5 Metadata Reconstruction - Reassigns and forces SOAPAction headers back into context
171
+ headers = {'Content-Type': environ.get('CONTENT_TYPE', 'text/xml; charset=utf-8')}
172
+ if 'HTTP_SOAPACTION' in environ:
173
+ headers['SOAPAction'] = environ['HTTP_SOAPACTION']
174
+ if request_body:
175
+ headers['Content-Length'] = str(len(request_body))
176
+
177
+ # 3.6 Remote Connection Assembly - Generates outbound HTTP stream objects matching inbound methods
178
+ req = urllib.request.Request(
179
+ backup_url,
180
+ data=request_body,
181
+ headers=headers,
182
+ method=environ.get('REQUEST_METHOD', 'POST')
183
+ )
184
+
185
+ # 3.7 Execution and Response Stream Resolution
186
+ try:
187
+ with urllib.request.urlopen(req, timeout=10) as response:
188
+ status = f"{response.status} {response.reason}"
189
+ content_type = response.headers.get('Content-Type', 'text/xml; charset=utf-8')
190
+ start_response(status, [('Content-Type', content_type)])
191
+ return [response.read()]
192
+ except HTTPError as e:
193
+ status = f"{e.code} {e.reason}"
194
+ start_response(status, [('Content-Type', e.headers.get('Content-Type', 'text/xml; charset=utf-8'))])
195
+ return [e.read()]
196
+ except URLError:
197
+ start_response("502 Bad Gateway", [('Content-Type', 'text/plain')])
198
+ return [b"Backup service unreachable."]
199
+
200
+ # Helper functions
201
+ def _parse_lock_file(self):
202
+ """Helper to safely unpack lock file configurations."""
203
+ if not os.path.exists(self.lock_path):
204
+ return None, None
205
+ try:
206
+ with open(self.lock_path, "r") as f:
207
+ # 1. Added execution parentheses () to strip
208
+ raw_data = f.read().strip()
209
+ if not raw_data:
210
+ return None, None
211
+
212
+ content = raw_data.split('|')
213
+
214
+ backup_url = content[1] if len(content) > 1 and content[1] else None
215
+ bypass_token = content[2] if len(content) > 2 else None
216
+ return backup_url, bypass_token
217
+ except Exception:
218
+ return None, None
@@ -0,0 +1,184 @@
1
+ Metadata-Version: 2.4
2
+ Name: soap-failover-proxy
3
+ Version: 2.0.2
4
+ Summary: Dynamic failover proxy routing middleware for SOAP and WSGI web services
5
+ Requires-Python: >=3.7
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: cryptography>=42.0.0
8
+
9
+ # SOAP FAILOVER PROXY
10
+
11
+ ## 1.0 Administration
12
+
13
+ ### 1.1 CHANGE LOG
14
+
15
+ ```text
16
+ |Version | Date | Author | Description |
17
+ |--------|-------------|----------|---------------|
18
+ | 1.0 | 11 Oct 2026 | Sarna, J.| First Draft |
19
+ ```
20
+
21
+ ## 2.0 DESCRIPTION
22
+ When compiled into an assembly and imported by SOAP webservices, allows dynamic reconfiguration.
23
+
24
+ The application uses Python 3.12.1. It was designed to work with Spyne SOAP Python Servers, but can work with REST Python Servers too. Packages have been frozen in requirements.txt via cmd 'pip freeze > requirements.txt'
25
+
26
+
27
+ ### 3.1 How to install
28
+
29
+ #### 3.1.1 LOCAL
30
+
31
+ ##### 3.1.1.1 Create Assembly
32
+
33
+ ###### When adding new version
34
+ Once, I changed the version to 2.0.0. Even, when 'pip install -e .' passes, the package could not be located (cmd 'python -c "import soap_failover_proxy; print('SUCCESS!')"' failed).
35
+
36
+ This was resolved via running a Force clean reinstall of local folder:
37
+
38
+ ```bash
39
+ pip install -e . --force-reinstall
40
+ ```
41
+
42
+ ##### 3.1.1.2 Unit test the assembly process:
43
+
44
+ ```bash
45
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>python -c "import soap_failover_proxy; print('Transliteration app successfully grabbed it!')"
46
+ Transliteration app successfully grabbed it!
47
+ ```
48
+
49
+
50
+
51
+ ### 3.2 HOW to Test
52
+
53
+
54
+ #### 3.2.1 Import into webservice, which has a like for like duplicate/backup
55
+
56
+ Since, the folder holding the webservice, and the soap-service is different, provide location:
57
+
58
+ ```bash
59
+
60
+ C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>venv\Scripts\activate
61
+
62
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>pip install -e ../../eclipse-my-workspace/Soap-failover-proxy/. --force-reinstall
63
+ Obtaining file:///C:/Users/moose/eclipse-my-workspace/Soap-failover-proxy
64
+ Installing build dependencies ... done
65
+ Checking if build backend supports build_editable ... done
66
+ Getting requirements to build editable ... done
67
+ Preparing editable metadata (pyproject.toml) ... done
68
+ Requirement already satisfied: cryptography>=42.0.0 in c:\users\moose\eclipse-workspace\transliteration.systematicdefence.tech\venv\lib\site-packages (from soap-failover-proxy==2.0.1) (50.0.2)
69
+ Requirement already satisfied: cffi>=2.0.0 in c:\users\moose\eclipse-workspace\transliteration.systematicdefence.tech\venv\lib\site-packages (from cryptography>=42.0.0->soap-failover-proxy==2.0.1) (2.1.1)
70
+ Requirement already satisfied: pycparser in c:\users\moose\eclipse-workspace\transliteration.systematicdefence.tech\venv\lib\site-packages (from cffi>=2.0.0->cryptography>=42.0.0->soap-failover-proxy==2.0.1) (3.11)
71
+ Building wheels for collected packages: soap-failover-proxy
72
+ Building editable for soap-failover-proxy (pyproject.toml) ... done
73
+ Created wheel for soap-failover-proxy: filename=soap_failover_proxy-2.0.1-0.editable-py3-none-any.whl size=3178 sha256=48dfe3a350343c2023b89d64c16c58d13f5ce65af12ec2f3017ecd7f0f212b0c
74
+ Stored in directory: C:\Users\moose\AppData\Local\Temp\pip-ephem-wheel-cache-11lhnhsp\wheels\7d\21\47\83dbedb8aef8b572caa0e369eca420685dfe13015ff98b7cc6
75
+ Successfully built soap-failover-proxy
76
+ Installing collected packages: soap-failover-proxy
77
+ Attempting uninstall: soap-failover-proxy
78
+ Found existing installation: soap-failover-proxy 2.0.0
79
+ Uninstalling soap-failover-proxy-2.0.0:
80
+ Successfully uninstalled soap-failover-proxy-2.0.0
81
+ Successfully installed soap-failover-proxy-2.0.1
82
+
83
+ [notice] A new release of pip is available: 24.0 -> 26.2.2
84
+ [notice] To update, run: python.exe -m pip install --upgrade pip
85
+
86
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>python -c "import soap_failover_proxy; print('Transliteration app successfully grabbed it')"
87
+ Transliteration app successfully grabbed it
88
+
89
+ ```
90
+
91
+ #### 3.2.2 Add vendor supplied 'ecryption key' and 'admin key' to webservice's .env
92
+
93
+ ```text
94
+ ADMIN_API_KEY=<redacted>
95
+ MY_AES_SECRET_KEY=<redacted>
96
+ ```
97
+
98
+ #### 3.2.3 Create encrypted string
99
+
100
+ ![Create encrypted string as admin key](./CustomerKeyGenTool.png)
101
+
102
+
103
+ #### 3.2.4 Ensure both candidate web services are turned on
104
+
105
+ ##### 3.2.4.1 Calc Webservice
106
+
107
+ ```bash
108
+ C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>rmdir /s /q venv
109
+
110
+ C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>py -3.11 -m venv venv
111
+
112
+ C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>venv\Scripts\activate
113
+
114
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>pip install -r requirements.txt
115
+
116
+ (venv) C:\Users\moose\eclipse-workspace\transliteration.systematicdefence.tech>waitress-serve --host=127.0.0.1 --port=8000 passenger_wsgi:application
117
+ INFO:waitress:Serving on http://127.0.0.1:8000
118
+
119
+ ```
120
+
121
+ ##### 3.2.4.2 Calc Backup Webservice
122
+
123
+ ```bash
124
+ (venv) C:\Users\moose\eclipse-workspace\transliteration-backup.systematicdefence.tech>waitress-serve --host=127.0.0.1 --port=8080 passenger_wsgi:application
125
+ INFO:waitress:Serving on http://127.0.0.1:8080
126
+ ```
127
+
128
+ #### 3.2.5 Make Request
129
+
130
+ ##### 3.2.5.1 Switch to backup
131
+
132
+ ![SWITCH_TO_BACKUP](./SWITCH_TO_BACKUP_WORKS.png)
133
+
134
+ ##### 3.2.5.2 Switch from backup
135
+
136
+ ![SWITCH_TO_LOCAL](./SWITCH_TO_LOCAL_WORKS.png)
137
+
138
+ ## Versions
139
+
140
+ ### Version 1.0 Operational
141
+
142
+ 11 Oct 2026 Sunday 15:43
143
+
144
+ See tests/EndtoEndSmokeTest.md and tests/UnitTests.md for current functionality.
145
+
146
+ ### Version 1.0.1 Post Quantum protection added
147
+ 11 Oct 2026 Sunday 16:59
148
+
149
+ Added Shared Secret to keep Admin key protected from Post Quantam attacks. Updated tests.
150
+
151
+ ### Version 2.0.0 Post Quantum protection tests pass
152
+
153
+ 11 Oct 2026 Sunday 18:22
154
+
155
+ Post Quantum protection and dependency in assembly. See test/UnitTests.md for evidence.
156
+
157
+ ### Version 2.0.1 Add facility of testing endpoint, when all service endpoints redirected
158
+
159
+ 24 Oct 2026 Sunday 17:00
160
+
161
+ Now the assembly provides facility to enable testing even when it is being redirected to backup. It does so via a token it generates at runtime. This needs to be provided to the webservice in the header. This token is stored in Maintenance.lock, and is returned as part of the 'switch-to-backup' method. Unit Tests all pass. See UnitTests.md for details. Here is an example
162
+
163
+ ```bash
164
+ PS C:\Users\moose> curl -X POST http://127.0.0.1:8000/ `
165
+ >> -H "Content-Type: text/xml; charset=utf-8" `
166
+ >> -H "X-BYPASS-TOKEN: 3698e1add5287563cd4c03e06da9ce37" `
167
+ >> -d $xmlData
168
+ <?xml version='1.0' encoding='UTF-8'?>
169
+ <soap11env:Envelope xmlns:soap11env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="spyne.examples.hello"><soap11env:Body><tns:add_numbersResponse><tns:add_numbersResult>12</tns:add_numbersResult></tns:add_numbersResponse></soap11env:Body></soap11env:Envelope>
170
+ ```
171
+
172
+ ### Version 2.0.2 Updated to ensure that incorrect header provided for testing endpoint is handled gracefully
173
+
174
+ 29 Oct 2026 Thursday 21:30
175
+
176
+ Negative scenario setup to ensure test url:
177
+
178
+ ```bash
179
+ PS C:\Users\moose> curl -X POST http://127.0.0.1:8000/ `
180
+ >> -H "Content-Type: text/xml; charset=utf-8" `
181
+ >> -H "X-BYPASS-TOKEN: asd" `
182
+ >> -d $xmlData
183
+ 403 Forbidden: Invalid maintenance bypass token validation parameter.
184
+ ```
@@ -0,0 +1,13 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/soap_failover_proxy/__init__.py
4
+ src/soap_failover_proxy/cli.py
5
+ src/soap_failover_proxy/middleware.py
6
+ src/soap_failover_proxy.egg-info/PKG-INFO
7
+ src/soap_failover_proxy.egg-info/SOURCES.txt
8
+ src/soap_failover_proxy.egg-info/dependency_links.txt
9
+ src/soap_failover_proxy.egg-info/entry_points.txt
10
+ src/soap_failover_proxy.egg-info/requires.txt
11
+ src/soap_failover_proxy.egg-info/top_level.txt
12
+ tests/test_middleware_2_0_0.py
13
+ tests/test_middleware_2_0_1.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ soap-proxy = soap_failover_proxy.cli:main
@@ -0,0 +1 @@
1
+ cryptography>=42.0.0
@@ -0,0 +1 @@
1
+ soap_failover_proxy
@@ -0,0 +1,139 @@
1
+ #####################################################################################
2
+ # AUTHOR: Jay Sarna
3
+ # DATE: 1 Oct 2026
4
+ # DESCRIPTION: This test suite utilizes Python's built-in unittest framework alongside unittest.mock to simulate
5
+ # real WSGI network transactions and environment configurations. This allows the code to safely test, without
6
+ # requiring an active network container or live SOAP server:
7
+ # a. administrative intercepts,
8
+ # b. dynamic url overrides,
9
+ # c. file-system locking operations (maintenance.lock file), and
10
+ # d. target application failover pathways
11
+ # HOW TO USE OPTIONS:
12
+ # a. STANDARD: python3 test_middleware.py
13
+ # b. VERBOSE: python3 -m unittest -v test_middleware.py
14
+ #####################################################################################
15
+ import os
16
+ import unittest
17
+ import base64
18
+ from unittest.mock import MagicMock, patch, mock_open
19
+ from io import BytesIO
20
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
21
+
22
+ # Import the production component under test
23
+ from soap_failover_proxy.middleware import SoapProxyMiddleware
24
+
25
+
26
+ class TestSoapProxyMiddleware(unittest.TestCase):
27
+
28
+ @patch("os.getenv")
29
+ def setUp(self, mock_getenv):
30
+ """Sets up mock applications and base environment setups before each test loop."""
31
+ self.mock_app = MagicMock()
32
+ # Mock standard WSGI start_response callable interface
33
+ self.mock_start_response = MagicMock()
34
+
35
+ # Configure a test-specific 32-byte secret key and patch os.getenv for object instantiation
36
+ self.test_secret_key = "test_32_character_secret_key_!!!"
37
+ mock_getenv.side_effect = lambda key, default=None: self.test_secret_key if key == "MY_AES_SECRET_KEY" else default
38
+
39
+ # Instantiate middleware configuration defaults under test
40
+ self.api_key_var = "ADMIN_API_KEY"
41
+ self.lock_file = "test_maintenance.lock"
42
+ self.middleware = SoapProxyMiddleware(
43
+ app=self.mock_app,
44
+ api_key_env_var=self.api_key_var,
45
+ lock_filename=self.lock_file
46
+ )
47
+
48
+ # Establish testing baseline environment states
49
+ self.middleware.api_key = "supersecret123"
50
+
51
+ # Generate a valid AES-256-GCM encrypted payload for "supersecret123"
52
+ aesgcm = AESGCM(self.test_secret_key.encode('utf-8'))
53
+ iv = b"\x00" * 12 # Static deterministic 12-byte IV for testing purposes
54
+ ciphertext_and_tag = aesgcm.encrypt(iv, self.middleware.api_key.encode('utf-8'), None)
55
+ self.valid_encrypted_payload = base64.b64encode(iv + ciphertext_and_tag).decode('utf-8')
56
+
57
+ def tearDown(self):
58
+ """Cleans up leftover persistent tracking assets from disk after execution loops."""
59
+ if os.path.exists(self.middleware.lock_path):
60
+ os.remove(self.middleware.lock_path)
61
+
62
+ @patch("os.path.exists")
63
+ def test_call_routes_to_local_app_under_normal_operations(self, mock_exists):
64
+ """Verifies that traffic passes directly to the local application if no lock asset is active."""
65
+ mock_exists.return_value = False
66
+ environ = {"HTTP_X_ADMIN_API_KEY": "malicious_or_empty", "wsgi.input": BytesIO(b"")}
67
+
68
+ self.middleware(environ, self.mock_start_response)
69
+
70
+ # Target local app should be explicitly triggered
71
+ self.mock_app.assert_called_once_with(environ, self.mock_start_response)
72
+
73
+ def test_admin_command_switches_to_backup_and_creates_lock_file(self):
74
+ """Validates that a correctly authenticated admin request trips the backup flag on disk."""
75
+ environ = {
76
+ "HTTP_X_ADMIN_API_KEY": self.valid_encrypted_payload,
77
+ "HTTP_X_PROXY_COMMAND": "SWITCH_TO_BACKUP",
78
+ "HTTP_X_PROXY_BACKUP_URL": "https://backup.com"
79
+ }
80
+
81
+ response = self.middleware(environ, self.mock_start_response)
82
+
83
+ # Verify 200 OK structural status response
84
+ self.mock_start_response.assert_called_once()
85
+ self.assertIn(b"Proxy switched to BACKUP mode", response[0])
86
+
87
+ # Ensure tracking metrics successfully persisted to the disk path
88
+ self.assertTrue(os.path.exists(self.middleware.lock_path))
89
+ with open(self.middleware.lock_path, "r") as f:
90
+ self.assertEqual(f.read(), "active|https://backup.com")
91
+
92
+ def test_admin_command_switches_back_to_local_mode_and_removes_lock_file(self):
93
+ """Confirms that the SWITCH_TO_LOCAL administrative payload flushes file metrics out of context."""
94
+ # Pre-seed an active lock state file onto the system
95
+ with open(self.middleware.lock_path, "w") as f:
96
+ f.write("active")
97
+
98
+ environ = {
99
+ "HTTP_X_ADMIN_API_KEY": self.valid_encrypted_payload,
100
+ "HTTP_X_PROXY_COMMAND": "SWITCH_TO_LOCAL"
101
+ }
102
+
103
+ response = self.middleware(environ, self.mock_start_response)
104
+
105
+ self.assertIn(b"Proxy restored to LOCAL application mode", response[0])
106
+ # Assert persistence engine data has been safely unlinked
107
+ self.assertFalse(os.path.exists(self.middleware.lock_path))
108
+
109
+ @patch("urllib.request.urlopen")
110
+ def test_operational_failover_triggers_on_local_app_exception(self, mock_urlopen):
111
+ """Asserts that the system catches downstream runtime errors and forces a backup relay."""
112
+ # Configure local application server to simulate a structural crash failure
113
+ self.mock_app.side_effect = Exception("Database Connection Blown!")
114
+
115
+ # Configure mocked remote response metadata configurations
116
+ mock_response = MagicMock()
117
+ mock_response.status = 200
118
+ mock_response.reason = "OK"
119
+ mock_response.headers = {"Content-Type": "text/xml"}
120
+ mock_response.read.return_value = b"<soap:Envelope>Backup Data</soap:Envelope>"
121
+ mock_urlopen.return_value.__enter__.return_value = mock_response
122
+
123
+ environ = {
124
+ "REQUEST_METHOD": "POST",
125
+ "CONTENT_LENGTH": "0",
126
+ "wsgi.input": BytesIO(b""),
127
+ "HTTP_SOAPACTION": "SayHello"
128
+ }
129
+
130
+ with patch.dict(os.environ, {"IS_PRODUCTION": "True", "PROD_BACKUP_URL": "https://fallback.com"}):
131
+ response = self.middleware(environ, self.mock_start_response)
132
+
133
+ # Verify that even though local crashed, proxy intercepted and fetched data from target fallback
134
+ self.mock_start_response.assert_called_with("200 OK", [("Content-Type", "text/xml")])
135
+ self.assertEqual(response[0], b"<soap:Envelope>Backup Data</soap:Envelope>")
136
+
137
+
138
+ if __name__ == "__main__":
139
+ unittest.main()
@@ -0,0 +1,150 @@
1
+ #####################################################################################
2
+ # AUTHOR: Jay Sarna
3
+ # DATE: 1 Oct 2026
4
+ # DESCRIPTION: This test suite utilizes Python's built-in unittest framework alongside unittest.mock to simulate
5
+ # real WSGI network transactions and environment configurations. This allows the code to safely test, without
6
+ # requiring an active network container or live SOAP server:
7
+ # a. administrative intercepts,
8
+ # b. dynamic url overrides,
9
+ # c. file-system locking operations (maintenance.lock file), and
10
+ # d. target application failover pathways
11
+ # HOW TO USE OPTIONS:
12
+ # a. STANDARD: python3 test_middleware.py
13
+ # b. VERBOSE: python3 -m unittest -v test_middleware.py
14
+ #####################################################################################
15
+ import os
16
+ import unittest
17
+ import base64
18
+ import re # Added for matching the dynamic hex bypass token format cleanly
19
+ from unittest.mock import MagicMock, patch
20
+ from io import BytesIO
21
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
22
+
23
+ # Import the production component under test
24
+ from soap_failover_proxy.middleware import SoapProxyMiddleware
25
+
26
+
27
+ class TestSoapProxyMiddleware(unittest.TestCase):
28
+
29
+ @patch("os.getenv")
30
+ def setUp(self, mock_getenv):
31
+ """Sets up mock applications and base environment setups before each test loop."""
32
+ self.mock_app = MagicMock()
33
+ # Mock standard WSGI start_response callable interface
34
+ self.mock_start_response = MagicMock()
35
+
36
+ # Configure a test-specific 32-byte secret key and patch os.getenv for object instantiation
37
+ self.test_secret_key = "test_32_character_secret_key_!!!"
38
+
39
+ # Store a copy of the original environment provider logic to ensure nested test scopes survive
40
+ self.env_map = {
41
+ "MY_AES_SECRET_KEY": self.test_secret_key,
42
+ "ADMIN_API_KEY": "supersecret123"
43
+ }
44
+ mock_getenv.side_effect = lambda key, default=None: self.env_map.get(key, default)
45
+
46
+ # Instantiate middleware configuration defaults under test
47
+ self.api_key_var = "ADMIN_API_KEY"
48
+ self.lock_file = "test_maintenance.lock"
49
+ self.middleware = SoapProxyMiddleware(
50
+ app=self.mock_app,
51
+ api_key_env_var=self.api_key_var,
52
+ lock_filename=self.lock_file
53
+ )
54
+
55
+ # Establish testing baseline environment states
56
+ self.middleware.api_key = "supersecret123"
57
+
58
+ # Generate a valid AES-256-GCM encrypted payload for "supersecret123"
59
+ aesgcm = AESGCM(self.test_secret_key.encode('utf-8'))
60
+ iv = b"\x00" * 12 # Static deterministic 12-byte IV for testing purposes
61
+ ciphertext_and_tag = aesgcm.encrypt(iv, self.middleware.api_key.encode('utf-8'), None)
62
+ self.valid_encrypted_payload = base64.b64encode(iv + ciphertext_and_tag).decode('utf-8')
63
+
64
+ def tearDown(self):
65
+ """Cleans up leftover persistent tracking assets from disk after execution loops."""
66
+ if os.path.exists(self.middleware.lock_path):
67
+ os.remove(self.middleware.lock_path)
68
+
69
+ @patch("os.path.exists")
70
+ def test_call_routes_to_local_app_under_normal_operations(self, mock_exists):
71
+ """Verifies that traffic passes directly to the local application if no lock asset is active."""
72
+ mock_exists.return_value = False
73
+ environ = {"HTTP_X_ADMIN_API_KEY": "malicious_or_empty", "wsgi.input": BytesIO(b"")}
74
+
75
+ self.middleware(environ, self.mock_start_response)
76
+
77
+ # Target local app should be explicitly triggered
78
+ self.mock_app.assert_called_once_with(environ, self.mock_start_response)
79
+
80
+ def test_admin_command_switches_to_backup_and_creates_lock_file(self):
81
+ """Validates that a correctly authenticated admin request trips the backup flag on disk."""
82
+ environ = {
83
+ "HTTP_X_ADMIN_API_KEY": self.valid_encrypted_payload,
84
+ "HTTP_X_PROXY_COMMAND": "SWITCH_TO_BACKUP",
85
+ "HTTP_X_PROXY_BACKUP_URL": "https://backup.com"
86
+ }
87
+
88
+ response = self.middleware(environ, self.mock_start_response)
89
+
90
+ # Verify 200 OK structural status response
91
+ self.mock_start_response.assert_called_once()
92
+ self.assertIn(b"OK|", response[0])
93
+
94
+ # Ensure tracking metrics successfully persisted to the disk path
95
+ self.assertTrue(os.path.exists(self.middleware.lock_path))
96
+ with open(self.middleware.lock_path, "r") as f:
97
+ file_content = f.read()
98
+ # Assert file contains active prefix, path tracking endpoint, and a cryptographically random 32-character bypass token
99
+ self.assertTrue(re.match(r"^active\|https://backup\.com\|[a-f0-9]{32}$", file_content))
100
+
101
+ def test_admin_command_switches_back_to_local_mode_and_removes_lock_file(self):
102
+ """Confirms that the SWITCH_TO_LOCAL administrative payload flushes file metrics out of context."""
103
+ # Pre-seed an active lock state file onto the system
104
+ with open(self.middleware.lock_path, "w") as f:
105
+ f.write("active")
106
+
107
+ environ = {
108
+ "HTTP_X_ADMIN_API_KEY": self.valid_encrypted_payload,
109
+ "HTTP_X_PROXY_COMMAND": "SWITCH_TO_LOCAL"
110
+ }
111
+
112
+ response = self.middleware(environ, self.mock_start_response)
113
+
114
+ self.assertIn(b"Proxy restored to LOCAL application mode", response[0])
115
+ # Assert persistence engine data has been safely unlinked
116
+ self.assertFalse(os.path.exists(self.middleware.lock_path))
117
+
118
+ @patch("urllib.request.urlopen")
119
+ def test_operational_failover_triggers_on_local_app_exception(self, mock_urlopen):
120
+ """Asserts that the system catches downstream runtime errors and forces a backup relay."""
121
+ # Configure local application server to simulate a structural crash failure
122
+ self.mock_app.side_effect = Exception("Database Connection Blown!")
123
+
124
+ # Configure mocked remote response metadata configurations
125
+ mock_response = MagicMock()
126
+ mock_response.status = 200
127
+ mock_response.reason = "OK"
128
+ mock_response.headers = {"Content-Type": "text/xml"}
129
+ mock_response.read.return_value = b"<soap:Envelope>Backup Data</soap:Envelope>"
130
+ mock_urlopen.return_value.__enter__.return_value = mock_response
131
+
132
+ environ = {
133
+ "REQUEST_METHOD": "POST",
134
+ "CONTENT_LENGTH": "0",
135
+ "wsgi.input": BytesIO(b""),
136
+ "HTTP_SOAPACTION": "SayHello"
137
+ }
138
+
139
+ # Extend base key configurations dynamically to prevent os.getenv evaluation errors
140
+ with patch.dict(os.environ, {"IS_PRODUCTION": "True", "PROD_BACKUP_URL": "https://fallback.com"}):
141
+ self.env_map.update({"IS_PRODUCTION": "True", "PROD_BACKUP_URL": "https://fallback.com"})
142
+ response = self.middleware(environ, self.mock_start_response)
143
+
144
+ # Verify that even though local crashed, proxy intercepted and fetched data from target fallback
145
+ self.mock_start_response.assert_called_with("200 OK", [("Content-Type", "text/xml")])
146
+ self.assertEqual(response[0], b"<soap:Envelope>Backup Data</soap:Envelope>")
147
+
148
+
149
+ if __name__ == "__main__":
150
+ unittest.main()