httpdis 0.6.35__tar.gz → 0.6.37__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 (38) hide show
  1. {httpdis-0.6.35/httpdis.egg-info → httpdis-0.6.37}/PKG-INFO +45 -9
  2. {httpdis-0.6.35 → httpdis-0.6.37}/README.md +44 -8
  3. httpdis-0.6.37/RELEASE +1 -0
  4. httpdis-0.6.37/VERSION +1 -0
  5. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis/httpdis.py +107 -79
  6. {httpdis-0.6.35 → httpdis-0.6.37/httpdis.egg-info}/PKG-INFO +45 -9
  7. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis.egg-info/SOURCES.txt +1 -0
  8. {httpdis-0.6.35 → httpdis-0.6.37}/setup.yml +2 -2
  9. {httpdis-0.6.35 → httpdis-0.6.37}/tests/test_context.py +24 -1
  10. httpdis-0.6.37/tests/test_cors.py +91 -0
  11. {httpdis-0.6.35 → httpdis-0.6.37}/tests/test_httpdis.py +2 -0
  12. httpdis-0.6.35/RELEASE +0 -1
  13. httpdis-0.6.35/VERSION +0 -1
  14. {httpdis-0.6.35 → httpdis-0.6.37}/LICENSE +0 -0
  15. {httpdis-0.6.35 → httpdis-0.6.37}/MANIFEST.in +0 -0
  16. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis/__init__.py +0 -0
  17. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis/auth_backend.py +0 -0
  18. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis/auth_browser.py +0 -0
  19. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis/auth_sqlite.py +0 -0
  20. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis/authentication.py +0 -0
  21. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis/config.py +0 -0
  22. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis/content_disposition.py +0 -0
  23. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis/ext/__init__.py +0 -0
  24. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis/ext/httpdis_json.py +0 -0
  25. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis.egg-info/dependency_links.txt +0 -0
  26. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis.egg-info/requires.txt +0 -0
  27. {httpdis-0.6.35 → httpdis-0.6.37}/httpdis.egg-info/top_level.txt +0 -0
  28. {httpdis-0.6.35 → httpdis-0.6.37}/pyproject.toml +0 -0
  29. {httpdis-0.6.35 → httpdis-0.6.37}/requirements.txt +0 -0
  30. {httpdis-0.6.35 → httpdis-0.6.37}/setup.cfg +0 -0
  31. {httpdis-0.6.35 → httpdis-0.6.37}/setup.py +0 -0
  32. {httpdis-0.6.35 → httpdis-0.6.37}/tests/test_audit_regressions.py +0 -0
  33. {httpdis-0.6.35 → httpdis-0.6.37}/tests/test_auth_backend.py +0 -0
  34. {httpdis-0.6.35 → httpdis-0.6.37}/tests/test_auth_browser.py +0 -0
  35. {httpdis-0.6.35 → httpdis-0.6.37}/tests/test_auth_sqlite.py +0 -0
  36. {httpdis-0.6.35 → httpdis-0.6.37}/tests/test_authentication_provider.py +0 -0
  37. {httpdis-0.6.35 → httpdis-0.6.37}/tests/test_body_limits.py +0 -0
  38. {httpdis-0.6.35 → httpdis-0.6.37}/tests/test_http_contract_errors.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: httpdis
3
- Version: 0.6.35
3
+ Version: 0.6.37
4
4
  Summary: httpdis
5
5
  Home-page: https://github.com/decryptus/httpdis
6
6
  Author: Adrien Delle Cave
@@ -121,6 +121,34 @@ parsing. Routing and header/body-size checks may run before authentication;
121
121
  unknown routes and wrong methods do not inherit another method's auth policy.
122
122
  Applications still own operation-level authorization. Public routes are unchanged.
123
123
 
124
+ ## Browser access from a separate origin (CORS)
125
+
126
+ HTTPdis denies cross-origin preflight requests by default. If a separate web
127
+ frontend needs access, register its exact origin on each route and method it uses:
128
+
129
+ ```python
130
+ server.register(create_job, 'POST', name='jobs', to_auth=True,
131
+ cors_origins=['https://console.example.org'])
132
+ ```
133
+
134
+ Use HTTPS origins without a path or trailing slash. Local development can use
135
+ an HTTP loopback origin such as `http://127.0.0.1:3000`. An empty list is the
136
+ default. Wildcards and `null` are rejected at registration.
137
+
138
+ An allowed preflight returns 204 for the requested route and method.
139
+ It accepts the request headers `Accept`, `Authorization`, `Content-Type` and
140
+ `X-Requested-With`. Send API tokens explicitly and use `credentials: "omit"`.
141
+ The actual response, including a route's authentication failure, carries the
142
+ allowed origin. Keep cookie-based browser sessions on their dedicated origin.
143
+
144
+ **Migration from 0.6.35 and earlier.** Frontends that relied on the generic
145
+ preflight need an explicit registration. A plain `OPTIONS` request returns 405
146
+ and the registered methods for an existing route, or 404 for an unknown path.
147
+ Same-origin browser clients and server-to-server clients need no CORS setup.
148
+ Browsers can send simple requests without preflight and can reuse preflight
149
+ decisions cached before an upgrade. Keep authentication and CSRF checks on
150
+ state-changing routes.
151
+
124
152
  ## Request read deadlines and query limits
125
153
 
126
154
  The default handler allows 10 seconds in total for the request line and all
@@ -165,10 +193,20 @@ continue to use the query handler; this option does not change their behavior.
165
193
  Configure `auth_basic_file` with a trusted htpasswd file and `auth_basic` with the
