• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mozilla-releng / balrog / #4793

23 Jul 2025 11:36AM UTC coverage: 85.843%. First build
#4793

Pull #3426

circleci

jcristau
admin: move CORS handling to starlette CORSMiddleware

CORS checks need to happen before routing, otherwise preflight requests
get a 405.
Pull Request #3426: update to connexion 3.x

2951 of 3583 branches covered (82.36%)

Branch coverage included in aggregate %.

57 of 65 new or added lines in 3 files covered. (87.69%)

5429 of 6179 relevant lines covered (87.86%)

0.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.5
/src/auslib/web/admin/base.py
1
import logging
1✔
2
import re
1✔
3
from os import path
1✔
4

5
import connexion
1✔
6
from connexion.middleware import MiddlewarePosition
1✔
7
from connexion.options import SwaggerUIOptions
1✔
8
from flask import g, request
1✔
9
from sentry_sdk import capture_exception
1✔
10
from specsynthase.specbuilder import SpecBuilder
1✔
11
from starlette.middleware.cors import CORSMiddleware
1✔
12
from statsd.defaults.env import statsd
1✔
13

14
import auslib
1✔
15
import auslib.web.admin.views.validators  # noqa
1✔
16
from auslib.db import ChangeScheduledError, OutdatedDataError, UpdateMergeError
1✔
17
from auslib.dockerflow import create_dockerflow_endpoints
1✔
18
from auslib.errors import BlobValidationError, PermissionDeniedError, ReadOnlyError, SignoffRequiredError
1✔
19
from auslib.util.auth import AuthError, verified_userinfo
1✔
20
from auslib.web.admin.views.problem import problem
1✔
21
from auslib.web.common import middlewares
1✔
22

23
log = logging.getLogger(__name__)
1✔
24

25
current_dir = path.dirname(__file__)
1✔
26
web_dir = path.dirname(auslib.web.__file__)
1✔
27

28
spec = (
1✔
29
    SpecBuilder()
30
    .add_spec(path.join(current_dir, "swagger/api.yml"))
31
    .add_spec(path.join(web_dir, "common/swagger/definitions.yml"))
32
    .add_spec(path.join(web_dir, "common/swagger/parameters.yml"))
33
    .add_spec(path.join(web_dir, "common/swagger/responses.yml"))
34
)
35

36
swagger_ui_options = SwaggerUIOptions(swagger_ui=False)
1✔
37

38

39
def should_time_request():
1✔
40
    # don't time OPTIONS requests
41
    if request.method == "OPTIONS":
1!
NEW
42
        return False
×
43
    # don't time requests that don't match a valid route
44
    if request.url_rule is None:
1✔
45
        return False
1✔
46
    # don't time dockerflow endpoints
47
    if request.path.startswith("/__"):
1✔
48
        return False
1✔
49

50
    return True
1✔
51

52

53
def create_app(allow_origins=None):
1✔
54
    connexion_app = connexion.App(__name__, swagger_ui_options=swagger_ui_options)
1✔
55
    connexion_app = connexion.App(__name__, swagger_ui_options=swagger_ui_options, middlewares=middlewares)
1✔
56
    connexion_app.app.debug = False
1✔
57
    connexion_app.add_api(spec, strict_validation=True)
1✔
58
    connexion_app.add_api(path.join(current_dir, "swagger", "api_v2.yml"), base_path="/v2", strict_validation=True, validate_responses=True)
1✔
59
    flask_app = connexion_app.app
1✔
60

61
    create_dockerflow_endpoints(flask_app)
1✔
62

63
    @flask_app.before_request
1✔
64
    def setup_timer():
1✔
65
        g.request_timer = None
1✔
66
        if should_time_request():
1✔
67
            # do some massaging to get the metric name right
68
            # * get rid of the `/v2` prefix on v2 endpoints added by `base_path` further up
69
            # * remove various module prefixes
70
            # * add a common prefix to ensure that we can mark these metrics as gauges for
71
            #   statsd
72
            metric = (
1✔
73
                request.url_rule.endpoint.removeprefix("/v2.")
74
                .removeprefix("auslib_web_admin_views_")
75
                .removeprefix("auslib_web_admin_")
76
                .removeprefix("auslib_web_common_")
77
            )
78
            metric = f"endpoint_{metric}"
1✔
79
            g.request_timer = statsd.timer(metric)
1✔
80
            g.request_timer.start()
1✔
81

82
    @flask_app.before_request
1✔
83
    def setup_request():
1✔
84
        if request.full_path.startswith("/v2"):
1✔
85
            from auslib.global_state import dbo
1✔
86

87
            request.transaction = dbo.begin()
1✔
88

89
            if request.method in ("POST", "PUT", "DELETE"):
1✔
90
                username = verified_userinfo(request, flask_app.config["AUTH_DOMAIN"], flask_app.config["AUTH_AUDIENCE"])["email"]
1✔
91
                if not username:
1!
92
                    log.warning("Login Required")
×
93
                    return problem(401, "Unauthenticated", "Login Required")
×
94
                # Machine to machine accounts are identified by uninformative clientIds
95
                # In order to keep Balrog permissions more readable, we map them to
96
                # more useful usernames, which are stored in the app config.
97
                if "@" not in username:
1!
98
                    username = flask_app.config["M2M_ACCOUNT_MAPPING"].get(username, username)
1✔
99
                # Even if the user has provided a valid access token, we don't want to assume
100
                # that person should be able to access Balrog (in case auth0 is not configured
101
                # to be restrictive enough.
102
                elif not dbo.isKnownUser(username):
×
103
                    log.warning("Authorization Required")
×
104
                    return problem(403, "Forbidden", "Authorization Required")
×
105

106
                request.username = username
1✔
107

108
    @flask_app.after_request
1✔
109
    def complete_request(response):
1✔
110
        if hasattr(request, "transaction"):
1✔
111
            try:
1✔
112
                if response.status_code >= 400:
1✔
113
                    request.transaction.rollback()
1✔
114
                else:
115
                    request.transaction.commit()
1✔
116
            finally:
117
                request.transaction.close()
1✔
118

119
        return response
1✔
120

121
    @flask_app.errorhandler(OutdatedDataError)
1✔
122
    def outdated_data_error(error):
1✔
123
        msg = "Couldn't perform the request %s. Outdated Data Version. old_data_version doesn't match current data_version" % request.method
1✔
124
        log.warning("Bad input: %s", msg)
1✔
125
        log.warning(error)
1✔
126
        return problem(400, "Bad Request", "OutdatedDataError", ext={"exception": msg})
1✔
127

128
    @flask_app.errorhandler(UpdateMergeError)
1✔
129
    def update_merge_error(error):
1✔
130
        msg = "Couldn't perform the request %s due to merge error. Is there a scheduled change that conflicts with yours?" % request.method
1✔
131
        log.warning("Bad input: %s", msg)
1✔
132
        log.warning(error)
1✔
133
        return problem(400, "Bad Request", "UpdateMergeError", ext={"exception": msg})
1✔
134

135
    @flask_app.errorhandler(ChangeScheduledError)
1✔
136
    def change_scheduled_error(error):
1✔
137
        msg = "Couldn't perform the request %s due a conflict with a scheduled change. " % request.method
1✔
138
        msg += str(error)
1✔
139
        log.warning("Bad input: %s", msg)
1✔
140
        log.warning(error)
1✔
141
        return problem(400, "Bad Request", "ChangeScheduledError", ext={"exception": msg})
1✔
142

143
    @flask_app.errorhandler(AuthError)
1✔
144
    def auth_error(error):
1✔
145
        msg = "Permission denied to perform the request. {}".format(error.error)
1✔
146
        log.warning(msg)
1✔
147
        return problem(error.status_code, "Forbidden", "PermissionDeniedError", ext={"exception": msg})
1✔
148

149
    @flask_app.errorhandler(BlobValidationError)
1✔
150
    def blob_validation_error(error):
1✔
151
        return problem(400, "Bad Request", "Invalid Blob", ext={"exception": error.errors})
1✔
152

153
    @flask_app.errorhandler(SignoffRequiredError)
1✔
154
    def signoff_required_error(error):
1✔
155
        return problem(400, "Bad Request", "Signoff Required", ext={"exception": f"{error}"})
1✔
156

157
    @flask_app.errorhandler(ReadOnlyError)
1✔
158
    def read_only_error(error):
1✔
159
        return problem(400, "Bad Request", "Read only", ext={"exception": f"{error}"})
1✔
160

161
    @flask_app.errorhandler(PermissionDeniedError)
1✔
162
    def permission_denied_error(error):
1✔
163
        return problem(403, "Forbidden", "Permission Denied", ext={"exception": f"{error}"})
1✔
164

165
    @flask_app.errorhandler(ValueError)
1✔
166
    def value_error(error):
1✔
167
        return problem(400, "Bad Request", "Unknown error", ext={"exception": f"{error}"})
1✔
168

169
    # Connexion's error handling sometimes breaks when parameters contain
170
    # unicode characters (https://github.com/zalando/connexion/issues/604).
171
    # To work around, we catch them and return a 400 (which is what Connexion
172
    # would do if it didn't hit this error).
173
    @flask_app.errorhandler(UnicodeEncodeError)
1✔
174
    def unicode(error):
1✔
175
        return problem(400, "Unicode Error", "Connexion was unable to parse some unicode data correctly.")
×
176

177
    @flask_app.errorhandler(Exception)
1✔
178
    def ise(error):
1✔
179
        capture_exception(error)
1✔
180
        log.exception("Caught ISE 500 error: %r", error)
1✔
181
        log.debug("Request path is: %s", request.path)
1✔
182
        log.debug("Request environment is: %s", request.environ)
1✔
183
        log.debug("Request headers are: %s", request.headers)
1✔
184
        return problem(500, "Internal Server Error", "Internal Server Error")
1✔
185

186
    @flask_app.after_request
1✔
187
    def add_security_headers(response):
1✔
188
        response.headers["X-Frame-Options"] = "DENY"
1✔
189
        response.headers["X-Content-Type-Options"] = "nosniff"
1✔
190
        response.headers["Strict-Transport-Security"] = flask_app.config.get("STRICT_TRANSPORT_SECURITY", "max-age=31536000;")
1✔
191
        if re.match("^/ui/", request.path):
1!
192
            # This enables swagger-ui to dynamically fetch and
193
            # load the swagger specification JSON file containing API definition and examples.
194
            response.headers["X-Frame-Options"] = "SAMEORIGIN"
×
195
        else:
196
            response.headers["Content-Security-Policy"] = flask_app.config.get("CONTENT_SECURITY_POLICY", "default-src 'none'; frame-ancestors 'none'")
1✔
197
        return response
1✔
198

199
    # this is specifically set-up last before after_request handlers are called
200
    # in reverse order of registering, and we want this one to be called first
201
    # to avoid it being skipped if another one raises an exception
202
    @flask_app.after_request
1✔
203
    def send_stats(response):
1✔
204
        if hasattr(g, "request_timer") and g.request_timer:
1✔
205
            g.request_timer.stop()
1✔
206

207
        return response
1✔
208

209
    if allow_origins:
1!
210
        connexion_app.add_middleware(
1✔
211
            CORSMiddleware,
212
            MiddlewarePosition.BEFORE_ROUTING,
213
            allow_origins=allow_origins,
214
            allow_headers=["Authorization", "Content-Type"],
215
            allow_methods=["OPTIONS", "GET", "POST", "PUT", "DELETE"],
216
        )
217

218
    return connexion_app
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc