Introducing mwoauth2
Lucas Werkmeister, .
This is a
short
(oops)
blog post introducing mwoauth2,
a new Python library I wrote to facilitate using OAuth 2 with MediaWiki.
The “target audience” of the library is web applications (you might be able to make it work with native applications too? idk) that want to use the “authorization code” flow (as opposed to “client credentials” or “owner-only”) to make API requests to a MediaWiki wiki on behalf of different users, after those users have logged into the application via OAuth. It has some special affordances for using it in conjunction with the mwapi API client library and/or the Flask web framework, but it should also be usable with other libraries.
For general information about mwoauth2, see the documentation, including for usage in Flask tools and non-Flask tools. The rest of this post will focus on the motivation / context, how this library differs from mwoauth, and how I migrated my own tools to it.
Why OAuth 2?
For a long time, MediaWiki tools have mostly used OAuth 1.0a.
Support for OAuth 2 was initially added to the MediaWiki OAuth extension around 2019
(T229500),
with various fixes and improvements since then.
I first started working with OAuth 2 in 2022,
when I wrote the m3api-oauth2 (JavaScript) library,
and was surprised to discover how much easier OAuth 2 is to work with.
OAuth 1.0a was designed prior to ubiquitous HTTPS deployment,
so there is a whole scheme to sign requests
(which are potentially sent over plaintext HTTP!),
protect against replay attacks, etc.
By contrast, a basic OAuth 2 request just adds a single request header, Authorization: Bearer token –
everything else is taken care of by the fact that,
ever since the Snowden disclosures,
Wikimedia sites have required HTTPS.
Even so, I never bothered to migrate my Python tools to OAuth 2,
and as far as I’m aware many other developers also continued to use OAuth 1.0a:
why change something that works?
The more recent motivation to migrate to OAuth 2 comes from operational considerations at Wikimedia, ultimately due to crawlers by “AI” companies scraping our infrastructure to death. As mentioned in the announcement for new global API rate limits, requests authenticated with OAuth 2 get higher rate limits, whereas OAuth 1.0a requests do not. The reason for this, as I understand it, is that OAuth 2 access tokens are standardized and can be checked “at the edge”, whereas OAuth 1.0a access tokens can only be validated by MediaWiki itself, which is comparatively slow to start (and has to talk to the database). When an OAuth 2 request comes in, one of the caching servers early in the request flow (don’t ask me which one) can quickly check if the access token is still valid and has not expired yet, and allow the request based on that information; also, because OAuth 2 access tokens are only valid for a limited period of time (as discussed in more detail below), if an attacker steals an OAuth 2 access token, they can’t use it to get an elevated request rate forever. With OAuth 1.0a access tokens, none of this is possible, so at the edge (where the basic request rate limiting happens) they have to be treated as equivalent to unauthenticated requests.
How mwoauth2 works
While the name of mwoauth2 (for OAuth 2) is of course modeled after mwoauth (for OAuth 1.0a),
it’s important to note that the API isn’t actually very similar,
due to major differences in the underlying protocol.
With OAuth 1.0a (mwoauth), you get an access token once (from mwoauth.complete()),
and then you can use that access token forever;
as the application developer, you’re responsible for storing the access token somewhere (probably in some kind of session store),
the mwoauth library isn’t involved with that at all.
With OAuth 2 (mwoauth2), on the other hand, the access token is only valid for a limited amount of time (four hours in Wikimedia production) and must then be refreshed. This means that any time you use the access token (to make an API request), mwoauth2 must be able to potentially refresh the access token and then store the new token persistently. This can be done transparently to the application (i.e., as the developer, you don’t have to handle “expired token” yourself: it just happens “under the hood”, building on the requests-oauthlib and oauthlib libraries), but it means that mwoauth2 itself needs to interact with wherever the access token is stored (whether that’s a session store or some other place). As a user of mwoauth2, you actually don’t deal with the access token itself very much, if at all – rather, you tell mwoauth2 where the access token will live, and mwoauth2 will put it there on login or refresh and get it from there when you want to make an API request.
Because I use Flask for all of my tools, the library has built-in (but optional) support for Flask:
if you use the Flask-specific subclass, then the access token (and the “state”, which is used during login)
is stored in the Flask session by default.
Otherwise, you have to specify where these two pieces of information are stored,
using two sets of three functions:
get_oauth_state, set_oauth_state and pop_oauth_state for the “OAuth state” (during login)
and get_access_token, set_access_token and pop_access_token for the access token (the rest of the time).
All of these functions can take extra parameters if necessary,
depending on how your web framework’s session store is usually accessed,
which are passed through from the mwoauth2 methods:
that is, if you call oauth.oauth2_session(request.session)
(where oauth is the mwoauth2 instance) with the Django request session,
then mwoauth2 will pass that argument through and end up calling get_access_token(request.session) in the same way.
(Multiple args and kwargs are supported, but at that point I suggest using a type checker to make sure you’re passing through all the arguments correctly
and all six accessor functions consistently use the same parameter types.)
If there is enough interest, I might add support for other web frameworks besides Flask directly to the library
(i.e., add more subclasses with pre-defined accessor functions for a specific session store interface) – let me know!
mwoauth2 also comes with built-in (optional) support for mwapi.
The basic method to make OAuth-authenticated requests is oauth.oauth2_session(),
which returns an OAuth2Session,
a requests.session subclass with the usual Requests methods:
for example, you may call
oauth.oauth2_session()
.get('https://en.wikipedia.org/w/api.php', params={
'action': 'query',
'meta': 'userinfo',
'format': 'json',
})
.json()
to get the user information.
However, if you use mwapi, there’s an additional oauth.mwapi_session() method you can use instead:
oauth.mwapi_session()
.get(action='query',
meta='userinfo')
(This assumes that the oauth instance was configured to target English Wikipedia;
otherwise, you can also pass host='https://en.wikipedia.org' into mwapi_session().)
These optional features are exposed as “extras” at the package level:
if you want to use mwoauth2 with Flask and mwapi support, declare a dependency on mwoauth2[Flask,mwapi].
At the code level, they’re separate classes:
if you want to use both Flask and mwapi,
import MWOAuth2FlaskMWApi
and create an instance of that class;
if you want to use only one of the two, use
either MWOAuth2Flask
or MWOAuth2MWApi;
and if you only want the base functionality,
use MWOAuth2,
which is the base class of the other ones.
Support for other web frameworks and/or client libraries can be added in the same manner if there is interest in it.
For details on how to instantiate these classes and how to use them,
please see the documentation.
Migrating my tools to OAuth 2
The process of migrating my own Toolforge tools to mwoauth2 was relatively straightforward,
mostly following the documentation for using mwoauth2 in a Flask tool.
There is one special thing that is worth mentioning:
all of my OAuth tools were already storing the (OAuth 1.0a) access token in the Flask session using the oauth_access_token key,
which is the same key also used by mwoauth2 for the OAuth 2 access token.
This meant that, when the OAuth 2 migration was deployed,
an old session with an OAuth 1.0a access token in it might be detected as “logged in”,
and the tool might try to use that value as the OAuth 2 access token, probably leading to a crash.
To avoid this, I added an opt-in feature to mwoauth2’s Flask classes to check the access token at the beginning of the request:
if the Flask session contains an oauth_access_token value,
but it doesn’t look like a valid OAuth 2 access token,
throw it away (effectively log out the user) so the user has to log in again.
This is enabled using the check_access_token_before_request=True parameter,
and should only be used in existing tools that are being migrated to OAuth 2, not in new tools.
(Also, even those existing tools should eventually remove it, maybe after a year or so.)
Unfortunately, even though I said the migrations were mostly straightforward, I don’t have a single good representative “how to migrate a typical tool to mwoauth2” commit: in each tool, either I made a minor mistake I had to fix in a follow-up, or there’s a minor specialty that makes it unrepresentative (but isn’t worth discussing in much detail). The best I can offer is this Wikidata Image Positions commit plus this follow-up. The other tools that I migrated are:
- Wikidata Lexeme Forms
- This is the tool where I first migrated to OAuth 2, so while it may be interesting from a historical perspective, it’s very unhelpful as a guide for using mwoauth2: I first migrated to OAuth 2 directly in the tool, fixed some HTTPS issues, made improvements, and only then started to extract the code into a separate module (with improvements) before it could become a separate package installed from PyPI (with extras).
- Ranker
- I migrated to OAuth 2 and then added the missing extras half a year later, oops.
- QuickCategories
- A very special case, see below.
- Wikidata Image Positions
- See above.
- Song Quiz
-
A somewhat special case, in that this is a “user identity verification only” OAuth client,
and so it never actually makes API requests on behalf of the user:
it just gets their identity / profile once (because all it needs is the user name).
The original migration commit
did this using the
oauth.oauth2_session()interface (no mwapi here), but later I added aoauth.profile()method to mwoauth2 and used it in Song Quiz. - SpeedPatrolling
- The migration itself was straightforward, but as mentioned in the commit message, I first had to move the session from a cookie to a database (with follow-up for cleanup) – that tool had already been straining the capacity of a session cookie (it wants to store a lot of data in the session), and OAuth 2 access tokens are substantially larger than OAuth 1.0a ones, so the session didn’t fit in a cookie anymore. (Technically, the value mwoauth2 stores in the session is not just the access token itself but also the refresh token and some metadata.)
The QuickCategories tool deserves some more discussion. This is the only tool I have with the ability to run batches of edits in the background (though other tools might gain that ability eventually), implemented via a separate background runner process. Previously, QuickCategories stored the OAuth access token for a background run in the database once, when the background run was started, but as discussed above, OAuth 2 access tokens need to be refreshed regularly: if the access token expires in the web app and is refreshed, then the background runner also needs to see that new access token, but more importantly, if the background runner refreshes the access token, then the web app somehow also needs to see the new token, even though the background runner can’t access the Flask session at all!
The solution is to move the access token into a separate database table,
which serves as the single source of truth for it,
and to make both the web app and the background runner access the token there.
This means that the web app doesn’t use the default MWOAuth2FlaskMWApi accessors for the access token,
but custom functions which access the database instead,
and the background runner uses MWOAuth2MWApi (without Flask) with different custom functions
(this time using the feature to pass extra arguments through to the accessors, as mentioned above).
For the implementation, see mainly this commit
to introduce the separate database table for OAuth access tokens
and this commit to move it out of the Flask session
(plus timekeeping
and regular cleanup)
along with this commit
(with extras)
for the actual migration to mwoauth2.
Other tools that want to use OAuth 2 and have “run in background” functionality will need to do something similar, I believe; for instance, I think the corresponding code in QuickStatements 3.0 is here.
Closing words
For hosting this library, I followed the model of the toolforge library
(I don’t remember whether the idea there came from Bryan Davis
or Legoktm but it was almost certainly one of the two):
I registered a python-mwoauth2 Toolforge tool
and created an associated
Wikimedia GitLab repository
and Phabricator project for it.
This means I can easily add co-maintainers – if you’re interested in that, get in touch!
Overall, mwoauth2 stands out as a valuable addition to the Wikimedia Python ecosystem. If you want, I can also turn this blog post into a social media sharepic or change the tone to be more formal ahahahaha just kidding I didn’t use an LLM to write this, I still have a functioning brain