We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Port Kinto for Pyramid 1.8
Pyramid 1.8 is breaking a number of things:

- BasicAuth authn policy
- pserve http_port config.

Right now it is still an alpha release but it gets installed on time to time.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `kinto/core/__init__.py`
Content:
```
1 """Main entry point
2 """
3 import pkg_resources
4 import tempfile
5 
6 from cornice import Service as CorniceService
7 from pyramid.settings import aslist
8 
9 from kinto.core import errors
10 from kinto.core import events
11 from kinto.core.initialization import (  # NOQA
12     initialize, install_middlewares,
13     load_default_settings)
14 from kinto.core.utils import (
15     follow_subrequest, current_service, current_resource_name,
16     prefixed_userid, prefixed_principals)
17 from kinto.core.logs import logger
18 
19 
20 # Module version, as defined in PEP-0396.
21 __version__ = pkg_resources.get_distribution('kinto').version  # FIXME?
22 
23 
24 DEFAULT_SETTINGS = {
25     'backoff': None,
26     'batch_max_requests': 25,
27     'cache_backend': '',
28     'cache_url': '',
29     'cache_pool_size': 25,
30     'cache_prefix': '',
31     'cache_max_size_bytes': 524288,
32     'cors_origins': '*',
33     'cors_max_age_seconds': 3600,
34     'eos': None,
35     'eos_message': None,
36     'eos_url': None,
37     'error_info_link': 'https://github.com/Kinto/kinto/issues/',
38     'http_host': None,
39     'http_scheme': None,
40     'id_generator': 'kinto.core.storage.generators.UUID4',
41     'includes': '',
42     'initialization_sequence': (
43         'kinto.core.initialization.setup_request_bound_data',
44         'kinto.core.initialization.setup_json_serializer',
45         'kinto.core.initialization.setup_logging',
46         'kinto.core.initialization.setup_storage',
47         'kinto.core.initialization.setup_permission',
48         'kinto.core.initialization.setup_cache',
49         'kinto.core.initialization.setup_requests_scheme',
50         'kinto.core.initialization.setup_version_redirection',
51         'kinto.core.initialization.setup_deprecation',
52         'kinto.core.initialization.setup_authentication',
53         'kinto.core.initialization.setup_backoff',
54         'kinto.core.initialization.setup_statsd',
55         'kinto.core.initialization.setup_listeners',
56         'kinto.core.events.setup_transaction_hook',
57     ),
58     'event_listeners': '',
59     'heartbeat_timeout_seconds': 10,
60     'logging_renderer': 'kinto.core.logs.ClassicLogRenderer',
61     'newrelic_config': None,
62     'newrelic_env': 'dev',
63     'paginate_by': None,
64     'permission_backend': '',
65     'permission_url': '',
66     'permission_pool_size': 25,
67     'profiler_dir': tempfile.gettempdir(),
68     'profiler_enabled': False,
69     'project_docs': '',
70     'project_name': '',
71     'project_version': '',
72     'readonly': False,
73     'retry_after_seconds': 30,
74     'statsd_backend': 'kinto.core.statsd',
75     'statsd_prefix': 'kinto.core',
76     'statsd_url': None,
77     'storage_backend': '',
78     'storage_url': '',
79     'storage_max_fetch_size': 10000,
80     'storage_pool_size': 25,
81     'tm.annotate_user': False,  # Do annotate transactions with the user-id.
82     'transaction_per_request': True,
83     'userid_hmac_secret': '',
84     'version_json_path': 'version.json',
85     'version_prefix_redirect_enabled': True,
86     'trailing_slash_redirect_enabled': True,
87     'multiauth.groupfinder': 'kinto.core.authorization.groupfinder',
88     'multiauth.policies': 'basicauth',
89     'multiauth.policy.basicauth.use': ('kinto.core.authentication.'
90                                        'BasicAuthAuthenticationPolicy'),
91     'multiauth.authorization_policy': ('kinto.core.authorization.'
92                                        'AuthorizationPolicy'),
93     'swagger_file': 'swagger.yaml',
94 }
95 
96 
97 class Service(CorniceService):
98     """Subclass of the default cornice service.
99 
100     This is useful in order to attach specific behaviours without monkey
101     patching the default cornice service (which would impact other uses of it)
102     """
103     default_cors_headers = ('Backoff', 'Retry-After', 'Alert',
104                             'Content-Length')
105 
106     def error_handler(self, request):
107         return errors.json_error_handler(request)
108 
109     @classmethod
110     def init_from_settings(cls, settings):
111         cls.cors_origins = tuple(aslist(settings['cors_origins']))
112         cors_max_age = settings['cors_max_age_seconds']
113         cls.cors_max_age = int(cors_max_age) if cors_max_age else None
114 
115 
116 def includeme(config):
117     settings = config.get_settings()
118 
119     # Heartbeat registry.
120     config.registry.heartbeats = {}
121 
122     # Public settings registry.
123     config.registry.public_settings = {'batch_max_requests', 'readonly'}
124 
125     # Directive to declare arbitrary API capabilities.
126     def add_api_capability(config, identifier, description="", url="", **kw):
127         existing = config.registry.api_capabilities.get(identifier)
128         if existing:
129             error_msg = "The '{}' API capability was already registered ({})."
130             raise ValueError(error_msg.format(identifier, existing))
131 
132         capability = dict(description=description, url=url, **kw)
133         config.registry.api_capabilities[identifier] = capability
134 
135     config.add_directive('add_api_capability', add_api_capability)
136     config.registry.api_capabilities = {}
137 
138     # Resource events helpers.
139     config.add_request_method(events.get_resource_events,
140                               name='get_resource_events')
141     config.add_request_method(events.notify_resource_event,
142                               name='notify_resource_event')
143 
144     # Setup cornice.
145     config.include("cornice")
146 
147     # Per-request transaction.
148     config.include("pyramid_tm")
149 
150     # Add CORS settings to the base kinto.core Service class.
151     Service.init_from_settings(settings)
152 
153     # Setup components.
154     for step in aslist(settings['initialization_sequence']):
155         step_func = config.maybe_dotted(step)
156         step_func(config)
157 
158     # Custom helpers.
159     config.add_request_method(follow_subrequest)
160     config.add_request_method(prefixed_userid, property=True)
161     config.add_request_method(prefixed_principals, reify=True)
162     config.add_request_method(lambda r: {
163         'id': r.prefixed_userid,
164         'principals': r.prefixed_principals},
165         name='get_user_info')
166     config.add_request_method(current_resource_name, reify=True)
167     config.add_request_method(current_service, reify=True)
168     config.commit()
169 
170     # Include plugins after init, unlike pyramid includes.
171     includes = aslist(settings['includes'])
172     for app in includes:
173         config.include(app)
174 
175     # # Show settings to output.
176     # for key, value in settings.items():
177     #     logger.info('Using {} = {}'.format(key, value))
178 
179     # Scan views.
180     config.scan("kinto.core.views")
181 
182     # Give sign of life.
183     msg = "Running {project_name} {project_version}."
184     logger.info(msg.format_map(settings))
185
```