166
194
  realm. Set `to_auth=True` on protected routes, or use a username list such as
167
195
  `to_auth=['alice']`. A protected route without configured authentication now returns
168
- 401 rather than allowing the request. Invalid credentials are rejected; request
169
- credentials are isolated between threads. Existing `{SHA}` and system crypt hashes
170
- remain readable for compatibility; legacy SHA-1/DES hashes are not recommendations
171
- for new password storage. Basic credentials require HTTPS in transit.
196
+ 401. After successful verification and route authorization, handlers can read
197
+ the username from `request.get_server_vars()['HTTP_AUTH_USER']`.
198
+
199
+ Since 0.6.37, HTTPdis omits `HTTP_AUTH_PASSWD` from server variables and
200
+ `HttpAuthentication.passwd` returns `None`. Migrate handlers that consumed
201
+ the plaintext password to the verified username or to a dedicated downstream
202
+ credential. The incoming `Authorization` header still contains credentials:
203
+ redact it from request logs and use HTTPS for Basic authentication.
204
+
205
+ HTTPdis reads existing `{SHA}` and system crypt entries. At file load it logs
206
+ a single warning listing any SHA-1 or traditional DES formats detected.
207
+ Replace affected entries with a hash supported on the server. For example,
208
+ on a host with bcrypt support, run `htpasswd -B /path/to/htpasswd alice`,
209
+ enter the password at the prompt, reload the file and verify the login.
172
210
 
173
211
  Bind to loopback or a private interface behind a reverse proxy providing TLS,
174
212
  request timeouts, connection limits and access controls. This release does not
@@ -344,8 +382,7 @@ the optional local service described below supplies those separately. Browser lo
344
382
  HTTP routes and TOTP enrollment/replay protection remain pending. The contract does
345
383
  not configure cookies, HTTPS, CSRF or CORS automatically.
346
384
  Browser sessions must not be exposed until those transport controls and the backend
347
- are implemented and tested together. Existing HTTPdis CORS/OPTIONS behavior is
348
- unchanged by this compatibility-preserving addition.
385
+ are implemented and tested together. Configure cross-origin API access separately on the intended routes.
349
386
 
350
387
  ## Local authentication backend (development, optional)
351
388
 
@@ -520,8 +557,7 @@ Embedding requirements: serve only fixed public login/assets routes; protect all
520
557
  business routes; bound login request bodies; prohibit CORS/preflight in browser
521
558
  mode; apply no-store, CSP, frame denial and nosniff headers to errors as well as
522
559
  successes; never log credentials, payloads or cookies. `require_browser` is exposed
523
- for checking public routes before parsing their body. HTTPdis's historical generic
524
- OPTIONS behavior is unchanged: override it in the embedding browser handler.
560
+ for checking public routes before parsing their body. Leave CORS disabled on cookie-authenticated routes.
525
561
  Application scopes, ownership and action confirmation remain application policy.
526
562
  This adapter supplies no HTML UI, proxy configuration, TOTP or SSO.
527
563
 
@@ -77,6 +77,34 @@ parsing. Routing and header/body-size checks may run before authentication;
77
77
  unknown routes and wrong methods do not inherit another method's auth policy.
78
78
  Applications still own operation-level authorization. Public routes are unchanged.
79
79
 
80
+ ## Browser access from a separate origin (CORS)
81
+
82
+ HTTPdis denies cross-origin preflight requests by default. If a separate web
83
+ frontend needs access, register its exact origin on each route and method it uses:
84
+
85
+ ```python
86
+ server.register(create_job, 'POST', name='jobs', to_auth=True,
87
+ cors_origins=['https://console.example.org'])
88
+ ```
89
+
90
+ Use HTTPS origins without a path or trailing slash. Local development can use
91
+ an HTTP loopback origin such as `http://127.0.0.1:3000`. An empty list is the
92
+ default. Wildcards and `null` are rejected at registration.
93
+
94
+ An allowed preflight returns 204 for the requested route and method.
95
+ It accepts the request headers `Accept`, `Authorization`, `Content-Type` and
96
+ `X-Requested-With`. Send API tokens explicitly and use `credentials: "omit"`.
97
+ The actual response, including a route's authentication failure, carries the
98
+ allowed origin. Keep cookie-based browser sessions on their dedicated origin.
99
+
100
+ **Migration from 0.6.35 and earlier.** Frontends that relied on the generic
101
+ preflight need an explicit registration. A plain `OPTIONS` request returns 405
102
+ and the registered methods for an existing route, or 404 for an unknown path.
103
+ Same-origin browser clients and server-to-server clients need no CORS setup.
104
+ Browsers can send simple requests without preflight and can reuse preflight
105
+ decisions cached before an upgrade. Keep authentication and CSRF checks on
106
+ state-changing routes.
107
+
80
108
  ## Request read deadlines and query limits
81
109
 
82
110
  The default handler allows 10 seconds in total for the request line and all
@@ -121,10 +149,20 @@ continue to use the query handler; this option does not change their behavior.
121
149
  Configure `auth_basic_file` with a trusted htpasswd file and `auth_basic` with the
122
150
  realm. Set `to_auth=True` on protected routes, or use a username list such as
123
151
  `to_auth=['alice']`. A protected route without configured authentication now returns
124
- 401 rather than allowing the request. Invalid credentials are rejected; request
125
- credentials are isolated between threads. Existing `{SHA}` and system crypt hashes
126
- remain readable for compatibility; legacy SHA-1/DES hashes are not recommendations
127
- for new password storage. Basic credentials require HTTPS in transit.
152
+ 401. After successful verification and route authorization, handlers can read
153
+ the username from `request.get_server_vars()['HTTP_AUTH_USER']`.
154
+
155
+ Since 0.6.37, HTTPdis omits `HTTP_AUTH_PASSWD` from server variables and
156
+ `HttpAuthentication.passwd` returns `None`. Migrate handlers that consumed
157
+ the plaintext password to the verified username or to a dedicated downstream
158
+ credential. The incoming `Authorization` header still contains credentials:
159
+ redact it from request logs and use HTTPS for Basic authentication.
160
+
161
+ HTTPdis reads existing `{SHA}` and system crypt entries. At file load it logs
162
+ a single warning listing any SHA-1 or traditional DES formats detected.
163
+ Replace affected entries with a hash supported on the server. For example,
164
+ on a host with bcrypt support, run `htpasswd -B /path/to/htpasswd alice`,
165
+ enter the password at the prompt, reload the file and verify the login.
128
166
 
129
167
  Bind to loopback or a private interface behind a reverse proxy providing TLS,
130
168
  request timeouts, connection limits and access controls. This release does not
@@ -300,8 +338,7 @@ the optional local service described below supplies those separately. Browser lo
300
338
  HTTP routes and TOTP enrollment/replay protection remain pending. The contract does
301
339
  not configure cookies, HTTPS, CSRF or CORS automatically.
302
340
  Browser sessions must not be exposed until those transport controls and the backend
303
- are implemented and tested together. Existing HTTPdis CORS/OPTIONS behavior is
304
- unchanged by this compatibility-preserving addition.
341
+ are implemented and tested together. Configure cross-origin API access separately on the intended routes.
305
342
 
306
343
  ## Local authentication backend (development, optional)
307
344
 
@@ -476,8 +513,7 @@ Embedding requirements: serve only fixed public login/assets routes; protect all
476
513
  business routes; bound login request bodies; prohibit CORS/preflight in browser
477
514
  mode; apply no-store, CSP, frame denial and nosniff headers to errors as well as
478
515
  successes; never log credentials, payloads or cookies. `require_browser` is exposed
479
- for checking public routes before parsing their body. HTTPdis's historical generic
480
- OPTIONS behavior is unchanged: override it in the embedding browser handler.
516
+ for checking public routes before parsing their body. Leave CORS disabled on cookie-authenticated routes.
481
517
  Application scopes, ownership and action confirmation remain application policy.
482
518
  This adapter supplies no HTML UI, proxy configuration, TOTP or SSO.
483
519
 
httpdis-0.6.37/RELEASE ADDED
@@ -0,0 +1 @@
1
+ 0.6.37
httpdis-0.6.37/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.6.37
@@ -76,6 +76,7 @@ from sonicprobe import helpers
76
76
  from sonicprobe.libs import urisup
77
77
  from sonicprobe.libs.threading_tcp_server import KillableThreadingHTTPServer
78
78
 
79
+ from .auth_browser import browser_origin
79
80
  from .content_disposition import build_header, parse_headers
80
81
 
81
82
  from .config import (BUFFER_SIZE, # pylint: disable=unused-import
@@ -84,6 +85,7 @@ from .config import (BUFFER_SIZE, # pylint: disable=unused-import
84
85
 
85
86
 
86
87
  LOG = logging.getLogger('httpdis') # pylint: disable-msg=C0103
88
+ _DES_CRYPT_HASH = re.compile(r'[./0-9A-Za-z]{13}\Z')
87
89
  _CONTENT_LENGTH = re.compile(r'[0-9]+\Z')
88
90
  _QUERY_BRACKETS = re.compile(r'\[([^\]]*)\]')
89
91
  MAX_QUERY_FIELDS = 1024
@@ -92,6 +94,8 @@ HEADER_READ_SECONDS = 10
92
94
  BODY_GRACE_SECONDS = 10
93
95
  BODY_BYTES_PER_SECOND = 32 * 1024
94
96
  BODY_MAX_SECONDS = 120
97
+ _CORS_REQUEST_HEADERS = frozenset(('accept', 'authorization', 'content-type', 'x-requested-with'))
98
+ _CORS_PREFLIGHT_VARY = 'Origin, Access-Control-Request-Method, Access-Control-Request-Headers'
95
99
  _BODYLESS_CODES = (204, 205, 304)
96
100
  _NO_LENGTH_CODES = (204, 304)
97
101
 
@@ -138,13 +142,17 @@ class Command(object): # pylint: disable=too-few-public-methods,useless-object-i
138
142
  content_type,
139
143
  to_auth,
140
144
  to_log,
141
- max_body_size = None):
145
+ max_body_size = None,
146
+ cors_origins = ()):
142
147
  if max_body_size is not None \
143
148
  and (isinstance(max_body_size, bool) \
144
149
  or not isinstance(max_body_size, integer_types) \
145
150
  or max_body_size < 0):
146
151
  raise ValueError("max_body_size must be a non-negative integer or None")
147
152
 
153
+ if not isinstance(cors_origins, (list, tuple)):
154
+ raise ValueError('cors_origins must be a list or tuple of explicit origins')
155
+ self.cors_origins = frozenset(browser_origin(origin) for origin in cors_origins)
148
156
  self.max_body_size = max_body_size
149
157
  self.handler = handler
150
158
  self.name = name
@@ -277,21 +285,24 @@ class HttpAuthentication(object): # pylint: disable=useless-object-inheritance
277
285
  self._credentials = threading.local()
278
286
 
279
287
  def parse_file(self):
280
- f = None
281
-
282
- try:
283
- with open(self.htpasswd, 'r') as f:
284
- for line in f.readlines():
285
- tmp = line.strip()
286
- if not tmp or tmp.startswith('#') or tmp.find(':') < 1:
287
- continue
288
- user, passwd = tmp.split(':', 1)
289
- if not passwd:
290
- continue
291
- self.users[user] = passwd
292
- finally:
293
- if f:
294
- f.close()
288
+ legacy_formats = set()
289
+ with open(self.htpasswd, 'r') as stream:
290
+ for line in stream:
291
+ entry = line.strip()
292
+ if not entry or entry.startswith('#') or entry.find(':') < 1:
293
+ continue
294
+ user, secret = entry.split(':', 1)
295
+ if not secret:
296
+ continue
297
+ self.users[user] = secret
298
+ if secret.startswith('{SHA}'):
299
+ legacy_formats.add('SHA-1')
300
+ elif _DES_CRYPT_HASH.match(secret):
301
+ legacy_formats.add('DES')
302
+ if legacy_formats:
303
+ LOG.warning('Legacy Basic password hashes detected (%s). '
304
+ 'Update the affected htpasswd entries.',
305
+ ', '.join(sorted(legacy_formats)))
295
306
 
296
307
  return self
297
308
 
@@ -301,10 +312,11 @@ class HttpAuthentication(object): # pylint: disable=useless-object-inheritance
301
312
 
302
313
  @property
303
314
  def passwd(self):
304
- return getattr(self._credentials, 'passwd', None)
315
+ """Compatibility accessor. The verifier retains only the username."""
316
+ return None
305
317
 
306
318
  def valid_authorization(self, authorization):
307
- self._credentials.user = self._credentials.passwd = None
319
+ self._credentials.user = None
308
320
  try:
309
321
  kind, data = authorization.split(None, 1)
310
322
  if kind.lower() != 'basic':
@@ -326,7 +338,7 @@ class HttpAuthentication(object): # pylint: disable=useless-object-inheritance
326
338
  calculated = crypt(password, secret)
327
339
  if not calculated or not compare_digest(ensure_binary(secret), ensure_binary(calculated)):
328
340
  return False
329
- self._credentials.user, self._credentials.passwd = user, password
341
+ self._credentials.user = user
330
342
  return True
331
343
 
332
344
  def unauthorized(self, req_error = None):
@@ -581,7 +593,17 @@ class HttpReqHandler(BaseHTTPRequestHandler):
581
593
  if code >= 200 and code not in _NO_LENGTH_CODES:
582
594
  self.send_header('Content-Length', str(clen))
583
595
 
596
+ route_cors = self._cmd and self._cmd.cors_origins and self.command != 'OPTIONS'
597
+ if route_cors:
598
+ # Emit per request. A handler may reuse a response across origins.
599
+ self.send_header('Vary', 'Origin')
600
+ origin = self._allowed_origin(self._cmd)
601
+ if origin:
602
+ self.send_header('Access-Control-Allow-Origin', origin)
603
+
584
604
  for header, value in response.header_items():
605
+ if route_cors and header.lower() in ('access-control-allow-origin', 'access-control-allow-credentials'):
606
+ continue
585
607
  if header.lower() not in tuple(h.lower() for h in _END_EXC_HEADERS):
586
608
  self.send_header(header, value)
587
609
 
@@ -879,19 +901,11 @@ class HttpReqHandler(BaseHTTPRequestHandler):
879
901
  if not auth:
880
902
  raise auth_context.unauthorized()
881
903
 
882
- allowed = auth_context.valid_authorization(auth)
883
-
884
- if not allowed or None in (auth_context.user, auth_context.passwd):
904
+ if not auth_context.valid_authorization(auth) or auth_context.user is None:
885
905
  raise auth_context.unauthorized()
886
-
887
- self._SERVER['HTTP_AUTH_USER'] = auth_context.user
888
- self._SERVER['HTTP_AUTH_PASSWD'] = auth_context.passwd
889
-
890
906
  if auth_users and auth_context.user not in auth_users:
891
907
  raise auth_context.unauthorized()
892
-
893
- if not allowed:
894
- raise auth_context.unauthorized()
908
+ self._SERVER['HTTP_AUTH_USER'] = auth_context.user
895
909
 
896
910
  def _authenticate_provider(self, provider, auth_users):
897
911
  headers = tuple((key.lower(), value) for key, value in self.headers.items()
@@ -957,6 +971,22 @@ class HttpReqHandler(BaseHTTPRequestHandler):
957
971
 
958
972
  return repr(data)
959
973
 
974
+ def _resolve_command(self, method, cmd):
975
+ context = self.get_context()
976
+ if not isinstance(self._query_params, dict):
977
+ self._query_params = {}
978
+ named = context.named_commands.get('%s /%s' % (method, cmd))
979
+ if named is not None:
980
+ return named
981
+ for key in sorted(context.regex_commands, key=len, reverse=True):
982
+ if key.startswith(method + ' '):
983
+ command = context.regex_commands[key]
984
+ match = command.name.match(cmd)
985
+ if match:
986
+ self._query_params.update(match.groupdict())
987
+ return command
988
+ return None
989
+
960
990
  def _missing_command(self, cmd):
961
991
  """Distinguish an unknown path from an unsupported registered method."""
962
992
  context = self.get_context()
@@ -977,25 +1007,8 @@ class HttpReqHandler(BaseHTTPRequestHandler):
977
1007
  """
978
1008
  Callback for .execute_command() for DELETE/GET/HEAD requests
979
1009
  """
980
- context = self.get_context()
981
1010
  res = None
982
- ckey = "%s /%s" % (self.command, cmd)
983
-
984
- if not isinstance(self._query_params, dict):
985
- self._query_params = {}
986
-
987
- if ckey in context.named_commands:
988
- self._cmd = context.named_commands[ckey]
989
- else:
990
- for key in sorted(context.regex_commands, key=len, reverse=True):
991
- if not key.startswith("%s " % self.command):
992
- continue
993
-
994
- m = context.regex_commands[key].name.match(cmd)
995
- if m:
996
- self._cmd = context.regex_commands[key]
997
- self._query_params.update(m.groupdict())
998
- break
1011
+ self._cmd = self._resolve_command(self.command, cmd)
999
1012
 
1000
1013
  try:
1001
1014
  if not self._cmd:
@@ -1024,13 +1037,22 @@ class HttpReqHandler(BaseHTTPRequestHandler):
1024
1037
  finally:
1025
1038
  self._query_params = {}
1026
1039
 
1040
+ def _header_values(self, name):
1041
+ get_all = getattr(self.headers, 'get_all', None) or getattr(self.headers, 'getheaders', None)
1042
+ if get_all is not None:
1043
+ return get_all(name) or []
1044
+ return [self.headers[name]] if name in self.headers else []
1045
+
1046
+ def _allowed_origin(self, command):
1047
+ origins = self._header_values('Origin')
1048
+ if len(origins) == 1 and origins[0] in command.cors_origins:
1049
+ return origins[0]
1050
+ return None
1051
+
1027
1052
  def _validate_request_framing(self):
1028
1053
  """Reject ambiguous framing before authentication or application code."""
1029
- get_all = getattr(self.headers, 'get_all', None) or getattr(self.headers, 'getheaders', None)
1030
- if get_all is None:
1031
- get_all = lambda name: ([self.headers[name]] if name in self.headers else [])
1032
- lengths = get_all('Content-Length') or []
1033
- encodings = get_all('Transfer-Encoding') or []
1054
+ lengths = self._header_values('Content-Length')
1055
+ encodings = self._header_values('Transfer-Encoding')
1034
1056
  self.close_connection = True
1035
1057
  if encodings and lengths:
1036
1058
  raise self.req_error(400, 'Conflicting request framing')
@@ -1072,23 +1094,7 @@ class HttpReqHandler(BaseHTTPRequestHandler):
1072
1094
  """
1073
1095
  context = self.get_context()
1074
1096
  multipart = False
1075
- ckey = "%s /%s" % (self.command, cmd)
1076
-
1077
- if not isinstance(self._query_params, dict):
1078
- self._query_params = {}
1079
-
1080
- if ckey in context.named_commands:
1081
- self._cmd = context.named_commands[ckey]
1082
- else:
1083
- for key in sorted(context.regex_commands, key=len, reverse=True):
1084
- if not key.startswith("%s " % self.command):
1085
- continue
1086
-
1087
- m = context.regex_commands[key].name.match(cmd)
1088
- if m:
1089
- self._cmd = context.regex_commands[key]
1090
- self._query_params.update(m.groupdict())
1091
- break
1097
+ self._cmd = self._resolve_command(self.command, cmd)
1092
1098
 
1093
1099
  try:
1094
1100
  if not self._cmd:
@@ -1221,17 +1227,35 @@ class HttpReqHandler(BaseHTTPRequestHandler):
1221
1227
 
1222
1228
  def do_OPTIONS(self):
1223
1229
  "OPTIONS method"
1230
+ self._query_params = {}
1231
+ self._cmd = None
1224
1232
  try:
1225
1233
  self._validate_request_framing()
1234
+ cmd = self._pathify()[1:]
1235
+ methods = self._header_values('Access-Control-Request-Method')
1236
+ if not methods:
1237
+ raise self._missing_command(cmd)
1238
+ if len(methods) != 1 or methods[0] not in _METHODS:
1239
+ raise self.req_error(403)
1240
+ command = self._resolve_command(methods[0], cmd)
1241
+ origin = self._allowed_origin(command) if command is not None else None
1242
+ if not origin:
1243
+ raise self.req_error(403)
1244
+ headers = [name.strip().lower()
1245
+ for line in self._header_values('Access-Control-Request-Headers')
1246
+ for name in line.split(',')]
1247
+ if not _CORS_REQUEST_HEADERS.issuperset(headers):
1248
+ raise self.req_error(403)
1226
1249
  except HttpReqError as error:
1227
1250
  error.report(self)
1228
1251
  return
1229
- req = self.build_response(code = 204)
1230
- req.add_header('Access-Control-Allow-Origin', "*")
1231
- req.add_header('Access-Control-Allow-Methods', "OPTIONS, POST")
1232
- req.add_header('Access-Control-Allow-Headers', "Origin, X-Requested-With, Content-Type, Accept, Authorization")
1233
- req.add_header('Access-Control-Max-Age', 1728000)
1234
- self.end_response(req)
1252
+ response = self.build_response(code=204)
1253
+ response.add_header('Access-Control-Allow-Origin', origin)
1254
+ response.add_header('Access-Control-Allow-Methods', methods[0])
1255
+ response.add_header('Vary', _CORS_PREFLIGHT_VARY)
1256
+ if headers:
1257
+ response.add_header('Access-Control-Allow-Headers', ', '.join(sorted(set(headers))))
1258
+ self.end_response(response)
1235
1259
 
1236
1260
  def do_PATCH(self):
1237
1261
  "POST method"
@@ -1288,7 +1312,8 @@ class HttpServerContext(object):
1288
1312
  content_type = None,
1289
1313
  to_auth = False,
1290
1314
  to_log = True,
1291
- max_body_size = None):
1315
+ max_body_size = None,
1316
+ cors_origins = ()):
1292
1317
  """
1293
1318
  Register a command
1294
1319
  @handler: function to execute when the command is received
@@ -1304,6 +1329,7 @@ class HttpServerContext(object):
1304
1329
  @content_type: content_type
1305
1330
  @to_auth: use basic authentification if True
1306
1331
  @to_log: log request if True
1332
+ @cors_origins: explicit origins allowed to read this route from a browser
1307
1333
  @max_body_size: maximum request body bytes; None inherits this context's limit
1308
1334
 
1309
1335
  prototypes:
@@ -1361,7 +1387,8 @@ class HttpServerContext(object):
1361
1387
  content_type,
1362
1388
  to_auth,
1363
1389
  to_log,
1364
- max_body_size)
1390
+ max_body_size,
1391
+ cors_origins)
1365
1392
 
