httpdis 0.6.35__tar.gz → 0.6.36__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.36}/PKG-INFO +31 -5
  2. {httpdis-0.6.35 → httpdis-0.6.36}/README.md +30 -4
  3. httpdis-0.6.36/RELEASE +1 -0
  4. httpdis-0.6.36/VERSION +1 -0
  5. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis/httpdis.py +82 -51
  6. {httpdis-0.6.35 → httpdis-0.6.36/httpdis.egg-info}/PKG-INFO +31 -5
  7. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis.egg-info/SOURCES.txt +1 -0
  8. {httpdis-0.6.35 → httpdis-0.6.36}/setup.yml +2 -2
  9. httpdis-0.6.36/tests/test_cors.py +91 -0
  10. httpdis-0.6.35/RELEASE +0 -1
  11. httpdis-0.6.35/VERSION +0 -1
  12. {httpdis-0.6.35 → httpdis-0.6.36}/LICENSE +0 -0
  13. {httpdis-0.6.35 → httpdis-0.6.36}/MANIFEST.in +0 -0
  14. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis/__init__.py +0 -0
  15. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis/auth_backend.py +0 -0
  16. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis/auth_browser.py +0 -0
  17. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis/auth_sqlite.py +0 -0
  18. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis/authentication.py +0 -0
  19. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis/config.py +0 -0
  20. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis/content_disposition.py +0 -0
  21. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis/ext/__init__.py +0 -0
  22. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis/ext/httpdis_json.py +0 -0
  23. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis.egg-info/dependency_links.txt +0 -0
  24. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis.egg-info/requires.txt +0 -0
  25. {httpdis-0.6.35 → httpdis-0.6.36}/httpdis.egg-info/top_level.txt +0 -0
  26. {httpdis-0.6.35 → httpdis-0.6.36}/pyproject.toml +0 -0
  27. {httpdis-0.6.35 → httpdis-0.6.36}/requirements.txt +0 -0
  28. {httpdis-0.6.35 → httpdis-0.6.36}/setup.cfg +0 -0
  29. {httpdis-0.6.35 → httpdis-0.6.36}/setup.py +0 -0
  30. {httpdis-0.6.35 → httpdis-0.6.36}/tests/test_audit_regressions.py +0 -0
  31. {httpdis-0.6.35 → httpdis-0.6.36}/tests/test_auth_backend.py +0 -0
  32. {httpdis-0.6.35 → httpdis-0.6.36}/tests/test_auth_browser.py +0 -0
  33. {httpdis-0.6.35 → httpdis-0.6.36}/tests/test_auth_sqlite.py +0 -0
  34. {httpdis-0.6.35 → httpdis-0.6.36}/tests/test_authentication_provider.py +0 -0
  35. {httpdis-0.6.35 → httpdis-0.6.36}/tests/test_body_limits.py +0 -0
  36. {httpdis-0.6.35 → httpdis-0.6.36}/tests/test_context.py +0 -0
  37. {httpdis-0.6.35 → httpdis-0.6.36}/tests/test_http_contract_errors.py +0 -0
  38. {httpdis-0.6.35 → httpdis-0.6.36}/tests/test_httpdis.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.36
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
@@ -344,8 +372,7 @@ the optional local service described below supplies those separately. Browser lo
344
372
  HTTP routes and TOTP enrollment/replay protection remain pending. The contract does
345
373
  not configure cookies, HTTPS, CSRF or CORS automatically.
346
374
  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.
375
+ are implemented and tested together. Configure cross-origin API access separately on the intended routes.
349
376
 
350
377
  ## Local authentication backend (development, optional)
351
378
 
@@ -520,8 +547,7 @@ Embedding requirements: serve only fixed public login/assets routes; protect all
520
547
  business routes; bound login request bodies; prohibit CORS/preflight in browser
521
548
  mode; apply no-store, CSP, frame denial and nosniff headers to errors as well as
522
549
  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.
550
+ for checking public routes before parsing their body. Leave CORS disabled on cookie-authenticated routes.
525
551
  Application scopes, ownership and action confirmation remain application policy.
526
552
  This adapter supplies no HTML UI, proxy configuration, TOTP or SSO.
527
553
 
@@ -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
@@ -300,8 +328,7 @@ the optional local service described below supplies those separately. Browser lo
300
328
  HTTP routes and TOTP enrollment/replay protection remain pending. The contract does
301
329
  not configure cookies, HTTPS, CSRF or CORS automatically.
302
330
  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.
331
+ are implemented and tested together. Configure cross-origin API access separately on the intended routes.
305
332
 
306
333
  ## Local authentication backend (development, optional)
307
334
 
@@ -476,8 +503,7 @@ Embedding requirements: serve only fixed public login/assets routes; protect all
476
503
  business routes; bound login request bodies; prohibit CORS/preflight in browser
477
504
  mode; apply no-store, CSP, frame denial and nosniff headers to errors as well as
478
505
  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.
506
+ for checking public routes before parsing their body. Leave CORS disabled on cookie-authenticated routes.
481
507
  Application scopes, ownership and action confirmation remain application policy.
482
508
  This adapter supplies no HTML UI, proxy configuration, TOTP or SSO.
483
509
 
httpdis-0.6.36/RELEASE ADDED
@@ -0,0 +1 @@
1
+ 0.6.36
httpdis-0.6.36/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.6.36
@@ -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
@@ -92,6 +93,8 @@ HEADER_READ_SECONDS = 10
92
93
  BODY_GRACE_SECONDS = 10
93
94
  BODY_BYTES_PER_SECOND = 32 * 1024
94
95
  BODY_MAX_SECONDS = 120
96
+ _CORS_REQUEST_HEADERS = frozenset(('accept', 'authorization', 'content-type', 'x-requested-with'))
97
+ _CORS_PREFLIGHT_VARY = 'Origin, Access-Control-Request-Method, Access-Control-Request-Headers'
95
98
  _BODYLESS_CODES = (204, 205, 304)
96
99
  _NO_LENGTH_CODES = (204, 304)
97
100
 
@@ -138,13 +141,17 @@ class Command(object): # pylint: disable=too-few-public-methods,useless-object-i
138
141
  content_type,
139
142
  to_auth,
140
143
  to_log,
141
- max_body_size = None):
144
+ max_body_size = None,
145
+ cors_origins = ()):
142
146
  if max_body_size is not None \
143
147
  and (isinstance(max_body_size, bool) \
144
148
  or not isinstance(max_body_size, integer_types) \
145
149
  or max_body_size < 0):
146
150
  raise ValueError("max_body_size must be a non-negative integer or None")
147
151
 
152
+ if not isinstance(cors_origins, (list, tuple)):
153
+ raise ValueError('cors_origins must be a list or tuple of explicit origins')
154
+ self.cors_origins = frozenset(browser_origin(origin) for origin in cors_origins)
148
155
  self.max_body_size = max_body_size
149
156
  self.handler = handler
150
157
  self.name = name
@@ -581,7 +588,17 @@ class HttpReqHandler(BaseHTTPRequestHandler):
581
588
  if code >= 200 and code not in _NO_LENGTH_CODES:
582
589
  self.send_header('Content-Length', str(clen))
583
590
 
591
+ route_cors = self._cmd and self._cmd.cors_origins and self.command != 'OPTIONS'
592
+ if route_cors:
593
+ # Emit per request. A handler may reuse a response across origins.
594
+ self.send_header('Vary', 'Origin')
595
+ origin = self._allowed_origin(self._cmd)
596
+ if origin:
597
+ self.send_header('Access-Control-Allow-Origin', origin)
598
+
584
599
  for header, value in response.header_items():
600
+ if route_cors and header.lower() in ('access-control-allow-origin', 'access-control-allow-credentials'):
601
+ continue
585
602
  if header.lower() not in tuple(h.lower() for h in _END_EXC_HEADERS):
586
603
  self.send_header(header, value)
587
604
 
@@ -957,6 +974,22 @@ class HttpReqHandler(BaseHTTPRequestHandler):
957
974
 
958
975
  return repr(data)
959
976
 
977
+ def _resolve_command(self, method, cmd):
978
+ context = self.get_context()
979
+ if not isinstance(self._query_params, dict):
980
+ self._query_params = {}
981
+ named = context.named_commands.get('%s /%s' % (method, cmd))
982
+ if named is not None:
983
+ return named
984
+ for key in sorted(context.regex_commands, key=len, reverse=True):
985
+ if key.startswith(method + ' '):
986
+ command = context.regex_commands[key]
987
+ match = command.name.match(cmd)
988
+ if match:
989
+ self._query_params.update(match.groupdict())
990
+ return command
991
+ return None
992
+
960
993
  def _missing_command(self, cmd):
961
994
  """Distinguish an unknown path from an unsupported registered method."""
962
995
  context = self.get_context()
@@ -977,25 +1010,8 @@ class HttpReqHandler(BaseHTTPRequestHandler):
977
1010
  """
978
1011
  Callback for .execute_command() for DELETE/GET/HEAD requests
979
1012
  """
980
- context = self.get_context()
981
1013
  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
1014
+ self._cmd = self._resolve_command(self.command, cmd)
999
1015
 
1000
1016
  try:
1001
1017
  if not self._cmd:
@@ -1024,13 +1040,22 @@ class HttpReqHandler(BaseHTTPRequestHandler):
1024
1040
  finally:
1025
1041
  self._query_params = {}
1026
1042
 
1043
+ def _header_values(self, name):
1044
+ get_all = getattr(self.headers, 'get_all', None) or getattr(self.headers, 'getheaders', None)
1045
+ if get_all is not None:
1046
+ return get_all(name) or []
1047
+ return [self.headers[name]] if name in self.headers else []
1048
+
1049
+ def _allowed_origin(self, command):
1050
+ origins = self._header_values('Origin')
1051
+ if len(origins) == 1 and origins[0] in command.cors_origins:
1052
+ return origins[0]
1053
+ return None
1054
+
1027
1055
  def _validate_request_framing(self):
1028
1056
  """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 []
1057
+ lengths = self._header_values('Content-Length')
1058
+ encodings = self._header_values('Transfer-Encoding')
1034
1059
  self.close_connection = True
1035
1060
  if encodings and lengths:
1036
1061
  raise self.req_error(400, 'Conflicting request framing')
@@ -1072,23 +1097,7 @@ class HttpReqHandler(BaseHTTPRequestHandler):
1072
1097
  """
1073
1098
  context = self.get_context()
1074
1099
  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
1100
+ self._cmd = self._resolve_command(self.command, cmd)
1092
1101
 
1093
1102
  try:
1094
1103
  if not self._cmd:
@@ -1221,17 +1230,35 @@ class HttpReqHandler(BaseHTTPRequestHandler):
1221
1230
 
1222
1231
  def do_OPTIONS(self):
1223
1232
  "OPTIONS method"
1233
+ self._query_params = {}
1234
+ self._cmd = None
1224
1235
  try:
1225
1236
  self._validate_request_framing()
1237
+ cmd = self._pathify()[1:]
1238
+ methods = self._header_values('Access-Control-Request-Method')
1239
+ if not methods:
1240
+ raise self._missing_command(cmd)
1241
+ if len(methods) != 1 or methods[0] not in _METHODS:
1242
+ raise self.req_error(403)
1243
+ command = self._resolve_command(methods[0], cmd)
1244
+ origin = self._allowed_origin(command) if command is not None else None
1245
+ if not origin:
1246
+ raise self.req_error(403)
1247
+ headers = [name.strip().lower()
1248
+ for line in self._header_values('Access-Control-Request-Headers')
1249
+ for name in line.split(',')]
1250
+ if not _CORS_REQUEST_HEADERS.issuperset(headers):
1251
+ raise self.req_error(403)
1226
1252
  except HttpReqError as error:
1227
1253
  error.report(self)
1228
1254
  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)
1255
+ response = self.build_response(code=204)
1256
+ response.add_header('Access-Control-Allow-Origin', origin)
1257
+ response.add_header('Access-Control-Allow-Methods', methods[0])
1258
+ response.add_header('Vary', _CORS_PREFLIGHT_VARY)
1259
+ if headers:
1260
+ response.add_header('Access-Control-Allow-Headers', ', '.join(sorted(set(headers))))
1261
+ self.end_response(response)
1235
1262
 
1236
1263
  def do_PATCH(self):
1237
1264
  "POST method"
@@ -1288,7 +1315,8 @@ class HttpServerContext(object):
1288
1315
  content_type = None,
1289
1316
  to_auth = False,
1290
1317
  to_log = True,
1291
- max_body_size = None):
1318
+ max_body_size = None,
1319
+ cors_origins = ()):
1292
1320
  """
1293
1321
  Register a command
1294
1322
  @handler: function to execute when the command is received
@@ -1304,6 +1332,7 @@ class HttpServerContext(object):
1304
1332
  @content_type: content_type
1305
1333
  @to_auth: use basic authentification if True
1306
1334
  @to_log: log request if True
1335
+ @cors_origins: explicit origins allowed to read this route from a browser
1307
1336
  @max_body_size: maximum request body bytes; None inherits this context's limit
1308
1337
 
1309
1338
  prototypes:
@@ -1361,7 +1390,8 @@ class HttpServerContext(object):
1361
1390
  content_type,
1362
1391
  to_auth,
1363
1392
  to_log,
1364
- max_body_size)
1393
+ max_body_size,
1394
+ cors_origins)
1365
1395
 
1366
1396
  for method in methods:
1367
1397
  if not is_reg:
@@ -1576,10 +1606,11 @@ def register(handler,
1576
1606
  content_type = None,
1577
1607
  to_auth = False,
1578
1608
  to_log = True,
1579
- max_body_size = None):
1609
+ max_body_size = None,
1610
+ cors_origins = ()):
1580
1611
  return _DEFAULT_CONTEXT.register(handler, op, safe_init, at_start, name,
1581
1612
  at_stop, static, root, replacement, charset,
1582
- content_type, to_auth, to_log, max_body_size)
1613
+ content_type, to_auth, to_log, max_body_size, cors_origins)
1583
1614
 
1584
1615
 
1585
1616
  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.36
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
@@ -344,8 +372,7 @@ the optional local service described below supplies those separately. Browser lo
344
372
  HTTP routes and TOTP enrollment/replay protection remain pending. The contract does
345
373
  not configure cookies, HTTPS, CSRF or CORS automatically.
346
374
  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.
375
+ are implemented and tested together. Configure cross-origin API access separately on the intended routes.
349
376
 
350
377
  ## Local authentication backend (development, optional)
351
378
 
@@ -520,8 +547,7 @@ Embedding requirements: serve only fixed public login/assets routes; protect all
520
547
  business routes; bound login request bodies; prohibit CORS/preflight in browser
521
548
  mode; apply no-store, CSP, frame denial and nosniff headers to errors as well as
522
549
  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.
550
+ for checking public routes before parsing their body. Leave CORS disabled on cookie-authenticated routes.
525
551
  Application scopes, ownership and action confirmation remain application policy.
526
552
  This adapter supplies no HTML UI, proxy configuration, TOTP or SSO.
527
553
 
@@ -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.36'
8
+ version: '0.6.36'
9
9
  license: License GPL-3
10
10
  url: https://github.com/decryptus/httpdis
11
11
  python_requires:
@@ -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)
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
File without changes
File without changes