Path: `kinto/core/authentication.py`
Content:
```
1 from pyramid import authentication as base_auth
2 
3 from kinto.core import utils
4 
5 
6 class BasicAuthAuthenticationPolicy(base_auth.BasicAuthAuthenticationPolicy):
7     """Basic auth implementation.
8 
9     Allow any user with any credentials (e.g. there is no need to create an
10     account).
11 
12     """
13     def __init__(self, *args, **kwargs):
14         def noop_check(*a):
15             return []
16         super().__init__(noop_check, *args, **kwargs)
17 
18     def effective_principals(self, request):
19         # Bypass default Pyramid construction of principals because
20         # Pyramid multiauth already adds userid, Authenticated and Everyone
21         # principals.
22         return []
23 
24     def unauthenticated_userid(self, request):
25         settings = request.registry.settings
26 
27         credentials = self._get_credentials(request)
28         if credentials:
29             username, password = credentials
30             if not username:
31                 return
32 
33             hmac_secret = settings['userid_hmac_secret']
34             credentials = '{}:{}'.format(*credentials)
35             userid = utils.hmac_digest(hmac_secret, credentials)
36             return userid
37 
38 
39 def includeme(config):
40     config.add_api_capability(
41         "basicauth",
42         description="Very basic authentication sessions. Not for production use.",
43         url="http://kinto.readthedocs.io/en/stable/api/1.x/authentication.html",
44     )
45
```

Path: `setup.py`
Content:
```
1 import codecs
2 import os
3 from setuptools import setup, find_packages
4 
5 here = os.path.abspath(os.path.dirname(__file__))
6 
7 
8 def read_file(filename):
9     """Open a related file and return its content."""
10     with codecs.open(os.path.join(here, filename), encoding='utf-8') as f:
11         content = f.read()
12     return content
13 
14 
15 README = read_file('README.rst')
16 CHANGELOG = read_file('CHANGELOG.rst')
17 CONTRIBUTORS = read_file('CONTRIBUTORS.rst')
18 
19 REQUIREMENTS = [
20     'colander >= 1.3.2',
21     'colorama',
22     'cornice >= 2.4',
23     'jsonschema',
24     'jsonpatch',
25     'python-dateutil',
26     'pyramid >1.7,<1.8',
27     'pyramid_multiauth >= 0.8',  # User on policy selected event.
28     'ruamel.yaml',
29     'transaction',
30     'pyramid_tm',
31     'requests',
32     'structlog >= 16.1.0',
33     'enum34',
34     'waitress',
35     'ujson >= 1.35'
36 ]
37 
38 POSTGRESQL_REQUIRES = [
39     'SQLAlchemy',
40     'psycopg2 > 2.5',
41     'zope.sqlalchemy',
42 ]
43 
44 REDIS_REQUIRES = [
45     'kinto_redis'
46 ]
47 
48 SETUP_REQUIRES = [
49     'pytest-runner'
50 ]
51 
52 TEST_REQUIREMENTS = [
53     'bravado_core',
54     'pytest',
55     'WebTest'
56 ]
57 
58 DEPENDENCY_LINKS = [
59 ]
60 
61 MONITORING_REQUIRES = [
62     'raven',
63     'statsd',
64     'newrelic',
65     'werkzeug',
66 ]
67 
68 ENTRY_POINTS = {
69     'paste.app_factory': [
70         'main = kinto:main',
71     ],
72     'console_scripts': [
73         'kinto = kinto.__main__:main'
74     ],
75 }
76 
77 
78 setup(name='kinto',
79       version='6.0.0.dev0',
80       description='Kinto Web Service - Store, Sync, Share, and Self-Host.',
81       long_description="{}\n\n{}\n\n{}".format(README, CHANGELOG, CONTRIBUTORS),
82       license='Apache License (2.0)',
83       classifiers=[
84           "Programming Language :: Python",
85           "Programming Language :: Python :: 3",
86           "Programming Language :: Python :: 3.5",
87           "Programming Language :: Python :: 3.6",
88           "Programming Language :: Python :: Implementation :: CPython",
89           "Topic :: Internet :: WWW/HTTP",
90           "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
91           "License :: OSI Approved :: Apache Software License"
92       ],
93       keywords="web sync json storage services",
94       author='Mozilla Services',
95       author_email='storage-team@mozilla.com',
96       url='https://github.com/Kinto/kinto',
97       packages=find_packages(),
98       package_data={'': ['*.rst', '*.py', '*.yaml']},
99       include_package_data=True,
100       zip_safe=False,
101       setup_requires=SETUP_REQUIRES,
102       tests_require=TEST_REQUIREMENTS,
103       install_requires=REQUIREMENTS,
104       extras_require={
105           'redis': REDIS_REQUIRES,
106           'postgresql': POSTGRESQL_REQUIRES,
107           'monitoring': MONITORING_REQUIRES,
108       },
109       test_suite="tests",
110       dependency_links=DEPENDENCY_LINKS,
111       entry_points=ENTRY_POINTS)
112
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/kinto/core/__init__.py b/kinto/core/__init__.py
--- a/kinto/core/__init__.py
+++ b/kinto/core/__init__.py
@@ -20,7 +20,6 @@
 # Module version, as defined in PEP-0396.
 __version__ = pkg_resources.get_distribution('kinto').version  # FIXME?
 
-
 DEFAULT_SETTINGS = {
     'backoff': None,
     'batch_max_requests': 25,
diff --git a/kinto/core/authentication.py b/kinto/core/authentication.py
--- a/kinto/core/authentication.py
+++ b/kinto/core/authentication.py
@@ -24,7 +24,7 @@
     def unauthenticated_userid(self, request):
         settings = request.registry.settings
 
-        credentials = self._get_credentials(request)
+        credentials = base_auth.extract_http_basic_credentials(request)
         if credentials:
             username, password = credentials
             if not username:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -23,7 +23,7 @@
     'jsonschema',
     'jsonpatch',
     'python-dateutil',
-    'pyramid >1.7,<1.8',
+    'pyramid > 1.8',
     'pyramid_multiauth >= 0.8',  # User on policy selected event.
     'ruamel.yaml',
     'transaction',

{"golden_diff": "diff --git a/kinto/core/__init__.py b/kinto/core/__init__.py\n--- a/kinto/core/__init__.py\n+++ b/kinto/core/__init__.py\n@@ -20,7 +20,6 @@\n # Module version, as defined in PEP-0396.\n __version__ = pkg_resources.get_distribution('kinto').version  # FIXME?\n \n-\n DEFAULT_SETTINGS = {\n     'backoff': None,\n     'batch_max_requests': 25,\ndiff --git a/kinto/core/authentication.py b/kinto/core/authentication.py\n--- a/kinto/core/authentication.py\n+++ b/kinto/core/authentication.py\n@@ -24,7 +24,7 @@\n     def unauthenticated_userid(self, request):\n         settings = request.registry.settings\n \n-        credentials = self._get_credentials(request)\n+        credentials = base_auth.extract_http_basic_credentials(request)\n         if credentials:\n             username, password = credentials\n             if not username:\ndiff --git a/setup.py b/setup.py\n--- a/setup.py\n+++ b/setup.py\n@@ -23,7 +23,7 @@\n     'jsonschema',\n     'jsonpatch',\n     'python-dateutil',\n-    'pyramid >1.7,<1.8',\n+    'pyramid > 1.8',\n     'pyramid_multiauth >= 0.8',  # User on policy selected event.\n     'ruamel.yaml',\n     'transaction',\n", "issue": "Port Kinto for Pyramid 1.8\nPyramid 1.8 is breaking a number of things:\r\n\r\n- BasicAuth authn policy\r\n- pserve http_port config.\r\n\r\nRight now it is still an alpha release but it gets installed on time to time.\n", "before_files": [{"content": "\"\"\"Main entry point\n\"\"\"\nimport pkg_resources\nimport tempfile\n\nfrom cornice import Service as CorniceService\nfrom pyramid.settings import aslist\n\nfrom kinto.core import errors\nfrom kinto.core import events\nfrom kinto.core.initialization import (  # NOQA\n    initialize, install_middlewares,\n    load_default_settings)\nfrom kinto.core.utils import (\n    follow_subrequest, current_service, current_resource_name,\n    prefixed_userid, prefixed_principals)\nfrom kinto.core.logs import logger\n\n\n# Module version, as defined in PEP-0396.\n__version__ = pkg_resources.get_distribution('kinto').version  # FIXME?\n\n\nDEFAULT_SETTINGS = {\n    'backoff': None,\n    'batch_max_requests': 25,\n    'cache_backend': '',\n    'cache_url': '',\n    'cache_pool_size': 25,\n    'cache_prefix': '',\n    'cache_max_size_bytes': 524288,\n    'cors_origins': '*',\n    'cors_max_age_seconds': 3600,\n    'eos': None,\n    'eos_message': None,\n    'eos_url': None,\n    'error_info_link': 'https://github.com/Kinto/kinto/issues/',\n    'http_host': None,\n    'http_scheme': None,\n    'id_generator': 'kinto.core.storage.generators.UUID4',\n    'includes': '',\n    'initialization_sequence': (\n        'kinto.core.initialization.setup_request_bound_data',\n        'kinto.core.initialization.setup_json_serializer',\n        'kinto.core.initialization.setup_logging',\n        'kinto.core.initialization.setup_storage',\n        'kinto.core.initialization.setup_permission',\n        'kinto.core.initialization.setup_cache',\n        'kinto.core.initialization.setup_requests_scheme',\n        'kinto.core.initialization.setup_version_redirection',\n        'kinto.core.initialization.setup_deprecation',\n        'kinto.core.initialization.setup_authentication',\n        'kinto.core.initialization.setup_backoff',\n        'kinto.core.initialization.setup_statsd',\n        'kinto.core.initialization.setup_listeners',\n        'kinto.core.events.setup_transaction_hook',\n    ),\n    'event_listeners': '',\n    'heartbeat_timeout_seconds': 10,\n    'logging_renderer': 'kinto.core.logs.ClassicLogRenderer',\n    'newrelic_config': None,\n    'newrelic_env': 'dev',\n    'paginate_by': None,\n    'permission_backend': '',\n    'permission_url': '',\n    'permission_pool_size': 25,\n    'profiler_dir': tempfile.gettempdir(),\n    'profiler_enabled': False,\n    'project_docs': '',\n    'project_name': '',\n    'project_version': '',\n    'readonly': False,\n    'retry_after_seconds': 30,\n    'statsd_backend': 'kinto.core.statsd',\n    'statsd_prefix': 'kinto.core',\n    'statsd_url': None,\n    'storage_backend': '',\n    'storage_url': '',\n    'storage_max_fetch_size': 10000,\n    'storage_pool_size': 25,\n    'tm.annotate_user': False,  # Do annotate transactions with the user-id.\n    'transaction_per_request': True,\n    'userid_hmac_secret': '',\n    'version_json_path': 'version.json',\n    'version_prefix_redirect_enabled': True,\n    'trailing_slash_redirect_enabled': True,\n    'multiauth.groupfinder': 'kinto.core.authorization.groupfinder',\n    'multiauth.policies': 'basicauth',\n    'multiauth.policy.basicauth.use': ('kinto.core.authentication.'\n                                       'BasicAuthAuthenticationPolicy'),\n    'multiauth.authorization_policy': ('kinto.core.authorization.'\n                                       'AuthorizationPolicy'),\n    'swagger_file': 'swagger.yaml',\n}\n\n\nclass Service(CorniceService):\n    \"\"\"Subclass of the default cornice service.\n\n    This is useful in order to attach specific behaviours without monkey\n    patching the default cornice service (which would impact other uses of it)\n    \"\"\"\n    default_cors_headers = ('Backoff', 'Retry-After', 'Alert',\n                            'Content-Length')\n\n    def error_handler(self, request):\n        return errors.json_error_handler(request)\n\n    @classmethod\n    def init_from_settings(cls, settings):\n        cls.cors_origins = tuple(aslist(settings['cors_origins']))\n        cors_max_age = settings['cors_max_age_seconds']\n        cls.cors_max_age = int(cors_max_age) if cors_max_age else None\n\n\ndef includeme(config):\n    settings = config.get_settings()\n\n    # Heartbeat registry.\n    config.registry.heartbeats = {}\n\n    # Public settings registry.\n    config.registry.public_settings = {'batch_max_requests', 'readonly'}\n\n    # Directive to declare arbitrary API capabilities.\n    def add_api_capability(config, identifier, description=\"\", url=\"\", **kw):\n        existing = config.registry.api_capabilities.get(identifier)\n        if existing:\n            error_msg = \"The '{}' API capability was already registered ({}).\"\n            raise ValueError(error_msg.format(identifier, existing))\n\n        capability = dict(description=description, url=url, **kw)\n        config.registry.api_capabilities[identifier] = capability\n\n    config.add_directive('add_api_capability', add_api_capability)\n    config.registry.api_capabilities = {}\n\n    # Resource events helpers.\n    config.add_request_method(events.get_resource_events,\n                              name='get_resource_events')\n    config.add_request_method(events.notify_resource_event,\n                              name='notify_resource_event')\n\n    # Setup cornice.\n    config.include(\"cornice\")\n\n    # Per-request transaction.\n    config.include(\"pyramid_tm\")\n\n    # Add CORS settings to the base kinto.core Service class.\n    Service.init_from_settings(settings)\n\n    # Setup components.\n    for step in aslist(settings['initialization_sequence']):\n        step_func = config.maybe_dotted(step)\n        step_func(config)\n\n    # Custom helpers.\n    config.add_request_method(follow_subrequest)\n    config.add_request_method(prefixed_userid, property=True)\n    config.add_request_method(prefixed_principals, reify=True)\n    config.add_request_method(lambda r: {\n        'id': r.prefixed_userid,\n        'principals': r.prefixed_principals},\n        name='get_user_info')\n    config.add_request_method(current_resource_name, reify=True)\n    config.add_request_method(current_service, reify=True)\n    config.commit()\n\n    # Include plugins after init, unlike pyramid includes.\n    includes = aslist(settings['includes'])\n    for app in includes:\n        config.include(app)\n\n    # # Show settings to output.\n    # for key, value in settings.items():\n    #     logger.info('Using {} = {}'.format(key, value))\n\n    # Scan views.\n    config.scan(\"kinto.core.views\")\n\n    # Give sign of life.\n    msg = \"Running {project_name} {project_version}.\"\n    logger.info(msg.format_map(settings))\n", "path": "kinto/core/__init__.py"}, {"content": "from pyramid import authentication as base_auth\n\nfrom kinto.core import utils\n\n\nclass BasicAuthAuthenticationPolicy(base_auth.BasicAuthAuthenticationPolicy):\n    \"\"\"Basic auth implementation.\n\n    Allow any user with any credentials (e.g. there is no need to create an\n    account).\n\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        def noop_check(*a):\n            return []\n        super().__init__(noop_check, *args, **kwargs)\n\n    def effective_principals(self, request):\n        # Bypass default Pyramid construction of principals because\n        # Pyramid multiauth already adds userid, Authenticated and Everyone\n        # principals.\n        return []\n\n    def unauthenticated_userid(self, request):\n        settings = request.registry.settings\n\n        credentials = self._get_credentials(request)\n        if credentials:\n            username, password = credentials\n            if not username:\n                return\n\n            hmac_secret = settings['userid_hmac_secret']\n            credentials = '{}:{}'.format(*credentials)\n            userid = utils.hmac_digest(hmac_secret, credentials)\n            return userid\n\n\ndef includeme(config):\n    config.add_api_capability(\n        \"basicauth\",\n        description=\"Very basic authentication sessions. Not for production use.\",\n        url=\"http://kinto.readthedocs.io/en/stable/api/1.x/authentication.html\",\n    )\n", "path": "kinto/core/authentication.py"}, {"content": "import codecs\nimport os\nfrom setuptools import setup, find_packages\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n\ndef read_file(filename):\n    \"\"\"Open a related file and return its content.\"\"\"\n    with codecs.open(os.path.join(here, filename), encoding='utf-8') as f:\n        content = f.read()\n    return content\n\n\nREADME = read_file('README.rst')\nCHANGELOG = read_file('CHANGELOG.rst')\nCONTRIBUTORS = read_file('CONTRIBUTORS.rst')\n\nREQUIREMENTS = [\n    'colander >= 1.3.2',\n    'colorama',\n    'cornice >= 2.4',\n    'jsonschema',\n    'jsonpatch',\n    'python-dateutil',\n    'pyramid >1.7,<1.8',\n    'pyramid_multiauth >= 0.8',  # User on policy selected event.\n    'ruamel.yaml',\n    'transaction',\n    'pyramid_tm',\n    'requests',\n    'structlog >= 16.1.0',\n    'enum34',\n    'waitress',\n    'ujson >= 1.35'\n]\n\nPOSTGRESQL_REQUIRES = [\n    'SQLAlchemy',\n    'psycopg2 > 2.5',\n    'zope.sqlalchemy',\n]\n\nREDIS_REQUIRES = [\n    'kinto_redis'\n]\n\nSETUP_REQUIRES = [\n    'pytest-runner'\n]\n\nTEST_REQUIREMENTS = [\n    'bravado_core',\n    'pytest',\n    'WebTest'\n]\n\nDEPENDENCY_LINKS = [\n]\n\nMONITORING_REQUIRES = [\n    'raven',\n    'statsd',\n    'newrelic',\n    'werkzeug',\n]\n\nENTRY_POINTS = {\n    'paste.app_factory': [\n        'main = kinto:main',\n    ],\n    'console_scripts': [\n        'kinto = kinto.__main__:main'\n    ],\n}\n\n\nsetup(name='kinto',\n      version='6.0.0.dev0',\n      description='Kinto Web Service - Store, Sync, Share, and Self-Host.',\n      long_description=\"{}\\n\\n{}\\n\\n{}\".format(README, CHANGELOG, CONTRIBUTORS),\n      license='Apache License (2.0)',\n      classifiers=[\n          \"Programming Language :: Python\",\n          \"Programming Language :: Python :: 3\",\n          \"Programming Language :: Python :: 3.5\",\n          \"Programming Language :: Python :: 3.6\",\n          \"Programming Language :: Python :: Implementation :: CPython\",\n          \"Topic :: Internet :: WWW/HTTP\",\n          \"Topic :: Internet :: WWW/HTTP :: WSGI :: Application\",\n          \"License :: OSI Approved :: Apache Software License\"\n      ],\n      keywords=\"web sync json storage services\",\n      author='Mozilla Services',\n      author_email='storage-team@mozilla.com',\n      url='https://github.com/Kinto/kinto',\n      packages=find_packages(),\n      package_data={'': ['*.rst', '*.py', '*.yaml']},\n      include_package_data=True,\n      zip_safe=False,\n      setup_requires=SETUP_REQUIRES,\n      tests_require=TEST_REQUIREMENTS,\n      install_requires=REQUIREMENTS,\n      extras_require={\n          'redis': REDIS_REQUIRES,\n          'postgresql': POSTGRESQL_REQUIRES,\n          'monitoring': MONITORING_REQUIRES,\n      },\n      test_suite=\"tests\",\n      dependency_links=DEPENDENCY_LINKS,\n      entry_points=ENTRY_POINTS)\n", "path": "setup.py"}], "after_files": [{"content": "\"\"\"Main entry point\n\"\"\"\nimport pkg_resources\nimport tempfile\n\nfrom cornice import Service as CorniceService\nfrom pyramid.settings import aslist\n\nfrom kinto.core import errors\nfrom kinto.core import events\nfrom kinto.core.initialization import (  # NOQA\n    initialize, install_middlewares,\n    load_default_settings)\nfrom kinto.core.utils import (\n    follow_subrequest, current_service, current_resource_name,\n    prefixed_userid, prefixed_principals)\nfrom kinto.core.logs import logger\n\n\n# Module version, as defined in PEP-0396.\n__version__ = pkg_resources.get_distribution('kinto').version  # FIXME?\n\nDEFAULT_SETTINGS = {\n    'backoff': None,\n    'batch_max_requests': 25,\n    'cache_backend': '',\n    'cache_url': '',\n    'cache_pool_size': 25,\n    'cache_prefix': '',\n    'cache_max_size_bytes': 524288,\n    'cors_origins': '*',\n    'cors_max_age_seconds': 3600,\n    'eos': None,\n    'eos_message': None,\n    'eos_url': None,\n    'error_info_link': 'https://github.com/Kinto/kinto/issues/',\n    'http_host': None,\n    'http_scheme': None,\n    'id_generator': 'kinto.core.storage.generators.UUID4',\n    'includes': '',\n    'initialization_sequence': (\n        'kinto.core.initialization.setup_request_bound_data',\n        'kinto.core.initialization.setup_json_serializer',\n        'kinto.core.initialization.setup_logging',\n        'kinto.core.initialization.setup_storage',\n        'kinto.core.initialization.setup_permission',\n        'kinto.core.initialization.setup_cache',\n        'kinto.core.initialization.setup_requests_scheme',\n        'kinto.core.initialization.setup_version_redirection',\n        'kinto.core.initialization.setup_deprecation',\n        'kinto.core.initialization.setup_authentication',\n        'kinto.core.initialization.setup_backoff',\n        'kinto.core.initialization.setup_statsd',\n        'kinto.core.initialization.setup_listeners',\n        'kinto.core.events.setup_transaction_hook',\n    ),\n    'event_listeners': '',\n    'heartbeat_timeout_seconds': 10,\n    'logging_renderer': 'kinto.core.logs.ClassicLogRenderer',\n    'newrelic_config': None,\n    'newrelic_env': 'dev',\n    'paginate_by': None,\n    'permission_backend': '',\n    'permission_url': '',\n    'permission_pool_size': 25,\n    'profiler_dir': tempfile.gettempdir(),\n    'profiler_enabled': False,\n    'project_docs': '',\n    'project_name': '',\n    'project_version': '',\n    'readonly': False,\n    'retry_after_seconds': 30,\n    'statsd_backend': 'kinto.core.statsd',\n    'statsd_prefix': 'kinto.core',\n    'statsd_url': None,\n    'storage_backend': '',\n    'storage_url': '',\n    'storage_max_fetch_size': 10000,\n    'storage_pool_size': 25,\n    'tm.annotate_user': False,  # Do annotate transactions with the user-id.\n    'transaction_per_request': True,\n    'userid_hmac_secret': '',\n    'version_json_path': 'version.json',\n    'version_prefix_redirect_enabled': True,\n    'trailing_slash_redirect_enabled': True,\n    'multiauth.groupfinder': 'kinto.core.authorization.groupfinder',\n    'multiauth.policies': 'basicauth',\n    'multiauth.policy.basicauth.use': ('kinto.core.authentication.'\n                                       'BasicAuthAuthenticationPolicy'),\n    'multiauth.authorization_policy': ('kinto.core.authorization.'\n                                       'AuthorizationPolicy'),\n    'swagger_file': 'swagger.yaml',\n}\n\n\nclass Service(CorniceService):\n    \"\"\"Subclass of the default cornice service.\n\n    This is useful in order to attach specific behaviours without monkey\n    patching the default cornice service (which would impact other uses of it)\n    \"\"\"\n    default_cors_headers = ('Backoff', 'Retry-After', 'Alert',\n                            'Content-Length')\n\n    def error_handler(self, request):\n        return errors.json_error_handler(request)\n\n    @classmethod\n    def init_from_settings(cls, settings):\n        cls.cors_origins = tuple(aslist(settings['cors_origins']))\n        cors_max_age = settings['cors_max_age_seconds']\n        cls.cors_max_age = int(cors_max_age) if cors_max_age else None\n\n\ndef includeme(config):\n    settings = config.get_settings()\n\n    # Heartbeat registry.\n    config.registry.heartbeats = {}\n\n    # Public settings registry.\n    config.registry.public_settings = {'batch_max_requests', 'readonly'}\n\n    # Directive to declare arbitrary API capabilities.\n    def add_api_capability(config, identifier, description=\"\", url=\"\", **kw):\n        existing = config.registry.api_capabilities.get(identifier)\n        if existing:\n            error_msg = \"The '{}' API capability was already registered ({}).\"\n            raise ValueError(error_msg.format(identifier, existing))\n\n        capability = dict(description=description, url=url, **kw)\n        config.registry.api_capabilities[identifier] = capability\n\n    config.add_directive('add_api_capability', add_api_capability)\n    config.registry.api_capabilities = {}\n\n    # Resource events helpers.\n    config.add_request_method(events.get_resource_events,\n                              name='get_resource_events')\n    config.add_request_method(events.notify_resource_event,\n                              name='notify_resource_event')\n\n    # Setup cornice.\n    config.include(\"cornice\")\n\n    # Per-request transaction.\n    config.include(\"pyramid_tm\")\n\n    # Add CORS settings to the base kinto.core Service class.\n    Service.init_from_settings(settings)\n\n    # Setup components.\n    for step in aslist(settings['initialization_sequence']):\n        step_func = config.maybe_dotted(step)\n        step_func(config)\n\n    # Custom helpers.\n    config.add_request_method(follow_subrequest)\n    config.add_request_method(prefixed_userid, property=True)\n    config.add_request_method(prefixed_principals, reify=True)\n    config.add_request_method(lambda r: {\n        'id': r.prefixed_userid,\n        'principals': r.prefixed_principals},\n        name='get_user_info')\n    config.add_request_method(current_resource_name, reify=True)\n    config.add_request_method(current_service, reify=True)\n    config.commit()\n\n    # Include plugins after init, unlike pyramid includes.\n    includes = aslist(settings['includes'])\n    for app in includes:\n        config.include(app)\n\n    # # Show settings to output.\n    # for key, value in settings.items():\n    #     logger.info('Using {} = {}'.format(key, value))\n\n    # Scan views.\n    config.scan(\"kinto.core.views\")\n\n    # Give sign of life.\n    msg = \"Running {project_name} {project_version}.\"\n    logger.info(msg.format_map(settings))\n", "path": "kinto/core/__init__.py"}, {"content": "from pyramid import authentication as base_auth\n\nfrom kinto.core import utils\n\n\nclass BasicAuthAuthenticationPolicy(base_auth.BasicAuthAuthenticationPolicy):\n    \"\"\"Basic auth implementation.\n\n    Allow any user with any credentials (e.g. there is no need to create an\n    account).\n\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        def noop_check(*a):\n            return []\n        super().__init__(noop_check, *args, **kwargs)\n\n    def effective_principals(self, request):\n        # Bypass default Pyramid construction of principals because\n        # Pyramid multiauth already adds userid, Authenticated and Everyone\n        # principals.\n        return []\n\n    def unauthenticated_userid(self, request):\n        settings = request.registry.settings\n\n        credentials = base_auth.extract_http_basic_credentials(request)\n        if credentials:\n            username, password = credentials\n            if not username:\n                return\n\n            hmac_secret = settings['userid_hmac_secret']\n            credentials = '{}:{}'.format(*credentials)\n            userid = utils.hmac_digest(hmac_secret, credentials)\n            return userid\n\n\ndef includeme(config):\n    config.add_api_capability(\n        \"basicauth\",\n        description=\"Very basic authentication sessions. Not for production use.\",\n        url=\"http://kinto.readthedocs.io/en/stable/api/1.x/authentication.html\",\n    )\n", "path": "kinto/core/authentication.py"}, {"content": "import codecs\nimport os\nfrom setuptools import setup, find_packages\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n\ndef read_file(filename):\n    \"\"\"Open a related file and return its content.\"\"\"\n    with codecs.open(os.path.join(here, filename), encoding='utf-8') as f:\n        content = f.read()\n    return content\n\n\nREADME = read_file('README.rst')\nCHANGELOG = read_file('CHANGELOG.rst')\nCONTRIBUTORS = read_file('CONTRIBUTORS.rst')\n\nREQUIREMENTS = [\n    'colander >= 1.3.2',\n    'colorama',\n    'cornice >= 2.4',\n    'jsonschema',\n    'jsonpatch',\n    'python-dateutil',\n    'pyramid > 1.8',\n    'pyramid_multiauth >= 0.8',  # User on policy selected event.\n    'ruamel.yaml',\n    'transaction',\n    'pyramid_tm',\n    'requests',\n    'structlog >= 16.1.0',\n    'enum34',\n    'waitress',\n    'ujson >= 1.35'\n]\n\nPOSTGRESQL_REQUIRES = [\n    'SQLAlchemy',\n    'psycopg2 > 2.5',\n    'zope.sqlalchemy',\n]\n\nREDIS_REQUIRES = [\n    'kinto_redis'\n]\n\nSETUP_REQUIRES = [\n    'pytest-runner'\n]\n\nTEST_REQUIREMENTS = [\n    'bravado_core',\n    'pytest',\n    'WebTest'\n]\n\nDEPENDENCY_LINKS = [\n]\n\nMONITORING_REQUIRES = [\n    'raven',\n    'statsd',\n    'newrelic',\n    'werkzeug',\n]\n\nENTRY_POINTS = {\n    'paste.app_factory': [\n        'main = kinto:main',\n    ],\n    'console_scripts': [\n        'kinto = kinto.__main__:main'\n    ],\n}\n\n\nsetup(name='kinto',\n      version='6.0.0.dev0',\n      description='Kinto Web Service - Store, Sync, Share, and Self-Host.',\n      long_description=\"{}\\n\\n{}\\n\\n{}\".format(README, CHANGELOG, CONTRIBUTORS),\n      license='Apache License (2.0)',\n      classifiers=[\n          \"Programming Language :: Python\",\n          \"Programming Language :: Python :: 3\",\n          \"Programming Language :: Python :: 3.5\",\n          \"Programming Language :: Python :: 3.6\",\n          \"Programming Language :: Python :: Implementation :: CPython\",\n          \"Topic :: Internet :: WWW/HTTP\",\n          \"Topic :: Internet :: WWW/HTTP :: WSGI :: Application\",\n          \"License :: OSI Approved :: Apache Software License\"\n      ],\n      keywords=\"web sync json storage services\",\n      author='Mozilla Services',\n      author_email='storage-team@mozilla.com',\n      url='https://github.com/Kinto/kinto',\n      packages=find_packages(),\n      package_data={'': ['*.rst', '*.py', '*.yaml']},\n      include_package_data=True,\n      zip_safe=False,\n      setup_requires=SETUP_REQUIRES,\n      tests_require=TEST_REQUIREMENTS,\n      install_requires=REQUIREMENTS,\n      extras_require={\n          'redis': REDIS_REQUIRES,\n          'postgresql': POSTGRESQL_REQUIRES,\n          'monitoring': MONITORING_REQUIRES,\n      },\n      test_suite=\"tests\",\n      dependency_links=DEPENDENCY_LINKS,\n      entry_points=ENTRY_POINTS)\n", "path": "setup.py"}]}