1366
1393
  for method in methods:
1367
1394
  if not is_reg:
@@ -1576,10 +1603,11 @@ def register(handler,
1576
1603
  content_type = None,
1577
1604
  to_auth = False,
1578
1605
  to_log = True,
1579
- max_body_size = None):
1606
+ max_body_size = None,
1607
+ cors_origins = ()):
1580
1608
  return _DEFAULT_CONTEXT.register(handler, op, safe_init, at_start, name,
1581
1609
  at_stop, static, root, replacement, charset,
1582
- content_type, to_auth, to_log, max_body_size)
1610
+ content_type, to_auth, to_log, max_body_size, cors_origins)
1583
1611
 
1584
1612
 
1585
1613
  def sigterm_handler(signum, stack_frame):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: httpdis
3
- Version: 0.6.35
3
+ Version: 0.6.37
4
4
  Summary: httpdis
5
5
  Home-page: https://github.com/decryptus/httpdis
6
6
  Author: Adrien Delle Cave
@@ -121,6 +121,34 @@ parsing. Routing and header/body-size checks may run before authentication;
121
121
  unknown routes and wrong methods do not inherit another method's auth policy.
122
122
  Applications still own operation-level authorization. Public routes are unchanged.
123
123
 
124
+ ## Browser access from a separate origin (CORS)
125
+
126
+ HTTPdis denies cross-origin preflight requests by default. If a separate web
127
+ frontend needs access, register its exact origin on each route and method it uses:
128
+
129
+ ```python
130
+ server.register(create_job, 'POST', name='jobs', to_auth=True,
131
+ cors_origins=['https://console.example.org'])
132
+ ```
133
+
134
+ Use HTTPS origins without a path or trailing slash. Local development can use
135
+ an HTTP loopback origin such as `http://127.0.0.1:3000`. An empty list is the
136
+ default. Wildcards and `null` are rejected at registration.
137
+
138
+ An allowed preflight returns 204 for the requested route and method.
139
+ It accepts the request headers `Accept`, `Authorization`, `Content-Type` and
140
+ `X-Requested-With`. Send API tokens explicitly and use `credentials: "omit"`.
141
+ The actual response, including a route's authentication failure, carries the
142
+ allowed origin. Keep cookie-based browser sessions on their dedicated origin.
143
+
144
+ **Migration from 0.6.35 and earlier.** Frontends that relied on the generic
145
+ preflight need an explicit registration. A plain `OPTIONS` request returns 405
146
+ and the registered methods for an existing route, or 404 for an unknown path.
147
+ Same-origin browser clients and server-to-server clients need no CORS setup.
148
+ Browsers can send simple requests without preflight and can reuse preflight
149
+ decisions cached before an upgrade. Keep authentication and CSRF checks on
150
+ state-changing routes.
151
+
124
152
  ## Request read deadlines and query limits
125
153
 
126
154
  The default handler allows 10 seconds in total for the request line and all
@@ -165,10 +193,20 @@ continue to use the query handler; this option does not change their behavior.
165
193
  Configure `auth_basic_file` with a trusted htpasswd file and `auth_basic` with the
166
194
  realm. Set `to_auth=True` on protected routes, or use a username list such as
167
195
  `to_auth=['alice']`. A protected route without configured authentication now returns
168
- 401 rather than allowing the request. Invalid credentials are rejected; request
169
- credentials are isolated between threads. Existing `{SHA}` and system crypt hashes
170
- remain readable for compatibility; legacy SHA-1/DES hashes are not recommendations
171
- for new password storage. Basic credentials require HTTPS in transit.
196
+ 401. After successful verification and route authorization, handlers can read
197
+ the username from `request.get_server_vars()['HTTP_AUTH_USER']`.
198
+
199
+ Since 0.6.37, HTTPdis omits `HTTP_AUTH_PASSWD` from server variables and
200
+ `HttpAuthentication.passwd` returns `None`. Migrate handlers that consumed
201
+ the plaintext password to the verified username or to a dedicated downstream
202
+ credential. The incoming `Authorization` header still contains credentials:
203
+ redact it from request logs and use HTTPS for Basic authentication.
204
+
205
+ HTTPdis reads existing `{SHA}` and system crypt entries. At file load it logs
206
+ a single warning listing any SHA-1 or traditional DES formats detected.
207
+ Replace affected entries with a hash supported on the server. For example,
208
+ on a host with bcrypt support, run `htpasswd -B /path/to/htpasswd alice`,
209
+ enter the password at the prompt, reload the file and verify the login.
172
210
 
173
211
  Bind to loopback or a private interface behind a reverse proxy providing TLS,
174
212
  request timeouts, connection limits and access controls. This release does not
@@ -344,8 +382,7 @@ the optional local service described below supplies those separately. Browser lo
344
382
  HTTP routes and TOTP enrollment/replay protection remain pending. The contract does
345
383
  not configure cookies, HTTPS, CSRF or CORS automatically.
346
384
  Browser sessions must not be exposed until those transport controls and the backend
347
- are implemented and tested together. Existing HTTPdis CORS/OPTIONS behavior is
348
- unchanged by this compatibility-preserving addition.
385
+ are implemented and tested together. Configure cross-origin API access separately on the intended routes.
349
386
 
350
387
  ## Local authentication backend (development, optional)
351
388
 
@@ -520,8 +557,7 @@ Embedding requirements: serve only fixed public login/assets routes; protect all
520
557
  business routes; bound login request bodies; prohibit CORS/preflight in browser
521
558
  mode; apply no-store, CSP, frame denial and nosniff headers to errors as well as
522
559
  successes; never log credentials, payloads or cookies. `require_browser` is exposed
523
- for checking public routes before parsing their body. HTTPdis's historical generic
524
- OPTIONS behavior is unchanged: override it in the embedding browser handler.
560
+ for checking public routes before parsing their body. Leave CORS disabled on cookie-authenticated routes.
525
561
  Application scopes, ownership and action confirmation remain application policy.
526
562
  This adapter supplies no HTML UI, proxy configuration, TOTP or SSO.
527
563
 
@@ -30,5 +30,6 @@ tests/test_auth_sqlite.py
30
30
  tests/test_authentication_provider.py
31
31
  tests/test_body_limits.py
32
32
  tests/test_context.py
33
+ tests/test_cors.py
33
34
  tests/test_http_contract_errors.py
34
35
  tests/test_httpdis.py
@@ -4,8 +4,8 @@ description: httpdis
4
4
  author: Adrien Delle Cave
5
5
  author_email: pypi@doowan.net
6
6
  copyright: '2022-2026 Adrien Delle Cave'
7
- release: '0.6.35'
8
- version: '0.6.35'
7
+ release: '0.6.37'
8
+ version: '0.6.37'
9
9
  license: License GPL-3
10
10
  url: https://github.com/decryptus/httpdis
11
11
  python_requires:
@@ -60,7 +60,9 @@ class ContextTests(unittest.TestCase):
60
60
  ready = threading.Event()
61
61
  hooks = []
62
62
  def identity(request):
63
- return {'label': label, 'user': request.get_server_vars().get('HTTP_AUTH_USER')}
63
+ values = request.get_server_vars()
64
+ self.assertNotIn('HTTP_AUTH_PASSWD', values)
65
+ return {'label': label, 'user': values.get('HTTP_AUTH_USER')}
64
66
  context.register(identity, 'GET', name='identity', to_auth=True,
65
67
  safe_init=lambda options: hooks.append(('init', options['max_body_size'])),
66
68
  at_start=lambda options: ready.set(),
@@ -98,6 +100,27 @@ class ContextTests(unittest.TestCase):
98
100
  finally:
99
101
  connection.close()
100
102
 
103
+ def test_htpasswd_warns_once_without_account_or_hash_data(self):
104
+ path = self.credentials('private-account')
105
+ with open(path, 'a') as stream:
106
+ stream.write('other-account:abJnggxhB/yWI\n')
107
+ with mock.patch.object(h.LOG, 'warning') as warning:
108
+ auth = h.HttpAuthentication(path).parse_file()
109
+ self.assertTrue(auth.valid_authorization('Basic ' + base64.b64encode(
110
+ b'private-account:secret').decode('ascii')))
111
+ self.assertEqual(warning.call_count, 1)
112
+ arguments = warning.call_args[0]
113
+ message = arguments[0] % arguments[1:]
114
+ self.assertIn('SHA-1', message)
115
+ self.assertIn('DES', message)
116
+ for value in list(auth.users) + list(auth.users.values()):
117
+ self.assertNotIn(value, message)
118
+ with open(path, 'w') as stream:
119
+ stream.write('# comment\nmodern:$6$salt$verification-data\n')
120
+ with mock.patch.object(h.LOG, 'warning') as warning:
121
+ h.HttpAuthentication(path).parse_file()
122
+ self.assertFalse(warning.called)
123
+
101
124
  def test_idle_connections_release_all_workers(self):
102
125
  class FastHeader(j.HttpReqHandler):
103
126
  header_read_seconds = .25
@@ -0,0 +1,91 @@
1
+ """Exercise route-level browser access on the wire, including handler errors."""
2
+ import re
3
+ import threading
4
+ import unittest
5
+
6
+ from six.moves import http_client
7
+ from six.moves.BaseHTTPServer import HTTPServer
8
+ from httpdis import httpdis as h
9
+ from httpdis.ext import httpdis_json as j
10
+
11
+
12
+ ORIGIN = 'https://console.example.org'
13
+ ROUTE = re.compile(r'^jobs/(?P<id>[0-9]+)$')
14
+
15
+
16
+ class CorsTests(unittest.TestCase):
17
+ def setUp(self):
18
+ self.calls = []
19
+ self.shared = h.HttpResponse(data='result', headers={'Vary': 'Accept-Encoding'})
20
+ context = j.HttpServerContext()
21
+ context.init({})
22
+ def callback(request):
23
+ self.calls.append(request.query_params().get('id'))
24
+ return self.shared
25
+ context.register(callback, 'POST', name=ROUTE, cors_origins=[ORIGIN])
26
+ context.register(callback, 'POST', name='jobs/0')
27
+ context.register(callback, 'GET', name='private', to_auth=True, cors_origins=[ORIGIN])
28
+ self.server = HTTPServer(('127.0.0.1', 0), context.bind_handler())
29
+ thread = threading.Thread(target=self.server.serve_forever, kwargs={'poll_interval': .01})
30
+ thread.daemon = True
31
+ thread.start()
32
+ self.addCleanup(thread.join, 2)
33
+ self.addCleanup(self.server.server_close)
34
+ self.addCleanup(self.server.shutdown)
35
+
36
+ def request(self, method, path, headers):
37
+ connection = http_client.HTTPConnection('127.0.0.1', self.server.server_port, timeout=2)
38
+ try:
39
+ connection.putrequest(method, path)
40
+ for name, value in headers:
41
+ connection.putheader(name, value)
42
+ connection.endheaders()
43
+ response = connection.getresponse()
44
+ response.read()
45
+ return response
46
+ finally:
47
+ connection.close()
48
+
49
+ def test_exact_origin_method_headers_and_named_route_precedence(self):
50
+ base = [('Origin', ORIGIN), ('Access-Control-Request-Method', 'POST')]
51
+ permitted = base + [('Access-Control-Request-Headers', 'Authorization, Content-Type')]
52
+ reply = self.request('OPTIONS', '/jobs/1', permitted)
53
+ self.assertEqual(reply.status, 204)
54
+ self.assertEqual(reply.getheader('Access-Control-Allow-Origin'), ORIGIN)
55
+ self.assertEqual(reply.getheader('Access-Control-Allow-Methods'), 'POST')
56
+ self.assertEqual(reply.getheader('Access-Control-Allow-Headers'), 'authorization, content-type')
57
+ for path, headers in (('/jobs/0', base), ('/missing', base),
58
+ ('/jobs/1', [('Origin', ORIGIN), ('Access-Control-Request-Method', 'PUT')]),
59
+ ('/jobs/1', base + [('Access-Control-Request-Headers', 'x-secret')]),
60
+ ('/jobs/1', base + [('Origin', ORIGIN)]),
61
+ ('/jobs/1', base + [('Access-Control-Request-Method', 'POST')]),
62
+ ('/jobs/1', [('Origin', ORIGIN + '.evil'), base[1]])):
63
+ reply = self.request('OPTIONS', path, headers)
64
+ self.assertEqual(reply.status, 403)
65
+ self.assertIsNone(reply.getheader('Access-Control-Allow-Origin'))
66
+ self.assertEqual(self.calls, [])
67
+
68
+ def test_plain_options_lists_registered_methods(self):
69
+ response = self.request('OPTIONS', '/jobs/1', [])
70
+ self.assertEqual(response.status, 405)
71
+ self.assertEqual(response.getheader('Allow'), 'POST')
72
+ self.assertEqual(self.request('OPTIONS', '/missing', []).status, 404)
73
+
74
+ def test_actual_response_is_request_local_and_preserves_authentication(self):
75
+ for origin, expected in ((ORIGIN, ORIGIN), ('null', None), (ORIGIN + '.evil', None)):
76
+ response = self.request('POST', '/jobs/1', [('Origin', origin)])
77
+ self.assertEqual(response.status, 200)
78
+ self.assertEqual(response.getheader('Access-Control-Allow-Origin'), expected)
79
+ self.assertIsNone(response.getheader('Access-Control-Allow-Credentials'))
80
+ self.assertIn('Accept-Encoding', response.getheader('Vary'))
81
+ self.assertIn('Origin', response.getheader('Vary'))
82
+ denied = self.request('GET', '/private', [('Origin', ORIGIN)])
83
+ self.assertEqual(denied.status, 401)
84
+ self.assertEqual(denied.getheader('Access-Control-Allow-Origin'), ORIGIN)
85
+ self.assertEqual(self.calls, ['1', '1', '1'])
86
+ self.assertIsNone(self.shared.get_header('Access-control-allow-origin'))
87
+
88
+ def test_registration_rejects_invalid_origins(self):
89
+ for value in (ORIGIN, ['*'], ['null'], [ORIGIN + '/path'], ['https://user@host']):
90
+ with self.assertRaises(ValueError):
91
+ h.register(lambda r: None, 'GET', name='invalid-cors', cors_origins=value)
@@ -25,6 +25,8 @@ class HttpTests(unittest.TestCase):
25
25
  auth.users['alice'] = '{SHA}' + base64.b64encode(hashlib.sha1(b'secret').digest()).decode('ascii')
26
26
  self.assertTrue(auth.valid_authorization('Basic ' + base64.b64encode(b'alice:secret').decode('ascii')))
27
27
  self.assertEqual(auth.user, 'alice')
28
+ self.assertIsNone(auth.passwd)
29
+ self.assertNotIn('passwd', vars(auth._credentials))
28
30
  for invalid in ('', 'Basic', 'Bearer abc', 'Basic !!!', 'Basic bm9jb2xvbg==', 'Basic YWxpY2U6YmFk'):
29
31
  self.assertFalse(auth.valid_authorization(invalid))
30
32
  self.assertIsNone(auth.user)
httpdis-0.6.35/RELEASE DELETED
@@ -1 +0,0 @@
1
- 0.6.35
httpdis-0.6.35/VERSION DELETED
@@ -1 +0,0 @@
1
- 0.6.35
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes