We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Doom transaction if `request.user` is None
Fixes #12422.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `warehouse/db.py`
Content:
```
1 # Licensed under the Apache License, Version 2.0 (the "License");
2 # you may not use this file except in compliance with the License.
3 # You may obtain a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS,
9 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 # See the License for the specific language governing permissions and
11 # limitations under the License.
12 
13 import functools
14 import logging
15 
16 import alembic.config
17 import pyramid_retry
18 import sqlalchemy
19 import venusian
20 import zope.sqlalchemy
21 
22 from sqlalchemy import event, inspect
23 from sqlalchemy.dialects.postgresql import UUID
24 from sqlalchemy.exc import IntegrityError, OperationalError
25 from sqlalchemy.ext.declarative import declarative_base  # type: ignore
26 from sqlalchemy.orm import sessionmaker
27 
28 from warehouse.metrics import IMetricsService
29 from warehouse.utils.attrs import make_repr
30 
31 __all__ = ["includeme", "metadata", "ModelBase"]
32 
33 
34 logger = logging.getLogger(__name__)
35 
36 
37 DEFAULT_ISOLATION = "READ COMMITTED"
38 
39 
40 # On the surface this might seem wrong, because retrying a request whose data violates
41 # the constraints of the database doesn't seem like a useful endeavor. However what
42 # happens if you have two requests that are trying to insert a row, and that row
43 # contains a unique, user provided value, you can get into a race condition where both
44 # requests check the database, see nothing with that value exists, then both attempt to
45 # insert it. One of the requests will succeed, the other will fail with an
46 # IntegrityError. Retrying the request that failed will then have it see the object
47 # created by the other request, and will have it do the appropriate action in that case.
48 #
49 # The most common way to run into this, is when submitting a form in the browser, if the
50 # user clicks twice in rapid succession, the browser will send two almost identical
51 # requests at basically the same time.
52 #
53 # One possible issue that this raises, is that it will slow down "legitimate"
54 # IntegrityError because they'll have to fail multiple times before they ultimately
55 # fail. We consider this an acceptable trade off, because deterministic IntegrityError
56 # should be caught with proper validation prior to submitting records to the database
57 # anyways.
58 pyramid_retry.mark_error_retryable(IntegrityError)
59 
60 
61 # A generic wrapper exception that we'll raise when the database isn't available, we
62 # use this so we can catch it later and turn it into a generic 5xx error.
63 class DatabaseNotAvailableError(Exception):
64     ...
65 
66 
67 class ModelBase:
68     def __repr__(self):
69         inst = inspect(self)
70         self.__repr__ = make_repr(
71             *[c_attr.key for c_attr in inst.mapper.column_attrs], _self=self
72         )
73         return self.__repr__()
74 
75 
76 # The Global metadata object.
77 metadata = sqlalchemy.MetaData()
78 
79 
80 # Base class for models using declarative syntax
81 ModelBase = declarative_base(cls=ModelBase, metadata=metadata)  # type: ignore
82 
83 
84 class Model(ModelBase):
85 
86     __abstract__ = True
87 
88     id = sqlalchemy.Column(
89         UUID(as_uuid=True),
90         primary_key=True,
91         server_default=sqlalchemy.text("gen_random_uuid()"),
92     )
93 
94 
95 # Create our session class here, this will stay stateless as we'll bind the
96 # engine to each new state we create instead of binding it to the session
97 # class.
98 Session = sessionmaker()
99 
100 
101 def listens_for(target, identifier, *args, **kwargs):
102     def deco(wrapped):
103         def callback(scanner, _name, wrapped):
104             wrapped = functools.partial(wrapped, scanner.config)
105             event.listen(target, identifier, wrapped, *args, **kwargs)
106 
107         venusian.attach(wrapped, callback, category="warehouse")
108 
109         return wrapped
110 
111     return deco
112 
113 
114 def _configure_alembic(config):
115     alembic_cfg = alembic.config.Config()
116     alembic_cfg.set_main_option("script_location", "warehouse:migrations")
117     alembic_cfg.set_main_option("url", config.registry.settings["database.url"])
118     return alembic_cfg
119 
120 
121 def _create_session(request):
122     metrics = request.find_service(IMetricsService, context=None)
123     metrics.increment("warehouse.db.session.start")
124 
125     # Create our connection, most likely pulling it from the pool of
126     # connections
127     try:
128         connection = request.registry["sqlalchemy.engine"].connect()
129     except OperationalError:
130         # When we tried to connection to PostgreSQL, our database was not available for
131         # some reason. We're going to log it here and then raise our error. Most likely
132         # this is a transient error that will go away.
133         logger.warning("Got an error connecting to PostgreSQL", exc_info=True)
134         metrics.increment("warehouse.db.session.error", tags=["error_in:connecting"])
135         raise DatabaseNotAvailableError()
136 
137     # Now, create a session from our connection
138     session = Session(bind=connection)
139 
140     # Register only this particular session with zope.sqlalchemy
141     zope.sqlalchemy.register(session, transaction_manager=request.tm)
142 
143     # Setup a callback that will ensure that everything is cleaned up at the
144     # end of our connection.
145     @request.add_finished_callback
146     def cleanup(request):
147         metrics.increment("warehouse.db.session.finished")
148         session.close()
149         connection.close()
150 
151     # Check if we're in read-only mode
152     from warehouse.admin.flags import AdminFlag, AdminFlagValue
153 
154     flag = session.query(AdminFlag).get(AdminFlagValue.READ_ONLY.value)
155     if flag and flag.enabled and not request.user.is_superuser:
156         request.tm.doom()
157 
158     # Return our session now that it's created and registered
159     return session
160 
161 
162 def includeme(config):
163     # Add a directive to get an alembic configuration.
164     config.add_directive("alembic_config", _configure_alembic)
165 
166     # Create our SQLAlchemy Engine.
167     config.registry["sqlalchemy.engine"] = sqlalchemy.create_engine(
168         config.registry.settings["database.url"],
169         isolation_level=DEFAULT_ISOLATION,
170         pool_size=35,
171         max_overflow=65,
172         pool_timeout=20,
173     )
174 
175     # Register our request.db property
176     config.add_request_method(_create_session, name="db", reify=True)
177
```
--- 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/warehouse/db.py b/warehouse/db.py
--- a/warehouse/db.py
+++ b/warehouse/db.py
@@ -152,7 +152,7 @@
     from warehouse.admin.flags import AdminFlag, AdminFlagValue
 
     flag = session.query(AdminFlag).get(AdminFlagValue.READ_ONLY.value)
-    if flag and flag.enabled and not request.user.is_superuser:
+    if flag and flag.enabled:
         request.tm.doom()
 
     # Return our session now that it's created and registered

{"golden_diff": "diff --git a/warehouse/db.py b/warehouse/db.py\n--- a/warehouse/db.py\n+++ b/warehouse/db.py\n@@ -152,7 +152,7 @@\n     from warehouse.admin.flags import AdminFlag, AdminFlagValue\n \n     flag = session.query(AdminFlag).get(AdminFlagValue.READ_ONLY.value)\n-    if flag and flag.enabled and not request.user.is_superuser:\n+    if flag and flag.enabled:\n         request.tm.doom()\n \n     # Return our session now that it's created and registered\n", "issue": "Doom transaction if `request.user` is None\nFixes #12422.\n", "before_files": [{"content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport functools\nimport logging\n\nimport alembic.config\nimport pyramid_retry\nimport sqlalchemy\nimport venusian\nimport zope.sqlalchemy\n\nfrom sqlalchemy import event, inspect\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom sqlalchemy.exc import IntegrityError, OperationalError\nfrom sqlalchemy.ext.declarative import declarative_base  # type: ignore\nfrom sqlalchemy.orm import sessionmaker\n\nfrom warehouse.metrics import IMetricsService\nfrom warehouse.utils.attrs import make_repr\n\n__all__ = [\"includeme\", \"metadata\", \"ModelBase\"]\n\n\nlogger = logging.getLogger(__name__)\n\n\nDEFAULT_ISOLATION = \"READ COMMITTED\"\n\n\n# On the surface this might seem wrong, because retrying a request whose data violates\n# the constraints of the database doesn't seem like a useful endeavor. However what\n# happens if you have two requests that are trying to insert a row, and that row\n# contains a unique, user provided value, you can get into a race condition where both\n# requests check the database, see nothing with that value exists, then both attempt to\n# insert it. One of the requests will succeed, the other will fail with an\n# IntegrityError. Retrying the request that failed will then have it see the object\n# created by the other request, and will have it do the appropriate action in that case.\n#\n# The most common way to run into this, is when submitting a form in the browser, if the\n# user clicks twice in rapid succession, the browser will send two almost identical\n# requests at basically the same time.\n#\n# One possible issue that this raises, is that it will slow down \"legitimate\"\n# IntegrityError because they'll have to fail multiple times before they ultimately\n# fail. We consider this an acceptable trade off, because deterministic IntegrityError\n# should be caught with proper validation prior to submitting records to the database\n# anyways.\npyramid_retry.mark_error_retryable(IntegrityError)\n\n\n# A generic wrapper exception that we'll raise when the database isn't available, we\n# use this so we can catch it later and turn it into a generic 5xx error.\nclass DatabaseNotAvailableError(Exception):\n    ...\n\n\nclass ModelBase:\n    def __repr__(self):\n        inst = inspect(self)\n        self.__repr__ = make_repr(\n            *[c_attr.key for c_attr in inst.mapper.column_attrs], _self=self\n        )\n        return self.__repr__()\n\n\n# The Global metadata object.\nmetadata = sqlalchemy.MetaData()\n\n\n# Base class for models using declarative syntax\nModelBase = declarative_base(cls=ModelBase, metadata=metadata)  # type: ignore\n\n\nclass Model(ModelBase):\n\n    __abstract__ = True\n\n    id = sqlalchemy.Column(\n        UUID(as_uuid=True),\n        primary_key=True,\n        server_default=sqlalchemy.text(\"gen_random_uuid()\"),\n    )\n\n\n# Create our session class here, this will stay stateless as we'll bind the\n# engine to each new state we create instead of binding it to the session\n# class.\nSession = sessionmaker()\n\n\ndef listens_for(target, identifier, *args, **kwargs):\n    def deco(wrapped):\n        def callback(scanner, _name, wrapped):\n            wrapped = functools.partial(wrapped, scanner.config)\n            event.listen(target, identifier, wrapped, *args, **kwargs)\n\n        venusian.attach(wrapped, callback, category=\"warehouse\")\n\n        return wrapped\n\n    return deco\n\n\ndef _configure_alembic(config):\n    alembic_cfg = alembic.config.Config()\n    alembic_cfg.set_main_option(\"script_location\", \"warehouse:migrations\")\n    alembic_cfg.set_main_option(\"url\", config.registry.settings[\"database.url\"])\n    return alembic_cfg\n\n\ndef _create_session(request):\n    metrics = request.find_service(IMetricsService, context=None)\n    metrics.increment(\"warehouse.db.session.start\")\n\n    # Create our connection, most likely pulling it from the pool of\n    # connections\n    try:\n        connection = request.registry[\"sqlalchemy.engine\"].connect()\n    except OperationalError:\n        # When we tried to connection to PostgreSQL, our database was not available for\n        # some reason. We're going to log it here and then raise our error. Most likely\n        # this is a transient error that will go away.\n        logger.warning(\"Got an error connecting to PostgreSQL\", exc_info=True)\n        metrics.increment(\"warehouse.db.session.error\", tags=[\"error_in:connecting\"])\n        raise DatabaseNotAvailableError()\n\n    # Now, create a session from our connection\n    session = Session(bind=connection)\n\n    # Register only this particular session with zope.sqlalchemy\n    zope.sqlalchemy.register(session, transaction_manager=request.tm)\n\n    # Setup a callback that will ensure that everything is cleaned up at the\n    # end of our connection.\n    @request.add_finished_callback\n    def cleanup(request):\n        metrics.increment(\"warehouse.db.session.finished\")\n        session.close()\n        connection.close()\n\n    # Check if we're in read-only mode\n    from warehouse.admin.flags import AdminFlag, AdminFlagValue\n\n    flag = session.query(AdminFlag).get(AdminFlagValue.READ_ONLY.value)\n    if flag and flag.enabled and not request.user.is_superuser:\n        request.tm.doom()\n\n    # Return our session now that it's created and registered\n    return session\n\n\ndef includeme(config):\n    # Add a directive to get an alembic configuration.\n    config.add_directive(\"alembic_config\", _configure_alembic)\n\n    # Create our SQLAlchemy Engine.\n    config.registry[\"sqlalchemy.engine\"] = sqlalchemy.create_engine(\n        config.registry.settings[\"database.url\"],\n        isolation_level=DEFAULT_ISOLATION,\n        pool_size=35,\n        max_overflow=65,\n        pool_timeout=20,\n    )\n\n    # Register our request.db property\n    config.add_request_method(_create_session, name=\"db\", reify=True)\n", "path": "warehouse/db.py"}], "after_files": [{"content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport functools\nimport logging\n\nimport alembic.config\nimport pyramid_retry\nimport sqlalchemy\nimport venusian\nimport zope.sqlalchemy\n\nfrom sqlalchemy import event, inspect\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom sqlalchemy.exc import IntegrityError, OperationalError\nfrom sqlalchemy.ext.declarative import declarative_base  # type: ignore\nfrom sqlalchemy.orm import sessionmaker\n\nfrom warehouse.metrics import IMetricsService\nfrom warehouse.utils.attrs import make_repr\n\n__all__ = [\"includeme\", \"metadata\", \"ModelBase\"]\n\n\nlogger = logging.getLogger(__name__)\n\n\nDEFAULT_ISOLATION = \"READ COMMITTED\"\n\n\n# On the surface this might seem wrong, because retrying a request whose data violates\n# the constraints of the database doesn't seem like a useful endeavor. However what\n# happens if you have two requests that are trying to insert a row, and that row\n# contains a unique, user provided value, you can get into a race condition where both\n# requests check the database, see nothing with that value exists, then both attempt to\n# insert it. One of the requests will succeed, the other will fail with an\n# IntegrityError. Retrying the request that failed will then have it see the object\n# created by the other request, and will have it do the appropriate action in that case.\n#\n# The most common way to run into this, is when submitting a form in the browser, if the\n# user clicks twice in rapid succession, the browser will send two almost identical\n# requests at basically the same time.\n#\n# One possible issue that this raises, is that it will slow down \"legitimate\"\n# IntegrityError because they'll have to fail multiple times before they ultimately\n# fail. We consider this an acceptable trade off, because deterministic IntegrityError\n# should be caught with proper validation prior to submitting records to the database\n# anyways.\npyramid_retry.mark_error_retryable(IntegrityError)\n\n\n# A generic wrapper exception that we'll raise when the database isn't available, we\n# use this so we can catch it later and turn it into a generic 5xx error.\nclass DatabaseNotAvailableError(Exception):\n    ...\n\n\nclass ModelBase:\n    def __repr__(self):\n        inst = inspect(self)\n        self.__repr__ = make_repr(\n            *[c_attr.key for c_attr in inst.mapper.column_attrs], _self=self\n        )\n        return self.__repr__()\n\n\n# The Global metadata object.\nmetadata = sqlalchemy.MetaData()\n\n\n# Base class for models using declarative syntax\nModelBase = declarative_base(cls=ModelBase, metadata=metadata)  # type: ignore\n\n\nclass Model(ModelBase):\n\n    __abstract__ = True\n\n    id = sqlalchemy.Column(\n        UUID(as_uuid=True),\n        primary_key=True,\n        server_default=sqlalchemy.text(\"gen_random_uuid()\"),\n    )\n\n\n# Create our session class here, this will stay stateless as we'll bind the\n# engine to each new state we create instead of binding it to the session\n# class.\nSession = sessionmaker()\n\n\ndef listens_for(target, identifier, *args, **kwargs):\n    def deco(wrapped):\n        def callback(scanner, _name, wrapped):\n            wrapped = functools.partial(wrapped, scanner.config)\n            event.listen(target, identifier, wrapped, *args, **kwargs)\n\n        venusian.attach(wrapped, callback, category=\"warehouse\")\n\n        return wrapped\n\n    return deco\n\n\ndef _configure_alembic(config):\n    alembic_cfg = alembic.config.Config()\n    alembic_cfg.set_main_option(\"script_location\", \"warehouse:migrations\")\n    alembic_cfg.set_main_option(\"url\", config.registry.settings[\"database.url\"])\n    return alembic_cfg\n\n\ndef _create_session(request):\n    metrics = request.find_service(IMetricsService, context=None)\n    metrics.increment(\"warehouse.db.session.start\")\n\n    # Create our connection, most likely pulling it from the pool of\n    # connections\n    try:\n        connection = request.registry[\"sqlalchemy.engine\"].connect()\n    except OperationalError:\n        # When we tried to connection to PostgreSQL, our database was not available for\n        # some reason. We're going to log it here and then raise our error. Most likely\n        # this is a transient error that will go away.\n        logger.warning(\"Got an error connecting to PostgreSQL\", exc_info=True)\n        metrics.increment(\"warehouse.db.session.error\", tags=[\"error_in:connecting\"])\n        raise DatabaseNotAvailableError()\n\n    # Now, create a session from our connection\n    session = Session(bind=connection)\n\n    # Register only this particular session with zope.sqlalchemy\n    zope.sqlalchemy.register(session, transaction_manager=request.tm)\n\n    # Setup a callback that will ensure that everything is cleaned up at the\n    # end of our connection.\n    @request.add_finished_callback\n    def cleanup(request):\n        metrics.increment(\"warehouse.db.session.finished\")\n        session.close()\n        connection.close()\n\n    # Check if we're in read-only mode\n    from warehouse.admin.flags import AdminFlag, AdminFlagValue\n\n    flag = session.query(AdminFlag).get(AdminFlagValue.READ_ONLY.value)\n    if flag and flag.enabled:\n        request.tm.doom()\n\n    # Return our session now that it's created and registered\n    return session\n\n\ndef includeme(config):\n    # Add a directive to get an alembic configuration.\n    config.add_directive(\"alembic_config\", _configure_alembic)\n\n    # Create our SQLAlchemy Engine.\n    config.registry[\"sqlalchemy.engine\"] = sqlalchemy.create_engine(\n        config.registry.settings[\"database.url\"],\n        isolation_level=DEFAULT_ISOLATION,\n        pool_size=35,\n        max_overflow=65,\n        pool_timeout=20,\n    )\n\n    # Register our request.db property\n    config.add_request_method(_create_session, name=\"db\", reify=True)\n", "path": "warehouse/db.py"}]}