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

mozilla-releng / balrog / #4816

24 Jul 2025 12:14PM UTC coverage: 89.369%. First build
#4816

Pull #3426

circleci

jcristau
public: port statsd request handler to a middleware
Pull Request #3426: update to connexion 3.x

3063 of 3579 branches covered (85.58%)

Branch coverage included in aggregate %.

69 of 74 new or added lines in 3 files covered. (93.24%)

5671 of 6194 relevant lines covered (91.56%)

0.92 hits per line

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

90.86
/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 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
class StatsdMiddleware:
1✔
40
    def __init__(self, app):
1✔
41
        self.app = app
1✔
42

43
    def metric_name(self, scope):
1✔
44
        if scope["method"] == "OPTIONS":
1!
NEW
45
            return
×
46
        op = scope.get("extensions", {}).get("connexion_routing", {}).get("operation_id")
1✔
47
        if op is None:
1✔
48
            return
1✔
49
        # do some massaging to get the metric name right
50
        # * remove various module prefixes
51
        # * add a common prefix to ensure that we can mark these metrics as gauges for
52
        #   statsd
53
        metric = op.replace(".", "_").removeprefix("auslib_web_admin_views_").removeprefix("auslib_web_admin_").removeprefix("auslib_web_common_")
1✔
54
        return f"endpoint_{metric}"
1✔
55

56
    async def __call__(self, scope, receive, send):
1✔
57
        if scope["type"] != "http":
1!
NEW
58
            await self.app(scope, receive, send)
×
NEW
59
            return
×
60

61
        metric = self.metric_name(scope)
1✔
62
        if not metric:
1✔
63
            await self.app(scope, receive, send)
1✔
64
            return
1✔
65

66
        timer = statsd.timer(metric)
1✔
67
        timer.start()
1✔
68
        try:
1✔
69
            await self.app(scope, receive, send)
1✔
70
        finally:
71
            timer.stop()
1✔
72

73

74
def create_app(allow_origins=None):
1✔
75
    connexion_app = connexion.App(__name__, swagger_ui_options=swagger_ui_options, middlewares=middlewares[:])
1✔
76
    connexion_app.app.debug = False
1✔
77
    connexion_app.add_api(spec, strict_validation=True)
1✔
78
    connexion_app.add_api(path.join(current_dir, "swagger", "api_v2.yml"), base_path="/v2", strict_validation=True, validate_responses=True)
1✔
79
    connexion_app.add_middleware(StatsdMiddleware, MiddlewarePosition.BEFORE_VALIDATION)
1✔
80
    flask_app = connexion_app.app
1✔
81

82
    create_dockerflow_endpoints(flask_app)
1✔
83

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

89
            request.transaction = dbo.begin()
1✔
90

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

108
                request.username = username
1✔
109

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

121
        return response
1✔
122

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

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

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

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

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

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

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

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

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

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

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

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

201
    if allow_origins:
1!
202
        connexion_app.add_middleware(
1✔
203
            CORSMiddleware,
204
            MiddlewarePosition.BEFORE_ROUTING,
205
            allow_origins=allow_origins,
206
            allow_headers=["Authorization", "Content-Type"],
207
            allow_methods=["OPTIONS", "GET", "POST", "PUT", "DELETE"],
208
        )
209

210
    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