diff --git a/CHANGELOG b/CHANGELOG
new file mode 100644
--- /dev/null
+++ b/CHANGELOG
@@ -0,0 +1,2 @@
+0.3.4:
+  - initial version
diff --git a/LICENSE b/LICENSE
new file mode 100644
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,661 @@
+                    GNU AFFERO GENERAL PUBLIC LICENSE
+                       Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+  A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate.  Many developers of free software are heartened and
+encouraged by the resulting cooperation.  However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+  The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community.  It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server.  Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+  An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals.  This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU Affero General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Remote Network Interaction; Use with the GNU General Public License.
+
+  Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software.  This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time.  Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source.  For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code.  There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<https://www.gnu.org/licenses/>.
diff --git a/README.md b/README.md
new file mode 100644
--- /dev/null
+++ b/README.md
@@ -0,0 +1,33 @@
+# System for Cross-domain Identity Management (SCIM)
+
+This implements part of the [SCIM standard](http://www.simplecloud.info)
+for identity management. The parts that are currently supported are:
+
+ * User schema version 2.0
+
+## Building
+
+This project uses stack. You can install the sample executable with
+
+```sh
+stack install
+```
+
+## Developing and testing
+
+This library only implements the schemas and endpoints defined by the
+SCIM standard. You will need to implement the actual storage by giving
+an instance for the `Persistence` class.
+
+There's a simple in-memory implementation of this class, which is used
+for tests. You can run the tests with the standard stack interface:
+
+```sh
+stack test
+```
+
+# Contributing
+
+Before submitting a PR, make sure to install [ormolu](https://github.com/tweag/ormolu)
+by doing `stack install ormolu` (we pin the version in our `stack.yaml` file)
+and run `make format`.
diff --git a/Setup.hs b/Setup.hs
new file mode 100644
--- /dev/null
+++ b/Setup.hs
@@ -0,0 +1,20 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+import Distribution.Simple
+
+main = defaultMain
diff --git a/hscim.cabal b/hscim.cabal
new file mode 100644
--- /dev/null
+++ b/hscim.cabal
@@ -0,0 +1,217 @@
+cabal-version: 1.12
+
+-- This file has been generated from package.yaml by hpack version 0.34.2.
+--
+-- see: https://github.com/sol/hpack
+--
+-- hash: 83af2bccd0f2eb8ffc6a89254b3c8de7c938537ad70df57e11701e997242f1f7
+
+name:           hscim
+version:        0.3.4
+synopsis:       hscim json schema and server implementation
+description:    The README file will answer all the questions you might have
+category:       Web
+homepage:       https://github.com/wireapp/hscim/README.md
+bug-reports:    https://github.com/wireapp/hscim/issues
+author:         Wire Swiss GmbH
+maintainer:     Wire Swiss GmbH <backend@wire.com>
+copyright:      (c) 2021 Wire Swiss GmbH
+license:        AGPL-3
+license-file:   LICENSE
+build-type:     Simple
+extra-source-files:
+    README.md
+    CHANGELOG
+
+source-repository head
+  type: git
+  location: https://github.com/wireapp/hscim
+
+library
+  exposed-modules:
+      Web.Scim.AttrName
+      Web.Scim.Capabilities.MetaSchema
+      Web.Scim.Capabilities.MetaSchema.Group
+      Web.Scim.Capabilities.MetaSchema.ResourceType
+      Web.Scim.Capabilities.MetaSchema.Schema
+      Web.Scim.Capabilities.MetaSchema.SPConfig
+      Web.Scim.Capabilities.MetaSchema.User
+      Web.Scim.Class.Auth
+      Web.Scim.Class.Group
+      Web.Scim.Class.User
+      Web.Scim.ContentType
+      Web.Scim.Filter
+      Web.Scim.Handler
+      Web.Scim.Schema.AuthenticationScheme
+      Web.Scim.Schema.Common
+      Web.Scim.Schema.Error
+      Web.Scim.Schema.ListResponse
+      Web.Scim.Schema.Meta
+      Web.Scim.Schema.PatchOp
+      Web.Scim.Schema.ResourceType
+      Web.Scim.Schema.Schema
+      Web.Scim.Schema.User
+      Web.Scim.Schema.User.Address
+      Web.Scim.Schema.User.Certificate
+      Web.Scim.Schema.User.Email
+      Web.Scim.Schema.User.IM
+      Web.Scim.Schema.User.Name
+      Web.Scim.Schema.User.Phone
+      Web.Scim.Schema.User.Photo
+      Web.Scim.Schema.UserTypes
+      Web.Scim.Server
+      Web.Scim.Server.Mock
+      Web.Scim.Test.Acceptance
+      Web.Scim.Test.Util
+  other-modules:
+      Paths_hscim
+  hs-source-dirs:
+      src
+  default-extensions: ConstraintKinds DataKinds DeriveFunctor DeriveGeneric FlexibleContexts FlexibleInstances KindSignatures LambdaCase MultiParamTypeClasses OverloadedStrings RankNTypes ScopedTypeVariables TypeApplications TypeFamilies TypeOperators TypeSynonymInstances
+  ghc-options: -Wall
+  build-depends:
+      aeson >=1.4.5 && <1.5
+    , aeson-qq >=0.8.2 && <0.9
+    , attoparsec >=0.13.2 && <0.14
+    , base >=4.12 && <4.15
+    , bytestring >=0.10.8 && <0.11
+    , case-insensitive >=1.2.1.0 && <1.3
+    , email-validate >=2.3.2 && <2.4
+    , hashable >=1.2.7 && <1.4
+    , hedgehog >=1.0.1 && <1.1
+    , hspec >=2.7.1 && <2.8
+    , hspec-expectations >=0.8.2 && <0.9
+    , hspec-wai >=0.9.2 && <0.10
+    , http-api-data >=0.4.1 && <0.5
+    , http-media >=0.8.0 && <0.9
+    , http-types >=0.12.3 && <0.13
+    , hw-hspec-hedgehog >=0.1.0 && <0.2
+    , list-t >=1.0.4 && <1.1
+    , microlens >=0.4.10 && <0.5
+    , mmorph >=1.1.3 && <1.2
+    , mtl >=2.2.2 && <2.3
+    , network-uri >=2.6.2 && <2.7
+    , retry >=0.8.1.0 && <0.9
+    , scientific >=0.3.6 && <0.4
+    , servant >=0.16.2 && <0.19
+    , servant-server >=0.16.2 && <0.19
+    , stm >=2.5.0 && <2.6
+    , stm-containers >=1.1.0 && <1.2
+    , string-conversions >=0.4.0 && <0.5
+    , template-haskell >=2.14.0 && <2.17
+    , text >=1.2.3 && <1.3
+    , time >=1.8.0 && <1.10
+    , unordered-containers >=0.2.10 && <0.3
+    , uuid >=1.3.13 && <1.4
+    , wai >=3.2.2 && <3.3
+    , wai-extra >=3.0.28 && <3.1
+    , warp >=3.2.28 && <3.4
+  default-language: Haskell2010
+
+executable hscim-server
+  main-is: Main.hs
+  other-modules:
+      Paths_hscim
+  hs-source-dirs:
+      server
+  default-extensions: ConstraintKinds DataKinds DeriveFunctor DeriveGeneric FlexibleContexts FlexibleInstances KindSignatures LambdaCase MultiParamTypeClasses OverloadedStrings RankNTypes ScopedTypeVariables TypeApplications TypeFamilies TypeOperators TypeSynonymInstances
+  ghc-options: -Wall -threaded -rtsopts -with-rtsopts=-N
+  build-depends:
+      aeson >=1.4.5 && <1.5
+    , aeson-qq >=0.8.2 && <0.9
+    , attoparsec >=0.13.2 && <0.14
+    , base >=4.12 && <4.15
+    , bytestring >=0.10.8 && <0.11
+    , case-insensitive >=1.2.1.0 && <1.3
+    , email-validate >=2.3.2 && <2.4
+    , hashable >=1.2.7 && <1.4
+    , hedgehog >=1.0.1 && <1.1
+    , hscim
+    , hspec >=2.7.1 && <2.8
+    , hspec-expectations >=0.8.2 && <0.9
+    , hspec-wai >=0.9.2 && <0.10
+    , http-api-data >=0.4.1 && <0.5
+    , http-media >=0.8.0 && <0.9
+    , http-types >=0.12.3 && <0.13
+    , hw-hspec-hedgehog >=0.1.0 && <0.2
+    , list-t >=1.0.4 && <1.1
+    , microlens >=0.4.10 && <0.5
+    , mmorph >=1.1.3 && <1.2
+    , mtl >=2.2.2 && <2.3
+    , network-uri >=2.6.2 && <2.7
+    , retry >=0.8.1.0 && <0.9
+    , scientific >=0.3.6 && <0.4
+    , servant >=0.16.2 && <0.19
+    , servant-server >=0.16.2 && <0.19
+    , stm >=2.5.0 && <2.6
+    , stm-containers >=1.1.0 && <1.2
+    , string-conversions >=0.4.0 && <0.5
+    , template-haskell >=2.14.0 && <2.17
+    , text >=1.2.3 && <1.3
+    , time >=1.8.0 && <1.10
+    , unordered-containers >=0.2.10 && <0.3
+    , uuid >=1.3.13 && <1.4
+    , wai >=3.2.2 && <3.3
+    , wai-extra >=3.0.28 && <3.1
+    , warp >=3.2.28 && <3.4
+  default-language: Haskell2010
+
+test-suite spec
+  type: exitcode-stdio-1.0
+  main-is: Spec.hs
+  other-modules:
+      Test.AcceptanceSpec
+      Test.Capabilities.MetaSchemaSpec
+      Test.Class.AuthSpec
+      Test.Class.GroupSpec
+      Test.Class.UserSpec
+      Test.FilterSpec
+      Test.MiscSpec
+      Test.Schema.PatchOpSpec
+      Test.Schema.UserSpec
+      Paths_hscim
+  hs-source-dirs:
+      test
+  default-extensions: ConstraintKinds DataKinds DeriveFunctor DeriveGeneric FlexibleContexts FlexibleInstances KindSignatures LambdaCase MultiParamTypeClasses OverloadedStrings RankNTypes ScopedTypeVariables TypeApplications TypeFamilies TypeOperators TypeSynonymInstances
+  ghc-options: -Wall -threaded -rtsopts -with-rtsopts=-N
+  build-tool-depends:
+      hspec-discover:hspec-discover
+  build-depends:
+      aeson >=1.4.5 && <1.5
+    , aeson-qq >=0.8.2 && <0.9
+    , attoparsec >=0.13.2 && <0.14
+    , base >=4.12 && <4.15
+    , bytestring >=0.10.8 && <0.11
+    , case-insensitive >=1.2.1.0 && <1.3
+    , email-validate >=2.3.2 && <2.4
+    , hashable >=1.2.7 && <1.4
+    , hedgehog >=1.0.1 && <1.1
+    , hscim
+    , hspec >=2.7.1 && <2.8
+    , hspec-expectations >=0.8.2 && <0.9
+    , hspec-wai >=0.9.2 && <0.10
+    , http-api-data >=0.4.1 && <0.5
+    , http-media >=0.8.0 && <0.9
+    , http-types >=0.12.3 && <0.13
+    , hw-hspec-hedgehog >=0.1.0 && <0.2
+    , list-t >=1.0.4 && <1.1
+    , microlens >=0.4.10 && <0.5
+    , mmorph >=1.1.3 && <1.2
+    , mtl >=2.2.2 && <2.3
+    , network-uri >=2.6.2 && <2.7
+    , retry >=0.8.1.0 && <0.9
+    , scientific >=0.3.6 && <0.4
+    , servant >=0.16.2 && <0.19
+    , servant-server >=0.16.2 && <0.19
+    , stm >=2.5.0 && <2.6
+    , stm-containers >=1.1.0 && <1.2
+    , string-conversions >=0.4.0 && <0.5
+    , template-haskell >=2.14.0 && <2.17
+    , text >=1.2.3 && <1.3
+    , time >=1.8.0 && <1.10
+    , unordered-containers >=0.2.10 && <0.3
+    , uuid >=1.3.13 && <1.4
+    , wai >=3.2.2 && <3.3
+    , wai-extra >=3.0.28 && <3.1
+    , warp >=3.2.28 && <3.4
+  default-language: Haskell2010
diff --git a/server/Main.hs b/server/Main.hs
new file mode 100644
--- /dev/null
+++ b/server/Main.hs
@@ -0,0 +1,91 @@
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Main where
+
+import Control.Monad.STM (atomically)
+import Data.Time
+import Network.URI.Static
+import Network.Wai.Handler.Warp
+import qualified StmContainers.Map as STMMap
+import Text.Email.Validate
+import Web.Scim.Capabilities.MetaSchema as MetaSchema
+import Web.Scim.Schema.Common as Common
+import Web.Scim.Schema.Meta hiding (meta)
+import Web.Scim.Schema.ResourceType hiding (name)
+import Web.Scim.Schema.Schema (Schema (User20))
+import Web.Scim.Schema.User as User
+import Web.Scim.Schema.User.Email as E
+import Web.Scim.Schema.User.Name
+import Web.Scim.Server
+import Web.Scim.Server.Mock
+
+main :: IO ()
+main = do
+  storage <- TestStorage <$> mkUserDB <*> STMMap.newIO
+  run 9000 (app @Mock MetaSchema.empty (nt storage))
+
+-- | Create a UserDB with a single user:
+--
+-- @
+-- UserID: sample-user
+-- @
+mkUserDB :: IO UserStorage
+mkUserDB = do
+  db <- STMMap.newIO
+  now <- getCurrentTime
+  let meta =
+        Meta
+          { resourceType = UserResource,
+            created = now,
+            lastModified = now,
+            version = Weak "0", -- we don't support etags
+            location = Common.URI [relativeReference|/Users/sample-user|]
+          }
+  -- Note: Okta required at least one email, 'active', 'name.familyName',
+  -- and 'name.givenName'. We might want to be able to express these
+  -- constraints in code (and in the schema we serve) without turning this
+  -- library into something that is Okta-specific.
+  let email =
+        Email
+          { E.typ = Just "work",
+            E.value =
+              maybe
+                (error "couldn't parse email")
+                EmailAddress2
+                (emailAddress "elton@wire.com"),
+            E.primary = Nothing
+          }
+  let user =
+        (User.empty [User20] "elton" NoUserExtra)
+          { name =
+              Just
+                Name
+                  { formatted = Just "Elton John",
+                    familyName = Just "John",
+                    givenName = Just "Elton",
+                    middleName = Nothing,
+                    honorificPrefix = Nothing,
+                    honorificSuffix = Nothing
+                  },
+            active = Just (ScimBool True),
+            emails = [email]
+          }
+  atomically $ STMMap.insert (WithMeta meta (WithId (Id 0) user)) (Id 0) db
+  pure db
diff --git a/src/Web/Scim/AttrName.hs b/src/Web/Scim/AttrName.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/AttrName.hs
@@ -0,0 +1,61 @@
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+-- | Scim attribute names. these are case-insensitive
+module Web.Scim.AttrName where
+
+import Data.Aeson.Types (FromJSONKey, ToJSONKey)
+import Data.Attoparsec.ByteString.Char8
+import Data.Hashable
+import Data.String (IsString, fromString)
+import Data.Text (Text, cons, toCaseFold)
+import Data.Text.Encoding (decodeUtf8)
+import Prelude hiding (takeWhile)
+
+-- | An attribute (e.g. username).
+--
+-- ATTRNAME  = ALPHA *(nameChar)
+-- NOTE: We use the FromJSONKey instance of Text. The default instances parses
+-- a list of key values instead of a map
+newtype AttrName
+  = AttrName Text
+  deriving (Show, FromJSONKey, ToJSONKey)
+
+instance Eq AttrName where
+  AttrName a == AttrName b = toCaseFold a == toCaseFold b
+
+instance Ord AttrName where
+  compare (AttrName a) (AttrName b) = compare (toCaseFold a) (toCaseFold b)
+
+instance Hashable AttrName where
+  hashWithSalt x (AttrName a) = hashWithSalt x (toCaseFold a)
+
+instance IsString AttrName where
+  fromString = AttrName . fromString
+
+-- | Attribute name parser.
+pAttrName :: Parser AttrName
+pAttrName =
+  (\c str -> AttrName (cons c (decodeUtf8 str)))
+    <$> letter_ascii
+    <*> takeWhile (\x -> isDigit x || isAlpha_ascii x || x == '-' || x == '_')
+
+-- | Attribute name renderer.
+rAttrName :: AttrName -> Text
+rAttrName (AttrName x) = x
diff --git a/src/Web/Scim/Capabilities/MetaSchema.hs b/src/Web/Scim/Capabilities/MetaSchema.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Capabilities/MetaSchema.hs
@@ -0,0 +1,147 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Capabilities.MetaSchema
+  ( ConfigSite,
+    configServer,
+    Supported (..),
+    BulkConfig (..),
+    FilterConfig (..),
+    Configuration (..),
+    empty,
+  )
+where
+
+import Data.Aeson
+import qualified Data.HashMap.Lazy as HML
+import Data.Text (Text)
+import Servant hiding (URI)
+import Servant.API.Generic
+import Servant.Server.Generic
+import Web.Scim.Capabilities.MetaSchema.Group
+import Web.Scim.Capabilities.MetaSchema.ResourceType
+import Web.Scim.Capabilities.MetaSchema.SPConfig
+import Web.Scim.Capabilities.MetaSchema.Schema
+import Web.Scim.Capabilities.MetaSchema.User
+import Web.Scim.ContentType
+import Web.Scim.Handler
+import Web.Scim.Schema.AuthenticationScheme
+import Web.Scim.Schema.Common
+import Web.Scim.Schema.Error hiding (schemas)
+import Web.Scim.Schema.ListResponse as ListResponse hiding (schemas)
+import Web.Scim.Schema.ResourceType hiding (schema)
+import Web.Scim.Schema.Schema
+import Prelude hiding (filter)
+
+data Supported a = Supported
+  { supported :: ScimBool,
+    subConfig :: a
+  }
+  deriving (Show, Eq, Generic)
+
+instance ToJSON a => ToJSON (Supported a) where
+  toJSON (Supported (ScimBool b) v) = case toJSON v of
+    (Object o) -> Object $ HML.insert "supported" (Bool b) o
+    _ -> Object $ HML.fromList [("supported", Bool b)]
+
+data BulkConfig = BulkConfig
+  { maxOperations :: Int,
+    maxPayloadSize :: Int
+  }
+  deriving (Show, Eq, Generic)
+
+instance ToJSON BulkConfig where
+  toJSON = genericToJSON serializeOptions
+
+data FilterConfig = FilterConfig
+  { maxResults :: Int
+  }
+  deriving (Show, Eq, Generic)
+
+instance ToJSON FilterConfig where
+  toJSON = genericToJSON serializeOptions
+
+data Configuration = Configuration
+  { documentationUri :: Maybe URI,
+    schemas :: [Schema],
+    patch :: Supported (),
+    bulk :: Supported BulkConfig,
+    filter :: Supported FilterConfig,
+    changePassword :: Supported (),
+    sort :: Supported (),
+    etag :: Supported (),
+    authenticationSchemes :: [AuthenticationSchemeEncoding]
+  }
+  deriving (Show, Eq, Generic)
+
+instance ToJSON Configuration where
+  toJSON = genericToJSON serializeOptions
+
+empty :: Configuration
+empty =
+  Configuration
+    { documentationUri = Nothing,
+      schemas =
+        [ User20,
+          ServiceProviderConfig20,
+          Group20,
+          Schema20,
+          ResourceType20
+        ],
+      patch = Supported (ScimBool True) (),
+      bulk = Supported (ScimBool False) $ BulkConfig 0 0,
+      filter = Supported (ScimBool False) $ FilterConfig 0,
+      changePassword = Supported (ScimBool False) (),
+      sort = Supported (ScimBool False) (),
+      etag = Supported (ScimBool False) (),
+      authenticationSchemes = [authHttpBasicEncoding]
+    }
+
+configServer ::
+  Monad m =>
+  Configuration ->
+  ConfigSite (AsServerT (ScimHandler m))
+configServer config =
+  ConfigSite
+    { spConfig = pure config,
+      getSchemas =
+        pure $
+          ListResponse.fromList
+            [ userSchema,
+              spConfigSchema,
+              groupSchema,
+              metaSchema,
+              resourceSchema
+            ],
+      schema = \uri -> case getSchema (fromSchemaUri uri) of
+        Nothing -> throwScim (notFound "Schema" uri)
+        Just s -> pure s,
+      resourceTypes =
+        pure $
+          ListResponse.fromList
+            [ usersResource,
+              groupsResource
+            ]
+    }
+
+data ConfigSite route = ConfigSite
+  { spConfig :: route :- "ServiceProviderConfig" :> Get '[SCIM] Configuration,
+    getSchemas :: route :- "Schemas" :> Get '[SCIM] (ListResponse Value),
+    schema :: route :- "Schemas" :> Capture "id" Text :> Get '[SCIM] Value,
+    resourceTypes :: route :- "ResourceTypes" :> Get '[SCIM] (ListResponse Resource)
+  }
+  deriving (Generic)
diff --git a/src/Web/Scim/Capabilities/MetaSchema/Group.hs b/src/Web/Scim/Capabilities/MetaSchema/Group.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Capabilities/MetaSchema/Group.hs
@@ -0,0 +1,109 @@
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Capabilities.MetaSchema.Group
+  ( groupSchema,
+  )
+where
+
+import Data.Aeson (Value)
+import Data.Aeson.QQ
+
+-- NB: errata for the SCIM RFC says that 'displayName' should have
+-- 'required: true'. This makes sense but we're not going to change this for
+-- now because nobody seems to care about these schemas anyway.
+-- See https://www.rfc-editor.org/errata_search.php?rfc=7643
+groupSchema :: Value
+groupSchema =
+  [aesonQQ|
+{
+  "id": "urn:ietf:params:scim:schemas:core:2.0:Group",
+  "name": "Group",
+  "description": "Group",
+  "attributes": [
+    {
+      "name": "displayName",
+      "type": "string",
+      "multiValued": false,
+      "description": "A human-readable name for the Group. REQUIRED.",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "members",
+      "type": "complex",
+      "multiValued": true,
+      "description": "A list of members of the Group.",
+      "required": false,
+      "subAttributes": [
+        {
+          "name": "value",
+          "type": "string",
+          "multiValued": false,
+          "description": "Identifier of the member of this Group.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "immutable",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "$ref",
+          "type": "reference",
+          "referenceTypes": [
+            "User",
+            "Group"
+          ],
+          "multiValued": false,
+          "description": "The URI corresponding to a SCIM resource that is a member of this Group.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "immutable",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "type",
+          "type": "string",
+          "multiValued": false,
+          "description": "A label indicating the type of resource, e.g., 'User' or 'Group'.",
+          "required": false,
+          "caseExact": false,
+          "canonicalValues": [
+            "User",
+            "Group"
+          ],
+          "mutability": "immutable",
+          "returned": "default",
+          "uniqueness": "none"
+        }
+      ],
+      "mutability": "readWrite",
+      "returned": "default"
+    }
+  ],
+  "meta": {
+    "resourceType": "Schema",
+    "location": "/v2/Schemas/urn:ietf:params:scim:schemas:core:2.0:Group"
+  }
+}
+|]
diff --git a/src/Web/Scim/Capabilities/MetaSchema/ResourceType.hs b/src/Web/Scim/Capabilities/MetaSchema/ResourceType.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Capabilities/MetaSchema/ResourceType.hs
@@ -0,0 +1,133 @@
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Capabilities.MetaSchema.ResourceType
+  ( resourceSchema,
+  )
+where
+
+import Data.Aeson (Value)
+import Data.Aeson.QQ
+
+resourceSchema :: Value
+resourceSchema =
+  [aesonQQ|
+{
+  "id": "urn:ietf:params:scim:schemas:core:2.0:ResourceType",
+  "name": "ResourceType",
+  "description": "Specifies the schema that describes a SCIM resource type",
+  "attributes": [
+    {
+      "name": "id",
+      "type": "string",
+      "multiValued": false,
+      "description": "The resource type's server unique id. May be the same as the 'name' attribute.",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readOnly",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "name",
+      "type": "string",
+      "multiValued": false,
+      "description": "The resource type name.  When applicable, service providers MUST specify the name, e.g., 'User'.",
+      "required": true,
+      "caseExact": false,
+      "mutability": "readOnly",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "description",
+      "type": "string",
+      "multiValued": false,
+      "description": "The resource type's human-readable description.  When applicable, service providers MUST specify the description.",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readOnly",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "endpoint",
+      "type": "reference",
+      "referenceTypes": [
+        "uri"
+      ],
+      "multiValued": false,
+      "description": "The resource type's HTTP-addressable endpoint relative to the Base URL, e.g., '\/Users'.",
+      "required": true,
+      "caseExact": false,
+      "mutability": "readOnly",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "schema",
+      "type": "reference",
+      "referenceTypes": [
+        "uri"
+      ],
+      "multiValued": false,
+      "description": "The resource type's primary\/base schema URI.",
+      "required": true,
+      "caseExact": true,
+      "mutability": "readOnly",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "schemaExtensions",
+      "type": "complex",
+      "multiValued": false,
+      "description": "A list of URIs of the resource type's schema extensions.",
+      "required": true,
+      "mutability": "readOnly",
+      "returned": "default",
+      "subAttributes": [
+        {
+          "name": "schema",
+          "type": "reference",
+          "referenceTypes": [
+            "uri"
+          ],
+          "multiValued": false,
+          "description": "The URI of a schema extension.",
+          "required": true,
+          "caseExact": true,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "required",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value that specifies whether or not the schema extension is required for the resource type.  If true, a resource of this type MUST include this schema extension and also include any attributes declared as required in this schema extension. If false, a resource of this type MAY omit this schema extension.",
+          "required": true,
+          "mutability": "readOnly",
+          "returned": "default"
+        }
+      ]
+    }
+  ]
+}
+|]
diff --git a/src/Web/Scim/Capabilities/MetaSchema/SPConfig.hs b/src/Web/Scim/Capabilities/MetaSchema/SPConfig.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Capabilities/MetaSchema/SPConfig.hs
@@ -0,0 +1,245 @@
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Capabilities.MetaSchema.SPConfig
+  ( spConfigSchema,
+  )
+where
+
+import Data.Aeson (Value)
+import Data.Aeson.QQ
+
+-- NB: it looks like 'authenticationSchemes' should also have a 'type'
+-- attribute. The sample schema from the RFC doesn't list it, though.
+spConfigSchema :: Value
+spConfigSchema =
+  [aesonQQ|
+{
+  "id": "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig",
+  "name": "Service Provider Configuration",
+  "description": "Schema for representing the service provider's configuration",
+  "attributes": [
+    {
+      "name": "documentationUri",
+      "type": "reference",
+      "referenceTypes": [
+        "external"
+      ],
+      "multiValued": false,
+      "description": "An HTTP-addressable URL pointing to the service provider's human-consumable help documentation.",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readOnly",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "patch",
+      "type": "complex",
+      "multiValued": false,
+      "description": "A complex type that specifies PATCH configuration options.",
+      "required": true,
+      "returned": "default",
+      "mutability": "readOnly",
+      "subAttributes": [
+        {
+          "name": "supported",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value specifying whether or not the operation is supported.",
+          "required": true,
+          "mutability": "readOnly",
+          "returned": "default"
+        }
+      ]
+    },
+    {
+      "name": "bulk",
+      "type": "complex",
+      "multiValued": false,
+      "description": "A complex type that specifies bulk configuration options.",
+      "required": true,
+      "returned": "default",
+      "mutability": "readOnly",
+      "subAttributes": [
+        {
+          "name": "supported",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value specifying whether or not the operation is supported.",
+          "required": true,
+          "mutability": "readOnly",
+          "returned": "default"
+        },
+        {
+          "name": "maxOperations",
+          "type": "integer",
+          "multiValued": false,
+          "description": "An integer value specifying the maximum number of operations.",
+          "required": true,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "maxPayloadSize",
+          "type": "integer",
+          "multiValued": false,
+          "description": "An integer value specifying the maximum payload size in bytes.",
+          "required": true,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        }
+      ]
+    },
+    {
+      "name": "filter",
+      "type": "complex",
+      "multiValued": false,
+      "description": "A complex type that specifies FILTER options.",
+      "required": true,
+      "returned": "default",
+      "mutability": "readOnly",
+      "subAttributes": [
+        {
+          "name": "supported",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value specifying whether or not the operation is supported.",
+          "required": true,
+          "mutability": "readOnly",
+          "returned": "default"
+        },
+        {
+          "name": "maxResults",
+          "type": "integer",
+          "multiValued": false,
+          "description": "An integer value specifying the maximum number of resources returned in a response.",
+          "required": true,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        }
+      ]
+    },
+    {
+      "name": "changePassword",
+      "type": "complex",
+      "multiValued": false,
+      "description": "A complex type that specifies configuration options related to changing a password.",
+      "required": true,
+      "returned": "default",
+      "mutability": "readOnly",
+      "subAttributes": [
+        {
+          "name": "supported",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value specifying whether or not the operation is supported.",
+          "required": true,
+          "mutability": "readOnly",
+          "returned": "default"
+        }
+      ]
+    },
+    {
+      "name": "sort",
+      "type": "complex",
+      "multiValued": false,
+      "description": "A complex type that specifies sort result options.",
+      "required": true,
+      "returned": "default",
+      "mutability": "readOnly",
+      "subAttributes": [
+        {
+          "name": "supported",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value specifying whether or not the operation is supported.",
+          "required": true,
+          "mutability": "readOnly",
+          "returned": "default"
+        }
+      ]
+    },
+    {
+      "name": "authenticationSchemes",
+      "type": "complex",
+      "multiValued": true,
+      "description": "A complex type that specifies supported authentication scheme properties.",
+      "required": true,
+      "returned": "default",
+      "mutability": "readOnly",
+      "subAttributes": [
+        {
+          "name": "name",
+          "type": "string",
+          "multiValued": false,
+          "description": "The common authentication scheme name, e.g., HTTP Basic.",
+          "required": true,
+          "caseExact": false,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "description",
+          "type": "string",
+          "multiValued": false,
+          "description": "A description of the authentication scheme.",
+          "required": true,
+          "caseExact": false,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "specUri",
+          "type": "reference",
+          "referenceTypes": [
+            "external"
+          ],
+          "multiValued": false,
+          "description": "An HTTP-addressable URL pointing to the authentication scheme's specification.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "documentationUri",
+          "type": "reference",
+          "referenceTypes": [
+            "external"
+          ],
+          "multiValued": false,
+          "description": "An HTTP-addressable URL pointing to the authentication scheme's usage documentation.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        }
+      ]
+    }
+  ]
+}
+|]
diff --git a/src/Web/Scim/Capabilities/MetaSchema/Schema.hs b/src/Web/Scim/Capabilities/MetaSchema/Schema.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Capabilities/MetaSchema/Schema.hs
@@ -0,0 +1,375 @@
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Capabilities.MetaSchema.Schema
+  ( metaSchema,
+  )
+where
+
+import Data.Aeson (Value)
+import Data.Aeson.QQ
+
+metaSchema :: Value
+metaSchema =
+  [aesonQQ|
+{
+  "id": "urn:ietf:params:scim:schemas:core:2.0:Schema",
+  "name": "Schema",
+  "description": "Specifies the schema that describes a SCIM schema",
+  "attributes": [
+    {
+      "name": "id",
+      "type": "string",
+      "multiValued": false,
+      "description": "The unique URI of the schema. When applicable, service providers MUST specify the URI.",
+      "required": true,
+      "caseExact": false,
+      "mutability": "readOnly",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "name",
+      "type": "string",
+      "multiValued": false,
+      "description": "The schema's human-readable name. When applicable, service providers MUST specify the name, e.g., 'User'.",
+      "required": true,
+      "caseExact": false,
+      "mutability": "readOnly",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "description",
+      "type": "string",
+      "multiValued": false,
+      "description": "The schema's human-readable name.  When applicable, service providers MUST specify the name, e.g., 'User'.",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readOnly",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "attributes",
+      "type": "complex",
+      "multiValued": true,
+      "description": "A complex attribute that includes the attributes of a schema.",
+      "required": true,
+      "mutability": "readOnly",
+      "returned": "default",
+      "subAttributes": [
+        {
+          "name": "name",
+          "type": "string",
+          "multiValued": false,
+          "description": "The attribute's name.",
+          "required": true,
+          "caseExact": true,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "type",
+          "type": "string",
+          "multiValued": false,
+          "description": "The attribute's data type. Valid values include 'string', 'complex', 'boolean', 'decimal', 'integer', 'dateTime', 'reference'.",
+          "required": true,
+          "canonicalValues": [
+            "string",
+            "complex",
+            "boolean",
+            "decimal",
+            "integer",
+            "dateTime",
+            "reference"
+          ],
+          "caseExact": false,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "multiValued",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value indicating an attribute's plurality.",
+          "required": true,
+          "mutability": "readOnly",
+          "returned": "default"
+        },
+        {
+          "name": "description",
+          "type": "string",
+          "multiValued": false,
+          "description": "A human-readable description of the attribute.",
+          "required": false,
+          "caseExact": true,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "required",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A boolean value indicating whether or not the attribute is required.",
+          "required": false,
+          "mutability": "readOnly",
+          "returned": "default"
+        },
+        {
+          "name": "canonicalValues",
+          "type": "string",
+          "multiValued": true,
+          "description": "A collection of canonical values.  When applicable, service providers MUST specify the canonical types, e.g., 'work', 'home'.",
+          "required": false,
+          "caseExact": true,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "caseExact",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value indicating whether or not a string attribute is case sensitive.",
+          "required": false,
+          "mutability": "readOnly",
+          "returned": "default"
+        },
+        {
+          "name": "mutability",
+          "type": "string",
+          "multiValued": false,
+          "description": "Indicates whether or not an attribute is modifiable.",
+          "required": false,
+          "caseExact": true,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none",
+          "canonicalValues": [
+            "readOnly",
+            "readWrite",
+            "immutable",
+            "writeOnly"
+          ]
+        },
+        {
+          "name": "returned",
+          "type": "string",
+          "multiValued": false,
+          "description": "Indicates when an attribute is returned in a response (e.g., to a query).",
+          "required": false,
+          "caseExact": true,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none",
+          "canonicalValues": [
+            "always",
+            "never",
+            "default",
+            "request"
+          ]
+        },
+        {
+          "name": "uniqueness",
+          "type": "string",
+          "multiValued": false,
+          "description": "Indicates how unique a value must be.",
+          "required": false,
+          "caseExact": true,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none",
+          "canonicalValues": [
+            "none",
+            "server",
+            "global"
+          ]
+        },
+        {
+          "name": "referenceTypes",
+          "type": "string",
+          "multiValued": true,
+          "description": "Used only with an attribute of type 'reference'.  Specifies a SCIM resourceType that a reference attribute MAY refer to, e.g., 'User'.",
+          "required": false,
+          "caseExact": true,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "subAttributes",
+          "type": "complex",
+          "multiValued": true,
+          "description": "Used to define the sub-attributes of a complex attribute.",
+          "required": false,
+          "mutability": "readOnly",
+          "returned": "default",
+          "subAttributes": [
+            {
+              "name": "name",
+              "type": "string",
+              "multiValued": false,
+              "description": "The attribute's name.",
+              "required": true,
+              "caseExact": true,
+              "mutability": "readOnly",
+              "returned": "default",
+              "uniqueness": "none"
+            },
+            {
+              "name": "type",
+              "type": "string",
+              "multiValued": false,
+              "description": "The attribute's data type. Valid values include 'string', 'complex', 'boolean', 'decimal', 'integer', 'dateTime', 'reference'.",
+              "required": true,
+              "caseExact": false,
+              "mutability": "readOnly",
+              "returned": "default",
+              "uniqueness": "none",
+              "canonicalValues": [
+                "string",
+                "complex",
+                "boolean",
+                "decimal",
+                "integer",
+                "dateTime",
+                "reference"
+              ]
+            },
+            {
+              "name": "multiValued",
+              "type": "boolean",
+              "multiValued": false,
+              "description": "A Boolean value indicating an attribute's plurality.",
+              "required": true,
+              "mutability": "readOnly",
+              "returned": "default"
+            },
+            {
+              "name": "description",
+              "type": "string",
+              "multiValued": false,
+              "description": "A human-readable description of the attribute.",
+              "required": false,
+              "caseExact": true,
+              "mutability": "readOnly",
+              "returned": "default",
+              "uniqueness": "none"
+            },
+            {
+              "name": "required",
+              "type": "boolean",
+              "multiValued": false,
+              "description": "A boolean value indicating whether or not the attribute is required.",
+              "required": false,
+              "mutability": "readOnly",
+              "returned": "default"
+            },
+            {
+              "name": "canonicalValues",
+              "type": "string",
+              "multiValued": true,
+              "description": "A collection of canonical values.  When applicable, service providers MUST specify the canonical types, e.g., 'work', 'home'.",
+              "required": false,
+              "caseExact": true,
+              "mutability": "readOnly",
+              "returned": "default",
+              "uniqueness": "none"
+            },
+            {
+              "name": "caseExact",
+              "type": "boolean",
+              "multiValued": false,
+              "description": "A Boolean value indicating whether or not a string attribute is case sensitive.",
+              "required": false,
+              "mutability": "readOnly",
+              "returned": "default"
+            },
+            {
+              "name": "mutability",
+              "type": "string",
+              "multiValued": false,
+              "description": "Indicates whether or not an attribute is modifiable.",
+              "required": false,
+              "caseExact": true,
+              "mutability": "readOnly",
+              "returned": "default",
+              "uniqueness": "none",
+              "canonicalValues": [
+                "readOnly",
+                "readWrite",
+                "immutable",
+                "writeOnly"
+              ]
+            },
+            {
+              "name": "returned",
+              "type": "string",
+              "multiValued": false,
+              "description": "Indicates when an attribute is returned in a response (e.g., to a query).",
+              "required": false,
+              "caseExact": true,
+              "mutability": "readOnly",
+              "returned": "default",
+              "uniqueness": "none",
+              "canonicalValues": [
+                "always",
+                "never",
+                "default",
+                "request"
+              ]
+            },
+            {
+              "name": "uniqueness",
+              "type": "string",
+              "multiValued": false,
+              "description": "Indicates how unique a value must be.",
+              "required": false,
+              "caseExact": true,
+              "mutability": "readOnly",
+              "returned": "default",
+              "uniqueness": "none",
+              "canonicalValues": [
+                "none",
+                "server",
+                "global"
+              ]
+            },
+            {
+              "name": "referenceTypes",
+              "type": "string",
+              "multiValued": false,
+              "description": "Used only with an attribute of type 'reference'.  Specifies a SCIM resourceType that a reference attribute MAY refer to, e.g., 'User'.",
+              "required": false,
+              "caseExact": true,
+              "mutability": "readOnly",
+              "returned": "default",
+              "uniqueness": "none"
+            }
+          ]
+        }
+      ]
+    }
+  ]
+}
+|]
diff --git a/src/Web/Scim/Capabilities/MetaSchema/User.hs b/src/Web/Scim/Capabilities/MetaSchema/User.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Capabilities/MetaSchema/User.hs
@@ -0,0 +1,806 @@
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Capabilities.MetaSchema.User
+  ( userSchema,
+  )
+where
+
+import Data.Aeson (Value)
+import Data.Aeson.QQ
+
+userSchema :: Value
+userSchema =
+  [aesonQQ|
+{
+  "id": "urn:ietf:params:scim:schemas:core:2.0:User",
+  "name": "User",
+  "description": "User Account",
+  "attributes": [
+    {
+      "name": "userName",
+      "type": "string",
+      "multiValued": false,
+      "description": "Unique identifier for the User, typically used by the user to directly authenticate to the service provider. Each User MUST include a non-empty userName value.  This identifier MUST be unique across the service provider's entire set of Users. REQUIRED.",
+      "required": true,
+      "caseExact": false,
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "server"
+    },
+    {
+      "name": "name",
+      "type": "complex",
+      "multiValued": false,
+      "description": "The components of the user's real name. Providers MAY return just the full name as a single string in the formatted sub-attribute, or they MAY return just the individual component attributes using the other sub-attributes, or they MAY return both.  If both variants are returned, they SHOULD be describing the same name, with the formatted name indicating how the component attributes should be combined.",
+      "required": false,
+      "subAttributes": [
+        {
+          "name": "formatted",
+          "type": "string",
+          "multiValued": false,
+          "description": "The full name, including all middle names, titles, and suffixes as appropriate, formatted for display (e.g., 'Ms. Barbara J Jensen, III').",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "familyName",
+          "type": "string",
+          "multiValued": false,
+          "description": "The family name of the User, or last name in most Western languages (e.g., 'Jensen' given the full name 'Ms. Barbara J Jensen, III').",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "givenName",
+          "type": "string",
+          "multiValued": false,
+          "description": "The given name of the User, or first name in most Western languages (e.g., 'Barbara' given the full name 'Ms. Barbara J Jensen, III').",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "middleName",
+          "type": "string",
+          "multiValued": false,
+          "description": "The middle name(s) of the User (e.g., 'Jane' given the full name 'Ms. Barbara J Jensen, III').",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "honorificPrefix",
+          "type": "string",
+          "multiValued": false,
+          "description": "The honorific prefix(es) of the User, or title in most Western languages (e.g., 'Ms.' given the full name 'Ms. Barbara J Jensen, III').",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "honorificSuffix",
+          "type": "string",
+          "multiValued": false,
+          "description": "The honorific suffix(es) of the User, or suffix in most Western languages (e.g., 'III' given the full name 'Ms. Barbara J Jensen, III').",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        }
+      ],
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "displayName",
+      "type": "string",
+      "multiValued": false,
+      "description": "The name of the User, suitable for display to end-users.  The name SHOULD be the full name of the User being described, if known.",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "nickName",
+      "type": "string",
+      "multiValued": false,
+      "description": "The casual way to address the user in real life, e.g., 'Bob' or 'Bobby' instead of 'Robert'.  This attribute SHOULD NOT be used to represent a User's username (e.g., 'bjensen' or 'mpepperidge').",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "profileUrl",
+      "type": "reference",
+      "referenceTypes": [
+        "external"
+      ],
+      "multiValued": false,
+      "description": "A fully qualified URL pointing to a page representing the User's online profile.",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "title",
+      "type": "string",
+      "multiValued": false,
+      "description": "The user's title, such as \"Vice President.\"",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "userType",
+      "type": "string",
+      "multiValued": false,
+      "description": "Used to identify the relationship between the organization and the user.  Typical values used might be 'Contractor', 'Employee', 'Intern', 'Temp', 'External', and 'Unknown', but any value may be used.",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "preferredLanguage",
+      "type": "string",
+      "multiValued": false,
+      "description": "Indicates the User's preferred written or spoken language.  Generally used for selecting a localized user interface; e.g., 'en_US' specifies the language English and country US.",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "locale",
+      "type": "string",
+      "multiValued": false,
+      "description": "Used to indicate the User's default location for purposes of localizing items such as currency, date time format, or numerical representations.",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "timezone",
+      "type": "string",
+      "multiValued": false,
+      "description": "The User's time zone in the 'Olson' time zone database format, e.g., 'America\/Los_Angeles'.",
+      "required": false,
+      "caseExact": false,
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "active",
+      "type": "boolean",
+      "multiValued": false,
+      "description": "A Boolean value indicating the User's administrative status.",
+      "required": false,
+      "mutability": "readWrite",
+      "returned": "default"
+    },
+    {
+      "name": "password",
+      "type": "string",
+      "multiValued": false,
+      "description": "The User's cleartext password.  This attribute is intended to be used as a means to specify an initial password when creating a new User or to reset an existing User's password.",
+      "required": false,
+      "caseExact": false,
+      "mutability": "writeOnly",
+      "returned": "never",
+      "uniqueness": "none"
+    },
+    {
+      "name": "emails",
+      "type": "complex",
+      "multiValued": true,
+      "description": "Email addresses for the user.  The value SHOULD be canonicalized by the service provider, e.g., 'bjensen@example.com' instead of 'bjensen@EXAMPLE.COM'. Canonical type values of 'work', 'home', and 'other'.",
+      "required": false,
+      "subAttributes": [
+        {
+          "name": "value",
+          "type": "string",
+          "multiValued": false,
+          "description": "Email addresses for the user.  The value SHOULD be canonicalized by the service provider, e.g., 'bjensen@example.com' instead of 'bjensen@EXAMPLE.COM'. Canonical type values of 'work', 'home', and 'other'.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "display",
+          "type": "string",
+          "multiValued": false,
+          "description": "A human-readable name, primarily used for display purposes.  READ-ONLY.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "type",
+          "type": "string",
+          "multiValued": false,
+          "description": "A label indicating the attribute's function, e.g., 'work' or 'home'.",
+          "required": false,
+          "caseExact": false,
+          "canonicalValues": [
+            "work",
+            "home",
+            "other"
+          ],
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "primary",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g., the preferred mailing address or primary email address.  The primary attribute value 'true' MUST appear no more than once.",
+          "required": false,
+          "mutability": "readWrite",
+          "returned": "default"
+        }
+      ],
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "phoneNumbers",
+      "type": "complex",
+      "multiValued": true,
+      "description": "Phone numbers for the User.  The value SHOULD be canonicalized by the service provider according to the format specified in RFC 3966, e.g., 'tel:+1-201-555-0123'. Canonical type values of 'work', 'home', 'mobile', 'fax', 'pager', and 'other'.",
+      "required": false,
+      "subAttributes": [
+        {
+          "name": "value",
+          "type": "string",
+          "multiValued": false,
+          "description": "Phone number of the User.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "display",
+          "type": "string",
+          "multiValued": false,
+          "description": "A human-readable name, primarily used for display purposes.  READ-ONLY.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "type",
+          "type": "string",
+          "multiValued": false,
+          "description": "A label indicating the attribute's function, e.g., 'work', 'home', 'mobile'.",
+          "required": false,
+          "caseExact": false,
+          "canonicalValues": [
+            "work",
+            "home",
+            "mobile",
+            "fax",
+            "pager",
+            "other"
+          ],
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "primary",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g., the preferred phone number or primary phone number.  The primary attribute value 'true' MUST appear no more than once.",
+          "required": false,
+          "mutability": "readWrite",
+          "returned": "default"
+        }
+      ],
+      "mutability": "readWrite",
+      "returned": "default"
+    },
+    {
+      "name": "ims",
+      "type": "complex",
+      "multiValued": true,
+      "description": "Instant messaging addresses for the User.",
+      "required": false,
+      "subAttributes": [
+        {
+          "name": "value",
+          "type": "string",
+          "multiValued": false,
+          "description": "Instant messaging address for the User.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "display",
+          "type": "string",
+          "multiValued": false,
+          "description": "A human-readable name, primarily used for display purposes.  READ-ONLY.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "type",
+          "type": "string",
+          "multiValued": false,
+          "description": "A label indicating the attribute's function, e.g., 'aim', 'gtalk', 'xmpp'.",
+          "required": false,
+          "caseExact": false,
+          "canonicalValues": [
+            "aim",
+            "gtalk",
+            "icq",
+            "xmpp",
+            "msn",
+            "skype",
+            "qq",
+            "yahoo"
+          ],
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "primary",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g., the preferred messenger or primary messenger.  The primary attribute value 'true' MUST appear no more than once.",
+          "required": false,
+          "mutability": "readWrite",
+          "returned": "default"
+        }
+      ],
+      "mutability": "readWrite",
+      "returned": "default"
+    },
+    {
+      "name": "photos",
+      "type": "complex",
+      "multiValued": true,
+      "description": "URLs of photos of the User.",
+      "required": false,
+      "subAttributes": [
+        {
+          "name": "value",
+          "type": "reference",
+          "referenceTypes": [
+            "external"
+          ],
+          "multiValued": false,
+          "description": "URL of a photo of the User.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "display",
+          "type": "string",
+          "multiValued": false,
+          "description": "A human-readable name, primarily used for display purposes.  READ-ONLY.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "type",
+          "type": "string",
+          "multiValued": false,
+          "description": "A label indicating the attribute's function, i.e., 'photo' or 'thumbnail'.",
+          "required": false,
+          "caseExact": false,
+          "canonicalValues": [
+            "photo",
+            "thumbnail"
+          ],
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "primary",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value indicating the 'primary' or preferred attribute value for this attribute, e.g., the preferred photo or thumbnail.  The primary attribute value 'true' MUST appear no more than once.",
+          "required": false,
+          "mutability": "readWrite",
+          "returned": "default"
+        }
+      ],
+      "mutability": "readWrite",
+      "returned": "default"
+    },
+    {
+      "name": "addresses",
+      "type": "complex",
+      "multiValued": true,
+      "description": "A physical mailing address for this User. Canonical type values of 'work', 'home', and 'other'.  This attribute is a complex type with the following sub-attributes.",
+      "required": false,
+      "subAttributes": [
+        {
+          "name": "formatted",
+          "type": "string",
+          "multiValued": false,
+          "description": "The full mailing address, formatted for display or use with a mailing label.  This attribute MAY contain newlines.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "streetAddress",
+          "type": "string",
+          "multiValued": false,
+          "description": "The full street address component, which may include house number, street name, P.O. box, and multi-line extended street address information.  This attribute MAY contain newlines.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "locality",
+          "type": "string",
+          "multiValued": false,
+          "description": "The city or locality component.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "region",
+          "type": "string",
+          "multiValued": false,
+          "description": "The state or region component.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "postalCode",
+          "type": "string",
+          "multiValued": false,
+          "description": "The zip code or postal code component.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "country",
+          "type": "string",
+          "multiValued": false,
+          "description": "The country name component.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "type",
+          "type": "string",
+          "multiValued": false,
+          "description": "A label indicating the attribute's function, e.g., 'work' or 'home'.",
+          "required": false,
+          "caseExact": false,
+          "canonicalValues": [
+            "work",
+            "home",
+            "other"
+          ],
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        }
+      ],
+      "mutability": "readWrite",
+      "returned": "default",
+      "uniqueness": "none"
+    },
+    {
+      "name": "groups",
+      "type": "complex",
+      "multiValued": true,
+      "description": "A list of groups to which the user belongs, either through direct membership, through nested groups, or dynamically calculated.",
+      "required": false,
+      "subAttributes": [
+        {
+          "name": "value",
+          "type": "string",
+          "multiValued": false,
+          "description": "The identifier of the User's group.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "$ref",
+          "type": "reference",
+          "referenceTypes": [
+            "User",
+            "Group"
+          ],
+          "multiValued": false,
+          "description": "The URI of the corresponding 'Group' resource to which the user belongs.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "display",
+          "type": "string",
+          "multiValued": false,
+          "description": "A human-readable name, primarily used for display purposes.  READ-ONLY.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "type",
+          "type": "string",
+          "multiValued": false,
+          "description": "A label indicating the attribute's function, e.g., 'direct' or 'indirect'.",
+          "required": false,
+          "caseExact": false,
+          "canonicalValues": [
+            "direct",
+            "indirect"
+          ],
+          "mutability": "readOnly",
+          "returned": "default",
+          "uniqueness": "none"
+        }
+      ],
+      "mutability": "readOnly",
+      "returned": "default"
+    },
+    {
+      "name": "entitlements",
+      "type": "complex",
+      "multiValued": true,
+      "description": "A list of entitlements for the User that represent a thing the User has.",
+      "required": false,
+      "subAttributes": [
+        {
+          "name": "value",
+          "type": "string",
+          "multiValued": false,
+          "description": "The value of an entitlement.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "display",
+          "type": "string",
+          "multiValued": false,
+          "description": "A human-readable name, primarily used for display purposes.  READ-ONLY.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "type",
+          "type": "string",
+          "multiValued": false,
+          "description": "A label indicating the attribute's function.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "primary",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value indicating the 'primary' or preferred attribute value for this attribute.  The primary attribute value 'true' MUST appear no more than once.",
+          "required": false,
+          "mutability": "readWrite",
+          "returned": "default"
+        }
+      ],
+      "mutability": "readWrite",
+      "returned": "default"
+    },
+    {
+      "name": "roles",
+      "type": "complex",
+      "multiValued": true,
+      "description": "A list of roles for the User that collectively represent who the User is, e.g., 'Student', 'Faculty'.",
+      "required": false,
+      "subAttributes": [
+        {
+          "name": "value",
+          "type": "string",
+          "multiValued": false,
+          "description": "The value of a role.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "display",
+          "type": "string",
+          "multiValued": false,
+          "description": "A human-readable name, primarily used for display purposes.  READ-ONLY.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "type",
+          "type": "string",
+          "multiValued": false,
+          "description": "A label indicating the attribute's function.",
+          "required": false,
+          "caseExact": false,
+          "canonicalValues": [
+
+          ],
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "primary",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value indicating the 'primary' or preferred attribute value for this attribute.  The primary attribute value 'true' MUST appear no more than once.",
+          "required": false,
+          "mutability": "readWrite",
+          "returned": "default"
+        }
+      ],
+      "mutability": "readWrite",
+      "returned": "default"
+    },
+    {
+      "name": "x509Certificates",
+      "type": "complex",
+      "multiValued": true,
+      "description": "A list of certificates issued to the User.",
+      "required": false,
+      "caseExact": false,
+      "subAttributes": [
+        {
+          "name": "value",
+          "type": "binary",
+          "multiValued": false,
+          "description": "The value of an X.509 certificate.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "display",
+          "type": "string",
+          "multiValued": false,
+          "description": "A human-readable name, primarily used for display purposes.  READ-ONLY.",
+          "required": false,
+          "caseExact": false,
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "type",
+          "type": "string",
+          "multiValued": false,
+          "description": "A label indicating the attribute's function.",
+          "required": false,
+          "caseExact": false,
+          "canonicalValues": [],
+          "mutability": "readWrite",
+          "returned": "default",
+          "uniqueness": "none"
+        },
+        {
+          "name": "primary",
+          "type": "boolean",
+          "multiValued": false,
+          "description": "A Boolean value indicating the 'primary' or preferred attribute value for this attribute.  The primary attribute value 'true' MUST appear no more than once.",
+          "required": false,
+          "mutability": "readWrite",
+          "returned": "default"
+        }
+      ],
+      "mutability": "readWrite",
+      "returned": "default"
+    }
+  ],
+  "meta": {
+    "resourceType": "Schema",
+    "location": "/v2/Schemas/urn:ietf:params:scim:schemas:core:2.0:User"
+  }
+}
+|]
diff --git a/src/Web/Scim/Class/Auth.hs b/src/Web/Scim/Class/Auth.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Class/Auth.hs
@@ -0,0 +1,54 @@
+{-# LANGUAGE AllowAmbiguousTypes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+-- | HTTP authentication support. Can be used with basic auth, token-based
+-- auth, or something else (though OAuth is likely not implementable with
+-- this API).
+module Web.Scim.Class.Auth
+  ( AuthTypes (..),
+    AuthDB (..),
+  )
+where
+
+import Servant
+import Web.Scim.Handler
+
+-- | Types used in authentication routines.
+class AuthTypes tag where
+  -- | The type that the “Authorization” header will be parsed as. This info
+  -- will be given to 'authCheck'.
+  type AuthData tag
+
+  -- | The result of performing authentication.
+  --
+  -- Can be '()' to handle just authorized/non-authorized, or something more
+  -- complex – for instance, if the auth header provides a token that may or
+  -- may not correspond to a particular organization, then the result could
+  -- be the ID of that organization).
+  type AuthInfo tag
+
+-- | An interface that has to be implemented for a server to provide
+-- authentication.
+class (AuthTypes tag, FromHttpApiData (AuthData tag)) => AuthDB tag m where
+  -- | Do authentication or throw an error in `ScimHandler` (e.g.
+  -- 'Web.Scim.Schema.Error.unauthorized') if the provided credentials are
+  -- invalid or don't correspond to any user.
+  authCheck ::
+    Maybe (AuthData tag) ->
+    ScimHandler m (AuthInfo tag)
diff --git a/src/Web/Scim/Class/Group.hs b/src/Web/Scim/Class/Group.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Class/Group.hs
@@ -0,0 +1,198 @@
+{-# LANGUAGE AllowAmbiguousTypes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Class.Group
+  ( GroupSite (..),
+    GroupDB (..),
+    GroupTypes (..),
+    StoredGroup,
+    Group (..),
+    Member (..),
+    groupServer,
+  )
+where
+
+import Data.Aeson
+import qualified Data.Aeson as Aeson
+import Data.Text
+import Servant
+import Servant.API.Generic
+import Servant.Server.Generic
+import Web.Scim.Class.Auth
+import Web.Scim.ContentType
+import Web.Scim.Handler
+import Web.Scim.Schema.Common
+import Web.Scim.Schema.ListResponse
+import Web.Scim.Schema.Meta
+
+----------------------------------------------------------------------------
+-- /Groups API
+
+type Schema = Text
+
+-- | Configurable parts of 'Group'.
+class GroupTypes tag where
+  -- | Group ID type.
+  type GroupId tag
+
+-- TODO
+data Member = Member
+  { value :: Text,
+    typ :: Text,
+    ref :: Text
+  }
+  deriving (Show, Eq, Generic)
+
+instance FromJSON Member where
+  parseJSON = genericParseJSON parseOptions . jsonLower
+
+instance ToJSON Member where
+  toJSON = genericToJSON serializeOptions
+
+data Group = Group
+  { schemas :: [Schema],
+    displayName :: Text,
+    members :: [Member]
+  }
+  deriving (Show, Eq, Generic)
+
+instance FromJSON Group where
+  parseJSON = genericParseJSON parseOptions . jsonLower
+
+instance ToJSON Group where
+  toJSON = genericToJSON serializeOptions
+
+type StoredGroup tag = WithMeta (WithId (GroupId tag) Group)
+
+data GroupSite tag route = GroupSite
+  { gsGetGroups ::
+      route
+        :- Get '[SCIM] (ListResponse (StoredGroup tag)),
+    gsGetGroup ::
+      route
+        :- Capture "id" (GroupId tag)
+        :> Get '[SCIM] (StoredGroup tag),
+    gsPostGroup ::
+      route
+        :- ReqBody '[SCIM] Group
+        :> PostCreated '[SCIM] (StoredGroup tag),
+    gsPutGroup ::
+      route
+        :- Capture "id" (GroupId tag)
+        :> ReqBody '[SCIM] Group
+        :> Put '[SCIM] (StoredGroup tag),
+    gsPatchGroup ::
+      route
+        :- Capture "id" (GroupId tag)
+        :> ReqBody '[SCIM] Aeson.Value
+        :> Patch '[SCIM] (StoredGroup tag),
+    gsDeleteGroup ::
+      route
+        :- Capture "id" (GroupId tag)
+        :> DeleteNoContent
+  }
+  deriving (Generic)
+
+----------------------------------------------------------------------------
+-- Methods used by the API
+
+class (Monad m, GroupTypes tag, AuthDB tag m) => GroupDB tag m where
+  -- | Get all groups.
+  getGroups ::
+    AuthInfo tag ->
+    ScimHandler m (ListResponse (StoredGroup tag))
+
+  -- | Get a single group by ID.
+  --
+  -- Should throw 'notFound' if the group does not.
+  getGroup ::
+    AuthInfo tag ->
+    GroupId tag ->
+    ScimHandler m (StoredGroup tag)
+
+  -- | Create a new group.
+  --
+  -- Should throw 'conflict' if uniqueness constraints are violated.
+  postGroup ::
+    AuthInfo tag ->
+    Group ->
+    ScimHandler m (StoredGroup tag)
+
+  -- | Overwrite an existing group.
+  --
+  -- Should throw 'notFound' if the group does not exist, and 'conflict' if uniqueness
+  -- constraints are violated.
+  putGroup ::
+    AuthInfo tag ->
+    GroupId tag ->
+    Group ->
+    ScimHandler m (StoredGroup tag)
+
+  -- | Modify an existing group.
+  --
+  -- Should throw 'notFound' if the group doesn't exist, and 'conflict' if uniqueness
+  -- constraints are violated.
+  --
+  -- FUTUREWORK: add types for PATCH (instead of 'Aeson.Value').
+  -- See <https://tools.ietf.org/html/rfc7644#section-3.5.2>
+  patchGroup ::
+    AuthInfo tag ->
+    GroupId tag ->
+    -- | PATCH payload
+    Aeson.Value ->
+    ScimHandler m (StoredGroup tag)
+
+  -- | Delete a group.
+  --
+  -- Should throw 'notFound' if the group does not exist.
+  deleteGroup ::
+    AuthInfo tag ->
+    GroupId tag ->
+    ScimHandler m ()
+
+----------------------------------------------------------------------------
+-- API handlers
+
+groupServer ::
+  forall tag m.
+  (Show (GroupId tag), GroupDB tag m) =>
+  Maybe (AuthData tag) ->
+  GroupSite tag (AsServerT (ScimHandler m))
+groupServer authData =
+  GroupSite
+    { gsGetGroups = do
+        auth <- authCheck @tag authData
+        getGroups @tag auth,
+      gsGetGroup = \gid -> do
+        auth <- authCheck @tag authData
+        getGroup @tag auth gid,
+      gsPostGroup = \gr -> do
+        auth <- authCheck @tag authData
+        postGroup @tag auth gr,
+      gsPutGroup = \gid gr -> do
+        auth <- authCheck @tag authData
+        putGroup @tag auth gid gr,
+      gsPatchGroup = \gid patch -> do
+        auth <- authCheck @tag authData
+        patchGroup @tag auth gid patch,
+      gsDeleteGroup = \gid -> do
+        auth <- authCheck @tag authData
+        deleteGroup @tag auth gid
+        pure NoContent
+    }
diff --git a/src/Web/Scim/Class/User.hs b/src/Web/Scim/Class/User.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Class/User.hs
@@ -0,0 +1,189 @@
+{-# LANGUAGE AllowAmbiguousTypes #-}
+{-# LANGUAGE DefaultSignatures #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Class.User
+  ( UserDB (..),
+    StoredUser,
+    UserSite (..),
+    userServer,
+  )
+where
+
+import Data.Aeson.Types (FromJSON)
+import Servant
+import Servant.API.Generic
+import Servant.Server.Generic
+import Web.Scim.Class.Auth
+import Web.Scim.ContentType
+import Web.Scim.Filter
+import Web.Scim.Handler
+import Web.Scim.Schema.Common
+import Web.Scim.Schema.ListResponse hiding (schemas)
+import Web.Scim.Schema.Meta
+import Web.Scim.Schema.PatchOp
+import Web.Scim.Schema.User
+
+----------------------------------------------------------------------------
+-- /Users API
+
+type StoredUser tag = WithMeta (WithId (UserId tag) (User tag))
+
+data UserSite tag route = UserSite
+  { usGetUsers ::
+      route
+        :- QueryParam "filter" Filter
+        :> Get '[SCIM] (ListResponse (StoredUser tag)),
+    usGetUser ::
+      route
+        :- Capture "id" (UserId tag)
+        :> Get '[SCIM] (StoredUser tag),
+    usPostUser ::
+      route
+        :- ReqBody '[SCIM] (User tag)
+        :> PostCreated '[SCIM] (StoredUser tag),
+    usPutUser ::
+      route
+        :- Capture "id" (UserId tag)
+        :> ReqBody '[SCIM] (User tag)
+        :> Put '[SCIM] (StoredUser tag),
+    usPatchUser ::
+      route
+        :- Capture "id" (UserId tag)
+        :> ReqBody '[SCIM] (PatchOp tag)
+        :> Patch '[SCIM] (StoredUser tag),
+    usDeleteUser ::
+      route
+        :- Capture "id" (UserId tag)
+        :> DeleteNoContent
+  }
+  deriving (Generic)
+
+----------------------------------------------------------------------------
+-- Methods used by the API
+
+class (Monad m, AuthTypes tag, UserTypes tag) => UserDB tag m where
+  -- | Get all users, optionally filtered by a 'Filter'.
+  getUsers ::
+    AuthInfo tag ->
+    Maybe Filter ->
+    ScimHandler m (ListResponse (StoredUser tag))
+
+  -- | Get a single user by ID.
+  --
+  -- Should throw 'notFound' if the user doesn't exist.
+  getUser ::
+    AuthInfo tag ->
+    UserId tag ->
+    ScimHandler m (StoredUser tag)
+
+  -- | Create a new user.
+  --
+  -- Should throw 'conflict' if uniqueness constraints are violated.
+  postUser ::
+    AuthInfo tag ->
+    User tag ->
+    ScimHandler m (StoredUser tag)
+
+  -- | Overwrite an existing user.
+  --
+  -- Should throw 'notFound' if the user doesn't exist, and 'conflict' if
+  -- uniqueness constraints are violated.
+  putUser ::
+    AuthInfo tag ->
+    UserId tag ->
+    User tag ->
+    ScimHandler m (StoredUser tag)
+
+  -- | Modify an existing user.
+  --
+  -- Should throw 'notFound' if the user doesn't exist, and 'conflict' if
+  -- uniqueness constraints are violated.
+  --
+  --  https://tools.ietf.org/html/rfc7644#section-3.5.2
+  --
+  --    If the target location already contains the value specified, no changes
+  --    SHOULD be made to the resource, and a success response SHOULD be
+  --    returned.  Unless other operations change the resource, this operation
+  --    SHALL NOT change the modify timestamp of the resource.
+  --
+  --  Given that PUT has the same constraints, we can implement PATCH in terms
+  --  of some magic in this library, GET and PUT.
+  --
+  --  SCIM's Patch semantics are hard to get right. So we advice using the
+  --  library built-in implementation.  we implement PATCH in terms of a GET
+  --  followed by a PUT.  GET will retrieve the entire record; we then modify
+  --  this record by a series of PATCH operations, and then PUT the entire
+  --  record.
+  patchUser ::
+    AuthInfo tag ->
+    UserId tag ->
+    -- | PATCH payload
+    PatchOp tag ->
+    ScimHandler m (StoredUser tag)
+  default patchUser ::
+    (Patchable (UserExtra tag), FromJSON (UserExtra tag)) =>
+    AuthInfo tag ->
+    UserId tag ->
+    -- | PATCH payload
+    PatchOp tag ->
+    ScimHandler m (StoredUser tag)
+  patchUser info uid op' = do
+    (WithMeta _ (WithId _ (user :: User tag))) <- getUser info uid
+    (newUser :: User tag) <- applyPatch user op'
+    putUser info uid newUser
+
+  -- | Delete a user.
+  --
+  -- Should throw 'notFound' if the user doesn't exist.
+  deleteUser ::
+    AuthInfo tag ->
+    UserId tag ->
+    ScimHandler m ()
+
+----------------------------------------------------------------------------
+-- API handlers
+
+userServer ::
+  forall tag m.
+  (AuthDB tag m, UserDB tag m) =>
+  Maybe (AuthData tag) ->
+  UserSite tag (AsServerT (ScimHandler m))
+userServer authData =
+  UserSite
+    { usGetUsers = \mbFilter -> do
+        auth <- authCheck @tag authData
+        getUsers @tag auth mbFilter,
+      usGetUser = \uid -> do
+        auth <- authCheck @tag authData
+        getUser @tag auth uid,
+      usPostUser = \user -> do
+        auth <- authCheck @tag authData
+        postUser @tag auth user,
+      usPutUser = \uid user -> do
+        auth <- authCheck @tag authData
+        putUser @tag auth uid user,
+      usPatchUser = \uid patch -> do
+        auth <- authCheck @tag authData
+        patchUser @tag @m auth uid patch,
+      usDeleteUser = \uid -> do
+        auth <- authCheck @tag authData
+        deleteUser @tag auth uid
+        pure NoContent
+    }
diff --git a/src/Web/Scim/ContentType.hs b/src/Web/Scim/ContentType.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/ContentType.hs
@@ -0,0 +1,50 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+-- | SCIM defines its own content type (application/scim+json). It's
+-- intended to be used for all requests and responses; see the first
+-- paragraph in the SCIM specification at
+-- <https://tools.ietf.org/html/rfc7644#section-3.1>.
+--
+-- This module contains helpers for handling it. Basically, just write
+-- 'SCIM' instead of 'JSON' in all Servant routes.
+module Web.Scim.ContentType
+  ( SCIM,
+  )
+where
+
+import Data.Aeson
+import Data.List.NonEmpty
+import Data.Proxy
+import Network.HTTP.Media hiding (Accept)
+import Servant.API.ContentTypes
+
+data SCIM
+
+instance Accept SCIM where
+  contentTypes _ =
+    "application" // "scim+json" /: ("charset", "utf-8")
+      :| "application" // "scim+json" :
+    "application" // "json" /: ("charset", "utf-8") :
+    "application" // "json" :
+    []
+
+instance ToJSON a => MimeRender SCIM a where
+  mimeRender _ = mimeRender (Proxy @JSON)
+
+instance FromJSON a => MimeUnrender SCIM a where
+  mimeUnrender _ = mimeUnrender (Proxy @JSON)
diff --git a/src/Web/Scim/Filter.hs b/src/Web/Scim/Filter.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Filter.hs
@@ -0,0 +1,293 @@
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+-- | A query might specify a filter that should be applied to the results
+-- before returning them. This module implements a very limited subset of
+-- the specification: <https://tools.ietf.org/html/rfc7644#section-3.4.2.2>.
+--
+-- Supported:
+--
+-- * All comparison operators (@eq@, @le@, etc)
+-- * The @userName@ attribute
+--
+-- Not supported:
+--
+-- * The @pr@ operator
+-- * Boolean operators
+-- * Combined filters
+-- * Fully qualified attribute names (schema prefixes, attribute paths)
+module Web.Scim.Filter
+  ( -- * Filter type
+    Filter (..),
+    parseFilter,
+    renderFilter,
+
+    -- * Constructing filters
+    CompValue (..),
+    CompareOp (..),
+    AttrPath (..),
+    ValuePath (..),
+    SubAttr (..),
+    pAttrPath,
+    pValuePath,
+    pSubAttr,
+    pFilter,
+    rAttrPath,
+    rCompareOp,
+    rValuePath,
+    rSubAttr,
+    compareStr,
+    topLevelAttrPath,
+  )
+where
+
+import Control.Applicative (optional, (<|>))
+import Data.Aeson as Aeson
+import Data.Aeson.Parser as Aeson
+import Data.Aeson.Text as Aeson
+import Data.Attoparsec.ByteString.Char8
+import Data.Scientific
+import Data.String
+import Data.Text (Text, isInfixOf, isPrefixOf, isSuffixOf, pack)
+import Data.Text.Encoding (encodeUtf8)
+import Data.Text.Lazy (toStrict)
+import Lens.Micro
+import Web.HttpApiData
+import Web.Scim.AttrName
+import Web.Scim.Schema.Schema (Schema (User20), getSchemaUri, pSchema)
+import Prelude hiding (takeWhile)
+
+----------------------------------------------------------------------------
+-- Types
+
+-- NB: when extending these types, don't forget to update Test.FilterSpec
+
+-- | A value type. Attributes are compared against literal values.
+data CompValue
+  = ValNull
+  | ValBool Bool
+  | ValNumber Scientific
+  | ValString Text
+  deriving (Eq, Ord, Show)
+
+-- | A comparison operator.
+data CompareOp
+  = -- | Equal
+    OpEq
+  | -- | Not equal
+    OpNe
+  | -- | Contains
+    OpCo
+  | -- | Starts with
+    OpSw
+  | -- | Ends with
+    OpEw
+  | -- | Greater than
+    OpGt
+  | -- | Greater than or equal to
+    OpGe
+  | -- | Less than
+    OpLt
+  | -- | Less than or equal to
+    OpLe
+  deriving (Eq, Ord, Show, Enum, Bounded)
+
+-- | A filter.
+--
+-- Our representation of filters is lax and doesn't attempt to ensure
+-- validity on the type level. If a filter does something silly (e.g. tries
+-- to compare a username with a boolean), it will be caught during filtering
+-- and an appropriate error message will be thrown (see 'filterUser').
+--
+-- TODO(arianvp): Implement the following grammar fully if we want to support
+-- more complex filters
+--
+-- FILTER    = attrExp / logExp / valuePath / *1"not" "(" FILTER ")"
+data Filter
+  = -- | Compare the attribute value with a literal
+    FilterAttrCompare AttrPath CompareOp CompValue
+  deriving (Eq, Show)
+
+-- | valuePath = attrPath "[" valFilter "]"
+-- TODO(arianvp): This is a slight simplification at the moment as we
+-- don't support the complete Filter grammar. This should be a
+-- valFilter, not a FILTER.
+data ValuePath = ValuePath AttrPath Filter
+  deriving (Eq, Show)
+
+-- | subAttr   = "." ATTRNAME
+newtype SubAttr = SubAttr AttrName
+  deriving (Eq, Show, IsString)
+
+-- | attrPath  = [URI ":"] ATTRNAME *1subAtt
+data AttrPath = AttrPath (Maybe Schema) AttrName (Maybe SubAttr)
+  deriving (Eq, Show)
+
+-- | Smart constructor that refers to a toplevel field with default schema
+topLevelAttrPath :: Text -> AttrPath
+topLevelAttrPath x = AttrPath Nothing (AttrName x) Nothing
+
+-- | PATH = attrPath / valuePath [subAttr]
+--
+-- Currently we don't support matching on lists in paths as
+-- we currently don't support filtering on arbitrary attributes yet
+-- e.g.
+-- @
+-- "path":"members[value eq
+--            \"2819c223-7f76-453a-919d-413861904646\"].displayName"
+-- @
+-- is not supported
+
+----------------------------------------------------------------------------
+-- Parsing
+
+-- | Parse a filter. Spaces surrounding the filter will be stripped.
+--
+-- If parsing fails, returns a 'Left' with an error description.
+--
+-- Note: this parser is written with Attoparsec because I don't know how to
+-- lift an Attoparsec parser (from Aeson) to Megaparsec
+parseFilter :: [Schema] -> Text -> Either Text Filter
+parseFilter supportedSchemas =
+  over _Left pack
+    . parseOnly (skipSpace *> pFilter supportedSchemas <* skipSpace <* endOfInput)
+    . encodeUtf8
+
+-- |
+-- @
+-- ATTRNAME  = ALPHA *(nameChar)
+-- attrPath  = [URI ":"] ATTRNAME *1subAtt
+-- @
+pAttrPath :: [Schema] -> Parser AttrPath
+pAttrPath supportedSchemas = do
+  schema <- (Just <$> (pSchema supportedSchemas <* char ':')) <|> pure Nothing
+  AttrPath schema <$> pAttrName <*> optional pSubAttr
+
+-- | subAttr   = "." ATTRNAME
+pSubAttr :: Parser SubAttr
+pSubAttr = char '.' *> (SubAttr <$> pAttrName)
+
+-- | valuePath = attrPath "[" valFilter "]"
+pValuePath :: [Schema] -> Parser ValuePath
+pValuePath supportedSchemas =
+  ValuePath <$> pAttrPath supportedSchemas <*> (char '[' *> pFilter supportedSchemas <* char ']')
+
+-- | Value literal parser.
+pCompValue :: Parser CompValue
+pCompValue =
+  choice
+    [ ValNull <$ string "null",
+      ValBool True <$ (stringCI "true"),
+      ValBool False <$ (stringCI "false"),
+      ValNumber <$> Aeson.scientific,
+      ValString <$> Aeson.jstring
+    ]
+
+-- | Comparison operator parser.
+pCompareOp :: Parser CompareOp
+pCompareOp =
+  choice
+    [ OpEq <$ stringCI "eq",
+      OpNe <$ stringCI "ne",
+      OpCo <$ stringCI "co",
+      OpSw <$ stringCI "sw",
+      OpEw <$ stringCI "ew",
+      OpGt <$ stringCI "gt",
+      OpGe <$ stringCI "ge",
+      OpLt <$ stringCI "lt",
+      OpLe <$ stringCI "le"
+    ]
+
+-- | Filter parser.
+pFilter :: [Schema] -> Parser Filter
+pFilter supportedSchemas =
+  FilterAttrCompare
+    <$> pAttrPath supportedSchemas
+    <*> (skipSpace1 *> pCompareOp)
+    <*> (skipSpace1 *> pCompValue)
+
+-- | Utility parser for skipping one or more spaces.
+skipSpace1 :: Parser ()
+skipSpace1 = space *> skipSpace
+
+----------------------------------------------------------------------------
+-- Rendering
+
+-- | Render a filter according to the SCIM spec.
+renderFilter :: Filter -> Text
+renderFilter filter_ = case filter_ of
+  FilterAttrCompare attr op val ->
+    rAttrPath attr <> " " <> rCompareOp op <> " " <> rCompValue val
+
+rAttrPath :: AttrPath -> Text
+rAttrPath (AttrPath schema attr subAttr) =
+  maybe "" ((<> ":") . getSchemaUri) schema
+    <> rAttrName attr
+    <> maybe "" rSubAttr subAttr
+
+rSubAttr :: SubAttr -> Text
+rSubAttr (SubAttr x) = "." <> rAttrName x
+
+rValuePath :: ValuePath -> Text
+rValuePath (ValuePath attrPath filter') = rAttrPath attrPath <> "[" <> renderFilter filter' <> "]"
+
+-- | Value literal renderer.
+rCompValue :: CompValue -> Text
+rCompValue = \case
+  ValNull -> "null"
+  ValBool True -> "true"
+  ValBool False -> "false"
+  ValNumber n -> toStrict $ Aeson.encodeToLazyText (Aeson.Number n)
+  ValString s -> toStrict $ Aeson.encodeToLazyText (Aeson.String s)
+
+-- | Comparison operator renderer.
+rCompareOp :: CompareOp -> Text
+rCompareOp = \case
+  OpEq -> "eq"
+  OpNe -> "ne"
+  OpCo -> "co"
+  OpSw -> "sw"
+  OpEw -> "ew"
+  OpGt -> "gt"
+  OpGe -> "ge"
+  OpLt -> "lt"
+  OpLe -> "le"
+
+-- | Execute a comparison operator.
+compareStr :: CompareOp -> Text -> Text -> Bool
+compareStr = \case
+  OpEq -> (==) -- equal
+  OpNe -> (/=) -- not equal
+  OpCo -> flip isInfixOf -- A contains B
+  OpSw -> flip isPrefixOf -- A starts with B
+  OpEw -> flip isSuffixOf -- A ends with B
+  OpGt -> (>) -- greater than
+  OpGe -> (>=) -- greater than or equal to
+  OpLt -> (<) -- less than
+  OpLe -> (<=) -- less than or equal to
+
+----------------------------------------------------------------------------
+-- Instances
+
+-- | We currently only support filtering on core user schema
+instance FromHttpApiData Filter where
+  parseUrlPiece = parseFilter [User20]
+
+instance ToHttpApiData Filter where
+  toUrlPiece = renderFilter
diff --git a/src/Web/Scim/Handler.hs b/src/Web/Scim/Handler.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Handler.hs
@@ -0,0 +1,48 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Handler
+  ( ScimHandler,
+    throwScim,
+    fromScimHandler,
+  )
+where
+
+import Control.Monad.Except
+import Web.Scim.Schema.Error
+
+-- | Handler type for SCIM. All errors will be thrown via 'ExceptT'.
+type ScimHandler m = ExceptT ScimError m
+
+-- | Throw a 'ScimError'.
+throwScim :: Monad m => ScimError -> ScimHandler m a
+throwScim = throwError
+
+-- | A natural transformation for Servant handlers. To use it, you need to
+-- provide a way to throw errors in the underlying @m@ monad.
+--
+-- We can't use something like 'MonadError' to throw errors in @m@ because
+-- 'MonadError' allows only one type of errors per monad and @m@ might have
+-- one already.
+--
+-- You can either do something custom for 'ScimError', or use
+-- 'scimToServantErr'.
+fromScimHandler ::
+  Monad m =>
+  (forall a. ScimError -> m a) ->
+  (forall a. ScimHandler m a -> m a)
+fromScimHandler fromError = either fromError pure <=< runExceptT
diff --git a/src/Web/Scim/Schema/AuthenticationScheme.hs b/src/Web/Scim/Schema/AuthenticationScheme.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/AuthenticationScheme.hs
@@ -0,0 +1,82 @@
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.AuthenticationScheme
+  ( AuthenticationScheme (..),
+    AuthenticationSchemeEncoding,
+    authHttpBasicEncoding,
+  )
+where
+
+import Data.Aeson
+import Data.Text
+import GHC.Generics
+import Network.URI.Static
+import Web.Scim.Schema.Common
+
+----------------------------------------------------------------------------
+-- Types
+
+-- | Possible authentication schemes. The specification defines the values
+-- "oauth", "oauth2", "oauthbearertoken", "httpbasic", and "httpdigest".
+data AuthenticationScheme
+  = AuthOAuth
+  | AuthOAuth2
+  | AuthOAuthBearerToken
+  | AuthHttpBasic
+  | AuthHttpDigest
+  deriving (Eq, Show, Enum, Bounded, Ord)
+
+-- | The way authentication schemes are expected to be represented in the
+-- configuration. Each 'AuthenticationScheme' corresponds to one of such
+-- encodings.
+data AuthenticationSchemeEncoding = AuthenticationSchemeEncoding
+  { -- | The authentication scheme
+    typ :: Text,
+    -- | The common authentication scheme name, e.g. HTTP Basic
+    name :: Text,
+    -- | A description of the authentication scheme
+    description :: Text,
+    -- | An HTTP-addressable URL pointing to the authentication scheme's
+    -- specification
+    specUri :: Maybe URI,
+    -- | An HTTP-addressable URL pointing to the authentication scheme's usage
+    -- documentation
+    documentationUri :: Maybe URI
+  }
+  deriving (Show, Eq, Generic)
+
+instance ToJSON AuthenticationSchemeEncoding where
+  toJSON = genericToJSON serializeOptions
+
+-- NB: "typ" will be converted to "type" thanks to 'serializeOptions'
+
+----------------------------------------------------------------------------
+-- Scheme encodings
+
+-- | The description of the 'AuthHttpBasic' scheme.
+authHttpBasicEncoding :: AuthenticationSchemeEncoding
+authHttpBasicEncoding =
+  AuthenticationSchemeEncoding
+    { typ = "httpbasic",
+      name = "HTTP Basic",
+      description = "Authentication via the HTTP Basic standard",
+      specUri = Just $ URI [uri|https://tools.ietf.org/html/rfc7617|],
+      documentationUri = Just $ URI [uri|https://en.wikipedia.org/wiki/Basic_access_authentication|]
+    }
diff --git a/src/Web/Scim/Schema/Common.hs b/src/Web/Scim/Schema/Common.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/Common.hs
@@ -0,0 +1,100 @@
+{-# LANGUAGE DerivingStrategies #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.Common where
+
+import Data.Aeson
+import qualified Data.CaseInsensitive as CI
+import qualified Data.Char as Char
+import qualified Data.HashMap.Lazy as HML
+import qualified Data.HashMap.Strict as HM
+import Data.String (IsString)
+import Data.String.Conversions (cs)
+import Data.Text hiding (dropWhile)
+import qualified Network.URI as Network
+
+data WithId id a = WithId
+  { id :: id,
+    value :: a
+  }
+  deriving (Eq, Show)
+
+instance (ToJSON id, ToJSON a) => ToJSON (WithId id a) where
+  toJSON (WithId i v) = case toJSON v of
+    (Object o) -> Object (HML.insert "id" (toJSON i) o)
+    other -> other
+
+instance (FromJSON id, FromJSON a) => FromJSON (WithId id a) where
+  parseJSON = withObject "WithId" $ \o ->
+    WithId <$> o .: "id" <*> parseJSON (Object o)
+
+newtype URI = URI {unURI :: Network.URI}
+  deriving (Show, Eq)
+
+instance FromJSON URI where
+  parseJSON = withText "URI" $ \uri -> case Network.parseURI (unpack uri) of
+    Nothing -> fail "Invalid URI"
+    Just some -> pure $ URI some
+
+instance ToJSON URI where
+  toJSON (URI uri) = String $ pack $ show uri
+
+newtype ScimBool = ScimBool {unScimBool :: Bool}
+  deriving stock (Eq, Show, Ord)
+  deriving newtype (ToJSON)
+
+instance FromJSON ScimBool where
+  parseJSON (Bool bl) = pure (ScimBool bl)
+  parseJSON (String str) =
+    case CI.mk str of
+      "true" -> pure (ScimBool True)
+      "false" -> pure (ScimBool False)
+      _ -> fail $ "Expected true, false, \"true\", or \"false\" (case insensitive), but got " <> cs str
+  parseJSON bad = fail $ "Expected true, false, \"true\", or \"false\" (case insensitive), but got " <> show bad
+
+toKeyword :: (IsString p, Eq p) => p -> p
+toKeyword "typ" = "type"
+toKeyword "ref" = "$ref"
+toKeyword other = other
+
+serializeOptions :: Options
+serializeOptions =
+  defaultOptions
+    { omitNothingFields = True,
+      fieldLabelModifier = toKeyword
+    }
+
+-- | Turn all keys in a JSON object to lowercase.
+jsonLower :: Value -> Value
+jsonLower (Object o) = Object . HM.fromList . fmap lowerPair . HM.toList $ o
+  where
+    lowerPair (key, val) = (fromKeyword . toLower $ key, val)
+jsonLower x = x
+
+fromKeyword :: (IsString p, Eq p) => p -> p
+fromKeyword "type" = "typ"
+fromKeyword "$ref" = "ref"
+fromKeyword other = other
+
+parseOptions :: Options
+parseOptions =
+  defaultOptions
+    { fieldLabelModifier = fmap Char.toLower
+    }
diff --git a/src/Web/Scim/Schema/Error.hs b/src/Web/Scim/Schema/Error.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/Error.hs
@@ -0,0 +1,218 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+-- | SCIM errors
+module Web.Scim.Schema.Error
+  ( -- * Types
+    ScimErrorType (..),
+    ScimError (..),
+    Status (..),
+
+    -- * Constructors
+    notFound,
+    badRequest,
+    conflict,
+    unauthorized,
+    forbidden,
+    serverError,
+
+    -- * Servant interoperability
+    scimToServerError,
+  )
+where
+
+import Control.Exception
+import Data.Aeson hiding (Error)
+import Data.Text (Text, pack)
+import GHC.Generics (Generic)
+import Servant (ServerError (..))
+import Web.Scim.Schema.Common
+import Web.Scim.Schema.Schema
+
+----------------------------------------------------------------------------
+-- Types
+
+-- | An ADT for error types in the SCIM specification. Not all possible SCIM
+-- errors have a corresponding 'ScimErrorType' (for instance, authorization
+-- is not covered by this type).
+--
+-- See <https://tools.ietf.org/html/rfc7644#page-69>
+data ScimErrorType
+  = InvalidFilter
+  | TooMany
+  | Uniqueness
+  | Mutability
+  | InvalidSyntax
+  | InvalidPath
+  | NoTarget
+  | InvalidValue
+  | InvalidVers
+  | Sensitive
+  deriving (Show, Eq, Generic)
+
+instance ToJSON ScimErrorType where
+  toJSON InvalidFilter = "invalidFilter"
+  toJSON TooMany = "tooMany"
+  toJSON Uniqueness = "uniqueness"
+  toJSON Mutability = "mutability"
+  toJSON InvalidSyntax = "invalidSyntax"
+  toJSON InvalidPath = "invalidPath"
+  toJSON NoTarget = "noTarget"
+  toJSON InvalidValue = "invalidValue"
+  toJSON InvalidVers = "invalidVers"
+  toJSON Sensitive = "sensitive"
+
+-- wrapped in a newtype because SCIM wants strings for status codes
+newtype Status = Status {unStatus :: Int}
+  deriving (Show, Eq, Generic)
+
+instance ToJSON Status where
+  toJSON (Status stat) = String . pack . show $ stat
+
+data ScimError = ScimError
+  { schemas :: [Schema],
+    status :: Status,
+    scimType :: Maybe ScimErrorType,
+    detail :: Maybe Text
+  }
+  deriving (Show, Eq, Generic)
+
+instance ToJSON ScimError where
+  toJSON = genericToJSON serializeOptions
+
+instance Exception ScimError
+
+----------------------------------------------------------------------------
+-- Constructors
+
+badRequest ::
+  -- | Error type
+  ScimErrorType ->
+  -- | Error details
+  Maybe Text ->
+  ScimError
+badRequest typ mbDetail =
+  ScimError
+    { schemas = [Error20],
+      status = Status 400,
+      scimType = pure typ,
+      detail = mbDetail
+    }
+
+unauthorized ::
+  -- | Error details
+  Text ->
+  ScimError
+unauthorized details =
+  ScimError
+    { schemas = [Error20],
+      status = Status 401,
+      scimType = Nothing,
+      detail = pure $ "authorization failed: " <> details
+    }
+
+forbidden ::
+  -- | Error details
+  Text ->
+  ScimError
+forbidden details =
+  ScimError
+    { schemas = [Error20],
+      status = Status 403,
+      scimType = Nothing,
+      detail = pure $ "forbidden: " <> details
+    }
+
+notFound ::
+  -- | Resource type
+  Text ->
+  -- | Resource ID
+  Text ->
+  ScimError
+notFound resourceType resourceId =
+  ScimError
+    { schemas = [Error20],
+      status = Status 404,
+      scimType = Nothing,
+      detail = pure $ resourceType <> " " <> resourceId <> " not found"
+    }
+
+conflict :: ScimError
+conflict =
+  ScimError
+    { schemas = [Error20],
+      status = Status 409,
+      scimType = Just Uniqueness,
+      detail = Nothing
+    }
+
+serverError ::
+  -- | Error details
+  Text ->
+  ScimError
+serverError details =
+  ScimError
+    { schemas = [Error20],
+      status = Status 500,
+      scimType = Nothing,
+      detail = pure details
+    }
+
+----------------------------------------------------------------------------
+-- Servant
+
+-- | Convert a SCIM 'Error' to a Servant one by encoding it with the
+-- appropriate headers.
+scimToServerError :: ScimError -> ServerError
+scimToServerError err =
+  ServerError
+    { errHTTPCode = unStatus (status err),
+      errReasonPhrase = reasonPhrase (status err),
+      errBody = encode err,
+      errHeaders = [("Content-Type", "application/scim+json;charset=utf-8")]
+    }
+
+-- | A mapping of error code "reason phrases" (e.g. "Method Not Allowed")
+-- for all 4xx and 5xx errors.
+reasonPhrase :: Status -> String
+reasonPhrase = \case
+  Status 400 -> "Bad Request"
+  Status 401 -> "Unauthorized"
+  Status 402 -> "Payment Required"
+  Status 403 -> "Forbidden"
+  Status 404 -> "Not Found"
+  Status 405 -> "Method Not Allowed"
+  Status 406 -> "Not Acceptable"
+  Status 407 -> "Proxy Authentication Required"
+  Status 408 -> "Request Time-out"
+  Status 409 -> "Conflict"
+  Status 410 -> "Gone"
+  Status 411 -> "Length Required"
+  Status 412 -> "Precondition Failed"
+  Status 413 -> "Request Entity Too Large"
+  Status 414 -> "Request-URI Too Large"
+  Status 415 -> "Unsupported Media Type"
+  Status 416 -> "Range Not Satisfiable"
+  Status 417 -> "Expectation Failed"
+  Status 422 -> "Unprocessable Entity"
+  Status 500 -> "Internal Server Error"
+  Status 501 -> "Not Implemented"
+  Status 502 -> "Bad Gateway"
+  Status 503 -> "Service Unavailable"
+  Status 504 -> "Gateway Time-out"
+  Status 505 -> "HTTP Version not supported"
+  other -> show other
diff --git a/src/Web/Scim/Schema/ListResponse.hs b/src/Web/Scim/Schema/ListResponse.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/ListResponse.hs
@@ -0,0 +1,72 @@
+{-# LANGUAGE RecordWildCards #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.ListResponse
+  ( ListResponse (..),
+    fromList,
+  )
+where
+
+import Data.Aeson
+import GHC.Generics (Generic)
+import Web.Scim.Schema.Common
+import Web.Scim.Schema.Schema
+
+-- | A "pagination" type used as a wrapper whenever a SCIM endpoint has to
+-- return a list.
+--
+-- Pagination is not actually supported anywhere in the code yet; whenever
+-- there are several results we always return them all as one page, and we
+-- don't support different values of 'startIndex'.
+--
+-- FUTUREWORK: Support for pagination might be added once we have to handle
+-- organizations with lots of users.
+data ListResponse a = ListResponse
+  { schemas :: [Schema],
+    totalResults :: Int,
+    itemsPerPage :: Int,
+    startIndex :: Int,
+    resources :: [a]
+  }
+  deriving (Show, Eq, Generic)
+
+fromList :: [a] -> ListResponse a
+fromList list =
+  ListResponse
+    { schemas = [ListResponse20],
+      totalResults = len,
+      itemsPerPage = len,
+      startIndex = 1, -- NOTE: lists are 1-indexed in SCIM
+      resources = list
+    }
+  where
+    len = length list
+
+instance FromJSON a => FromJSON (ListResponse a) where
+  parseJSON = genericParseJSON parseOptions . jsonLower
+
+instance ToJSON a => ToJSON (ListResponse a) where
+  toJSON ListResponse {..} =
+    object
+      [ "Resources" .= resources,
+        "schemas" .= schemas,
+        "totalResults" .= totalResults,
+        "itemsPerPage" .= itemsPerPage,
+        "startIndex" .= startIndex
+      ]
diff --git a/src/Web/Scim/Schema/Meta.hs b/src/Web/Scim/Schema/Meta.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/Meta.hs
@@ -0,0 +1,85 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.Meta where
+
+import Data.Aeson
+import qualified Data.HashMap.Lazy as HML
+import Data.Text (Text, pack, unpack)
+import qualified Data.Text as Text
+import Data.Time.Clock
+import GHC.Generics (Generic)
+import Text.Read (readEither)
+import Web.Scim.Schema.Common
+import Web.Scim.Schema.ResourceType
+import Prelude hiding (map)
+
+data ETag = Weak Text | Strong Text
+  deriving (Eq, Show)
+
+instance ToJSON ETag where
+  toJSON (Weak tag) = String $ "W/" <> pack (show tag)
+  toJSON (Strong tag) = String $ pack (show tag)
+
+instance FromJSON ETag where
+  parseJSON = withText "ETag" $ \s ->
+    case Text.stripPrefix "W/" s of
+      Nothing -> Strong <$> unquote s
+      Just s' -> Weak <$> unquote s'
+    where
+      unquote s = case readEither (unpack s) of
+        Right x -> pure x
+        Left e -> fail ("couldn't unquote the string: " <> e)
+
+data Meta = Meta
+  { resourceType :: ResourceType,
+    created :: UTCTime,
+    lastModified :: UTCTime,
+    -- | Resource version: <https://tools.ietf.org/html/rfc7644#section-3.14>.
+    --
+    -- A version is an /opaque/ string that doesn't need to conform to any
+    -- format (e.g. it does not have to be a monotonically increasing integer,
+    -- contrary to what the word @version@ suggests).
+    --
+    -- For 'Weak' versions we have to guarantee that different resources will
+    -- have different 'version's. For 'Strong' versions we also have to
+    -- guarantee that same resources will have the same 'version'.
+    version :: ETag,
+    location :: URI
+  }
+  deriving (Eq, Show, Generic)
+
+instance ToJSON Meta where
+  toJSON = genericToJSON serializeOptions
+
+instance FromJSON Meta where
+  parseJSON = genericParseJSON parseOptions . jsonLower
+
+data WithMeta a = WithMeta
+  { meta :: Meta,
+    thing :: a
+  }
+  deriving (Eq, Show, Generic)
+
+instance (ToJSON a) => ToJSON (WithMeta a) where
+  toJSON (WithMeta m v) = case toJSON v of
+    (Object o) -> Object (HML.insert "meta" (toJSON m) o)
+    other -> other
+
+instance (FromJSON a) => FromJSON (WithMeta a) where
+  parseJSON = withObject "WithMeta" $ \o ->
+    WithMeta <$> o .: "meta" <*> parseJSON (Object o)
diff --git a/src/Web/Scim/Schema/PatchOp.hs b/src/Web/Scim/Schema/PatchOp.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/PatchOp.hs
@@ -0,0 +1,147 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.PatchOp where
+
+import Control.Applicative
+import Control.Monad.Except
+import Data.Aeson.Types (FromJSON (parseJSON), ToJSON (toJSON), Value (String), object, withObject, withText, (.:), (.:?), (.=))
+import qualified Data.Aeson.Types as Aeson
+import Data.Attoparsec.ByteString (Parser, endOfInput, parseOnly)
+import Data.Bifunctor (first)
+import qualified Data.HashMap.Strict as HM
+import qualified Data.HashMap.Strict as HashMap
+import Data.Text (Text, toCaseFold, toLower)
+import Data.Text.Encoding (encodeUtf8)
+import Web.Scim.AttrName (AttrName (..))
+import Web.Scim.Filter (AttrPath (..), SubAttr (..), ValuePath (..), pAttrPath, pSubAttr, pValuePath, rAttrPath, rSubAttr, rValuePath)
+import Web.Scim.Schema.Error
+import Web.Scim.Schema.Schema (Schema (PatchOp20))
+import Web.Scim.Schema.UserTypes (UserTypes (supportedSchemas))
+
+newtype PatchOp tag = PatchOp
+  {getOperations :: [Operation]}
+  deriving (Eq, Show)
+
+-- | The 'Path' attribute value is a 'String' containing an attribute path
+-- describing the target of the operation.  It is OPTIONAL
+-- for 'Op's "add" and "replace", and is REQUIRED for "remove".  See
+-- relevant operation sections below for details.
+--
+-- TODO(arianvp):  When value is an array, it needs special handling.
+-- e.g. primary fields need to be negated and whatnot.
+-- We currently do not do that :)
+--
+-- NOTE: When the path contains a schema, this schema must be implicitly added
+-- to the list of schemas on the result type
+data Operation = Operation
+  { op :: Op,
+    path :: Maybe Path,
+    value :: Maybe Value
+  }
+  deriving (Eq, Show)
+
+data Op
+  = Add
+  | Replace
+  | Remove
+  deriving (Eq, Show, Enum, Bounded)
+
+-- | PATH = attrPath / valuePath [subAttr]
+data Path
+  = NormalPath AttrPath
+  | IntoValuePath ValuePath (Maybe SubAttr)
+  deriving (Eq, Show)
+
+parsePath :: [Schema] -> Text -> Either String Path
+parsePath schemas' = parseOnly (pPath schemas' <* endOfInput) . encodeUtf8
+
+-- | PATH = attrPath / valuePath [subAttr]
+pPath :: [Schema] -> Parser Path
+pPath schemas' =
+  IntoValuePath <$> pValuePath schemas' <*> optional pSubAttr
+    <|> NormalPath <$> pAttrPath schemas'
+
+rPath :: Path -> Text
+rPath (NormalPath attrPath) = rAttrPath attrPath
+rPath (IntoValuePath valuePath subAttr) = rValuePath valuePath <> maybe "" rSubAttr subAttr
+
+-- TODO(arianvp): According to the SCIM spec we should throw an InvalidPath
+-- error when the path is invalid syntax. this is a bit hard to do though as we
+-- can't control what errors FromJSON throws :/
+instance UserTypes tag => FromJSON (PatchOp tag) where
+  parseJSON = withObject "PatchOp" $ \v -> do
+    let o = HashMap.fromList . map (first toLower) . HashMap.toList $ v
+    schemas' :: [Schema] <- o .: "schemas"
+    guard $ PatchOp20 `elem` schemas'
+    operations <- Aeson.explicitParseField (Aeson.listParser $ operationFromJSON (supportedSchemas @tag)) o "operations"
+    pure $ PatchOp operations
+
+instance ToJSON (PatchOp tag) where
+  toJSON (PatchOp operations) =
+    object ["operations" .= operations, "schemas" .= [PatchOp20]]
+
+-- TODO: Azure wants us to be case-insensitive on _values_ as well here.  We currently do not
+-- comply with that.
+operationFromJSON :: [Schema] -> Value -> Aeson.Parser Operation
+operationFromJSON schemas' =
+  withObject "Operation" $ \v -> do
+    let o = HashMap.fromList . map (first toLower) . HashMap.toList $ v
+    Operation
+      <$> (o .: "op")
+      <*> (Aeson.explicitParseFieldMaybe (pathFromJSON schemas') o "path")
+      <*> (o .:? "value")
+
+pathFromJSON :: [Schema] -> Value -> Aeson.Parser Path
+pathFromJSON schemas' =
+  withText "Path" $ either fail pure . (parsePath schemas')
+
+instance ToJSON Operation where
+  toJSON (Operation op' path' value') =
+    object $ ("op" .= op') : concat [optionalField "path" path', optionalField "value" value']
+    where
+      optionalField fname = \case
+        Nothing -> []
+        Just x -> [fname .= x]
+
+instance FromJSON Op where
+  parseJSON = withText "Op" $ \op' ->
+    case toCaseFold op' of
+      "add" -> pure Add
+      "replace" -> pure Replace
+      "remove" -> pure Remove
+      _ -> fail "unknown operation"
+
+instance ToJSON Op where
+  toJSON Add = String "add"
+  toJSON Replace = String "replace"
+  toJSON Remove = String "remove"
+
+instance ToJSON Path where
+  toJSON = String . rPath
+
+-- | A very coarse description of what it means to be 'Patchable'
+-- I do not like it. We should handhold people using this library more
+class Patchable a where
+  applyOperation :: (MonadError ScimError m) => a -> Operation -> m a
+
+instance Patchable (HM.HashMap Text Text) where
+  applyOperation theMap (Operation Remove (Just (NormalPath (AttrPath _schema (AttrName attrName) _subAttr))) _) =
+    pure $ HM.delete attrName theMap
+  applyOperation theMap (Operation _AddOrReplace (Just (NormalPath (AttrPath _schema (AttrName attrName) _subAttr))) (Just (String val))) =
+    pure $ HM.insert attrName val theMap
+  applyOperation _ _ = throwError $ badRequest InvalidValue $ Just "Unsupported operation"
diff --git a/src/Web/Scim/Schema/ResourceType.hs b/src/Web/Scim/Schema/ResourceType.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/ResourceType.hs
@@ -0,0 +1,78 @@
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.ResourceType where
+
+import Data.Aeson
+import Data.Text (Text)
+import GHC.Generics (Generic)
+import Network.URI.Static
+import Web.Scim.Schema.Common
+import Web.Scim.Schema.Schema (Schema (..))
+import Prelude hiding (map)
+
+-- | Supported resource types. Each resource type also corresponds to an
+-- endpoint, described by 'ResourceTypeEndpoint'.
+data ResourceType
+  = UserResource
+  | GroupResource
+  deriving (Show, Eq)
+
+instance ToJSON ResourceType where
+  toJSON UserResource = "User"
+  toJSON GroupResource = "Group"
+
+instance FromJSON ResourceType where
+  parseJSON = withText "ResourceType" $ \case
+    "User" -> pure UserResource
+    "Group" -> pure GroupResource
+    other -> fail ("unknown ResourceType: " ++ show other)
+
+-- | Definitions of endpoints, returned by @/ResourceTypes@.
+data Resource = Resource
+  { name :: Text,
+    endpoint :: URI,
+    schema :: Schema
+  }
+  deriving (Show, Eq, Generic)
+
+instance ToJSON Resource where
+  toJSON = genericToJSON serializeOptions
+
+instance FromJSON Resource where
+  parseJSON = genericParseJSON parseOptions . jsonLower
+
+----------------------------------------------------------------------------
+-- Available resource endpoints
+
+usersResource :: Resource
+usersResource =
+  Resource
+    { name = "User",
+      endpoint = URI [relativeReference|/Users|],
+      schema = User20
+    }
+
+groupsResource :: Resource
+groupsResource =
+  Resource
+    { name = "Group",
+      endpoint = URI [relativeReference|/Groups|],
+      schema = Group20
+    }
diff --git a/src/Web/Scim/Schema/Schema.hs b/src/Web/Scim/Schema/Schema.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/Schema.hs
@@ -0,0 +1,134 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.Schema where
+
+import Data.Aeson (FromJSON, ToJSON, Value, parseJSON, toJSON, withText)
+import Data.Attoparsec.ByteString (Parser)
+import qualified Data.Attoparsec.ByteString.Char8 as Parser
+import Data.Text (Text)
+import Data.Text.Encoding (decodeUtf8, encodeUtf8)
+import Web.Scim.Capabilities.MetaSchema.Group
+import Web.Scim.Capabilities.MetaSchema.ResourceType
+import Web.Scim.Capabilities.MetaSchema.SPConfig
+import Web.Scim.Capabilities.MetaSchema.Schema
+import Web.Scim.Capabilities.MetaSchema.User
+
+-- | All schemas that we support.
+data Schema
+  = User20
+  | ServiceProviderConfig20
+  | Group20
+  | Schema20
+  | ResourceType20
+  | ListResponse20
+  | Error20
+  | PatchOp20
+  | CustomSchema Text
+  deriving (Show, Eq)
+
+instance FromJSON Schema where
+  parseJSON = withText "schema" $ \t -> pure (fromSchemaUri t)
+
+instance ToJSON Schema where
+  toJSON = toJSON . getSchemaUri
+
+-- | Get schema URI (e.g. @urn:ietf:params:scim:schemas:core:2.0:User@).
+getSchemaUri :: Schema -> Text
+getSchemaUri User20 =
+  "urn:ietf:params:scim:schemas:core:2.0:User"
+getSchemaUri ServiceProviderConfig20 =
+  "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"
+getSchemaUri Group20 =
+  "urn:ietf:params:scim:schemas:core:2.0:Group"
+getSchemaUri Schema20 =
+  "urn:ietf:params:scim:schemas:core:2.0:Schema"
+getSchemaUri ResourceType20 =
+  "urn:ietf:params:scim:schemas:core:2.0:ResourceType"
+getSchemaUri ListResponse20 =
+  "urn:ietf:params:scim:api:messages:2.0:ListResponse"
+getSchemaUri Error20 =
+  "urn:ietf:params:scim:api:messages:2.0:Error"
+getSchemaUri PatchOp20 =
+  "urn:ietf:params:scim:api:messages:2.0:PatchOp"
+getSchemaUri (CustomSchema x) =
+  x
+
+-- TODO(akshay): Make everything Text, ByteStrings are unnecessary here
+
+-- | Parser for schemas
+--
+-- NOTE: according to the spec, this parser needs to be case insensitive, but
+-- that is literally insane. Won't implement.
+pSchema :: [Schema] -> Parser Schema
+pSchema supportedSchemas =
+  Parser.choice $
+    map (\s -> fromSchemaUri . decodeUtf8 <$> Parser.string (encodeUtf8 $ getSchemaUri s)) supportedSchemas
+
+-- | Get a schema by its URI.
+--
+-- NOTE: case sensitive against the spec.  Same as 'pSchema'.
+--
+-- TODO(arianvp): probably too lenient. want to only accept valid URNs
+-- This means the CustomSchema part might go... We need to kind of
+-- rethink how we're  gonna do extensions anyway, as we're gonna have to
+-- support multiple extensions, which is currently a bit iffy I think
+fromSchemaUri :: Text -> Schema
+fromSchemaUri s = case s of
+  "urn:ietf:params:scim:schemas:core:2.0:User" ->
+    User20
+  "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig" ->
+    ServiceProviderConfig20
+  "urn:ietf:params:scim:schemas:core:2.0:Group" ->
+    Group20
+  "urn:ietf:params:scim:schemas:core:2.0:Schema" ->
+    Schema20
+  "urn:ietf:params:scim:schemas:core:2.0:ResourceType" ->
+    ResourceType20
+  "urn:ietf:params:scim:api:messages:2.0:ListResponse" ->
+    ListResponse20
+  "urn:ietf:params:scim:api:messages:2.0:Error" ->
+    Error20
+  "urn:ietf:params:scim:api:messages:2.0:PatchOp" ->
+    PatchOp20
+  x ->
+    CustomSchema x
+
+-- | Get schema description as JSON.
+getSchema :: Schema -> Maybe Value
+getSchema ServiceProviderConfig20 =
+  pure spConfigSchema
+getSchema User20 =
+  pure userSchema
+getSchema Group20 =
+  pure groupSchema
+getSchema Schema20 =
+  pure metaSchema
+getSchema ResourceType20 =
+  pure resourceSchema
+-- Schemas for these types are not in the SCIM standard.
+-- FUTUREWORK: write schema definitions anyway.
+getSchema ListResponse20 =
+  Nothing
+getSchema Error20 =
+  Nothing
+getSchema PatchOp20 =
+  Nothing
+-- This is not controlled by @hscim@ so we can't write a schema.
+-- FUTUREWORK: allow supplying schemas for 'CustomSchema'.
+getSchema (CustomSchema _) =
+  Nothing
diff --git a/src/Web/Scim/Schema/User.hs b/src/Web/Scim/Schema/User.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/User.hs
@@ -0,0 +1,359 @@
+{-# LANGUAGE GADTs #-}
+{-# LANGUAGE RecordWildCards #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE StandaloneDeriving #-}
+{-# LANGUAGE UndecidableInstances #-}
+{-# LANGUAGE ViewPatterns #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+-- | SCIM user representation.
+--
+-- = Our interpretation of the spec
+--
+-- The spec can be read at <https://tools.ietf.org/html/rfc7643#section-4.1>.
+-- While implementing the spec we had to resolve some ambiguities and place some
+-- additional constraints on the possible SCIM server behavior we can support.
+--
+-- == Resource ID / user ID
+--
+-- The 'User' object doesn't contain a user ID (as in "opaque server-assigned
+-- immutable ID") by design. IDs and metadata are added to types in a uniform
+-- fashion by using @WithId@ and @WithMeta@.
+--
+-- == Optional fields
+--
+-- The spec only mandates the @userName@ and @id@ attribute. All other
+-- attributes seem optional.
+--
+-- == Multi-valued fields
+--
+-- When a multi-valued field (e.g. @emails@) doesn't contain any values, it's
+-- unclear whether we should serialize it as @[]@ or omit it entirely. We have
+-- opted for the latter to conform to an example in the spec:
+-- <https://tools.ietf.org/html/rfc7644#section-3.5.1>.
+--
+-- TODO(arianvp):
+--  Multi-valued attributes actually have some more quirky semantics that we
+--  currently don't support yet. E.g. if the multi-values have a
+--  'primary' field then only one of the entires must have 'primary: true'
+--  and all the others are either implied 'primary: false' or must be checked
+--  that they're false
+--
+--
+-- == Attribute names
+--
+-- When parsing JSON objects, we ignore capitalization differences in field
+-- names -- e.g. both @USERNAME@ and @userName@ are accepted.
+--  This is described by the spec  https://tools.ietf.org/html/rfc7643#section-2.1
+module Web.Scim.Schema.User
+  ( User (..),
+    empty,
+    NoUserExtra (..),
+    applyPatch,
+    resultToScimError,
+    isUserSchema,
+    module Web.Scim.Schema.UserTypes,
+  )
+where
+
+import Control.Monad.Except
+import Data.Aeson
+import qualified Data.HashMap.Strict as HM
+import Data.List ((\\))
+import Data.Text (Text, pack, toLower)
+import qualified Data.Text as Text
+import GHC.Generics (Generic)
+import Lens.Micro
+import Web.Scim.AttrName
+import Web.Scim.Filter (AttrPath (..))
+import Web.Scim.Schema.Common
+import Web.Scim.Schema.Error
+import Web.Scim.Schema.PatchOp
+import Web.Scim.Schema.Schema (Schema (..), getSchemaUri)
+import Web.Scim.Schema.User.Address (Address)
+import Web.Scim.Schema.User.Certificate (Certificate)
+import Web.Scim.Schema.User.Email (Email)
+import Web.Scim.Schema.User.IM (IM)
+import Web.Scim.Schema.User.Name (Name)
+import Web.Scim.Schema.User.Phone (Phone)
+import Web.Scim.Schema.User.Photo (Photo)
+import Web.Scim.Schema.UserTypes
+
+-- | SCIM user record, parametrized with type-level tag @t@ (see 'UserTypes').
+data User tag = User
+  { schemas :: [Schema],
+    -- Mandatory fields
+    userName :: Text,
+    -- Optional fields
+    externalId :: Maybe Text,
+    name :: Maybe Name,
+    displayName :: Maybe Text,
+    nickName :: Maybe Text,
+    profileUrl :: Maybe URI,
+    title :: Maybe Text,
+    userType :: Maybe Text,
+    preferredLanguage :: Maybe Text,
+    locale :: Maybe Text,
+    active :: Maybe ScimBool,
+    password :: Maybe Text,
+    -- Multi-valued fields
+    emails :: [Email],
+    phoneNumbers :: [Phone],
+    ims :: [IM],
+    photos :: [Photo],
+    addresses :: [Address],
+    entitlements :: [Text],
+    roles :: [Text],
+    x509Certificates :: [Certificate],
+    -- Extra data.
+    --
+    -- During rendering, we'll convert it to JSON; if it's an object we'll merge it with the
+    -- main user object, if it's @null@ we'll do nothing, otherwise we'll add it under the
+    -- @"extra"@ field (though you should definitely not rely on this).
+    --
+    -- During parsing, we'll attempt to parse the /whole/ user object as @extra@, so your
+    -- 'FromJSON' instance should be prepared to ignore unrelated fields. Also keep in mind that
+    -- the SCIM spec requires field names to be case-insensitive, i.e. if you're looking for a
+    -- field "foo" you should also handle a field called "FOO". Look at the @FromJSON User@
+    -- instance to see how it can be done.
+    --
+    -- FUTUREWORK: make it easy for hscim users to implement a proper parser (with correct
+    -- rendering of optional and multivalued fields, lowercase objects, etc).
+    extra :: UserExtra tag
+  }
+  deriving (Generic)
+
+deriving instance Show (UserExtra tag) => Show (User tag)
+
+deriving instance Eq (UserExtra tag) => Eq (User tag)
+
+empty ::
+  -- | Schemas
+  [Schema] ->
+  -- | userName
+  Text ->
+  -- | Extra data
+  UserExtra tag ->
+  User tag
+empty schemas userName extra =
+  User
+    { schemas = schemas,
+      userName = userName,
+      externalId = Nothing,
+      name = Nothing,
+      displayName = Nothing,
+      nickName = Nothing,
+      profileUrl = Nothing,
+      title = Nothing,
+      userType = Nothing,
+      preferredLanguage = Nothing,
+      locale = Nothing,
+      active = Nothing,
+      password = Nothing,
+      emails = [],
+      phoneNumbers = [],
+      ims = [],
+      photos = [],
+      addresses = [],
+      entitlements = [],
+      roles = [],
+      x509Certificates = [],
+      extra = extra
+    }
+
+instance FromJSON (UserExtra tag) => FromJSON (User tag) where
+  parseJSON = withObject "User" $ \obj -> do
+    -- Lowercase all fields
+    let o = HM.fromList . map (over _1 toLower) . HM.toList $ obj
+    schemas <-
+      o .:? "schemas" <&> \case
+        Nothing -> [User20]
+        Just xs -> if User20 `elem` xs then xs else User20 : xs
+    userName <- o .: "username"
+    externalId <- o .:? "externalid"
+    name <- o .:? "name"
+    displayName <- o .:? "displayname"
+    nickName <- o .:? "nickname"
+    profileUrl <- o .:? "profileurl"
+    title <- o .:? "title"
+    userType <- o .:? "usertype"
+    preferredLanguage <- o .:? "preferredlanguage"
+    locale <- o .:? "locale"
+    active <- o .:? "active"
+    password <- o .:? "password"
+    emails <- o .:? "emails" .!= []
+    phoneNumbers <- o .:? "phonenumbers" .!= []
+    ims <- o .:? "ims" .!= []
+    photos <- o .:? "photos" .!= []
+    addresses <- o .:? "addresses" .!= []
+    entitlements <- o .:? "entitlements" .!= []
+    roles <- o .:? "roles" .!= []
+    x509Certificates <- o .:? "x509certificates" .!= []
+    extra <- parseJSON (Object obj)
+    pure User {..}
+
+instance ToJSON (UserExtra tag) => ToJSON (User tag) where
+  toJSON User {..} =
+    let mainObject =
+          HM.fromList $
+            concat
+              [ ["schemas" .= schemas],
+                ["userName" .= userName],
+                optionalField "externalId" externalId,
+                optionalField "name" name,
+                optionalField "displayName" displayName,
+                optionalField "nickName" nickName,
+                optionalField "profileUrl" profileUrl,
+                optionalField "title" title,
+                optionalField "userType" userType,
+                optionalField "preferredLanguage" preferredLanguage,
+                optionalField "locale" locale,
+                optionalField "active" active,
+                optionalField "password" password,
+                multiValuedField "emails" emails,
+                multiValuedField "phoneNumbers" phoneNumbers,
+                multiValuedField "ims" ims,
+                multiValuedField "photos" photos,
+                multiValuedField "addresses" addresses,
+                multiValuedField "entitlements" entitlements,
+                multiValuedField "roles" roles,
+                multiValuedField "x509Certificates" x509Certificates
+              ]
+        extraObject = case toJSON extra of
+          Null -> mempty
+          Object x -> x
+          other -> HM.fromList ["extra" .= other]
+     in Object (HM.union mainObject extraObject)
+    where
+      -- Omit a field if it's Nothing
+      optionalField fname = \case
+        Nothing -> []
+        Just x -> [fname .= x]
+      -- Omit a field if it's []
+      multiValuedField fname = \case
+        [] -> []
+        xs -> [fname .= xs]
+
+-- | A type used to indicate that the SCIM record doesn't have any extra data. Encoded as an
+-- empty map.
+data NoUserExtra = NoUserExtra
+  deriving (Eq, Show)
+
+instance FromJSON NoUserExtra where
+  parseJSON = withObject "NoUserExtra" $ \_ -> pure NoUserExtra
+
+instance ToJSON NoUserExtra where
+  toJSON _ = object []
+
+instance Patchable NoUserExtra where
+  applyOperation _ _ = throwError $ badRequest InvalidValue (Just "there are no user extra attributes to patch")
+
+----------------------------------------------------------------------------
+-- Applying
+
+-- | Applies a JSON Patch to a SCIM Core User
+-- Only supports the core attributes.
+-- Evenmore, only some hand-picked ones currently.
+-- We'll have to think how patch is going to work in the presence of extensions.
+-- Also, we can probably make  PatchOp type-safe to some extent (Read arianvp's thesis :))
+applyPatch ::
+  ( Patchable (UserExtra tag),
+    FromJSON (UserExtra tag),
+    MonadError ScimError m,
+    UserTypes tag
+  ) =>
+  User tag ->
+  PatchOp tag ->
+  m (User tag)
+applyPatch = (. getOperations) . foldM applyOperation
+
+resultToScimError :: (MonadError ScimError m) => Result a -> m a
+resultToScimError (Error reason) = throwError $ badRequest InvalidValue (Just (pack reason))
+resultToScimError (Success a) = pure a
+
+-- TODO(arianvp): support multi-valued and complex attributes.
+-- TODO(arianvp): Actually do this in some kind of type-safe way. e.g.
+-- have a UserPatch type.
+--
+-- What I understand from the spec:  The difference between add an replace is only
+-- in the fact that replace will not concat multi-values, and behaves differently for complex values too.
+-- For simple attributes, add and replace are identical.
+applyUserOperation ::
+  forall m tag.
+  ( UserTypes tag,
+    FromJSON (User tag),
+    Patchable (UserExtra tag),
+    MonadError ScimError m
+  ) =>
+  User tag ->
+  Operation ->
+  m (User tag)
+applyUserOperation user (Operation Add path value) = applyUserOperation user (Operation Replace path value)
+applyUserOperation user (Operation Replace (Just (NormalPath (AttrPath _schema attr _subAttr))) (Just value)) =
+  case attr of
+    "username" ->
+      (\x -> user {userName = x}) <$> resultToScimError (fromJSON value)
+    "displayname" ->
+      (\x -> user {displayName = x}) <$> resultToScimError (fromJSON value)
+    "externalid" ->
+      (\x -> user {externalId = x}) <$> resultToScimError (fromJSON value)
+    "active" ->
+      (\x -> user {active = x}) <$> resultToScimError (fromJSON value)
+    _ -> throwError (badRequest InvalidPath (Just "we only support attributes username, displayname, externalid, active"))
+applyUserOperation _ (Operation Replace (Just (IntoValuePath _ _)) _) = do
+  throwError (badRequest InvalidPath (Just "can not lens into multi-valued attributes yet"))
+applyUserOperation user (Operation Replace Nothing (Just value)) = do
+  case value of
+    Object hm | null ((AttrName <$> HM.keys hm) \\ ["username", "displayname", "externalid", "active"]) -> do
+      (u :: User tag) <- resultToScimError $ fromJSON value
+      pure $
+        user
+          { userName = userName u,
+            displayName = displayName u,
+            externalId = externalId u,
+            active = active u
+          }
+    _ -> throwError (badRequest InvalidPath (Just "we only support attributes username, displayname, externalid, active"))
+applyUserOperation _ (Operation Replace _ Nothing) =
+  throwError (badRequest InvalidValue (Just "No value was provided"))
+applyUserOperation _ (Operation Remove Nothing _) = throwError (badRequest NoTarget Nothing)
+applyUserOperation user (Operation Remove (Just (NormalPath (AttrPath _schema attr _subAttr))) _value) =
+  case attr of
+    "username" -> throwError (badRequest Mutability Nothing)
+    "displayname" -> pure $ user {displayName = Nothing}
+    "externalid" -> pure $ user {externalId = Nothing}
+    "active" -> pure $ user {active = Nothing}
+    _ -> pure user
+applyUserOperation _ (Operation Remove (Just (IntoValuePath _ _)) _) = do
+  throwError (badRequest InvalidPath (Just "can not lens into multi-valued attributes yet"))
+
+instance (UserTypes tag, FromJSON (User tag), Patchable (UserExtra tag)) => Patchable (User tag) where
+  applyOperation user op@(Operation _ (Just (NormalPath (AttrPath schema _ _))) _)
+    | isUserSchema schema = applyUserOperation user op
+    | isSupportedCustomSchema schema = (\x -> user {extra = x}) <$> applyOperation (extra user) op
+    | otherwise =
+      throwError $ badRequest InvalidPath $ Just $ "we only support these schemas: " <> (Text.intercalate ", " $ map getSchemaUri (supportedSchemas @tag))
+    where
+      isSupportedCustomSchema = maybe False (`elem` supportedSchemas @tag)
+  applyOperation user op = applyUserOperation user op
+
+-- Omission of a schema for users is implicitly the core schema
+-- TODO(arianvp): Link to part of the spec that claims this.
+isUserSchema :: Maybe Schema -> Bool
+isUserSchema = maybe True (== User20)
diff --git a/src/Web/Scim/Schema/User/Address.hs b/src/Web/Scim/Schema/User/Address.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/User/Address.hs
@@ -0,0 +1,42 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.User.Address where
+
+import Data.Aeson
+import Data.Text hiding (dropWhile)
+import GHC.Generics (Generic)
+import Web.Scim.Schema.Common
+
+data Address = Address
+  { formatted :: Maybe Text,
+    streetAddress :: Maybe Text,
+    locality :: Maybe Text,
+    region :: Maybe Text,
+    postalCode :: Maybe Text,
+    -- TODO: country is specified as ISO3166, but example uses "USA"
+    country :: Maybe Text,
+    typ :: Maybe Text,
+    primary :: Maybe ScimBool
+  }
+  deriving (Show, Eq, Generic)
+
+instance FromJSON Address where
+  parseJSON = genericParseJSON parseOptions . jsonLower
+
+instance ToJSON Address where
+  toJSON = genericToJSON serializeOptions
diff --git a/src/Web/Scim/Schema/User/Certificate.hs b/src/Web/Scim/Schema/User/Certificate.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/User/Certificate.hs
@@ -0,0 +1,35 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.User.Certificate where
+
+import Data.Aeson
+import Data.Text (Text)
+import GHC.Generics
+import Web.Scim.Schema.Common
+
+data Certificate = Certificate
+  { typ :: Maybe Text,
+    value :: Maybe Text
+  }
+  deriving (Show, Eq, Generic)
+
+instance FromJSON Certificate where
+  parseJSON = genericParseJSON parseOptions . jsonLower
+
+instance ToJSON Certificate where
+  toJSON = genericToJSON serializeOptions
diff --git a/src/Web/Scim/Schema/User/Email.hs b/src/Web/Scim/Schema/User/Email.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/User/Email.hs
@@ -0,0 +1,50 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.User.Email where
+
+import Data.Aeson
+import Data.Text hiding (dropWhile)
+import Data.Text.Encoding (decodeUtf8, encodeUtf8)
+import GHC.Generics (Generic)
+import Text.Email.Validate
+import Web.Scim.Schema.Common
+
+newtype EmailAddress2 = EmailAddress2
+  {unEmailAddress :: EmailAddress}
+  deriving (Show, Eq)
+
+instance FromJSON EmailAddress2 where
+  parseJSON = withText "Email" $ \e -> case emailAddress (encodeUtf8 e) of
+    Nothing -> fail "Invalid email"
+    Just some -> pure $ EmailAddress2 some
+
+instance ToJSON EmailAddress2 where
+  toJSON (EmailAddress2 e) = String $ decodeUtf8 . toByteString $ e
+
+data Email = Email
+  { typ :: Maybe Text,
+    value :: EmailAddress2,
+    primary :: Maybe ScimBool
+  }
+  deriving (Show, Eq, Generic)
+
+instance FromJSON Email where
+  parseJSON = genericParseJSON parseOptions . jsonLower
+
+instance ToJSON Email where
+  toJSON = genericToJSON serializeOptions
diff --git a/src/Web/Scim/Schema/User/IM.hs b/src/Web/Scim/Schema/User/IM.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/User/IM.hs
@@ -0,0 +1,35 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.User.IM where
+
+import Data.Aeson
+import Data.Text (Text)
+import GHC.Generics
+import Web.Scim.Schema.Common
+
+data IM = IM
+  { typ :: Maybe Text,
+    value :: Maybe Text
+  }
+  deriving (Show, Eq, Generic)
+
+instance FromJSON IM where
+  parseJSON = genericParseJSON parseOptions . jsonLower
+
+instance ToJSON IM where
+  toJSON = genericToJSON serializeOptions
diff --git a/src/Web/Scim/Schema/User/Name.hs b/src/Web/Scim/Schema/User/Name.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/User/Name.hs
@@ -0,0 +1,42 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.User.Name where
+
+import Data.Aeson
+import Data.Text (Text)
+import GHC.Generics
+import Web.Scim.Schema.Common
+
+data Name = Name
+  { formatted :: Maybe Text,
+    familyName :: Maybe Text,
+    givenName :: Maybe Text,
+    middleName :: Maybe Text,
+    honorificPrefix :: Maybe Text,
+    honorificSuffix :: Maybe Text
+  }
+  deriving (Show, Eq, Generic)
+
+emptyName :: Name
+emptyName = Name Nothing Nothing Nothing Nothing Nothing Nothing
+
+instance FromJSON Name where
+  parseJSON = genericParseJSON parseOptions . jsonLower
+
+instance ToJSON Name where
+  toJSON = genericToJSON serializeOptions
diff --git a/src/Web/Scim/Schema/User/Phone.hs b/src/Web/Scim/Schema/User/Phone.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/User/Phone.hs
@@ -0,0 +1,35 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.User.Phone where
+
+import Data.Aeson
+import Data.Text hiding (dropWhile)
+import GHC.Generics (Generic)
+import Web.Scim.Schema.Common
+
+data Phone = Phone
+  { typ :: Maybe Text,
+    value :: Maybe Text
+  }
+  deriving (Show, Eq, Ord, Generic)
+
+instance FromJSON Phone where
+  parseJSON = genericParseJSON parseOptions . jsonLower
+
+instance ToJSON Phone where
+  toJSON = genericToJSON serializeOptions
diff --git a/src/Web/Scim/Schema/User/Photo.hs b/src/Web/Scim/Schema/User/Photo.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/User/Photo.hs
@@ -0,0 +1,35 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.User.Photo where
+
+import Data.Aeson
+import Data.Text (Text)
+import GHC.Generics
+import Web.Scim.Schema.Common
+
+data Photo = Photo
+  { typ :: Maybe Text,
+    value :: Maybe URI
+  }
+  deriving (Show, Eq, Generic)
+
+instance FromJSON Photo where
+  parseJSON = genericParseJSON parseOptions . jsonLower
+
+instance ToJSON Photo where
+  toJSON = genericToJSON serializeOptions
diff --git a/src/Web/Scim/Schema/UserTypes.hs b/src/Web/Scim/Schema/UserTypes.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Schema/UserTypes.hs
@@ -0,0 +1,35 @@
+{-# LANGUAGE AllowAmbiguousTypes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Schema.UserTypes where
+
+import Web.Scim.Schema.Schema (Schema)
+
+-- | Configurable parts of 'User'.
+class UserTypes tag where
+  -- | User ID type.
+  type UserId tag
+
+  -- | Extra data carried with each 'User'.
+  type UserExtra tag
+
+  -- | Schemas supported by the 'User' for filtering and patching.
+  --
+  -- This must include User20, this is not checked.
+  supportedSchemas :: [Schema]
diff --git a/src/Web/Scim/Server.hs b/src/Web/Scim/Server.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Server.hs
@@ -0,0 +1,127 @@
+{-# LANGUAGE AllowAmbiguousTypes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Server
+  ( -- * WAI application
+    app,
+    mkapp,
+    App,
+
+    -- * API tree
+    SiteAPI,
+    siteServer,
+
+    -- ** API subtrees, useful for tests
+    ConfigAPI,
+    configServer,
+    UserAPI,
+    userServer,
+    GroupAPI,
+    groupServer,
+  )
+where
+
+import Network.Wai
+import Servant
+import Servant.API.Generic
+import Servant.Server.Generic
+import Web.Scim.Capabilities.MetaSchema (ConfigSite, Configuration, configServer)
+import Web.Scim.Class.Auth (AuthDB (..), AuthTypes (..))
+import Web.Scim.Class.Group (GroupDB, GroupSite (..), GroupTypes (..), groupServer)
+import Web.Scim.Class.User (UserDB (..), UserSite (..), userServer)
+import Web.Scim.Handler
+
+----------------------------------------------------------------------------
+-- API specification
+
+-- | A constraint indicating that monad @m@ supports operations with users and groups marked
+-- with tag @t@.
+type DB tag m = (UserDB tag m, GroupDB tag m, AuthDB tag m)
+
+type ConfigAPI = ToServantApi ConfigSite
+
+type UserAPI tag = ToServantApi (UserSite tag)
+
+type GroupAPI tag = ToServantApi (GroupSite tag)
+
+type SiteAPI tag = ToServantApi (Site tag)
+
+data Site tag route = Site
+  { config ::
+      route
+        :- ConfigAPI,
+    users ::
+      route
+        :- Header "Authorization" (AuthData tag)
+        :> "Users"
+        :> UserAPI tag,
+    groups ::
+      route
+        :- Header "Authorization" (AuthData tag)
+        :> "Groups"
+        :> GroupAPI tag
+  }
+  deriving (Generic)
+
+----------------------------------------------------------------------------
+-- API implementation
+
+siteServer ::
+  forall tag m.
+  (DB tag m, Show (GroupId tag)) =>
+  Configuration ->
+  Site tag (AsServerT (ScimHandler m))
+siteServer conf =
+  Site
+    { config = toServant $ configServer conf,
+      users = \authData -> toServant (userServer @tag authData),
+      groups = \authData -> toServant (groupServer @tag authData)
+    }
+  where
+
+----------------------------------------------------------------------------
+-- Server-starting utilities
+
+type App tag m api =
+  ( DB tag m,
+    Show (GroupId tag),
+    HasServer api '[]
+  )
+
+mkapp ::
+  forall tag m api.
+  (App tag m api) =>
+  Proxy api ->
+  ServerT api (ScimHandler m) ->
+  (forall a. ScimHandler m a -> Handler a) ->
+  Application
+mkapp proxy api nt =
+  serve proxy $
+    hoistServer proxy nt api
+
+app ::
+  forall tag m.
+  App tag m (SiteAPI tag) =>
+  Configuration ->
+  (forall a. ScimHandler m a -> Handler a) ->
+  Application
+app c =
+  mkapp @tag
+    (Proxy @(SiteAPI tag))
+    (toServant $ siteServer c)
diff --git a/src/Web/Scim/Server/Mock.hs b/src/Web/Scim/Server/Mock.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Server/Mock.hs
@@ -0,0 +1,253 @@
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+-- | A mock server for use in our testsuite, as well as for automated
+-- compliance testing (e.g. with Runscope – see
+-- <https://developer.okta.com/standards/SCIM/#step-2-test-your-scim-server>).
+module Web.Scim.Server.Mock where
+
+import Control.Monad.Morph
+import Control.Monad.Reader
+import Control.Monad.STM (STM, atomically)
+import Data.Aeson
+import Data.Hashable
+import Data.Text (Text, pack, toCaseFold)
+import Data.Time.Calendar
+import Data.Time.Clock
+import GHC.Exts (sortWith)
+import ListT
+import qualified Network.URI as URI
+import Servant
+import qualified StmContainers.Map as STMMap
+import Text.Read (readMaybe)
+import Web.Scim.Class.Auth
+import Web.Scim.Class.Group hiding (value)
+import Web.Scim.Class.User
+import Web.Scim.Filter (AttrPath (..), CompValue (..), Filter (..), compareStr)
+import Web.Scim.Handler
+import Web.Scim.Schema.Common (WithId (WithId, value))
+import qualified Web.Scim.Schema.Common as Common
+import Web.Scim.Schema.Error
+import Web.Scim.Schema.ListResponse
+import Web.Scim.Schema.Meta
+import Web.Scim.Schema.ResourceType
+import Web.Scim.Schema.Schema (Schema (User20))
+import Web.Scim.Schema.User
+
+-- | Tag used in the mock server.
+data Mock
+
+-- | A simple ID type.
+--
+-- >>> eitherDecode' @Id . encode $ (Id 3)
+-- Right (Id {unId = 3})
+--
+-- WARNING: {doctests don't work in our
+-- infrastructure](https://github.com/zinfra/backend-issues/issues/1549), so this is
+-- duplicated in the unit tests.
+newtype Id = Id {unId :: Int}
+  deriving (Eq, Show, Ord, Hashable, ToHttpApiData, FromHttpApiData)
+
+instance ToJSON Id where
+  toJSON = toJSON . show . unId
+
+instance FromJSON Id where
+  parseJSON = maybe (fail "not a number") (pure . Id) . readMaybe <=< parseJSON
+
+type UserStorage = STMMap.Map Id (StoredUser Mock)
+
+type GroupStorage = STMMap.Map Id (StoredGroup Mock)
+
+data TestStorage = TestStorage
+  { userDB :: UserStorage,
+    groupDB :: GroupStorage
+  }
+
+emptyTestStorage :: IO TestStorage
+emptyTestStorage =
+  TestStorage <$> STMMap.newIO <*> STMMap.newIO
+
+-- in-memory implementation of the API for tests
+type TestServer = ReaderT TestStorage Handler
+
+liftSTM :: MonadIO m => STM a -> m a
+liftSTM = liftIO . atomically
+
+hoistSTM :: (MFunctor t, MonadIO m) => t STM a -> t m a
+hoistSTM = hoist liftSTM
+
+----------------------------------------------------------------------------
+-- UserDB
+
+instance UserTypes Mock where
+  type UserId Mock = Id
+  type UserExtra Mock = NoUserExtra
+  supportedSchemas = [User20]
+
+instance UserDB Mock TestServer where
+  getUsers () mbFilter = do
+    m <- userDB <$> ask
+    users <- liftSTM $ ListT.toList $ STMMap.listT m
+    let check user = case mbFilter of
+          Nothing -> pure True
+          Just filter_ -> do
+            let user' = value (thing user) -- unwrap
+            case filterUser filter_ user' of
+              Right res -> pure res
+              Left err -> throwScim (badRequest InvalidFilter (Just err))
+    fromList . sortWith (Common.id . thing) <$> filterM check (snd <$> users)
+
+  getUser () uid = do
+    m <- userDB <$> ask
+    liftSTM (STMMap.lookup uid m) >>= \case
+      Nothing -> throwScim (notFound "User" (pack (show uid)))
+      Just x -> pure x
+
+  postUser () user = do
+    m <- userDB <$> ask
+    uid <- Id <$> liftSTM (STMMap.size m)
+    let newUser = WithMeta (createMeta UserResource) $ WithId uid user
+    liftSTM $ STMMap.insert newUser uid m
+    return newUser
+
+  putUser () uid user = do
+    m <- userDB <$> ask
+    liftSTM (STMMap.lookup uid m) >>= \case
+      Nothing -> throwScim (notFound "User" (pack (show uid)))
+      Just stored -> do
+        let newUser = WithMeta (meta stored) $ WithId uid user
+        liftSTM $ STMMap.insert newUser uid m
+        pure newUser
+
+  deleteUser () uid = do
+    m <- userDB <$> ask
+    liftSTM (STMMap.lookup uid m) >>= \case
+      Nothing -> throwScim (notFound "User" (pack (show uid)))
+      Just _ -> liftSTM $ STMMap.delete uid m
+
+-- (there seems to be no readOnly fields in User)
+assertMutability :: User Mock -> StoredUser Mock -> Bool
+assertMutability _newUser _stored = True
+
+----------------------------------------------------------------------------
+-- GroupDB
+
+instance GroupTypes Mock where
+  type GroupId Mock = Id
+
+instance GroupDB Mock TestServer where
+  getGroups () = do
+    m <- groupDB <$> ask
+    groups <- liftSTM $ ListT.toList $ STMMap.listT m
+    return $ fromList . sortWith (Common.id . thing) $ snd <$> groups
+
+  getGroup () gid = do
+    m <- groupDB <$> ask
+    liftSTM (STMMap.lookup gid m) >>= \case
+      Nothing -> throwScim (notFound "Group" (pack (show gid)))
+      Just grp -> pure grp
+
+  postGroup () grp = do
+    m <- groupDB <$> ask
+    gid <- Id <$> liftSTM (STMMap.size m)
+    let newGroup = WithMeta (createMeta GroupResource) $ WithId gid grp
+    liftSTM $ STMMap.insert newGroup gid m
+    return newGroup
+
+  putGroup () gid grp = do
+    m <- groupDB <$> ask
+    liftSTM (STMMap.lookup gid m) >>= \case
+      Nothing -> throwScim (notFound "Group" (pack (show gid)))
+      Just stored -> do
+        let newGroup = WithMeta (meta stored) $ WithId gid grp
+        liftSTM $ STMMap.insert newGroup gid m
+        pure newGroup
+
+  patchGroup _ _ _ = throwScim (serverError "PATCH /Users not implemented")
+
+  deleteGroup () gid = do
+    m <- groupDB <$> ask
+    liftSTM (STMMap.lookup gid m) >>= \case
+      Nothing -> throwScim (notFound "Group" (pack (show gid)))
+      Just _ -> liftSTM $ STMMap.delete gid m
+
+----------------------------------------------------------------------------
+-- AuthDB
+
+instance AuthTypes Mock where
+  type AuthData Mock = Text
+  type AuthInfo Mock = ()
+
+instance AuthDB Mock TestServer where
+  authCheck = \case
+    Just "authorized" -> pure ()
+    _ -> throwScim (unauthorized "expected 'authorized'")
+
+----------------------------------------------------------------------------
+-- Misc
+
+-- 2018-01-01 00:00
+testDate :: UTCTime
+testDate =
+  UTCTime
+    { utctDay = ModifiedJulianDay 58119,
+      utctDayTime = 0
+    }
+
+-- static meta for testing
+createMeta :: ResourceType -> Meta
+createMeta rType =
+  Meta
+    { resourceType = rType,
+      created = testDate,
+      lastModified = testDate,
+      version = Weak "testVersion",
+      location =
+        Common.URI $ -- FUTUREWORK: getting the actual schema, authority, and path here
+        -- is a bit of work, but it may be required one day.
+          URI "https:" (Just $ URI.URIAuth "" "example.com" "") "/Users/id" "" ""
+    }
+
+-- Natural transformation from our transformer stack to the Servant stack
+-- this takes the initial environment and returns the transformation
+nt :: TestStorage -> ScimHandler TestServer a -> Handler a
+nt storage =
+  flip runReaderT storage
+    . fromScimHandler (lift . throwError . scimToServerError)
+
+-- | Check whether a user satisfies the filter.
+--
+-- Returns 'Left' if the filter is constructed incorrectly (e.g. tries to
+-- compare a username with a boolean).
+--
+-- TODO(arianvp): We need to generalise filtering at some point probably.
+filterUser :: Filter -> User extra -> Either Text Bool
+filterUser (FilterAttrCompare (AttrPath schema' attrib subAttr) op val) user
+  | isUserSchema schema' =
+    case (subAttr, val) of
+      (Nothing, (ValString str))
+        | attrib == "userName" ->
+          Right (compareStr op (toCaseFold (userName user)) (toCaseFold str))
+      (Nothing, _)
+        | attrib == "userName" ->
+          Left "usernames can only be compared with strings"
+      (_, _) ->
+        Left "Only search on usernames is currently supported"
+  | otherwise = Left "Invalid schema. Only user schema is supported"
diff --git a/src/Web/Scim/Test/Acceptance.hs b/src/Web/Scim/Test/Acceptance.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Test/Acceptance.hs
@@ -0,0 +1,294 @@
+{-# LANGUAGE QuasiQuotes #-}
+{-# LANGUAGE RecordWildCards #-}
+{-# LANGUAGE TupleSections #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+-- | A bunch of hspec acceptance tests that assert that your SCIM
+-- implementation is compatible with popular SCIM 2.0 providers
+module Web.Scim.Test.Acceptance
+  ( module Web.Scim.Test.Acceptance,
+    module Web.Scim.Test.Util,
+  )
+where
+
+import Control.Monad.IO.Class (liftIO)
+import qualified Data.Aeson as Aeson
+import qualified Data.ByteString as BS
+import qualified Data.ByteString.Lazy as L
+import Data.String.Conversions (cs)
+import Data.Text (Text)
+import Network.HTTP.Types.Status
+import Network.Wai.Test
+import Servant.API as Servant
+import Test.Hspec (Spec, beforeAll, describe, it, pending, pendingWith, shouldBe, shouldSatisfy)
+import Test.Hspec.Wai (matchStatus)
+import Test.Hspec.Wai.Internal (runWaiSession)
+import Web.Scim.Class.User
+import Web.Scim.Schema.Common as Hscim
+import qualified Web.Scim.Schema.ListResponse as ListResponse
+import Web.Scim.Schema.Meta
+import Web.Scim.Schema.UserTypes
+import Web.Scim.Test.Util
+
+ignore :: Monad m => m a -> m ()
+ignore _ = pure ()
+
+-- https://docs.microsoft.com/en-us/azure/active-directory/manage-apps/use-scim-to-provision-users-and-groups#step-2-understand-the-azure-ad-scim-implementation
+microsoftAzure :: forall tag. (Aeson.FromJSON (UserId tag), Aeson.FromJSON (UserExtra tag), ToHttpApiData (UserId tag)) => AcceptanceConfig tag -> Spec
+microsoftAzure AcceptanceConfig {..} = do
+  describe "Within the SCIM 2.0 protocol specification, your application must meet these requirements:" $ do
+    it "Supports creating users, and optionally also groups, as per section 3.3 of the SCIM protocol." $ pending -- TODO(arianvp): Write test
+    it "Supports modifying users or groups with PATCH requests, as per section 3.5.2 of the SCIM protocol." $ pending -- TODO(arianvp): Write test
+    it "Supports retrieving a known resource for a user or group created earlier, as per section 3.4.1 of the SCIM protocol." $ pending -- TODO(arianvp): Write test
+    it "Supports querying users or groups, as per section 3.4.2 of the SCIM protocol. By default, users are retrieved by their id and queried by their username and externalid, and groups are queried by displayName." $ pending
+    describe "Supports querying user by ID and by manager, as per section 3.4.2 of the SCIM protocol." $ do
+      it "query by id" $ pending -- TODO(arianvp): Write test
+      it "query by manager" $ pending -- TODO(arianvp): Implement support for enterprise extension
+    it "Supports querying groups by ID and by member, as per section 3.4.2 of the SCIM protocol." $ pending -- TODO(arianvp): Implement groups
+    it "Accepts a single bearer token for authentication and authorization of Azure AD to your application." $
+      -- This is provided by the library
+      True `shouldBe` True
+  describe "Follow these general guidelines when implementing a SCIM endpoint to ensure compatibility with Azure AD:" $ do
+    it "id is a required property for all the resources. Every response that returns a resource should ensure each resource has this property, except for ListResponse with zero members." $
+      -- NOTE: This is guaranteed by the type-system. No need for a test
+      True `shouldBe` True
+    it "Response to a query/filter request should always be a ListResponse." $
+      -- NOTE: This is guaranteed by the type-system. No need for a test
+      True `shouldBe` True
+    it "Groups are optional, but only supported if the SCIM implementation supports PATCH requests." $
+      -- TODO(arianvp): Implement groups
+      True `shouldBe` True
+    it "Don't require a case-sensitive match on structural elements in SCIM, in particular PATCH op operation values, as defined in https://tools.ietf.org/html/rfc7644#section-3.5.2. Azure AD emits the values of 'op' as Add, " $
+      -- TODO(arianvp): Write test
+      pending
+    describe "Microsoft Azure AD only uses the following operators: eq and" $ do
+      -- TODO(arianvp): Write test
+      it "eq" $ pending
+      -- TODO(arianvp): Implement 'and' as Azure needs it
+      it "and" $ pending
+  describe "good errors" $ do
+    -- (we may touch servant for this?)
+    it "surfaces parse errors of the user id path segment" $ do
+      pendingWith "should contain the offending id and the error; currently contains neither"
+    it "same for user id in query" $ do
+      pending
+    it "same for all other things parsed in path, query, body, ..." $ do
+      pending
+  beforeAll scimAppAndConfig $ do
+    it "User Operations" $ \(app, queryConfig) -> flip runWaiSession app $ do
+      userName1 <- liftIO genUserName
+      userName2 <- liftIO genUserName
+      -- POST /Users
+      resp :: SResponse <- post' queryConfig "/Users" (sampleUser1 userName1)
+      liftIO $ simpleStatus resp `shouldBe` status201
+      let testuid :: BS.ByteString
+          testuid =
+            either (error . show . (,resp)) (cs . Servant.toUrlPiece . Hscim.id . thing) $
+              Aeson.eitherDecode' @(StoredUser tag) (simpleBody resp)
+      -- Get users without query
+      get' queryConfig "/Users" >>= \rsp -> liftIO $ do
+        simpleStatus rsp `shouldSatisfy` (`elem` [status200, status400])
+      -- Get single user by query
+      get' queryConfig (cs $ "/Users?filter=userName eq " <> show userName1) >>= \rsp -> liftIO $ do
+        simpleStatus rsp `shouldBe` status200
+        ListResponse.totalResults <$> Aeson.eitherDecode' @(ListResponse.ListResponse (StoredUser tag)) (simpleBody rsp) `shouldBe` Right 1
+      -- Get single user by query, zero results
+      get' queryConfig (cs $ "/Users?filter=userName eq " <> show userName2)
+        `shouldRespondWith` [scim|
+          {
+            "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
+            "totalResults": 0,
+            "Resources": [],
+            "startIndex": 1,
+            "itemsPerPage": 0
+          }
+        |]
+          { matchStatus = 200
+          }
+      -- Get single user by externalId works
+      ignore $ do
+        get' queryConfig "/Users?filter=externalId eq \"0a21f0f2-8d2a-4f8e-479e-a20b-2d77186b5dd1\"" >>= \rsp -> liftIO $ do
+          simpleStatus rsp `shouldBe` status200
+          ListResponse.totalResults <$> Aeson.eitherDecode' @(ListResponse.ListResponse (StoredUser tag)) (simpleBody rsp) `shouldBe` Right 1
+      -- Update user [Multi-valued properties]
+      ignore $
+        patch'
+          queryConfig
+          "/Users/0"
+          [scim|
+            {
+              "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+              "Operations": [
+                  {
+                      "op": "Replace",
+                      "path": "emails[type eq \"work\"].value",
+                      "value": "updatedEmail@microsoft.com"
+                  },
+                  {
+                      "op": "Replace",
+                      "path": "name.familyName",
+                      "value": "updatedFamilyName"
+                  }
+              ]
+            }
+        |]
+          `shouldRespondWith` 200
+      -- update user [single-valued properties]
+      -- replace userName
+      let ops1 =
+            [scim|
+                   {
+                         "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+                         "Operations": [{
+                                 "op": "Replace",
+                                 "path": "userName",
+                                 "value": #{userName2}
+                         }]
+                   }
+                 |]
+      patch' queryConfig ("/Users/" <> testuid) ops1 `shouldRespondWith` 200
+      -- replace displayName
+      let ops2 =
+            [scim|
+                   {
+                           "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+                           "Operations": [{
+                                   "op": "Replace",
+                                   "path": "displayName",
+                                   "value": "newDisplayName"
+                           }]
+                   }
+                 |]
+          exactResult =
+            [scim|
+                     {
+                       "schemas": [
+                         "urn:ietf:params:scim:schemas:core:2.0:User",
+                         "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
+                       ],
+                       "userName": #{userName2},
+                       "active": true,
+                       "name": {
+                         "givenName": "givenName",
+                         "formatted": "givenName familyName",
+                         "familyName": "familyName"
+                       },
+                       "emails": [
+                         {
+                           "value": #{userName1 <> "@testuser.com"},
+                           "primary": true,
+                           "type": "work"
+                         }
+                       ],
+                       "displayName": "newDisplayName",
+                       "id": "0",
+                       "meta": {
+                         "resourceType": "User",
+                         "location": "https://example.com/Users/id",
+                         "created": "2018-01-01T00:00:00Z",
+                         "version": "W/\"testVersion\"",
+                         "lastModified": "2018-01-01T00:00:00Z"
+                       },
+                       "externalId": "0a21f0f2-8d2a-4f8e-bf98-7363c4aed4ef"
+                     }
+                   |]
+          result =
+            if responsesFullyKnown
+              then exactResult
+              else 200 -- TODO(fisx): check the fields changed by the patch operations?
+      patch' queryConfig ("/Users/" <> testuid) ops2 `shouldRespondWith` result
+      -- remove displayName
+      let op3 =
+            [scim|
+                 {
+                         "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+                         "Operations": [{
+                                 "op": "Remove",
+                                 "path": "displayName"
+                         }]
+                 }
+               |]
+          exactResult3 =
+            [scim|
+                     {
+                       "schemas": [
+                         "urn:ietf:params:scim:schemas:core:2.0:User",
+                         "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
+                       ],
+                       "userName": #{userName2},
+                       "active": true,
+                       "name": {
+                         "givenName": "givenName",
+                         "formatted": "givenName familyName",
+                         "familyName": "familyName"
+                       },
+                       "emails": [
+                         {
+                           "value": #{userName1 <> "@testuser.com"},
+                           "primary": true,
+                           "type": "work"
+                         }
+                       ],
+                       "id": "0",
+                       "meta": {
+                         "resourceType": "User",
+                         "location": "https://example.com/Users/id",
+                         "created": "2018-01-01T00:00:00Z",
+                         "version": "W/\"testVersion\"",
+                         "lastModified": "2018-01-01T00:00:00Z"
+                       },
+                       "externalId": "0a21f0f2-8d2a-4f8e-bf98-7363c4aed4ef"
+                     }
+                   |]
+          result3 =
+            if responsesFullyKnown
+              then exactResult3
+              else 200 -- TODO(fisx): check the fields changed by the patch operations?
+      patch' queryConfig ("/Users/" <> testuid) op3 `shouldRespondWith` result3
+      -- Delete User
+      delete' queryConfig ("/Users/" <> testuid) "" `shouldRespondWith` 204
+      delete' queryConfig ("/Users/" <> testuid) "" `shouldEventuallyRespondWith` 404
+    it "Group operations" $ \_ -> pending
+
+sampleUser1 :: Text -> L.ByteString
+sampleUser1 userName1 =
+  [scim|
+  {
+    "schemas": [
+        "urn:ietf:params:scim:schemas:core:2.0:User",
+        "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"],
+    "externalId": "0a21f0f2-8d2a-4f8e-bf98-7363c4aed4ef",
+    "userName": #{userName1},
+    "active": true,
+    "emails": [{
+            "primary": true,
+            "type": "work",
+            "value": #{userName1 <> "@testuser.com"}
+    }],
+    "meta": {
+            "resourceType": "User"
+    },
+    "name": {
+            "formatted": "givenName familyName",
+            "familyName": "familyName",
+            "givenName": "givenName"
+    },
+    "roles": []
+  }
+|]
diff --git a/src/Web/Scim/Test/Util.hs b/src/Web/Scim/Test/Util.hs
new file mode 100644
--- /dev/null
+++ b/src/Web/Scim/Test/Util.hs
@@ -0,0 +1,261 @@
+{-# LANGUAGE RecordWildCards #-}
+{-# LANGUAGE TemplateHaskell #-}
+{-# LANGUAGE TupleSections #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Web.Scim.Test.Util
+  ( shouldRespondWith,
+    shouldEventuallyRespondWith,
+
+    -- * Making wai requests
+    post,
+    put,
+    patch,
+    AcceptanceConfig (..),
+    defAcceptanceConfig,
+    AcceptanceQueryConfig (..),
+    defAcceptanceQueryConfig,
+    post',
+    put',
+    patch',
+    get',
+    delete',
+    (<//>),
+
+    -- * Request/response quasiquoter
+    scim,
+
+    -- * JSON parsing
+    Field (..),
+    getField,
+
+    -- * Tag
+    TestTag,
+  )
+where
+
+import qualified Control.Retry as Retry
+import Data.Aeson
+import Data.Aeson.QQ
+import Data.Aeson.Types (JSONPathElement (Key))
+import Data.ByteString (ByteString)
+import qualified Data.ByteString as BS
+import qualified Data.ByteString.Char8 as BS8
+import qualified Data.ByteString.Lazy as L
+import qualified Data.HashMap.Strict as SMap
+import Data.Proxy
+import Data.Text
+import Data.UUID as UUID
+import Data.UUID.V4 as UUID
+import GHC.Stack
+import GHC.TypeLits (KnownSymbol, Symbol, symbolVal)
+import Language.Haskell.TH.Quote
+import Network.HTTP.Types
+import Network.Wai (Application)
+import Network.Wai.Test (SResponse)
+import Test.Hspec.Expectations (expectationFailure)
+import Test.Hspec.Wai hiding (patch, post, put, shouldRespondWith)
+import Test.Hspec.Wai.Matcher (bodyEquals, match)
+import Web.Scim.Class.Auth (AuthTypes (..))
+import Web.Scim.Class.Group (GroupTypes (..))
+import Web.Scim.Schema.Schema (Schema (CustomSchema, User20))
+import Web.Scim.Schema.User (UserTypes (..))
+
+-- | re-implementation of 'shouldRespondWith' with better error reporting.
+-- FUTUREWORK: make this a PR upstream.  (while we're at it, we can also patch 'WaiSession'
+-- and 'request' to keep track of the 'SRequest', and add that to the error message here with
+-- the response.)
+shouldRespondWith :: HasCallStack => WaiSession SResponse -> ResponseMatcher -> WaiExpectation
+shouldRespondWith action matcher =
+  either (liftIO . expectationFailure) pure =<< doesRespondWith action matcher
+
+doesRespondWith :: HasCallStack => WaiSession SResponse -> ResponseMatcher -> WaiSession (Either String ())
+doesRespondWith action matcher = do
+  r <- action
+  let extmsg = "  details:  " <> show r <> "\n"
+  pure $ maybe (Right ()) (Left . (<> extmsg)) (match r matcher)
+
+shouldEventuallyRespondWith :: HasCallStack => WaiSession SResponse -> ResponseMatcher -> WaiExpectation
+shouldEventuallyRespondWith action matcher =
+  either (liftIO . expectationFailure) pure
+    =<< Retry.retrying
+      (Retry.exponentialBackoff 66000 <> Retry.limitRetries 6)
+      (\_ -> pure . either (const True) (const False))
+      (\_ -> doesRespondWith action matcher)
+
+data AcceptanceConfig tag = AcceptanceConfig
+  { scimAppAndConfig :: IO (Application, AcceptanceQueryConfig tag),
+    genUserName :: IO Text,
+    -- | some acceptance tests match against a fully rendered
+    -- response body, which will not work when running the test
+    -- as a library user (since the response will have more and
+    -- other information).  if you leave this on 'False' (default
+    -- from 'defAcceptanceConfig'), the test will only check some
+    -- invariants on the response instead that must hold in all
+    -- cases.
+    responsesFullyKnown :: Bool
+  }
+
+defAcceptanceConfig :: IO Application -> AcceptanceConfig tag
+defAcceptanceConfig scimApp = AcceptanceConfig {..}
+  where
+    scimAppAndConfig = (,defAcceptanceQueryConfig) <$> scimApp
+    genUserName = ("Test_User_" <>) . UUID.toText <$> UUID.nextRandom
+    responsesFullyKnown = False
+
+data AcceptanceQueryConfig tag = AcceptanceQueryConfig
+  { scimPathPrefix :: BS.ByteString,
+    scimAuthToken :: BS.ByteString
+  }
+
+defAcceptanceQueryConfig :: AcceptanceQueryConfig tag
+defAcceptanceQueryConfig = AcceptanceQueryConfig {..}
+  where
+    scimPathPrefix = ""
+    scimAuthToken = "authorized"
+
+----------------------------------------------------------------------------
+-- Redefine wai test helpers to include scim+json content type
+
+-- | avoid multiple @/@.  (kill at most one @/@ at the end of first arg and beginning of
+-- second arg, resp., then add one during concatenation.
+--
+-- >>> ["a" <//> "b", "a" <//> "/b", "a/" <//> "b", "a/" <//> "/b"]
+-- ["a/b","a/b","a/b","a/b"]
+--
+-- WARNING: {doctests don't work in our
+-- infrastructure](https://github.com/zinfra/backend-issues/issues/1549), so this is
+-- duplicated in the unit tests.
+(<//>) :: ByteString -> ByteString -> ByteString
+(<//>) a b = a' <> "/" <> b'
+  where
+    a' = maybe a (\(t, l) -> if l == '/' then t else a) $ BS8.unsnoc a
+    b' = maybe b (\(h, t) -> if h == '/' then t else b) $ BS8.uncons b
+
+post :: ByteString -> L.ByteString -> WaiSession SResponse
+post path = request methodPost path [(hContentType, "application/scim+json")]
+
+put :: ByteString -> L.ByteString -> WaiSession SResponse
+put path = request methodPut path [(hContentType, "application/scim+json")]
+
+patch :: ByteString -> L.ByteString -> WaiSession SResponse
+patch path = request methodPatch path [(hContentType, "application/scim+json")]
+
+request' :: Method -> AcceptanceQueryConfig tag -> ByteString -> L.ByteString -> WaiSession SResponse
+request' method (AcceptanceQueryConfig prefix token) path = request method (prefix <//> path) [(hAuthorization, token), (hContentType, "application/scim+json")]
+
+get' :: AcceptanceQueryConfig tag -> ByteString -> WaiSession SResponse
+get' cfg path = request' methodGet cfg path ""
+
+post' :: AcceptanceQueryConfig tag -> ByteString -> L.ByteString -> WaiSession SResponse
+post' = request' methodPost
+
+put' :: AcceptanceQueryConfig tag -> ByteString -> L.ByteString -> WaiSession SResponse
+put' = request' methodPut
+
+patch' :: AcceptanceQueryConfig tag -> ByteString -> L.ByteString -> WaiSession SResponse
+patch' = request' methodPatch
+
+delete' :: AcceptanceQueryConfig tag -> ByteString -> L.ByteString -> WaiSession SResponse
+delete' = request' methodDelete
+
+----------------------------------------------------------------------------
+-- Redefine wai quasiquoter
+--
+-- This code was taken from Test.Hspec.Wai.JSON and modified to accept
+-- @application/scim+json@. In order to keep the code simple, we also
+-- require @charset=utf-8@, even though the original implementation
+-- considers it optional.
+
+-- | A response matcher and quasiquoter that should be used instead of
+-- 'Test.Hspec.Wai.JSON.json'.
+scim :: QuasiQuoter
+scim =
+  QuasiQuoter
+    { quoteExp = \input -> [|fromValue $(quoteExp aesonQQ input)|],
+      quotePat = const $ error "No quotePat defined for Test.Util.scim",
+      quoteType = const $ error "No quoteType defined for Test.Util.scim",
+      quoteDec = const $ error "No quoteDec defined for Test.Util.scim"
+    }
+
+class FromValue a where
+  fromValue :: Value -> a
+
+instance FromValue ResponseMatcher where
+  fromValue = ResponseMatcher 200 [matchHeader] . equalsJSON
+    where
+      matchHeader = "Content-Type" <:> "application/scim+json;charset=utf-8"
+
+equalsJSON :: Value -> MatchBody
+equalsJSON expected = MatchBody matcher
+  where
+    matcher headers actualBody = case decode actualBody of
+      Just actual | actual == expected -> Nothing
+      _ -> let MatchBody m = bodyEquals (encode expected) in m headers actualBody
+
+instance FromValue L.ByteString where
+  fromValue = encode
+
+instance FromValue Value where
+  fromValue = id
+
+----------------------------------------------------------------------------
+-- Ad-hoc JSON parsing
+
+-- | A way to parse out a single value from a JSON object by specifying the
+-- field as a type-level string. Very useful when you don't want to create
+-- extra types.
+newtype Field (s :: Symbol) a = Field a
+  deriving (Eq, Ord, Show, Read, Functor)
+
+getField :: Field s a -> a
+getField (Field a) = a
+
+-- Copied from https://hackage.haskell.org/package/aeson-extra-0.4.1.1/docs/src/Data.Aeson.Extra.SingObject.html
+instance (KnownSymbol s, FromJSON a) => FromJSON (Field s a) where
+  parseJSON = withObject ("Field " <> show key) $ \obj ->
+    case SMap.lookup key obj of
+      Nothing -> fail $ "key " ++ show key ++ " not present"
+      Just v -> Field <$> parseJSON v <?> Key key
+    where
+      key = pack $ symbolVal (Proxy :: Proxy s)
+
+instance (KnownSymbol s, ToJSON a) => ToJSON (Field s a) where
+  toJSON (Field x) = object [key .= x]
+    where
+      key = pack $ symbolVal (Proxy :: Proxy s)
+
+----------------------------------------------------------------------------
+-- Tag
+
+-- | A type-level tag for 'UserTypes', 'AuthTypes', etc. that allows picking any types we
+-- might need in tests.
+data TestTag id authData authInfo userExtra
+
+instance UserTypes (TestTag id authData authInfo userExtra) where
+  type UserId (TestTag id authData authInfo userExtra) = id
+  type UserExtra (TestTag id authData authInfo userExtra) = userExtra
+  supportedSchemas = [User20, CustomSchema "urn:hscim:test"]
+
+instance GroupTypes (TestTag id authData authInfo userExtra) where
+  type GroupId (TestTag id authData authInfo userExtra) = id
+
+instance AuthTypes (TestTag id authData authInfo userExtra) where
+  type AuthData (TestTag id authData authInfo userExtra) = authData
+  type AuthInfo (TestTag id authData authInfo userExtra) = authInfo
diff --git a/test/Spec.hs b/test/Spec.hs
new file mode 100644
--- /dev/null
+++ b/test/Spec.hs
@@ -0,0 +1,18 @@
+{-# OPTIONS_GHC -F -pgmF hspec-discover #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
diff --git a/test/Test/AcceptanceSpec.hs b/test/Test/AcceptanceSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Test/AcceptanceSpec.hs
@@ -0,0 +1,32 @@
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+-- | A set of acceptance tests that you can use to test that your server is
+module Test.AcceptanceSpec where
+
+import Test.Hspec (Spec, describe)
+import Web.Scim.Capabilities.MetaSchema (empty)
+import Web.Scim.Server (app)
+import Web.Scim.Server.Mock
+import Web.Scim.Test.Acceptance (defAcceptanceConfig, microsoftAzure, responsesFullyKnown)
+
+spec :: Spec
+spec = do
+  let app' = do
+        storage <- emptyTestStorage
+        pure (app @Mock empty (nt storage))
+  describe "Azure" $ microsoftAzure ((defAcceptanceConfig @Mock app') {responsesFullyKnown = True})
diff --git a/test/Test/Capabilities/MetaSchemaSpec.hs b/test/Test/Capabilities/MetaSchemaSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Test/Capabilities/MetaSchemaSpec.hs
@@ -0,0 +1,138 @@
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Test.Capabilities.MetaSchemaSpec
+  ( spec,
+  )
+where
+
+import Data.Aeson
+import Data.Coerce
+import qualified Data.List as List
+import Data.Text (Text)
+import Network.Wai.Test (SResponse (..))
+import Servant
+import Servant.API.Generic
+import Test.Hspec hiding (shouldSatisfy)
+import qualified Test.Hspec.Expectations as Expect
+import Test.Hspec.Wai hiding (patch, post, put, shouldRespondWith)
+import Web.Scim.Capabilities.MetaSchema
+import Web.Scim.Server (ConfigAPI, mkapp)
+import Web.Scim.Server.Mock
+import Web.Scim.Test.Util
+
+app :: IO Application
+app = do
+  storage <- emptyTestStorage
+  pure $ mkapp @Mock (Proxy @ConfigAPI) (toServant (configServer empty)) (nt storage)
+
+shouldSatisfy ::
+  (Show a, FromJSON a) =>
+  WaiSession SResponse ->
+  (a -> Bool) ->
+  WaiExpectation
+shouldSatisfy resp predicate = do
+  maybeDecoded <- eitherDecode . simpleBody <$> resp
+  case maybeDecoded of
+    Left err -> liftIO $ Expect.expectationFailure ("decode error: " <> err)
+    Right decoded -> liftIO $ Expect.shouldSatisfy decoded predicate
+
+-- | A type that helps us parse out the pieces that we're interested in
+-- (specifically, a list of schema URIs). The whole response is very big and
+-- we don't want to print it out when the response parses correctly but the
+-- sets of schemas don't match.
+type SchemasResponse = Field "Resources" [Field "id" Text]
+
+coreSchemas :: [Text]
+coreSchemas =
+  [ "urn:ietf:params:scim:schemas:core:2.0:User",
+    "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig",
+    "urn:ietf:params:scim:schemas:core:2.0:Group",
+    "urn:ietf:params:scim:schemas:core:2.0:Schema",
+    "urn:ietf:params:scim:schemas:core:2.0:ResourceType"
+  ]
+
+spec :: Spec
+spec = beforeAll app $ do
+  describe "GET /Schemas" $ do
+    it "lists schemas" $ do
+      get "/Schemas" `shouldRespondWith` 200
+      get "/Schemas" `shouldSatisfy` \(resp :: SchemasResponse) ->
+        List.sort (coerce resp) == List.sort coreSchemas
+  describe "GET /Schemas/:id" $ do
+    it "returns valid schema" $ do
+      -- TODO: (partially) verify content
+      get "/Schemas/urn:ietf:params:scim:schemas:core:2.0:User"
+        `shouldRespondWith` 200
+    it "returns 404 on unknown schemaId" $ do
+      get "/Schemas/unknown" `shouldRespondWith` 404
+  describe "GET /ServiceProviderConfig" $ do
+    it "returns configuration" $ do
+      get "/ServiceProviderConfig" `shouldRespondWith` spConfig
+  describe "GET /ResourceTypes" $ do
+    it "returns resource types" $ do
+      get "/ResourceTypes" `shouldRespondWith` resourceTypes
+
+-- FIXME: missing some "supported" fields
+spConfig :: ResponseMatcher
+spConfig =
+  [scim|
+{"schemas":["urn:ietf:params:scim:schemas:core:2.0:User",
+            "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig",
+            "urn:ietf:params:scim:schemas:core:2.0:Group",
+            "urn:ietf:params:scim:schemas:core:2.0:Schema",
+            "urn:ietf:params:scim:schemas:core:2.0:ResourceType"],
+ "etag":{"supported":false},
+ "bulk":{"maxOperations":0,
+         "maxPayloadSize":0,
+         "supported":false
+        },
+ "patch":{"supported":true},
+ "authenticationSchemes":[
+   {"type":"httpbasic",
+    "name":"HTTP Basic",
+    "description":"Authentication via the HTTP Basic standard",
+    "specUri":"https://tools.ietf.org/html/rfc7617",
+    "documentationUri":"https://en.wikipedia.org/wiki/Basic_access_authentication"
+   }
+ ],
+ "changePassword":{"supported":false},
+ "sort":{"supported":false},
+ "filter":{"maxResults":0,
+           "supported":false
+          }
+}
+|]
+
+resourceTypes :: ResponseMatcher
+resourceTypes =
+  [scim|
+{"schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
+ "Resources":[
+   {"schema":"urn:ietf:params:scim:schemas:core:2.0:User",
+    "name":"User",
+    "endpoint":"/Users"},
+   {"schema":"urn:ietf:params:scim:schemas:core:2.0:Group",
+    "name":"Group",
+    "endpoint":"/Groups"}],
+ "totalResults":2,
+ "startIndex":1,
+ "itemsPerPage":2
+}
+|]
diff --git a/test/Test/Class/AuthSpec.hs b/test/Test/Class/AuthSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Test/Class/AuthSpec.hs
@@ -0,0 +1,58 @@
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Test.Class.AuthSpec
+  ( spec,
+  )
+where
+
+import Data.Text (Text)
+import Data.Text.Encoding
+import Network.HTTP.Types.Header
+import Network.HTTP.Types.Method (methodGet)
+import qualified StmContainers.Map as STMMap
+import Test.Hspec
+import Test.Hspec.Wai hiding (patch, post, put)
+import Web.Scim.Capabilities.MetaSchema (empty)
+import Web.Scim.Server (app)
+import Web.Scim.Server.Mock
+
+testStorage :: IO TestStorage
+testStorage = TestStorage <$> STMMap.newIO <*> STMMap.newIO
+
+spec :: Spec
+spec = beforeAll ((\s -> app @Mock empty (nt s)) <$> testStorage) $ do
+  describe "/ServiceProviderConfig" $ do
+    it "is accessible without authentication" $ do
+      get "/ServiceProviderConfig" `shouldRespondWith` 200
+    it "doesn't check auth credentials" $ do
+      request methodGet "/ServiceProviderConfig" [authHeader "blah"] ""
+        `shouldRespondWith` 200
+  describe "/Users" $ do
+    it "succeeds with authentication" $ do
+      request methodGet "/Users" [authHeader "authorized"] ""
+        `shouldRespondWith` 200
+    it "fails if the auth token is invalid" $ do
+      request methodGet "/Users" [authHeader "blah"] ""
+        `shouldRespondWith` 401
+    it "fails if no authentication is provided" $ do
+      get "/Users" `shouldRespondWith` 401
+
+authHeader :: Text -> Header
+authHeader token = (hAuthorization, encodeUtf8 token)
diff --git a/test/Test/Class/GroupSpec.hs b/test/Test/Class/GroupSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Test/Class/GroupSpec.hs
@@ -0,0 +1,161 @@
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Test.Class.GroupSpec
+  ( spec,
+  )
+where
+
+import Data.ByteString.Lazy (ByteString)
+import Network.Wai (Application)
+import Servant (Proxy (Proxy))
+import Servant.API.Generic
+import Test.Hspec hiding (shouldSatisfy)
+import Test.Hspec.Wai hiding (patch, post, put, shouldRespondWith)
+import Web.Scim.Server (GroupAPI, groupServer, mkapp)
+import Web.Scim.Server.Mock
+import Web.Scim.Test.Util
+
+app :: IO Application
+app = do
+  storage <- emptyTestStorage
+  let auth = Just "authorized"
+  pure $
+    mkapp @Mock
+      (Proxy @(GroupAPI Mock))
+      (toServant (groupServer @Mock auth))
+      (nt storage)
+
+spec :: Spec
+spec = beforeAll app $ do
+  describe "GET & POST /Groups" $ do
+    it "responds with [] in empty environment" $ do
+      get "/" `shouldRespondWith` emptyList
+    it "can insert then retrieve stored group" $ do
+      post "/" adminGroup `shouldRespondWith` 201
+      get "/" `shouldRespondWith` groups
+  describe "GET /Groups/:id" $ do
+    it "responds with 404 for unknown group" $ do
+      get "/9999" `shouldRespondWith` 404
+    it "retrieves stored group" $ do
+      -- the test implementation stores groups with uid [0,1..n-1]
+      get "/0" `shouldRespondWith` admins
+  describe "PUT /Groups/:id" $ do
+    it "adds member to existing group" $ do
+      put "/0" adminUpdate0 `shouldRespondWith` updatedAdmins0
+    it "does not create new group" $ do
+      put "/9999" adminGroup `shouldRespondWith` 404
+  describe "DELETE /Groups/:id" $ do
+    it "responds with 404 for unknown group" $ do
+      delete "/Users/unknown" `shouldRespondWith` 404
+    it "deletes a stored group" $ do
+      delete "/0" `shouldRespondWith` 204
+      -- group should be gone
+      get "/0" `shouldRespondWith` 404
+      delete "/0" `shouldRespondWith` 404
+
+adminGroup :: ByteString
+adminGroup =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:schemas:core:2.0:Group"],
+          "displayName":"Admin",
+          "members":[]
+        }|]
+
+groups :: ResponseMatcher
+groups =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
+          "Resources":
+            [{ "schemas":["urn:ietf:params:scim:schemas:core:2.0:Group"],
+               "displayName":"Admin",
+               "members":[],
+               "id":"0",
+               "meta":{
+                 "resourceType":"Group",
+                 "location":"https://example.com/Users/id",
+                 "created":"2018-01-01T00:00:00Z",
+                 "version":"W/\"testVersion\"",
+                 "lastModified":"2018-01-01T00:00:00Z"
+               }
+             }
+            ],
+          "totalResults":1,
+          "itemsPerPage":1,
+          "startIndex":1
+        }|]
+
+admins :: ResponseMatcher
+admins =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:schemas:core:2.0:Group"],
+           "displayName":"Admin",
+           "members":[],
+           "id":"0",
+           "meta":{
+             "resourceType":"Group",
+             "location":"https://example.com/Users/id",
+             "created":"2018-01-01T00:00:00Z",
+             "version":"W/\"testVersion\"",
+             "lastModified":"2018-01-01T00:00:00Z"
+           }
+        }|]
+
+adminUpdate0 :: ByteString
+adminUpdate0 =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:schemas:core:2.0:Group"],
+          "displayName":"Admin",
+          "members":[
+            { "value": "0",
+              "$ref": "https://example.com/Users/0",
+              "type": "User"
+            }
+          ]
+        }|]
+
+updatedAdmins0 :: ResponseMatcher
+updatedAdmins0 =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:schemas:core:2.0:Group"],
+           "displayName":"Admin",
+           "members":[
+             { "value": "0",
+               "$ref": "https://example.com/Users/0",
+               "type": "User"
+             }],
+           "id":"0",
+           "meta":{
+             "resourceType":"Group",
+             "location":"https://example.com/Users/id",
+             "created":"2018-01-01T00:00:00Z",
+             "version":"W/\"testVersion\"",
+             "lastModified":"2018-01-01T00:00:00Z"
+           }
+        }|]
+
+emptyList :: ResponseMatcher
+emptyList =
+  [scim|
+       { "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
+         "Resources":[],
+         "totalResults":0,
+         "itemsPerPage":0,
+         "startIndex":1
+       }|]
diff --git a/test/Test/Class/UserSpec.hs b/test/Test/Class/UserSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Test/Class/UserSpec.hs
@@ -0,0 +1,586 @@
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Test.Class.UserSpec
+  ( spec,
+  )
+where
+
+import Data.ByteString.Lazy (ByteString)
+import Network.Wai (Application)
+import Servant (Proxy (Proxy))
+import Servant.API.Generic
+import Test.Hspec
+import Test.Hspec.Wai hiding (patch, post, put, shouldRespondWith)
+import Web.Scim.Server (UserAPI, mkapp, userServer)
+import Web.Scim.Server.Mock
+import Web.Scim.Test.Util
+
+app :: IO Application
+app = do
+  storage <- emptyTestStorage
+  let auth = Just "authorized"
+  pure $ mkapp @Mock (Proxy @(UserAPI Mock)) (toServant (userServer auth)) (nt storage)
+
+spec :: Spec
+spec = beforeAll app $ do
+  describe "GET & POST /Users" $ do
+    it "responds with [] in empty environment" $ do
+      get "/" `shouldRespondWith` emptyList
+    it "can insert then retrieve stored Users" $ do
+      post "/" newBarbara `shouldRespondWith` 201
+      post "/" newJim `shouldRespondWith` 201
+      get "/" `shouldRespondWith` allUsers
+    describe "filtering" $ do
+      it "can filter by username" $ do
+        get "/?filter=userName eq \"bjensen\"" `shouldRespondWith` onlyBarbara
+      it "is case-insensitive regarding syntax" $ do
+        get "/?filter=USERName EQ \"bjensen\"" `shouldRespondWith` onlyBarbara
+      it "is case-insensitive regarding usernames" $ do
+        get "/?filter=userName eq \"BJensen\"" `shouldRespondWith` onlyBarbara
+      it "handles malformed filter syntax" $ do
+        get "/?filter=userName eqq \"bjensen\"" `shouldRespondWith` 400
+      -- TODO: would be nice to check the error message as well
+
+      it "handles type errors in comparisons" $ do
+        get "/?filter=userName eq true" `shouldRespondWith` 400
+  describe "GET /Users/:id" $ do
+    it "responds with 404 for unknown user" $ do
+      get "/9999" `shouldRespondWith` 404
+    -- FUTUREWORK: currently it returns 404:
+    -- https://github.com/haskell-servant/servant/issues/1155
+    xit "responds with 401 for unparseable user ID" $ do
+      get "/unparseable" `shouldRespondWith` 401
+    it "retrieves stored user" $ do
+      -- the test implementation stores users with uid [0,1..n-1]
+      get "/0" `shouldRespondWith` barbara
+  describe "PUT /Users/:id" $ do
+    it "overwrites the user" $ do
+      put "/0" barbUpdate0 `shouldRespondWith` updatedBarb0
+    it "does not create new users" $ do
+      put "/9999" newBarbara `shouldRespondWith` 404
+  -- TODO(arianvp): Perhaps we want to make this an acceptance spec.
+  describe "PATCH /Users/:id" $ do
+    describe "Add" $ do
+      -- TODO(arianvp): Implement and test multi-value fields properly
+      -- TODO(arianvp): We need to merge multi-value fields, but not supported yet
+      -- TODO(arianvp): Add and Replace tests currently identical, because of lack of multi-value
+      it "adds all fields if no target" $ do
+        _ <- put "/0" smallUser -- reset
+        patch
+          "/0"
+          [scim|{
+              "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+              "Operations": [{
+                "op": "Add",
+                "value": {
+                  "userName": "arian",
+                  "displayName": "arian"
+                }
+
+              }]
+        }|]
+          `shouldRespondWith` [scim|
+          {
+            "schemas": [
+              "urn:ietf:params:scim:schemas:core:2.0:User"
+            ],
+            "userName": "arian",
+            "displayName": "arian",
+            "id": "0",
+            "meta": {
+              "resourceType": "User",
+              "location": "https://example.com/Users/id",
+              "created": "2018-01-01T00:00:00Z",
+              "version": "W/\"testVersion\"",
+              "lastModified": "2018-01-01T00:00:00Z"
+            }
+          }
+        |]
+            { matchStatus = 200
+            }
+      it "adds fields if they didn't exist yet" $ do
+        _ <- put "/0" smallUser -- reset
+        patch
+          "/0"
+          [scim|{
+          "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+          "Operations": [{
+            "op": "Add",
+            "path": "displayName",
+            "value": "arian"
+          }]
+        }|]
+          `shouldRespondWith` [scim|
+          {
+            "schemas": [
+              "urn:ietf:params:scim:schemas:core:2.0:User"
+            ],
+            "userName": "bjensen",
+            "displayName": "arian",
+            "id": "0",
+            "meta": {
+              "resourceType": "User",
+              "location": "https://example.com/Users/id",
+              "created": "2018-01-01T00:00:00Z",
+              "version": "W/\"testVersion\"",
+              "lastModified": "2018-01-01T00:00:00Z"
+            }
+          }
+        |]
+            { matchStatus = 200
+            }
+      it "replaces individual simple fields" $ do
+        _ <- put "/0" smallUser -- reset
+        patch
+          "/0"
+          [scim|{
+          "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+          "Operations": [{
+            "op": "Add",
+            "path": "userName",
+            "value": "arian"
+          }]
+        }|]
+          `shouldRespondWith` [scim|
+          {
+            "schemas": [
+              "urn:ietf:params:scim:schemas:core:2.0:User"
+            ],
+            "userName": "arian",
+            "displayName": "bjensen2",
+            "id": "0",
+            "meta": {
+              "resourceType": "User",
+              "location": "https://example.com/Users/id",
+              "created": "2018-01-01T00:00:00Z",
+              "version": "W/\"testVersion\"",
+              "lastModified": "2018-01-01T00:00:00Z"
+            }
+          }
+        |]
+            { matchStatus = 200
+            }
+      -- TODO(arianvp): I think this is better done with quickcheck test.
+      -- Generate some adds, replaces, removes and then an invalid one However,
+      -- for this we need to be able to generate valid patches but a patch does
+      -- not limit by type what fields it lenses in to. It is a very untyped
+      -- thingy currently.
+      it "PatchOp is atomic. Either fully applies or not at all" $ do
+        _ <- put "/0" smallUser -- reset
+        patch
+          "/0"
+          [scim|{
+          "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+          "Operations": [{
+            "op": "Add",
+            "path": "userName",
+            "value": "arian"
+          },
+          { "op": "Add",
+            "path": "displayName",
+            "value": 5
+          }]}|]
+          `shouldRespondWith` 400
+        get "/0" `shouldRespondWith` smallUserGet {matchStatus = 200}
+    describe "Replace" $ do
+      -- TODO(arianvp): Implement and test multi-value fields properly
+      it "adds all fields if no target" $ do
+        _ <- put "/0" smallUser -- reset
+        patch
+          "/0"
+          [scim|{
+              "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+              "Operations": [{
+                "op": "Replace",
+                "value": {
+                  "userName": "arian",
+                  "displayName": "arian"
+                }
+
+              }]
+        }|]
+          `shouldRespondWith` [scim|
+          {
+            "schemas": [
+              "urn:ietf:params:scim:schemas:core:2.0:User"
+            ],
+            "userName": "arian",
+            "displayName": "arian",
+            "id": "0",
+            "meta": {
+              "resourceType": "User",
+              "location": "https://example.com/Users/id",
+              "created": "2018-01-01T00:00:00Z",
+              "version": "W/\"testVersion\"",
+              "lastModified": "2018-01-01T00:00:00Z"
+            }
+          }
+        |]
+            { matchStatus = 200
+            }
+      it "adds fields if they didn't exist yet" $ do
+        _ <- put "/0" smallUser -- reset
+        patch
+          "/0"
+          [scim|{
+          "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+          "Operations": [{
+            "op": "Replace",
+            "path": "displayName",
+            "value": "arian"
+          }]
+        }|]
+          `shouldRespondWith` [scim|
+          {
+            "schemas": [
+              "urn:ietf:params:scim:schemas:core:2.0:User"
+            ],
+            "userName": "bjensen",
+            "displayName": "arian",
+            "id": "0",
+            "meta": {
+              "resourceType": "User",
+              "location": "https://example.com/Users/id",
+              "created": "2018-01-01T00:00:00Z",
+              "version": "W/\"testVersion\"",
+              "lastModified": "2018-01-01T00:00:00Z"
+            }
+          }
+        |]
+            { matchStatus = 200
+            }
+      it "replaces individual simple fields" $ do
+        _ <- put "/0" smallUser -- reset
+        patch
+          "/0"
+          [scim|{
+          "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+          "Operations": [{
+            "op": "Replace",
+            "path": "userName",
+            "value": "arian"
+          }]
+        }|]
+          `shouldRespondWith` [scim|
+          {
+            "schemas": [
+              "urn:ietf:params:scim:schemas:core:2.0:User"
+            ],
+            "userName": "arian",
+            "displayName": "bjensen2",
+            "id": "0",
+            "meta": {
+              "resourceType": "User",
+              "location": "https://example.com/Users/id",
+              "created": "2018-01-01T00:00:00Z",
+              "version": "W/\"testVersion\"",
+              "lastModified": "2018-01-01T00:00:00Z"
+            }
+          }
+        |]
+            { matchStatus = 200
+            }
+      it "PatchOp is atomic. Either fully applies or not at all" $ do
+        _ <- put "/0" smallUser -- reset
+        patch
+          "/0"
+          [scim|{
+          "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+          "Operations": [{
+            "op": "Replace",
+            "path": "userName",
+            "value": "arian"
+          },
+          { "op": "Replace",
+            "path": "displayName",
+            "value": 5
+          }]}|]
+          `shouldRespondWith` 400
+        get "/0" `shouldRespondWith` smallUserGet {matchStatus = 200}
+    describe "Remove" $ do
+      it "fails if no target" $ do
+        _ <- put "/0" barbUpdate0 -- reset
+        patch
+          "/0"
+          [scim|{
+          "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+          "Operations": [{ "op": "Remove" }]
+        }|]
+          `shouldRespondWith` [scim|{
+          "scimType":"noTarget","status":"400","schemas":["urn:ietf:params:scim:api:messages:2.0:Error"]
+        }|]
+            { matchStatus = 400
+            }
+      it "fails if removing immutable" $ do
+        _ <- put "/0" barbUpdate0 -- reset
+        patch
+          "/0"
+          [scim|{
+          "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+          "Operations": [{ "op": "Remove", "path": "userName"}]
+        }|]
+          `shouldRespondWith` [scim|{
+          "scimType":"mutability","status":"400","schemas":["urn:ietf:params:scim:api:messages:2.0:Error"]
+        }|]
+            { matchStatus = 400
+            }
+      it "deletes the specified attribute" $ do
+        _ <- put "/0" smallUser -- reset
+        patch
+          "/0"
+          [scim|{
+          "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+          "Operations": [{ "op": "Remove", "path": "displayName"}]
+        }|]
+          `shouldRespondWith` [scim|{
+          "schemas": [
+            "urn:ietf:params:scim:schemas:core:2.0:User"
+          ],
+          "userName": "bjensen",
+          "id": "0",
+          "meta": {
+            "resourceType": "User",
+            "location": "https://example.com/Users/id",
+            "created": "2018-01-01T00:00:00Z",
+            "version": "W/\"testVersion\"",
+            "lastModified": "2018-01-01T00:00:00Z"
+          }
+        }|]
+            { matchStatus = 200
+            }
+  describe "DELETE /Users/:id" $ do
+    it "responds with 404 for unknown user" $ do
+      delete "/9999" `shouldRespondWith` 404
+    it "deletes a stored user" $ do
+      delete "/0" `shouldRespondWith` 204
+      -- user should be gone
+      get "/0" `shouldRespondWith` 404
+      delete "/0" `shouldRespondWith` 404
+
+smallUser :: ByteString
+smallUser =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],
+          "userName":"bjensen",
+          "displayName": "bjensen2"
+        }|]
+
+smallUserGet :: ResponseMatcher
+smallUserGet =
+  [scim|
+{
+  "schemas": [
+    "urn:ietf:params:scim:schemas:core:2.0:User"
+  ],
+  "userName": "bjensen",
+  "displayName": "bjensen2",
+  "id": "0",
+  "meta": {
+    "resourceType": "User",
+    "location": "https://example.com/Users/id",
+    "created": "2018-01-01T00:00:00Z",
+    "version": "W/\"testVersion\"",
+    "lastModified": "2018-01-01T00:00:00Z"
+  }
+}
+|]
+
+newBarbara :: ByteString
+newBarbara =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],
+          "userName":"bjensen",
+          "externalId":"bjensen",
+          "name":{
+            "formatted":"Ms. Barbara J Jensen III",
+            "familyName":"Jensen",
+            "givenName":"Barbara"
+          }
+        }|]
+
+newJim :: ByteString
+newJim =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],
+          "userName":"jim",
+          "externalId":"jim",
+          "name":{
+            "formatted":"Jim",
+            "familyName":"",
+            "givenName":"Jim"
+          }
+        }|]
+
+barbara :: ResponseMatcher
+barbara =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],
+          "userName":"bjensen",
+          "name": {
+            "givenName":"Barbara",
+            "formatted":"Ms. Barbara J Jensen III",
+            "familyName":"Jensen"
+          },
+          "id":"0",
+          "externalId":"bjensen",
+          "meta":{
+            "resourceType":"User",
+            "location":"https://example.com/Users/id",
+            "created":"2018-01-01T00:00:00Z",
+            "version":"W/\"testVersion\"",
+            "lastModified":"2018-01-01T00:00:00Z"
+          }
+        }|]
+
+allUsers :: ResponseMatcher
+allUsers =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
+          "totalResults": 2,
+          "itemsPerPage": 2,
+          "startIndex": 1,
+          "Resources":
+            [{ "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],
+               "userName":"bjensen",
+               "externalId":"bjensen",
+               "id" : "0",
+               "name":{
+                 "formatted":"Ms. Barbara J Jensen III",
+                 "familyName":"Jensen",
+                 "givenName":"Barbara"
+               },
+               "meta":{
+                 "resourceType":"User",
+                 "location":"https://example.com/Users/id",
+                 "created":"2018-01-01T00:00:00Z",
+                 "version":"W/\"testVersion\"",
+                 "lastModified":"2018-01-01T00:00:00Z"
+               }
+             },
+             { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],
+               "userName":"jim",
+               "externalId":"jim",
+               "id" : "1",
+               "name":{
+                 "formatted":"Jim",
+                 "familyName":"",
+                 "givenName":"Jim"
+               },
+               "meta":{
+                 "resourceType":"User",
+                 "location":"https://example.com/Users/id",
+                 "created":"2018-01-01T00:00:00Z",
+                 "version":"W/\"testVersion\"",
+                 "lastModified":"2018-01-01T00:00:00Z"
+               }
+             }]
+        }|]
+
+onlyBarbara :: ResponseMatcher
+onlyBarbara =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
+          "totalResults": 1,
+          "itemsPerPage": 1,
+          "startIndex": 1,
+          "Resources":
+            [{ "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],
+               "userName":"bjensen",
+               "externalId":"bjensen",
+               "id" : "0",
+               "name":{
+                 "formatted":"Ms. Barbara J Jensen III",
+                 "familyName":"Jensen",
+                 "givenName":"Barbara"
+               },
+               "meta":{
+                 "resourceType":"User",
+                 "location":"https://example.com/Users/id",
+                 "created":"2018-01-01T00:00:00Z",
+                 "version":"W/\"testVersion\"",
+                 "lastModified":"2018-01-01T00:00:00Z"
+               }
+             }]
+        }|]
+
+-- source: https://tools.ietf.org/html/rfc7644#section-3.5.1 (p. 30)
+barbUpdate0 :: ByteString
+barbUpdate0 =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],
+          "id":"0",
+          "userName":"bjensen",
+          "externalId":"bjensen",
+          "name":{
+            "formatted":"Ms. Barbara J Jensen III",
+            "familyName":"Jensen",
+            "givenName":"Barbara",
+            "middleName":"Jane"
+          },
+          "roles":[],
+          "emails":[
+            {
+              "value":"bjensen@example.com"
+            },
+            {
+              "value":"babs@jensen.org"
+            }
+          ]
+        }|]
+
+updatedBarb0 :: ResponseMatcher
+updatedBarb0 =
+  [scim|
+        { "schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],
+          "id":"0",
+          "userName":"bjensen",
+          "externalId":"bjensen",
+          "name":{
+            "formatted":"Ms. Barbara J Jensen III",
+            "familyName":"Jensen",
+            "givenName":"Barbara",
+            "middleName":"Jane"
+          },
+          "emails":[
+            {
+              "value":"bjensen@example.com"
+            },
+            {
+              "value":"babs@jensen.org"
+            }
+          ],
+          "meta":{
+            "resourceType":"User",
+            "location":"https://example.com/Users/id",
+            "created":"2018-01-01T00:00:00Z",
+            "version":"W/\"testVersion\"",
+            "lastModified":"2018-01-01T00:00:00Z"
+          }
+        }|]
+
+emptyList :: ResponseMatcher
+emptyList =
+  [scim|
+       { "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
+         "Resources":[],
+         "totalResults":0,
+         "itemsPerPage":0,
+         "startIndex":1
+       }|]
diff --git a/test/Test/FilterSpec.hs b/test/Test/FilterSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Test/FilterSpec.hs
@@ -0,0 +1,89 @@
+{-# LANGUAGE AllowAmbiguousTypes #-}
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Test.FilterSpec where
+
+import Data.Text (Text, cons)
+import HaskellWorks.Hspec.Hedgehog
+import Hedgehog
+import qualified Hedgehog.Gen as Gen
+import qualified Hedgehog.Range as Range
+import Test.Hspec
+import Web.Scim.AttrName
+import Web.Scim.Filter
+import Web.Scim.Schema.Schema (Schema (..))
+import Web.Scim.Schema.User (NoUserExtra)
+import Web.Scim.Schema.UserTypes (UserTypes (supportedSchemas))
+import Web.Scim.Test.Util (TestTag)
+
+prop_roundtrip :: forall tag. UserTypes tag => Property
+prop_roundtrip = property $ do
+  x <- forAll $ genFilter @tag
+  tripping x renderFilter $ parseFilter (supportedSchemas @tag)
+
+spec :: Spec
+spec = do
+  describe "Filter" $ do
+    it "parse . render === id" $ require $ prop_roundtrip @(TestTag Text () () NoUserExtra)
+
+----------------------------------------------------------------------------
+-- Generators
+
+genValuePath :: forall tag. UserTypes tag => Gen ValuePath
+genValuePath = ValuePath <$> genAttrPath @tag <*> genFilter @tag
+
+genCompValue :: Gen CompValue
+genCompValue =
+  Gen.choice
+    [ pure ValNull,
+      ValBool <$> Gen.bool,
+      ValNumber
+        <$> Gen.choice
+          [ Gen.realFrac_ (Range.constantFrom 0 (-100) 100),
+            fromInteger <$> Gen.integral (Range.constantFrom 0 (-100) 100)
+          ],
+      ValString <$> Gen.text (Range.constant 0 1000) Gen.unicode
+    ]
+
+genCompareOp :: Gen CompareOp
+genCompareOp = Gen.enumBounded
+
+genSubAttr :: Gen SubAttr
+genSubAttr = SubAttr <$> genAttrName
+
+-- | FUTUREWORK: no support for custom schemas.
+--
+-- FUTUREWORK: we also may want to factor a bounded enum type out of the 'Schema' type for
+-- this: @data Schema = Buitin BuitinSchema | Custom Text; data BuiltinSchema = ... deriving
+-- (Bounded, Enum, ...)@
+genSchema :: forall tag. UserTypes tag => Gen Schema
+genSchema = Gen.element (supportedSchemas @tag)
+
+genAttrPath :: forall tag. UserTypes tag => Gen AttrPath
+genAttrPath = AttrPath <$> Gen.maybe (genSchema @tag) <*> genAttrName <*> Gen.maybe genSubAttr
+
+genAttrName :: Gen AttrName
+genAttrName = AttrName <$> (cons <$> Gen.alpha <*> Gen.text (Range.constant 0 50) (Gen.choice [Gen.alphaNum, Gen.constant '-', Gen.constant '_']))
+
+genFilter :: forall tag. UserTypes tag => Gen Filter
+genFilter =
+  Gen.choice
+    [ FilterAttrCompare <$> (genAttrPath @tag) <*> genCompareOp <*> genCompValue
+    ]
diff --git a/test/Test/MiscSpec.hs b/test/Test/MiscSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Test/MiscSpec.hs
@@ -0,0 +1,40 @@
+{-# LANGUAGE AllowAmbiguousTypes #-}
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Test.MiscSpec where
+
+import Data.Aeson (eitherDecode', encode)
+import Test.Hspec (Spec, describe, it, shouldBe)
+import Web.Scim.Server.Mock (Id (..))
+import Web.Scim.Test.Util ((<//>))
+
+-- | These tests are also doctests in the prod code,
+-- [but](https://github.com/zinfra/backend-issues/issues/1549).
+spec :: Spec
+spec = do
+  describe "(<//>)" $ do
+    it "works" $ do
+      "a" <//> "b" `shouldBe` "a/b"
+      "a" <//> "/b" `shouldBe` "a/b"
+      "a/" <//> "b" `shouldBe` "a/b"
+      "a/" <//> "/b" `shouldBe` "a/b"
+  describe "Id" $ do
+    it "works" $ do
+      (eitherDecode' . encode) (Id 3) `shouldBe` Right Id {unId = 3}
diff --git a/test/Test/Schema/PatchOpSpec.hs b/test/Test/Schema/PatchOpSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Test/Schema/PatchOpSpec.hs
@@ -0,0 +1,138 @@
+{-# LANGUAGE AllowAmbiguousTypes #-}
+{-# LANGUAGE QuasiQuotes #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Test.Schema.PatchOpSpec where
+
+import qualified Data.Aeson as Aeson
+import Data.Aeson.Types (Result (Error, Success), Value (String), fromJSON, toJSON)
+import qualified Data.Aeson.Types as Aeson
+import Data.Attoparsec.ByteString (parseOnly)
+import Data.Either (isLeft)
+import Data.Foldable (for_)
+import Data.HashMap.Strict (HashMap)
+import qualified Data.HashMap.Strict as HM
+import Data.Text (Text)
+import Data.Text.Encoding (decodeUtf8, encodeUtf8)
+import HaskellWorks.Hspec.Hedgehog (require)
+import Hedgehog (Gen, Property, forAll, property, tripping)
+import qualified Hedgehog.Gen as Gen
+import qualified Hedgehog.Range as Range
+import Test.FilterSpec (genAttrPath, genSubAttr, genValuePath)
+import Test.Hspec (Spec, describe, it, shouldBe, shouldSatisfy, xit)
+import Web.Scim.AttrName (AttrName (..))
+import Web.Scim.Filter (AttrPath (..), CompValue (ValNull), CompareOp (OpEq), Filter (..), ValuePath (..))
+import Web.Scim.Schema.PatchOp
+import Web.Scim.Schema.Schema (Schema (User20))
+import Web.Scim.Schema.User (UserTypes)
+import Web.Scim.Schema.UserTypes (supportedSchemas)
+import Web.Scim.Test.Util (TestTag, scim)
+
+isSuccess :: Result a -> Bool
+isSuccess (Success _) = True
+isSuccess (Error _) = False
+
+genPatchOp :: forall tag. UserTypes tag => Gen Value -> Gen (PatchOp tag)
+genPatchOp genValue = PatchOp <$> Gen.list (Range.constant 0 20) ((genOperation @tag) genValue)
+
+genOperation :: forall tag. UserTypes tag => Gen Value -> Gen Operation
+genOperation genValue = Operation <$> Gen.enumBounded <*> Gen.maybe (genPath @tag) <*> Gen.maybe genValue
+
+genPath :: forall tag. UserTypes tag => Gen Path
+genPath =
+  Gen.choice
+    [ IntoValuePath <$> (genValuePath @tag) <*> Gen.maybe genSubAttr,
+      NormalPath <$> (genAttrPath @tag)
+    ]
+
+prop_roundtrip :: forall tag. UserTypes tag => Property
+prop_roundtrip = property $ do
+  x <- forAll $ genPath @tag
+  tripping x (encodeUtf8 . rPath) (parseOnly $ pPath (supportedSchemas @tag))
+
+prop_roundtrip_PatchOp :: forall tag. UserTypes tag => Property
+prop_roundtrip_PatchOp = property $ do
+  -- Just some strings for now. However, should be constrained to what the
+  -- PatchOp is operating on in the future... We need better typed PatchOp for
+  -- this. TODO(arianvp)
+  x <- forAll (genPatchOp @tag (String <$> Gen.text (Range.constant 0 20) Gen.unicode))
+  tripping x toJSON fromJSON
+
+type PatchTestTag = TestTag () () () ()
+
+spec :: Spec
+spec = do
+  describe "Patchable" $ do
+    describe "HashMap Text Text" $ do
+      it "supports `Add` operation" $ do
+        let theMap :: HashMap Text Text = HM.empty
+            operation = Operation Add (Just $ NormalPath (AttrPath Nothing (AttrName "key") Nothing)) $ Just "value"
+        applyOperation theMap operation `shouldBe` (Right $ HM.singleton "key" "value")
+      it "supports `Replace` operation" $ do
+        let theMap :: HashMap Text Text = HM.singleton "key" "value1"
+            operation = Operation Replace (Just $ NormalPath (AttrPath Nothing (AttrName "key") Nothing)) $ Just "value2"
+        applyOperation theMap operation `shouldBe` (Right $ HM.singleton "key" "value2")
+      it "supports `Delete` operation" $ do
+        let theMap :: HashMap Text Text = HM.fromList [("key1", "value1"), ("key2", "value2")]
+            operation = Operation Remove (Just $ NormalPath (AttrPath Nothing (AttrName "key1") Nothing)) Nothing
+        applyOperation theMap operation `shouldBe` (Right $ HM.singleton "key2" "value2")
+      it "gracefully rejects invalid/unsupported operations" $ do
+        let theMap :: HashMap Text Text = HM.fromList [("key1", "value1"), ("key2", "value2")]
+            key1Path = (AttrPath Nothing (AttrName "key1") Nothing)
+            key2Path = (AttrPath Nothing (AttrName "key2") Nothing)
+            invalidOperations =
+              [ Operation Add (Just $ NormalPath key1Path) Nothing, -- Nothing to add
+                Operation Replace (Just $ NormalPath key1Path) Nothing, -- Nothing to replace
+                Operation Add (Just $ IntoValuePath (ValuePath key1Path (FilterAttrCompare key2Path OpEq ValNull)) Nothing) Nothing
+                -- IntoValuePaths don't make sense for HashMap Text Text
+              ]
+        mapM_ (\o -> applyOperation theMap o `shouldSatisfy` isLeft) invalidOperations
+  describe "urn:ietf:params:scim:api:messages:2.0:PatchOp" $ do
+    describe "The body of each request MUST contain the \"schemas\" attribute with the URI value of \"urn:ietf:params:scim:api:messages:2.0:PatchOp\"." $ do
+      it "rejects an empty schemas list" $ do
+        fromJSON @(PatchOp PatchTestTag)
+          [scim| {
+          "schemas": [],
+          "operations": []
+        }|]
+          `shouldSatisfy` (not . isSuccess)
+    --TODO(arianvp): We don't support arbitrary path names (yet)
+    it "roundtrips Path" $ require $ prop_roundtrip @PatchTestTag
+    it "roundtrips PatchOp" $ require $ prop_roundtrip_PatchOp @PatchTestTag
+    it "rejects invalid operations" $ do
+      fromJSON @(PatchOp PatchTestTag)
+        [scim| {
+          "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+          "operations": [{"op":"unknown"}]
+      }|]
+        `shouldSatisfy` (not . isSuccess)
+    -- TODO(arianvp/akshay): Implement if required
+    xit "rejects unknown paths" $ do
+      Aeson.parse (pathFromJSON [User20]) (Aeson.String "unknown.field") `shouldSatisfy` (not . isSuccess)
+    it "rejects invalid paths" $ do
+      Aeson.parse (pathFromJSON [User20]) "unknown]field" `shouldSatisfy` (not . isSuccess)
+    describe "Examples from https://tools.ietf.org/html/rfc7644#section-3.5.2 Figure 8" $ do
+      let examples =
+            [ "members",
+              "name.familyname",
+              "addresses[type eq \"work\"]",
+              "members[value eq \"2819c223-7f76-453a-919d-413861904646\"]",
+              "members[value eq \"2819c223-7f76-453a-919d-413861904646\"].displayname"
+            ]
+      for_ examples $ \p -> it ("parses " ++ show p) $ (rPath <$> parseOnly (pPath (supportedSchemas @PatchTestTag)) p) `shouldBe` Right (decodeUtf8 p)
diff --git a/test/Test/Schema/UserSpec.hs b/test/Test/Schema/UserSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Test/Schema/UserSpec.hs
@@ -0,0 +1,482 @@
+{-# LANGUAGE QuasiQuotes #-}
+{-# LANGUAGE TypeApplications #-}
+{-# LANGUAGE ViewPatterns #-}
+
+-- This file is part of the Wire Server implementation.
+--
+-- Copyright (C) 2020 Wire Swiss GmbH <opensource@wire.com>
+--
+-- This program is free software: you can redistribute it and/or modify it under
+-- the terms of the GNU Affero General Public License as published by the Free
+-- Software Foundation, either version 3 of the License, or (at your option) any
+-- later version.
+--
+-- This program is distributed in the hope that it will be useful, but WITHOUT
+-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
+-- details.
+--
+-- You should have received a copy of the GNU Affero General Public License along
+-- with this program. If not, see <https://www.gnu.org/licenses/>.
+
+module Test.Schema.UserSpec
+  ( spec,
+  )
+where
+
+import Data.Aeson
+import Data.Either (isLeft, isRight)
+import Data.Foldable (for_)
+import qualified Data.HashMap.Strict as HM
+import Data.Text (Text, toLower, toUpper)
+import HaskellWorks.Hspec.Hedgehog (require)
+import Hedgehog
+import qualified Hedgehog.Gen as Gen
+import qualified Hedgehog.Range as Range
+import Lens.Micro
+import Network.URI.Static (uri)
+import Test.Hspec
+import Text.Email.Validate (emailAddress)
+import Web.Scim.Filter (AttrPath (..))
+import Web.Scim.Schema.Common (ScimBool (ScimBool), URI (..))
+import Web.Scim.Schema.PatchOp (Op (..), Operation (..), PatchOp (..), Patchable (..), Path (..))
+import qualified Web.Scim.Schema.PatchOp as PatchOp
+import Web.Scim.Schema.Schema (Schema (..))
+import Web.Scim.Schema.User (NoUserExtra (..), User (..))
+import qualified Web.Scim.Schema.User as User
+import Web.Scim.Schema.User.Address as Address
+import Web.Scim.Schema.User.Certificate as Certificate
+import Web.Scim.Schema.User.Email as Email
+import Web.Scim.Schema.User.IM as IM
+import Web.Scim.Schema.User.Name as Name
+import Web.Scim.Schema.User.Phone as Phone
+import Web.Scim.Schema.User.Photo as Photo
+import Web.Scim.Test.Util
+
+prop_roundtrip :: Property
+prop_roundtrip = property $ do
+  user <- forAll genUser
+  tripping user toJSON fromJSON
+
+-- TODO(arianvp): Note that this only tests the top-level fields.
+-- extrac this to a generic test and also do this for sub-properties
+prop_caseInsensitive :: Property
+prop_caseInsensitive = property $ do
+  user <- forAll genUser
+  let (Object user') = toJSON user
+  let user'' = HM.foldlWithKey' (\u k v -> HM.insert (toUpper k) v u) user' HM.empty
+  let user''' = HM.foldlWithKey' (\u k v -> HM.insert (toLower k) v u) user' HM.empty
+  fromJSON (Object user'') === Success user
+  fromJSON (Object user''') === Success user
+
+type PatchTag = TestTag Text () () UserExtraPatch
+
+type UserExtraPatch = HM.HashMap Text Text
+
+spec :: Spec
+spec = do
+  describe "applyPatch" $ do
+    it "only applies patch for supported fields" $ do
+      let schemas' = []
+      let extras = HM.empty
+      let user :: User PatchTag = User.empty schemas' "hello" extras
+      for_
+        [ ("username", String "lol"),
+          ("displayname", String "lol"),
+          ("externalid", String "lol"),
+          ("active", Bool True)
+        ]
+        $ \(key, upd) -> do
+          let operation = Operation Replace (Just (NormalPath (AttrPath Nothing key Nothing))) (Just upd)
+          let patchOp = PatchOp [operation]
+          User.applyPatch user patchOp `shouldSatisfy` isRight
+    it "does not support multi-value attributes" $ do
+      let schemas' = []
+      let extras = HM.empty
+      let user :: User PatchTag = User.empty schemas' "hello" extras
+      for_
+        [ ("schemas", toJSON @[Schema] mempty),
+          ("name", toJSON @Name emptyName),
+          ("nickName", toJSON @Text mempty),
+          ("profileUrl", toJSON @URI (URI [uri|https://example.com|])),
+          ("title", toJSON @Text mempty),
+          ("userType", toJSON @Text mempty),
+          ("preferredLanguage", toJSON @Text mempty),
+          ("locale", toJSON @Text mempty),
+          ("password", toJSON @Text mempty),
+          ("emails", toJSON @[Email] mempty),
+          ("phoneNumbers", toJSON @[Phone] mempty),
+          ("ims", toJSON @[IM] mempty),
+          ("photos", toJSON @[Photo] mempty),
+          ("addresses", toJSON @[Address] mempty),
+          ("entitlements", toJSON @[Text] mempty),
+          ("roles", toJSON @[Text] mempty),
+          ("x509Certificates", toJSON @[Certificate] mempty)
+        ]
+        $ \(key, upd) -> do
+          let operation = Operation Replace (Just (NormalPath (AttrPath Nothing key Nothing))) (Just upd)
+          let patchOp = PatchOp [operation]
+          User.applyPatch user patchOp `shouldSatisfy` isLeft
+    it "applies patch to `extra`" $ do
+      let schemas' = []
+      let extras = HM.empty
+      let user :: User PatchTag = User.empty schemas' "hello" extras
+      let Right programmingLanguagePath = PatchOp.parsePath (User.supportedSchemas @PatchTag) "urn:hscim:test:programmingLanguage"
+      let operation = Operation Replace (Just programmingLanguagePath) (Just (toJSON @Text "haskell"))
+      let patchOp = PatchOp [operation]
+      User.extra <$> (User.applyPatch user patchOp) `shouldBe` Right (HM.singleton "programmingLanguage" "haskell")
+  describe "JSON serialization" $ do
+    it "handles all fields" $ do
+      require prop_roundtrip
+      toJSON completeUser `shouldBe` completeUserJson
+      eitherDecode (encode completeUserJson) `shouldBe` Right completeUser
+    it "has defaults for all optional and multi-valued fields" $ do
+      toJSON minimalUser `shouldBe` minimalUserJson
+      eitherDecode (encode minimalUserJson) `shouldBe` Right minimalUser
+    it "treats 'null' and '[]' as absence of fields" $
+      eitherDecode (encode minimalUserJsonRedundant) `shouldBe` Right minimalUser
+    it "allows casing variations in field names" $ do
+      require prop_caseInsensitive
+      eitherDecode (encode minimalUserJsonNonCanonical) `shouldBe` Right minimalUser
+    it "doesn't require the 'schemas' field" $
+      eitherDecode (encode minimalUserJsonNoSchemas) `shouldBe` Right minimalUser
+    it "doesn't add 'extra' if it's an empty object" $ do
+      toJSON (extendedUser UserExtraEmpty) `shouldBe` extendedUserEmptyJson
+      eitherDecode (encode extendedUserEmptyJson)
+        `shouldBe` Right (extendedUser UserExtraEmpty)
+    it "encodes and decodes 'extra' correctly" $ do
+      toJSON (extendedUser (UserExtraObject "foo")) `shouldBe` extendedUserObjectJson
+      eitherDecode (encode extendedUserObjectJson)
+        `shouldBe` Right (extendedUser (UserExtraObject "foo"))
+
+genName :: Gen Name
+genName =
+  Name
+    <$> Gen.maybe (Gen.text (Range.constant 0 20) Gen.unicode)
+    <*> Gen.maybe (Gen.text (Range.constant 0 20) Gen.unicode)
+    <*> Gen.maybe (Gen.text (Range.constant 0 20) Gen.unicode)
+    <*> Gen.maybe (Gen.text (Range.constant 0 20) Gen.unicode)
+    <*> Gen.maybe (Gen.text (Range.constant 0 20) Gen.unicode)
+    <*> Gen.maybe (Gen.text (Range.constant 0 20) Gen.unicode)
+
+genUri :: Gen URI
+genUri = Gen.element [URI [uri|https://example.com|]]
+
+-- TODO(arianvp) Generate the lists too, but first need better support for SCIM
+-- lists in the first place
+genUser :: Gen (User (TestTag Text () () NoUserExtra))
+genUser = do
+  schemas' <- pure [User20] -- TODO random schemas or?
+  userName' <- Gen.text (Range.constant 0 20) Gen.unicode
+  externalId' <- Gen.maybe $ Gen.text (Range.constant 0 20) Gen.unicode
+  name' <- Gen.maybe genName
+  displayName' <- Gen.maybe $ Gen.text (Range.constant 0 20) Gen.unicode
+  nickName' <- Gen.maybe $ Gen.text (Range.constant 0 20) Gen.unicode
+  profileUrl' <- Gen.maybe $ genUri
+  title' <- Gen.maybe $ Gen.text (Range.constant 0 20) Gen.unicode
+  userType' <- Gen.maybe $ Gen.text (Range.constant 0 20) Gen.unicode
+  preferredLanguage' <- Gen.maybe $ Gen.text (Range.constant 0 20) Gen.unicode
+  locale' <- Gen.maybe $ Gen.text (Range.constant 0 20) Gen.unicode
+  active' <- Gen.maybe $ (ScimBool <$> Gen.bool)
+  password' <- Gen.maybe $ Gen.text (Range.constant 0 20) Gen.unicode
+  emails' <- pure [] -- Gen.list (Range.constant 0 20) genEmail
+  phoneNumbers' <- pure [] -- Gen.list (Range.constant 0 20) genPhone
+  ims' <- pure [] -- Gen.list (Range.constant 0 20) genIM
+  photos' <- pure [] -- Gen.list (Range.constant 0 20) genPhoto
+  addresses' <- pure [] -- Gen.list (Range.constant 0 20) genAddress
+  entitlements' <- pure [] -- Gen.list (Range.constant 0 20) (Gen.text (Range.constant 0 20) Gen.unicode)
+  roles' <- pure [] -- Gen.list (Range.constant 0 20) (Gen.text (Range.constant 0 10) Gen.unicode)
+  x509Certificates' <- pure [] -- Gen.list (Range.constant 0 20) genCertificate
+  pure $
+    User
+      { schemas = schemas',
+        userName = userName',
+        externalId = externalId',
+        name = name',
+        displayName = displayName',
+        nickName = nickName',
+        profileUrl = profileUrl',
+        title = title',
+        userType = userType',
+        preferredLanguage = preferredLanguage',
+        locale = locale',
+        active = active',
+        password = password',
+        emails = emails',
+        phoneNumbers = phoneNumbers',
+        ims = ims',
+        photos = photos',
+        addresses = addresses',
+        entitlements = entitlements',
+        roles = roles',
+        x509Certificates = x509Certificates',
+        extra = NoUserExtra
+      }
+
+-- | A 'User' with all attributes present.
+completeUser :: User (TestTag Text () () NoUserExtra)
+completeUser =
+  User
+    { schemas = [User20],
+      userName = "sample userName",
+      externalId = Just "sample externalId",
+      name =
+        Just $
+          Name
+            { Name.formatted = Just "sample formatted name",
+              Name.familyName = Nothing,
+              Name.givenName = Nothing,
+              Name.middleName = Nothing,
+              Name.honorificPrefix = Nothing,
+              Name.honorificSuffix = Nothing
+            },
+      displayName = Just "sample displayName",
+      nickName = Just "sample nickName",
+      profileUrl = Just (URI [uri|https://example.com|]),
+      title = Just "sample title",
+      userType = Just "sample userType",
+      preferredLanguage = Just "da, en-gb;q=0.8, en;q=0.7",
+      locale = Just "en-US",
+      active = Just (ScimBool True),
+      password = Just "sample password",
+      emails =
+        [ Email
+            { Email.typ = Just "work",
+              Email.value =
+                maybe
+                  (error "couldn't parse email")
+                  EmailAddress2
+                  (emailAddress "user@example.com"),
+              Email.primary = Nothing
+            }
+        ],
+      phoneNumbers =
+        [ Phone
+            { Phone.typ = Just "work",
+              Phone.value = Just "+15417543010"
+            }
+        ],
+      ims =
+        [ IM
+            { IM.typ = Just "Wire",
+              IM.value = Just "@user"
+            }
+        ],
+      photos =
+        [ Photo
+            { Photo.typ = Just "userpic",
+              Photo.value = Just (URI [uri|https://example.com/userpic.png|])
+            }
+        ],
+      addresses =
+        [ Address
+            { Address.formatted = Just "sample Address",
+              Address.streetAddress = Nothing,
+              Address.locality = Nothing,
+              Address.region = Nothing,
+              Address.postalCode = Nothing,
+              Address.country = Nothing,
+              Address.typ = Just "home",
+              Address.primary = Just (ScimBool True)
+            }
+        ],
+      entitlements = ["sample entitlement"],
+      roles = ["sample role"],
+      x509Certificates =
+        [ Certificate
+            { Certificate.typ = Just "sample certificate type",
+              Certificate.value = Just "sample certificate"
+            }
+        ],
+      extra = NoUserExtra
+    }
+
+-- | Reference encoding of 'completeUser'.
+completeUserJson :: Value
+completeUserJson =
+  [scim|
+{
+  "roles": [
+    "sample role"
+  ],
+  "x509Certificates": [
+    {
+      "value": "sample certificate",
+      "type": "sample certificate type"
+    }
+  ],
+  "schemas": [
+    "urn:ietf:params:scim:schemas:core:2.0:User"
+  ],
+  "locale": "en-US",
+  "addresses": [
+    {
+      "formatted": "sample Address",
+      "primary": true,
+      "type": "home"
+    }
+  ],
+  "userName": "sample userName",
+  "phoneNumbers": [
+    {
+      "value": "+15417543010",
+      "type": "work"
+    }
+  ],
+  "active": true,
+  "photos": [
+    {
+      "value": "https://example.com/userpic.png",
+      "type": "userpic"
+    }
+  ],
+  "name": {
+    "formatted": "sample formatted name"
+  },
+  "password": "sample password",
+  "emails": [
+    {
+      "value": "user@example.com",
+      "type": "work"
+    }
+  ],
+  "ims": [
+    {
+      "value": "@user",
+      "type": "Wire"
+    }
+  ],
+  "preferredLanguage": "da, en-gb;q=0.8, en;q=0.7",
+  "entitlements": [
+    "sample entitlement"
+  ],
+  "displayName": "sample displayName",
+  "nickName": "sample nickName",
+  "profileUrl": "https://example.com",
+  "title": "sample title",
+  "externalId": "sample externalId",
+  "userType": "sample userType"
+}
+|]
+
+-- | A 'User' with all attributes empty (if possible).
+minimalUser :: User (TestTag Text () () NoUserExtra)
+minimalUser = User.empty [User20] "sample userName" NoUserExtra
+
+-- | Reference encoding of 'minimalUser'.
+minimalUserJson :: Value
+minimalUserJson =
+  [scim|
+{
+  "schemas": [
+    "urn:ietf:params:scim:schemas:core:2.0:User"
+  ],
+  "userName": "sample userName"
+}
+|]
+
+-- | An encoding of 'minimalUser' with redundant @null@s and @[]@s for missing
+-- fields.
+minimalUserJsonRedundant :: Value
+minimalUserJsonRedundant =
+  [scim|
+{
+  "schemas": [
+    "urn:ietf:params:scim:schemas:core:2.0:User"
+  ],
+  "roles": [],
+  "x509Certificates": [],
+  "locale": null,
+  "addresses": [],
+  "userName": "sample userName",
+  "phoneNumbers": [],
+  "active": null,
+  "photos": [],
+  "name": null,
+  "password": null,
+  "emails": [],
+  "ims": [],
+  "preferredLanguage": null,
+  "entitlements": [],
+  "displayName": null,
+  "nickName": null,
+  "profileUrl": null,
+  "title": null,
+  "externalId": null,
+  "userType": null
+}
+|]
+
+-- | An encoding of 'minimalUser' with non-canonical field name casing.
+minimalUserJsonNonCanonical :: Value
+minimalUserJsonNonCanonical =
+  [scim|
+{
+  "schemas": [
+    "urn:ietf:params:scim:schemas:core:2.0:User"
+  ],
+  "USERname": "sample userName"
+}
+|]
+
+-- | An encoding of 'minimalUser' without the @schemas@ field.
+minimalUserJsonNoSchemas :: Value
+minimalUserJsonNoSchemas =
+  [scim|
+{
+  "userName": "sample userName"
+}
+|]
+
+data UserExtraTest = UserExtraEmpty | UserExtraObject {test :: Text}
+  deriving (Show, Eq)
+
+instance FromJSON UserExtraTest where
+  parseJSON = withObject "UserExtraObject" $ \(lowercase -> o) -> do
+    o .:? "urn:hscim:test" >>= \case
+      Nothing -> pure UserExtraEmpty
+      Just (lowercase -> o2) -> UserExtraObject <$> o2 .: "test"
+    where
+      lowercase = HM.fromList . map (over _1 toLower) . HM.toList
+
+instance ToJSON UserExtraTest where
+  toJSON UserExtraEmpty = object []
+  toJSON (UserExtraObject t) =
+    object ["urn:hscim:test" .= object ["test" .= t]]
+
+instance Patchable UserExtraTest where
+  applyOperation _ _ = undefined
+
+-- | A 'User' with extra fields present.
+extendedUser :: UserExtraTest -> User (TestTag Text () () UserExtraTest)
+extendedUser e =
+  (User.empty [User20, CustomSchema "urn:hscim:test"] "sample userName" e)
+
+-- | Encoding of @extendedUser UserExtraEmpty@.
+extendedUserEmptyJson :: Value
+extendedUserEmptyJson =
+  [scim|
+{
+  "schemas": [
+    "urn:ietf:params:scim:schemas:core:2.0:User",
+    "urn:hscim:test"
+  ],
+  "userName": "sample userName"
+}
+|]
+
+-- | Encoding of @extendedUser (UserExtraObject "foo")@.
+extendedUserObjectJson :: Value
+extendedUserObjectJson =
+  [scim|
+{
+  "schemas": [
+    "urn:ietf:params:scim:schemas:core:2.0:User",
+    "urn:hscim:test"
+  ],
+  "userName": "sample userName",
+  "urn:hscim:test": {
+    "test": "foo"
+  }
+}
+|]
