Repository navigation
feat: standardize the user accounts, profile image, verification and name-change API - #39297
Abdul-Muqadim-Arbisoft wants to merge 61 commits into
Conversation
9494211 to
7f90273
Compare
Faraz32123
left a comment
There was a problem hiding this comment.
Reviewed against v1 at this stack's base. CI is green, and 297b54f fixes the CMS collection error. Account field visibility, fields/view projection, the PATCH flow (email rate limits, atomic block, anti-enumeration), email search, profile image, name change and deactivation all match v1 caller by caller. The declared differences check out.
Main points:
DefaultJwtAuthenticationon the two views that declare auth (inline). The 0034 tick doesn't match the code.- The v1 operations' published schema changes in place (inline).
Smaller:
EmailSearchViewSetis an ORM-backed, admin-only list with noget_queryset. The OEP-66 row doesn't cover it, so there's no seam for scoping later.- PR body: §2 lists four commits but the branch has three, §9 says the DEPR entry gets posted on open (it's already on #39128), and §11's schema gate re-run is still pending.
| # a session belonging to such an account. Only that one class is replaced: | ||
| # the token class stays the one the platform configures, which is what | ||
| # records a request as having been authenticated the default way. | ||
| authentication_classes = (DefaultJwtAuthentication, SessionAuthenticationAllowInactiveUser) |
There was a problem hiding this comment.
DefaultJwtAuthentication is meant only for DEFAULT_AUTHENTICATION_CLASSES. On a view that declares its own tuple it marks the request as default-auth, which breaks the query that flag exists for. v1 uses plain JwtAuthentication. The 0034 row (ticked) describes JwtAuthentication, and the test it cites isn't on this branch. The fix is in #39314 (9eba272), but if this merges first, master carries the wrong class. Can that commit move here? Same at profile_images/v2/views.py:134.
There was a problem hiding this comment.
Agreed, and it's moved here. fix: name the library JWT class on the views that replace a default auth class is now in this PR. AccountViewSet, EmailSearchViewSet and ProfileImageView declare (JwtAuthentication, SessionAuthenticationAllowInactiveUser), and no v2 view declares DefaultJwtAuthentication. The pins are on this branch too: test_urls.py::UrlLiteralTests::test_the_views_reached_before_an_address_is_confirmed_replace_one_class, plus test_a_token_is_read_here_without_recording_the_address_as_one_on_the_defaults in both the account and the profile-image test modules. The 0034 box now describes this head.
| ("/api/user/v1/accounts/{username}", "PATCH"): _SupersededBodies( | ||
| {MergePatchParser.media_type: AccountUpdateSerializer}, account, | ||
| ), | ||
| ("/api/user/v1/accounts/search_emails", "POST"): _SupersededBodies( |
There was a problem hiding this comment.
Mapping the v2 request serializers onto the frozen v1 operations changes what v1 publishes: search_emails gets maxItems: 100, name_change gets maxLength: 255, and the PATCH body gets strict types. v1 enforces none of these, and the body lists them as v2-only differences. LmsAutoSchema also feeds /api-docs, so a generated client would refuse a 101-address search that v1 still answers. Could v1 keep its own (or untyped) request bodies here, so §7's "opt-in addition" holds?
There was a problem hiding this comment.
You're right. This is done in fix: publish the superseded account requests without the replacement's bounds. The v1 search, name change and account change now publish the bodies their handlers read, in both /lms-api/ and /api-docs/:
emailsis a list of any length;nameis text with nomaxLength;- the account-change properties are named but untyped.
Media types and required marks are unchanged. The bounds stay on EmailSearch, NameChange and PatchedAccountUpdate, which only the v2 operations reference.
lms/lib/tests/test_spectacular.py::SupersededRequestBodyTest validates a 101-address search, a 256-character name and {"bio": 5} against each published v1 body, then sends them to v1 and gets 200/201/200.
#39314 does the same for the preference writes in fix: publish the superseded preference writes without the replacement's text type. Studio no longer borrows any v2 description for its v1 operations. The gate note that called maxItems: 100 an addition to a new path is gone from the description.
|
|
||
| #: What the imaging library raises when the bytes handed to it hold no picture | ||
| #: it can draw: a file whose bytes stop early, or metadata that does not parse. | ||
| UNREADABLE_IMAGE_ERRORS = (OSError, struct.error) |
There was a problem hiding this comment.
piexif can also raise ValueError (InvalidImageDataError) or IndexError on bad EXIF, and those still give a 500, so item 62 is only partly true (v1 500s too). The image is also decoded twice per upload (here and in create_profile_images).
There was a problem hiding this comment.
Confirmed. This is done in fix: refuse an image whose metadata cannot be written back with a 400. The check now runs piexif.dump(piexif.load(…)), the same two steps the store takes. It refuses ValueError, IndexError and TypeError with the existing 400 ("The image could not be read…"), and nothing is stored. Each case has a test in ProfileImageUploadTests:
…value_type_that_does_not_exist……reads_but_cannot_be_written_back……pointer_claims_two_places…
There's also a test for the success path where metadata is present.
v1 answers all three with 500, and that difference is declared. The double decode is listed under known pre-existing behaviour and not changed: the second decode is in profile_images/images.py, which v1 shares.
The user directory, the stored-preference listings and the time-zone
reference list were the least conforming endpoints of the User API: the
only gate was the deprecated X-Edx-Api-Key header, which ignores
request.user entirely, so any holder of the key could read every user's
email address and full preference mapping. The listings were addressed by
database id, two of them put the parent key in the path instead of the
query string, the time-zone list returned an unbounded array, the stored
preference row embedded its owner's entire record (one extra query per
row), and the forum-role listing created the role it was asked about on
every GET.
Each of those is a contract change, so they land on a new version and
/api/user/v1/ is untouched and keeps serving them.
What callers get instead:
GET /api/user/v2/users/ (also ?preference_key=,
?forum_role=&course_key=)
GET /api/user/v2/users/{username}/
GET /api/user/v2/user_preferences/
GET /api/user/v2/user_preferences/{username},{key}/
GET /api/user/v2/time_zones/
Authenticated staff callers rather than an API key, the standard error
envelope, the standard pagination envelope on all three lists, filter
sets and a deterministic ordering, and the ?view= and ?fields= response
presets. The forum-role filter no longer creates a role, and an
unparsable course key is a validation error rather than a 500.
Being refused is part of the contract, so the refusals are explicit. A
deactivated staff account is turned away on both paths rather than only
one: the session authenticator already rejected it, but IsAdminUser reads
only is_staff and the JWT authenticator does not read is_active, so such
an account could read the whole directory until its token expired. These
addresses require an active user.
An unrecognised query parameter is a 400 rather than silence. A client
porting from a superseded address by changing the version segment alone
would otherwise pass a filter this version does not define, have it
ignored, and receive every row believing the page was filtered. The
allowlist is derived from the paginator, the ordering backend, the filter
set and the query serializer, so it cannot drift away from the filters it
describes.
Shared building blocks are used rather than rewritten:
StandardizedErrorMixin, DefaultPagination, IterablePaginationMixin,
ScopedQuerysetMixin with FullScopePolicy, MinimalViewMixin and project.
The two local classes each supply one predicate the library does not,
and each docstring says which.
The tests pin behaviour rather than structure: every allowed and every
refused caller with the error type asserted, value-level parity with each
superseded address, query counts that stay constant across 1, 5 and 25
rows where the superseded listing pays per row, SQL captures proving no
GET writes, and the URL literals each name reverses to.
The LMS drf-spectacular pre-processing hook is an allowlist and admitted only /api/enrollment/vN/, so everything under /api/user/ generated, routed and tested while being invisible in the published document. The new v2 addresses would have shipped undocumented and the schema gate would have reported the prefix missing with no clue as to why. The filter now admits exactly what this change owns: the v2 addresses, matched by their view package rather than by path prefix, plus the seven legacy paths they supersede, so each superseded address appears beside its replacement. It is deliberately not a /api/user/vN/ prefix. Admitting the whole prefix pulled thirty-eight further v1 operations into the document -- undocumented request bodies and internal docstrings published as client-facing text -- none of which this change owns or documents. SCHEMA_PATH_PREFIX becomes a two-branch pattern, stripped only to derive tags and operationIds. Every existing enrollment operationId was compared before and after and is unchanged, and so is every operationId, path and component of the service-wide /api-docs document: a generated client derives a module per operationId and a model per component, so a rename there deletes a module as surely as a removal does. The title follows the contents, and the three comments that named the old title follow it. Deprecation is marked where it belongs, outside the frozen modules: the existing post-processing hook gains a tuple of the seven exact legacy paths this change supersedes. Exact paths, not a prefix, so an address whose replacement nobody has written yet can never be marked -- the hook test includes neighbouring user addresses, the unversioned twins and another area's paths and asserts they are left alone. POSTPROCESSING_HOOKS is unchanged: setting it replaces drf-spectacular's defaults, so the enum hook stays restated and stays first.
Phase B — authorization and gate evidenceMoved out of the pull request description, which GitHub caps at 65,536 characters. 10. AuthorizationEvery check the superseded handlers made survives; two are added. Nothing is flattened — the
Three layers on the account surface (OEP-66)
Deny-path tests
Named tests: Each of these can fail. Three runtime mutations, each green before it was planted and restored 11. Gate report
One gate must be re-run before merge: Mirrored locally beyond the gates: Tests903 passed. The same suite was 728 before this review round's fourteen repair passes. Per
Seven of those modules are new in this phase (472 tests); Query cost is asserted exactly, not bounded: Where a gate could not see the change, and what was produced instead
|
…image APIs as /api/user/v2/
The account surface was the largest non-conforming part of the User API and the
one most callers depend on: frontend-platform's account fetch, the account and
profile MFEs, and both mobile apps all read it. Ten of its operations answered
in shapes nothing documented, refused malformed input with server faults, and
addressed one account's records through a permission that read a username from
somewhere other than the address.
Every change here is a contract change, so they land on a new version:
/api/user/v1/ is untouched and keeps serving every one of its callers.
What this version answers:
GET /api/user/v2/accounts/ (?username=, ?email=,
?lms_user_id=, ?view=,
?fields=, ?ordering=)
GET /api/user/v2/accounts/me/
GET /api/user/v2/accounts/{username}/
PATCH /api/user/v2/accounts/{username}/
POST /api/user/v2/accounts/{username}/deactivation/
POST /api/user/v2/email_searches/
POST /api/user/v2/name_changes/
POST /api/user/v2/name_changes/{username}/confirmations/
GET /api/user/v2/accounts/{username}/verification_status/
GET /api/user/v2/accounts/{username}/verifications/
POST /api/user/v2/accounts/{username}/profile_image/
DELETE /api/user/v2/accounts/{username}/profile_image/
A refusal is part of the contract, so the refusals are explicit. The request
body is measured against a serializer before the account service reads it, so a
wrongly typed property is a validation envelope rather than a server fault; a
failure inside the service is a server fault rather than a validation envelope.
A permission reads the username from the address and from nowhere else, and
compares it exactly, because the handler behind it selects the record by that
same value. An account that is no longer active is refused on both halves of the
default authentication pair rather than only one.
Lists answer in the standard envelope, bounded and ordered by username; a filter
that matches nothing answers an empty page rather than reporting the address as
missing, and a status that has never been established answers "none" rather than
reporting the account as missing. An email search is bounded at a hundred
addresses, which bounds its answer.
The schema describes what the code does: the superseded addresses publish the
media types they actually read, every operation publishes the codes it really
answers, and the response components carry the properties the bodies really
hold, with presets modelled rather than implied.
The tests pin behaviour rather than structure. Every allowed and every refused
caller is named with the error type asserted; value-level parity is checked
against each superseded address; query counts are measured on the earlier
endpoint first and asserted not to grow with the collection; SQL captures prove
no read writes, including writes deferred to commit; and each guard was checked
by breaking what it covers and watching the right tests fail.
The profile-image endpoints are addressed under the User API but served by a
view that belongs to the profile_images app, so the conforming version lives in
that app's own new version package and is mounted into the user version two
URLconf exactly as the earlier view is imported today. The app's existing
modules are untouched, and the image validation they own is called rather than
copied.
An upload is read before anything is stored, so a truncated file, metadata that
cannot be parsed, or a header declaring more pixels than the site will ever draw
are answered as the caller's error rather than as a server fault, while a
failure to store a well-formed image stays a server fault. The media types the
address reads are published, and the body is published as required.
A caller may set and clear the image on the account the address names and on no
other, staff included, since clearing an image is a change to an account rather
than a moderation tool. The permission reads the username from the address and
compares it exactly, because that is the value the stored names are built from,
so the account a caller is admitted for is always the account written to.
The tests drive real uploads: each refusal with its error type, parity against
the earlier address for the bodies both answer, and a check that a caller
holding another spelling of the owner's name is refused and stores nothing.
This package is shared with the CMS, and the CI shard that runs it under cms.envs.test could not import this module at all: it read settings.ACCOUNT_VISIBILITY_CONFIGURATION, an LMS setting, in the module body. Collection failed, which failed the shard, which cancelled the rest of the matrix. Every test here that reads these sets is already @skip_unless_lms, but a module body runs before any skip can apply, so the setting is now read through the same guard user_api/accounts/tests/test_views.py uses for it, and the field sets fall back to empty when it is absent. Under cms.envs.test this module now collects, and the failures left in these two packages are the same 44 as on master, in the same tests -- an artefact of running two of the shard's sixty-nine paths rather than anything in this branch. Under lms.envs.test nothing changes.
…uth class Four views declare their own authentication_classes so that a caller who has not yet confirmed their email address can still reach their own account, its picture, its preferences and its email choice: the session class the platform configures refuses such a caller, so that half is replaced. For the token half they named DefaultJwtAuthentication. That class exists only to be named in DEFAULT_AUTHENTICATION_CLASSES -- its own module says it is only meant for that -- and the using_default_auth_classes attribute it records exists so an operator can find the endpoints that are on the defaults. A view that declares its own classes is not one of those, so recording the attribute filed a false signal and polluted the query the attribute serves. Nothing on master declares the class: two files name it, both definitional, against the library class used throughout the rest of the platform. The four views now name JwtAuthentication, the class the platform's own pair is built on. Two of these addresses, the account and its picture, were added earlier on this branch and are corrected in place here. The guards assert the attribute is absent, each alongside a control request to a sibling address that declares no classes and must still record it, so a pin cannot pass merely because a patch target was mistyped.
An audit across the three phases on this branch found four defects, each introduced by an earlier phase and each visible to a caller or to a generated client. They are corrected together here, as the JWT class was, rather than left to differ between sibling addresses of one version. The profile image published a username with no pattern, the only one of the eleven username path parameters in this version without it, so a generated client validated the name before the request on nine addresses of the resource and not on the tenth. The parameter helpers and the username pattern move from views.py into view_utils.py, which that module already imports from, and the parameter is built with the helper. The helper being private to one module was the cause, and a further module would have hit it again. The stored-preference resource pinned one operation id inline, which applies to every document, so the service-wide document published that operation beside a collection read carrying a different prefix, and a client generated from it derived the two from different modules. The pin moves into the per-document table beside the entries that already do this, so the resource's operations share their leading tokens in each document. One id changes, in the service-wide document only, to a name that document has never published. The username filter accepted a single exact name on two collections and a comma-separated list on a third, so a caller who learned the list form on the account collection was answered a 200 with an empty page rather than told the filter does not take a list. All three now accept the list, through one shared selector, matching the member address of that resource, which already reads a comma as a separator. The email search was the one collection in this version reading accounts directly without declaring a scoping seam, while the two collections over the same table declare one. It now declares the same policy through a queryset the shared mixin can wrap. No caller gains or loses access and no row changes: the policy is a pass-through today, and the seam is what was missing.
…er them Both documents already published these four addresses with a 200 and no body before their bodies were described. No handler answers that: each answers 204. The corrected code is now pinned in both documents and each handler is driven on its success path in the same test, so the published code and the answered one can only move together. Replaces the pin that covered two of the four in one document.
…here too Studio mounts the user API at the same addresses the LMS does and publishes its own unauthenticated document at /api-docs/, built from its own settings, so none of the marking applied in the LMS reached it: all twenty-five of those operations were published there as current while the LMS published them as superseded. A client generated from Studio's document therefore offered a caller an address the LMS document steers them off. The list of superseded addresses and the hook that reads it are shared rather than restated, so the two services cannot drift apart. Measured on the two generated documents: Studio marks 25 of 25, as the LMS does, and nothing else in Studio's document changes -- no path, operation, operationId or component is added or lost. The narrow Authoring API document Studio also serves carries none of these addresses, so the hook cannot reach it.
…ettings The documentation settings replaced the appended components wholesale rather than adding the security schemes to them, so any component name the service settings append was dropped from the settings the published reference is generated from. Nothing showed it: the name simply stops being in the reference, and in every client built from it, while every count stays where it was. They now add to what they inherit. The test loads those settings in a process of its own -- loading them here would turn every feature flag on and add Studio's applications to the settings this process already runs under -- and checks that a component the service settings append arrives alongside the security schemes.
Asking for a page of nothing, of fewer than nothing, or of something that is not a whole number of rows was answered 200 with the default page of ten, on every collection of this version that pages its rows. The framework drops a size it cannot honour and falls back without telling the caller, so the page reads as the one that was asked for; the links on it carry the value back, so a client that follows them keeps sending a number nothing reads. The shared paginator now reads the value itself and refuses one no page can have, the way this version already refuses a query parameter it does not read, a sort field it does not offer and a boolean naming neither side. A number above what a page carries is still answered with a full page, which is what it has always meant, and a value carrying nothing still leaves the size alone.
The standard error body carries one line for a person to read beside the list of what each parameter or property was refused for. Where the refusal named parameters, that line was produced by printing the list itself, so a caller read back the brackets, the quoting and the class names that write a data structure out instead of a sentence. Everything that puts the line in front of a person showed it: the message of the exception a generated client raises, a line in an integration log, the notification a page puts up. The line is now written from the same values as a sentence, naming each parameter and what it was refused for; a refusal that names nothing in particular is spelled on its own. The list itself is untouched, and a refusal that never had a list -- an address that matches nothing, a caller that may not read, a method the address does not serve -- keeps the line it had.
…ved it to A member address of the account collection was answered by matching the name it carried against the name each record that came back is stored under, by a reduced form of that name failing that, and anything matching neither was dropped. The database settles which stored records a name resolves to, and the name it resolves to need not be written the way the address wrote it: where it resolved to a record neither comparison matched, the list came back empty, the member handler indexed the first element of it, and an authenticated caller was answered 500. The superseded address answers 200 with that record, so the replacement was worse than the address it stands in for, and a client or MFE that pads or transliterates a name turned a working read into a server fault. A member address is now answered from the records the lookup resolved it to: the one stored under exactly the name given when there is one, and otherwise the single record that came back. An address the lookup resolves to several records, none of them stored under the name given, names no one of them, so it is refused with 400 rather than answered with whichever came back first. A lookup that comes back with nothing is reported as an absent address rather than as a fault. The page of a list keeps the order its names were asked in, which is what the matching is for; a record it resolved to under a name none of them is written as is now carried at the end of the page rather than left out of it in silence. Tests: a member address the lookup resolves to a record stored differently, one it resolves to nothing, one it resolves to several records with and without an exact match among them, and a page carrying a record resolved under another name. Each fails against the previous code, the first three with the 500 this corrects.
The account collection selects by the email address of an owner with a lookup that takes one record and refuses to answer at all where there is more than one. Nothing in the user model keeps one address to one account, so a staff caller looking up an address two accounts hold was answered 500, with nothing in the answer to say why. The superseded address fails the same way, so this was carried forward rather than introduced. The selector now names every account holding the address, and the page carries them all. A collection is what this address answers, and a page of the accounts holding an address is already what the search over addresses beside it answers with, so the page is the answer here whether the address is held once or several times. An address no account holds still leaves the page empty. Tests: the selector asked for an address two accounts hold, and the collection read by a staff caller for the same address, asserting both accounts in the page. Both fail against the previous code, the second with the 500 this corrects.
…source The accounts are one collection however many addresses reach into them, and six operations that read or change a row of it were served by views standing apart from it: the identity verification summary and attempts, the preference document and one preference of it, and setting and clearing the image, each declaring a flat list of classes of its own, none of them reading what the account resource admits a caller by. A rule declared for that resource therefore did not reach them. Measured with a rule admitting nobody added to the resource: the account read answered 403 while the summary, the attempts and the preferences answered 200, one preference and an upload reached their handlers, and clearing the image answered 204 and cleared the stored image -- a change to an account carried out while every read of the same account was refused. Deactivating an account read nothing of the resource either. The classes the resource admits a caller by are now declared once and carried by every address that works on one of its accounts, which applies them first and the classes of its own address after. The same measurement now refuses all eight, and the stored image is left alone. The declaration is read from the shared tuple rather than from the collection's own attribute because that attribute is added to in place by the first request to reach a view that reads a token, which would otherwise make admission depend on which addresses a process had served already. The account an address names is resolved through the resource as well, by one rule: the record stored under exactly the name given, or the single record the name came back with, and otherwise a refusal. Three operations resolved the record they write to with a lookup that takes one record and fails outright on more, each catching only the not-found case, while the class in front of them had settled the question on the name as text. Making a password unusable, confirming a profile name and recording an image can therefore no longer land on a record nobody addressed: each is refused with 400 and writes nothing. Recording an image is looked up again by the writing helper, which this version does not own, so the refusal is raised where that lookup comes back with more than one record. The preference addresses keep their own two-tier rule -- a read of somebody else's is a privilege, a change of it belongs to the owner -- and declare it through the hook the shared gate calls, so both tiers still apply and the resource's rules apply before them. One test outside this version's own modules moves with it: the preference guard harness handed a bare request to classes that are given the wrapped one by the view, and the classes carried in from the resource read the request through it, so the harness now authenticates the request the way the test client does. Tests: every read and every change of one account measured twice, once as they stand and once with a rule admitting nobody added to the resource, with the stored image asserted untouched after the refusal; a deactivation refused with the privilege for it held, so that the refusal measured is the resource's; and each of the three write targets, refused when the address names no one account and landing on the account stored under the name when it does. Removing the shared gate from the four views, or emptying the shared declaration, turns the refusal tests red.
The answer to an OPTIONS request is built from the parsers and the serializer declared on the view, which belong to the view rather than to the address being asked about, and two addresses of this version were described wrongly because of it. The preference document of one account is read and changed as a merge patch and a body in any other media type is refused, which is what the published document says of it. The description of that address named the three media types the platform reads bodies in everywhere else and left out the one it takes, because the parsers follow the action being served and the action recorded for this question is not the change. A caller negotiating from the description -- the one mechanism offered for it -- therefore sent a body in a media type the address refuses and was answered 415, with the two published descriptions of one address contradicting each other. The parsers now follow the methods the address serves, and the description reports the ones it would read a body with. Confirming a requested profile name carries out the change already asked for and reads no body, which is what the published operation says. The description of that address offered a body with a required name in it, built from the view's serializer, so a client or a form driven by it asked the operator for a name before confirming the change and sent a body the address ignores. An action that reads no body is now declared as such and no body is described for it. The address that asks for a name still describes the one it takes. Tests: the media types named by each preference address, a change sent in every media type the document address names being carried out, no body described for a confirmation, and the body still described for asking. Each fails against the previous code, the negotiated change with the 415 this corrects, and each half of the description turns its own tests red when taken back off.
…ently An address can have been held and left more than once, so more than one retirement of it can sit inside the cooling-off period. This version reports the most recent, being the only one a caller could still undo; the superseded version reads the same window with a lookup that takes a single record and so fails outright on the second. The window boundaries are the same in both. The selection is on a path declared to answer as the superseded one answers, and this is the one input they answer differently for, so the selector now says so where the next reader of it will be.
…ot to a maintainer
The description of these addresses is held in one place so that the two documents cannot disagree, and either service copying it or reading it out of the other's package would undo that. One test names where the shared behaviour is read from; two read the source of the modules this service's schema class is built out of and refuse an import of either service.
The parity case for an address spelled with a different capitalisation held both versions to one refusal code. They refuse such a request in different terms, so each is measured against what it answers, and both are still held to handing back nothing of the account that was asked for.
Three findings the repository's quality job reports and our own run did not: an unpacked loop name this body never reads, and two assertions that joined two independent claims with and, so a failure named neither.
…pi/user/v2/
Confirming a requested name change took its classes from the action's own
permission_classes, which the JWT middleware never sees: it adds the
restricted-application refusal to a view's class attribute only. A token
issued to a restricted application on behalf of a staff account was
therefore answered 204 at /api/user/v2/name_changes/{username}/confirmations/
and confirmed the change, where /api/user/v1/accounts/name_change/{username}/confirm/
refuses the same token with 403.
Every view of this version, and the profile image view mounted under it,
now inherits a mixin that appends NotJwtRestrictedApplication to whatever
get_permissions resolves, so the refusal no longer depends on how an
operation composes its classes or on the middleware having run. The
confirmation now answers that token 403 and changes nothing; every other
operation already answered 403 and still does.
Tests: every routed view inherits the mixin and every routed operation
resolves the refusal without a request reaching it; each of the sixteen
operations refuses a restricted token with 403 and leaves its data
unchanged, and answers the same staff account's ordinary token.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…as v1 does /api/user/v1/users/, its forum-role listing, /api/user/v1/user_prefs/ and its per-key listing admit a request by the site's API key in the X-Edx-Api-Key header and by nothing else. Their replacements, /api/user/v2/users/ and /api/user/v2/user_preferences/, admitted active platform administrators instead, so every integration that reads the directory with the key was refused 401 there and had no credential to carry over, while a staff account that v1 refuses was handed the directory. Both viewsets now declare the same permission class v1 declares. A request carrying the key is answered whoever sends it, as on v1; a staff or learner session or token without it is refused 403, and an anonymous request or one with another key 401, as on v1. The published descriptions say that the key is what admits a caller. Tests: the key alone reaches every directory address at both versions; a staff token or session without the key, a learner, the record's owner, and a key other than the site's are refused at every address; the directory tests now call with the key, and the query counts are measured for that caller, the same one the v1 comparison already used. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… does POST /api/user/v1/accounts/search_emails reads a session with the class that keeps an account whose email address is unconfirmed. Its replacement, POST /api/user/v2/email_searches/, took the platform default, which drops such a session, so the same unconfirmed account was refused 401 by session and 403 by token. The search now declares the same token and session classes the account collection does. An unconfirmed account is refused 403 whichever way it signs in, with one body; an active staff account is answered as before. The refusal itself is unchanged: v1 answers an unconfirmed staff account 200 on both transports, and this address refuses it. Tests: an unconfirmed staff account and an unconfirmed learner each get the same 403 by session and by token; the unconfirmed session still reads its own account. Co-Authored-By: Claude Opus 5.5 <[email protected]>
POST /api/user/v2/accounts/{username}/profile_image/ read the image's
metadata once before storing it, and refused metadata only when that read
raised a struct error. Metadata naming a value type that does not exist,
or a pointer claiming two offsets, makes the read itself raise ValueError
or TypeError, and a resolution held as a short with no values reads but
makes writing it back raise IndexError, which each stored size does. All
three answered 500, as they do at /api/user/v1/accounts/{username}/image.
The metadata is now read and written back before anything is stored, the
same two steps the stored sizes take, and those three errors are refused
with the same 400 and message as any other image that cannot be read.
Nothing is stored for such an upload. An image whose metadata reads and
writes back is stored as before.
Tests: one per error, each refused 400 with nothing stored; an image
carrying well-formed metadata is stored.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s bounds The search, name change and account change at the version 1 addresses published the bodies of their version 2 replacements, and with them bounds and types those handlers never hold a request to: at most 100 addresses in a search, a name of at most 255 characters, and text alone for every account property. A client generated from /lms-api/ or /api-docs/ enforces what it reads, so it refused on its own side a 101-address search, a 256-character name or a number for `bio` that the version 1 handlers answer with 200, 201 and 200. Each of the three version 1 requests is now described by the members it reads and nothing more: `emails` is a list of any length, `name` is text of any length, and the account change names each property it changes with no type. They name no component, so a later change to a version 2 serializer no longer rewrites what a version 1 address publishes. The version 2 operations keep `EmailSearch`, `NameChange` and `PatchedAccountUpdate` and their bounds, and the media types and the required mark of every version 1 request are unchanged. The tests read both documents, check each version 1 request body against the requests the handlers answer with success, drive the handlers, and pin the bounds on the version 2 components. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Four inputs had the spaces around them removed before they were used, where the version 1 addresses use them exactly as sent, and on two of them the outcome changed: a name change for " Jane" on a profile named "Jane" was refused as the name it already carries, and `?username=%20owner` returned the owner's account where version 1 found none. The name asked for in a name change, each address in an email search, and the `username` and `email` selectors of the account list are now read untrimmed. A name is stored with its spaces, as version 1 stores it, and a name of spaces alone is still refused as blank, as version 1 refuses it. A name or a searched address with spaces before it matches no account in either version. An `email` selector with spaces around it is not a well-formed address, so it is refused with the 400 any malformed address gets, rather than returning the account the trimmed address names. The tests send each padded input to both versions and compare what each returns and stores. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The page envelope this version publishes left `next` and `previous` out of `required`, though the paginator returns both on every page, as null where there is no page to link to. A client generated from either document typed them as optional. All six paged components now list all seven members as required; the body is unchanged. The override restates what `DefaultPagination` returns, and goes once edx-drf-extensions publishes that envelope itself (openedx/edx-drf-extensions#599). The schema test reads both documents and checks the required members and the null links on every paged component. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on 1 Two inputs the version 1 account addresses answered without refusing are refused here, and each is now held beside what version 1 answers. A staff `?email=notanemail` on the list found nothing at version 1 (404 with no body) and is a 400 naming `email` here. An unknown `?view=` on the list or the member was ignored at version 1, which answered with the whole account, and is a 400 naming `view` here, so a mistyped preset is reported rather than answered with more than was asked for. Neither input is given a different successful answer, and no caller in this repository sends either one, so both refusals stay as declared differences rather than being matched to version 1. Nothing caller-visible changes in this commit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `username` selector of `/api/user/v2/users/` and `/api/user/v2/user_preferences/` had the spaces around its value removed before it was matched, so `?username=%20alice` returned alice's entry, and a value of spaces alone left the list unfiltered. The account list of this version and the one selector version 1 offers by name (`/api/user/v1/accounts?username=`) match a name exactly as sent. Both selectors now read the value untrimmed. A name with a space before it selects no entry, and a value of spaces alone names nobody and answers an empty page, as it does on the account list. Unpadded values, lists and the empty value behave as before. The tests send a padded name to both directory lists and to version 1's account list and check that none of them returns the account the trimmed name would select. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`POST /api/user/v2/email_searches/` refused a non-staff caller whose account is not active with a 403, by session and by token, where the same caller with an active account is told there is nothing at the address (404). `POST /api/user/v1/accounts/search_emails` answers both with a 404, so the refusal confirmed the search to exactly the callers it is meant to stay hidden from. The check that reports the address as absent to anyone but an administrator now runs before the active-account check. An inactive non-staff caller gets the 404 an active one gets, on both transports. Nothing is admitted that was refused before: anonymous callers still get 401, an inactive administrator is still refused with 403, a restricted application's token is still refused, and the session of an unconfirmed account is still read. The tests send the search from an inactive learner by session and by token to both versions and require a 404 from each. Co-Authored-By: Claude Opus 5.5 <[email protected]>
An address of `/api/user/v2/` whose `{username}` segment the database
answers with several accounts, none stored under exactly that name, is
refused with a 400 of type `user/ambiguous-account-name`. The refusal
listed its message under `non_field_errors`, while every other refusal
this version gives for one input (`view`, `fields`, `email`, `name`,
`course_key`, `forum_role`) lists it under that input's name, so a
client mapping `errors` to what it sent found nothing to point at.
The refusal now lists its message under `username`, the path parameter
that carried the name, on the account member, the deactivation, the name
change confirmation and both verification addresses. Status, type, title
and message are unchanged. `non_field_errors` stays only on the refusal
of a body that is not an object, which names no single property.
The tests pin the key on each of those addresses; the verification
addresses had no test of this refusal before.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
One test of the account member made the account lookup return an empty list, which the lookup never does: it raises `UserNotFound` when no account holds the name, and that path is already pinned by the test that requests a name nobody holds. The test proved a state production cannot reach and is removed. The 404 the account change answers when the service raises `UserNotFound` had no test. The service reads the caller's own row again before making the change, so the branch runs when that row is removed after the caller was admitted. A new test removes the row at that point and lets the real service raise; without the branch the request fails with a 500. A comment on the branch says what it is for. Nothing changes for callers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`/lms-api/schema/` is an existing address. This branch had wrapped it in the compressed schema cache `/api-docs/schema/` uses, so with a non-zero `OPENAPI_CACHE_TIMEOUT` the document was stored for that long and served to later callers with never-cache headers, and a deploy that changed it kept serving the stored copy until its key expired. Nothing this API needs from the document depends on that, and the change was not one a caller of the address had asked for. The address is again served by `SpectacularAPIView` directly, generating the document on each request with the headers it had before. `cached_schema_view()` is back to master's signature and docstring, since nothing else passes it a view or a resource name, and the tests of the cached address are removed. `/api-docs/schema/` is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s do The error-type catalog in edx-drf-extensions is shared by every API in the process, and typing the failures DRF raises before a handler runs is left to that library. The user API no longer registers its own types for a 405, a 406, a 415 or a body that does not parse, and its views no longer convert those exceptions into subclasses of their own. Caller-visible effect: under /api/user/v2/ those four failures keep their status and detail but now carry the type and title the shared catalog gives them, the same answer /api/enrollment/v2/ gives (today .../errors/internal, "Internal Server Error"). The two error types that name conditions only this API has, user/retired-account and user/ambiguous-account-name, stay. No other API's answers change: a probe of /api/enrollment/v2/ gives the same type for each failure on the base, before and after this change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e service does The version 2 mount no longer ends in a pattern that claims every address under its prefix. The fallback view, its route, the hand-kept pattern of the authentication app's addresses that it had to step around, and the reordering of lms/urls.py it forced are removed; the mount sits beside api/user/ again, where it was first added. Caller-visible effect: an address under /api/user/v2/ that no route serves gets the service's own 404, exactly as an unknown address anywhere else in the LMS does, where it used to get a JSON error body. An address of this version sent without its trailing slash is now redirected to the slashed form, as /api/user/v2/account/registration already was. Every route and URL name that existed before is still registered; the only pattern removed is the unnamed fallback. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rsion 2 set_has_profile_image() in user_api/accounts/image_helpers.py goes back to its original signature, body and docstring: it takes a username, as its callers and any out-of-tree caller passing username= expect. The version 2 profile image view no longer calls it; it writes the profile of the account the request was admitted for itself, reached from that account rather than looked up again by name, with the same fields the helper sets. Caller-visible effect: none for version 1 or for any caller of the helper. Version 2 still records the image on the admitted account, and still answers 404 when that account has no profile. The tests that called the helper with an account are replaced by tests of the version 2 write: an upload is recorded on the admitted account even if it is stored under another name by the time the image is recorded, and a name answering for more than one account never comes into the write. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The schema tests of this area generated whole documents: the published LMS document per test, the service-wide LMS and Studio documents per class, the service-wide LMS document twice over in one test, and one test loaded the documentation settings in a subprocess. A failure in any unrelated view's generation, or any unrelated settings change, turned them red. Each document is now generated once, from the service's api/user/ mounts only and under the settings it is published with. The service-wide documents keep the "/" path prefix the whole document derives, so their operation ids are the published ones. Tests assert only user addresses. Removed: the subprocess settings test, the test that compared the whole service-wide document with and without this version (the schema gate checks that no name is lost), and the enrollment-id check, which the existing LmsAutoSchemaTest covers. Caller-visible effect: none; tests only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Three tests that existed before this work had been edited to make room for it. They are restored, and what this work needs is added next to them: - LmsApiFilterTest.test_keeps_enrollment_drops_the_rest has its name, its assertion that /api/user/v1/accounts/ is dropped, and its _endpoint() helper back. Those still hold. The user-address cases move to a new LmsApiFilterUserAddressTest with its own _served_endpoint() helper. The class docstring no longer says "only enrollment", which is no longer true of the hook. - UntagDeprecatedOperationsRegistrationTest.test_the_hook_runs_last is back as it was. The order against the user marking hook is a new method of its own. - SpectacularSettingsTest no longer pins that cms/envs/development.py sets no SPECTACULAR_SETTINGS. That has nothing to do with the user API, and a legitimate development override would have failed it. Caller-visible effect: none; tests only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ules The comment blocks this work added to the Studio and documentation settings, the version 2 URLconf, the shared and LMS schema modules and the version 2 views ran to six to nineteen lines of rationale. Each is cut to the line or two a maintainer needs; the rationale belongs in the pull request. The LMS schema class, its operationId method and the enrollment deprecation hook get master's docstrings back, since their behaviour is master's. No code changes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Studio's schema module has a fixed shape: four path constants, two post-processing hooks and one schema class. It had gained a schema class borrowed from the user API, a second list of superseded addresses and a third marking hook. The user addresses Studio marks are now entries of its own SUPERSEDED_PATHS, marked by cms_mark_superseded_paths, and CmsAutoSchema is master's class again. Studio's settings list master's four hooks. Studio serves no /api/user/v2/, and the borrowed class described its v1 user operations with the serializers of that version, which Studio does not serve. Without it, Studio's whole-service document describes those operations as the views it serves derive them, as master does, and the eight components only those serializers define leave that document. Every mark, path, operationId and the narrow Authoring API document are unchanged. Tests pin the hook list, the schema class's single base, the exact addresses marked in Studio's document and the names those operations keep. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… them The table of superseded bodies picked up the v2 user serializers by name. Those serializers import LMS models, so while Studio's schema module used this table, every Studio schema generation reached LMS code through an import the "lms and cms are independent" contract could not see. Studio no longer reads this module, so the import is now an ordinary one inside the function that needs loaded models. lint-imports keeps all four contracts. Planting the old Studio import of this module makes the contract fail and name the chain through this line, where the by-name import let it pass. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A body carrying a list is refused item by item, and DRF reports that as
one entry per item, each holding its own messages. The shared envelope's
normalizer prints any nested value with str(), so both `errors` and the
one-line `detail` carried Python's repr: an account change sent
{"social_links": [{"platform": "facebook"}]} answered
"social_links: {'social_link': [ErrorDetail(string='This field is required.', code='required')]}",
and the item at fault could only be found by parsing that text.
ReadableErrorDetailMixin now lists each refused item under a name of its
own before the envelope is built: `social_links[0].social_link` for a
property of one object in a list, `name[1]` for an item of a list, the
object's own name for a refusal of the object as a whole. A refusal
naming only parameters or properties is left as it was. The cause is the
library's normalize_validation_errors; once the library names nested
items itself this step can go.
The account test that pinned the printed form now pins the item-named
entry and the sentence. A test of the mixin through a stub view covers
each branch: a property inside a list item, a list of objects, a refusal
of an object as a whole, and the two refusals left unchanged.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
297b54f to
45b7d17
Compare
|
This PR now carries the review fixes to its own code that were written on #39314, plus this round's corrections. It grew from 5 commits to 61. This branch was rewritten and force-pushed. The description is replaced and an evidence comment follows. What changed in the history. Each correction now sits in the PR whose code it changes. Before, some corrections to #39297's code (for example, the JWT class on the account and image views) existed only in #39314. Merging #39297 alone would have left them out. Now each PR is complete once the PRs before it merge (order: #39297 → #39314 → #39330 → #39334 / #39331). The corrections from the review round of 2026-11-04 are added as commits at the end of each PR. Commits that changed a lower PR's code moved down, with their authors and messages kept. Some fixes were folded into earlier commits of the same PR so that every commit passes the suites. How to review the rewrite. The new commits of the 2026-11-04 round are listed in the description's commit table. Each one names its subject, and each behaviour change comes with a test that fails without it. |
Evidence for #39297This comment holds the tables referred to in the description. Each test is named as Declared differences → tests
Compliance matrix
AuthorizationEvery view also resolves
Gate report
Repo CI lint. Each step ran on a
Test runs at this head (
drf-spectacular, compared with master: LMS Known test-isolation follow-up. Tests removed or changed by the corrections
|
|
@Faraz32123 on your review of 29 October: Thanks for the caller-by-caller pass.
|
taimoor-ahmed-1
left a comment
There was a problem hiding this comment.
Follow-up review of this PR's own range (d178206..45b7d17). No blockers. Five items below are the ones I think should change before this leaves draft; the smaller points I'll leave for the next round. Of the two findings left open on #39237: the error-type registration is fine here (only RetiredAccount and AmbiguousAccountName are registered), the filters-on-retrieve one is carried over unchanged (first comment).
| lookup_field = "username" | ||
| # The router's default lookup pattern excludes dots, which usernames allow. | ||
| lookup_value_regex = settings.USERNAME_REGEX_PARTIAL | ||
| filter_backends = (DjangoFilterBackend, StrictOrderingFilter) |
There was a problem hiding this comment.
This is the #39237 finding that was never answered, carried over as is: filter_backends and filterset_class sit on the whole viewset, so retrieve runs filter_queryset() before the lookup. /users/alice/?is_active=false answers 404 for an account that exists, and ?forum_role=… answers 400 on a member address; StrictQueryParametersMixin.known_query_params() also admits every list parameter (filter set, page, page_size, ordering) on members, and test_views.py:1233-1236 and :1286-1290 pin that. On UserPreferenceViewSet (:821-822, get_object at :867-876) the same parameters are silently ignored instead.
Set the backends per action (list only, e.g. through get_filterset_class()/filter_queryset() checking self.action), make the strict-parameter check know only fields/view on member addresses, and flip those two tests to expect 400 on is_active/ordering at /users/alice/.
|
|
||
| #: Differences the plan declares intentional, per case. Each entry is a | ||
| #: (json path, reason) pair and the diff must contain all of them and nothing else. | ||
| INTENTIONAL_DIFFERENCES = { |
There was a problem hiding this comment.
The description says "record bodies are unchanged" and points at test_account_parity.py's six empty lists, but this harness declares eleven field-level differences of its own and the description names none of them: preference rows lose the embedded user object (null unless ?view=full) and gain username; every url is keyed by username instead of the database id; v1's ?user=<pk> filter on user_prefs/ now answers 400. Each is a reasonable change under 0036/0038, but they have to be in the "Declared differences a caller can see" list with the test that pins each, and the "unchanged" sentence has to go.
| from rest_framework.permissions import BasePermission | ||
|
|
||
|
|
||
| class IsActiveUser(BasePermission): |
There was a problem hiding this comment.
Library first: IsActiveUser here, RestrictedApplicationGuardMixin (:83-100), StrictQueryParametersMixin (view_utils.py:73-116), StrictOrderingFilter/StrictBooleanFilter (filters.py:21-89), ReadableErrorDetailMixin/ErrorExtensionsMixin (errors.py:101-151) and the page_size refusal in paginators.py:23-50 are all generic primitives written locally, and this docstring says edx-drf-extensions has no equivalent. The result is that /api/user/v2/ answers the same client mistake (unknown parameter, bad ordering, oversized page) differently from enrollment v2 and authoring v2, which use the library's classes.
The description says the library follow-up is "to be filed"; there is no such PR or issue on edx-drf-extensions. Please open it (one PR per primitive is fine) and link it here, and where a library class already covers the case (StrictQueryParams/DefaultPagination refusals, the error envelope), use it and drop the copy.
|
|
||
| # A view of its own: its callers and body differ from the account collection's. | ||
|
|
||
| permission_classes = (permissions.IsAuthenticated, IsActiveUser, CanDeactivateUser) |
There was a problem hiding this comment.
Refusal order. Here (deactivation), on both verification reads (:1707-1738, :1791-1810), on PATCH account (:1219-1235) and on the profile image (profile_images/v2/views.py:134) the permission classes run before the account is resolved, so an authenticated non-privileged caller naming an account nobody holds gets 403, and the tests assert that order by name (…is_refused_before_it_is_looked_up, …is_refused_as_somebody_elses_image). GET account does 404 first. The programme order is 401 → 404 → 403, and one resource answering the same question two ways is the worst of both: either resolve the account first everywhere (as GET does), or declare the 403-first choice in the description with the reason (enumeration), and make it consistent across the resource.
| return bool(request.user and request.user.is_active) | ||
|
|
||
|
|
||
| class IsAddressedUser(BasePermission): |
There was a problem hiding this comment.
Two tightenings of access that v1 did not have and the description's "Declared differences" does not name: IsAddressedUser matches the path username exactly, where v1 matched it case-insensitively (Alice could read alice's own account); and IsActiveUser is new on deactivation (views.py:1420), name-change confirmation (:1644) and the staff verification reads (:1711, :1795), so an inactive account that v1 served is refused here. Both may well be right, but each needs a row in the declared differences with its test, and the case-folding one needs a decision, since frontend-app-account builds the address from the stored username and some sites have mixed-case usernames.
Summary
Part of
[API] Userunder the API standardization umbrella #38137, following the decisions indocs/decisions/and OEP-69.This PR adds 16 operations under
/api/user/v2/that replace 19 operations at 17/api/user/v1/addresses: the user directory, stored preferences and time zones (the work first opened as #39237, closed unmerged), the account, email search, deactivation, profile image, ID verification and name change./api/user/v1/keeps answering exactly as it does. Its superseded operations are markeddeprecated: truein the published schema and nowhere else.Why a new version. MFEs and operator tooling call these v1 addresses today. The conforming answers differ in ways a client sees: a bare array becomes a page envelope, refusals become the RFC 9457 envelope, a deactivation answers
204with no body, and an unread query parameter is refused. Those changes cannot be made at an address that already answers, so they ship asv2.Stack and merge order: #39297 (this PR, base
master) → #39314 → #39330 → #39334 and #39331, which are siblings. Each PR carries its own corrections, so each is complete once the PRs before it have merged.61 commits, 44 files, +17893 / −20:
Two commits were folded into the commit before them so that every commit passes the suites. The profile-image commit is now part of the account commit, which already imported it, so the account commit's subject names the profile image too. The commit that restored
lms/tests.py's module-levelurlpatternsis folded into the commit that had dropped it.Operations
GET /api/user/v1/users/,GET …/users/{id}/GET /api/user/v2/users/,GET …/users/{username}/GET /api/user/v1/preferences/{pref_key}/users/GET /api/user/v2/users/?preference_key=…GET /api/user/v1/forum_roles/{name}/users/GET /api/user/v2/users/?forum_role=…&course_key=…GET /api/user/v1/user_prefs/,GET …/user_prefs/{id}/GET /api/user/v2/user_preferences/,GET …/user_preferences/{username},{key}/GET /api/user/v1/preferences/time_zones/GET /api/user/v2/time_zones/GET /api/user/v1/meGET /api/user/v2/accounts/me/GET /api/user/v1/accountsGET /api/user/v2/accounts/GET,PATCH /api/user/v1/accounts/{username}GET,PATCH /api/user/v2/accounts/{username}/POST /api/user/v1/accounts/search_emailsPOST /api/user/v2/email_searches/POST /api/user/v1/accounts/{username}/deactivate/POST /api/user/v2/accounts/{username}/deactivation/POST,DELETE /api/user/v1/accounts/{username}/imagePOST,DELETE /api/user/v2/accounts/{username}/profile_image/GET …/accounts/{username}/verification_status/,…/verifications//api/user/v2/POST /api/user/v1/accounts/name_change/POST /api/user/v2/name_changes/POST …/name_change/{username}/confirm/POST /api/user/v2/name_changes/{username}/confirmations/Declared differences a caller can see
Record bodies are unchanged:
INTENTIONAL_DIFFERENCESintest_account_parity.pyis six empty lists. Each item below names a test in the evidence comment.Every operation
type,title,status,detail,instance). A query parameter an operation does not read is refused with400. No operation acceptsBearerAuthentication.403at every operation, as at the v1 addresses these replace. Each view declares the refusal itself rather than relying on the JWT middleware.page_size=0, a negative value or a non-number is refused400underpage_size, where the v1 directory answers the default page. All sixPaginated*components list the seven envelope members as required, withnextandpreviousnullable.Accept(406), media type (415) or an unparsable body (400) keeps its status and detail. Itstypeandtitleare the ones the edx-drf-extensions catalog gives every standardized API, today…/errors/internal. Onlyuser/retired-accountanduser/ambiguous-account-nameare registered here.301).social_links[0].social_link, anddetailis written in words.{username}that the database matches to several accounts, none stored under exactly that name, is refused400user/ambiguous-account-name, with the message undererrors.username.Directory, preferences and time zones
users/,users/{username}/,user_preferences/anduser_preferences/{username},{key}/admit a request by the site's API key inX-Edx-Api-Keyand by nothing else, as the v1 directory addresses do. A session or token without the key is refused403. An anonymous request, or one with a different key, is refused401. Callers keep the credential they already use.usernameis read exactly as sent. A name with a leading space selects nothing, and a value of spaces alone returns an empty page.preference_key, andforum_rolewithcourse_key, replace the two v1 listings keyed by path.email,is_active,ordering,viewandfieldsare new capability that v1 never offered.time_zones/is paged (10 by default, 100 at most), where v1 returned all 433 zones in one array.country_codemust be two letters, andFRAis refused400where v1 ignored it. Spaces around a two-letter code are dropped. A code with no zones still returns every zone.Accounts and email search
/accounts/me/answers the whole account.?fields=usernamereproduces the body of v1/me.?email=or?lms_user_id=matches nothing, the answer is200with an empty page, where v1 answers404.username/emailselectors are read exactly as sent, as v1 reads them. Anemailselector with spaces around it is not a well-formed address and is refused400underemail, where v1 answers404. On a MySQL collation that ignores trailing spaces, v1 can match such a value while v2 refuses it.400here. One is a staff?email=value that is not an address (v1:404with no body). The other is a?view=value other thanminimal/shared(v1 ignores it and returns the whole account). Neither gets a different successful answer.PATCHreadsapplication/merge-patch+jsononly and answers415to anything else. The body is checked against the published serializer before it is applied. A change that could not be carried out answers500 internal./email_searches/. It names at most 100 addresses, and the answer is paged. A caller who is not staff is told there is nothing at the address (404), whether the account is active or not and whether it signs in by session or by token. A staff account that is not active is refused403.Deactivation, name change, profile image, verification
204with no body (v1 answers200with the account). An unknown username answers404.201 {"name": …}. The name is stored exactly as sent, and a name of spaces alone is refused as blank in both versions. For an account with no profile, the request and the confirmation answer404 not-found, where v1 ends in a 500 page.ValueError,IndexError,TypeErroror a struct error frompiexif), is refused400and nothing is stored. v1 answers each of these500.verification_status/for an account that has never been checked answers200 {"status": "none", …}, and404means only that no account holds the name.verifications/is paged and acceptsordering.POST /name_changes/keep the platform's default authentication, as the addresses they replace do. An account whose email address is unconfirmed is refused401by session and answered by token.Published documents
/lms-api/schema/is retitled from "LMS Enrollment API" to "LMS API". ItsSCHEMA_PATH_PREFIXwidens to/api/(enrollment|user), and it now carries the v2 user operations and the superseded v1 ones.maxItems: 100, nomaxLength: 255, untyped account properties. The bounds stay on the v2 components./api-docs/, the v1 name-change confirmation and imagePOSTnow publish204, the code their handlers answer, in place of200./api-docs/marks the 19 operations of these 17 addressesdeprecated: true. Studio serves them and has no/api/user/v2/. Nothing else in Studio's documents changes, and its Authoring API document is unchanged.ADRs applied
The evidence for each box is in the compliance matrix in the evidence comment.
APIViews, with the reason given in the docstringsinternaltype until edx-drf-extensions types them/api/user/v1/meis answered by the account member addresspage_sizeis refusedorderingare validated and published; unknown values are refusedJwtAuthenticationwithSessionAuthenticationAllowInactiveUseron the account and image views (the reason is a comment above each), and the platform default elsewhereuser_api/v2/andprofile_images/v2/packages; no v1 file changedFullScopePolicyon the queryset-backed directory and email search; the account service decides field visibilityIn-place edits
None of the superseded v1 views, serializers, URLconfs or tests is in the diff.
user_api/accounts/image_helpers.pyis byte-identical tomaster. Files outside a version directory:lms/urls.pyapi/user/v2/besideapi/user/lms/envs/common.pySCHEMA_PATH_PREFIXwidens to `/api/(enrollmentlms/envs/devstack.py,lms/envs/production.pylms/lib/spectacular.pyLmsAutoSchemauses the sharedSupersededUserOperationsmixin and tags user operationsuserlms/lib/tests/test_spectacular.pyLmsApiFilterTestdocstring reworded, because the hook no longer keeps enrollment endpoints onlycms/lib/spectacular.pySUPERSEDED_PATHScms/lib/tests/test_spectacular.pytest_both_spellings_of_each_superseded_path_are_listed, now compares only the/api/contentstore/entriesdocs/docs_settings.pysecuritySchemes)openedx/core/apidocs.pyopenedx/core/tests/test_apidocs.pyopenedx/core/djangoapps/user_api/schema.py(new)Error-format decision
Versioned. The envelope applies to
/api/user/v2/only. v1 bodies (empty,{"detail"},{developer_message, user_message}) are unchanged because existing clients read them.Deprecations
The 19 v1 operations above are marked
deprecated: truein the LMS documents and in Studio's/api-docs/. There is no response header and no note in code. This is tracked on #39128 (entries 6185917785 and 6359376146). The replacements are LMS-only, so a caller that uses these addresses on the Studio host has to move to the LMS.Deliberate deviations
ApiKeyHeaderPermission, whose docstring calls it deprecated, is the only admission on the four directory operations. It matches v1, so integrations move without a credential change. It also recordsdeprecated_api_key_headerfor monitoring.SupersededUserOperationsoverrides drf-spectacular 0.30's private_get_request_body, because the library marks a body required only when every media type requires it, and it has no public per-operation switch. The override affects onlyrequestBody.requiredon four/api/user/operations (three in Studio). Four schema tests fail if a release renames the method.UserApiPaginationrestates the page schema with all seven members until edx-drf-extensions publishes it (edx-drf-extensions#599).RecordingScopePolicy(a test double intest_views.py) and H3 WARN onUserApiPagination. Both are intended.Known pre-existing behaviour, left as it is
/api-docs/schema/is cached forOPENAPI_CACHE_TIMEOUTunder a key with no release component. After the deploy that ships this PR, the earlier document is served until the key expires. This ismaster's behaviour, and this PR does not touch it.POST /api/user/v2/accounts/{username}/profile_image/decodes the image twice: once in this view's check, and once inprofile_images/images.py, which is shared with v1.RecursionErroron a deeply nested body. v1 answers500for the same body.Evidence
Full tables are in the evidence comment: the compliance matrix, authorization mapping, gate output, and the test behind each declared item.
run_gates.sh, based178206575, MongoDB attached; run on a tree that differs from this head only by the C1803 line and by three lines of_get_request_bodyinuser_api/schema.py, see the evidence comment): versions PASS; urls PASS (3034 → 3048 routes, no URL name lost); schema 0 BREAKING (54 WARN, 37 INFO); hygiene 1 FAIL / 1 WARN (above); old-tests 1255 passed, 4 skipped; tests 943 passed.45b7d175d3; the suites ran on a commit with an identical tree), MongoDB attached:user_api/,profile_images/,user_authn/,lms/lib/tests/,lms/tests.py,openedx/core/tests/test_apidocs.py;-n 4): 2167 passed, 1 skipped, 0 failed.cms/lib/tests/,cms/tests.py,user_api/): 198 passed, 1277 skipped, 0 failed.origin/masterd2dbc6a593, conflict-free (wider targets, which adddjango_comment_common/,oauth_dispatch/,student/tests/anddjangolib/testing/tests/; the tree is this PR one step earlier, differing only by the C1803 line and the_get_request_bodyreorder): LMS 2912 passed, 8 skipped, 0 failed; Studio 370 passed, 1661 skipped, 0 failed. Every master test id is still collected./api-docs/: 261 against master's 266).Follow-ups
UserApiPaginationschema override.normalize_validation_errorsappliesstr()to nested validation detail. The platform's readable-error step goes once the library names nested items itself.openedx-platform-sdk.pytest -nwith load distribution. CI runs them serially, so CI is unaffected. The fix is a username per test, or a storage directory per test.