Sign Up
Log In
Log In
or
Sign Up
Places
All Projects
Status Monitor
Collapse sidebar
openSUSE:Leap:16.0:Staging:B
signon-plugin-oauth2
signon-plugin-oauth2-0.25git.20231124T142245~fa...
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File signon-plugin-oauth2-0.25git.20231124T142245~fab6988.obscpio of Package signon-plugin-oauth2
07070100000000000081A40000000000000000000000016560A3A5000000B2000000000000000000000000000000000000004000000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/.gitignore.moc .obj Makefile* builddir build-stamp configure-stamp core coverage-html debian moc_* tests/signon-oauth2plugin-tests *~ *.a *.gcda *.gcno *.moc *.o *.so *.swp *.so.* *.tar.* 07070100000001000081A40000000000000000000000016560A3A5000003B7000000000000000000000000000000000000004400000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/.gitlab-ci.ymlimage: ubuntu:bionic cache: key: apt-cache paths: - apt-cache/ before_script: - export APT_CACHE_DIR=`pwd`/apt-cache && mkdir -pv $APT_CACHE_DIR - apt-get update -yq && apt-get -o dir::cache::archives="$APT_CACHE_DIR" install -y qt5-qmake qtbase5-dev qtchooser pkg-config libqt5xmlpatterns5-dev libsignon-qt5-dev signon-plugins-dev - apt-get -o dir::cache::archives="$APT_CACHE_DIR" install -y dbus-test-runner lcov gcovr build_amd64: stage: build script: - export QT_SELECT=qt5 - mkdir build - cd build - qmake CONFIG+=debug CONFIG+=coverage .. - make -j 4 artifacts: paths: - ./ test_amd64: stage: test script: - cd build - make coverage-html dependencies: - build_amd64 artifacts: paths: - ./ pages: stage: deploy script: - mkdir public - cp -a build/coverage-html public/coverage dependencies: - test_amd64 artifacts: paths: - public 07070100000002000081A40000000000000000000000016560A3A500006742000000000000000000000000000000000000003D00000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/COPYING GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the library's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. <signature of Ty Coon>, 1 April 1990 Ty Coon, President of Vice That's all there is to it! 07070100000003000081A40000000000000000000000016560A3A5000001AA000000000000000000000000000000000000003F00000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/README.mdOAuth 1.0/2.0 plugin for the SignOn daemon ========================================== This plugin for the Accounts-SSO SignOn daemon handles the OAuth 1.0 and 2.0 authentication protocols. License ------- See COPYING file. Build instructions ------------------ This project depends on Qt 5.8 (or newer) and [signond](https://gitlab.com/accounts-sso/signond). To build it, just run ``` qmake make make install ``` 07070100000004000081A40000000000000000000000016560A3A500000789000000000000000000000000000000000000005000000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/common-installs-config.pri#----------------------------------------------------------------------------- # Installation configuration for all SSO plugins #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # default installation target for applications #----------------------------------------------------------------------------- contains( TEMPLATE, app ) { target.path = $${INSTALL_PREFIX}/bin INSTALLS += target message("====") message("==== INSTALLS += target") } #----------------------------------------------------------------------------- # default installation target for libraries #----------------------------------------------------------------------------- contains( TEMPLATE, lib ) { target.path = $${SIGNON_PLUGINS_DIR} INSTALLS += target message("====") message("==== INSTALLS += target") } #----------------------------------------------------------------------------- # target for header files #----------------------------------------------------------------------------- !isEmpty( headers.files ) { headers.path = $${INSTALL_PREFIX}/include/signon-plugins INSTALLS += headers message("====") message("==== INSTALLS += headers") } else { message("====") message("==== NOTE: Remember to add your plugin headers into `headers.files' for installation!") } #----------------------------------------------------------------------------- # target for header files #----------------------------------------------------------------------------- !isEmpty( pkgconfig.files ) { pkgconfig.path = $${INSTALL_LIBDIR}/pkgconfig INSTALLS += pkgconfig message("====") message("==== INSTALLS += pkgconfig") } else { message("====") message("==== NOTE: Remember to add your pkgconfig into `pkgconfig.files' for installation!") } # End of File 07070100000005000081A40000000000000000000000016560A3A50000099B000000000000000000000000000000000000004F00000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/common-project-config.pri#----------------------------------------------------------------------------- # Common variables for all projects. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Common configuration for all projects. #----------------------------------------------------------------------------- CONFIG += \ c++17 \ link_pkgconfig #MOC_DIR = .moc #OBJECTS_DIR = .obj RCC_DIR = resources UI_DIR = ui UI_HEADERS_DIR = ui/include UI_SOURCES_DIR = ui/src QMAKE_CXXFLAGS += -fno-exceptions \ -fno-rtti TOP_SRC_DIR = $$PWD #DEFINES += QT_NO_DEBUG_OUTPUT DEFINES += \ SIGNON_TRACE \ QT_DISABLE_DEPRECATED_BEFORE=0x050900 #----------------------------------------------------------------------------- # setup the installation prefix #----------------------------------------------------------------------------- INSTALL_PREFIX = /usr # default installation prefix # default prefix can be overriden by defining PREFIX when running qmake isEmpty( PREFIX ) { message("====") message("==== NOTE: To override the installation path run: `qmake PREFIX=/custom/path'") message("==== (current installation path is `$${INSTALL_PREFIX}')") } else { INSTALL_PREFIX = $${PREFIX} message("====") message("==== install prefix set to `$${INSTALL_PREFIX}'") } # Setup the library installation directory exists( meego-release ) { ARCH = $$system(tail -n1 meego-release) } else { ARCH = $$system(uname -m) } contains( ARCH, x86_64 ) { INSTALL_LIBDIR = $${INSTALL_PREFIX}/lib64 } else { INSTALL_LIBDIR = $${INSTALL_PREFIX}/lib } # default library directory can be overriden by defining LIBDIR when # running qmake isEmpty( LIBDIR ) { message("====") message("==== NOTE: To override the library installation path run: `qmake LIBDIR=/custom/path'") message("==== (current installation path is `$${INSTALL_LIBDIR}')") } else { INSTALL_LIBDIR = $${LIBDIR} message("====") message("==== library install path set to `$${INSTALL_LIBDIR}'") } # Default directory for signond extensions isEmpty(SIGNON_PLUGINS_DIR) { _PLUGINS = $$system(pkg-config --variable=plugindir signon-plugins) isEmpty(_PLUGINS) { error("plugin directory not available through pkg-config") } else { SIGNON_PLUGINS_DIR = $$_PLUGINS } } include( coverage.pri ) 07070100000006000081A40000000000000000000000016560A3A5000003D0000000000000000000000000000000000000004500000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/common-vars.pri#----------------------------------------------------------------------------- # Common variables for all projects. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Project name (used e.g. in include file and doc install path). # remember to update debian/* files if you changes this #----------------------------------------------------------------------------- PROJECT_NAME = signon-oauth2 #----------------------------------------------------------------------------- # Project version # remember to update debian/* files if you changes this #----------------------------------------------------------------------------- PROJECT_VERSION = 0.25 #----------------------------------------------------------------------------- # Library version #----------------------------------------------------------------------------- LIBRARY_VERSION = 0.5 # End of File 07070100000007000081A40000000000000000000000016560A3A500000734000000000000000000000000000000000000004200000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/coverage.pri# Coverage CONFIG(coverage) { LIBS += -lgcov QMAKE_CXXFLAGS += --coverage QMAKE_LDFLAGS += --coverage QMAKE_EXTRA_TARGETS += coverage cov QMAKE_EXTRA_TARGETS += clean-gcno clean-gcda coverage-html \ generate-coverage-html clean-coverage-html coverage-gcovr \ generate-gcovr generate-coverage-gcovr clean-coverage-gcovr clean-gcno.commands = \ "@echo Removing old coverage instrumentation"; \ "find -name '*.gcno' -print | xargs -r rm" clean-gcda.commands = \ "@echo Removing old coverage results"; \ "find -name '*.gcda' -print | xargs -r rm" coverage-html.depends = clean-gcda check generate-coverage-html generate-coverage-html.commands = \ "@echo Collecting coverage data"; \ "lcov --directory $${TOP_SRC_DIR} --capture --output-file coverage.info --no-checksum --compat-libtool"; \ "lcov --extract coverage.info \"*/src/*.cpp\" -o coverage.info"; \ "lcov --remove coverage.info \"moc_*.cpp\" -o coverage.info"; \ "LANG=C genhtml --prefix $${TOP_SRC_DIR} --output-directory coverage-html --title \"Code Coverage\" --legend --show-details coverage.info" clean-coverage-html.depends = clean-gcda clean-coverage-html.commands = \ "lcov --directory $${TOP_SRC_DIR} -z"; \ "rm -rf coverage.info coverage-html" coverage-gcovr.depends = clean-gcda check generate-coverage-gcovr generate-coverage-gcovr.commands = \ "@echo Generating coverage GCOVR report"; \ "gcovr -x -r $${TOP_SRC_DIR} -o $${TOP_SRC_DIR}/coverage.xml -e \".*/moc_.*\" -e \"tests/.*\" -e \".*\\.h\"" clean-coverage-gcovr.depends = clean-gcda clean-coverage-gcovr.commands = \ "rm -rf $${TOP_SRC_DIR}/coverage.xml" QMAKE_CLEAN += *.gcda *.gcno coverage.info coverage.xml } 07070100000008000041ED0000000000000000000000026560A3A500000000000000000000000000000000000000000000003D00000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/example07070100000009000081A40000000000000000000000016560A3A50000000C000000000000000000000000000000000000004800000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/example/.gitignoreoauthclient 0707010000000A000081A40000000000000000000000016560A3A50000020E000000000000000000000000000000000000004900000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/example/example.proinclude( ../common-project-config.pri ) include( ../common-vars.pri ) TEMPLATE = app TARGET = oauthclient INCLUDEPATH += . \ $$TOP_SRC_DIR/src/ CONFIG += \ debug \ link_pkgconfig QT -= gui PKGCONFIG += libsignon-qt$$QT_MAJOR_VERSION HEADERS += \ oauthclient.h SOURCES += \ main.cpp \ oauthclient.cpp # install include( ../common-installs-config.pri ) signon-ui.files = \ m.facebook.com.conf \ www.facebook.com.conf signon-ui.path = /etc/signon-ui/webkit-options.d/ INSTALLS += signon-ui 0707010000000B000081A40000000000000000000000016560A3A500000025000000000000000000000000000000000000005100000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/example/m.facebook.com.confPreferredWidth = 220 ZoomFactor = 2 0707010000000C000081A40000000000000000000000016560A3A50000046E000000000000000000000000000000000000004600000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/example/main.cpp/* * This file is part of signon * * Copyright (C) 2009-2010 Nokia Corporation. * * Contact: Alberto Mardegan <alberto.mardegan@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "oauthclient.h" #include <QCoreApplication> using namespace SignOn; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); OAuthClient client("213156715390803", "bf89c2d9de5e929fe5c5921e9a1f2924"); client.authenticate(); return app.exec(); } 0707010000000D000081A40000000000000000000000016560A3A50000096F000000000000000000000000000000000000004D00000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/example/oauthclient.cpp/* * This file is part of signon * * Copyright (C) 2011 Nokia Corporation. * * Contact: Alberto Mardegan <alberto.mardegan@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "oauthclient.h" #include "oauth2data.h" #include <QCoreApplication> #include <QDebug> using namespace OAuth2PluginNS; OAuthClient::OAuthClient(const QString &clientId, const QString &clientSecret, QObject *parent): QObject(parent), m_clientId(clientId), m_clientSecret(clientSecret), m_identity(0), m_session(0) { m_identity = SignOn::Identity::newIdentity(SignOn::IdentityInfo(), this); } OAuthClient::~OAuthClient() { } void OAuthClient::authenticate() { SignOn::AuthSession *m_session = m_identity->createSession("oauth2"); QObject::connect(m_session, &SignOn::AuthSession::response, this, &OAuthClient::onResponse); QObject::connect(m_session, &SignOn::AuthSession::error, this, &OAuthClient::onError); OAuth2PluginData data; data.setHost("www.facebook.com"); data.setAuthPath("/dialog/oauth"); data.setRedirectUri("https://www.facebook.com/connect/login_success.html"); data.setClientId(m_clientId); data.setClientSecret(m_clientSecret); m_session->process(data, "user_agent"); } void OAuthClient::onResponse(const SignOn::SessionData &sessionData) { OAuth2PluginTokenData response = sessionData.data<OAuth2PluginTokenData>(); qDebug() << "Access token:" << response.AccessToken(); qDebug() << "Expires in:" << response.ExpiresIn(); QCoreApplication::quit(); } void OAuthClient::onError(const SignOn::Error &error) { qDebug() << "Got error:" << error.message(); QCoreApplication::quit(); } 0707010000000E000081A40000000000000000000000016560A3A5000005C4000000000000000000000000000000000000004B00000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/example/oauthclient.h/* * This file is part of signon * * Copyright (C) 2009-2010 Nokia Corporation. * * Contact: Alberto Mardegan <alberto.mardegan@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef OAUTHCLIENT_H #define OAUTHCLIENT_H #include <SignOn/Identity> #include <SignOn/AuthSession> #include <QObject> class OAuthClient: public QObject { Q_OBJECT public: OAuthClient(const QString &clientId, const QString &clientSecret, QObject *parent = 0); ~OAuthClient(); public Q_SLOTS: void authenticate(); private Q_SLOTS: void onResponse(const SignOn::SessionData &sessionData); void onError(const SignOn::Error &error); private: QString m_clientId; QString m_clientSecret; SignOn::Identity *m_identity; SignOn::AuthSession *m_session; }; #endif // OAUTHCLIENT_H 0707010000000F000081A40000000000000000000000016560A3A500000025000000000000000000000000000000000000005300000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/example/www.facebook.com.confPreferredWidth = 220 ZoomFactor = 2 07070100000010000081A40000000000000000000000016560A3A500000230000000000000000000000000000000000000004700000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/signon-oauth2.proinclude( common-vars.pri ) include( common-project-config.pri ) TEMPLATE = subdirs CONFIG += ordered SUBDIRS = src tests CONFIG(make_examples) { SUBDIRS += example } CONFIG(nomake_tests) { SUBDIRS -= tests } include( common-installs-config.pri ) #include( doc/doc.pri ) DISTNAME = $${PROJECT_NAME}-$${PROJECT_VERSION} EXCLUDES = \ --exclude-vcs \ --exclude-from .gitignore dist.commands = "tar -cvjf $${DISTNAME}.tar.bz2 $$EXCLUDES --transform='s,^,$$DISTNAME/,' *" dist.depends = distclean QMAKE_EXTRA_TARGETS += dist # End of File 07070100000011000041ED0000000000000000000000026560A3A500000000000000000000000000000000000000000000003900000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src07070100000012000081A40000000000000000000000016560A3A500001751000000000000000000000000000000000000004900000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/base-plugin.cpp/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "common.h" #include "base-plugin.h" #include "oauth2tokendata.h" #include <QUrl> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkProxy> #include <QDateTime> #include <QCryptographicHash> using namespace SignOn; using namespace OAuth2PluginNS; namespace OAuth2PluginNS { class BasePluginPrivate { Q_DECLARE_PUBLIC(BasePlugin) public: BasePluginPrivate(BasePlugin *q); ~BasePluginPrivate(); void disposeReply(); QNetworkAccessManager *m_networkAccessManager; QNetworkReply *m_reply; mutable BasePlugin *q_ptr; }; //Private } //namespace OAuth2PluginNS BasePluginPrivate::BasePluginPrivate(BasePlugin *q): m_networkAccessManager(0), m_reply(0), q_ptr(q) { } BasePluginPrivate::~BasePluginPrivate() { disposeReply(); } void BasePluginPrivate::disposeReply() { Q_Q(BasePlugin); if (m_reply != 0) { QObject::disconnect(m_reply, 0, q, 0); m_reply->deleteLater(); m_reply = 0; } } BasePlugin::BasePlugin(QObject *parent): QObject(parent), d_ptr(new BasePluginPrivate(this)) { } BasePlugin::~BasePlugin() { delete d_ptr; d_ptr = 0; } void BasePlugin::cancel() { Q_D(BasePlugin); TRACE(); emit error(Error(Error::SessionCanceled)); if (d->m_reply) d->m_reply->abort(); } void BasePlugin::refresh(const SignOn::UiSessionData &data) { TRACE(); emit refreshed(data); } void BasePlugin::setNetworkAccessManager(QNetworkAccessManager *nam) { Q_D(BasePlugin); d->m_networkAccessManager = nam; } QNetworkAccessManager *BasePlugin::networkAccessManager() const { Q_D(const BasePlugin); return d->m_networkAccessManager; } void BasePlugin::postRequest(const QNetworkRequest &request, const QByteArray &data) { Q_D(BasePlugin); d->m_reply = d->m_networkAccessManager->post(request, data); connect(d->m_reply, &QNetworkReply::finished, this, &BasePlugin::onPostFinished); #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) connect(d->m_reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &BasePlugin::onNetworkError); #else connect(d->m_reply, &QNetworkReply::errorOccurred, this, &BasePlugin::onNetworkError); #endif connect(d->m_reply, &QNetworkReply::sslErrors, this, &BasePlugin::handleSslErrors); } void BasePlugin::serverReply(QNetworkReply *reply) { Q_UNUSED(reply); // Implemented by subclasses } void BasePlugin::onPostFinished() { Q_D(BasePlugin); QNetworkReply *reply = d->m_reply; TRACE() << "Finished signal received - reply object:" << reply; if (Q_UNLIKELY(!reply)) return; d->disposeReply(); if (reply->error() != QNetworkReply::NoError) { if (handleNetworkError(reply, reply->error())) return; } serverReply(reply); } void BasePlugin::onNetworkError(QNetworkReply::NetworkError err) { Q_D(BasePlugin); QNetworkReply *reply = d->m_reply; TRACE() << "Network error:" << err; if (Q_UNLIKELY(!reply)) return; handleNetworkError(reply, err); d->disposeReply(); } bool BasePlugin::handleNetworkError(QNetworkReply *reply, QNetworkReply::NetworkError err) { /* Has been handled by handleSslErrors already */ if (err == QNetworkReply::SslHandshakeFailedError) { return true; } /* HTTP errors handled in slots attached to signal */ if ((err > QNetworkReply::UnknownProxyError) && (err <= QNetworkReply::UnknownContentError)) { return false; } Error::ErrorType type = Error::Network; if (err <= QNetworkReply::UnknownNetworkError) type = Error::NoConnection; QString errorString = ""; errorString = reply->errorString(); emit error(Error(type, errorString)); return true; } void BasePlugin::handleSslErrors(QList<QSslError> errorList) { Q_D(BasePlugin); TRACE() << "Error: " << errorList; QString errorString = ""; foreach (QSslError error, errorList) { errorString += error.errorString() + ";"; } d->disposeReply(); emit error(Error(Error::Ssl, errorString)); } bool BasePlugin::handleUiErrors(const SignOn::UiSessionData &data) { int code = data.QueryErrorCode(); if (code == QUERY_ERROR_NONE) { return false; } TRACE() << "userActionFinished with error: " << code; if (code == QUERY_ERROR_CANCELED) { Q_EMIT error(Error(Error::SessionCanceled, QLatin1String("Cancelled by user"))); } else if (code == QUERY_ERROR_NETWORK) { Q_EMIT error(Error(Error::Network, QLatin1String("Network error"))); } else if (code == QUERY_ERROR_SSL) { Q_EMIT error(Error(Error::Ssl, QLatin1String("SSL error"))); } else { Q_EMIT error(Error(Error::UserInteraction, QString("userActionFinished error: ") + QString::number(data.QueryErrorCode()))); } return true; } 07070100000013000081A40000000000000000000000016560A3A500000B2E000000000000000000000000000000000000004700000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/base-plugin.h/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef SIGNON_PLUGIN_BASE #define SIGNON_PLUGIN_BASE #include <QtCore> #include <QSslError> #include <QNetworkReply> #include <SignOn/AuthPluginInterface> #include <SignOn/Error> #include <SignOn/SessionData> #include <SignOn/UiSessionData> class QNetworkAccessManager; namespace OAuth2PluginNS { /*! * @class BasePlugin * Base class for OAuth-based plugins. */ class BasePluginPrivate; class BasePlugin: public QObject { Q_OBJECT public: BasePlugin(QObject *parent = 0); ~BasePlugin(); virtual void cancel(); virtual void process(const SignOn::SessionData &inData, const QString &mechanism) = 0; virtual void userActionFinished(const SignOn::UiSessionData &data) = 0; virtual void refresh(const SignOn::UiSessionData &data); void setNetworkAccessManager(QNetworkAccessManager *nam); QNetworkAccessManager *networkAccessManager() const; protected: void postRequest(const QNetworkRequest &request, const QByteArray &data); virtual void serverReply(QNetworkReply *reply); /*! * Returns true if processing of the reply must stop. */ virtual bool handleNetworkError(QNetworkReply *reply, QNetworkReply::NetworkError err); bool handleUiErrors(const SignOn::UiSessionData &data); protected Q_SLOTS: void onPostFinished(); void onNetworkError(QNetworkReply::NetworkError err); virtual void handleSslErrors(QList<QSslError> errorList); Q_SIGNALS: void result(const SignOn::SessionData &data); void store(const SignOn::SessionData &data); void error(const SignOn::Error &err); void userActionRequired(const SignOn::UiSessionData &data); void refreshed(const SignOn::UiSessionData &data); void statusChanged(const AuthPluginState state, const QString &message); private: BasePluginPrivate *d_ptr; Q_DECLARE_PRIVATE(BasePlugin) }; } //namespace OAuth2PluginNS #endif // SIGNON_PLUGIN_BASE 07070100000014000081A40000000000000000000000016560A3A50000047E000000000000000000000000000000000000004200000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/common.h/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef SIGNON_PLUGIN_OAUTH2_COMMON #define SIGNON_PLUGIN_OAUTH2_COMMON #ifdef TRACE #undef TRACE #endif #ifdef SIGNON_TRACE #define TRACE() qDebug() << __FILE__ << __LINE__ << __func__ << ":" #else #define TRACE() if (0) qDebug() #endif #endif // SIGNON_PLUGIN_OAUTH2_COMMON 07070100000015000081A40000000000000000000000016560A3A500000DB4000000000000000000000000000000000000004600000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/oauth1data.h/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef OAUTH1DATA_H #define OAUTH1DATA_H #include <sessiondata.h> class OAuth2PluginTest; namespace OAuth2PluginNS { /*! * @class OAuth1PluginData * Data container to hold values for OAuth 1.0a authentication session. */ class OAuth1PluginData : public SignOn::SessionData { friend class ::OAuth2PluginTest; public: using SignOn::SessionData::SessionData; /*! * Request token endpoint of the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, RequestEndpoint); /*! * Access token endpoint of the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, TokenEndpoint); SIGNON_SESSION_DECLARE_PROPERTY(QString, AuthorizationEndpoint); /*! * Application client ID and secret */ SIGNON_SESSION_DECLARE_PROPERTY(QString, ConsumerKey); SIGNON_SESSION_DECLARE_PROPERTY(QString, ConsumerSecret); /*! * redirection URI */ SIGNON_SESSION_DECLARE_PROPERTY(QString, Callback); SIGNON_SESSION_DECLARE_PROPERTY(QString, Realm); /*! * one of "PLAINTEXT", "HMAC-SHA1", or "RSA-SHA1" * a method used used to sign the requests. */ SIGNON_SESSION_DECLARE_PROPERTY(QString, SignatureMethod); /*! * Set this to true if the access token returned by the previous * authentication is invalid. This instructs the OAuth plugin to * generate a new access token. */ SIGNON_SESSION_DECLARE_PROPERTY(bool, ForceTokenRefresh); /* Optional username */ SIGNON_SESSION_DECLARE_PROPERTY(QString, UserName); /*! * The User-Agent to be used in all HTTP requests. */ SIGNON_SESSION_DECLARE_PROPERTY(QString, UserAgent); }; class OAuth1PluginTokenData : public SignOn::SessionData { public: OAuth1PluginTokenData(const QVariantMap &data = QVariantMap()): SignOn::SessionData(data) {} /*! * Access token received from the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, AccessToken); /*! * Token secret received from the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, TokenSecret); /*! * Possible user ID received from the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, UserId); /*! * Possible screen name received from the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, ScreenName); }; } // namespace OAuth2PluginNS #endif // OAUTH1DATA_H 07070100000016000081A40000000000000000000000016560A3A500006326000000000000000000000000000000000000004A00000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/oauth1plugin.cpp/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "common.h" #include "oauth1data.h" #include "oauth1plugin.h" #include "oauth2tokendata.h" #include <QUrl> #include <QUrlQuery> #include <QNetworkReply> #include <QNetworkRequest> #include <QDateTime> #include <QCryptographicHash> using namespace SignOn; using namespace OAuth2PluginNS; namespace OAuth2PluginNS { // Enum for OAuth 1.0 POST request type typedef enum { OAUTH1_POST_REQUEST_INVALID = 0, OAUTH1_POST_REQUEST_TOKEN, OAUTH1_POST_ACCESS_TOKEN } OAuth1RequestType; const QString HMAC_SHA1 = QString("HMAC-SHA1"); const QString PLAINTEXT = QString("PLAINTEXT"); const QString RSA_SHA1 = QString("RSA-SHA1"); const QString OAUTH1 = QString("oauth1"); const QString EXPIRY = QString ("Expiry"); const QString USER_ID = QString("user_id"); const QString SCREEN_NAME = QString("screen_name"); const QString FORCE_LOGIN = QString("force_login"); const int HTTP_STATUS_OK = 200; const QString TIMESTAMP = QString("timestamp"); const QString AUTH_ERROR = QString("error"); const QString EQUAL = QString("="); const QString EQUAL_WITH_QUOTES = QString("%1=\"%2\""); const QString DELIMITER = QString(", "); const QString SPACE = QString(" "); const QString OAUTH = QString("OAuth"); const QString OAUTH_REALM = QString("realm"); const QString OAUTH_CALLBACK = QString("oauth_callback"); const QString OAUTH_CONSUMERKEY = QString("oauth_consumer_key"); const QString OAUTH_NONCE = QString("oauth_nonce"); const QString OAUTH_TIMESTAMP = QString("oauth_timestamp"); const QString OAUTH_SIGNATURE = QString("oauth_signature"); const QString OAUTH_SIGNATURE_METHOD = QString("oauth_signature_method"); const QString OAUTH_VERSION = QString("oauth_version"); const QString OAUTH_VERSION_1 = QString("1.0"); const QString OAUTH_TOKEN = QString("oauth_token"); const QString OAUTH_TOKEN_SECRET = QString("oauth_token_secret"); const QString OAUTH_VERIFIER = QString("oauth_verifier"); const QString OAUTH_PROBLEM = QString("oauth_problem"); const QString OAUTH_USER_REFUSED = QString("user_refused"); const QString OAUTH_PERMISSION_DENIED = QString("permission_denied"); const QByteArray CONTENT_TYPE = QByteArray("Content-Type"); const QByteArray CONTENT_APP_URLENCODED = QByteArray("application/x-www-form-urlencoded"); const QByteArray CONTENT_TEXT_PLAIN = QByteArray("text/plain"); const QByteArray CONTENT_TEXT_HTML = QByteArray("text/html"); class OAuth1PluginPrivate { public: OAuth1PluginPrivate() { TRACE(); #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) // Initialize randomizer qsrand(QTime::currentTime().msec()); #endif } ~OAuth1PluginPrivate() { TRACE(); } QString m_mechanism; OAuth1PluginData m_oauth1Data; QByteArray m_oauth1Token; QByteArray m_oauth1TokenSecret; QString m_oauth1UserId; QString m_oauth1ScreenName; QString m_oauth1TokenVerifier; OAuth1RequestType m_oauth1RequestType; QVariantMap m_tokens; QString m_key; QString m_username; QString m_password; }; //Private } //namespace OAuth2PluginNS OAuth1Plugin::OAuth1Plugin(QObject *parent): BasePlugin(parent), d_ptr(new OAuth1PluginPrivate()) { TRACE(); } OAuth1Plugin::~OAuth1Plugin() { TRACE(); delete d_ptr; d_ptr = 0; } QStringList OAuth1Plugin::mechanisms() { QStringList res = QStringList(); res.append(HMAC_SHA1); res.append(PLAINTEXT); res.append(OAUTH1); return res; } void OAuth1Plugin::sendOAuth1AuthRequest() { Q_D(OAuth1Plugin); QUrl url(d->m_oauth1Data.AuthorizationEndpoint()); QUrlQuery query(url); query.addQueryItem(OAUTH_TOKEN, d->m_oauth1Token); if (!d->m_oauth1ScreenName.isEmpty()) { // Prefill username for Twitter query.addQueryItem(SCREEN_NAME, d->m_oauth1ScreenName); query.addQueryItem(FORCE_LOGIN, d->m_oauth1ScreenName); } url.setQuery(query); TRACE() << "URL = " << url.toString(); SignOn::UiSessionData uiSession; uiSession.setOpenUrl(url.toString()); if (d->m_oauth1Data.Callback() != "oob") uiSession.setFinalUrl(d->m_oauth1Data.Callback()); /* add username and password, for fields initialization (the * decision on whether to actually use them is up to the signon UI */ uiSession.setUserName(d->m_username); uiSession.setSecret(d->m_password); emit userActionRequired(uiSession); } bool OAuth1Plugin::validateInput(const SignOn::SessionData &inData, const QString &mechanism) { OAuth1PluginData input = inData.data<OAuth1PluginData>(); if (mechanism == OAUTH1 && input.SignatureMethod().isEmpty()) { return false; } if (input.AuthorizationEndpoint().isEmpty() || input.ConsumerKey().isEmpty() || input.ConsumerSecret().isEmpty() || input.Callback().isEmpty() || input.TokenEndpoint().isEmpty() || input.RequestEndpoint().isEmpty()){ return false; } return true; } bool OAuth1Plugin::respondWithStoredToken(const QVariantMap &token, const QString &mechanism) { int timeToExpiry = 0; // if the token is expired, ignore it if (token.contains(EXPIRY)) { timeToExpiry = token.value(EXPIRY).toUInt() + token.value(TIMESTAMP).toUInt() - QDateTime::currentDateTime().toSecsSinceEpoch(); if (timeToExpiry < 0) { TRACE() << "Stored token is expired"; return false; } } if (mechanism == HMAC_SHA1 || mechanism == RSA_SHA1 || mechanism == PLAINTEXT) { if (token.contains(OAUTH_TOKEN) && token.contains(OAUTH_TOKEN_SECRET)) { OAuth1PluginTokenData response = oauth1responseFromMap(token); emit result(response); return true; } } return false; } void OAuth1Plugin::process(const SignOn::SessionData &inData, const QString &mechanism) { Q_D(OAuth1Plugin); if (!validateInput(inData, mechanism)) { TRACE() << "Invalid parameters passed"; emit error(Error(Error::MissingData)); return; } d->m_oauth1Data = inData.data<OAuth1PluginData>(); d->m_key = d->m_oauth1Data.ConsumerKey(); if (mechanism == OAUTH1) { d->m_mechanism = d->m_oauth1Data.SignatureMethod(); } else { d->m_mechanism = mechanism; } //get stored data OAuth2TokenData tokens = inData.data<OAuth2TokenData>(); d->m_tokens = tokens.Tokens(); if (inData.UiPolicy() == RequestPasswordPolicy) { //remove old token for given Key TRACE() << d->m_tokens; d->m_tokens.remove(d->m_key); OAuth2TokenData tokens; tokens.setTokens(d->m_tokens); emit store(tokens); TRACE() << d->m_tokens; } else if (d->m_oauth1Data.ForceTokenRefresh()) { // remove only the access token, not the refresh token QVariantMap storedData = d->m_tokens.value(d->m_key).toMap(); storedData.remove(OAUTH_TOKEN); d->m_tokens.insert(d->m_key, storedData); OAuth2TokenData tokens; tokens.setTokens(d->m_tokens); Q_EMIT store(tokens); TRACE() << "Clearing access token" << d->m_tokens; } //get provided token data if specified if (!tokens.ProvidedTokens().isEmpty()) { //check that the provided tokens contain required values OAuth1PluginTokenData providedTokens = SignOn::SessionData(tokens.ProvidedTokens()) .data<OAuth1PluginTokenData>(); if (providedTokens.AccessToken().isEmpty() || providedTokens.TokenSecret().isEmpty()) { //note: we don't check UserId or ScreenName as it might not be required TRACE() << "Invalid provided tokens data - continuing normal process flow"; } else { TRACE() << "Storing provided tokens"; QVariantMap storeTokens; storeTokens.insert(OAUTH_TOKEN, providedTokens.AccessToken()); storeTokens.insert(OAUTH_TOKEN_SECRET, providedTokens.TokenSecret()); if (!providedTokens.UserId().isNull()) storeTokens.insert(USER_ID, providedTokens.UserId()); if (!providedTokens.ScreenName().isNull()) storeTokens.insert(SCREEN_NAME, providedTokens.ScreenName()); d->m_oauth1Token = providedTokens.AccessToken().toLatin1(); d->m_oauth1TokenSecret = providedTokens.TokenSecret().toLatin1(); d->m_oauth1UserId = providedTokens.UserId().toLatin1(); d->m_oauth1ScreenName = providedTokens.ScreenName().toLatin1(); OAuth2TokenData tokens; d->m_tokens.insert(d->m_key, QVariant::fromValue(storeTokens)); tokens.setTokens(d->m_tokens); emit store(tokens); } } QVariant tokenVar = d->m_tokens.value(d->m_key); QVariantMap storedData; if (tokenVar.canConvert<QVariantMap>()) { storedData = tokenVar.value<QVariantMap>(); if (respondWithStoredToken(storedData, mechanism)) { return; } } /* Get username and password; the plugin doesn't use them, but forwards * them to the signon UI */ d->m_username = inData.UserName(); d->m_password = inData.Secret(); d->m_oauth1Token.clear(); d->m_oauth1TokenSecret.clear(); d->m_oauth1TokenVerifier.clear(); d->m_oauth1RequestType = OAUTH1_POST_REQUEST_INVALID; d->m_oauth1RequestType = OAUTH1_POST_REQUEST_TOKEN; if (!d->m_oauth1Data.UserName().isEmpty()) { d->m_oauth1ScreenName = d->m_oauth1Data.UserName(); //qDebug() << "Found username:" << d->m_oauth1ScreenName; } sendOAuth1PostRequest(); } QByteArray OAuth1Plugin::urlEncode(QString strData) { return QUrl::toPercentEncoding(strData).constData(); } // Create a HMAC-SHA1 signature QByteArray OAuth1Plugin::hashHMACSHA1(const QByteArray &baseSignatureString, const QByteArray &secret) { // The algorithm is defined in RFC 2104 int blockSize = 64; QByteArray key(baseSignatureString); QByteArray opad(blockSize, 0x5c); QByteArray ipad(blockSize, 0x36); // If key size is too large, compute the hash if (key.size() > blockSize) { key = QCryptographicHash::hash(key, QCryptographicHash::Sha1); } // If too small, pad with 0x00 if (key.size() < blockSize) { key += QByteArray(blockSize - key.size(), 0x00); } // Compute the XOR operations for (int i=0; i <= key.size() - 1; i++) { ipad[i] = (char) (ipad[i] ^ key[i]); opad[i] = (char) (opad[i] ^ key[i]); } // Append the data to ipad ipad += secret; // Hash sha1 of ipad and append the data to opad opad += QCryptographicHash::hash(ipad, QCryptographicHash::Sha1); // Return array contains the result of HMAC-SHA1 return QCryptographicHash::hash(opad, QCryptographicHash::Sha1); } QByteArray OAuth1Plugin::constructSignatureBaseString(const QString &aUrl, const OAuth1PluginData &inData, const QString ×tamp, const QString &nonce) { Q_D(OAuth1Plugin); QMap<QString, QString> oAuthHeaderMap; QUrl fullUrl(aUrl); QUrlQuery query(fullUrl); // Constructing the base string as per RFC 5849. Sec 3.4.1 QList<QPair<QString, QString> > queryItems = query.queryItems(); QPair<QString, QString> queryItem; foreach (queryItem, queryItems) { oAuthHeaderMap[queryItem.first] = queryItem.second; } if (!inData.Callback().isEmpty()) { oAuthHeaderMap[OAUTH_CALLBACK] = inData.Callback(); } oAuthHeaderMap[OAUTH_CONSUMERKEY] = inData.ConsumerKey(); oAuthHeaderMap[OAUTH_NONCE] = nonce; oAuthHeaderMap[OAUTH_SIGNATURE_METHOD] = d->m_mechanism; oAuthHeaderMap[OAUTH_TIMESTAMP] = timestamp; if (!d->m_oauth1Token.isEmpty()) { oAuthHeaderMap[OAUTH_TOKEN] = d->m_oauth1Token; } if (!d->m_oauth1TokenVerifier.isEmpty()) { oAuthHeaderMap[OAUTH_VERIFIER] = d->m_oauth1TokenVerifier; } oAuthHeaderMap[OAUTH_VERSION] = OAUTH_VERSION_1; QString oAuthHeaderString; QMap<QString, QString>::iterator i; bool first = true; for (i = oAuthHeaderMap.begin(); i != oAuthHeaderMap.end(); ++i) { if(!first) { oAuthHeaderString.append(QLatin1Char('&')); } else { first = false; } oAuthHeaderString.append(urlEncode(i.key()) + EQUAL + urlEncode(i.value())); } QString urlWithHostAndPath = fullUrl.toString(QUrl::RemoveUserInfo | QUrl::RemoveQuery | QUrl::RemoveFragment | QUrl::StripTrailingSlash); QByteArray signatureBase; signatureBase.append("POST"); signatureBase.append('&'); signatureBase.append(urlEncode(urlWithHostAndPath)); signatureBase.append('&'); signatureBase.append(urlEncode(oAuthHeaderString)); return signatureBase; } // Method to create the Authorization header QString OAuth1Plugin::createOAuth1Header(const QString &aUrl, OAuth1PluginData inData) { Q_D(OAuth1Plugin); QString authHeader = OAUTH + SPACE; if (!inData.Realm().isEmpty()) { authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_REALM) .arg(urlEncode(inData.Realm()).constData())); authHeader.append(DELIMITER); } if (!inData.Callback().isEmpty()) { authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_CALLBACK) .arg(urlEncode(inData.Callback()).constData())); authHeader.append(DELIMITER); } authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_CONSUMERKEY) .arg(urlEncode(inData.ConsumerKey()).constData())); authHeader.append(DELIMITER); // Nonce #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) unsigned long nonce1 = (unsigned long) qrand(); unsigned long nonce2 = (unsigned long) qrand(); #else unsigned long nonce1 = QRandomGenerator::global()->generate64(); unsigned long nonce2 = QRandomGenerator::global()->generate64(); #endif QString oauthNonce = QString("%1%2").arg(nonce1).arg(nonce2); authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_NONCE) .arg(urlEncode(oauthNonce).constData())); authHeader.append(DELIMITER); // Timestamp QString oauthTimestamp = QString("%1").arg(QDateTime::currentDateTime().toSecsSinceEpoch()); authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_TIMESTAMP) .arg(urlEncode(oauthTimestamp).constData())); authHeader.append(DELIMITER); if (!d->m_oauth1Token.isEmpty()) { authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_TOKEN) .arg(urlEncode(d->m_oauth1Token).constData())); authHeader.append(DELIMITER); } authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_SIGNATURE_METHOD) .arg(urlEncode(d->m_mechanism).constData())); authHeader.append(DELIMITER); // Creating the signature // PLAINTEXT signature method QByteArray secretKey; secretKey.append(urlEncode(inData.ConsumerSecret()) + '&' + urlEncode(d->m_oauth1TokenSecret)); if (d->m_mechanism == PLAINTEXT) { TRACE() << "Signature = " << secretKey; authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_SIGNATURE) .arg(urlEncode(secretKey).constData())); authHeader.append(DELIMITER); } // HMAC-SHA1 signature method else if (d->m_mechanism == HMAC_SHA1) { QByteArray signatureBase = constructSignatureBaseString(aUrl, inData, oauthTimestamp, oauthNonce); TRACE() << "Signature Base = " << signatureBase; QByteArray signature = hashHMACSHA1(secretKey, signatureBase); TRACE() << "Signature = " << signature; authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_SIGNATURE) .arg(urlEncode(signature.toBase64()).constData())); authHeader.append(DELIMITER); } // TODO: RSA-SHA1 signature method should be implemented else { Q_ASSERT_X(false, __FUNCTION__, "Unsupported mechanism"); } if (!d->m_oauth1TokenVerifier.isEmpty()) { authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_VERIFIER) .arg(urlEncode(d->m_oauth1TokenVerifier).constData())); authHeader.append(DELIMITER); } authHeader.append(EQUAL_WITH_QUOTES.arg(OAUTH_VERSION) .arg(urlEncode(OAUTH_VERSION_1).constData())); return authHeader; } void OAuth1Plugin::userActionFinished(const SignOn::UiSessionData &data) { Q_D(OAuth1Plugin); if (handleUiErrors(data)) return; TRACE() << data.UrlResponse(); // Checking if authorization server granted access QUrlQuery query(QUrl(data.UrlResponse())); if (query.hasQueryItem(AUTH_ERROR)) { TRACE() << "Server denied access permission"; emit error(Error(Error::NotAuthorized, query.queryItemValue(AUTH_ERROR))); return; } if (query.hasQueryItem(OAUTH_VERIFIER)) { d->m_oauth1TokenVerifier = query.queryItemValue(OAUTH_VERIFIER); d->m_oauth1Data.setCallback(QString()); d->m_oauth1RequestType = OAUTH1_POST_ACCESS_TOKEN; sendOAuth1PostRequest(); } else if (query.hasQueryItem(OAUTH_PROBLEM)) { handleOAuth1ProblemError(query.queryItemValue(OAUTH_PROBLEM)); } else { emit error(Error(Error::NotAuthorized, QString("oauth_verifier missing"))); } } // Method to handle responses for OAuth 1.0a Request token request void OAuth1Plugin::serverReply(QNetworkReply *reply) { Q_D(OAuth1Plugin); QByteArray replyContent = reply->readAll(); TRACE() << replyContent; if (reply->error() != QNetworkReply::NoError) { d->m_oauth1RequestType = OAUTH1_POST_REQUEST_INVALID; } // Handle error responses QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); TRACE() << statusCode; if (statusCode != HTTP_STATUS_OK) { handleOAuth1Error(replyContent); d->m_oauth1RequestType = OAUTH1_POST_REQUEST_INVALID; return; } // Handling 200 OK response (HTTP_STATUS_OK) WITH content if (reply->hasRawHeader(CONTENT_TYPE)) { // Checking if supported content type received if ((reply->rawHeader(CONTENT_TYPE).startsWith(CONTENT_APP_URLENCODED)) || (reply->rawHeader(CONTENT_TYPE).startsWith(CONTENT_TEXT_HTML)) || (reply->rawHeader(CONTENT_TYPE).startsWith(CONTENT_TEXT_PLAIN))) { const QMap<QString,QString> map = parseTextReply(replyContent); if (d->m_oauth1RequestType == OAUTH1_POST_REQUEST_TOKEN) { // Extracting the request token, token secret d->m_oauth1Token = map.value(OAUTH_TOKEN).toLatin1(); d->m_oauth1TokenSecret = map.value(OAUTH_TOKEN_SECRET).toLatin1(); if (d->m_oauth1Token.isEmpty() || !map.contains(OAUTH_TOKEN_SECRET)) { TRACE() << "OAuth request token is empty or secret is missing"; emit error(Error(Error::OperationFailed, QString("Request token or secret missing"))); } else { sendOAuth1AuthRequest(); } } else if (d->m_oauth1RequestType == OAUTH1_POST_ACCESS_TOKEN) { // Extracting the access token d->m_oauth1Token = map.value(OAUTH_TOKEN).toLatin1(); d->m_oauth1TokenSecret = map.value(OAUTH_TOKEN_SECRET).toLatin1(); if (d->m_oauth1Token.isEmpty() || !map.contains(OAUTH_TOKEN_SECRET)) { TRACE()<< "OAuth access token is empty or secret is missing"; emit error(Error(Error::OperationFailed, QString("Access token or secret missing"))); } else { QVariantMap siteResponse; QMap<QString, QString>::const_iterator i; for (i = map.begin(); i != map.end(); i++) { siteResponse.insert(i.key(), i.value()); } OAuth1PluginTokenData response = oauth1responseFromMap(siteResponse); // storing token and token secret for later use OAuth2TokenData tokens; d->m_tokens.insert(d->m_key, QVariant::fromValue(siteResponse)); tokens.setTokens(d->m_tokens); emit store(tokens); emit result(response); } } else { Q_ASSERT_X(false, __FUNCTION__, "Invalid OAuth1 POST request"); } } else { TRACE()<< "Unsupported content type received: " << reply->rawHeader(CONTENT_TYPE); emit error(Error(Error::OperationFailed, QString("Unsupported content type received"))); } } // Handling 200 OK response (HTTP_STATUS_OK) WITHOUT content else { TRACE()<< "Content is not present"; emit error(Error(Error::OperationFailed, QString("Content missing"))); } d->m_oauth1RequestType = OAUTH1_POST_REQUEST_INVALID; } OAuth1PluginTokenData OAuth1Plugin::oauth1responseFromMap(const QVariantMap &map) { Q_D(OAuth1Plugin); TRACE() << "Response:" << map; OAuth1PluginTokenData response(map); response.setAccessToken(map[OAUTH_TOKEN].toString().toLatin1()); response.setTokenSecret(map[OAUTH_TOKEN_SECRET].toString().toLatin1()); // Store also (possible) user_id & screen_name if (map.contains(USER_ID)) { d->m_oauth1UserId = map[USER_ID].toString(); response.setUserId(d->m_oauth1UserId); } if (map.contains(SCREEN_NAME)) { d->m_oauth1ScreenName = map[SCREEN_NAME].toString(); response.setScreenName(d->m_oauth1ScreenName); } return response; } void OAuth1Plugin::handleOAuth1ProblemError(const QString &errorString) { TRACE(); Error::ErrorType type = Error::OperationFailed; if (errorString == OAUTH_USER_REFUSED || errorString == OAUTH_PERMISSION_DENIED) { type = Error::PermissionDenied; } TRACE() << "Error Emitted"; emit error(Error(type, errorString)); } void OAuth1Plugin::handleOAuth1Error(const QByteArray &reply) { TRACE(); QMap<QString,QString> map = parseTextReply(reply); QString errorString = map[OAUTH_PROBLEM]; if (!errorString.isEmpty()) { handleOAuth1ProblemError(errorString); return; } TRACE() << "Error Emitted"; emit error(Error(Error::OperationFailed, errorString)); } void OAuth1Plugin::sendOAuth1PostRequest() { Q_D(OAuth1Plugin); TRACE(); QNetworkRequest request; request.setRawHeader(CONTENT_TYPE, CONTENT_APP_URLENCODED); if (!d->m_oauth1Data.UserAgent().isEmpty()) { request.setHeader(QNetworkRequest::UserAgentHeader, d->m_oauth1Data.UserAgent()); } QString authHeader; if (d->m_oauth1RequestType == OAUTH1_POST_REQUEST_TOKEN) { request.setUrl(d->m_oauth1Data.RequestEndpoint()); authHeader = createOAuth1Header(d->m_oauth1Data.RequestEndpoint(), d->m_oauth1Data); } else if (d->m_oauth1RequestType == OAUTH1_POST_ACCESS_TOKEN) { request.setUrl(d->m_oauth1Data.TokenEndpoint()); authHeader = createOAuth1Header(d->m_oauth1Data.TokenEndpoint(), d->m_oauth1Data); } else { Q_ASSERT_X(false, __FUNCTION__, "Invalid OAuth1 POST request"); } request.setRawHeader(QByteArray("Authorization"), authHeader.toLatin1()); postRequest(request, QByteArray()); } const QMap<QString, QString> OAuth1Plugin::parseTextReply(const QByteArray &reply) { TRACE(); QMap<QString, QString> map; QList<QByteArray> items = reply.split('&'); foreach (QByteArray item, items) { int idx = item.indexOf("="); if (idx > -1) { map.insert(item.left(idx), QByteArray::fromPercentEncoding(item.mid(idx + 1))); } } return map; } 07070100000017000081A40000000000000000000000016560A3A500000A58000000000000000000000000000000000000004800000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/oauth1plugin.h/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef SIGNON_PLUGIN_OAUTH1 #define SIGNON_PLUGIN_OAUTH1 #include <QtCore> #include "base-plugin.h" #include "oauth1data.h" namespace OAuth2PluginNS { /*! * @class OAuth1Plugin * OAuth 1.0a authentication plugin. */ class OAuth1PluginPrivate; class OAuth1Plugin: public BasePlugin { Q_OBJECT public: OAuth1Plugin(QObject *parent = 0); ~OAuth1Plugin(); static QStringList mechanisms(); void process(const SignOn::SessionData &inData, const QString &mechanism = 0); void userActionFinished(const SignOn::UiSessionData &data); protected: void serverReply(QNetworkReply *reply); private: void sendOAuth1AuthRequest(); bool validateInput(const SignOn::SessionData &inData, const QString &mechanism); bool respondWithStoredToken(const QVariantMap &token, const QString &mechanism); void sendOAuth1PostRequest(); const QMap<QString, QString> parseTextReply(const QByteArray &reply); void handleOAuth1ProblemError(const QString &errorString); void handleOAuth1Error(const QByteArray &reply); QByteArray constructSignatureBaseString(const QString &aUrl, const OAuth1PluginData &inData, const QString ×tamp, const QString &nonce); QByteArray urlEncode(QString strData); QString createOAuth1Header(const QString &aUrl, OAuth1PluginData inData); QByteArray hashHMACSHA1(const QByteArray &keyForHash ,const QByteArray &secret); OAuth1PluginTokenData oauth1responseFromMap(const QVariantMap &map); OAuth1PluginPrivate *d_ptr; Q_DECLARE_PRIVATE(OAuth1Plugin) }; } //namespace OAuth2PluginNS #endif // SIGNON_PLUGIN_OAUTH1 07070100000018000081A40000000000000000000000016560A3A5000012FD000000000000000000000000000000000000004600000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/oauth2data.h/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef OAUTH2DATA_H #define OAUTH2DATA_H #include <sessiondata.h> class OAuth2PluginTest; namespace OAuth2PluginNS { /*! * @class OAuth2PluginData * Data container to hold values for OAuth 2.0 authentication session. */ class OAuth2PluginData : public SignOn::SessionData { friend class ::OAuth2PluginTest; public: using SignOn::SessionData::SessionData; /*! * hostname of the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, Host); /*! * hostname component of the authorization endpoint URI */ SIGNON_SESSION_DECLARE_PROPERTY(QString, AuthHost); /*! * hostname component of the token endpoint URI */ SIGNON_SESSION_DECLARE_PROPERTY(QString, TokenHost); /*! * authorization endpoint of the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, AuthPath); /*! * token endpoint of the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, TokenPath); /*! * port component of the token endpoint URI */ SIGNON_SESSION_DECLARE_PROPERTY(quint16, AuthPort); /*! * port component of the authorization endpoint URI */ SIGNON_SESSION_DECLARE_PROPERTY(quint16, TokenPort); /*! * Application client ID and secret */ SIGNON_SESSION_DECLARE_PROPERTY(QString, ClientId); SIGNON_SESSION_DECLARE_PROPERTY(QString, ClientSecret); /*! * Set this to true if the server does not conform to the OAuth 2.0 * specification in that it does not support supplying client ID and * secret via basic HTTP authorization. */ SIGNON_SESSION_DECLARE_PROPERTY(bool, ForceClientAuthViaRequestBody); /*! * Set this to true if the access token returned by the previous * authentication is invalid. This instructs the OAuth plugin to * generate a new access token. */ SIGNON_SESSION_DECLARE_PROPERTY(bool, ForceTokenRefresh); /*! * Set this to true if the provider does not support passing the * "state" parameter around, as described in * http://tools.ietf.org/html/rfc6749#appendix-A.5 */ SIGNON_SESSION_DECLARE_PROPERTY(bool, DisableStateParameter); /*! * redirection URI */ SIGNON_SESSION_DECLARE_PROPERTY(QString, RedirectUri); /*! * access scope */ SIGNON_SESSION_DECLARE_PROPERTY(QStringList, Scope); /*! * response type */ SIGNON_SESSION_DECLARE_PROPERTY(QStringList, ResponseType); /*! * query component of the authorization endpoint URI */ SIGNON_SESSION_DECLARE_PROPERTY(QString, AuthQuery); /*! * query component of the token endpoint URI */ SIGNON_SESSION_DECLARE_PROPERTY(QString, TokenQuery); }; class OAuth2PluginTokenData : public SignOn::SessionData { public: /*! * Access token received from the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, AccessToken); /*! * OpenID token received from the server (optional) */ SIGNON_SESSION_DECLARE_PROPERTY(QString, IdToken); /*! * Refresh token received from the server */ SIGNON_SESSION_DECLARE_PROPERTY(QString, RefreshToken); /*! * Access token expiry time */ SIGNON_SESSION_DECLARE_PROPERTY(int, ExpiresIn); /*! * Granted permissions */ SIGNON_SESSION_DECLARE_PROPERTY(QStringList, Scope); /*! * Any extra (non standard) fields which were returned by the server */ SIGNON_SESSION_DECLARE_PROPERTY(QVariantMap, ExtraFields); }; } // namespace OAuth2PluginNS #endif // OAUTH2DATA_H 07070100000019000081A40000000000000000000000016560A3A5000070D4000000000000000000000000000000000000004A00000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/oauth2plugin.cpp/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "common.h" #include "oauth2plugin.h" #include "oauth2tokendata.h" #include <QJsonDocument> #include <QUrl> #include <QUrlQuery> #include <QNetworkRequest> #include <QNetworkReply> #include <QDateTime> using namespace SignOn; using namespace OAuth2PluginNS; namespace OAuth2PluginNS { const QString WEB_SERVER = QString("web_server"); const QString USER_AGENT = QString("user_agent"); const QString OAUTH2 = QString("oauth2"); const QString TOKEN = QString("Token"); const QString EXPIRY = QString("Expiry"); const QString SCOPES = QString("Scopes"); const QString EXTRA_FIELDS = QString("ExtraFields"); const int HTTP_STATUS_OK = 200; const QString AUTH_CODE = QString("code"); const QString REDIRECT_URI = QString("redirect_uri"); const QString RESPONSE_TYPE = QString("response_type"); const QString STATE = QString("state"); const QString USERNAME = QString("username"); const QString PASSWORD = QString("password"); const QString ASSERTION_TYPE = QString("assertion_type"); const QString ASSERTION = QString("assertion"); const QString ACCESS_TOKEN = QString("access_token"); const QString ID_TOKEN = QString("id_token"); const QString EXPIRES_IN = QString("expires_in"); const QString SCOPE = QString("scope"); const QString TIMESTAMP = QString("timestamp"); const QString GRANT_TYPE = QString("grant_type"); const QString AUTHORIZATION_CODE = QString("authorization_code"); const QString USER_BASIC = QString("user_basic"); const QString CLIENT_ID = QString("client_id"); const QString CLIENT_SECRET = QString("client_secret"); const QString REFRESH_TOKEN = QString("refresh_token"); const QString AUTH_ERROR = QString("error"); const QByteArray CONTENT_TYPE = QByteArray("Content-Type"); const QByteArray CONTENT_APP_URLENCODED = QByteArray("application/x-www-form-urlencoded"); const QByteArray CONTENT_APP_JSON = QByteArray("application/json"); const QByteArray CONTENT_TEXT_PLAIN = QByteArray("text/plain"); const QByteArray CONTENT_TEXT_HTML = QByteArray("text/html"); class OAuth2PluginPrivate { public: OAuth2PluginPrivate(): m_grantType(GrantType::Undefined) { TRACE(); #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) // Initialize randomizer qsrand(QTime::currentTime().msec()); #endif } ~OAuth2PluginPrivate() { TRACE(); } QString m_mechanism; OAuth2PluginData m_oauth2Data; QVariantMap m_tokens; QString m_state; QString m_key; QString m_username; QString m_password; GrantType::e m_grantType; }; //Private } //namespace OAuth2PluginNS OAuth2Plugin::OAuth2Plugin(QObject *parent): BasePlugin(parent), d_ptr(new OAuth2PluginPrivate()) { TRACE(); } OAuth2Plugin::~OAuth2Plugin() { TRACE(); delete d_ptr; d_ptr = 0; } QStringList OAuth2Plugin::mechanisms() { QStringList res = QStringList(); res.append(WEB_SERVER); res.append(USER_AGENT); res.append(OAUTH2); return res; } QUrl OAuth2Plugin::getAuthUrl() { Q_D(OAuth2Plugin); QString host = d->m_oauth2Data.AuthHost(); if (host.isEmpty()) host = d->m_oauth2Data.Host(); if (host.isEmpty()) return QUrl(); QUrl url(QString("https://%1/%2").arg(host).arg(d->m_oauth2Data.AuthPath())); quint16 port = d->m_oauth2Data.AuthPort(); if (port != 0) url.setPort(port); QString query = d->m_oauth2Data.AuthQuery(); if (!query.isEmpty()) url.setQuery(query); return url; } QUrl OAuth2Plugin::getTokenUrl() { Q_D(OAuth2Plugin); QString host = d->m_oauth2Data.TokenHost(); if (host.isEmpty()) host = d->m_oauth2Data.Host(); if (host.isEmpty()) return QUrl(); QUrl url(QString("https://%1/%2").arg(host).arg(d->m_oauth2Data.TokenPath())); quint16 port = d->m_oauth2Data.TokenPort(); if (port != 0) url.setPort(port); return url; } void OAuth2Plugin::sendOAuth2AuthRequest() { Q_D(OAuth2Plugin); QUrl url = getAuthUrl(); QUrlQuery query(url); query.addQueryItem(CLIENT_ID, d->m_oauth2Data.ClientId()); QString redirectUri = d->m_oauth2Data.RedirectUri(); query.addQueryItem(REDIRECT_URI, QUrl::toPercentEncoding(redirectUri)); if (!d->m_oauth2Data.DisableStateParameter()) { #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) d->m_state = QString::number(qrand()); #else d->m_state = QString::number(QRandomGenerator::global()->generate()); #endif query.addQueryItem(STATE, d->m_state); } QStringList responseType = d->m_oauth2Data.ResponseType(); if (!responseType.isEmpty()) { query.addQueryItem(RESPONSE_TYPE, responseType.join(" ")); } QStringList scopes = d->m_oauth2Data.Scope(); if (!scopes.isEmpty()) { // Passing list of scopes query.addQueryItem(SCOPE, QUrl::toPercentEncoding(scopes.join(" "))); } url.setQuery(query); TRACE() << "Url = " << url.toString(); SignOn::UiSessionData uiSession; uiSession.setOpenUrl(url.toString()); if (!redirectUri.isEmpty()) uiSession.setFinalUrl(redirectUri); /* add username and password, for fields initialization (the * decision on whether to actually use them is up to the signon UI */ uiSession.setUserName(d->m_username); uiSession.setSecret(d->m_password); emit userActionRequired(uiSession); } bool OAuth2Plugin::validateInput(const SignOn::SessionData &inData, const QString &mechanism) { OAuth2PluginData input = inData.data<OAuth2PluginData>(); if ((input.Host().isEmpty() && (input.AuthHost().isEmpty() || input.TokenHost().isEmpty())) || input.ClientId().isEmpty() || input.RedirectUri().isEmpty() || input.AuthPath().isEmpty()) return false; if (mechanism == WEB_SERVER || mechanism == OAUTH2) { /* According to the specs, the client secret is also required; however, * some services do not require it, see for instance point 8 from * http://msdn.microsoft.com/en-us/library/live/hh243647.aspx#authcodegrant */ if (input.TokenPath().isEmpty()) return false; } return true; } bool OAuth2Plugin::respondWithStoredToken(const QVariantMap &token, const QStringList &scopes) { int timeToExpiry = 0; // if the token is expired, ignore it if (token.contains(EXPIRY)) { timeToExpiry = token.value(EXPIRY).toUInt() + token.value(TIMESTAMP).toUInt() - QDateTime::currentDateTime().toSecsSinceEpoch(); if (timeToExpiry < 0) { TRACE() << "Stored token is expired"; return false; } } /* if the stored token does not contain all the requested scopes, * we cannot use it now */ if (!scopes.isEmpty()) { if (!token.contains(SCOPES)) return false; QStringList scopesList = token.value(SCOPES).toStringList(); #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) QSet<QString> cachedScopes = scopesList.toSet(); if (!cachedScopes.contains(scopes.toSet())) return false; #else QSet<QString> cachedScopes(scopesList.begin(), scopesList.end()); if (!cachedScopes.contains(QSet(scopes.begin(), scopes.end()))) return false; #endif } if (token.contains(TOKEN)) { OAuth2PluginTokenData response; response.setAccessToken(token.value(TOKEN).toByteArray()); if (token.contains(ID_TOKEN)) { response.setIdToken(token.value(ID_TOKEN).toByteArray()); } if (token.contains(REFRESH_TOKEN)) { response.setRefreshToken(token.value(REFRESH_TOKEN).toByteArray()); } if (token.contains(EXPIRY)) { response.setExpiresIn(timeToExpiry); } if (token.contains(EXTRA_FIELDS)) { response.setExtraFields(token.value(EXTRA_FIELDS).toMap()); } TRACE() << "Responding with stored token"; emit result(response); return true; } return false; } void OAuth2Plugin::process(const SignOn::SessionData &inData, const QString &mechanism) { Q_D(OAuth2Plugin); if ((!mechanism.isEmpty()) && (!mechanisms().contains(mechanism))) { emit error(Error(Error::MechanismNotAvailable)); return; } if (!validateInput(inData, mechanism)) { TRACE() << "Invalid parameters passed"; emit error(Error(Error::MissingData)); return; } const QVariant scopeVariant = inData.getProperty("Scope"); if (scopeVariant.type() == QVariant::String) { inData.toMap().insert(QLatin1String("Scope"), QVariant(scopeVariant.toString().split(" "))); } const QVariant resptypeVariant = inData.getProperty("ResponseType"); if (resptypeVariant.type() == QVariant::String) { inData.toMap().insert(QLatin1String("ResponseType"), QVariant(resptypeVariant.toString().split(" "))); } d->m_mechanism = mechanism; d->m_oauth2Data = inData.data<OAuth2PluginData>(); d->m_key = d->m_oauth2Data.ClientId(); //get stored data OAuth2TokenData tokens = inData.data<OAuth2TokenData>(); d->m_tokens = tokens.Tokens(); if (inData.UiPolicy() == RequestPasswordPolicy) { //remove old token for given Key TRACE() << d->m_tokens; d->m_tokens.remove(d->m_key); OAuth2TokenData tokens; tokens.setTokens(d->m_tokens); emit store(tokens); TRACE() << d->m_tokens; } else if (d->m_oauth2Data.ForceTokenRefresh()) { // remove only the access token, not the refresh token QVariantMap storedData = d->m_tokens.value(d->m_key).toMap(); storedData.remove(TOKEN); d->m_tokens.insert(d->m_key, storedData); OAuth2TokenData tokens; tokens.setTokens(d->m_tokens); Q_EMIT store(tokens); TRACE() << "Clearing access token" << d->m_tokens; } //get provided token data if specified if (!tokens.ProvidedTokens().isEmpty()) { //check that the provided tokens contain required values OAuth2PluginTokenData providedTokens = SignOn::SessionData(tokens.ProvidedTokens()) .data<OAuth2PluginTokenData>(); if (providedTokens.AccessToken().isEmpty() || providedTokens.RefreshToken().isEmpty()) { //note: we don't check ExpiresIn as it might not be required TRACE() << "Invalid provided tokens data - continuing normal process flow"; } else { TRACE() << "Storing provided tokens"; OAuth2PluginTokenData storeTokens; storeTokens.setAccessToken(providedTokens.AccessToken()); if (!providedTokens.IdToken().isEmpty()) { storeTokens.setIdToken(providedTokens.IdToken()); } storeTokens.setRefreshToken(providedTokens.RefreshToken()); storeTokens.setExpiresIn(providedTokens.ExpiresIn()); storeResponse(storeTokens); } } QVariant tokenVar = d->m_tokens.value(d->m_key); QVariantMap storedData; if (tokenVar.canConvert<QVariantMap>()) { storedData = tokenVar.value<QVariantMap>(); if (respondWithStoredToken(storedData, d->m_oauth2Data.Scope())) { return; } } /* Get username and password; the plugin doesn't use them, but forwards * them to the signon UI */ d->m_username = inData.UserName(); d->m_password = inData.Secret(); if (mechanism == WEB_SERVER || mechanism == USER_AGENT || mechanism == OAUTH2) { if ((mechanism == WEB_SERVER || mechanism == OAUTH2) && storedData.contains(REFRESH_TOKEN) && !storedData[REFRESH_TOKEN].toString().isEmpty()) { /* If we have a refresh token, use it to get a renewed * access token */ refreshOAuth2Token(storedData[REFRESH_TOKEN].toString()); } else { sendOAuth2AuthRequest(); } } else { emit error(Error(Error::MechanismNotAvailable)); } } QByteArray OAuth2Plugin::urlEncode(QString strData) { return QUrl::toPercentEncoding(strData); } void OAuth2Plugin::userActionFinished(const SignOn::UiSessionData &data) { Q_D(OAuth2Plugin); if (handleUiErrors(data)) return; TRACE() << data.UrlResponse(); // Checking if authorization server granted access QUrl url = QUrl(data.UrlResponse()); QUrlQuery query(url); if (query.hasQueryItem(AUTH_ERROR)) { TRACE() << "Server denied access permission"; emit error(Error(Error::NotAuthorized, query.queryItemValue(AUTH_ERROR))); return; } if (d->m_mechanism == USER_AGENT) { // Response should contain the access token OAuth2PluginTokenData respData; if (url.hasFragment()) { QString state; respData.setScope(d->m_oauth2Data.Scope()); QUrlQuery fragment(url.fragment()); QVariantMap extraFields; typedef QPair<QString, QString> StringPair; Q_FOREACH(const StringPair &pair, fragment.queryItems()) { if (pair.first == ACCESS_TOKEN) { respData.setAccessToken(pair.second); } else if (pair.first == ID_TOKEN) { respData.setIdToken(pair.second); } else if (pair.first == EXPIRES_IN) { respData.setExpiresIn(pair.second.toInt()); } else if (pair.first == REFRESH_TOKEN) { respData.setRefreshToken(pair.second); } else if (pair.first == STATE) { state = pair.second; } else if (pair.first == SCOPE) { #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) respData.setScope(pair.second.split(' ', QString::SkipEmptyParts)); #else respData.setScope(pair.second.split(' ', Qt::SkipEmptyParts)); #endif } else { extraFields.insert(pair.first, pair.second); } } respData.setExtraFields(extraFields); if (!d->m_oauth2Data.DisableStateParameter() && state != d->m_state) { Q_EMIT error(Error(Error::NotAuthorized, QString("'state' parameter mismatch"))); return; } if (respData.AccessToken().isEmpty()) { emit error(Error(Error::NotAuthorized, QString("Access token not present"))); } else { storeResponse(respData); emit result(respData); } } else { emit error(Error(Error::NotAuthorized, QString("Access token not present"))); } } else if (d->m_mechanism == WEB_SERVER || d->m_mechanism == OAUTH2) { // Access grant can be one of the floolwing types // 1. Authorization code (code, redirect_uri) // 2. Resource owner credentials (username, password) // 3. Assertion (assertion_type, assertion) // 4. Refresh Token (refresh_token) QUrlQuery tokenQuery(d->m_oauth2Data.TokenQuery()); if (query.hasQueryItem(AUTH_CODE)) { if (!d->m_oauth2Data.DisableStateParameter() && d->m_state != query.queryItemValue(STATE)) { Q_EMIT error(Error(Error::NotAuthorized, QString("'state' parameter mismatch"))); return; } QString code = query.queryItemValue(AUTH_CODE); tokenQuery.addQueryItem(GRANT_TYPE, AUTHORIZATION_CODE); tokenQuery.addQueryItem(AUTH_CODE, code); tokenQuery.addQueryItem(REDIRECT_URI, d->m_oauth2Data.RedirectUri()); sendOAuth2PostRequest(tokenQuery, GrantType::AuthorizationCode); } else if (query.hasQueryItem(USERNAME) && query.hasQueryItem(PASSWORD)) { QString username = query.queryItemValue(USERNAME); QString password = query.queryItemValue(PASSWORD); tokenQuery.addQueryItem(GRANT_TYPE, USER_BASIC); tokenQuery.addQueryItem(USERNAME, username); tokenQuery.addQueryItem(PASSWORD, password); sendOAuth2PostRequest(tokenQuery, GrantType::UserBasic); } else if (query.hasQueryItem(ASSERTION_TYPE) && query.hasQueryItem(ASSERTION)) { QString assertion_type = query.queryItemValue(ASSERTION_TYPE); QString assertion = query.queryItemValue(ASSERTION); tokenQuery.addQueryItem(GRANT_TYPE, ASSERTION); tokenQuery.addQueryItem(ASSERTION_TYPE, assertion_type); tokenQuery.addQueryItem(ASSERTION, assertion); sendOAuth2PostRequest(tokenQuery, GrantType::Assertion); } else if (query.hasQueryItem(REFRESH_TOKEN)) { QString refresh_token = query.queryItemValue(REFRESH_TOKEN); refreshOAuth2Token(refresh_token); } else { emit error(Error(Error::NotAuthorized, QString("Access grant not present"))); } } } QVariantMap OAuth2Plugin::parseReply(const QByteArray &contentType, const QByteArray &replyContent) { typedef QVariantMap (OAuth2Plugin::*Parser)(const QByteArray &replyContent); Parser preferredParser; Parser fallbackParser; QVariantMap map; // Handling application/json content type if (contentType.startsWith(CONTENT_APP_JSON)) { TRACE() << "application/json content received"; preferredParser = &OAuth2Plugin::parseJSONReply; fallbackParser = &OAuth2Plugin::parseTextReply; } // Added for facebook Graph API's (handling text/plain content type) else if (contentType.startsWith(CONTENT_TEXT_PLAIN) || contentType.startsWith(CONTENT_TEXT_HTML) || contentType.startsWith(CONTENT_APP_URLENCODED)) { TRACE() << contentType << "content received"; preferredParser = &OAuth2Plugin::parseTextReply; fallbackParser = &OAuth2Plugin::parseJSONReply; } else { TRACE() << "Unsupported content type received: " << contentType; Q_EMIT error(Error(Error::OperationFailed, QString("Unsupported content type received"))); return map; } map = (this->*preferredParser)(replyContent); if (Q_UNLIKELY(map.isEmpty())) { TRACE() << "Parse failed, trying fallback parser"; map = (this->*fallbackParser)(replyContent); if (Q_UNLIKELY(map.isEmpty())) { TRACE() << "Parse failed"; Q_EMIT error(Error(Error::NotAuthorized, QString("No access token found"))); } } return map; } // Method to handle responses for OAuth 2.0 requests void OAuth2Plugin::serverReply(QNetworkReply *reply) { Q_D(OAuth2Plugin); QByteArray replyContent = reply->readAll(); TRACE() << replyContent; // Handle error responses QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); TRACE() << statusCode; if (statusCode != HTTP_STATUS_OK) { handleOAuth2Error(replyContent); return; } // Handling 200 OK response (HTTP_STATUS_OK) WITH content if (reply->hasRawHeader(CONTENT_TYPE)) { QVariantMap map = parseReply(reply->rawHeader(CONTENT_TYPE), replyContent); if (Q_UNLIKELY(map.isEmpty())) { // The error has already been delivered return; } QByteArray accessToken = map.take("access_token").toByteArray(); QByteArray idToken = map.take("id_token").toByteArray(); int expiresIn = map.take("expires_in").toInt(); if (expiresIn == 0) { // Facebook uses just "expires" as key expiresIn = map.take("expires").toInt(); } QByteArray refreshToken = map.take("refresh_token").toByteArray(); QStringList scope; if (map.contains(SCOPE)) { QString rawScope = QString::fromUtf8(map.take(SCOPE).toByteArray()); #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) scope = rawScope.split(' ', QString::SkipEmptyParts); #else scope = rawScope.split(' ', Qt::SkipEmptyParts); #endif } else { scope = d->m_oauth2Data.Scope(); } if (accessToken.isEmpty()) { TRACE()<< "Access token is empty"; Q_EMIT error(Error(Error::NotAuthorized, QString("Access token is empty"))); } else { OAuth2PluginTokenData response; response.setAccessToken(accessToken); if (idToken.length() > 0) { response.setIdToken(idToken); } response.setRefreshToken(refreshToken); response.setExpiresIn(expiresIn); response.setScope(scope); response.setExtraFields(map); storeResponse(response); emit result(response); } } // Handling 200 OK response (HTTP_STATUS_OK) WITHOUT content else { TRACE()<< "Content is not present"; emit error(Error(Error::OperationFailed, QString("Content missing"))); } } bool OAuth2Plugin::handleNetworkError(QNetworkReply *reply, QNetworkReply::NetworkError err) { if (err >= QNetworkReply::ContentAccessDenied) { QByteArray replyContent = reply->readAll(); TRACE() << replyContent; handleOAuth2Error(replyContent); return true; } return BasePlugin::handleNetworkError(reply, err); } void OAuth2Plugin::handleOAuth2Error(const QByteArray &reply) { Q_D(OAuth2Plugin); TRACE(); QVariantMap map = parseJSONReply(reply); QByteArray errorString = map["error"].toByteArray(); if (!errorString.isEmpty()) { if (d->m_grantType == GrantType::RefreshToken) { /* The refresh token has expired; try once more using * the web-based authentication flow. */ TRACE() << "Authenticating without refresh token"; sendOAuth2AuthRequest(); return; } Error::ErrorType type = Error::OperationFailed; if (errorString == QByteArray("incorrect_client_credentials")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("redirect_uri_mismatch")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("bad_authorization_code")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("invalid_client_credentials")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("unauthorized_client")) { type = Error::NotAuthorized; } else if (errorString == QByteArray("invalid_assertion")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("unknown_format")) { type = Error::InvalidQuery; } else if (errorString == QByteArray("authorization_expired")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("multiple_credentials")) { type = Error::InvalidQuery; } else if (errorString == QByteArray("invalid_user_credentials")) { type = Error::InvalidCredentials; } else if (errorString == QByteArray("invalid_grant")) { type = Error::NotAuthorized; } TRACE() << "Error Emitted"; emit error(Error(type, errorString)); return; } // Added to work with facebook Graph API's errorString = map["message"].toByteArray(); TRACE() << "Error Emitted"; emit error(Error(Error::OperationFailed, errorString)); } void OAuth2Plugin::refreshOAuth2Token(const QString &refreshToken) { TRACE() << refreshToken; QUrlQuery query; query.addQueryItem(GRANT_TYPE, REFRESH_TOKEN); query.addQueryItem(REFRESH_TOKEN, refreshToken); sendOAuth2PostRequest(query, GrantType::RefreshToken); } void OAuth2Plugin::sendOAuth2PostRequest(QUrlQuery &postData, GrantType::e grantType) { Q_D(OAuth2Plugin); TRACE(); QUrl url(d->m_oauth2Data.TokenPath()); if (url.isRelative()) { url = getTokenUrl(); } QNetworkRequest request(url); request.setRawHeader(CONTENT_TYPE, CONTENT_APP_URLENCODED); if (!d->m_oauth2Data.ClientSecret().isEmpty()) { if (d->m_oauth2Data.ForceClientAuthViaRequestBody()) { postData.addQueryItem(CLIENT_ID, d->m_oauth2Data.ClientId()); postData.addQueryItem(CLIENT_SECRET, d->m_oauth2Data.ClientSecret()); } else { QByteArray authorization = QUrl::toPercentEncoding(d->m_oauth2Data.ClientId()) + ":" + QUrl::toPercentEncoding(d->m_oauth2Data.ClientSecret()); QByteArray basicAuthorization = QByteArray("Basic ") + authorization.toBase64(); request.setRawHeader("Authorization", basicAuthorization); } } else { postData.addQueryItem(CLIENT_ID, d->m_oauth2Data.ClientId()); } d->m_grantType = grantType; TRACE() << "Query string = " << postData.query(QUrl::FullyDecoded); postRequest(request, postData.query(QUrl::FullyDecoded).toLatin1()); } void OAuth2Plugin::storeResponse(const OAuth2PluginTokenData &response) { Q_D(OAuth2Plugin); OAuth2TokenData tokens; QVariantMap token; token.insert(TOKEN, response.AccessToken()); if (response.IdToken().length() > 0) { token.insert(ID_TOKEN, response.IdToken()); } /* Do not overwrite the refresh token with an empty one: when using the * refresh token to obtain a new access token, the replie could not contain * a refresh token (or contain an empty one). * In such cases, we should re-store the old refresh token. */ QString refreshToken; if (response.RefreshToken().isEmpty()) { QVariant tokenVar = d->m_tokens.value(d->m_key); QVariantMap storedData; if (tokenVar.canConvert<QVariantMap>()) { storedData = tokenVar.value<QVariantMap>(); if (storedData.contains(REFRESH_TOKEN) && !storedData[REFRESH_TOKEN].toString().isEmpty()) { refreshToken = storedData[REFRESH_TOKEN].toString(); } } } else { refreshToken = response.RefreshToken(); } token.insert(REFRESH_TOKEN, refreshToken); if (response.ExpiresIn() > 0) { token.insert(EXPIRY, response.ExpiresIn()); } token.insert(TIMESTAMP, QDateTime::currentDateTime().toSecsSinceEpoch()); token.insert(SCOPES, d->m_oauth2Data.Scope()); token.insert(EXTRA_FIELDS, response.ExtraFields()); d->m_tokens.insert(d->m_key, QVariant::fromValue(token)); tokens.setTokens(d->m_tokens); Q_EMIT store(tokens); TRACE() << d->m_tokens; } QVariantMap OAuth2Plugin::parseJSONReply(const QByteArray &reply) { TRACE(); QJsonDocument doc = QJsonDocument::fromJson(reply); bool ok = !doc.isEmpty(); QVariant tree = doc.toVariant(); if (ok) { return tree.toMap(); } return QVariantMap(); } QVariantMap OAuth2Plugin::parseTextReply(const QByteArray &reply) { TRACE(); QVariantMap map; QList<QByteArray> items = reply.split('&'); foreach (QByteArray item, items) { int idx = item.indexOf("="); if (idx > -1) { map.insert(item.left(idx), QByteArray::fromPercentEncoding(item.mid(idx + 1))); } } return map; } 0707010000001A000081A40000000000000000000000016560A3A500000B19000000000000000000000000000000000000004800000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/oauth2plugin.h/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef SIGNON_PLUGIN_OAUTH2 #define SIGNON_PLUGIN_OAUTH2 #include <QtCore> #include <SignOn/AuthPluginInterface> #include <SignOn/SessionData> #include <SignOn/Error> #include "base-plugin.h" #include "oauth2data.h" class QUrlQuery; namespace OAuth2PluginNS { namespace GrantType { enum e { Undefined = 0, RefreshToken, UserBasic, Assertion, AuthorizationCode, }; }; /*! * @class OAuth2Plugin * OAuth 2.0 authentication plugin. */ class OAuth2PluginPrivate; class OAuth2Plugin: public BasePlugin { Q_OBJECT public: OAuth2Plugin(QObject *parent = 0); ~OAuth2Plugin(); static QStringList mechanisms(); void process(const SignOn::SessionData &inData, const QString &mechanism); void userActionFinished(const SignOn::UiSessionData &data); protected: void serverReply(QNetworkReply *); bool handleNetworkError(QNetworkReply *reply, QNetworkReply::NetworkError err); private: void sendOAuth2AuthRequest(); bool validateInput(const SignOn::SessionData &inData, const QString &mechanism); bool respondWithStoredToken(const QVariantMap &token, const QStringList &scopes); void refreshOAuth2Token(const QString &refreshToken); void sendOAuth2PostRequest(QUrlQuery &postData, GrantType::e grantType); void storeResponse(const OAuth2PluginTokenData &response); QVariantMap parseReply(const QByteArray &contentType, const QByteArray &replyContent); QVariantMap parseJSONReply(const QByteArray &reply); QVariantMap parseTextReply(const QByteArray &reply); void handleOAuth2Error(const QByteArray &reply); QByteArray urlEncode(QString strData); QUrl getAuthUrl(); QUrl getTokenUrl(); OAuth2PluginPrivate *d_ptr; Q_DECLARE_PRIVATE(OAuth2Plugin) }; } //namespace OAuth2PluginNS #endif // SIGNON_PLUGIN_OAUTH2 0707010000001B000081A40000000000000000000000016560A3A500000958000000000000000000000000000000000000004B00000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/oauth2tokendata.h/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef OAUTH2TOKENDATA_H #define OAUTH2TOKENDATA_H #include <QDataStream> #include <QDebug> #include <SignOn/SessionData> class OAuth2PluginTest; namespace OAuth2PluginNS { /*! * Data container to hold values for storing Token. */ class OAuth2TokenData : public SignOn::SessionData { public: friend class ::OAuth2PluginTest; /*! * Declare property Tokens setter and getter * Received tokens are stored in this map */ SIGNON_SESSION_DECLARE_PROPERTY(QVariantMap, Tokens); /*! * Declares the property ProvidedTokens setter and getter. * If this property is set then process() will store the value * of this property and return the appropriate response data. * This should be used only if the signon process is performed * manually, and you wish to store the resulting credentials * into the identity. * * If the flow is OAuth2 then the ProvidedTokens value must * contain values for the following keys: * - AccessToken * - ExpiresIn * - RefreshToken * and clients should use the OAuth2PluginTokenData class. * * If the flow is OAuth1.0a then the ProvidedTokens value * must contain values for the following keys: * - AccessToken * - TokenSecret * and optionally for: * - UserId * - ScreenName * and clients should use the OAuth1PluginTokenData class. */ SIGNON_SESSION_DECLARE_PROPERTY(QVariantMap, ProvidedTokens); }; } // namespace #endif // OAUTH2TOKENDATA_H 0707010000001C000081A40000000000000000000000016560A3A500000F26000000000000000000000000000000000000004400000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/plugin.cpp/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include "common.h" #include "oauth1plugin.h" #include "oauth2plugin.h" #include "plugin.h" #include <QNetworkAccessManager> #include <QNetworkProxy> using namespace SignOn; using namespace OAuth2PluginNS; namespace OAuth2PluginNS { SIGNON_DECL_AUTH_PLUGIN(Plugin) } //namespace OAuth2PluginNS Plugin::Plugin(QObject *parent): AuthPluginInterface(parent), impl(0), m_networkAccessManager(0) { TRACE(); } Plugin::~Plugin() { TRACE(); delete impl; impl = 0; } QString Plugin::type() const { TRACE(); return QString("oauth2"); } QStringList Plugin::mechanisms() const { TRACE(); return OAuth1Plugin::mechanisms() + OAuth2Plugin::mechanisms(); } void Plugin::cancel() { TRACE(); if (impl != 0) impl->cancel(); } void Plugin::process(const SignOn::SessionData &inData, const QString &mechanism) { if (impl != 0) delete impl; if (!m_networkAccessManager) { m_networkAccessManager = new QNetworkAccessManager(this); } if (OAuth1Plugin::mechanisms().contains(mechanism)) { impl = new OAuth1Plugin(this); } else if (OAuth2Plugin::mechanisms().contains(mechanism)) { impl = new OAuth2Plugin(this); } else { emit error(Error(Error::MechanismNotAvailable)); return; } QNetworkProxy networkProxy = QNetworkProxy::applicationProxy(); // Override proxy, if given in the parameters QString proxy = inData.NetworkProxy(); if (!proxy.isEmpty()) { QUrl proxyUrl(proxy); if (!proxyUrl.host().isEmpty()) { networkProxy = QNetworkProxy(QNetworkProxy::HttpProxy, proxyUrl.host(), proxyUrl.port(), proxyUrl.userName(), proxyUrl.password()); TRACE() << proxyUrl.host() << ":" << proxyUrl.port(); } } m_networkAccessManager->setProxy(networkProxy); impl->setNetworkAccessManager(m_networkAccessManager); // Forward the signals from the implementation connect(impl, &BasePlugin::result, this, &Plugin::result); connect(impl, &BasePlugin::store, this, &Plugin::store); connect(impl, &BasePlugin::error, this, &Plugin::error); connect(impl, &BasePlugin::userActionRequired, this, &Plugin::userActionRequired); connect(impl, &BasePlugin::refreshed, this, &Plugin::refreshed); connect(impl, &BasePlugin::statusChanged, this, &Plugin::statusChanged); impl->process(inData, mechanism); } void Plugin::userActionFinished(const SignOn::UiSessionData &data) { TRACE(); if (impl != 0) impl->userActionFinished(data); } void Plugin::refresh(const SignOn::UiSessionData &data) { TRACE(); if (impl != 0) impl->refresh(data); } #ifdef SIGNON_PLUGINS_HAS_AUTHPLUGINIF_2 AuthPluginInterface *PluginInterface::createAuthPlugin(QObject *parent) { return new Plugin(parent); } #endif 0707010000001D000081A40000000000000000000000016560A3A500000896000000000000000000000000000000000000004200000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/plugin.h/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef SIGNON_PLUGIN_OAUTH2_MAIN #define SIGNON_PLUGIN_OAUTH2_MAIN #include <QtCore> #include <SignOn/AuthPluginInterface> #include <SignOn/SessionData> #include <SignOn/Error> class OAuth2PluginTest; class QNetworkAccessManager; namespace OAuth2PluginNS { class BasePlugin; /*! * @class Plugin * OAuth authentication plugin. */ class PluginPrivate; class Plugin: public AuthPluginInterface { Q_OBJECT Q_INTERFACES(AuthPluginInterface); friend class ::OAuth2PluginTest; public: Plugin(QObject *parent = 0); ~Plugin(); public Q_SLOTS: QString type() const; QStringList mechanisms() const; void cancel(); void process(const SignOn::SessionData &inData, const QString &mechanism = 0); void userActionFinished(const SignOn::UiSessionData &data); void refresh(const SignOn::UiSessionData &data); private: BasePlugin *impl; QNetworkAccessManager *m_networkAccessManager; }; #ifdef SIGNON_PLUGINS_HAS_AUTHPLUGINIF_2 class PluginInterface: public QObject, AuthPluginInterface2 { Q_OBJECT Q_INTERFACES(AuthPluginInterface2) Q_PLUGIN_METADATA(IID "com.nokia.SingleSignOn.PluginInterface/2") public: AuthPluginInterface *createAuthPlugin(QObject *parent = 0) Q_DECL_OVERRIDE; }; #endif } //namespace OAuth2PluginNS #endif // SIGNON_PLUGIN_OAUTH2_MAIN 0707010000001E000081A40000000000000000000000016560A3A5000000DF000000000000000000000000000000000000005000000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/signon-oauth2plugin.pcprefix=/usr exec_prefix=${prefix} libdir=${prefix}/lib/ includedir=${prefix}/include Name: signon-oauth2plugin Description: Signon OAuth 2.0 plugin Version: 0.0.1 Requires: signon-plugins Libs.private: -L/usr/lib -lQtCore 0707010000001F000081A40000000000000000000000016560A3A500000366000000000000000000000000000000000000004100000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/src/src.proinclude( ../common-project-config.pri ) include( ../common-vars.pri ) TEMPLATE = lib TARGET = oauth2plugin DESTDIR = lib/signon QT += core \ network QT -= gui CONFIG += plugin \ warn_on \ link_pkgconfig public_headers += oauth2data.h oauth1data.h private_headers = \ base-plugin.h \ common.h \ oauth1plugin.h \ oauth2plugin.h \ oauth2tokendata.h \ plugin.h HEADERS = $$public_headers \ $$private_headers SOURCES += \ base-plugin.cpp \ oauth1plugin.cpp \ oauth2plugin.cpp \ plugin.cpp isEmpty(SIGNON_PLUGINS_INCLUDEPATH) { PKGCONFIG += signon-plugins } else { INCLUDEPATH += $${SIGNON_PLUGINS_INCLUDEPATH} LIBS += $${SIGNON_PLUGINS_LIBS} QMAKE_LIBDIR += $${SIGNON_PLUGINS_LIBDIR} } headers.files = $$public_headers pkgconfig.files = signon-oauth2plugin.pc include( ../common-installs-config.pri ) 07070100000020000041ED0000000000000000000000026560A3A500000000000000000000000000000000000000000000003B00000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/tests07070100000021000081A40000000000000000000000016560A3A500012BFD000000000000000000000000000000000000005000000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/tests/oauth2plugintest.cpp/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #include <QJsonDocument> #include <QJsonObject> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QPointer> #include <QRegularExpression> #include <QScopedPointer> #include <QSignalSpy> #include <QTimer> #include <QtTest/QtTest> #include "plugin.h" #include "oauth1data.h" #include "oauth2data.h" #include "oauth2tokendata.h" #include "oauth2plugintest.h" using namespace OAuth2PluginNS; using namespace SignOn; namespace QTest { template<> char *toString(const QVariantMap &map) { QJsonDocument doc(QJsonObject::fromVariantMap(map)); return qstrdup(doc.toJson(QJsonDocument::Compact).data()); } } // QTest namespace static QString parseState(const QSignalSpy &userActionRequired) { UiSessionData data = userActionRequired.at(0).at(0).value<UiSessionData>(); QUrlQuery query(data.OpenUrl()); return query.queryItemValue("state"); } static bool mapIsSubset(const QVariantMap &set, const QVariantMap &test) { QMapIterator<QString, QVariant> it(set); while (it.hasNext()) { it.next(); if (QMetaType::Type(it.value().type()) == QMetaType::QVariantMap) { if (!mapIsSubset(it.value().toMap(), test.value(it.key()).toMap())) { return false; } } else if (test.value(it.key()) != it.value()) { qDebug() << "Maps differ: expected" << it.value() << "but found" << test.value(it.key()); return false; } } return true; } static QVariantMap parseAuthorizationHeader(const QStringList &parts, bool *ok) { QVariantMap map; *ok = true; Q_FOREACH(const QString &part, parts) { int equalPos = part.indexOf("="); if (equalPos < 0) { qDebug() << "Invalid authorization header" << part; *ok = false; return map; } QString key = part.left(equalPos); QString escapedValue = part.mid(equalPos + 1); if (!escapedValue.startsWith('"') || !escapedValue.endsWith('"')) { qDebug() << "Authorization header string not quoted!" << part; *ok = false; return map; } QString value = escapedValue.mid(1, escapedValue.length() - 2); map.insert(key, value); } return map; } class TestNetworkReply: public QNetworkReply { Q_OBJECT public: TestNetworkReply(QObject *parent = 0): QNetworkReply(parent), m_offset(0) {} void setError(NetworkError errorCode, const QString &errorString, int delay = -1) { QNetworkReply::setError(errorCode, errorString); if (delay > 0) { QTimer::singleShot(delay, this, SLOT(fail())); } } void setRawHeader(const QByteArray &headerName, const QByteArray &value) { QNetworkReply::setRawHeader(headerName, value); } void setContentType(const QString &contentType) { setRawHeader("Content-Type", contentType.toUtf8()); } void setStatusCode(int statusCode) { setAttribute(QNetworkRequest::HttpStatusCodeAttribute, statusCode); } void setContent(const QByteArray &content) { m_content = content; m_offset = 0; open(ReadOnly | Unbuffered); setHeader(QNetworkRequest::ContentLengthHeader, QVariant(content.size())); QTimer::singleShot(0, this, &TestNetworkReply::readyRead); QTimer::singleShot(10, this, &TestNetworkReply::finish); } public Q_SLOTS: void finish() { setFinished(true); Q_EMIT finished(); } void fail() { #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) Q_EMIT error(error()); #else Q_EMIT errorOccurred(error()); #endif } protected: void abort() Q_DECL_OVERRIDE {} qint64 bytesAvailable() const Q_DECL_OVERRIDE { return m_content.size() - m_offset + QIODevice::bytesAvailable(); } bool isSequential() const Q_DECL_OVERRIDE { return true; } qint64 readData(char *data, qint64 maxSize) Q_DECL_OVERRIDE { if (m_offset >= m_content.size()) return -1; qint64 number = qMin(maxSize, m_content.size() - m_offset); memcpy(data, m_content.constData() + m_offset, number); m_offset += number; return number; } private: QByteArray m_content; qint64 m_offset; }; class TestNetworkAccessManager: public QNetworkAccessManager { Q_OBJECT public: TestNetworkAccessManager(): QNetworkAccessManager() {} void setNextReply(TestNetworkReply *reply) { m_nextReply = reply; } protected: QNetworkReply *createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData = 0) Q_DECL_OVERRIDE { Q_UNUSED(op); m_lastRequest = request; m_lastRequestData = outgoingData->readAll(); return m_nextReply; } public: QPointer<TestNetworkReply> m_nextReply; QNetworkRequest m_lastRequest; QByteArray m_lastRequestData; }; void OAuth2PluginTest::initTestCase() { qRegisterMetaType<SignOn::SessionData>(); qRegisterMetaType<SignOn::UiSessionData>(); qRegisterMetaType<SignOn::Error>(); } void OAuth2PluginTest::cleanupTestCase() { } //prepare each test by creating new plugin void OAuth2PluginTest::init() { m_testPlugin = new Plugin(); } //finnish each test by deleting plugin void OAuth2PluginTest::cleanup() { delete m_testPlugin; m_testPlugin=NULL; } // TEST CASES void OAuth2PluginTest::testPlugin() { QVERIFY(m_testPlugin); } void OAuth2PluginTest::testPluginType() { QCOMPARE(m_testPlugin->type(), QString("oauth2")); } void OAuth2PluginTest::testPluginMechanisms() { QStringList mechs = m_testPlugin->mechanisms(); QVERIFY(!mechs.isEmpty()); QVERIFY(mechs.contains(QString("user_agent"))); QVERIFY(mechs.contains(QString("web_server"))); } void OAuth2PluginTest::testPluginCancel() { //does nothing as no active connections m_testPlugin->cancel(); //then real cancel QSignalSpy pluginError(m_testPlugin, &Plugin::error); OAuth2PluginData userAgentData; userAgentData.setHost("https://localhost"); userAgentData.setAuthPath("access_token"); userAgentData.setClientId("104660106251471"); userAgentData.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); userAgentData.setRedirectUri("http://localhost/connect/login_success.html"); m_testPlugin->process(userAgentData, QString("user_agent")); m_testPlugin->cancel(); QTRY_COMPARE(pluginError.count(), 1); Error error = pluginError.at(0).at(0).value<Error>(); QCOMPARE(error.type(), int(Error::SessionCanceled)); } void OAuth2PluginTest::testPluginProcess_data() { QTest::addColumn<QString>("mechanism"); QTest::addColumn<QVariantMap>("sessionData"); QTest::addColumn<int>("errorCode"); QTest::addColumn<bool>("uiExpected"); QTest::addColumn<QVariantMap>("response"); QTest::addColumn<QVariantMap>("stored"); OAuth2PluginData userAgentData; userAgentData.setHost("https://localhost"); userAgentData.setTokenPath("access_token"); userAgentData.setClientId("104660106251471"); userAgentData.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); userAgentData.setRedirectUri("http://localhost/connect/login_success.html"); QTest::newRow("invalid mechanism") << "ANONYMOUS" << userAgentData.toMap() << int(Error::MechanismNotAvailable) << false << QVariantMap() << QVariantMap(); QTest::newRow("without params, user_agent") << "user_agent" << userAgentData.toMap() << int(Error::MissingData) << false << QVariantMap() << QVariantMap(); OAuth2PluginData webServerData; webServerData.setHost("https://localhost"); webServerData.setAuthPath("authorize"); webServerData.setClientId("104660106251471"); webServerData.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); webServerData.setRedirectUri("http://localhost/connect/login_success.html"); webServerData.setScope(QStringList() << "scope1" << "scope2"); QTest::newRow("without params, web_server") << "web_server" << webServerData.toMap() << int(Error::MissingData) << false << QVariantMap() << QVariantMap(); userAgentData.setAuthPath("authorize"); QTest::newRow("ui-request, user_agent") << "user_agent" << userAgentData.toMap() << -1 << true << QVariantMap() << QVariantMap(); webServerData.setTokenPath("token"); QTest::newRow("ui-request, web_server") << "web_server" << webServerData.toMap() << -1 << true << QVariantMap() << QVariantMap(); QVariantMap tokens; QVariantMap token; token.insert("Token", QLatin1String("tokenfromtest")); token.insert("Token2", QLatin1String("token2fromtest")); token.insert("timestamp", QDateTime::currentDateTime().toSecsSinceEpoch()); token.insert("Expiry", 10000); tokens.insert(QLatin1String("invalidid"), QVariant::fromValue(token)); webServerData.m_data.insert(QLatin1String("Tokens"), tokens); QTest::newRow("stored response, without params") << "web_server" << webServerData.toMap() << -1 << true << QVariantMap() << QVariantMap(); tokens.insert(webServerData.ClientId(), QVariant::fromValue(token)); webServerData.m_data.insert(QLatin1String("Tokens"), tokens); QTest::newRow("stored response, missing cached scopes") << "web_server" << webServerData.toMap() << -1 << true << QVariantMap() << QVariantMap(); token.insert("Scopes", QStringList("scope2")); tokens.insert(webServerData.ClientId(), QVariant::fromValue(token)); webServerData.m_data.insert(QLatin1String("Tokens"), tokens); QTest::newRow("stored response, incomplete cached scopes") << "web_server" << webServerData.toMap() << -1 << true << QVariantMap() << QVariantMap(); token.insert("Scopes", QStringList() << "scope1" << "scope3" << "scope2"); tokens.insert(webServerData.ClientId(), QVariant::fromValue(token)); webServerData.m_data.insert(QLatin1String("Tokens"), tokens); QVariantMap response; response.insert("AccessToken", QLatin1String("tokenfromtest")); response.insert("ExpiresIn", int(10000)); QTest::newRow("stored response, sufficient cached scopes") << "web_server" << webServerData.toMap() << -1 << false << response << QVariantMap(); token.insert("id_token", QLatin1String("idtokenfromtest")); tokens.insert(webServerData.ClientId(), QVariant::fromValue(token)); webServerData.m_data.insert(QLatin1String("Tokens"), tokens); response.insert("IdToken", QLatin1String("idtokenfromtest")); QTest::newRow("stored response including id token, sufficient cached scopes") << "web_server" << webServerData.toMap() << -1 << false << response << QVariantMap(); webServerData.setForceTokenRefresh(true); QTest::newRow("force token refresh, without refresh token") << "web_server" << webServerData.toMap() << -1 << true << QVariantMap() << QVariantMap(); /* test the ProvidedTokens semantics */ OAuth2PluginData providedTokensWebServerData; providedTokensWebServerData.setHost("https://localhost"); providedTokensWebServerData.setAuthPath("authorize"); providedTokensWebServerData.setClientId("104660106251471"); providedTokensWebServerData.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); providedTokensWebServerData.setRedirectUri("http://localhost/connect/login_success.html"); providedTokensWebServerData.setTokenPath("token"); providedTokensWebServerData.setScope(QStringList() << "scope1" << "scope3" << "scope2"); QVariantMap providedTokens; providedTokens.insert("AccessToken", "providedtokenfromtest"); providedTokens.insert("RefreshToken", "providedrefreshfromtest"); providedTokens.insert("ExpiresIn", 12345); providedTokens.insert("ExtraFields", QVariantMap()); /* try providing tokens to be stored */ providedTokensWebServerData.m_data.insert("ProvidedTokens", providedTokens); QVariantMap storedTokensForKey; storedTokensForKey.insert("Token", providedTokens.value("AccessToken")); storedTokensForKey.insert("refresh_token", providedTokens.value("RefreshToken")); storedTokensForKey.insert("ExtraFields", providedTokens.value("ExtraFields")); QVariantMap storedTokens; storedTokens.insert(providedTokensWebServerData.ClientId(), storedTokensForKey); QVariantMap stored; stored.insert("Tokens", storedTokens); QTest::newRow("provided tokens") << "web_server" << providedTokensWebServerData.toMap() << -1 << false << providedTokens << stored; /* try providing tokens to be stored and include an openid token */ providedTokens.insert("IdToken", "providedidtokenfromtest"); providedTokensWebServerData.m_data.insert("ProvidedTokens", providedTokens); storedTokensForKey.insert("id_token", providedTokens.value("IdToken")); storedTokens.insert(providedTokensWebServerData.ClientId(), storedTokensForKey); stored.insert("Tokens", storedTokens); QTest::newRow("provided tokens with openid token") << "web_server" << providedTokensWebServerData.toMap() << -1 << false << providedTokens << stored; } void OAuth2PluginTest::testPluginProcess() { QFETCH(QString, mechanism); QFETCH(QVariantMap, sessionData); QFETCH(int, errorCode); QFETCH(bool, uiExpected); QFETCH(QVariantMap, response); QFETCH(QVariantMap, stored); QSignalSpy result(m_testPlugin, &Plugin::result); QSignalSpy error(m_testPlugin, &Plugin::error); QSignalSpy userActionRequired(m_testPlugin, &Plugin::userActionRequired); QSignalSpy store(m_testPlugin, &Plugin::store); m_testPlugin->process(sessionData, mechanism); if (errorCode < 0) { QCOMPARE(error.count(), 0); QTRY_COMPARE(userActionRequired.count(), uiExpected ? 1 : 0); if (!response.isEmpty()) { QCOMPARE(result.count(), 1); QVariantMap resp = result.at(0).at(0).value<SessionData>().toMap(); /* Round the expiration time, because some seconds might have passed */ if (resp.contains("ExpiresIn")) { resp["ExpiresIn"] = qRound(resp["ExpiresIn"].toInt() / 10.0) * 10; response["ExpiresIn"] = qRound(response["ExpiresIn"].toInt() / 10.0) * 10; } QCOMPARE(resp, response); } if (!stored.isEmpty()) { QCOMPARE(store.count(), 1); QVariantMap storedData = store.at(0).at(0).value<SessionData>().toMap(); QVERIFY(mapIsSubset(stored, storedData)); } } else { QTRY_COMPARE(error.count(), 1); Error err = error.at(0).at(0).value<Error>(); QCOMPARE(err.type(), errorCode); } } void OAuth2PluginTest::testPluginHmacSha1Process_data() { QTest::addColumn<QString>("mechanism"); QTest::addColumn<QVariantMap>("sessionData"); QTest::addColumn<int>("replyStatusCode"); QTest::addColumn<QString>("replyContentType"); QTest::addColumn<QString>("replyContents"); QTest::addColumn<int>("errorCode"); QTest::addColumn<bool>("uiExpected"); QTest::addColumn<QVariantMap>("response"); QTest::addColumn<QVariantMap>("stored"); OAuth1PluginData hmacSha1Data; hmacSha1Data.setRequestEndpoint("https://localhost/oauth/request_token"); hmacSha1Data.setTokenEndpoint("https://localhost/oauth/access_token"); hmacSha1Data.setAuthorizationEndpoint("https://localhost/oauth/authorize"); hmacSha1Data.setCallback("https://localhost/connect/login_success.html"); hmacSha1Data.setConsumerKey("104660106251471"); hmacSha1Data.setConsumerSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); hmacSha1Data.setRealm("MyHost"); QTest::newRow("invalid mechanism") << "ANONYMOUS" << hmacSha1Data.toMap() << int(200) << "" << "" << int(Error::MechanismNotAvailable) << false << QVariantMap() << QVariantMap(); // Try without params hmacSha1Data.setAuthorizationEndpoint(QString()); QTest::newRow("without params, HMAC-SHA1") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(200) << "" << "" << int(Error::MissingData) << false << QVariantMap() << QVariantMap(); // Check for signon UI request for HMAC-SHA1 hmacSha1Data.setAuthorizationEndpoint("https://localhost/oauth/authorize"); QTest::newRow("ui-request, HMAC-SHA1") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(200) << "text/plain" << "oauth_token=HiThere&oauth_token_secret=BigSecret" << -1 << true << QVariantMap() << QVariantMap(); QTest::newRow("ui-request, PLAINTEXT") << "PLAINTEXT" << hmacSha1Data.toMap() << int(200) << "text/plain" << "oauth_token=HiThere&oauth_token_secret=BigSecret" << -1 << true << QVariantMap() << QVariantMap(); QTest::newRow("ui-request, User-Agent") << "PLAINTEXT" << QVariantMap { { "RequestEndpoint", "https://localhost/oauth/request_token" }, { "TokenEndpoint", "https://localhost/oauth/access_token" }, { "AuthorizationEndpoint", "https://localhost/oauth/authorize" }, { "Callback", "https://localhost/connect/login_success.html" }, { "ConsumerKey", "104660106251471" }, { "ConsumerSecret", "fa28f40b5a1f8c1d5628963d880636fbkjkjkj" }, { "UserAgent", "PhotoTeleport/1.0" }, } << int(200) << "text/plain" << "oauth_token=HiThere&oauth_token_secret=BigSecret" << -1 << true << QVariantMap() << QVariantMap(); /* Now store some tokens and test the responses */ hmacSha1Data.m_data.insert("UiPolicy", NoUserInteractionPolicy); QVariantMap tokens; // ConsumerKey to Token map QVariantMap token; token.insert("oauth_token", QLatin1String("hmactokenfromtest")); token.insert("oauth_token_secret", QLatin1String("hmacsecretfromtest")); token.insert("timestamp", QDateTime::currentDateTime().toSecsSinceEpoch()); token.insert("Expiry", (uint)50000); tokens.insert(QLatin1String("invalidid"), QVariant::fromValue(token)); hmacSha1Data.m_data.insert(QLatin1String("Tokens"), tokens); // Try without cached token for our ConsumerKey QTest::newRow("cached tokens, no ConsumerKey") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(200) << "text/plain" << "oauth_token=HiThere&oauth_token_secret=BigSecret" << -1 << true << QVariantMap() << QVariantMap(); // Ensure that the cached token is returned as required tokens.insert(hmacSha1Data.ConsumerKey(), QVariant::fromValue(token)); hmacSha1Data.m_data.insert(QLatin1String("Tokens"), tokens); QVariantMap response; response.insert("AccessToken", QLatin1String("hmactokenfromtest")); QTest::newRow("cached tokens, with ConsumerKey") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(200) << "" << "" << -1 << false << response << QVariantMap(); hmacSha1Data.m_data.insert("UiPolicy", RequestPasswordPolicy); QTest::newRow("cached tokens, request password policy") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(200) << "text/plain" << "oauth_token=HiThere&oauth_token_secret=BigSecret" << -1 << true << QVariantMap() << QVariantMap(); hmacSha1Data.m_data.remove("UiPolicy"); hmacSha1Data.setForceTokenRefresh(true); QTest::newRow("cached tokens, force refresh") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(200) << "text/plain" << "oauth_token=HiThere&oauth_token_secret=BigSecret" << -1 << true << QVariantMap() << QVariantMap(); hmacSha1Data.setForceTokenRefresh(false); token.insert("timestamp", QDateTime::currentDateTime().toSecsSinceEpoch() - 50000); token.insert("Expiry", (uint)100); tokens.insert(hmacSha1Data.ConsumerKey(), QVariant::fromValue(token)); hmacSha1Data.m_data.insert(QLatin1String("Tokens"), tokens); QTest::newRow("cached tokens, expired") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(200) << "text/plain" << "oauth_token=HiThere&oauth_token_secret=BigSecret" << -1 << true << QVariantMap() << QVariantMap(); /* test the ProvidedTokens semantics */ OAuth1PluginData providedTokensHmacSha1Data; providedTokensHmacSha1Data.setRequestEndpoint("https://localhost/oauth/request_token"); providedTokensHmacSha1Data.setTokenEndpoint("https://localhost/oauth/access_token"); providedTokensHmacSha1Data.setAuthorizationEndpoint("https://localhost/oauth/authorize"); providedTokensHmacSha1Data.setCallback("https://localhost/connect/login_success.html"); providedTokensHmacSha1Data.setConsumerKey("104660106251471"); providedTokensHmacSha1Data.setConsumerSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); QVariantMap providedTokens; providedTokens.insert("AccessToken", "providedhmactokenfromtest"); providedTokens.insert("TokenSecret", "providedhmacsecretfromtest"); providedTokens.insert("ScreenName", "providedhmacscreennamefromtest"); providedTokens.insert("UserId", "providedUserId"); // try providing tokens to be stored providedTokensHmacSha1Data.m_data.insert("ProvidedTokens", providedTokens); QVariantMap storedTokensForKey; storedTokensForKey.insert("oauth_token", providedTokens.value("AccessToken")); storedTokensForKey.insert("oauth_token_secret", providedTokens.value("TokenSecret")); QVariantMap storedTokens; storedTokens.insert(providedTokensHmacSha1Data.ConsumerKey(), storedTokensForKey); QVariantMap stored; stored.insert("Tokens", storedTokens); QTest::newRow("provided tokens") << "HMAC-SHA1" << providedTokensHmacSha1Data.toMap() << int(200) << "" << "" << -1 << false << providedTokens << stored; QTest::newRow("http error 401") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(401) << "text/plain" << "oauth_token=HiThere&oauth_token_secret=BigSecret" << int(Error::OperationFailed) << false << QVariantMap() << QVariantMap(); QTest::newRow("no content returned") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(200) << "" << "" << int(Error::OperationFailed) << false << QVariantMap() << QVariantMap(); QTest::newRow("no token returned") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(200) << "text/plain" << "oauth_token=HiThere" << int(Error::OperationFailed) << false << QVariantMap() << QVariantMap(); /* Test handling of oauth_problem; this is a non standard extension: * http://wiki.oauth.net/w/page/12238543/ProblemReporting * https://developer.yahoo.com/oauth/guide/oauth-errors.html */ QTest::newRow("problem user_refused") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(400) << "text/plain" << "oauth_problem=user_refused" << int(Error::PermissionDenied) << false << QVariantMap() << QVariantMap(); QTest::newRow("problem permission_denied") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(400) << "text/plain" << "oauth_problem=permission_denied" << int(Error::PermissionDenied) << false << QVariantMap() << QVariantMap(); QTest::newRow("problem signature_invalid") << "HMAC-SHA1" << hmacSha1Data.toMap() << int(400) << "text/plain" << "oauth_problem=signature_invalid" << int(Error::OperationFailed) << false << QVariantMap() << QVariantMap(); } void OAuth2PluginTest::testPluginHmacSha1Process() { QFETCH(QString, mechanism); QFETCH(QVariantMap, sessionData); QFETCH(int, replyStatusCode); QFETCH(QString, replyContentType); QFETCH(QString, replyContents); QFETCH(int, errorCode); QFETCH(bool, uiExpected); QFETCH(QVariantMap, response); QFETCH(QVariantMap, stored); QSignalSpy result(m_testPlugin, &Plugin::result); QSignalSpy error(m_testPlugin, &Plugin::error); QSignalSpy userActionRequired(m_testPlugin, &Plugin::userActionRequired); QSignalSpy store(m_testPlugin, &Plugin::store); TestNetworkAccessManager *nam = new TestNetworkAccessManager; m_testPlugin->m_networkAccessManager = nam; TestNetworkReply *reply = new TestNetworkReply(this); reply->setStatusCode(replyStatusCode); if (!replyContentType.isEmpty()) { reply->setContentType(replyContentType); } reply->setContent(replyContents.toUtf8()); nam->setNextReply(reply); m_testPlugin->process(sessionData, mechanism); QTRY_COMPARE(result.count(), response.isEmpty() ? 0 : 1); /* In the test data sometimes we don't specify the expected stored data, * but this doesn't mean that store() shouldn't be emitted. */ if (!stored.isEmpty()) { QTRY_COMPARE(store.count(), 1); } QTRY_COMPARE(userActionRequired.count(), uiExpected ? 1 : 0); QTRY_COMPARE(error.count(), errorCode < 0 ? 0 : 1); /* Check the user agent */ const QNetworkRequest &req = nam->m_lastRequest; QVariant expectedUserAgent = sessionData.value("UserAgent"); QCOMPARE(req.header(QNetworkRequest::UserAgentHeader), expectedUserAgent); if (errorCode < 0) { QCOMPARE(error.count(), 0); QVariantMap resp = result.count() > 0 ? result.at(0).at(0).value<SessionData>().toMap() : QVariantMap(); QVariantMap storedData = store.count() > 0 ? store.at(0).at(0).value<SessionData>().toMap() : QVariantMap(); /* We don't check the network request if a response was received, * because a response can only be received if a cached token was * found -- and that doesn't cause any network request to be made. */ if (resp.isEmpty()) { QCOMPARE(nam->m_lastRequest.url(), sessionData.value("RequestEndpoint").toUrl()); QVERIFY(nam->m_lastRequestData.isEmpty()); /* Check the authorization header */ QString authorizationHeader = QString::fromUtf8(nam->m_lastRequest.rawHeader("Authorization")); QStringList authorizationHeaderParts = authorizationHeader.split(QRegularExpression(",?\\s+")); QCOMPARE(authorizationHeaderParts[0], QString("OAuth")); /* The rest of the header should be a mapping, let's parse it */ bool ok = true; QVariantMap authMap = parseAuthorizationHeader(authorizationHeaderParts.mid(1), &ok); QVERIFY(ok); QCOMPARE(authMap.value("oauth_signature_method").toString(), mechanism); } QVERIFY(mapIsSubset(response, resp)); QVERIFY(mapIsSubset(stored, storedData)); } else { Error err = error.at(0).at(0).value<Error>(); QCOMPARE(err.type(), errorCode); } } void OAuth2PluginTest::testPluginUseragentUserActionFinished() { SignOn::UiSessionData info; OAuth2PluginData data; data.setHost("https://localhost"); data.setAuthPath("authorize"); data.setTokenPath("access_token"); data.setClientId("104660106251471"); data.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); data.setRedirectUri("http://localhost/connect/login_success.html"); QStringList scopes = QStringList() << "scope1" << "scope2"; data.setScope(scopes); QSignalSpy resultSpy(m_testPlugin, &Plugin::result); QSignalSpy error(m_testPlugin, &Plugin::error); QSignalSpy userActionRequired(m_testPlugin, &Plugin::userActionRequired); QSignalSpy store(m_testPlugin, &Plugin::store); m_testPlugin->process(data, QString("user_agent")); QTRY_COMPARE(userActionRequired.count(), 1); QString state = parseState(userActionRequired); //empty data m_testPlugin->userActionFinished(info); QTRY_COMPARE(error.count(), 1); QCOMPARE(error.at(0).at(0).value<Error>().type(), int(Error::NotAuthorized)); error.clear(); //invalid data info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html#access_token=&expires_in=4776")); m_testPlugin->userActionFinished(info); QTRY_COMPARE(error.count(), 1); QCOMPARE(error.at(0).at(0).value<Error>().type(), int(Error::NotAuthorized)); error.clear(); //Invalid data info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html")); m_testPlugin->userActionFinished(info); QTRY_COMPARE(error.count(), 1); QCOMPARE(error.at(0).at(0).value<Error>().type(), int(Error::NotAuthorized)); error.clear(); // Wrong state info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html" "#access_token=123&expires_in=456&state=%1"). arg(state + "Boo")); m_testPlugin->userActionFinished(info); QTRY_COMPARE(error.count(), 1); QCOMPARE(error.at(0).at(0).value<Error>().type(), int(Error::NotAuthorized)); error.clear(); //valid data info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html#access_token=testtoken.&expires_in=4776&state=%1"). arg(state)); m_testPlugin->userActionFinished(info); QTRY_COMPARE(resultSpy.count(), 1); SessionData response = resultSpy.at(0).at(0).value<SessionData>(); OAuth2PluginTokenData result = response.data<OAuth2PluginTokenData>(); QCOMPARE(result.AccessToken(), QString("testtoken.")); QCOMPARE(result.ExpiresIn(), 4776); QCOMPARE(result.Scope(), QStringList() << "scope1" << "scope2"); resultSpy.clear(); QTRY_COMPARE(store.count(), 1); SessionData storedData = store.at(0).at(0).value<SessionData>(); QVariantMap storedTokenData = storedData.data<OAuth2TokenData>().Tokens(); QVariantMap storedClientData = storedTokenData.value(data.ClientId()).toMap(); QVERIFY(!storedClientData.isEmpty()); QCOMPARE(storedClientData["Scopes"].toStringList(), scopes); store.clear(); //valid data with openid token info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html#access_token=testtoken.&id_token=idtesttoken&expires_in=4776&state=%1"). arg(state)); m_testPlugin->userActionFinished(info); QTRY_COMPARE(resultSpy.count(), 1); response = resultSpy.at(0).at(0).value<SessionData>(); result = response.data<OAuth2PluginTokenData>(); QCOMPARE(result.AccessToken(), QString("testtoken.")); QCOMPARE(result.IdToken(), QString("idtesttoken")); QCOMPARE(result.ExpiresIn(), 4776); QCOMPARE(result.Scope(), QStringList() << "scope1" << "scope2"); resultSpy.clear(); QTRY_COMPARE(store.count(), 1); storedData = store.at(0).at(0).value<SessionData>(); storedTokenData = storedData.data<OAuth2TokenData>().Tokens(); storedClientData = storedTokenData.value(data.ClientId()).toMap(); QVERIFY(!storedClientData.isEmpty()); QCOMPARE(storedClientData["Scopes"].toStringList(), scopes); store.clear(); //valid data with openid token, and refresh token info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html#access_token=testtoken.&id_token=idtesttoken&refresh_token=testrefreshtoken&expires_in=4776&state=%1"). arg(state)); m_testPlugin->userActionFinished(info); QTRY_COMPARE(resultSpy.count(), 1); response = resultSpy.at(0).at(0).value<SessionData>(); result = response.data<OAuth2PluginTokenData>(); QCOMPARE(result.AccessToken(), QString("testtoken.")); QCOMPARE(result.IdToken(), QString("idtesttoken")); QCOMPARE(result.RefreshToken(), QString("testrefreshtoken")); QCOMPARE(result.ExpiresIn(), 4776); QCOMPARE(result.Scope(), QStringList() << "scope1" << "scope2"); resultSpy.clear(); QTRY_COMPARE(store.count(), 1); storedData = store.at(0).at(0).value<SessionData>(); storedTokenData = storedData.data<OAuth2TokenData>().Tokens(); storedClientData = storedTokenData.value(data.ClientId()).toMap(); QVERIFY(!storedClientData.isEmpty()); QCOMPARE(storedClientData["Scopes"].toStringList(), scopes); store.clear(); //valid data, got scopes info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html#access_token=testtoken.&expires_in=4776&state=%1&scope=scope2"). arg(state)); m_testPlugin->userActionFinished(info); QTRY_COMPARE(resultSpy.count(), 1); response = resultSpy.at(0).at(0).value<SessionData>(); result = response.data<OAuth2PluginTokenData>(); QCOMPARE(result.AccessToken(), QString("testtoken.")); QCOMPARE(result.ExpiresIn(), 4776); QCOMPARE(result.Scope(), QStringList() << "scope2"); resultSpy.clear(); store.clear(); //valid data, with extra info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html#" "access_token=testtoken.&expires_in=4776&" "state=%1&scope=scope2&user_id=987"). arg(state)); m_testPlugin->userActionFinished(info); QTRY_COMPARE(resultSpy.count(), 1); response = resultSpy.at(0).at(0).value<SessionData>(); result = response.data<OAuth2PluginTokenData>(); QCOMPARE(result.AccessToken(), QString("testtoken.")); QCOMPARE(result.ExpiresIn(), 4776); QCOMPARE(result.Scope(), QStringList() << "scope2"); QVariantMap expectedExtraData { { "user_id", "987" }, }; QCOMPARE(result.ExtraFields(), expectedExtraData); resultSpy.clear(); store.clear(); //valid data info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html" "#state=%1&access_token=testtoken."). arg(state)); m_testPlugin->userActionFinished(info); QTRY_COMPARE(resultSpy.count(), 1); response = resultSpy.at(0).at(0).value<SessionData>(); result = response.data<OAuth2PluginTokenData>(); QCOMPARE(result.AccessToken(), QString("testtoken.")); QCOMPARE(result.ExpiresIn(), 0); resultSpy.clear(); /* Check that the expiration time has not been stored, since the expiration * time was not given (https://bugs.launchpad.net/bugs/1316021) */ QTRY_COMPARE(store.count(), 1); storedData = store.at(0).at(0).value<SessionData>(); storedTokenData = storedData.data<OAuth2TokenData>().Tokens(); storedClientData = storedTokenData.value(data.ClientId()).toMap(); QVERIFY(!storedClientData.isEmpty()); QCOMPARE(storedClientData["Token"].toString(), QString("testtoken.")); QVERIFY(!storedClientData.contains("Expiry")); store.clear(); //Permission denied info.setUrlResponse(QString("http://www.facebook.com/connect/login_success.html?error=user_denied")); m_testPlugin->userActionFinished(info); QTRY_COMPARE(error.count(), 1); QCOMPARE(error.at(0).at(0).value<Error>().type(), int(Error::NotAuthorized)); error.clear(); } void OAuth2PluginTest::testPluginWebserverUserActionFinished_data() { QTest::addColumn<QString>("urlResponse"); QTest::addColumn<int>("errorCode"); QTest::addColumn<QString>("postUrl"); QTest::addColumn<QString>("postContents"); QTest::addColumn<bool>("disableStateParameter"); QTest::addColumn<int>("replyStatusCode"); QTest::addColumn<QString>("replyContentType"); QTest::addColumn<QString>("replyContents"); QTest::addColumn<QVariantMap>("response"); QVariantMap response; QTest::newRow("empty data") << "" << int(Error::NotAuthorized) << "" << "" << false << 0 << "" << "" << QVariantMap(); QTest::newRow("no query data") << "http://localhost/resp.html" << int(Error::NotAuthorized) << "" << "" << false << 0 << "" << "" << QVariantMap(); QTest::newRow("permission denied") << "http://localhost/resp.html?error=user_denied&$state" << int(Error::NotAuthorized) << "" << "" << false << 0 << "" << "" << QVariantMap(); QTest::newRow("invalid data") << "http://localhost/resp.html?sdsdsds=access.grant." << int(Error::NotAuthorized) << "" << "" << false << 0 << "" << "" << QVariantMap(); QTest::newRow("reply code, http error 401") << "http://localhost/resp.html?code=c0d3&$state" << int(Error::OperationFailed) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(401) << "application/json" << "something else" << QVariantMap(); QTest::newRow("reply code, empty reply") << "http://localhost/resp.html?code=c0d3&$state" << int(Error::NotAuthorized) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(200) << "application/json" << "something else" << QVariantMap(); QTest::newRow("reply code, no access token") << "http://localhost/resp.html?code=c0d3&$state" << int(Error::NotAuthorized) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(200) << "application/json" << "{ \"expires_in\": 3600 }" << QVariantMap(); QTest::newRow("reply code, no content type") << "http://localhost/resp.html?code=c0d3&$state" << int(Error::OperationFailed) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(200) << "" << "something else" << QVariantMap(); QTest::newRow("reply code, unsupported content type") << "http://localhost/resp.html?code=c0d3&$state" << int(Error::OperationFailed) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(200) << "image/jpeg" << "something else" << QVariantMap(); response.clear(); response.insert("AccessToken", "t0k3n"); response.insert("ExpiresIn", int(3600)); response.insert("RefreshToken", QString()); QTest::newRow("reply code, valid token, wrong state") << "http://localhost/resp.html?code=c0d3&$wrongstate" << int(Error::NotAuthorized) << "" << "" << false << int(200) << "application/json" << "{ \"access_token\":\"t0k3n\", \"expires_in\": 3600 }" << response; response.clear(); response.insert("AccessToken", "t0k3n"); response.insert("ExpiresIn", int(3600)); response.insert("RefreshToken", QString()); response.insert("Scope", QStringList() << "one" << "two"); response.insert("ExtraFields", QVariantMap()); QTest::newRow("reply code, valid token, wrong state ignored") << "http://localhost/resp.html?code=c0d3&$wrongstate" << int(-1) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << true << int(200) << "application/json" << "{ \"access_token\":\"t0k3n\", \"expires_in\": 3600, " "\"scope\": \"one two\" }" << response; response.clear(); response.insert("AccessToken", "t0k3n"); response.insert("ExpiresIn", int(3600)); response.insert("RefreshToken", QString()); response.insert("Scope", QStringList() << "one" << "two" << "three"); response.insert("ExtraFields", QVariantMap()); QTest::newRow("reply code, valid token, no scope") << "http://localhost/resp.html?code=c0d3&$state" << int(-1) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(200) << "application/json" << "{ \"access_token\":\"t0k3n\", \"expires_in\": 3600 }" << response; response.clear(); response.insert("AccessToken", "t0k3n"); response.insert("ExpiresIn", int(3600)); response.insert("RefreshToken", QString()); response.insert("Scope", QStringList()); response.insert("ExtraFields", QVariantMap()); QTest::newRow("reply code, valid token, empty scope") << "http://localhost/resp.html?code=c0d3&$state" << int(-1) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(200) << "application/json" << "{ \"access_token\":\"t0k3n\", \"expires_in\": 3600, \"scope\": \"\" }" << response; response.clear(); response.insert("AccessToken", "t0k3n"); response.insert("ExpiresIn", int(3600)); response.insert("RefreshToken", QString()); response.insert("Scope", QStringList() << "one" << "two"); response.insert("ExtraFields", QVariantMap()); QTest::newRow("reply code, valid token, other scope") << "http://localhost/resp.html?code=c0d3&$state" << int(-1) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(200) << "application/json" << "{ \"access_token\":\"t0k3n\", \"expires_in\": 3600, " "\"scope\": \"one two\" }" << response; response.clear(); response.insert("AccessToken", "t0k3n"); response.insert("IdToken", "t0k3n2"); response.insert("ExpiresIn", int(3600)); response.insert("RefreshToken", QString()); response.insert("Scope", QStringList() << "one" << "two"); response.insert("ExtraFields", QVariantMap()); QTest::newRow("reply code, valid token, openid token, other scope") << "http://localhost/resp.html?code=c0d3&$state" << int(-1) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(200) << "application/json" << "{ \"access_token\":\"t0k3n\", \"id_token\":\"t0k3n2\", \"expires_in\": 3600, " "\"scope\": \"one two\" }" << response; response = { { "AccessToken", "t0k3n" }, { "ExpiresIn", int(3600) }, { "RefreshToken", QString() }, { "Scope", QStringList { "one" } }, { "ExtraFields", QVariantMap { { "userId", "345" }, { "verified", true }, } }, }; QTest::newRow("reply code, valid token, extra data") << "http://localhost/resp.html?code=c0d3&$state" << int(-1) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(200) << "application/json" << "{ \"access_token\":\"t0k3n\", \"expires_in\": 3600, " "\"scope\": \"one\", \"userId\": \"345\", \"verified\": true }" << response; response = { { "AccessToken", "t0k3n" }, { "IdToken", "t0k3n2" }, { "ExpiresIn", int(3600) }, { "RefreshToken", QString() }, { "Scope", QStringList { "one" } }, { "ExtraFields", QVariantMap { { "userId", "345" }, { "verified", true }, } }, }; QTest::newRow("reply code, valid token, openid token, extra data") << "http://localhost/resp.html?code=c0d3&$state" << int(-1) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(200) << "application/json" << "{ \"access_token\":\"t0k3n\", \"id_token\":\"t0k3n2\", \"expires_in\": 3600, " "\"scope\": \"one\", \"userId\": \"345\", \"verified\": true }" << response; response.clear(); QTest::newRow("reply code, facebook, no token") << "http://localhost/resp.html?code=c0d3&$state" << int(Error::NotAuthorized) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(200) << "text/plain" << "expires=3600" << response; response.clear(); response.insert("AccessToken", "t0k3n"); response.insert("ExpiresIn", int(3600)); response.insert("RefreshToken", QString()); response.insert("Scope", QStringList() << "one" << "two" << "three"); response.insert("ExtraFields", QVariantMap()); QTest::newRow("reply code, facebook, valid token") << "http://localhost/resp.html?code=c0d3&$state" << int(-1) << "https://localhost/access_token" << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << false << int(200) << "text/plain" << "access_token=t0k3n&expires=3600" << response; response.clear(); response.insert("AccessToken", "t0k3n"); response.insert("ExpiresIn", int(3600)); response.insert("RefreshToken", QString()); response.insert("Scope", QStringList() << "one" << "two" << "three"); response.insert("ExtraFields", QVariantMap()); QTest::newRow("username-password, valid token") << "http://localhost/resp.html?username=us3r&password=s3cr3t" << int(-1) << "https://localhost/access_token" << "grant_type=user_basic&username=us3r&password=s3cr3t" << false << int(200) << "application/json" << "{ \"access_token\":\"t0k3n\", \"expires_in\": 3600 }" << response; response.clear(); response.insert("AccessToken", "t0k3n"); response.insert("ExpiresIn", int(3600)); response.insert("RefreshToken", QString()); response.insert("Scope", QStringList() << "one" << "two" << "three"); response.insert("ExtraFields", QVariantMap()); QTest::newRow("assertion, valid token") << "http://localhost/resp.html?assertion_type=http://oauth.net/token/1.0" "&assertion=oauth1t0k3n" << int(-1) << "https://localhost/access_token" << "grant_type=assertion&assertion_type=http://oauth.net/token/1.0&assertion=oauth1t0k3n" << false << int(200) << "application/json" << "{ \"access_token\":\"t0k3n\", \"expires_in\": 3600 }" << response; response.clear(); response.insert("AccessToken", "t0k3n"); response.insert("ExpiresIn", int(3600)); response.insert("RefreshToken", QString()); response.insert("Scope", QStringList() << "one" << "two" << "three"); response.insert("ExtraFields", QVariantMap()); QTest::newRow("username-password, valid token, wrong content type") << "http://localhost/resp.html?username=us3r&password=s3cr3t" << int(-1) << "https://localhost/access_token" << "grant_type=user_basic&username=us3r&password=s3cr3t" << false << int(200) << "text/plain" << "{ \"access_token\":\"t0k3n\", \"expires_in\": 3600 }" << response; } void OAuth2PluginTest::testPluginWebserverUserActionFinished() { QFETCH(QString, urlResponse); QFETCH(int, errorCode); QFETCH(QString, postUrl); QFETCH(QString, postContents); QFETCH(bool, disableStateParameter); QFETCH(int, replyStatusCode); QFETCH(QString, replyContentType); QFETCH(QString, replyContents); QFETCH(QVariantMap, response); SignOn::UiSessionData info; OAuth2PluginData data; data.setHost("localhost"); data.setAuthPath("authorize"); data.setTokenPath("access_token"); data.setClientId("104660106251471"); data.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); data.setRedirectUri("http://localhost/resp.html"); data.setScope(QStringList() << "one" << "two" << "three"); data.setDisableStateParameter(disableStateParameter); QSignalSpy result(m_testPlugin, &Plugin::result); QSignalSpy error(m_testPlugin, &Plugin::error); QSignalSpy userActionRequired(m_testPlugin, &Plugin::userActionRequired); TestNetworkAccessManager *nam = new TestNetworkAccessManager; m_testPlugin->m_networkAccessManager = nam; TestNetworkReply *reply = new TestNetworkReply(this); reply->setStatusCode(replyStatusCode); if (!replyContentType.isEmpty()) { reply->setContentType(replyContentType); } reply->setContent(replyContents.toUtf8()); nam->setNextReply(reply); m_testPlugin->process(data, QString("web_server")); QTRY_COMPARE(userActionRequired.count(), 1); QString state = parseState(userActionRequired); if (!urlResponse.isEmpty()) { urlResponse.replace("$state", QString("state=") + state); urlResponse.replace("$wrongstate", QString("state=12") + state); info.setUrlResponse(urlResponse); } m_testPlugin->userActionFinished(info); QTRY_COMPARE(error.count(), errorCode < 0 ? 0 : 1); QTRY_COMPARE(result.count(), errorCode < 0 ? 1 : 0); if (errorCode >= 0) { QCOMPARE(error.at(0).at(0).value<Error>().type(), errorCode); } else { QCOMPARE(result.at(0).at(0).value<SessionData>().toMap(), response); } QCOMPARE(nam->m_lastRequest.url(), QUrl(postUrl)); QCOMPARE(QString::fromUtf8(nam->m_lastRequestData), postContents); delete nam; } void OAuth2PluginTest::testUserActionFinishedErrors_data() { QTest::addColumn<int>("uiError"); QTest::addColumn<int>("expectedErrorCode"); QTest::newRow("user canceled") << int(QUERY_ERROR_CANCELED) << int(Error::SessionCanceled); QTest::newRow("network error") << int(QUERY_ERROR_NETWORK) << int(Error::Network); QTest::newRow("SSL error") << int(QUERY_ERROR_SSL) << int(Error::Ssl); QTest::newRow("generic") << int(QUERY_ERROR_NOT_AVAILABLE) << int(Error::UserInteraction); } void OAuth2PluginTest::testUserActionFinishedErrors() { QFETCH(int, uiError); QFETCH(int, expectedErrorCode); SignOn::UiSessionData info; OAuth2PluginData data; data.setHost("localhost"); data.setAuthPath("authorize"); data.setTokenPath("access_token"); data.setClientId("104660106251471"); data.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); data.setRedirectUri("http://localhost/resp.html"); QSignalSpy error(m_testPlugin, &Plugin::error); QSignalSpy userActionRequired(m_testPlugin, &Plugin::userActionRequired); m_testPlugin->process(data, QString("web_server")); QTRY_COMPARE(userActionRequired.count(), 1); info.setQueryErrorCode(uiError); m_testPlugin->userActionFinished(info); QTRY_COMPARE(error.count(), 1); QCOMPARE(error.at(0).at(0).value<Error>().type(), expectedErrorCode); } void OAuth2PluginTest::testOauth1UserActionFinished_data() { QTest::addColumn<QString>("mechanism"); QTest::addColumn<QString>("urlResponse"); QTest::addColumn<int>("errorCode"); QTest::addColumn<QVariantMap>("expectedAuthMap"); QTest::addColumn<int>("replyStatusCode"); QTest::addColumn<QString>("replyContentType"); QTest::addColumn<QString>("replyContents"); QTest::addColumn<QVariantMap>("response"); QTest::newRow("empty data") << "HMAC-SHA1" << "" << int(Error::NotAuthorized) << QVariantMap() << 0 << "" << "" << QVariantMap(); QTest::newRow("auth error") << "HMAC-SHA1" << "http://localhost/resp.html?error=permission_denied" << int(Error::NotAuthorized) << QVariantMap() << 0 << "" << "" << QVariantMap(); QTest::newRow("auth problem") << "HMAC-SHA1" << "http://localhost/resp.html?oauth_problem=permission_denied" << int(Error::PermissionDenied) << QVariantMap() << 0 << "" << "" << QVariantMap(); QVariantMap authMap; authMap.insert("oauth_verifier", QString("v3r1f13r")); authMap.insert("oauth_token", QString("HiThere")); QTest::newRow("http error 401") << "HMAC-SHA1" << "http://localhost/resp.html?oauth_verifier=v3r1f13r" << int(Error::OperationFailed) << authMap << int(401) << "text/plain" << "something else" << QVariantMap(); QTest::newRow("empty reply") << "HMAC-SHA1" << "http://localhost/resp.html?oauth_verifier=v3r1f13r" << int(Error::OperationFailed) << authMap << int(200) << "text/plain" << "" << QVariantMap(); QTest::newRow("missing secret") << "HMAC-SHA1" << "http://localhost/resp.html?oauth_verifier=v3r1f13r" << int(Error::OperationFailed) << authMap << int(200) << "text/plain" << "oauth_token=t0k3n" << QVariantMap(); QVariantMap response; response.insert("AccessToken", QString("t0k3n")); response.insert("TokenSecret", QString("t0k3nS3cr3t")); QTest::newRow("success") << "HMAC-SHA1" << "http://localhost/resp.html?oauth_verifier=v3r1f13r" << int(-1) << authMap << int(200) << "text/plain" << "oauth_token=t0k3n&oauth_token_secret=t0k3nS3cr3t" << response; response.insert("ExtraField", QString("v4lu3")); QTest::newRow("success with data") << "HMAC-SHA1" << "http://localhost/resp.html?oauth_verifier=v3r1f13r" << int(-1) << authMap << int(200) << "text/plain" << "oauth_token=t0k3n&oauth_token_secret=t0k3nS3cr3t" "&ExtraField=v4lu3" << response; } void OAuth2PluginTest::testOauth1UserActionFinished() { QFETCH(QString, mechanism); QFETCH(QString, urlResponse); QFETCH(int, errorCode); QFETCH(QVariantMap, expectedAuthMap); QFETCH(int, replyStatusCode); QFETCH(QString, replyContentType); QFETCH(QString, replyContents); QFETCH(QVariantMap, response); SignOn::UiSessionData info; OAuth1PluginData data; data.setRequestEndpoint("https://localhost/oauth/request_token"); data.setTokenEndpoint("https://localhost/oauth/access_token"); data.setAuthorizationEndpoint("https://localhost/oauth/authorize"); data.setCallback("http://localhost/resp.html"); data.setConsumerKey("104660106251471"); data.setConsumerSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); data.setRealm("MyHost"); QSignalSpy result(m_testPlugin, &Plugin::result); QSignalSpy error(m_testPlugin, &Plugin::error); QSignalSpy userActionRequired(m_testPlugin, &Plugin::userActionRequired); TestNetworkAccessManager *nam = new TestNetworkAccessManager; m_testPlugin->m_networkAccessManager = nam; TestNetworkReply *reply = new TestNetworkReply(this); reply->setStatusCode(200); reply->setContentType("text/plain"); reply->setContent("oauth_token=HiThere&oauth_token_secret=BigSecret"); nam->setNextReply(reply); m_testPlugin->process(data, mechanism); QTRY_COMPARE(userActionRequired.count(), 1); nam->m_lastRequest = QNetworkRequest(); nam->m_lastRequestData = QByteArray(); reply = new TestNetworkReply(this); reply->setStatusCode(replyStatusCode); if (!replyContentType.isEmpty()) { reply->setContentType(replyContentType); } reply->setContent(replyContents.toUtf8()); nam->setNextReply(reply); if (!urlResponse.isEmpty()) { info.setUrlResponse(urlResponse); } m_testPlugin->userActionFinished(info); QTRY_COMPARE(error.count(), errorCode < 0 ? 0 : 1); QTRY_COMPARE(result.count(), errorCode < 0 ? 1 : 0); QVariantMap resp; if (errorCode >= 0) { QCOMPARE(error.at(0).at(0).value<Error>().type(), errorCode); } else { resp = result.at(0).at(0).value<SessionData>().toMap(); QVERIFY(mapIsSubset(response, resp)); } if (!expectedAuthMap.isEmpty()) { QCOMPARE(nam->m_lastRequest.url().toString(), data.TokenEndpoint()); QVERIFY(nam->m_lastRequestData.isEmpty()); QString authorizationHeader = QString::fromUtf8(nam->m_lastRequest.rawHeader("Authorization")); QStringList authorizationHeaderParts = authorizationHeader.split(QRegularExpression(",?\\s+")); QCOMPARE(authorizationHeaderParts[0], QString("OAuth")); /* The rest of the header should be a mapping, let's parse it */ bool ok = true; QVariantMap authMap = parseAuthorizationHeader(authorizationHeaderParts.mid(1), &ok); QVERIFY(ok); QCOMPARE(authMap.value("oauth_signature_method").toString(), mechanism); QVERIFY(mapIsSubset(expectedAuthMap, authMap)); } delete nam; } void OAuth2PluginTest::testOAuth2Errors_data() { QTest::addColumn<QString>("replyContents"); QTest::addColumn<int>("expectedErrorCode"); QTest::newRow("incorrect_client_credentials") << "{ \"error\": \"incorrect_client_credentials\" }" << int(Error::InvalidCredentials); QTest::newRow("redirect_uri_mismatch") << "{ \"error\": \"redirect_uri_mismatch\" }" << int(Error::InvalidCredentials); QTest::newRow("bad_authorization_code") << "{ \"error\": \"bad_authorization_code\" }" << int(Error::InvalidCredentials); QTest::newRow("invalid_client_credentials") << "{ \"error\": \"invalid_client_credentials\" }" << int(Error::InvalidCredentials); QTest::newRow("unauthorized_client") << "{ \"error\": \"unauthorized_client\" }" << int(Error::NotAuthorized); QTest::newRow("invalid_assertion") << "{ \"error\": \"invalid_assertion\" }" << int(Error::InvalidCredentials); QTest::newRow("unknown_format") << "{ \"error\": \"unknown_format\" }" << int(Error::InvalidQuery); QTest::newRow("authorization_expired") << "{ \"error\": \"authorization_expired\" }" << int(Error::InvalidCredentials); QTest::newRow("multiple_credentials") << "{ \"error\": \"multiple_credentials\" }" << int(Error::InvalidQuery); QTest::newRow("invalid_user_credentials") << "{ \"error\": \"invalid_user_credentials\" }" << int(Error::InvalidCredentials); } void OAuth2PluginTest::testOAuth2Errors() { QFETCH(QString, replyContents); QFETCH(int, expectedErrorCode); SignOn::UiSessionData info; OAuth2PluginData data; data.setHost("localhost"); data.setAuthPath("authorize"); data.setTokenPath("access_token"); data.setClientId("104660106251471"); data.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); data.setRedirectUri("http://localhost/resp.html"); QSignalSpy error(m_testPlugin, &Plugin::error); QSignalSpy userActionRequired(m_testPlugin, &Plugin::userActionRequired); TestNetworkAccessManager *nam = new TestNetworkAccessManager; m_testPlugin->m_networkAccessManager = nam; TestNetworkReply *reply = new TestNetworkReply(this); reply->setStatusCode(401); reply->setContentType("application/json"); reply->setContent(replyContents.toUtf8()); nam->setNextReply(reply); m_testPlugin->process(data, QString("web_server")); QTRY_COMPARE(userActionRequired.count(), 1); QString state = parseState(userActionRequired); info.setUrlResponse("http://localhost/resp.html?code=c0d3&state=" + state); m_testPlugin->userActionFinished(info); QTRY_COMPARE(error.count(), 1); QCOMPARE(error.at(0).at(0).value<Error>().type(), expectedErrorCode); delete nam; } void OAuth2PluginTest::testRefreshToken_data() { QTest::addColumn<QVariantMap>("sessionData"); QTest::addColumn<QVariantMap>("expectedResponse"); OAuth2PluginData data; data.setHost("localhost"); data.setAuthPath("authorize"); data.setTokenPath("access_token"); data.setClientId("104660106251471"); data.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); data.setRedirectUri("http://localhost/resp.html"); QVariantMap tokens; QVariantMap token; token.insert("Token", QLatin1String("tokenfromtest")); token.insert("timestamp", QDateTime::currentDateTime().toSecsSinceEpoch() - 10000); token.insert("Expiry", 1000); token.insert("refresh_token", QString("r3fr3sh")); tokens.insert(data.ClientId(), QVariant::fromValue(token)); data.m_data.insert("Tokens", tokens); QVariantMap response; response.insert("AccessToken", "n3w-t0k3n"); response.insert("ExpiresIn", 3600); response.insert("RefreshToken", QString()); response.insert("Scope", QStringList()); response.insert("ExtraFields", QVariantMap()); QTest::newRow("expired access token") << data.toMap() << response; token.insert("timestamp", QDateTime::currentDateTime().toSecsSinceEpoch()); token.insert("Expiry", 50000); token.insert("ExtraFields", QVariantMap()); tokens.insert(data.ClientId(), QVariant::fromValue(token)); data.m_data.insert("Tokens", tokens); data.setForceTokenRefresh(true); QTest::newRow("valid access token, force refresh") << data.toMap() << response; } void OAuth2PluginTest::testRefreshToken() { QFETCH(QVariantMap, sessionData); QFETCH(QVariantMap, expectedResponse); SignOn::UiSessionData info; QSignalSpy result(m_testPlugin, &Plugin::result); QSignalSpy error(m_testPlugin, &Plugin::error); TestNetworkAccessManager *nam = new TestNetworkAccessManager; m_testPlugin->m_networkAccessManager = nam; TestNetworkReply *reply = new TestNetworkReply(this); reply->setStatusCode(200); reply->setContentType("application/json"); reply->setContent("{ \"access_token\":\"n3w-t0k3n\", \"expires_in\": 3600 }"); nam->setNextReply(reply); m_testPlugin->process(sessionData, QString("web_server")); QTRY_COMPARE(result.count(), 1); QCOMPARE(error.count(), 0); QCOMPARE(nam->m_lastRequest.url(), QUrl("https://localhost/access_token")); QCOMPARE(QString::fromUtf8(nam->m_lastRequestData), QString("grant_type=refresh_token&refresh_token=r3fr3sh")); QCOMPARE(result.at(0).at(0).value<SessionData>().toMap(), expectedResponse); delete nam; } void OAuth2PluginTest::testRefreshTokenError_data() { QTest::addColumn<int>("replyErrorCode"); QTest::addColumn<int>("replyStatusCode"); QTest::addColumn<QString>("replyContents"); QTest::addColumn<int>("expectedError"); QTest::newRow("invalid grant, 400") << int(QNetworkReply::ProtocolInvalidOperationError) << int(400) << "{ \"error\":\"invalid_grant\" }" << int(-1); QTest::newRow("invalid grant, 401") << int(QNetworkReply::ContentAccessDenied) << int(401) << "{ \"error\":\"invalid_grant\" }" << int(-1); QTest::newRow("invalid grant, 401, no error signal") << int(-1) << int(401) << "{ \"error\":\"invalid_grant\" }" << int(-1); QTest::newRow("temporary network failure") << int(QNetworkReply::TemporaryNetworkFailureError) << int(-1) << "" << int(Error::NoConnection); } void OAuth2PluginTest::testRefreshTokenError() { QFETCH(int, replyErrorCode); QFETCH(int, replyStatusCode); QFETCH(QString, replyContents); QFETCH(int, expectedError); OAuth2PluginData data; data.setHost("localhost"); data.setAuthPath("authorize"); data.setTokenPath("access_token"); data.setClientId("104660106251471"); data.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); data.setRedirectUri("http://localhost/resp.html"); QVariantMap tokens; QVariantMap token; token.insert("Token", QLatin1String("tokenfromtest")); token.insert("timestamp", QDateTime::currentDateTime().toSecsSinceEpoch() - 10000); token.insert("Expiry", 1000); token.insert("refresh_token", QString("r3fr3sh")); tokens.insert(data.ClientId(), QVariant::fromValue(token)); data.m_data.insert("Tokens", tokens); SignOn::UiSessionData info; QSignalSpy error(m_testPlugin, &Plugin::error); QSignalSpy userActionRequired(m_testPlugin, &Plugin::userActionRequired); TestNetworkAccessManager *nam = new TestNetworkAccessManager; m_testPlugin->m_networkAccessManager = nam; TestNetworkReply *reply = new TestNetworkReply(this); if (replyErrorCode >= 0) { reply->setError(QNetworkReply::NetworkError(replyErrorCode), "Dummy error", 5); } reply->setStatusCode(replyStatusCode); reply->setContentType("application/json"); reply->setContent(replyContents.toUtf8()); nam->setNextReply(reply); m_testPlugin->process(data, QString("web_server")); if (expectedError < 0) { QTRY_COMPARE(userActionRequired.count(), 1); QCOMPARE(error.count(), 0); } else { QTRY_COMPARE(error.count(), 1); QCOMPARE(error.at(0).at(0).value<Error>().type(), expectedError); } delete nam; } void OAuth2PluginTest::testClientAuthentication_data() { QTest::addColumn<QString>("clientSecret"); QTest::addColumn<bool>("forceAuthViaRequestBody"); QTest::addColumn<QString>("postContents"); QTest::addColumn<QString>("postAuthorization"); QTest::newRow("no secret, std auth") << "" << false << "grant_type=authorization_code&code=c0d3" "&redirect_uri=http://localhost/resp.html&client_id=104660106251471" << ""; QTest::newRow("no secret, auth in body") << "" << true << "grant_type=authorization_code&code=c0d3" "&redirect_uri=http://localhost/resp.html&client_id=104660106251471" << ""; QTest::newRow("with secret, std auth") << "s3cr3t" << false << "grant_type=authorization_code&code=c0d3&redirect_uri=http://localhost/resp.html" << "Basic MTA0NjYwMTA2MjUxNDcxOnMzY3IzdA=="; QTest::newRow("with secret, auth in body") << "s3cr3t" << true << "grant_type=authorization_code&code=c0d3" "&redirect_uri=http://localhost/resp.html" "&client_id=104660106251471&client_secret=s3cr3t" << ""; } void OAuth2PluginTest::testClientAuthentication() { QFETCH(QString, clientSecret); QFETCH(bool, forceAuthViaRequestBody); QFETCH(QString, postContents); QFETCH(QString, postAuthorization); SignOn::UiSessionData info; OAuth2PluginData data; data.setHost("localhost"); data.setAuthPath("authorize"); data.setTokenPath("access_token"); data.setClientId("104660106251471"); data.setClientSecret(clientSecret); data.setRedirectUri("http://localhost/resp.html"); data.setForceClientAuthViaRequestBody(forceAuthViaRequestBody); QSignalSpy result(m_testPlugin, &Plugin::result); QSignalSpy error(m_testPlugin, &Plugin::error); QSignalSpy userActionRequired(m_testPlugin, &Plugin::userActionRequired); TestNetworkAccessManager *nam = new TestNetworkAccessManager; m_testPlugin->m_networkAccessManager = nam; TestNetworkReply *reply = new TestNetworkReply(this); reply->setStatusCode(200); reply->setContentType("application/json"); reply->setContent("{ \"access_token\":\"t0k3n\", \"expires_in\": 3600 }"); nam->setNextReply(reply); m_testPlugin->process(data, QString("web_server")); QTRY_COMPARE(userActionRequired.count(), 1); QString state = parseState(userActionRequired); info.setUrlResponse("http://localhost/resp.html?code=c0d3&state=" + state); m_testPlugin->userActionFinished(info); QTRY_COMPARE(result.count(), 1); QCOMPARE(error.count(), 0); QCOMPARE(nam->m_lastRequest.url(), QUrl("https://localhost/access_token")); QCOMPARE(QString::fromUtf8(nam->m_lastRequestData), postContents); QCOMPARE(QString::fromUtf8(nam->m_lastRequest.rawHeader("Authorization")), postAuthorization); delete nam; } void OAuth2PluginTest::testTokenPath_data() { QTest::addColumn<QString>("host"); QTest::addColumn<QString>("tokenPath"); QTest::addColumn<QString>("expectedTokenUrl"); QTest::newRow("relative") << "localhost" << "access_token" << "https://localhost/access_token"; QTest::newRow("relative with slashes") << "localhost" << "path/to/access_token" << "https://localhost/path/to/access_token"; QTest::newRow("absolute") << "localhost" << "https://another.host/and/a/path" << "https://another.host/and/a/path"; } void OAuth2PluginTest::testTokenPath() { QFETCH(QString, host); QFETCH(QString, tokenPath); QFETCH(QString, expectedTokenUrl); SignOn::UiSessionData info; OAuth2PluginData data; data.setHost(host); data.setAuthPath("authorize"); data.setTokenPath(tokenPath); data.setClientId("104660106251471"); data.setRedirectUri("http://localhost/resp.html"); QSignalSpy result(m_testPlugin, &Plugin::result); QSignalSpy error(m_testPlugin, &Plugin::error); QSignalSpy userActionRequired(m_testPlugin, &Plugin::userActionRequired); TestNetworkAccessManager *nam = new TestNetworkAccessManager; m_testPlugin->m_networkAccessManager = nam; TestNetworkReply *reply = new TestNetworkReply(this); reply->setStatusCode(200); reply->setContentType("application/json"); reply->setContent("{ \"access_token\":\"t0k3n\", \"expires_in\": 3600 }"); nam->setNextReply(reply); m_testPlugin->process(data, QString("web_server")); QTRY_COMPARE(userActionRequired.count(), 1); QString state = parseState(userActionRequired); info.setUrlResponse("http://localhost/resp.html?code=c0d3&state=" + state); m_testPlugin->userActionFinished(info); QTRY_COMPARE(result.count(), 1); QCOMPARE(error.count(), 0); QCOMPARE(nam->m_lastRequest.url(), QUrl(expectedTokenUrl)); delete nam; } void OAuth2PluginTest::testTokenQuery_data() { QTest::addColumn<QVariantMap>("sessionData"); QTest::addColumn<QString>("expectedTokenUrl"); QTest::addColumn<QString>("expectedTokenData"); QString fixedData = QStringLiteral("grant_type=authorization_code&code=c0d3&" "redirect_uri=http://localhost/resp.html&" "client_id=104660106251471"); QTest::newRow("no query") << QVariantMap { { "Host", "localhost" }, { "TokenPath", "access_token" }, } << "https://localhost/access_token" << fixedData; QTest::newRow("with query") << QVariantMap { { "Host", "localhost" }, { "TokenPath", "access_token" }, { "TokenQuery", "one=1&bool=false" }, } << "https://localhost/access_token" << QString("one=1&bool=false&") + fixedData; QTest::newRow("token host, no query") << QVariantMap { { "AuthHost", "localhost" }, { "TokenHost", "localhost" }, { "TokenPath", "access_token" }, } << "https://localhost/access_token" << fixedData; QTest::newRow("token host, with query") << QVariantMap { { "AuthHost", "localhost" }, { "TokenHost", "localhost" }, { "TokenPath", "access_token" }, { "TokenQuery", "one=1&bool=false" }, } << "https://localhost/access_token" << QString("one=1&bool=false&") + fixedData; } void OAuth2PluginTest::testTokenQuery() { QFETCH(QVariantMap, sessionData); QFETCH(QString, expectedTokenUrl); QFETCH(QString, expectedTokenData); SignOn::UiSessionData info; OAuth2PluginData data(sessionData); data.setAuthPath("authorize"); data.setClientId("104660106251471"); data.setRedirectUri("http://localhost/resp.html"); QSignalSpy result(m_testPlugin, &Plugin::result); QSignalSpy error(m_testPlugin, &Plugin::error); QSignalSpy userActionRequired(m_testPlugin, &Plugin::userActionRequired); QScopedPointer<TestNetworkAccessManager> nam(new TestNetworkAccessManager); m_testPlugin->m_networkAccessManager = nam.data(); TestNetworkReply *reply = new TestNetworkReply(this); reply->setStatusCode(200); reply->setContentType("application/json"); reply->setContent("{ \"access_token\":\"t0k3n\", \"expires_in\": 3600 }"); nam->setNextReply(reply); m_testPlugin->process(data, QString("web_server")); QTRY_COMPARE(userActionRequired.count(), 1); QString state = parseState(userActionRequired); info.setUrlResponse("http://localhost/resp.html?code=c0d3&state=" + state); m_testPlugin->userActionFinished(info); QTRY_COMPARE(result.count(), 1); QCOMPARE(error.count(), 0); QCOMPARE(nam->m_lastRequest.url(), QUrl(expectedTokenUrl)); QCOMPARE(nam->m_lastRequestData, expectedTokenData.toUtf8()); } void OAuth2PluginTest::testOAuth2AuthRequestUri_data() { QTest::addColumn<QString>("mechanism"); QTest::addColumn<QVariantMap>("sessionData"); QTest::addColumn<QString>("expectedUri"); OAuth2PluginData sessionData; sessionData.setHost("localhost"); sessionData.setAuthPath("authorize"); sessionData.setClientId("104660106251471"); sessionData.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); sessionData.setRedirectUri("http://localhost/connect/login_success.html"); sessionData.setDisableStateParameter(true); QTest::newRow("no scopes") << "user_agent" << sessionData.toMap() << "https://localhost/authorize?client_id=104660106251471&" "redirect_uri=http%3A%2F%2Flocalhost%2Fconnect%2Flogin_success.html"; sessionData.setHost("www.example.com"); sessionData.setTokenPath("access_token"); sessionData.setClientId("104660106251471"); sessionData.setClientSecret("fa28f40b5a1f8c1d5628963d880636fbkjkjkj"); sessionData.setRedirectUri("http://localhost/connect/login_success.html"); sessionData.setScope(QStringList() << "http://scope1" << "http://scope2"); QTest::newRow("with scopes") << "web_server" << sessionData.toMap() << "https://www.example.com/authorize?client_id=104660106251471&" "redirect_uri=http%3A%2F%2Flocalhost%2Fconnect%2Flogin_success.html&" "scope=http%3A%2F%2Fscope1 http%3A%2F%2Fscope2"; } void OAuth2PluginTest::testOAuth2AuthRequestUri() { QFETCH(QString, mechanism); QFETCH(QVariantMap, sessionData); QFETCH(QString, expectedUri); QSignalSpy userActionRequired(m_testPlugin, &Plugin::userActionRequired); m_testPlugin->process(sessionData, mechanism); QCOMPARE(userActionRequired.count(), 1); UiSessionData uiRequest = userActionRequired.at(0).at(0).value<UiSessionData>(); QCOMPARE(uiRequest.OpenUrl(), expectedUri); } //end test cases QTEST_MAIN(OAuth2PluginTest) #include "oauth2plugintest.moc" 07070100000022000081A40000000000000000000000016560A3A500000943000000000000000000000000000000000000004E00000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/tests/oauth2plugintest.h/* * This file is part of oauth2 plugin * * Copyright (C) 2010 Nokia Corporation. * Copyright (C) 2012-2016 Canonical Ltd. * * Contact: Alberto Mardegan <alberto.mardegan@canonical.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA */ #ifndef OAUTH2PLUGINTEST_H #define OAUTH2PLUGINTEST_H #include <QNetworkReply> #include <QString> #include "plugin.h" #include "SignOn/AuthPluginInterface" using namespace OAuth2PluginNS; class OAuth2PluginTest : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); //test cases void testPlugin(); void testPluginType(); void testPluginMechanisms(); void testPluginCancel(); void testPluginProcess_data(); void testPluginProcess(); void testPluginHmacSha1Process_data(); void testPluginHmacSha1Process(); void testPluginUseragentUserActionFinished(); void testPluginWebserverUserActionFinished_data(); void testPluginWebserverUserActionFinished(); void testUserActionFinishedErrors_data(); void testUserActionFinishedErrors(); void testOauth1UserActionFinished_data(); void testOauth1UserActionFinished(); void testOAuth2Errors_data(); void testOAuth2Errors(); void testRefreshToken_data(); void testRefreshToken(); void testRefreshTokenError_data(); void testRefreshTokenError(); void testClientAuthentication_data(); void testClientAuthentication(); void testTokenPath_data(); void testTokenPath(); void testTokenQuery_data(); void testTokenQuery(); void testOAuth2AuthRequestUri_data(); void testOAuth2AuthRequestUri(); private: Plugin *m_testPlugin; }; #endif // OAUTH2PLUGINTEST_H 07070100000023000081A40000000000000000000000016560A3A5000003B6000000000000000000000000000000000000004500000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/tests/tests.proinclude( ../common-project-config.pri ) include( ../common-vars.pri ) TARGET = signon-oauth2plugin-tests QT += core \ network \ testlib QT -= gui DEFINES -= SIGNON_TRACE CONFIG += \ link_pkgconfig SOURCES += \ $${TOP_SRC_DIR}/src/base-plugin.cpp \ $${TOP_SRC_DIR}/src/oauth2plugin.cpp \ $${TOP_SRC_DIR}/src/oauth1plugin.cpp \ $${TOP_SRC_DIR}/src/plugin.cpp \ oauth2plugintest.cpp HEADERS += \ $${TOP_SRC_DIR}/src/base-plugin.h \ $${TOP_SRC_DIR}/src/oauth2plugin.h \ $${TOP_SRC_DIR}/src/oauth1plugin.h \ $${TOP_SRC_DIR}/src/plugin.h \ oauth2plugintest.h INCLUDEPATH += . \ $${TOP_SRC_DIR}/src PKGCONFIG += \ signon-plugins target.path = $${INSTALL_PREFIX}/bin testsuite.path = $${INSTALL_PREFIX}/share/$$TARGET testsuite.files = tests.xml INSTALLS += target \ testsuite check.depends = $$TARGET check.commands = ./$$TARGET || : QMAKE_EXTRA_TARGETS += check QMAKE_CLEAN += $$TARGET 07070100000024000081A40000000000000000000000016560A3A5000008EA000000000000000000000000000000000000004500000000signon-plugin-oauth2-0.25git.20231124T142245~fab6988/tests/tests.xml<?xml version="1.0" encoding="ISO-8859-1"?> <testdefinition version="1.0"> <suite name="signon-oauth2plugin-tests" domain="Accounts and SSO"> <set description="signon-oauth2plugin-tests:signon-oauth2plugin-tests" name="./signon-oauth2plugin-tests" feature="Google"> <description>signon-oauth2plugin-tests:signon-oauth2plugin-tests</description> <case name="signon-oauth2plugin-tests-testPlugin" type="Functional" level="Component"> <description>signon-oauth2plugin-tests:signon-oauth2plugin-tests:testPlugin</description> <step>/usr/bin/signon-oauth2plugin-tests testPlugin</step> </case> <case name="signon-oauth2plugin-tests-testPluginType" type="Functional" level="Component"> <description>signon-oauth2plugin-tests:signon-oauth2plugin-tests:testPluginType</description> <step>/usr/bin/signon-oauth2plugin-tests testPluginType</step> </case> <case name="signon-oauth2plugin-tests-testPluginMechanisms" type="Functional" level="Component"> <description>signon-oauth2plugin-tests:signon-oauth2plugin-tests:testPluginMechanisms</description> <step>/usr/bin/signon-oauth2plugin-tests testPluginMechanisms</step> </case> <case name="signon-oauth2plugin-tests-testPluginCancel" type="Functional" level="Component"> <description>signon-oauth2plugin-tests:signon-oauth2plugin-tests:testPluginCancel</description> <step>/usr/bin/signon-oauth2plugin-tests testPluginCancel</step> </case> <case name="signon-oauth2plugin-tests-testPluginProcess" type="Functional" level="Component"> <description>signon-oauth2plugin-tests:signon-oauth2plugin-tests:testPluginProcess</description> <step>/usr/bin/signon-oauth2plugin-tests testPluginProcess</step> </case> <case name="signon-oauth2plugin-tests-testPluginWebserverUserActionFinished" type="Functional" level="Component"> <description>signon-oauth2plugin-tests:signon-oauth2plugin-tests:testPluginWebserverUserActionFinished</description> <step>/usr/bin/signon-oauth2plugin-tests testPluginProcess</step> </case> <environments> <scratchbox>true</scratchbox> <hardware>true</hardware> </environments> </set> </suite> </testdefinition> 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!427 blocks
Locations
Projects
Search
Status Monitor
Help
OpenBuildService.org
Documentation
API Documentation
Code of Conduct
Contact
Support
@OBShq
Terms
openSUSE Build Service is sponsored by
The Open Build Service is an
openSUSE project
.
Sign Up
Log In
Places
Places
All Projects
Status Monitor