diff --git a/build/ubuntu/Dockerfile.builder b/build/ubuntu/Dockerfile.builder index bd919ee5d1..0c13f93b8e 100644 --- a/build/ubuntu/Dockerfile.builder +++ b/build/ubuntu/Dockerfile.builder @@ -19,7 +19,7 @@ RUN cd /tmp && \ git checkout 6370cd556f03f6834d0b8043615ffaf0044ef1fa && \ git rev-parse HEAD -RUN cd /tmp/rusty-jwt-tools && cargo build --release --target x86_64-unknown-linux-gnu +RUN cd /tmp/rusty-jwt-tools && cargo build --features haskell --release --target x86_64-unknown-linux-gnu FROM ${prebuilder} diff --git a/build/ubuntu/Dockerfile.deps b/build/ubuntu/Dockerfile.deps index 458f71f01a..d9290aa544 100644 --- a/build/ubuntu/Dockerfile.deps +++ b/build/ubuntu/Dockerfile.deps @@ -29,7 +29,7 @@ RUN cd /tmp && \ git checkout 6370cd556f03f6834d0b8043615ffaf0044ef1fa && \ git rev-parse HEAD -RUN cd /tmp/rusty-jwt-tools && cargo build --release --target x86_64-unknown-linux-gnu +RUN cd /tmp/rusty-jwt-tools && cargo build --features haskell --release --target x86_64-unknown-linux-gnu # Minimal dependencies for ubuntu-compiled, dynamically linked wire-server Haskell services diff --git a/cabal.project b/cabal.project index b6beec6f68..adf9ae39ab 100644 --- a/cabal.project +++ b/cabal.project @@ -16,6 +16,7 @@ packages: , libs/gundeck-types/ , libs/hscim/ , libs/imports/ + , libs/jwt-tools/ , libs/metrics-core/ , libs/metrics-wai/ , libs/polysemy-wire-zoo/ @@ -219,6 +220,8 @@ package hscim ghc-options: -Werror package imports ghc-options: -Werror +package jwt-tools + ghc-options: -Werror package metrics-core ghc-options: -Werror package metrics-wai diff --git a/changelog.d/5-internal/pr-2652 b/changelog.d/5-internal/pr-2652 new file mode 100644 index 0000000000..c51514fc22 --- /dev/null +++ b/changelog.d/5-internal/pr-2652 @@ -0,0 +1 @@ +Skeleton implementation of new endpoint for JWT DPoP access token generation (#2652, #2686) diff --git a/charts/brig/templates/configmap.yaml b/charts/brig/templates/configmap.yaml index 196b978a36..7036c716e4 100644 --- a/charts/brig/templates/configmap.yaml +++ b/charts/brig/templates/configmap.yaml @@ -287,5 +287,14 @@ data: {{- if .setNonceTtlSecs }} setNonceTtlSecs: {{ .setNonceTtlSecs }} {{- end }} + {{- if .setDpopMaxSkewSecs }} + setDpopMaxSkewSecs: {{ .setDpopMaxSkewSecs }} + {{- end }} + {{- if .setDpopTokenExpirationTimeSecs }} + setDpopTokenExpirationTimeSecs: {{ .setDpopTokenExpirationTimeSecs }} + {{- end }} + {{- if $.Values.secrets.dpopSigKeyBundle }} + setPublicKeyBundle: /etc/wire/brig/secrets/dpop_sig_key_bundle.pem + {{- end }} {{- end }} {{- end }} diff --git a/charts/brig/templates/secret.yaml b/charts/brig/templates/secret.yaml index 2ffebba629..dd967b4a67 100644 --- a/charts/brig/templates/secret.yaml +++ b/charts/brig/templates/secret.yaml @@ -25,4 +25,8 @@ data: {{- if (not $.Values.config.useSES) }} smtp-password.txt: {{ .smtpPassword | b64enc | quote }} {{- end }} + {{- if .dpopSigKeyBundle }} + dpop_sig_key_bundle.pem: {{ .dpopSigKeyBundle | b64enc | quote }} {{- end }} + {{- end }} + diff --git a/charts/brig/values.yaml b/charts/brig/values.yaml index efb2ecf525..31cac4fc9a 100644 --- a/charts/brig/values.yaml +++ b/charts/brig/values.yaml @@ -85,6 +85,8 @@ config: # - example.com set2FACodeGenerationDelaySecs: 300 # 5 minutes setNonceTtlSecs: 300 # 5 minutes + setDpopMaxSkewSecs: 1 + setDpopTokenExpirationTimeSecs: 300 # 5 minutes smtp: passwordFile: /etc/wire/brig/secrets/smtp-password.txt proxy: {} diff --git a/charts/nginz/values.yaml b/charts/nginz/values.yaml index bb6790f8e0..2e2622c554 100644 --- a/charts/nginz/values.yaml +++ b/charts/nginz/values.yaml @@ -484,9 +484,6 @@ nginx_conf: - path: /mls/public-keys envs: - all - - path: /nonce/clients - envs: - - all gundeck: - path: /push/api-docs$ envs: diff --git a/deploy/services-demo/conf/brig.demo-docker.yaml b/deploy/services-demo/conf/brig.demo-docker.yaml index a0ca16fadc..bed2160b0c 100644 --- a/deploy/services-demo/conf/brig.demo-docker.yaml +++ b/deploy/services-demo/conf/brig.demo-docker.yaml @@ -116,6 +116,8 @@ optSettings: setEmailVisibility: visible_to_self setFederationDomain: example.com setNonceTtlSecs: 300 # 5 minutes + setDpopMaxSkewSecs: 1 + setDpopTokenExpirationTimeSecs: 300 # 5 minutes logLevel: Debug logNetStrings: false diff --git a/deploy/services-demo/conf/brig.demo.yaml b/deploy/services-demo/conf/brig.demo.yaml index 437de1417f..b914240114 100644 --- a/deploy/services-demo/conf/brig.demo.yaml +++ b/deploy/services-demo/conf/brig.demo.yaml @@ -117,6 +117,9 @@ optSettings: setEmailVisibility: visible_to_self setFederationDomain: example.com setNonceTtlSecs: 300 # 5 minutes + setDpopMaxSkewSecs: 1 + setDpopTokenExpirationTimeSecs: 300 # 5 minutes + setPublicKeyBundle: conf/jwt/ed25519_bundle.pem logLevel: Debug logNetStrings: false diff --git a/deploy/services-demo/conf/jwt/ed25519_bundle.pem b/deploy/services-demo/conf/jwt/ed25519_bundle.pem new file mode 100644 index 0000000000..afbd4dfb0e --- /dev/null +++ b/deploy/services-demo/conf/jwt/ed25519_bundle.pem @@ -0,0 +1,6 @@ +-----BEGIN PRIVATE KEY----- +MC4CAQAwBQYDK2VwBCIEIFANnxZLNE4p+GDzWzR3wm/v8x/0bxZYkCyke1aTRucX +-----END PRIVATE KEY----- +-----BEGIN PUBLIC KEY----- +MCowBQYDK2VwAyEACPvhIdimF20tOPjbb+fXJrwS2RKDp7686T90AZ0+Th8= +-----END PUBLIC KEY----- diff --git a/deploy/services-demo/conf/nginz/nginx.conf b/deploy/services-demo/conf/nginz/nginx.conf index cc60d3f9f1..10e7a546ab 100644 --- a/deploy/services-demo/conf/nginz/nginx.conf +++ b/deploy/services-demo/conf/nginz/nginx.conf @@ -286,11 +286,6 @@ http { proxy_pass http://brig; } - location /nonce/clients { - include common_response_with_zauth.conf; - proxy_pass http://brig; - } - # Cargohold Endpoints rewrite ^/api-docs/assets /assets/api-docs?base_url=http://127.0.0.1:8080/ break; diff --git a/hack/helm_vars/wire-server/values.yaml.gotmpl b/hack/helm_vars/wire-server/values.yaml.gotmpl index fa1da9a772..44366ec19d 100644 --- a/hack/helm_vars/wire-server/values.yaml.gotmpl +++ b/hack/helm_vars/wire-server/values.yaml.gotmpl @@ -83,6 +83,8 @@ brig: search_policy: full_search set2FACodeGenerationDelaySecs: 5 setNonceTtlSecs: 300 + setDpopMaxSkewSecs: 1 + setDpopTokenExpirationTimeSecs: 300 aws: sesEndpoint: http://fake-aws-ses:4569 sqsEndpoint: http://fake-aws-sqs:4568 @@ -111,6 +113,13 @@ brig: key: "dummy" secret: "dummy" smtpPassword: dummy-smtp-password + dpopSigKeyBundle: | + -----BEGIN PRIVATE KEY----- + MC4CAQAwBQYDK2VwBCIEIFANnxZLNE4p+GDzWzR3wm/v8x/0bxZYkCyke1aTRucX + -----END PRIVATE KEY----- + -----BEGIN PUBLIC KEY----- + MCowBQYDK2VwAyEACPvhIdimF20tOPjbb+fXJrwS2RKDp7686T90AZ0+Th8= + -----END PUBLIC KEY----- tests: enableFederationTests: true cannon: diff --git a/libs/jwt-tools/LICENSE b/libs/jwt-tools/LICENSE new file mode 100644 index 0000000000..dba13ed2dd --- /dev/null +++ b/libs/jwt-tools/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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 +. diff --git a/libs/jwt-tools/jwt-tools.cabal b/libs/jwt-tools/jwt-tools.cabal new file mode 100644 index 0000000000..e4eb1a6b9a --- /dev/null +++ b/libs/jwt-tools/jwt-tools.cabal @@ -0,0 +1,144 @@ +cabal-version: 1.12 +name: jwt-tools +version: 0.1.0 +synopsis: FFI to rusty-jwt-tools +description: FFI to rusty-jwt-tools +category: Cryptography +author: Wire Swiss GmbH +maintainer: Wire Swiss GmbH +copyright: (c) 2017 Wire Swiss GmbH +license: AGPL-3 +license-file: LICENSE +build-type: Simple + +library + exposed-modules: Data.Jwt.Tools + hs-source-dirs: src + other-modules: Paths_jwt_tools + default-extensions: + NoImplicitPrelude + AllowAmbiguousTypes + BangPatterns + ConstraintKinds + DataKinds + DefaultSignatures + DeriveFunctor + DeriveGeneric + DeriveLift + DeriveTraversable + DerivingStrategies + DerivingVia + EmptyCase + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + InstanceSigs + KindSignatures + LambdaCase + MultiParamTypeClasses + MultiWayIf + NamedFieldPuns + OverloadedStrings + PackageImports + PatternSynonyms + PolyKinds + QuasiQuotes + RankNTypes + ScopedTypeVariables + StandaloneDeriving + TupleSections + TypeApplications + TypeFamilies + TypeFamilyDependencies + TypeOperators + UndecidableInstances + ViewPatterns + + ghc-options: + -O2 -Wall -Wincomplete-uni-patterns -Wincomplete-record-updates + -Wpartial-fields -fwarn-tabs -optP-Wno-nonportable-include-path + + build-depends: + base + , base64-bytestring + , bytestring + , bytestring-conversion + , http-types + , imports + , QuickCheck + , string-conversions + , transformers + , unliftio + + default-language: Haskell2010 + other-extensions: ForeignFunctionInterface + extra-libraries: + rusty_jwt_tools_ffi + pthread + +test-suite jwt-tools-tests + main-is: Spec.hs + type: exitcode-stdio-1.0 + build-depends: + base + , base64-bytestring + , bytestring + , bytestring-conversion + , either + , extra + , hspec + , http-types + , imports + , jwt-tools + , QuickCheck + , string-conversions + , text + , transformers + , uuid + + hs-source-dirs: test + default-language: Haskell2010 + ghc-options: + -O2 -Wall -Wincomplete-uni-patterns -Wincomplete-record-updates + -Wpartial-fields -fwarn-tabs -optP-Wno-nonportable-include-path + + default-extensions: + NoImplicitPrelude + AllowAmbiguousTypes + BangPatterns + ConstraintKinds + DataKinds + DefaultSignatures + DeriveFunctor + DeriveGeneric + DeriveLift + DeriveTraversable + DerivingStrategies + DerivingVia + EmptyCase + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + InstanceSigs + KindSignatures + LambdaCase + MultiParamTypeClasses + MultiWayIf + NamedFieldPuns + OverloadedStrings + PackageImports + PatternSynonyms + PolyKinds + QuasiQuotes + RankNTypes + ScopedTypeVariables + StandaloneDeriving + TupleSections + TypeApplications + TypeFamilies + TypeFamilyDependencies + TypeOperators + UndecidableInstances + ViewPatterns diff --git a/libs/jwt-tools/src/Data/Jwt/Tools.hs b/libs/jwt-tools/src/Data/Jwt/Tools.hs new file mode 100644 index 0000000000..11edd177bf --- /dev/null +++ b/libs/jwt-tools/src/Data/Jwt/Tools.hs @@ -0,0 +1,285 @@ +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE GeneralizedNewtypeDeriving #-} + +-- This file is part of the Wire Server implementation. +-- +-- Copyright (C) 2022 Wire Swiss GmbH +-- +-- 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 . + +module Data.Jwt.Tools + ( generateDpopToken, + toResult, + DPoPTokenGenerationError (..), + Proof (..), + UserId (..), + ClientId (..), + Domain (..), + Nonce (..), + Uri (..), + StdMethod (..), + MaxSkewSecs (..), + ExpiryEpoch (..), + NowEpoch (..), + PemBundle (..), + ) +where + +import Control.Exception +import Control.Monad.Trans.Except +import Data.ByteString.Conversion +import Data.String.Conversions (cs) +import Foreign.C (CUChar (..)) +import Foreign.C.String (CString, newCString, peekCString) +import Foreign.Ptr (Ptr, nullPtr) +import Foreign.Storable (peek) +import Imports +import Network.HTTP.Types (StdMethod (..)) + +data JwtResponse + +type ProofCStr = CString + +type UserIdCStr = CString + +type ClientIdWord16 = Word16 + +type DomainCStr = CString + +type NonceCStr = CString + +type UrlCStr = CString + +type MethodCStr = CString + +type MaxSkewSecsWord16 = Word16 + +type ExpiryEpochWord64 = Word64 + +type EpochWord64 = Word64 + +type BackendBundleCStr = CString + +foreign import ccall unsafe "generate_dpop_access_token" + generate_dpop_access_token :: + ProofCStr -> + UserIdCStr -> + ClientIdWord16 -> + DomainCStr -> + NonceCStr -> + UrlCStr -> + MethodCStr -> + MaxSkewSecsWord16 -> + ExpiryEpochWord64 -> + EpochWord64 -> + BackendBundleCStr -> + IO (Ptr JwtResponse) + +foreign import ccall unsafe "free_dpop_access_token" free_dpop_access_token :: Ptr JwtResponse -> IO () + +foreign import ccall unsafe "get_error" get_error :: Ptr JwtResponse -> Ptr CUChar + +foreign import ccall unsafe "get_token" get_token :: Ptr JwtResponse -> CString + +generateDpopAccessTokenFfi :: + ProofCStr -> + UserIdCStr -> + ClientIdWord16 -> + DomainCStr -> + NonceCStr -> + UrlCStr -> + MethodCStr -> + MaxSkewSecsWord16 -> + ExpiryEpochWord64 -> + EpochWord64 -> + BackendBundleCStr -> + IO (Maybe (Ptr JwtResponse)) +generateDpopAccessTokenFfi dpopProof user client domain nonce uri method maxSkewSecs expiration now backendKeys = do + ptr <- generate_dpop_access_token dpopProof user client domain nonce uri method maxSkewSecs expiration now backendKeys + if ptr /= nullPtr + then pure $ Just ptr + else pure Nothing + +getErrorFfi :: Ptr JwtResponse -> IO (Maybe Word8) +getErrorFfi ptr = do + let errorPtr = get_error ptr + if errorPtr /= nullPtr + then Just . fromIntegral <$> peek errorPtr + else pure Nothing + +getTokenFfi :: Ptr JwtResponse -> IO (Maybe String) +getTokenFfi ptr = do + let tokenPtr = get_token ptr + if tokenPtr /= nullPtr + then Just <$> peekCString tokenPtr + else pure Nothing + +generateDpopToken :: + (MonadIO m) => + Proof -> + UserId -> + ClientId -> + Domain -> + Nonce -> + Uri -> + StdMethod -> + MaxSkewSecs -> + ExpiryEpoch -> + NowEpoch -> + PemBundle -> + ExceptT DPoPTokenGenerationError m ByteString +generateDpopToken dpopProof uid cid domain nonce uri method maxSkewSecs maxExpiration now backendPubkeyBundle = do + dpopProofCStr <- toCStr dpopProof + uidCStr <- toCStr uid + domainCStr <- toCStr domain + nonceCStr <- toCStr nonce + uriCStr <- toCStr uri + methodCStr <- liftIO $ newCString $ cs $ methodToBS method + backendPubkeyBundleCStr <- toCStr backendPubkeyBundle + + let before = + generateDpopAccessTokenFfi + dpopProofCStr + uidCStr + (_unClientId cid) + domainCStr + nonceCStr + uriCStr + methodCStr + (_unMaxSkewSecs maxSkewSecs) + (_unExpiryEpoch maxExpiration) + (_unNowEpoch now) + backendPubkeyBundleCStr + + let mkAccessToken response = do + case response of + Nothing -> pure $ Left FfiError + Just r -> toResult <$> getErrorFfi r <*> getTokenFfi r + + let free = maybe (pure ()) free_dpop_access_token + + ExceptT $ liftIO $ bracket before free mkAccessToken + where + toCStr :: forall a m. (ToByteString a, MonadIO m) => a -> m CString + toCStr = liftIO . newCString . toStr + where + toStr :: a -> String + toStr = cs . toByteString' + + methodToBS :: StdMethod -> ByteString + methodToBS = \case + GET -> "GET" + POST -> "POST" + HEAD -> "HEAD" + PUT -> "PUT" + DELETE -> "DELETE" + TRACE -> "TRACE" + CONNECT -> "CONNECT" + OPTIONS -> "OPTIONS" + PATCH -> "PATCH" + +toResult :: Maybe Word8 -> Maybe String -> Either DPoPTokenGenerationError ByteString +-- the only valid case is when the error=0 (meaning no error) and the token is not null +toResult (Just 0) (Just token) = Right $ cs token +toResult Nothing (Just token) = Right $ cs token +-- errors +toResult (Just errNo) _ = Left $ fromInt (fromIntegral errNo) + where + fromInt :: Int -> DPoPTokenGenerationError + fromInt i = + if i >= fromEnum @DPoPTokenGenerationError minBound && i <= fromEnum @DPoPTokenGenerationError maxBound + then toEnum (fromIntegral i) + else UnknownError +-- internal errors (unexpected) +toResult Nothing Nothing = Left UnknownError + +newtype Proof = Proof {_unProof :: ByteString} + deriving (Eq, Show) + deriving newtype (ToByteString) + +newtype UserId = UserId {_unUserId :: ByteString} + deriving (Eq, Show) + deriving newtype (ToByteString) + +newtype ClientId = ClientId {_unClientId :: Word16} + deriving (Eq, Show) + deriving newtype (ToByteString) + +newtype Domain = Domain {_unDomain :: ByteString} + deriving (Eq, Show) + deriving newtype (ToByteString) + +newtype Nonce = Nonce {_unNonce :: ByteString} + deriving (Eq, Show) + deriving newtype (ToByteString) + +newtype Uri = Uri {_unUri :: ByteString} + deriving (Eq, Show) + deriving newtype (ToByteString) + +newtype MaxSkewSecs = MaxSkewSecs {_unMaxSkewSecs :: Word16} + deriving (Eq, Show) + deriving newtype (ToByteString) + +newtype ExpiryEpoch = ExpiryEpoch {_unExpiryEpoch :: Word64} + deriving (Eq, Show) + deriving newtype (ToByteString) + +newtype NowEpoch = NowEpoch {_unNowEpoch :: Word64} + deriving (Eq, Show) + deriving newtype (ToByteString) + +newtype PemBundle = PemBundle {_unPemBundle :: ByteString} + deriving (Eq, Show) + deriving newtype (ToByteString) + +data DPoPTokenGenerationError + = NoError + | -- | Unmapped error + UnknownError + | -- | Error at FFI boundary, probably related to raw pointer + FfiError + | -- | We messed up in rusty-jwt-tools + ImplementationError + | -- | DPoP token has an invalid syntax + DpopSyntaxError + | -- | DPoP header "typ" is not "dpop+jwt" + DpopTypError + | -- | DPoP signature algorithm (alg) in JWT header is not a supported algorithm (ES256, ES384, Ed25519) + DpopUnsupportedAlgorithmError + | -- | DPoP signature does not correspond to the public key (jwk) in the JWT header + DpopInvalidSignatureError + | -- | [client_id] does not correspond to the (sub) claim expressed as URI + ClientIdMismatchError + | -- | [backend_nonce] does not correspond to the (nonce) claim in DPoP token (base64url encoded) + BackendNonceMismatchError + | -- | [uri] does not correspond to the (htu) claim in DPoP token + HtuMismatchError + | -- | method does not correspond to the (htm) claim in DPoP token + HtmMismatchError + | -- | (jti) claim is absent in DPoP token + MissingJtiError + | -- | (chal) claim is absent in DPoP token + MissingChallengeError + | -- | (iat) claim is absent in DPoP token + MissingIatError + | -- | (iat) claim in DPoP token is not earlier of now (with [max_skew_secs] leeway) + IatError + | -- | (exp) claim is absent in DPoP token + MissingExpError + | -- | (exp) claim in DPoP token is larger than supplied [max_expiration] + ExpMismatchError + | -- | (exp) claim in DPoP token is sooner than now (with [max_skew_secs] leeway) + ExpError + deriving (Eq, Show, Generic, Bounded, Enum) diff --git a/libs/jwt-tools/test/Spec.hs b/libs/jwt-tools/test/Spec.hs new file mode 100644 index 0000000000..77b702f649 --- /dev/null +++ b/libs/jwt-tools/test/Spec.hs @@ -0,0 +1,95 @@ +-- This file is part of the Wire Server implementation. +-- +-- Copyright (C) 2022 Wire Swiss GmbH +-- +-- 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 . + +import Control.Monad.Trans.Except +import Data.Jwt.Tools +import Data.String.Conversions (cs) +import Imports +import Test.Hspec + +main :: IO () +main = hspec $ do + describe "generateDpopToken FFI" $ do + it "should return a value" $ do + actual <- callFFIWithConstValues + let expected = Right $ cs token + actual `shouldBe` expected + describe "toResult" $ do + it "should convert to correct error" $ do + toResult Nothing (Just token) `shouldBe` Right (cs token) + toResult (Just 1) Nothing `shouldBe` Left UnknownError + toResult (Just 1) (Just token) `shouldBe` Left UnknownError + toResult (Just 2) Nothing `shouldBe` Left FfiError + toResult (Just 2) (Just token) `shouldBe` Left FfiError + toResult (Just 3) Nothing `shouldBe` Left ImplementationError + toResult (Just 3) (Just token) `shouldBe` Left ImplementationError + toResult (Just 4) Nothing `shouldBe` Left DpopSyntaxError + toResult (Just 4) (Just token) `shouldBe` Left DpopSyntaxError + toResult (Just 5) Nothing `shouldBe` Left DpopTypError + toResult (Just 5) (Just token) `shouldBe` Left DpopTypError + toResult (Just 6) Nothing `shouldBe` Left DpopUnsupportedAlgorithmError + toResult (Just 6) (Just token) `shouldBe` Left DpopUnsupportedAlgorithmError + toResult (Just 7) Nothing `shouldBe` Left DpopInvalidSignatureError + toResult (Just 7) (Just token) `shouldBe` Left DpopInvalidSignatureError + toResult (Just 8) Nothing `shouldBe` Left ClientIdMismatchError + toResult (Just 8) (Just token) `shouldBe` Left ClientIdMismatchError + toResult (Just 9) Nothing `shouldBe` Left BackendNonceMismatchError + toResult (Just 9) (Just token) `shouldBe` Left BackendNonceMismatchError + toResult (Just 10) Nothing `shouldBe` Left HtuMismatchError + toResult (Just 10) (Just token) `shouldBe` Left HtuMismatchError + toResult (Just 11) Nothing `shouldBe` Left HtmMismatchError + toResult (Just 11) (Just token) `shouldBe` Left HtmMismatchError + toResult (Just 12) Nothing `shouldBe` Left MissingJtiError + toResult (Just 12) (Just token) `shouldBe` Left MissingJtiError + toResult (Just 13) Nothing `shouldBe` Left MissingChallengeError + toResult (Just 13) (Just token) `shouldBe` Left MissingChallengeError + toResult (Just 14) Nothing `shouldBe` Left MissingIatError + toResult (Just 14) (Just token) `shouldBe` Left MissingIatError + toResult (Just 15) Nothing `shouldBe` Left IatError + toResult (Just 15) (Just token) `shouldBe` Left IatError + toResult (Just 16) Nothing `shouldBe` Left MissingExpError + toResult (Just 16) (Just token) `shouldBe` Left MissingExpError + toResult (Just 17) Nothing `shouldBe` Left ExpMismatchError + toResult (Just 17) (Just token) `shouldBe` Left ExpMismatchError + toResult (Just 18) Nothing `shouldBe` Left ExpError + toResult (Just 18) (Just token) `shouldBe` Left ExpError + toResult Nothing Nothing `shouldBe` Left UnknownError + +token :: String +token = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" + +callFFIWithConstValues :: IO (Either DPoPTokenGenerationError ByteString) +callFFIWithConstValues = do + let proof = Proof "xxxx.yyyy.zzzz" + let uid = UserId "8a6e8a6e-8a6e-8a6e-8a6e-8a6e8a6e8a6e" + let cid = ClientId 8899 + let domain = Domain "example.com" + let nonce = Nonce "123" + let uri = Uri "/foo" + let method = POST + let maxSkewSecs = MaxSkewSecs 1 + let now = NowEpoch 5435234232 + let expires = ExpiryEpoch $ 5435234232 + 360 + let pem = + PemBundle $ + "-----BEGIN PRIVATE KEY-----\n\ + \MC4CAQAwBQYDK2VwBCIEIFANnxZLNE4p+GDzWzR3wm/v8x/0bxZYkCyke1aTRucX\n\ + \-----END PRIVATE KEY-----\n\ + \-----BEGIN PUBLIC KEY-----\n\ + \MCowBQYDK2VwAyEACPvhIdimF20tOPjbb+fXJrwS2RKDp7686T90AZ0+Th8=\n\ + \-----END PUBLIC KEY-----\n" + runExceptT $ generateDpopToken proof uid cid domain nonce uri method maxSkewSecs expires now pem diff --git a/libs/polysemy-wire-zoo/src/Wire/Sem/FromUTC.hs b/libs/polysemy-wire-zoo/src/Wire/Sem/FromUTC.hs index afea1fcf79..3f339fd581 100644 --- a/libs/polysemy-wire-zoo/src/Wire/Sem/FromUTC.hs +++ b/libs/polysemy-wire-zoo/src/Wire/Sem/FromUTC.hs @@ -19,8 +19,10 @@ module Wire.Sem.FromUTC where import Data.Time (UTCTime) +import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) import Imports import qualified SAML2.WebSSO.Types as SAML +import Wire.API.MLS.Epoch (Epoch (..)) -- | The class is helpful in interpreters for the 'Now' effect. It makes it -- possible to use the interpreters for any time type so long as it implements @@ -35,3 +37,7 @@ instance FromUTC UTCTime where -- An orphan instance instance FromUTC SAML.Time where fromUTCTime = SAML.Time + +-- An orphan instance +instance FromUTC Epoch where + fromUTCTime = Epoch . floor . utcTimeToPOSIXSeconds diff --git a/libs/types-common/src/Data/Nonce.hs b/libs/types-common/src/Data/Nonce.hs index 26e4073a5c..c627000e6a 100644 --- a/libs/types-common/src/Data/Nonce.hs +++ b/libs/types-common/src/Data/Nonce.hs @@ -45,7 +45,14 @@ import Test.QuickCheck.Instances.UUID () newtype Nonce = Nonce {unNonce :: UUID} deriving (Eq, Show) - deriving newtype (A.FromJSON, A.ToJSON, S.ToSchema, Arbitrary) + deriving newtype (Arbitrary) + deriving (A.FromJSON, A.ToJSON, S.ToSchema) via (Schema Nonce) + +instance ToSchema Nonce where + schema = (cs . toByteString') .= parsedText "Nonce" p + where + p :: Text -> Either String Nonce + p = maybe (Left "Invalid Nonce") Right . fromByteString' . cs instance ToByteString Nonce where builder = builder . Base64.encode . toStrict . UUID.toByteString . unNonce diff --git a/libs/types-common/src/Data/PEMKeys.hs b/libs/types-common/src/Data/PEMKeys.hs new file mode 100644 index 0000000000..9b69c02363 --- /dev/null +++ b/libs/types-common/src/Data/PEMKeys.hs @@ -0,0 +1,31 @@ +-- This file is part of the Wire Server implementation. +-- +-- Copyright (C) 2022 Wire Swiss GmbH +-- +-- 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 . + +module Data.PEMKeys where + +import Data.ByteString.Conversion +import Data.PEM +import Imports + +newtype PEMKeys = PEMKeys {unPEMKeys :: [PEM]} + deriving (Eq, Show) + +instance ToByteString PEMKeys where + builder (PEMKeys pems) = builder . mconcat $ map pemWriteBS pems + +instance FromByteString PEMKeys where + parser = parser >>= either fail (pure . PEMKeys) . pemParseBS diff --git a/libs/types-common/test/Main.hs b/libs/types-common/test/Main.hs index 061294564b..dd79477b0b 100644 --- a/libs/types-common/test/Main.hs +++ b/libs/types-common/test/Main.hs @@ -21,6 +21,7 @@ module Main where import Imports +import qualified Test.Data.PEMKeys as PEMKeys import qualified Test.Domain as Domain import qualified Test.Handle as Handle import qualified Test.Properties as Properties @@ -37,5 +38,6 @@ main = SizedHashMap.tests, Domain.tests, Handle.tests, - Qualified.tests + Qualified.tests, + PEMKeys.tests ] diff --git a/libs/types-common/test/Test/Data/PEMKeys.hs b/libs/types-common/test/Test/Data/PEMKeys.hs new file mode 100644 index 0000000000..e4f406630b --- /dev/null +++ b/libs/types-common/test/Test/Data/PEMKeys.hs @@ -0,0 +1,45 @@ +-- This file is part of the Wire Server implementation. +-- +-- Copyright (C) 2022 Wire Swiss GmbH +-- +-- 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 . + +module Test.Data.PEMKeys + ( tests, + ) +where + +import Data.ByteString.Conversion +import Data.PEMKeys +import Data.String.Conversions (cs) +import Imports +import Test.Tasty +import Test.Tasty.HUnit + +tests :: TestTree +tests = + testGroup + "PEMKeys" + [ testCase "ByteString conversion" $ do + Just (cs pem) @=? (toByteString <$> fromByteString @PEMKeys pem) + ] + where + pem :: ByteString + pem = + "-----BEGIN PRIVATE KEY-----\n\ + \MC4CAQAwBQYDK2VwBCIEIFANnxZLNE4p+GDzWzR3wm/v8x/0bxZYkCyke1aTRucX\n\ + \-----END PRIVATE KEY-----\n\ + \-----BEGIN PUBLIC KEY-----\n\ + \MCowBQYDK2VwAyEACPvhIdimF20tOPjbb+fXJrwS2RKDp7686T90AZ0+Th8=\n\ + \-----END PUBLIC KEY-----\n" diff --git a/libs/types-common/test/Test/Properties.hs b/libs/types-common/test/Test/Properties.hs index 31a3eef1e5..1340a367c1 100644 --- a/libs/types-common/test/Test/Properties.hs +++ b/libs/types-common/test/Test/Properties.hs @@ -214,7 +214,8 @@ tests = testGroup "Nonce" [ testProperty "decode . encode = id" $ - \(x :: Nonce) -> bsRoundtrip x + \(x :: Nonce) -> bsRoundtrip x, + jsonRoundtrip @Nonce ] ] diff --git a/libs/types-common/types-common.cabal b/libs/types-common/types-common.cabal index 9be5949ebc..96fb5b5526 100644 --- a/libs/types-common/types-common.cabal +++ b/libs/types-common/types-common.cabal @@ -24,6 +24,7 @@ library Data.List1 Data.Misc Data.Nonce + Data.PEMKeys Data.Qualified Data.Range Data.RetryAfter @@ -113,6 +114,7 @@ library , lens-datetime >=0.3 , mime >=0.4.0.2 , optparse-applicative >=0.10 + , pem , protobuf >=0.2 , QuickCheck >=2.9 , quickcheck-instances >=0.3.16 @@ -147,6 +149,7 @@ test-suite tests main-is: Main.hs other-modules: Paths_types_common + Test.Data.PEMKeys Test.Domain Test.Handle Test.Properties diff --git a/libs/wai-utilities/src/Network/Wai/Utilities.hs b/libs/wai-utilities/src/Network/Wai/Utilities.hs index ebc1833751..2047652fb5 100644 --- a/libs/wai-utilities/src/Network/Wai/Utilities.hs +++ b/libs/wai-utilities/src/Network/Wai/Utilities.hs @@ -19,9 +19,11 @@ module Network.Wai.Utilities ( module Network.Wai.Utilities.Error, module Network.Wai.Utilities.Request, module Network.Wai.Utilities.Response, + module Network.Wai.Utilities.Headers, ) where import Network.Wai.Utilities.Error +import Network.Wai.Utilities.Headers import Network.Wai.Utilities.Request import Network.Wai.Utilities.Response diff --git a/libs/wai-utilities/src/Network/Wai/Utilities/Headers.hs b/libs/wai-utilities/src/Network/Wai/Utilities/Headers.hs new file mode 100644 index 0000000000..9b111acb80 --- /dev/null +++ b/libs/wai-utilities/src/Network/Wai/Utilities/Headers.hs @@ -0,0 +1,47 @@ +-- This file is part of the Wire Server implementation. +-- +-- Copyright (C) 2022 Wire Swiss GmbH +-- +-- 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 . + +module Network.Wai.Utilities.Headers where + +import Data.ByteString.Conversion (FromByteString (..), ToByteString (..), fromByteString', toByteString') +import Data.String.Conversions (cs) +import Data.Swagger.ParamSchema (ToParamSchema (..)) +import Data.Text as T +import Imports +import Servant (FromHttpApiData (..), Proxy (Proxy), ToHttpApiData (..)) + +data CacheControl = NoStore + deriving (Eq, Show, Generic) + +instance ToByteString CacheControl where + builder NoStore = "no-store" + +instance FromByteString CacheControl where + parser = do + t :: Text <- parser + case t & T.toLower of + "no-store" -> pure NoStore + _ -> fail $ "Invalid CacheControl type: " ++ show t + +instance ToHttpApiData CacheControl where + toQueryParam = cs . toByteString' + +instance FromHttpApiData CacheControl where + parseQueryParam = maybe (Left "Invalid CacheControl") Right . fromByteString' . cs + +instance ToParamSchema CacheControl where + toParamSchema _ = toParamSchema (Proxy @Text) diff --git a/libs/wai-utilities/wai-utilities.cabal b/libs/wai-utilities/wai-utilities.cabal index 3ddf227528..af8f7d5645 100644 --- a/libs/wai-utilities/wai-utilities.cabal +++ b/libs/wai-utilities/wai-utilities.cabal @@ -15,6 +15,7 @@ library exposed-modules: Network.Wai.Utilities Network.Wai.Utilities.Error + Network.Wai.Utilities.Headers Network.Wai.Utilities.MockServer Network.Wai.Utilities.Request Network.Wai.Utilities.Response @@ -83,9 +84,11 @@ library , metrics-wai >=0.5.7 , pipes >=4.1 , prometheus-client + , servant-server , streaming-commons >=0.1 , string-conversions - , swagger >=0.1 + , swagger + , swagger2 , text >=0.11 , tinylog >=0.8 , types-common >=0.12 diff --git a/libs/wire-api/src/Wire/API/Asset.hs b/libs/wire-api/src/Wire/API/Asset.hs index 04f157ae7b..2020b1d557 100644 --- a/libs/wire-api/src/Wire/API/Asset.hs +++ b/libs/wire-api/src/Wire/API/Asset.hs @@ -396,10 +396,6 @@ instance S.ToParamSchema (AssetLocation r) where & S.type_ ?~ S.SwaggerString & S.format ?~ "url" -instance AsHeaders '[AssetLocation r] Asset (Asset, AssetLocation r) where - toHeaders (asset, loc) = (I loc :* Nil, asset) - fromHeaders (I loc :* Nil, asset) = (asset, loc) - -- | An asset as returned by the download API: if the asset is local, only a -- URL is returned, and if it is remote the content of the asset is streamed. data LocalOrRemoteAsset diff --git a/libs/wire-api/src/Wire/API/MLS/Epoch.hs b/libs/wire-api/src/Wire/API/MLS/Epoch.hs index c5fae61fa9..fb24771253 100644 --- a/libs/wire-api/src/Wire/API/MLS/Epoch.hs +++ b/libs/wire-api/src/Wire/API/MLS/Epoch.hs @@ -34,3 +34,6 @@ instance ParseMLS Epoch where instance SerialiseMLS Epoch where serialiseMLS (Epoch n) = put n + +addToEpoch :: Integral a => a -> Epoch -> Epoch +addToEpoch n (Epoch e) = Epoch (e + fromIntegral n) diff --git a/libs/wire-api/src/Wire/API/Routes/MultiVerb.hs b/libs/wire-api/src/Wire/API/Routes/MultiVerb.hs index 4802bcf5d1..4893b29ab3 100644 --- a/libs/wire-api/src/Wire/API/Routes/MultiVerb.hs +++ b/libs/wire-api/src/Wire/API/Routes/MultiVerb.hs @@ -305,6 +305,11 @@ instance AsHeaders '[a] () a where toHeaders a = (I a :* Nil, ()) fromHeaders = unI . hd . fst +-- single-header non-empty response, return value is a tuple of the response and the header +instance AsHeaders '[h] a (a, h) where + toHeaders (t, cc) = (I cc :* Nil, t) + fromHeaders (I cc :* Nil, t) = (t, cc) + data DescHeader (name :: Symbol) (desc :: Symbol) (a :: *) class ServantHeaders hs xs | hs -> xs where @@ -858,3 +863,7 @@ instance instance RoutesToPaths (MultiVerb method cs as r) where getRoutes = [] + +instance HasLink (MultiVerb method cs as r) where + type MkLink (MultiVerb method cs as r) a = a + toLink toA _ = toA diff --git a/libs/wire-api/src/Wire/API/Routes/Named.hs b/libs/wire-api/src/Wire/API/Routes/Named.hs index d385eeb3a7..df29b1a53b 100644 --- a/libs/wire-api/src/Wire/API/Routes/Named.hs +++ b/libs/wire-api/src/Wire/API/Routes/Named.hs @@ -39,6 +39,10 @@ instance HasServer api ctx => HasServer (Named name api) ctx where hoistServerWithContext _ ctx f = fmap (hoistServerWithContext (Proxy @api) ctx f) +instance HasLink endpoint => HasLink (Named name endpoint) where + type MkLink (Named name endpoint) a = MkLink endpoint a + toLink toA _ = toLink toA (Proxy @endpoint) + instance RoutesToPaths api => RoutesToPaths (Named name api) where getRoutes = getRoutes @api diff --git a/libs/wire-api/src/Wire/API/Routes/Public.hs b/libs/wire-api/src/Wire/API/Routes/Public.hs index 0fe291c1f2..fd3d774825 100644 --- a/libs/wire-api/src/Wire/API/Routes/Public.hs +++ b/libs/wire-api/src/Wire/API/Routes/Public.hs @@ -185,6 +185,10 @@ instance HasSwagger api => HasSwagger (ZAuthServant 'ZAuthUser _opts :> api) whe instance HasSwagger api => HasSwagger (ZAuthServant 'ZLocalAuthUser opts :> api) where toSwagger _ = toSwagger (Proxy @(ZAuthServant 'ZAuthUser opts :> api)) +instance HasLink endpoint => HasLink (ZAuthServant usr opts :> endpoint) where + type MkLink (ZAuthServant _ _ :> endpoint) a = MkLink endpoint a + toLink toA _ = toLink toA (Proxy @endpoint) + instance {-# OVERLAPPABLE #-} HasSwagger api => diff --git a/libs/wire-api/src/Wire/API/Routes/Public/Brig.hs b/libs/wire-api/src/Wire/API/Routes/Public/Brig.hs index e75deb517a..9fa9ad01c4 100644 --- a/libs/wire-api/src/Wire/API/Routes/Public/Brig.hs +++ b/libs/wire-api/src/Wire/API/Routes/Public/Brig.hs @@ -36,6 +36,7 @@ import Data.Swagger hiding (Contact, Header, Schema, ToSchema) import qualified Data.Swagger as S import qualified Generics.SOP as GSOP import Imports hiding (head) +import Network.Wai.Utilities import Servant (JSON) import Servant hiding (Handler, JSON, addHeader, respond) import Servant.Swagger (HasSwagger (toSwagger)) @@ -56,6 +57,7 @@ import Wire.API.Routes.Version import Wire.API.User hiding (NoIdentity) import Wire.API.User.Activation import Wire.API.User.Client +import Wire.API.User.Client.DPoPAccessToken import Wire.API.User.Client.Prekey import Wire.API.User.Handle import Wire.API.User.Password (CompletePasswordReset, NewPasswordReset, PasswordReset, PasswordResetKey) @@ -689,17 +691,40 @@ type UserClientAPI = :> "prekeys" :> Get '[JSON] [PrekeyId] ) - :<|> NonceAPI - -type NonceAPI = - -- be aware that the order matters, if get was first, then head requests would be routed to the get handler - NewNonce "head-nonce" 'HEAD 200 + -- be aware that the order of the head-nonce and get-nonce matters, if get was first, then head requests would be routed to the get handler + :<|> NewNonce "head-nonce" 'HEAD 200 :<|> NewNonce "get-nonce" 'GET 204 + :<|> CreateAccessToken + +type CreateAccessToken = + Named + "create-access-token" + ( Summary "Create a JWT DPoP access token" + :> Description + ( "[implementation stub, not supported yet!] \ + \Create an JWT DPoP access token for the client CSR, given a JWT DPoP proof, specified in the `DPoP` header. \ + \The access token will be returned as JWT DPoP token in the `DPoP` header." + ) + :> ZUser + :> "clients" + :> CaptureClientId "cid" + :> "access-token" + :> Header' '[Required, Strict] "DPoP" Proof + :> MultiVerb1 + 'POST + '[JSON] + ( WithHeaders + '[Header "Cache-Control" CacheControl] + (DPoPAccessTokenResponse, CacheControl) + (Respond 200 "Access token created" DPoPAccessTokenResponse) + ) + ) type NewNonce name method statusCode = Named name - ( Summary "Get a new nonce for a client CSR, specified in the response header `Replay-Nonce` as a uuidv4 in base64url encoding" + ( Summary "Get a new nonce for a client CSR" + :> Description "Get a new nonce for a client CSR, specified in the response header `Replay-Nonce` as a uuidv4 in base64url encoding." :> ZUser :> "clients" :> CaptureClientId "client" @@ -707,16 +732,20 @@ type NewNonce name method statusCode = :> MultiVerb1 method '[JSON] - (WithHeaders '[Header "Replay-Nonce" NonceHeader, Header "Cache-Control" Text] Nonce (RespondEmpty statusCode "No Content")) + ( WithHeaders + '[Header "Replay-Nonce" NonceHeader, Header "Cache-Control" CacheControl] + (Nonce, CacheControl) + (RespondEmpty statusCode "No Content") + ) ) newtype NonceHeader = NonceHeader Nonce deriving (Eq, Show) deriving newtype (FromByteString, ToByteString, ToParamSchema, ToHttpApiData, FromHttpApiData) -instance AsHeaders '[NonceHeader, Text] () Nonce where - fromHeaders (I (NonceHeader nonce) :* (_ :* Nil), _) = nonce - toHeaders nonce = (I (NonceHeader nonce) :* (I "no-store" :* Nil), ()) +instance AsHeaders '[NonceHeader, CacheControl] () (Nonce, CacheControl) where + fromHeaders (I (NonceHeader n) :* (I cc :* Nil), ()) = (n, cc) + toHeaders (n, cc) = (I (NonceHeader n) :* (I cc :* Nil), ()) type ClientAPI = Named diff --git a/libs/wire-api/src/Wire/API/User/Client/DPoPAccessToken.hs b/libs/wire-api/src/Wire/API/User/Client/DPoPAccessToken.hs new file mode 100644 index 0000000000..5701f0d36e --- /dev/null +++ b/libs/wire-api/src/Wire/API/User/Client/DPoPAccessToken.hs @@ -0,0 +1,90 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE GeneralizedNewtypeDeriving #-} + +-- This file is part of the Wire Server implementation. +-- +-- Copyright (C) 2022 Wire Swiss GmbH +-- +-- 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 . + +module Wire.API.User.Client.DPoPAccessToken where + +import Data.Aeson (FromJSON, ToJSON) +import Data.ByteString.Conversion (FromByteString (..), ToByteString (..), fromByteString', toByteString') +import Data.Json.Util (base64Schema) +import Data.SOP +import Data.Schema +import Data.String.Conversions (cs) +import qualified Data.Swagger as S +import Data.Swagger.ParamSchema (ToParamSchema (..)) +import Data.Text as T +import Imports +import Servant (FromHttpApiData (..), ToHttpApiData (..)) + +newtype Proof = Proof {unProof :: ByteString} + deriving (Eq, Show, Generic) + deriving newtype (FromByteString, ToByteString) + +instance ToHttpApiData Proof where + toQueryParam = cs . toByteString' + +instance FromHttpApiData Proof where + parseQueryParam = maybe (Left "Invalid Proof") Right . fromByteString' . cs + +instance ToParamSchema Proof where + toParamSchema _ = toParamSchema (Proxy @Text) + +newtype DPoPAccessToken = DPoPAccessToken {unDPoPAccessToken :: ByteString} + deriving (Eq, Show, Generic) + deriving newtype (FromByteString, ToByteString) + deriving (FromJSON, ToJSON, S.ToSchema) via (Schema DPoPAccessToken) + +instance ToSchema DPoPAccessToken where + schema = named "DPoPAccessToken" $ unDPoPAccessToken .= fmap DPoPAccessToken base64Schema + +instance ToParamSchema DPoPAccessToken where + toParamSchema _ = toParamSchema (Proxy @Text) + +instance ToHttpApiData DPoPAccessToken where + toQueryParam = cs . toByteString' + +instance FromHttpApiData DPoPAccessToken where + parseQueryParam = maybe (Left "Invalid DPoPAccessToken") Right . fromByteString' . cs + +data AccessTokenType = DPoP + deriving (Eq, Show, Generic) + deriving (FromJSON, ToJSON, S.ToSchema) via (Schema AccessTokenType) + +instance ToSchema AccessTokenType where + schema = + enum @Text "AccessTokenType" $ + mconcat + [ element "DPoP" DPoP + ] + +data DPoPAccessTokenResponse = DPoPAccessTokenResponse + { datrToken :: DPoPAccessToken, + datrType :: AccessTokenType, + datrExpiresIn :: Word64 + } + deriving (Eq, Show, Generic) + deriving (FromJSON, ToJSON, S.ToSchema) via (Schema DPoPAccessTokenResponse) + +instance ToSchema DPoPAccessTokenResponse where + schema = + object "DPoPAccessTokenResponse" $ + DPoPAccessTokenResponse + <$> datrToken .= field "token" schema + <*> datrType .= field "type" schema + <*> datrExpiresIn .= field "expires_in" schema diff --git a/libs/wire-api/wire-api.cabal b/libs/wire-api/wire-api.cabal index ac49c0a5a4..26d7c0f2ac 100644 --- a/libs/wire-api/wire-api.cabal +++ b/libs/wire-api/wire-api.cabal @@ -112,6 +112,7 @@ library Wire.API.User.Auth Wire.API.User.Auth2 Wire.API.User.Client + Wire.API.User.Client.DPoPAccessToken Wire.API.User.Client.Prekey Wire.API.User.Handle Wire.API.User.Identity diff --git a/nix/default.nix b/nix/default.nix index 8ad4517f70..6c078290f6 100644 --- a/nix/default.nix +++ b/nix/default.nix @@ -11,6 +11,7 @@ let }; c-lib-out-deps = [ + pkgs.rusty_jwt_tools pkgs.cryptobox pkgs.icu.out pkgs.libsodium.out @@ -39,6 +40,7 @@ let pkgs.haskell.compiler.ghc8107 pkgs.protobuf + pkgs.rusty_jwt_tools pkgs.cryptobox pkgs.icu.dev pkgs.libsodium.dev diff --git a/nix/overlay.nix b/nix/overlay.nix index 5c559dd32c..c213b266d1 100644 --- a/nix/overlay.nix +++ b/nix/overlay.nix @@ -54,6 +54,7 @@ self: super: { cryptobox = self.callPackage ./pkgs/cryptobox { }; zauth = self.callPackage ./pkgs/zauth { }; mls_test_cli = self.callPackage ./pkgs/mls_test_cli { }; + rusty_jwt_tools = self.callPackage ./pkgs/rusty_jwt_tools { }; nginxModules = super.nginxModules // { zauth = { diff --git a/nix/pkgs/rusty_jwt_tools/add-Cargo.lock.patch b/nix/pkgs/rusty_jwt_tools/add-Cargo.lock.patch new file mode 100644 index 0000000000..5ac52f2aaf --- /dev/null +++ b/nix/pkgs/rusty_jwt_tools/add-Cargo.lock.patch @@ -0,0 +1,1311 @@ +From 7d2af044a0a8d003936b5013defff915c4ca52dc Mon Sep 17 00:00:00 2001 +From: Leif Battermann +Date: Tue, 13 Sep 2022 12:08:40 +0200 +Subject: [PATCH] cargo lock + +--- + .gitignore | 1 - + Cargo.lock | 1279 ++++++++++++++++++++++++++++++++++++++++++++++++++++ + 2 files changed, 1279 insertions(+), 1 deletion(-) + create mode 100644 Cargo.lock + +diff --git a/.gitignore b/.gitignore +index a178556..68bc967 100644 +--- a/.gitignore ++++ b/.gitignore +@@ -1,7 +1,6 @@ + # Rust + /target + /debug +-/Cargo.lock + + # Idea + .idea +diff --git a/Cargo.lock b/Cargo.lock +new file mode 100644 +index 0000000..3f52488 +--- /dev/null ++++ b/Cargo.lock +@@ -0,0 +1,1279 @@ ++# This file is automatically @generated by Cargo. ++# It is not intended for manual editing. ++version = 3 ++ ++[[package]] ++name = "anyhow" ++version = "1.0.64" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "b9a8f622bcf6ff3df478e9deba3e03e4e04b300f8e6a139e192c05fa3490afc7" ++ ++[[package]] ++name = "autocfg" ++version = "1.1.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" ++ ++[[package]] ++name = "base16ct" ++version = "0.1.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce" ++ ++[[package]] ++name = "base64" ++version = "0.13.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" ++ ++[[package]] ++name = "base64ct" ++version = "1.5.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "ea2b2456fd614d856680dcd9fcc660a51a820fa09daef2e49772b56a193c8474" ++ ++[[package]] ++name = "binstring" ++version = "0.1.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "7e0d60973d9320722cb1206f412740e162a33b8547ea8d6be75d7cff237c7a85" ++ ++[[package]] ++name = "bitflags" ++version = "1.3.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" ++ ++[[package]] ++name = "block-buffer" ++version = "0.10.3" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e" ++dependencies = [ ++ "generic-array", ++] ++ ++[[package]] ++name = "bumpalo" ++version = "3.11.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "c1ad822118d20d2c234f427000d5acc36eabe1e29a348c89b63dd60b13f28e5d" ++ ++[[package]] ++name = "byteorder" ++version = "1.4.3" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" ++ ++[[package]] ++name = "cfg-if" ++version = "1.0.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" ++ ++[[package]] ++name = "coarsetime" ++version = "0.1.22" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "454038500439e141804c655b4cd1bc6a70bcb95cd2bc9463af5661b6956f0e46" ++dependencies = [ ++ "libc", ++ "once_cell", ++ "wasi", ++ "wasm-bindgen", ++] ++ ++[[package]] ++name = "console_error_panic_hook" ++version = "0.1.7" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" ++dependencies = [ ++ "cfg-if", ++ "wasm-bindgen", ++] ++ ++[[package]] ++name = "const-oid" ++version = "0.7.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3" ++ ++[[package]] ++name = "const-oid" ++version = "0.9.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "722e23542a15cea1f65d4a1419c4cfd7a26706c70871a13a04238ca3f40f1661" ++ ++[[package]] ++name = "cpufeatures" ++version = "0.2.5" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320" ++dependencies = [ ++ "libc", ++] ++ ++[[package]] ++name = "crypto-bigint" ++version = "0.3.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "03c6a1d5fa1de37e071642dfa44ec552ca5b299adb128fab16138e24b548fd21" ++dependencies = [ ++ "generic-array", ++ "subtle", ++] ++ ++[[package]] ++name = "crypto-bigint" ++version = "0.4.8" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "9f2b443d17d49dad5ef0ede301c3179cc923b8822f3393b4d2c28c269dd4a122" ++dependencies = [ ++ "generic-array", ++ "rand_core", ++ "subtle", ++ "zeroize", ++] ++ ++[[package]] ++name = "crypto-common" ++version = "0.1.6" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" ++dependencies = [ ++ "generic-array", ++ "typenum", ++] ++ ++[[package]] ++name = "ct-codecs" ++version = "1.1.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "f3b7eb4404b8195a9abb6356f4ac07d8ba267045c8d6d220ac4dc992e6cc75df" ++ ++[[package]] ++name = "der" ++version = "0.5.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "6919815d73839e7ad218de758883aae3a257ba6759ce7a9992501efbb53d705c" ++dependencies = [ ++ "const-oid 0.7.1", ++ "crypto-bigint 0.3.2", ++ "pem-rfc7468 0.3.1", ++] ++ ++[[package]] ++name = "der" ++version = "0.6.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "13dd2ae565c0a381dde7fade45fce95984c568bdcb4700a4fdbe3175e0380b2f" ++dependencies = [ ++ "const-oid 0.9.0", ++ "pem-rfc7468 0.6.0", ++ "zeroize", ++] ++ ++[[package]] ++name = "digest" ++version = "0.10.3" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506" ++dependencies = [ ++ "block-buffer", ++ "crypto-common", ++ "subtle", ++] ++ ++[[package]] ++name = "ecdsa" ++version = "0.14.5" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "1826508d57f3140a2e8e3c307b19915a266c92a1b8c2f6bb54e29e5d72a394ae" ++dependencies = [ ++ "der 0.6.0", ++ "elliptic-curve", ++ "rfc6979", ++ "signature", ++] ++ ++[[package]] ++name = "ed25519-compact" ++version = "1.0.11" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "24e1f30f0312ac83726c1197abeacd91c9557f8a623e904a009ae6bc529ae8d8" ++dependencies = [ ++ "ct-codecs", ++ "getrandom", ++] ++ ++[[package]] ++name = "elliptic-curve" ++version = "0.12.3" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "e7bb888ab5300a19b8e5bceef25ac745ad065f3c9f7efc6de1b91958110891d3" ++dependencies = [ ++ "base16ct", ++ "base64ct", ++ "crypto-bigint 0.4.8", ++ "der 0.6.0", ++ "digest", ++ "ff", ++ "generic-array", ++ "group", ++ "hkdf", ++ "pem-rfc7468 0.6.0", ++ "pkcs8 0.9.0", ++ "rand_core", ++ "sec1", ++ "serde_json", ++ "serdect", ++ "subtle", ++ "zeroize", ++] ++ ++[[package]] ++name = "ff" ++version = "0.12.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "df689201f395c6b90dfe87127685f8dbfc083a5e779e613575d8bd7314300c3e" ++dependencies = [ ++ "rand_core", ++ "subtle", ++] ++ ++[[package]] ++name = "fluvio-wasm-timer" ++version = "0.2.5" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "b768c170dc045fa587a8f948c91f9bcfb87f774930477c6215addf54317f137f" ++dependencies = [ ++ "futures", ++ "js-sys", ++ "parking_lot", ++ "pin-utils", ++ "wasm-bindgen", ++ "wasm-bindgen-futures", ++ "web-sys", ++] ++ ++[[package]] ++name = "form_urlencoded" ++version = "1.1.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8" ++dependencies = [ ++ "percent-encoding", ++] ++ ++[[package]] ++name = "futures" ++version = "0.3.24" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "7f21eda599937fba36daeb58a22e8f5cee2d14c4a17b5b7739c7c8e5e3b8230c" ++dependencies = [ ++ "futures-channel", ++ "futures-core", ++ "futures-executor", ++ "futures-io", ++ "futures-sink", ++ "futures-task", ++ "futures-util", ++] ++ ++[[package]] ++name = "futures-channel" ++version = "0.3.24" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "30bdd20c28fadd505d0fd6712cdfcb0d4b5648baf45faef7f852afb2399bb050" ++dependencies = [ ++ "futures-core", ++ "futures-sink", ++] ++ ++[[package]] ++name = "futures-core" ++version = "0.3.24" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "4e5aa3de05362c3fb88de6531e6296e85cde7739cccad4b9dfeeb7f6ebce56bf" ++ ++[[package]] ++name = "futures-executor" ++version = "0.3.24" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "9ff63c23854bee61b6e9cd331d523909f238fc7636290b96826e9cfa5faa00ab" ++dependencies = [ ++ "futures-core", ++ "futures-task", ++ "futures-util", ++] ++ ++[[package]] ++name = "futures-io" ++version = "0.3.24" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "bbf4d2a7a308fd4578637c0b17c7e1c7ba127b8f6ba00b29f717e9655d85eb68" ++ ++[[package]] ++name = "futures-macro" ++version = "0.3.24" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "42cd15d1c7456c04dbdf7e88bcd69760d74f3a798d6444e16974b505b0e62f17" ++dependencies = [ ++ "proc-macro2", ++ "quote", ++ "syn", ++] ++ ++[[package]] ++name = "futures-sink" ++version = "0.3.24" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "21b20ba5a92e727ba30e72834706623d94ac93a725410b6a6b6fbc1b07f7ba56" ++ ++[[package]] ++name = "futures-task" ++version = "0.3.24" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "a6508c467c73851293f390476d4491cf4d227dbabcd4170f3bb6044959b294f1" ++ ++[[package]] ++name = "futures-timer" ++version = "3.0.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c" ++ ++[[package]] ++name = "futures-util" ++version = "0.3.24" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "44fb6cb1be61cc1d2e43b262516aafcf63b241cffdb1d3fa115f91d9c7b09c90" ++dependencies = [ ++ "futures-channel", ++ "futures-core", ++ "futures-io", ++ "futures-macro", ++ "futures-sink", ++ "futures-task", ++ "memchr", ++ "pin-project-lite", ++ "pin-utils", ++ "slab", ++] ++ ++[[package]] ++name = "generic-array" ++version = "0.14.6" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9" ++dependencies = [ ++ "typenum", ++ "version_check", ++] ++ ++[[package]] ++name = "getrandom" ++version = "0.2.7" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6" ++dependencies = [ ++ "cfg-if", ++ "js-sys", ++ "libc", ++ "wasi", ++ "wasm-bindgen", ++] ++ ++[[package]] ++name = "group" ++version = "0.12.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "7391856def869c1c81063a03457c676fbcd419709c3dfb33d8d319de484b154d" ++dependencies = [ ++ "ff", ++ "rand_core", ++ "subtle", ++] ++ ++[[package]] ++name = "hkdf" ++version = "0.12.3" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "791a029f6b9fc27657f6f188ec6e5e43f6911f6f878e0dc5501396e09809d437" ++dependencies = [ ++ "hmac", ++] ++ ++[[package]] ++name = "hmac" ++version = "0.12.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" ++dependencies = [ ++ "digest", ++] ++ ++[[package]] ++name = "hmac-sha1-compact" ++version = "1.1.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "d103cfecf6edf3f7d1dc7c5ab64e99488c0f8d11786e43b40873e66e8489d014" ++ ++[[package]] ++name = "hmac-sha256" ++version = "1.1.4" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "fd29dbba58ee5314f3ec570066d78a3f4772bf45b322efcf2ce2a43af69a4d85" ++dependencies = [ ++ "digest", ++] ++ ++[[package]] ++name = "hmac-sha512" ++version = "1.1.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "a928b002dff1780b7fa21056991d395770ab9359154b8c1724c4d0511dad0a65" ++dependencies = [ ++ "digest", ++] ++ ++[[package]] ++name = "idna" ++version = "0.3.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6" ++dependencies = [ ++ "unicode-bidi", ++ "unicode-normalization", ++] ++ ++[[package]] ++name = "instant" ++version = "0.1.12" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" ++dependencies = [ ++ "cfg-if", ++ "js-sys", ++ "wasm-bindgen", ++ "web-sys", ++] ++ ++[[package]] ++name = "itoa" ++version = "1.0.3" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "6c8af84674fe1f223a982c933a0ee1086ac4d4052aa0fb8060c12c6ad838e754" ++ ++[[package]] ++name = "js-sys" ++version = "0.3.59" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "258451ab10b34f8af53416d1fdab72c22e805f0c92a1136d59470ec0b11138b2" ++dependencies = [ ++ "wasm-bindgen", ++] ++ ++[[package]] ++name = "jwt-simple" ++version = "0.10.0" ++source = "git+https://github.com/beltram/rust-jwt-simple?branch=master#e05b2875285a79ee8e06639d21fde827466ec2cb" ++dependencies = [ ++ "anyhow", ++ "binstring", ++ "coarsetime", ++ "ct-codecs", ++ "ed25519-compact", ++ "hmac-sha1-compact", ++ "hmac-sha256", ++ "hmac-sha512", ++ "k256", ++ "p256", ++ "p384", ++ "rand", ++ "rsa", ++ "serde", ++ "serde_json", ++ "spki 0.5.4", ++ "thiserror", ++ "zeroize", ++] ++ ++[[package]] ++name = "k256" ++version = "0.11.4" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "6db2573d3fd3e4cc741affc9b5ce1a8ce36cf29f09f80f36da4309d0ae6d7854" ++dependencies = [ ++ "cfg-if", ++ "ecdsa", ++ "elliptic-curve", ++ "sha2", ++] ++ ++[[package]] ++name = "lazy_static" ++version = "1.4.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" ++dependencies = [ ++ "spin", ++] ++ ++[[package]] ++name = "libc" ++version = "0.2.132" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "8371e4e5341c3a96db127eb2465ac681ced4c433e01dd0e938adbef26ba93ba5" ++ ++[[package]] ++name = "libm" ++version = "0.2.5" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "292a948cd991e376cf75541fe5b97a1081d713c618b4f1b9500f8844e49eb565" ++ ++[[package]] ++name = "lock_api" ++version = "0.4.8" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "9f80bf5aacaf25cbfc8210d1cfb718f2bf3b11c4c54e5afe36c236853a8ec390" ++dependencies = [ ++ "autocfg", ++ "scopeguard", ++] ++ ++[[package]] ++name = "log" ++version = "0.4.17" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" ++dependencies = [ ++ "cfg-if", ++] ++ ++[[package]] ++name = "memchr" ++version = "2.5.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" ++ ++[[package]] ++name = "num-bigint-dig" ++version = "0.8.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "566d173b2f9406afbc5510a90925d5a2cd80cae4605631f1212303df265de011" ++dependencies = [ ++ "byteorder", ++ "lazy_static", ++ "libm", ++ "num-integer", ++ "num-iter", ++ "num-traits", ++ "rand", ++ "smallvec", ++ "zeroize", ++] ++ ++[[package]] ++name = "num-integer" ++version = "0.1.45" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" ++dependencies = [ ++ "autocfg", ++ "num-traits", ++] ++ ++[[package]] ++name = "num-iter" ++version = "0.1.43" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" ++dependencies = [ ++ "autocfg", ++ "num-integer", ++ "num-traits", ++] ++ ++[[package]] ++name = "num-traits" ++version = "0.2.15" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" ++dependencies = [ ++ "autocfg", ++ "libm", ++] ++ ++[[package]] ++name = "once_cell" ++version = "1.14.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "2f7254b99e31cad77da24b08ebf628882739a608578bb1bcdfc1f9c21260d7c0" ++ ++[[package]] ++name = "p256" ++version = "0.11.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "51f44edd08f51e2ade572f141051021c5af22677e42b7dd28a88155151c33594" ++dependencies = [ ++ "ecdsa", ++ "elliptic-curve", ++ "sha2", ++] ++ ++[[package]] ++name = "p384" ++version = "0.11.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "dfc8c5bf642dde52bb9e87c0ecd8ca5a76faac2eeed98dedb7c717997e1080aa" ++dependencies = [ ++ "ecdsa", ++ "elliptic-curve", ++ "sha2", ++] ++ ++[[package]] ++name = "parking_lot" ++version = "0.11.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" ++dependencies = [ ++ "instant", ++ "lock_api", ++ "parking_lot_core", ++] ++ ++[[package]] ++name = "parking_lot_core" ++version = "0.8.5" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "d76e8e1493bcac0d2766c42737f34458f1c8c50c0d23bcb24ea953affb273216" ++dependencies = [ ++ "cfg-if", ++ "instant", ++ "libc", ++ "redox_syscall", ++ "smallvec", ++ "winapi", ++] ++ ++[[package]] ++name = "pem-rfc7468" ++version = "0.3.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "01de5d978f34aa4b2296576379fcc416034702fd94117c56ffd8a1a767cefb30" ++dependencies = [ ++ "base64ct", ++] ++ ++[[package]] ++name = "pem-rfc7468" ++version = "0.6.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "24d159833a9105500e0398934e205e0773f0b27529557134ecfc51c27646adac" ++dependencies = [ ++ "base64ct", ++] ++ ++[[package]] ++name = "percent-encoding" ++version = "2.2.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" ++ ++[[package]] ++name = "pin-project-lite" ++version = "0.2.9" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" ++ ++[[package]] ++name = "pin-utils" ++version = "0.1.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" ++ ++[[package]] ++name = "pkcs1" ++version = "0.3.3" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "a78f66c04ccc83dd4486fd46c33896f4e17b24a7a3a6400dedc48ed0ddd72320" ++dependencies = [ ++ "der 0.5.1", ++ "pkcs8 0.8.0", ++ "zeroize", ++] ++ ++[[package]] ++name = "pkcs8" ++version = "0.8.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "7cabda3fb821068a9a4fab19a683eac3af12edf0f34b94a8be53c4972b8149d0" ++dependencies = [ ++ "der 0.5.1", ++ "spki 0.5.4", ++ "zeroize", ++] ++ ++[[package]] ++name = "pkcs8" ++version = "0.9.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "9eca2c590a5f85da82668fa685c09ce2888b9430e83299debf1f34b65fd4a4ba" ++dependencies = [ ++ "der 0.6.0", ++ "spki 0.6.0", ++] ++ ++[[package]] ++name = "ppv-lite86" ++version = "0.2.16" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" ++ ++[[package]] ++name = "proc-macro2" ++version = "1.0.43" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab" ++dependencies = [ ++ "unicode-ident", ++] ++ ++[[package]] ++name = "quote" ++version = "1.0.21" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" ++dependencies = [ ++ "proc-macro2", ++] ++ ++[[package]] ++name = "rand" ++version = "0.8.5" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" ++dependencies = [ ++ "libc", ++ "rand_chacha", ++ "rand_core", ++] ++ ++[[package]] ++name = "rand_chacha" ++version = "0.3.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" ++dependencies = [ ++ "ppv-lite86", ++ "rand_core", ++] ++ ++[[package]] ++name = "rand_core" ++version = "0.6.3" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" ++dependencies = [ ++ "getrandom", ++] ++ ++[[package]] ++name = "redox_syscall" ++version = "0.2.16" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" ++dependencies = [ ++ "bitflags", ++] ++ ++[[package]] ++name = "rfc6979" ++version = "0.3.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "88c86280f057430a52f4861551b092a01b419b8eacefc7c995eacb9dc132fe32" ++dependencies = [ ++ "crypto-bigint 0.4.8", ++ "hmac", ++ "zeroize", ++] ++ ++[[package]] ++name = "rsa" ++version = "0.6.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "4cf22754c49613d2b3b119f0e5d46e34a2c628a937e3024b8762de4e7d8c710b" ++dependencies = [ ++ "byteorder", ++ "digest", ++ "num-bigint-dig", ++ "num-integer", ++ "num-iter", ++ "num-traits", ++ "pkcs1", ++ "pkcs8 0.8.0", ++ "rand_core", ++ "smallvec", ++ "subtle", ++ "zeroize", ++] ++ ++[[package]] ++name = "rstest" ++version = "0.15.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "e9c9dc66cc29792b663ffb5269be669f1613664e69ad56441fdb895c2347b930" ++dependencies = [ ++ "futures", ++ "futures-timer", ++ "rstest_macros", ++ "rustc_version", ++] ++ ++[[package]] ++name = "rstest_macros" ++version = "0.14.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "5015e68a0685a95ade3eee617ff7101ab6a3fc689203101ca16ebc16f2b89c66" ++dependencies = [ ++ "cfg-if", ++ "proc-macro2", ++ "quote", ++ "rustc_version", ++ "syn", ++] ++ ++[[package]] ++name = "rstest_reuse" ++version = "0.4.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "f9b5aed35457441e7e0db509695ba3932d4c47e046777141c167efe584d0ec17" ++dependencies = [ ++ "quote", ++ "rustc_version", ++ "syn", ++] ++ ++[[package]] ++name = "rustc_version" ++version = "0.4.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" ++dependencies = [ ++ "semver", ++] ++ ++[[package]] ++name = "rusty-jwt-tools" ++version = "0.1.0" ++dependencies = [ ++ "base64", ++ "ed25519-compact", ++ "elliptic-curve", ++ "fluvio-wasm-timer", ++ "getrandom", ++ "jwt-simple", ++ "p256", ++ "p384", ++ "rand", ++ "rstest", ++ "rstest_reuse", ++ "serde", ++ "serde_json", ++ "thiserror", ++ "url", ++ "uuid", ++ "wasm-bindgen-test", ++] ++ ++[[package]] ++name = "rusty-jwt-tools-ffi" ++version = "0.1.0" ++dependencies = [ ++ "cfg-if", ++ "rusty-jwt-tools", ++] ++ ++[[package]] ++name = "ryu" ++version = "1.0.11" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" ++ ++[[package]] ++name = "scoped-tls" ++version = "1.0.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" ++ ++[[package]] ++name = "scopeguard" ++version = "1.1.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" ++ ++[[package]] ++name = "sec1" ++version = "0.3.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "3be24c1842290c45df0a7bf069e0c268a747ad05a192f2fd7dcfdbc1cba40928" ++dependencies = [ ++ "base16ct", ++ "der 0.6.0", ++ "generic-array", ++ "pkcs8 0.9.0", ++ "serdect", ++ "subtle", ++ "zeroize", ++] ++ ++[[package]] ++name = "semver" ++version = "1.0.13" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "93f6841e709003d68bb2deee8c343572bf446003ec20a583e76f7b15cebf3711" ++ ++[[package]] ++name = "serde" ++version = "1.0.144" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "0f747710de3dcd43b88c9168773254e809d8ddbdf9653b84e2554ab219f17860" ++dependencies = [ ++ "serde_derive", ++] ++ ++[[package]] ++name = "serde_derive" ++version = "1.0.144" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "94ed3a816fb1d101812f83e789f888322c34e291f894f19590dc310963e87a00" ++dependencies = [ ++ "proc-macro2", ++ "quote", ++ "syn", ++] ++ ++[[package]] ++name = "serde_json" ++version = "1.0.85" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "e55a28e3aaef9d5ce0506d0a14dbba8054ddc7e499ef522dd8b26859ec9d4a44" ++dependencies = [ ++ "itoa", ++ "ryu", ++ "serde", ++] ++ ++[[package]] ++name = "serdect" ++version = "0.1.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "038fce1bf4d74b9b30ea7dcd59df75ba8ec669a5dcb3cc64fbfcef7334ced32c" ++dependencies = [ ++ "base16ct", ++ "serde", ++] ++ ++[[package]] ++name = "sha2" ++version = "0.10.5" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "cf9db03534dff993187064c4e0c05a5708d2a9728ace9a8959b77bedf415dac5" ++dependencies = [ ++ "cfg-if", ++ "cpufeatures", ++ "digest", ++] ++ ++[[package]] ++name = "signature" ++version = "1.6.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "f0ea32af43239f0d353a7dd75a22d94c329c8cdaafdcb4c1c1335aa10c298a4a" ++dependencies = [ ++ "digest", ++ "rand_core", ++] ++ ++[[package]] ++name = "slab" ++version = "0.4.7" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef" ++dependencies = [ ++ "autocfg", ++] ++ ++[[package]] ++name = "smallvec" ++version = "1.9.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "2fd0db749597d91ff862fd1d55ea87f7855a744a8425a64695b6fca237d1dad1" ++ ++[[package]] ++name = "spin" ++version = "0.5.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" ++ ++[[package]] ++name = "spki" ++version = "0.5.4" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "44d01ac02a6ccf3e07db148d2be087da624fea0221a16152ed01f0496a6b0a27" ++dependencies = [ ++ "base64ct", ++ "der 0.5.1", ++] ++ ++[[package]] ++name = "spki" ++version = "0.6.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "67cf02bbac7a337dc36e4f5a693db6c21e7863f45070f7064577eb4367a3212b" ++dependencies = [ ++ "base64ct", ++ "der 0.6.0", ++] ++ ++[[package]] ++name = "subtle" ++version = "2.4.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" ++ ++[[package]] ++name = "syn" ++version = "1.0.99" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13" ++dependencies = [ ++ "proc-macro2", ++ "quote", ++ "unicode-ident", ++] ++ ++[[package]] ++name = "thiserror" ++version = "1.0.34" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "8c1b05ca9d106ba7d2e31a9dab4a64e7be2cce415321966ea3132c49a656e252" ++dependencies = [ ++ "thiserror-impl", ++] ++ ++[[package]] ++name = "thiserror-impl" ++version = "1.0.34" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "e8f2591983642de85c921015f3f070c665a197ed69e417af436115e3a1407487" ++dependencies = [ ++ "proc-macro2", ++ "quote", ++ "syn", ++] ++ ++[[package]] ++name = "tinyvec" ++version = "1.6.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" ++dependencies = [ ++ "tinyvec_macros", ++] ++ ++[[package]] ++name = "tinyvec_macros" ++version = "0.1.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" ++ ++[[package]] ++name = "typenum" ++version = "1.15.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" ++ ++[[package]] ++name = "unicode-bidi" ++version = "0.3.8" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" ++ ++[[package]] ++name = "unicode-ident" ++version = "1.0.3" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "c4f5b37a154999a8f3f98cc23a628d850e154479cd94decf3414696e12e31aaf" ++ ++[[package]] ++name = "unicode-normalization" ++version = "0.1.21" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "854cbdc4f7bc6ae19c820d44abdc3277ac3e1b2b93db20a636825d9322fb60e6" ++dependencies = [ ++ "tinyvec", ++] ++ ++[[package]] ++name = "url" ++version = "2.3.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643" ++dependencies = [ ++ "form_urlencoded", ++ "idna", ++ "percent-encoding", ++ "serde", ++] ++ ++[[package]] ++name = "uuid" ++version = "1.1.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "dd6469f4314d5f1ffec476e05f17cc9a78bc7a27a6a857842170bdf8d6f98d2f" ++dependencies = [ ++ "getrandom", ++] ++ ++[[package]] ++name = "version_check" ++version = "0.9.4" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" ++ ++[[package]] ++name = "wasi" ++version = "0.11.0+wasi-snapshot-preview1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" ++ ++[[package]] ++name = "wasm-bindgen" ++version = "0.2.82" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "fc7652e3f6c4706c8d9cd54832c4a4ccb9b5336e2c3bd154d5cccfbf1c1f5f7d" ++dependencies = [ ++ "cfg-if", ++ "wasm-bindgen-macro", ++] ++ ++[[package]] ++name = "wasm-bindgen-backend" ++version = "0.2.82" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "662cd44805586bd52971b9586b1df85cdbbd9112e4ef4d8f41559c334dc6ac3f" ++dependencies = [ ++ "bumpalo", ++ "log", ++ "once_cell", ++ "proc-macro2", ++ "quote", ++ "syn", ++ "wasm-bindgen-shared", ++] ++ ++[[package]] ++name = "wasm-bindgen-futures" ++version = "0.4.32" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "fa76fb221a1f8acddf5b54ace85912606980ad661ac7a503b4570ffd3a624dad" ++dependencies = [ ++ "cfg-if", ++ "js-sys", ++ "wasm-bindgen", ++ "web-sys", ++] ++ ++[[package]] ++name = "wasm-bindgen-macro" ++version = "0.2.82" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "b260f13d3012071dfb1512849c033b1925038373aea48ced3012c09df952c602" ++dependencies = [ ++ "quote", ++ "wasm-bindgen-macro-support", ++] ++ ++[[package]] ++name = "wasm-bindgen-macro-support" ++version = "0.2.82" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "5be8e654bdd9b79216c2929ab90721aa82faf65c48cdf08bdc4e7f51357b80da" ++dependencies = [ ++ "proc-macro2", ++ "quote", ++ "syn", ++ "wasm-bindgen-backend", ++ "wasm-bindgen-shared", ++] ++ ++[[package]] ++name = "wasm-bindgen-shared" ++version = "0.2.82" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "6598dd0bd3c7d51095ff6531a5b23e02acdc81804e30d8f07afb77b7215a140a" ++ ++[[package]] ++name = "wasm-bindgen-test" ++version = "0.3.32" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "513df541345bb9fcc07417775f3d51bbb677daf307d8035c0afafd87dc2e6599" ++dependencies = [ ++ "console_error_panic_hook", ++ "js-sys", ++ "scoped-tls", ++ "wasm-bindgen", ++ "wasm-bindgen-futures", ++ "wasm-bindgen-test-macro", ++] ++ ++[[package]] ++name = "wasm-bindgen-test-macro" ++version = "0.3.32" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "6150d36a03e90a3cf6c12650be10626a9902d70c5270fd47d7a47e5389a10d56" ++dependencies = [ ++ "proc-macro2", ++ "quote", ++] ++ ++[[package]] ++name = "web-sys" ++version = "0.3.59" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "ed055ab27f941423197eb86b2035720b1a3ce40504df082cac2ecc6ed73335a1" ++dependencies = [ ++ "js-sys", ++ "wasm-bindgen", ++] ++ ++[[package]] ++name = "winapi" ++version = "0.3.9" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" ++dependencies = [ ++ "winapi-i686-pc-windows-gnu", ++ "winapi-x86_64-pc-windows-gnu", ++] ++ ++[[package]] ++name = "winapi-i686-pc-windows-gnu" ++version = "0.4.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" ++ ++[[package]] ++name = "winapi-x86_64-pc-windows-gnu" ++version = "0.4.0" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" ++ ++[[package]] ++name = "zeroize" ++version = "1.5.7" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "c394b5bd0c6f669e7275d9c20aa90ae064cb22e75a1cad54e1b34088034b149f" +-- +2.34.1 + diff --git a/nix/pkgs/rusty_jwt_tools/default.nix b/nix/pkgs/rusty_jwt_tools/default.nix new file mode 100644 index 0000000000..e62b32cbc4 --- /dev/null +++ b/nix/pkgs/rusty_jwt_tools/default.nix @@ -0,0 +1,33 @@ +{ fetchFromGitHub +, lib +, rustPlatform +}: + +rustPlatform.buildRustPackage rec { + name = "rusty-jwt-tools-${version}"; + version = "0.1.0"; + src = fetchFromGitHub { + owner = "wireapp"; + repo = "rusty-jwt-tools"; + # if you update this, please generate a new Cargo.lock file es described below at `cargoPatches` + rev = "6370cd556f03f6834d0b8043615ffaf0044ef1fa"; + sha256 = "sha256-vnTvKITie4pu+ISIl/RdYPfb/yWCdCI9eHl1KcZb050="; + }; + cargoBuildFeatures = "haskell"; + cargoSha256 = "sha256-gR9XKcJslCcXo3EnD3MweWm+pQr4/EAEuFyOq3/l97g="; + cargoPatches = [ + # a patch file to add/update Cargo.lock in the source code + # it's good practice not to add Cargo.lock to the source code for libraries + # see: https://doc.rust-lang.org/cargo/faq.html#why-do-binaries-have-cargolock-in-version-control-but-not-libraries + # however, because it is required by nix, we need to manually generate and add it: + # - `git clone git@github.com:wireapp/rusty-jwt-tools.git` + # - checkout the commit specified in `rev` + # - create a new branch: `git checkout -b patch-cargo-lock-` (replace `` with the commit hash) + # - `cargo build --release --features haskell` + # - `git add -f Cargo.lock` + # - `git commit -am "generate new cargo.lock"` + # - `git format-patch main` + # - copy contents of `0001-generate-new-cargo.lock.patch` into `nix/pkgs/rusty_jwt_tools/add-Cargo.lock.patch` + ./add-Cargo.lock.patch + ]; +} diff --git a/services/brig/brig.cabal b/services/brig/brig.cabal index 95f744d763..0fd5b904de 100644 --- a/services/brig/brig.cabal +++ b/services/brig/brig.cabal @@ -61,8 +61,10 @@ library Brig.Effects.CodeStore Brig.Effects.CodeStore.Cassandra Brig.Effects.Delay + Brig.Effects.JwtTools Brig.Effects.PasswordResetStore Brig.Effects.PasswordResetStore.CodeStore + Brig.Effects.PublicKeyBundle Brig.Effects.SFT Brig.Effects.UserPendingActivationStore Brig.Effects.UserPendingActivationStore.Cassandra @@ -227,6 +229,7 @@ library , insert-ordered-containers , iproute >=1.5 , iso639 >=0.1 + , jwt-tools , lens >=3.8 , lens-aeson >=1.0 , metrics-core >=0.3 @@ -507,6 +510,7 @@ executable brig-integration , attoparsec , base , base16-bytestring + , base64-bytestring , bilge , bloodhound , brig diff --git a/services/brig/brig.integration.yaml b/services/brig/brig.integration.yaml index 05e2eaaec9..4f2a64c247 100644 --- a/services/brig/brig.integration.yaml +++ b/services/brig/brig.integration.yaml @@ -189,6 +189,9 @@ optSettings: search_policy: full_search set2FACodeGenerationDelaySecs: 5 setNonceTtlSecs: 5 + setDpopMaxSkewSecs: 1 + setDpopTokenExpirationTimeSecs: 300 # 5 minutes + setPublicKeyBundle: test/resources/jwt/ed25519_bundle.pem logLevel: Warn # ^ NOTE: We log too much in brig, if we set this to Info like other services, running tests diff --git a/services/brig/src/Brig/API/Client.hs b/services/brig/src/Brig/API/Client.hs index a705eda0ae..0a139ecd90 100644 --- a/services/brig/src/Brig/API/Client.hs +++ b/services/brig/src/Brig/API/Client.hs @@ -33,6 +33,7 @@ module Brig.API.Client lookupLocalPubClientsBulk, Data.lookupPrekeyIds, Data.lookupUsersClientIds, + createAccessToken, -- * Prekeys claimLocalMultiPrekeyBundles, @@ -51,7 +52,12 @@ import Brig.API.Types import Brig.API.Util import Brig.App import qualified Brig.Data.Client as Data +import Brig.Data.Nonce as Nonce import qualified Brig.Data.User as Data +import Brig.Effects.JwtTools (JwtTools) +import qualified Brig.Effects.JwtTools as JwtTools +import Brig.Effects.PublicKeyBundle (PublicKeyBundle) +import qualified Brig.Effects.PublicKeyBundle as PublicKeyBundle import Brig.Federation.Client (getUserClients) import qualified Brig.Federation.Client as Federation import Brig.IO.Intra (guardLegalhold) @@ -80,20 +86,29 @@ import qualified Data.Map.Strict as Map import Data.Misc (PlainTextPassword (..)) import Data.Qualified import qualified Data.Set as Set +import Data.String.Conversions (cs) import Imports +import Network.HTTP.Types.Method (StdMethod) import Network.Wai.Utilities +import Polysemy (Member) +import Servant (Link, ToHttpApiData (toUrlPiece)) import System.Logger.Class (field, msg, val, (~~)) import qualified System.Logger.Class as Log import UnliftIO.Async (Concurrently (Concurrently, runConcurrently)) import Wire.API.Federation.API.Brig (GetUserClients (GetUserClients)) import Wire.API.Federation.Error +import Wire.API.MLS.Credential (ClientIdentity (..)) +import Wire.API.MLS.Epoch (addToEpoch) import qualified Wire.API.Message as Message import Wire.API.Team.LegalHold (LegalholdProtectee (..)) import Wire.API.User import qualified Wire.API.User as Code import Wire.API.User.Client +import Wire.API.User.Client.DPoPAccessToken import Wire.API.User.Client.Prekey import Wire.API.UserMap (QualifiedUserMap (QualifiedUserMap, qualifiedUserMap), UserMap (userMap)) +import Wire.Sem.FromUTC (FromUTC (fromUTCTime)) +import Wire.Sem.Now as Now lookupLocalClient :: UserId -> ClientId -> (AppT r) (Maybe Client) lookupLocalClient uid = wrapClient . Data.lookupClient uid @@ -438,3 +453,38 @@ removeLegalHoldClient uid = do -- maybe log if this isn't the case forM_ legalHoldClients (execDelete uid Nothing) wrapHttpClient $ Intra.onUserEvent uid Nothing (UserLegalHoldDisabled uid) + +createAccessToken :: + (Member JwtTools r, Member Now r, Member PublicKeyBundle r) => + UserId -> + ClientId -> + StdMethod -> + Link -> + Proof -> + ExceptT CertEnrollmentError (AppT r) (DPoPAccessTokenResponse, CacheControl) +createAccessToken uid cid method link proof = do + domain <- Opt.setFederationDomain <$> view settings + nonce <- ExceptT $ note NonceNotFound <$> wrapClient (Nonce.lookupAndDeleteNonce uid (cs $ toByteString cid)) + httpsUrl <- do + let urlBs = "https://" <> toByteString' domain <> "/" <> cs (toUrlPiece link) + maybe (throwE MisconfiguredRequestUrl) pure $ fromByteString $ urlBs + maxSkewSeconds <- Opt.setDpopMaxSkewSecs <$> view settings + expiresIn <- Opt.setDpopTokenExpirationTimeSecs <$> view settings + now <- fromUTCTime <$> lift (liftSem Now.get) + let expiresAt = now & addToEpoch expiresIn + pathToKeys <- ExceptT $ note KeyBundleError . Opt.setPublicKeyBundle <$> view settings + pubKeyBundle <- ExceptT $ note KeyBundleError <$> liftSem (PublicKeyBundle.get pathToKeys) + token <- + ExceptT $ + liftSem $ + JwtTools.generateDPoPAccessToken + proof + (ClientIdentity domain uid cid) + nonce + httpsUrl + method + maxSkewSeconds + expiresAt + now + pubKeyBundle + pure $ (DPoPAccessTokenResponse token DPoP expiresIn, NoStore) diff --git a/services/brig/src/Brig/API/Error.hs b/services/brig/src/Brig/API/Error.hs index acab9f94a7..9eafa8463d 100644 --- a/services/brig/src/Brig/API/Error.hs +++ b/services/brig/src/Brig/API/Error.hs @@ -25,6 +25,7 @@ import Data.Aeson import qualified Data.Aeson.KeyMap as KeyMap import Data.ByteString.Conversion import Data.Domain (Domain) +import Data.Jwt.Tools (DPoPTokenGenerationError (..)) import Data.String.Conversions (cs) import qualified Data.ZAuth.Validation as ZAuth import Imports @@ -170,6 +171,31 @@ clientError ClientMissingLegalholdConsent = StdError (errorToWai @'E.MissingLega clientError ClientCodeAuthenticationFailed = StdError verificationCodeAuthFailed clientError ClientCodeAuthenticationRequired = StdError verificationCodeRequired +certEnrollmentError :: CertEnrollmentError -> Error +certEnrollmentError (RustError NoError) = StdError $ Wai.mkError status500 "internal-error" "The server experienced an internal error during DPoP token generation. Unexpected NoError." +certEnrollmentError (RustError UnknownError) = StdError $ Wai.mkError status500 "internal-error" "The server experienced an internal error during DPoP token generation. Unknown error." +certEnrollmentError (RustError FfiError) = StdError $ Wai.mkError status500 "internal-error" "The server experienced an internal error during DPoP token generation" +certEnrollmentError (RustError ImplementationError) = StdError $ Wai.mkError status500 "internal-error" "The server experienced an internal error during DPoP token generation. Unexpected ImplementationError." +certEnrollmentError (RustError DpopSyntaxError) = StdError $ Wai.mkError status400 "client-token-parse-error" "The client JWT DPoP could not be parsed" +certEnrollmentError (RustError DpopTypError) = StdError $ Wai.mkError status400 "client-token-type-error" "The client JWT DPoP 'typ' must be 'dpop+jwt'" +certEnrollmentError (RustError DpopUnsupportedAlgorithmError) = StdError $ Wai.mkError status400 "client-token-unsupported-alg" "DPoP signature algorithm (alg) in JWT header is not a supported algorithm (ES256, ES384, Ed25519)" +certEnrollmentError (RustError DpopInvalidSignatureError) = StdError $ Wai.mkError status400 "client-token-bad-signature" "DPoP signature does not correspond to the public key (jwk) in the JWT header" +certEnrollmentError (RustError ClientIdMismatchError) = StdError $ Wai.mkError status400 "client-token-bad-client-id" "The client id does not correspond to the (sub) claim expressed as URI" +certEnrollmentError (RustError BackendNonceMismatchError) = StdError $ Wai.mkError status400 "client-token-bad-nonce" "The backend nonce does not correspond to the (nonce) claim in DPoP token (base64url encoded)" +certEnrollmentError (RustError HtuMismatchError) = StdError $ Wai.mkError status400 "client-token-bad-uri" "The request uri does not correspond to the (htu) claim in DPoP token" +certEnrollmentError (RustError HtmMismatchError) = StdError $ Wai.mkError status400 "client-token-bad-method" "The request method does not correspond to the (htm) claim in DPoP token" +certEnrollmentError (RustError MissingJtiError) = StdError $ Wai.mkError status400 "client-token-jti-missing" "(jti) claim is absent in DPoP token" +certEnrollmentError (RustError MissingChallengeError) = StdError $ Wai.mkError status400 "client-token-chal-missing" "(chal) claim is absent in DPoP token" +certEnrollmentError (RustError MissingIatError) = StdError $ Wai.mkError status400 "client-token-iat-missing" "(iat) claim is absent in DPoP token" +certEnrollmentError (RustError IatError) = StdError $ Wai.mkError status400 "client-token-bad-iat" "(iat) claim in DPoP token is not earlier of now (with max_skew_secs leeway)" +certEnrollmentError (RustError MissingExpError) = StdError $ Wai.mkError status400 "client-token-exp-missing" "(exp) claim is absent in DPoP token" +certEnrollmentError (RustError ExpMismatchError) = StdError $ Wai.mkError status400 "client-token-exp-too-large" "(exp) claim in DPoP token is larger than supplied [max_expiration]" +certEnrollmentError (RustError ExpError) = StdError $ Wai.mkError status400 "client-token-exp-too-small" "(exp) claim in DPoP token is sooner than now (with [max_skew_secs] leeway)" +certEnrollmentError NonceNotFound = StdError $ Wai.mkError status400 "client-token-bad-nonce" "The client sent an unacceptable anti-replay nonce" +certEnrollmentError MisconfiguredRequestUrl = StdError $ Wai.mkError status500 "misconfigured-request-url" "The request url cannot be derived from optSettings.setFederationDomain in brig.yaml" +certEnrollmentError KeyBundleError = StdError $ Wai.mkError status404 "no-server-key-bundle" "The key bundle required for the certificate enrollment process could not be found" +certEnrollmentError ClientIdSyntaxError = StdError $ Wai.mkError status400 "client-token-id-parse-error" "The client id could not be parsed" + fedError :: FederationError -> Error fedError = StdError . federationErrorToWai diff --git a/services/brig/src/Brig/API/Public.hs b/services/brig/src/Brig/API/Public.hs index b6eb96598c..ae22d1b844 100644 --- a/services/brig/src/Brig/API/Public.hs +++ b/services/brig/src/Brig/API/Public.hs @@ -47,7 +47,9 @@ import qualified Brig.Data.UserKey as UserKey import Brig.Effects.BlacklistPhonePrefixStore (BlacklistPhonePrefixStore) import Brig.Effects.BlacklistStore (BlacklistStore) import Brig.Effects.CodeStore (CodeStore) +import Brig.Effects.JwtTools (JwtTools) import Brig.Effects.PasswordResetStore (PasswordResetStore) +import Brig.Effects.PublicKeyBundle (PublicKeyBundle) import Brig.Effects.UserPendingActivationStore (UserPendingActivationStore) import qualified Brig.IO.Intra as Intra import Brig.Options hiding (internalEvents, sesQueue) @@ -127,12 +129,14 @@ import qualified Wire.API.User as Public import qualified Wire.API.User.Activation as Public import qualified Wire.API.User.Auth as Public import qualified Wire.API.User.Client as Public +import Wire.API.User.Client.DPoPAccessToken import qualified Wire.API.User.Client.Prekey as Public import qualified Wire.API.User.Handle as Public import qualified Wire.API.User.Password as Public import qualified Wire.API.User.RichInfo as Public import qualified Wire.API.UserMap as Public import qualified Wire.API.Wrapped as Public +import Wire.Sem.Now (Now) -- User API ----------------------------------------------------------- @@ -188,7 +192,10 @@ servantSitemap :: BlacklistPhonePrefixStore, UserPendingActivationStore p, PasswordResetStore, - CodeStore + CodeStore, + JwtTools, + PublicKeyBundle, + Now ] r => ServerT BrigAPI (Handler r) @@ -261,6 +268,7 @@ servantSitemap = userAPI :<|> selfAPI :<|> accountAPI :<|> clientAPI :<|> prekey :<|> Named @"get-client-prekeys" getClientPrekeys :<|> Named @"head-nonce" newNonce :<|> Named @"get-nonce" newNonce + :<|> Named @"create-access-token" (createAccessToken @UserClientAPI @CreateAccessToken POST) connectionAPI :: ServerT ConnectionAPI (Handler r) connectionAPI = @@ -512,12 +520,30 @@ getRichInfo self user = do getClientPrekeys :: UserId -> ClientId -> (Handler r) [Public.PrekeyId] getClientPrekeys usr clt = lift (wrapClient $ API.lookupPrekeyIds usr clt) -newNonce :: UserId -> ClientId -> (Handler r) Nonce +newNonce :: UserId -> ClientId -> (Handler r) (Nonce, CacheControl) newNonce uid cid = do ttl <- setNonceTtlSecs <$> view settings nonce <- randomNonce lift $ wrapClient $ Nonce.insertNonce ttl uid (client cid) nonce - pure nonce + pure (nonce, NoStore) + +createAccessToken :: + forall api endpoint r. + ( Member JwtTools r, + Member Now r, + Member PublicKeyBundle r, + IsElem endpoint api, + HasLink endpoint, + MkLink endpoint Link ~ (ClientId -> Link) + ) => + StdMethod -> + UserId -> + ClientId -> + Proof -> + (Handler r) (DPoPAccessTokenResponse, CacheControl) +createAccessToken method uid cid proof = do + let link = safeLink (Proxy @api) (Proxy @endpoint) cid + API.createAccessToken uid cid method link proof !>> certEnrollmentError -- | docs/reference/user/registration.md {#RefRegistration} createUser :: diff --git a/services/brig/src/Brig/API/Types.hs b/services/brig/src/Brig/API/Types.hs index b779fcb4dd..57acbd8697 100644 --- a/services/brig/src/Brig/API/Types.hs +++ b/services/brig/src/Brig/API/Types.hs @@ -39,6 +39,7 @@ import Brig.Data.UserKey (UserKey, foldKey) import Brig.Types.Intra import Data.Code import Data.Id +import Data.Jwt.Tools (DPoPTokenGenerationError (..)) import Data.Qualified import Data.RetryAfter import Imports @@ -204,6 +205,13 @@ data AccountStatusError data VerificationCodeThrottledError = VerificationCodeThrottled RetryAfter +data CertEnrollmentError + = NonceNotFound + | RustError DPoPTokenGenerationError + | KeyBundleError + | MisconfiguredRequestUrl + | ClientIdSyntaxError + ------------------------------------------------------------------------------- -- Exceptions diff --git a/services/brig/src/Brig/CanonicalInterpreter.hs b/services/brig/src/Brig/CanonicalInterpreter.hs index 37b22f9233..c05ec6710f 100644 --- a/services/brig/src/Brig/CanonicalInterpreter.hs +++ b/services/brig/src/Brig/CanonicalInterpreter.hs @@ -7,8 +7,10 @@ import Brig.Effects.BlacklistStore (BlacklistStore) import Brig.Effects.BlacklistStore.Cassandra (interpretBlacklistStoreToCassandra) import Brig.Effects.CodeStore (CodeStore) import Brig.Effects.CodeStore.Cassandra (codeStoreToCassandra, interpretClientToIO) +import Brig.Effects.JwtTools import Brig.Effects.PasswordResetStore (PasswordResetStore) import Brig.Effects.PasswordResetStore.CodeStore (passwordResetStoreToCodeStore) +import Brig.Effects.PublicKeyBundle import Brig.Effects.UserPendingActivationStore (UserPendingActivationStore) import Brig.Effects.UserPendingActivationStore.Cassandra (userPendingActivationStoreToCassandra) import qualified Cassandra as Cas @@ -20,7 +22,9 @@ import Wire.Sem.Now.IO (nowToIOAction) import Wire.Sem.Paging.Cassandra (InternalPaging) type BrigCanonicalEffects = - '[ BlacklistPhonePrefixStore, + '[ PublicKeyBundle, + JwtTools, + BlacklistPhonePrefixStore, BlacklistStore, PasswordResetStore, UserPendingActivationStore InternalPaging, @@ -42,4 +46,6 @@ runBrigToIO e (AppT ma) = . passwordResetStoreToCodeStore . interpretBlacklistStoreToCassandra @Cas.Client . interpretBlacklistPhonePrefixStoreToCassandra @Cas.Client + . interpretJwtTools + . interpretPublicKeyBundle $ runReaderT ma e diff --git a/services/brig/src/Brig/Effects/JwtTools.hs b/services/brig/src/Brig/Effects/JwtTools.hs new file mode 100644 index 0000000000..b345fcb2cf --- /dev/null +++ b/services/brig/src/Brig/Effects/JwtTools.hs @@ -0,0 +1,69 @@ +{-# LANGUAGE TemplateHaskell #-} + +module Brig.Effects.JwtTools where + +import Brig.API.Types (CertEnrollmentError (..)) +import Control.Monad.Trans.Except +import Data.ByteString.Conversion +import Data.Either.Extra +import Data.Id (ClientId (client)) +import qualified Data.Jwt.Tools as Jwt +import Data.Misc (HttpsUrl) +import Data.Nonce (Nonce) +import Data.PEMKeys +import Data.String.Conversions (cs) +import Imports +import Network.HTTP.Types (StdMethod (..)) +import Numeric (readHex) +import Polysemy +import Wire.API.MLS.Credential (ClientIdentity (..)) +import Wire.API.MLS.Epoch (Epoch (..)) +import Wire.API.User.Client.DPoPAccessToken (DPoPAccessToken (..), Proof (..)) + +data JwtTools m a where + GenerateDPoPAccessToken :: + -- | A DPoP proof in JWS Compact Serialization format + -- Note that the proof consists of three runs of base64url characters + -- (header, claims, signature) separated by period characters. + Proof -> + -- | The qualified client ID associated with the currently logged on user + ClientIdentity -> + -- | The most recent DPoP nonce provided by the backend to the current client + Nonce -> + -- | The HTTPS URI on the backend for the DPoP auth token endpoint + HttpsUrl -> + -- | The HTTPS method used on the backend for the DPoP auth token endpoint + StdMethod -> + -- | The maximum number of seconds of clock skew the implementation will allow + Word16 -> + -- | The expiration date and time, in seconds since "the epoch" + Epoch -> + -- | Current time in seconds since "the epoch" + Epoch -> + -- | PEM format concatenated private key and public key of the Wire backend + PEMKeys -> + JwtTools m (Either CertEnrollmentError DPoPAccessToken) + +makeSem ''JwtTools + +interpretJwtTools :: Members '[Embed IO] r => Sem (JwtTools ': r) a -> Sem r a +interpretJwtTools = interpret $ \(GenerateDPoPAccessToken pr ci n uri method skew ex now pem) -> do + case readHex @Word16 (cs $ client $ ciClient ci) of + [(parsedClientId, "")] -> + mapLeft RustError + <$> runExceptT + ( DPoPAccessToken + <$> Jwt.generateDpopToken + (Jwt.Proof (toByteString' pr)) + (Jwt.UserId (toByteString' (ciUser ci))) + (Jwt.ClientId parsedClientId) + (Jwt.Domain (toByteString' (ciDomain ci))) + (Jwt.Nonce (toByteString' n)) + (Jwt.Uri (toByteString' uri)) + method + (Jwt.MaxSkewSecs skew) + (Jwt.ExpiryEpoch (epochNumber ex)) + (Jwt.NowEpoch (epochNumber now)) + (Jwt.PemBundle (toByteString' pem)) + ) + _ -> pure $ Left ClientIdSyntaxError diff --git a/services/brig/src/Brig/Effects/PublicKeyBundle.hs b/services/brig/src/Brig/Effects/PublicKeyBundle.hs new file mode 100644 index 0000000000..2846bc7a5e --- /dev/null +++ b/services/brig/src/Brig/Effects/PublicKeyBundle.hs @@ -0,0 +1,20 @@ +{-# LANGUAGE TemplateHaskell #-} + +module Brig.Effects.PublicKeyBundle where + +import Control.Exception +import qualified Data.ByteString as BS +import Data.ByteString.Conversion +import Data.PEMKeys +import Imports +import Polysemy + +data PublicKeyBundle m a where + Get :: FilePath -> PublicKeyBundle m (Maybe PEMKeys) + +makeSem ''PublicKeyBundle + +interpretPublicKeyBundle :: Members '[Embed IO] r => Sem (PublicKeyBundle ': r) a -> Sem r a +interpretPublicKeyBundle = interpret $ \(Get fp) -> do + contents :: Either IOException ByteString <- liftIO $ try $ BS.readFile fp + pure $ either (const Nothing) fromByteString contents diff --git a/services/brig/src/Brig/Options.hs b/services/brig/src/Brig/Options.hs index dab2dbb1eb..f62c02472e 100644 --- a/services/brig/src/Brig/Options.hs +++ b/services/brig/src/Brig/Options.hs @@ -593,7 +593,16 @@ data Settings = Settings set2FACodeGenerationDelaySecsInternal :: !(Maybe Int), -- | The time-to-live of a nonce in seconds. -- use `setNonceTtlSecs` as the getter function which always provides a default value - setNonceTtlSecsInternal :: !(Maybe NonceTtlSecs) + setNonceTtlSecsInternal :: !(Maybe NonceTtlSecs), + -- | The maximum number of seconds of clock skew the implementation of generate_dpop_access_token in jwt-tools will allow + -- use `setDpopMaxSkewSecs` as the getter function which always provides a default value + setDpopMaxSkewSecsInternal :: !(Maybe Word16), + -- | The expiration time of a JWT DPoP token in seconds. + -- use `setDpopTokenExpirationTimeSecs` as the getter function which always provides a default value + setDpopTokenExpirationTimeSecsInternal :: !(Maybe Word64), + -- | Path to a .pem file containing the server's public key and private key + -- e.g. to sign JWT tokens + setPublicKeyBundle :: !(Maybe FilePath) } deriving (Show, Generic) @@ -627,6 +636,18 @@ defaultNonceTtlSecs = NonceTtlSecs $ 5 * 60 -- 5 minutes setNonceTtlSecs :: Settings -> NonceTtlSecs setNonceTtlSecs = fromMaybe defaultNonceTtlSecs . setNonceTtlSecsInternal +defaultDpopMaxSkewSecs :: Word16 +defaultDpopMaxSkewSecs = 1 + +setDpopMaxSkewSecs :: Settings -> Word16 +setDpopMaxSkewSecs = fromMaybe defaultDpopMaxSkewSecs . setDpopMaxSkewSecsInternal + +defaultDpopTokenExpirationTimeSecs :: Word64 +defaultDpopTokenExpirationTimeSecs = 30 + +setDpopTokenExpirationTimeSecs :: Settings -> Word64 +setDpopTokenExpirationTimeSecs = fromMaybe defaultDpopTokenExpirationTimeSecs . setDpopTokenExpirationTimeSecsInternal + -- | The analog to `GT.FeatureFlags`. This type tracks only the things that we need to -- express our current cloud business logic. -- @@ -808,6 +829,8 @@ instance FromJSON Settings where "setVerificationCodeTimeoutInternal" -> "setVerificationTimeout" "set2FACodeGenerationDelaySecsInternal" -> "set2FACodeGenerationDelaySecs" "setNonceTtlSecsInternal" -> "setNonceTtlSecs" + "setDpopMaxSkewSecsInternal" -> "setDpopMaxSkewSecs" + "setDpopTokenExpirationTimeSecsInternal" -> "setDpopTokenExpirationTimeSecs" other -> other } diff --git a/services/brig/test/integration/API/User/Client.hs b/services/brig/test/integration/API/User/Client.hs index 50bf88810e..e0e8e3f9bc 100644 --- a/services/brig/test/integration/API/User/Client.hs +++ b/services/brig/test/integration/API/User/Client.hs @@ -60,6 +60,7 @@ import Wire.API.User import qualified Wire.API.User as Public import Wire.API.User.Auth import Wire.API.User.Client +import Wire.API.User.Client.DPoPAccessToken import Wire.API.User.Client.Prekey import Wire.API.UserMap (QualifiedUserMap (..), UserMap (..), WrappedQualifiedUserMap) import Wire.API.Wrapped (Wrapped (..)) @@ -107,7 +108,13 @@ tests _cl _at opts p db b c g = test p "get /clients/:client - 200" $ testMLSClient b, test p "post /clients - 200 multiple temporary" $ testAddMultipleTemporary b g c, test p "client/prekeys/race" $ testPreKeyRace b, - test p "get/head nonce/clients" $ testNewNonce b + test p "get/head nonce/clients" $ testNewNonce b, + testGroup + "post /clients/:cid/access-token" + [ test p "success" $ testCreateAccessToken b, + test p "proof missing" $ testCreateAccessTokenMissingProof b, + test p "no nonce" $ testCreateAccessTokenNoNonce b + ] ] testAddGetClientVerificationCode :: DB.ClientState -> Brig -> Galley -> Http () @@ -976,6 +983,41 @@ testNewNonce brig = do Just "no-store" @=? getHeader "Cache-Control" response pure nonceBs +testCreateAccessToken :: Brig -> Http () +testCreateAccessToken brig = do + uid <- userId <$> randomUser brig + cid <- createClientForUser brig uid + n <- Util.headNonce brig uid cid Http () +testCreateAccessTokenMissingProof brig = do + uid <- userId <$> randomUser brig + cid <- createClientForUser brig uid + let mProof = Nothing + Util.createAccessToken brig uid cid mProof + !!! do + const 400 === statusCode + +testCreateAccessTokenNoNonce :: Brig -> Http () +testCreateAccessTokenNoNonce brig = do + uid <- userId <$> randomUser brig + cid <- createClientForUser brig uid + Util.createAccessToken brig uid cid (Just $ Proof "xxxx.yyyy.zzzz") + !!! do + const 400 === statusCode + const (Just "client-token-bad-nonce") === fmap Error.label . responseJsonMaybe + +createClientForUser :: Brig -> UserId -> Http ClientId +createClientForUser brig uid = + clientId <$> (responseJsonError =<< addClient brig uid (defNewClient PermanentClientType [head somePrekeys] (head someLastPrekeys))) + testCan'tDeleteLegalHoldClient :: Brig -> Http () testCan'tDeleteLegalHoldClient brig = do let hasPassword = False diff --git a/services/brig/test/integration/API/User/Util.hs b/services/brig/test/integration/API/User/Util.hs index 7551ef25c3..22b93dcb20 100644 --- a/services/brig/test/integration/API/User/Util.hs +++ b/services/brig/test/integration/API/User/Util.hs @@ -69,6 +69,7 @@ import qualified Wire.API.User as Public import Wire.API.User.Activation import Wire.API.User.Auth import Wire.API.User.Client +import Wire.API.User.Client.DPoPAccessToken (Proof) import Wire.API.User.Client.Prekey import Wire.API.User.Handle import Wire.API.User.Password @@ -578,3 +579,12 @@ nonce m brig uid cid = . paths ["clients", toByteString' cid, "nonce"] . zUser uid ) + +createAccessToken :: (MonadIO m, MonadHttp m, HasCallStack) => Brig -> UserId -> ClientId -> Maybe Proof -> m ResponseLBS +createAccessToken brig uid cid mProof = + post + ( brig + . paths ["clients", toByteString' cid, "access-token"] + . zUser uid + . maybe id (header "DPoP" . toByteString') mProof + ) diff --git a/services/brig/test/resources/jwt/ed25519_bundle.pem b/services/brig/test/resources/jwt/ed25519_bundle.pem new file mode 120000 index 0000000000..86e72031d1 --- /dev/null +++ b/services/brig/test/resources/jwt/ed25519_bundle.pem @@ -0,0 +1 @@ +../../../../../deploy/services-demo/conf/jwt/ed25519_bundle.pem \ No newline at end of file diff --git a/stack.yaml b/stack.yaml index 330a3c96a7..a04af0fab1 100644 --- a/stack.yaml +++ b/stack.yaml @@ -29,6 +29,7 @@ packages: - libs/gundeck-types - libs/hscim - libs/imports +- libs/jwt-tools - libs/metrics-core - libs/metrics-wai - libs/polysemy-wire-zoo