From 6e09be1cb1da5b3402b2ace2513733fd2f79d347 Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Mon, 8 Dec 2025 16:44:20 +0100 Subject: [PATCH 1/2] refactor: Fix many psalm issues Signed-off-by: Carl Schwan --- LICENSES/AGPL-3.0-only.txt | 235 +++++++++++++ lib/Command/UserAdd.php | 4 +- lib/Controller/SAMLController.php | 14 +- lib/Controller/SettingsController.php | 22 +- lib/GroupManager.php | 84 +++-- .../LoadAdditionalScriptsListener.php | 3 + .../Version5000Date20211025124248.php | 1 + lib/SAMLSettings.php | 16 +- lib/Settings/Admin.php | 36 +- lib/UserBackend.php | 184 +++++------ lib/UserData.php | 21 +- psalm.xml | 10 +- tests/psalm-baseline.xml | 38 --- tests/stub.phpstub | 4 + tests/stubs/oc.php | 122 +++++++ ...e_controller_clientflowlogincontroller.php | 13 + ...controller_clientflowloginv2controller.php | 18 + tests/stubs/oc_hooks_basicemitter.php | 15 + tests/stubs/oc_hooks_emitter.php | 36 ++ tests/unit/GroupManagerTest.php | 83 +++-- tests/unit/Settings/AdminTest.php | 66 ++-- tests/unit/UserBackendTest.php | 96 +++--- vendor-bin/psalm/composer.json | 8 +- vendor-bin/psalm/composer.lock | 311 +++++++++--------- 24 files changed, 938 insertions(+), 502 deletions(-) create mode 100644 LICENSES/AGPL-3.0-only.txt create mode 100644 tests/stubs/oc.php create mode 100644 tests/stubs/oc_core_controller_clientflowlogincontroller.php create mode 100644 tests/stubs/oc_core_controller_clientflowloginv2controller.php create mode 100644 tests/stubs/oc_hooks_basicemitter.php create mode 100644 tests/stubs/oc_hooks_emitter.php diff --git a/LICENSES/AGPL-3.0-only.txt b/LICENSES/AGPL-3.0-only.txt new file mode 100644 index 000000000..0c97efd25 --- /dev/null +++ b/LICENSES/AGPL-3.0-only.txt @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/lib/Command/UserAdd.php b/lib/Command/UserAdd.php index 48cbaf522..913dc4357 100644 --- a/lib/Command/UserAdd.php +++ b/lib/Command/UserAdd.php @@ -50,7 +50,8 @@ protected function configure(): void { protected function execute(InputInterface $input, OutputInterface $output): int { $uid = $input->getArgument('uid'); - if ($this->userManager->userExists($uid)) { + $user = $this->userManager->get($uid); + if ($user === null) { $output->writeln('The account "' . $uid . '" already exists.'); return 1; } @@ -70,7 +71,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->backend->setDisplayName($uid, $input->getOption('display-name')); $email = $input->getOption('email'); if (!empty($email)) { - $user = $this->userManager->get($uid); $user->setSystemEMailAddress($email); } } catch (\Exception $e) { diff --git a/lib/Controller/SAMLController.php b/lib/Controller/SAMLController.php index 30c980630..c0045b66f 100644 --- a/lib/Controller/SAMLController.php +++ b/lib/Controller/SAMLController.php @@ -100,13 +100,12 @@ private function autoprovisionIfPossible(): void { } $uid = $this->userData->getOriginalUid(); $uid = $this->userData->testEncodedObjectGUID($uid); - if (!$userExists && !$autoProvisioningAllowed) { + if (!$autoProvisioningAllowed) { throw new NoUserFoundException('Auto provisioning not allowed and user ' . $uid . ' does not exist'); - } elseif (!$userExists && $autoProvisioningAllowed) { - $this->userBackend->createUserIfNotExists($uid, $auth); - $this->userBackend->updateAttributes($uid); - return; } + + $this->userBackend->createUserIfNotExists($uid, $auth); + $this->userBackend->updateAttributes($uid); } /** @@ -355,7 +354,7 @@ public function assertionConsumerService(): Http\RedirectResponse { foreach ($errors as $error) { $this->logger->error($error, ['app' => $this->appName]); } - $this->logger->error($auth->getLastErrorReason(), ['app' => $this->appName]); + $this->logger->error($auth->getLastErrorReason() ?? 'No last error reason found', ['app' => $this->appName]); } if (!$auth->isAuthenticated()) { @@ -457,6 +456,7 @@ public function singleLogoutService(): Http\RedirectResponse { $idp = $decoded['idp'] ?? null; $pass = true; } catch (Exception) { + $pass = false; } } else { // standard request : need read CRSF check @@ -494,7 +494,7 @@ public function singleLogoutService(): Http\RedirectResponse { $this->userSession->logout(); } } - if (!empty($targetUrl) && !$auth->getLastErrorReason()) { + if (!empty($targetUrl) && $auth && !$auth->getLastErrorReason()) { $this->userSession->logout(); } } diff --git a/lib/Controller/SettingsController.php b/lib/Controller/SettingsController.php index ba777fa0c..80b0c1130 100644 --- a/lib/Controller/SettingsController.php +++ b/lib/Controller/SettingsController.php @@ -10,24 +10,32 @@ use OCA\User_SAML\SAMLSettings; use OCA\User_SAML\Settings\Admin; use OCP\AppFramework\Controller; +use OCP\AppFramework\Http; use OCP\AppFramework\Http\DataResponse; use OCP\AppFramework\Http\Response; -use OCP\IConfig; +use OCP\AppFramework\Services\IAppConfig; use OCP\IRequest; use OneLogin\Saml2\Constants; +/** + * @psalm-api + */ class SettingsController extends Controller { public function __construct( - $appName, + string $appName, IRequest $request, - private readonly IConfig $config, + private readonly IAppConfig $appConfig, private readonly Admin $admin, private readonly SAMLSettings $samlSettings, ) { parent::__construct($appName, $request); } + /** + * @return DataResponse + * @throws \OCP\DB\Exception + */ public function getSamlProviderIds(): DataResponse { $keys = array_keys($this->samlSettings->getListOfIdps()); return new DataResponse([ 'providerIds' => implode(',', $keys)]); @@ -51,6 +59,7 @@ public function getSamlProviderSettings(int $providerId): array { 'passthroughParameters' => ['required' => false], ]; /* Fetch all config values for the given providerId */ + $settings = []; // initialize settings with default value for option box (others are left empty) $settings['sp']['name-id-format'] = Constants::NAMEID_UNSPECIFIED; @@ -81,7 +90,7 @@ public function getSamlProviderSettings(int $providerId): array { if (isset($details['global']) && $details['global']) { // Read legacy data from oc_appconfig - $settings[$category][$setting] = $this->config->getAppValue('user_saml', $key, ''); + $settings[$category][$setting] = $this->appConfig->getAppValueString($key, ''); } else { $settings[$category][$setting] = $storedSettings[$key] ?? ''; } @@ -90,7 +99,7 @@ public function getSamlProviderSettings(int $providerId): array { return $settings; } - public function deleteSamlProviderSettings($providerId): Response { + public function deleteSamlProviderSettings(int $providerId): Response { $this->samlSettings->delete($providerId); return new Response(); } @@ -102,6 +111,9 @@ public function setProviderSetting(int $providerId, string $configKey, string $c return new Response(); } + /* + * @return DataResponse + */ public function newSamlProviderSettingsId(): DataResponse { return new DataResponse(['id' => $this->samlSettings->getNewProviderId()]); } diff --git a/lib/GroupManager.php b/lib/GroupManager.php index 17ab71fe2..05311b98b 100644 --- a/lib/GroupManager.php +++ b/lib/GroupManager.php @@ -10,18 +10,17 @@ use OCA\User_SAML\Exceptions\GroupNotFoundException; use OCA\User_SAML\Exceptions\NonMigratableGroupException; use OCA\User_SAML\Jobs\MigrateGroups; +use OCP\AppFramework\Services\IAppConfig; use OCP\BackgroundJob\IJobList; use OCP\EventDispatcher\IEventDispatcher; use OCP\Group\Events\BeforeGroupCreatedEvent; use OCP\Group\Events\BeforeGroupDeletedEvent; use OCP\Group\Events\GroupCreatedEvent; use OCP\Group\Events\GroupDeletedEvent; -use OCP\IConfig; use OCP\IDBConnection; use OCP\IGroup; use OCP\IGroupManager; use OCP\IUser; -use OCP\Server; use Psr\Log\LoggerInterface; class GroupManager { @@ -32,10 +31,11 @@ public function __construct( protected IDBConnection $db, private readonly IGroupManager $groupManager, private readonly GroupBackend $ownGroupBackend, - private readonly IConfig $config, + private readonly IAppConfig $appConfig, private readonly IEventDispatcher $dispatcher, private readonly IJobList $jobList, private readonly SAMLSettings $settings, + private readonly LoggerInterface $logger, ) { } @@ -47,7 +47,7 @@ public function __construct( private function getGroupsToRemove(array $samlGroupNames, array $assignedGroups): array { $groupsToRemove = []; foreach ($assignedGroups as $group) { - Server::get(LoggerInterface::class)->debug('Checking group {group} for removal', ['app' => 'user_saml', 'group' => $group->getGID()]); + $this->logger->debug('Checking group {group} for removal', ['app' => 'user_saml', 'group' => $group->getGID()]); if (in_array($group->getGID(), $samlGroupNames, true)) { continue; } @@ -69,10 +69,20 @@ private function getGroupsToRemove(array $samlGroupNames, array $assignedGroups) private function getGroupsToAdd(array $samlGroupNames, array $assignedGroupIds): array { $groupsToAdd = []; foreach ($samlGroupNames as $groupName) { - Server::get(LoggerInterface::class)->debug('Checking group {group} for addition', ['app' => 'user_saml', 'group' => $groupName]); + $this->logger->debug('Checking group {group} for addition', ['app' => 'user_saml', 'group' => $groupName]); + + // if user is not assigned to the group + if (!in_array($groupName, $assignedGroupIds)) { + $groupsToAdd[] = $groupName; + continue; + } + $group = $this->groupManager->get($groupName); - // if user is not assigned to the group or the provided group has a non SAML backend - if (!in_array($groupName, $assignedGroupIds) || !$this->hasSamlBackend($group)) { + if ($group === null) { + throw new GroupNotFoundException(); + } + // if the provided group has a non SAML backend + if (!$this->hasSamlBackend($group)) { $groupsToAdd[] = $groupName; } elseif ($this->mayModifyGroup($group)) { $groupsToAdd[] = $group->getGID(); @@ -126,15 +136,14 @@ protected function unassignUserFromGroup(IUser $user, string $gid): void { } // keep empty groups if general-keep_groups is set to 1 - $keepEmptyGroups = $this->config->getAppValue( - 'user_saml', + $keepEmptyGroups = $this->appConfig->getAppValueInt( 'general-keep_groups', - '0', + 0, ); if ($this->hasSamlBackend($group)) { $this->ownGroupBackend->removeFromGroup($user->getUID(), $group->getGID()); - if ($keepEmptyGroups !== '1' && $this->ownGroupBackend->countUsersInGroup($gid) === 0) { + if ($keepEmptyGroups !== 1 && $this->ownGroupBackend->countUsersInGroup($gid) === 0) { $this->dispatcher->dispatchTyped(new BeforeGroupDeletedEvent($group)); $this->ownGroupBackend->deleteGroup($group->getGID()); $this->dispatcher->dispatchTyped(new GroupDeletedEvent($group)); @@ -158,6 +167,9 @@ protected function assignUserToGroup(IUser $user, string $gid): void { $settings = $this->settings->get($providerId); $groupPrefix = $settings['saml-attribute-mapping-group_mapping_prefix'] ?? SAMLSettings::DEFAULT_GROUP_PREFIX; $group = $this->createGroupInBackend($groupPrefix . $gid, $gid); + if ($group === null) { + throw new \RuntimeException('Could not create group ' . $groupPrefix . $gid); + } } $group->addUser($user); @@ -170,6 +182,9 @@ protected function createGroupInBackend(string $gid, ?string $originalGid = null } $group = $this->groupManager->get($gid); + if ($group === null) { + throw new GroupNotFoundException('Could not found group ' . $gid); + } $this->dispatcher->dispatchTyped(new GroupCreatedEvent($group)); return $group; @@ -179,30 +194,26 @@ protected function createGroupInBackend(string $gid, ?string $originalGid = null * @throws GroupNotFoundException|NonMigratableGroupException */ protected function findGroup(string $gid): IGroup { - $migrationAllowListRaw = $this->config->getAppValue( - 'user_saml', + $migrationAllowListRaw = $this->appConfig->getAppValueString( GroupManager::LOCAL_GROUPS_CHECK_FOR_MIGRATION, - '' ); $strictBackendCheck = $migrationAllowListRaw === ''; $migrationAllowList = null; - if ($migrationAllowListRaw !== '' || $migrationAllowListRaw !== self::STATE_MIGRATION_PHASE_EXPIRED) { + if ($migrationAllowListRaw !== '' && $migrationAllowListRaw !== self::STATE_MIGRATION_PHASE_EXPIRED) { /** @var array{dropAfter: int, groups: string[]} $migrationAllowList */ $migrationAllowList = \json_decode($migrationAllowListRaw, true); } - if (!$strictBackendCheck && in_array($gid, $migrationAllowList['groups'] ?? [], true)) { - $group = $this->groupManager->get($gid); - if ($group === null) { - throw new GroupNotFoundException(); - } - return $group; - } $group = $this->groupManager->get($gid); if ($group === null) { throw new GroupNotFoundException(); } + + if (!$strictBackendCheck && in_array($gid, $migrationAllowList['groups'] ?? [], true)) { + return $group; + } + if ($this->hasSamlBackend($group)) { return $group; } @@ -244,14 +255,14 @@ protected function isGroupInTransitionList(string $groupId): bool { * @return array{dropAfter: int, groups: string[]}|null */ public function getCandidateInfoIfValid(): ?array { - $candidateInfo = $this->config->getAppValue('user_saml', self::LOCAL_GROUPS_CHECK_FOR_MIGRATION, ''); + $candidateInfo = $this->appConfig->getAppValueString(self::LOCAL_GROUPS_CHECK_FOR_MIGRATION); if ($candidateInfo === '' || $candidateInfo === self::STATE_MIGRATION_PHASE_EXPIRED) { return null; } - /** @var array{dropAfter: int, groups: string[]} $candidateInfo */ $candidateInfo = \json_decode($candidateInfo, true); + /** @var array{dropAfter: int, groups: string[]} $candidateInfo */ if (!isset($candidateInfo['dropAfter']) || $candidateInfo['dropAfter'] < time()) { - $this->config->setAppValue('user_saml', self::LOCAL_GROUPS_CHECK_FOR_MIGRATION, self::STATE_MIGRATION_PHASE_EXPIRED); + $this->appConfig->setAppValueString(self::LOCAL_GROUPS_CHECK_FOR_MIGRATION, self::STATE_MIGRATION_PHASE_EXPIRED); return null; } @@ -279,19 +290,21 @@ protected function mayModifyGroup(?IGroup $group): bool { && in_array('Database', $group->getBackendNames()) && $this->isGroupInTransitionList($group->getGID()); - if ($isInTransition) { - Server::get(LoggerInterface::class)->debug('Checking group {group} for foreign members', ['app' => 'user_saml', 'group' => $group->getGID()]); - $hasOnlySamlUsers = !$this->hasGroupForeignMembers($group); - Server::get(LoggerInterface::class)->debug('Completed checking group {group} for foreign members', ['app' => 'user_saml', 'group' => $group->getGID()]); - if (!$hasOnlySamlUsers) { - $this->updateCandidatePool([$group->getGID()]); - } + if (!$isInTransition) { + return false; + } + + $this->logger->debug('Checking group {group} for foreign members', ['app' => 'user_saml', 'group' => $group->getGID()]); + $hasOnlySamlUsers = !$this->hasGroupForeignMembers($group); + $this->logger->debug('Completed checking group {group} for foreign members', ['app' => 'user_saml', 'group' => $group->getGID()]); + if (!$hasOnlySamlUsers) { + $this->updateCandidatePool([$group->getGID()]); } - return $isInTransition && $hasOnlySamlUsers; + return $hasOnlySamlUsers; } public function updateCandidatePool(array $migratedGroups): void { - $candidateInfo = $this->config->getAppValue('user_saml', self::LOCAL_GROUPS_CHECK_FOR_MIGRATION, ''); + $candidateInfo = $this->appConfig->getAppValueString(self::LOCAL_GROUPS_CHECK_FOR_MIGRATION); if ($candidateInfo === '' || $candidateInfo === self::STATE_MIGRATION_PHASE_EXPIRED) { return; } @@ -300,8 +313,7 @@ public function updateCandidatePool(array $migratedGroups): void { return; } $candidateInfo['groups'] = array_diff($candidateInfo['groups'], $migratedGroups); - $this->config->setAppValue( - 'user_saml', + $this->appConfig->setAppValueString( self::LOCAL_GROUPS_CHECK_FOR_MIGRATION, json_encode($candidateInfo) ); diff --git a/lib/Listener/LoadAdditionalScriptsListener.php b/lib/Listener/LoadAdditionalScriptsListener.php index 470f955c9..14b24e54e 100644 --- a/lib/Listener/LoadAdditionalScriptsListener.php +++ b/lib/Listener/LoadAdditionalScriptsListener.php @@ -36,6 +36,9 @@ public function handle(Event $event): void { } $user = $this->userSession->getUser(); + if ($user === null) { + return; // already checked by $event->isLoggedIn above + } $timezoneDB = $this->config->getUserValue($user->getUID(), 'core', 'timezone', ''); if ($timezoneDB === '' || !$this->session->exists('timezone')) { diff --git a/lib/Migration/Version5000Date20211025124248.php b/lib/Migration/Version5000Date20211025124248.php index 1aa76be1c..741afbca8 100644 --- a/lib/Migration/Version5000Date20211025124248.php +++ b/lib/Migration/Version5000Date20211025124248.php @@ -108,6 +108,7 @@ public function postSchemaChange(IOutput $output, Closure $schemaClosure, array $prefixes = $this->fetchPrefixes(); foreach ($prefixes as $prefix) { $keyStart = $prefix === 1 ? '' : $prefix . '-'; + /** @var list $configKeys */ $configKeys = array_reduce( self::IDP_CONFIG_KEYS, function (array $carry, string $rawConfigKey) use ($keyStart): array { diff --git a/lib/SAMLSettings.php b/lib/SAMLSettings.php index 8f409bfd7..24ec605b4 100644 --- a/lib/SAMLSettings.php +++ b/lib/SAMLSettings.php @@ -9,6 +9,7 @@ use InvalidArgumentException; use OCA\User_SAML\Db\ConfigurationsMapper; +use OCP\AppFramework\Services\IAppConfig; use OCP\DB\Exception; use OCP\IConfig; use OCP\ISession; @@ -70,13 +71,14 @@ class SAMLSettings { public const DEFAULT_GROUP_PREFIX = 'SAML_'; /** @var array> */ - private $configurations = []; - /** @var int */ - private $configurationsLoadedState = self::LOADED_NONE; + private array $configurations = []; + /** @var self::LOADED_* $configurationsLoadedState */ + private int $configurationsLoadedState = self::LOADED_NONE; public function __construct( private readonly IURLGenerator $urlGenerator, private readonly IConfig $config, + private readonly IAppConfig $appConfig, private readonly ISession $session, private readonly ConfigurationsMapper $mapper, ) { @@ -104,9 +106,9 @@ public function getListOfIdps(): array { * Check if multiple user back ends are allowed */ public function allowMultipleUserBackEnds(): bool { - $type = $this->config->getAppValue('user_saml', 'type'); - $setting = $this->config->getAppValue('user_saml', 'general-allow_multiple_user_back_ends', '0'); - return ($setting === '1' && $type === 'saml'); + $type = $this->appConfig->getAppValueString('type'); + $setting = $this->appConfig->getAppValueInt('general-allow_multiple_user_back_ends'); + return $setting === 1 && $type === 'saml'; } public function usesSloWebServerDecode(int $idp): bool { @@ -124,7 +126,7 @@ public function getOneLoginSettingsArray(int $idp): array { $settings = [ 'strict' => true, - 'debug' => $this->config->getSystemValueBool('debug', false), + 'debug' => $this->config->getSystemValueBool('debug'), 'baseurl' => $this->urlGenerator->linkToRouteAbsolute('user_saml.SAML.base'), 'security' => [ 'nameIdEncrypted' => ($this->configurations[$idp]['security-nameIdEncrypted'] ?? '0') === '1', diff --git a/lib/Settings/Admin.php b/lib/Settings/Admin.php index 8f51616e7..4072baeda 100644 --- a/lib/Settings/Admin.php +++ b/lib/Settings/Admin.php @@ -1,5 +1,7 @@ samlSettings->getListOfIdps(); $providers = []; foreach ($providerIds as $id => $name) { @@ -188,13 +188,13 @@ public function getForm() { $nameIdFormats[Constants::NAMEID_UNSPECIFIED]['selected'] = true; } - $type = $this->config->getAppValue('user_saml', 'type'); + $type = $this->appConfig->getAppValueString( 'type'); $generalSettings['require_provisioned_account'] = [ 'text' => $this->l10n->t('Only allow authentication if an account exists on some other backend (e.g. LDAP).', [$this->defaults->getName()]), 'type' => 'checkbox', 'global' => true, - 'value' => $this->config->getAppValue('user_saml', 'general-require_provisioned_account', '0') + 'value' => $this->appConfig->getAppValueInt('general-require_provisioned_account'), ]; if ($type === 'saml') { $generalSettings['idp0_display_name'] = [ @@ -213,7 +213,7 @@ public function getForm() { 'type' => 'checkbox', 'hideForEnv' => true, 'global' => true, - 'value' => $this->config->getAppValue('user_saml', 'general-allow_multiple_user_back_ends', '0') + 'value' => $this->appConfig->getAppValueInt('general-allow_multiple_user_back_ends' ) ]; } @@ -234,21 +234,13 @@ public function getForm() { return new TemplateResponse('user_saml', 'admin', $params); } - /** - * @return string the section ID, e.g. 'sharing' - */ - public function getSection() { + #[Override] + public function getSection(): string { return 'saml'; } - /** - * @return int whether the form should be rather on the top or bottom of - * the admin section. The forms are arranged in ascending order of the - * priority values. It is required to return a value between 0 and 100. - * - * keep the server setting at the top, right after "server settings" - */ - public function getPriority() { + #[Override] + public function getPriority(): int { return 0; } } diff --git a/lib/UserBackend.php b/lib/UserBackend.php index ddff91afe..3212c3908 100644 --- a/lib/UserBackend.php +++ b/lib/UserBackend.php @@ -1,5 +1,7 @@ db->getQueryBuilder(); @@ -69,9 +74,6 @@ protected function userExistsInDatabase(string $uid): bool { /** * Creates a user if it does not exist. In case home directory mapping * is enabled we also set up the user's home from $attributes. - * - * @param string $uid - * @param array $attributes */ public function createUserIfNotExists(string $uid, array $attributes = []): void { if (!$this->userExistsInDatabase($uid)) { @@ -90,7 +92,7 @@ public function createUserIfNotExists(string $uid, array $attributes = []): void //if attribute's value is an absolute path take this, otherwise append it to data dir //check for / at the beginning or pattern c:\ resp. c:/ if ($home[0] !== '/' - && !(strlen((string)$home) > 3 && ctype_alpha((string)$home[0]) + && !(strlen($home) > 3 && ctype_alpha($home[0]) && $home[1] === ':' && ($home[2] === '\\' || $home[2] === '/')) ) { $home = $this->config->getSystemValueString('datadirectory', @@ -117,7 +119,8 @@ public function createUserIfNotExists(string $uid, array $attributes = []): void public function initializeHomeDir(string $uid): void { ### Code taken from lib/private/User/Session.php - function prepareUserLogin() ### //trigger creation of user home and /files folder - $userFolder = \OC::$server->getUserFolder($uid); + $userFolder = Server::get(IRootFolder::class) + ->getUserFolder($uid); try { // copy skeleton \OC_Util::copySkeleton($uid, $userFolder); @@ -126,16 +129,14 @@ public function initializeHomeDir(string $uid): void { } // trigger any other initialization $user = $this->userManager->get($uid); + if ($user === null) { + throw new \LogicException('Trying to initialize home dir for a non-existent user'); + } $this->eventDispatcher->dispatchTyped(new UserFirstTimeLoggedInEvent($user)); } - /** - * delete a user - * @param string $uid The username of the user to delete - * @return bool - * @since 4.5.0 - */ - public function deleteUser($uid) { + #[Override] + public function deleteUser($uid): bool { $qb = $this->db->getQueryBuilder(); $affected = $qb->delete('user_saml_users') ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid))) @@ -143,13 +144,8 @@ public function deleteUser($uid) { return $affected > 0; } - /** - * Returns the user's home directory, if home directory mapping is set up. - * - * @param string $uid the username - * @return string|bool - */ - public function getHome(string $uid) { + #[Override] + public function getHome(string $uid): string|false { $qb = $this->db->getQueryBuilder(); $qb->select('home') ->from('user_saml_users') @@ -161,16 +157,8 @@ public function getHome(string $uid) { return $users[0]['home'] ?? false; } - /** - * Get a list of all users - * - * @param string $search - * @param null|int $limit - * @param null|int $offset - * @return string[] an array of all uids - * @since 4.5.0 - */ - public function getUsers($search = '', $limit = null, $offset = null) { + #[Override] + public function getUsers($search = '', $limit = null, $offset = null): array { // shamelessly duplicated from \OC\User\Database $users = $this->getDisplayNames($search, $limit, $offset); $userIds = array_map(fn ($uid) => (string)$uid, array_keys($users)); @@ -178,13 +166,8 @@ public function getUsers($search = '', $limit = null, $offset = null) { return $userIds; } - /** - * check if a user exists - * @param string $uid the username - * @return boolean - * @since 4.5.0 - */ - public function userExists($uid) { + #[Override] + public function userExists($uid): bool { if ($backend = $this->getActualUserBackend($uid)) { return $backend->userExists($uid); } else { @@ -192,8 +175,10 @@ public function userExists($uid) { } } - public function setDisplayName($uid, $displayName) { + #[Override] + public function setDisplayName($uid, $displayName): bool { if ($backend = $this->getActualUserBackend($uid)) { + /** @var ISetDisplayNameBackend $backend */ return $backend->setDisplayName($uid, $displayName); } @@ -205,13 +190,7 @@ public function setDisplayName($uid, $displayName) { return $affected > 0; } - /** - * Get display name of the user - * - * @param string $uid user ID of the user - * @return string display name - * @since 14.0.0 - */ + #[Override] public function getDisplayName($uid): string { if ($backend = $this->getActualUserBackend($uid)) { return $backend->getDisplayName($uid); @@ -228,16 +207,8 @@ public function getDisplayName($uid): string { return $users[0]['displayname'] ?? $uid; } - /** - * Get a list of all display names and user ids. - * - * @param string $search - * @param string|null $limit - * @param string|null $offset - * @return array an array of all displayNames (value) and the corresponding uids (key) - * @since 4.5.0 - */ - public function getDisplayNames($search = '', $limit = null, $offset = null) { + #[Override] + public function getDisplayNames($search = '', $limit = null, $offset = null): array { // shamelessly duplicate from \OC\User\Database $query = $this->db->getQueryBuilder(); @@ -254,8 +225,11 @@ public function getDisplayNames($search = '', $limit = null, $offset = null) { ->orWhere($query->expr()->iLike('configvalue', $query->createPositionalParameter('%' . $this->db->escapeLikeParameter($search) . '%'))) ->orderBy($query->func()->lower('displayname'), 'ASC') ->addOrderBy('uid', 'ASC') - ->setMaxResults($limit) - ->setFirstResult($offset); + ->setMaxResults($limit); + + if ($offset !== null) { + $query->setFirstResult($offset); + } $result = $query->executeQuery(); $displayNames = []; @@ -267,33 +241,18 @@ public function getDisplayNames($search = '', $limit = null, $offset = null) { return $displayNames; } - /** - * Check if a user list is available or not - * @return boolean if users can be listed or not - * @since 4.5.0 - */ - public function hasUserListings() { - if ($this->autoprovisionAllowed()) { - return true; - } - - return false; + #[Override] + public function hasUserListings(): bool { + return $this->autoprovisionAllowed(); } - /** - * In case the user has been authenticated by Apache true is returned. - * - * @return boolean whether Apache reports a user as currently logged in. - * @since 6.0.0 - */ - public function isSessionActive() { + #[Override] + public function isSessionActive(): bool { return $this->session->get('user_saml.samlUserData') !== null; } - /** - * {@inheritdoc} - */ - public function getLogoutUrl() { + #[Override] + public function getLogoutUrl(): string { $id = $this->settings->getProviderId(); $settings = $this->settings->get($id); $slo = $settings['idp-singleLogoutService.url'] ?? ''; @@ -312,7 +271,19 @@ public function getLogoutUrl() { } /** - * return user data from the idp + * Return user data from the idp + * + * @return array{ + * formatted: array{ + * email: ?string, + * displayName: ?string, + * quota: ?string, + * groups: ?list, + * mfaVerified: ?string, + * uid: non-empty-string, + * }, + * raw: array, + * } */ public function getUserData(): array { $userData = $this->session->get('user_saml.samlUserData'); @@ -320,17 +291,29 @@ public function getUserData(): array { // make sure that a valid UID is given if (empty($userData['formatted']['uid'])) { - $this->logger->error('No valid uid given, please check your attribute mapping. Got uid: {uid}', ['app' => 'user_saml', 'uid' => $userData['uid']]); - throw new \InvalidArgumentException('No valid uid given, please check your attribute mapping. Got uid: ' . $userData['uid']); + $this->logger->error('No valid uid given, please check your attribute mapping. Got uid: {uid}', ['app' => 'user_saml', 'uid' => $userData['formatted']['uid']]); + throw new \InvalidArgumentException('No valid uid given, please check your attribute mapping. Got uid: ' . $userData['formatted']['uid']); } return $userData; } /** - * format user data and map them to the configured attributes + * Format user data and map them to the configured attributes + * + * @return array{ + * formatted: array{ + * email: ?string, + * displayName: ?string, + * quota: ?string, + * groups: ?list, + * mfaVerified: ?string, + * uid: string, + * }, + * raw: array, + * } */ - private function formatUserData($attributes): array { + private function formatUserData(array $attributes): array { $this->userData->setAttributes($attributes); $result = ['formatted' => [], 'raw' => $attributes]; @@ -371,12 +354,8 @@ private function formatUserData($attributes): array { return $result; } - /** - * Return the id of the current user - * @return string - * @since 6.0.0 - */ - public function getCurrentUserId() { + #[Override] + public function getCurrentUserId(): string { $user = Server::get(IUserSession::class)->getUser(); if ($user instanceof IUser && $this->session->get('user_saml.samlUserData')) { @@ -394,12 +373,8 @@ public function getCurrentUserId() { } - /** - * Backend name to be shown in user management - * @return string the name of the backend to be shown - * @since 8.0.0 - */ - public function getBackendName() { + #[Override] + public function getBackendName(): string { return 'user_saml'; } @@ -407,7 +382,7 @@ public function getBackendName() { * Whether autoprovisioning is enabled or not */ public function autoprovisionAllowed(): bool { - return $this->config->getAppValue('user_saml', 'general-require_provisioned_account', '0') === '0'; + return $this->appConfig->getAppValueInt('general-require_provisioned_account') === 0; } /** @@ -438,10 +413,11 @@ public function registerBackends(array $backends): void { /** * @throws \OCP\DB\Exception + * @return string[] */ - private function getAttributeKeys($name) { + private function getAttributeKeys(string $name): array { $settings = $this->settings->get($this->settings->getProviderId()); - $keys = explode(' ', $settings[$name] ?? $this->config->getAppValue('user_saml', $name, '')); + $keys = explode(' ', $settings[$name] ?? $this->appConfig->getAppValueString($name, '')); if (count($keys) === 1 && $keys[0] === '') { throw new \InvalidArgumentException('Attribute is not configured'); @@ -449,7 +425,7 @@ private function getAttributeKeys($name) { return $keys; } - private function getAttributeValue($name, array $attributes) { + private function getAttributeValue(string $name, array $attributes): string { $keys = $this->getAttributeKeys($name); $value = ''; diff --git a/lib/UserData.php b/lib/UserData.php index def1b7a34..f17a98dac 100644 --- a/lib/UserData.php +++ b/lib/UserData.php @@ -12,8 +12,7 @@ class UserData { private $uid; - /** @var array */ - private $attributes; + private ?array $attributes = null; public function __construct( private readonly UserResolver $userResolver, @@ -58,6 +57,9 @@ public function getEffectiveUid(): string { return $uid; } + /** + * @return list + */ public function getGroups(): array { $this->assertIsInitialized(); $mapping = $this->getProviderSettings()['saml-attribute-mapping-group_mapping'] ?? null; @@ -65,9 +67,13 @@ public function getGroups(): array { return []; } - return is_array($this->attributes[$mapping]) - ? $this->attributes[$mapping] - : array_map('trim', explode(',', (string)$this->attributes[$mapping])); + if (is_array($this->attributes[$mapping])) { + /** @var list $groups */ + $groups = $this->attributes[$mapping]; + return $groups; + } + + return array_map('trim', explode(',', (string)$this->attributes[$mapping])); } protected function extractSamlUserId(): string { @@ -129,7 +135,10 @@ protected function convertObjectGUID2Str($oguid): string { return strtoupper($hex_guid_to_guid_str); } - protected function assertIsInitialized() { + /** + * @psalm-assert array $this->attributes + */ + protected function assertIsInitialized(): void { if ($this->attributes === null) { throw new \LogicException('UserData have to be initialized with setAttributes first'); } diff --git a/psalm.xml b/psalm.xml index 22f08ade7..aefce95a2 100644 --- a/psalm.xml +++ b/psalm.xml @@ -4,7 +4,7 @@ - SPDX-License-Identifier: AGPL-3.0-or-later --> + + + + + + + + diff --git a/tests/psalm-baseline.xml b/tests/psalm-baseline.xml index 4dfbc8211..21702d2dc 100644 --- a/tests/psalm-baseline.xml +++ b/tests/psalm-baseline.xml @@ -4,25 +4,6 @@ - SPDX-License-Identifier: AGPL-3.0-or-later --> - - - - - - - - - - - - - - - - - - - @@ -32,23 +13,4 @@ - - - - - - - - - - - - - - - - - - - diff --git a/tests/stub.phpstub b/tests/stub.phpstub index 40d5235bf..8f78d3f91 100644 --- a/tests/stub.phpstub +++ b/tests/stub.phpstub @@ -87,3 +87,7 @@ class OC_User { public static function useBackend($userBackend): void; public static function handleApacheAuth(): void; } + +class OC_Util { + public static function copySkeleton(string $userId, \OCP\Files\Folder $userDirectory): void { } +} diff --git a/tests/stubs/oc.php b/tests/stubs/oc.php new file mode 100644 index 000000000..7d094c408 --- /dev/null +++ b/tests/stubs/oc.php @@ -0,0 +1,122 @@ + filename + */ + public static array $CLASSPATH = []; + /** + * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) + */ + public static string $SERVERROOT = ''; + /** + * the Nextcloud root path for http requests (e.g. /nextcloud) + */ + public static string $WEBROOT = ''; + /** + * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and + * web path in 'url' + */ + public static array $APPSROOTS = []; + + public static string $configDir; + + /** + * requested app + */ + public static string $REQUESTEDAPP = ''; + + /** + * check if Nextcloud runs in cli mode + */ + public static bool $CLI = false; + + public static \OC\Autoloader $loader; + + public static \Composer\Autoload\ClassLoader $composerAutoloader; + + public static \OC\Server $server; + + /** + * @throws \RuntimeException when the 3rdparty directory is missing or + * the app path list is empty or contains an invalid path + */ + public static function initPaths(): void { + } + + public static function checkConfig(): void { + } + + public static function checkInstalled(\OC\SystemConfig $systemConfig): void { + } + + public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void { + } + + public static function initSession(): void { + } + + /** + * @return bool true if the session expiry should only be done by gc instead of an explicit timeout + */ + public static function hasSessionRelaxedExpiry(): bool { + } + + /** + * Try to set some values to the required Nextcloud default + */ + public static function setRequiredIniValues(): void { + } + + public static function init(): void { + } + + /** + * register hooks for the cleanup of cache and bruteforce protection + */ + public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void { + } + + /** + * register hooks for sharing + */ + public static function registerShareHooks(\OC\SystemConfig $systemConfig): void { + } + + protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void { + } + + /** + * Handle the request + */ + public static function handleRequest(): void { + } + + /** + * Check login: apache auth, auth token, basic auth + */ + public static function handleLogin(OCP\IRequest $request): bool { + } + + protected static function handleAuthHeaders(): void { + } + + protected static function tryAppAPILogin(OCP\IRequest $request): bool { + } +} + +OC::init(); diff --git a/tests/stubs/oc_core_controller_clientflowlogincontroller.php b/tests/stubs/oc_core_controller_clientflowlogincontroller.php new file mode 100644 index 000000000..63ee41330 --- /dev/null +++ b/tests/stubs/oc_core_controller_clientflowlogincontroller.php @@ -0,0 +1,13 @@ +db = $this->createMock(IDBConnection::class); $this->groupManager = $this->createMock(Manager::class); $this->ownGroupBackend = $this->createMock(GroupBackend::class); - $this->config = $this->createMock(IConfig::class); + $this->appConfig = $this->createMock(IAppConfig::class); $this->eventDispatcher = $this->createMock(IEventDispatcher::class); - $this->jobList = $this->createMock(JobList::class); + $this->jobList = $this->createMock(IJobList::class); $this->settings = $this->createMock(SAMLSettings::class); $this->ownGroupManager = $this->createMock(GroupManager::class); + $this->logger = $this->createMock(LoggerInterface::class); } public function getGroupManager(array $mockedFunctions = []) { @@ -63,10 +58,11 @@ public function getGroupManager(array $mockedFunctions = []) { $this->db, $this->groupManager, $this->ownGroupBackend, - $this->config, + $this->appConfig, $this->eventDispatcher, $this->jobList, - $this->settings + $this->settings, + $this->logger, ]) ->onlyMethods($mockedFunctions) ->getMock(); @@ -75,10 +71,11 @@ public function getGroupManager(array $mockedFunctions = []) { $this->db, $this->groupManager, $this->ownGroupBackend, - $this->config, + $this->appConfig, $this->eventDispatcher, $this->jobList, - $this->settings + $this->settings, + $this->logger, ); } } @@ -89,9 +86,9 @@ public function testUpdateUserGroups() { // from GroupA and assigned to GroupC, while the GroupB association remains // unchanged. - $this->config->expects($this->any()) - ->method('getAppValue') - ->with('user_saml', GroupManager::LOCAL_GROUPS_CHECK_FOR_MIGRATION, '') + $this->appConfig->expects($this->any()) + ->method('getAppValueString') + ->with(GroupManager::LOCAL_GROUPS_CHECK_FOR_MIGRATION) ->willReturn(\json_encode(['groups' => ['groupA'], 'dropAfter' => time() + 2000])); $this->getGroupManager(['handleUserUnassignedFromGroups', 'handleUserAssignedToGroups', 'translateGroupToIds', 'hasSamlBackend']); @@ -186,11 +183,11 @@ public function testUnassignUserFromGroups() { public function testUnassignUserFromGroupsWithKeepEmpytGroups() { $this->getGroupManager(); // set general-keep_groups to 1 and assert it was read - $this->config + $this->appConfig ->expects($this->exactly(1)) - ->method('getAppValue') - ->with('user_saml', 'general-keep_groups', '0') - ->willReturn('1'); + ->method('getAppValueInt') + ->with('general-keep_groups', 0) + ->willReturn(1); // create user and group mock $user = $this->createMock(IUser::class); $groupA = $this->createMock(IGroup::class); @@ -230,10 +227,10 @@ public function testAssignUserToGroups() { $user = $this->createMock(IUser::class); $groupA = $this->createMock(IGroup::class); - $this->config->expects($this->any()) - ->method('getAppValue') - ->with('user_saml', GroupManager::LOCAL_GROUPS_CHECK_FOR_MIGRATION, '') - ->willReturnArgument(2); + $this->appConfig->expects($this->any()) + ->method('getAppValueString') + ->with(GroupManager::LOCAL_GROUPS_CHECK_FOR_MIGRATION) + ->willReturnArgument(1); // assert group already exists $this->groupManager @@ -261,10 +258,10 @@ public function testAssignUserToNonExistingGroups() { $user = $this->createMock(IUser::class); $groupB = $this->createMock(IGroup::class); - $this->config->expects($this->any()) - ->method('getAppValue') - ->with('user_saml', GroupManager::LOCAL_GROUPS_CHECK_FOR_MIGRATION, '') - ->willReturnArgument(2); + $this->appConfig->expects($this->any()) + ->method('getAppValueString') + ->with(GroupManager::LOCAL_GROUPS_CHECK_FOR_MIGRATION) + ->willReturnArgument(1); // assert group does not exist $this->groupManager @@ -295,10 +292,10 @@ public function testAssignUserToGroupsWithCollision() { $user = $this->createMock(IUser::class); $groupC = $this->createMock(IGroup::class); - $this->config->expects($this->any()) - ->method('getAppValue') - ->with('user_saml', GroupManager::LOCAL_GROUPS_CHECK_FOR_MIGRATION, '') - ->willReturnArgument(2); + $this->appConfig->expects($this->any()) + ->method('getAppValueString') + ->with(GroupManager::LOCAL_GROUPS_CHECK_FOR_MIGRATION) + ->willReturnArgument(1); // assert group exists $this->groupManager diff --git a/tests/unit/Settings/AdminTest.php b/tests/unit/Settings/AdminTest.php index 87e6a543e..ea70327f6 100644 --- a/tests/unit/Settings/AdminTest.php +++ b/tests/unit/Settings/AdminTest.php @@ -1,5 +1,7 @@ l10n = $this->createMock(IL10N::class); $this->defaults = $this->createMock(Defaults::class); - $this->config = $this->createMock(IConfig::class); + $this->appConfig = $this->createMock(IAppConfig::class); $this->settings = $this->createMock(SAMLSettings::class); $this->admin = new Admin( $this->l10n, $this->defaults, - $this->config, + $this->appConfig, $this->settings ); @@ -212,7 +209,7 @@ public function formDataProvider() { ], ]; - $params = [ + return [ 'sp' => $serviceProviderFields, 'security-offer' => $securityOfferFields, 'security-required' => $securityRequiredFields, @@ -227,8 +224,6 @@ public function formDataProvider() { 'name-id-formats' => $nameIdFormats, 'config' => [], ]; - - return $params; } public function testGetFormWithoutType() { @@ -238,11 +233,17 @@ public function testGetFormWithoutType() { 1 => 'Provider 1', 2 => 'Provider 2', ]); - $this->config - ->expects($this->exactly(2)) // 'type' and 'general-require_provisioned_account' - ->method('getAppValue') - ->with('user_saml', $this->anything(), $this->anything()) - ->willReturn($this->returnArgument(2)); + $this->appConfig + ->expects($this->exactly(1)) // 'type' + ->method('getAppValueString') + ->with($this->anything(), $this->anything()) + ->willReturn($this->returnArgument(1)); + + $this->appConfig + ->expects($this->exactly(1)) // 'general-require_provisioned_account' + ->method('getAppValueInt') + ->with($this->anything(), $this->anything()) + ->willReturn($this->returnArgument(1)); $params = $this->formDataProvider(); unset($params['general']['idp0_display_name'], $params['general']['is_saml_request_using_post'], $params['general']['allow_multiple_user_back_ends']); @@ -259,15 +260,20 @@ public function testGetFormWithSaml() { 1 => 'Provider 1', 2 => 'Provider 2', ]); - $this->config - ->expects($this->exactly(3)) # mode + three global values - ->method('getAppValue') + $this->appConfig + ->expects($this->exactly(1)) + ->method('getAppValueString') + ->with('type') + ->willReturn('saml'); + + $this->appConfig + ->expects($this->exactly(2)) + ->method('getAppValueInt') ->withConsecutive( - ['user_saml', 'type'], - ['user_saml', 'general-require_provisioned_account'], - ['user_saml', 'general-allow_multiple_user_back_ends'], + ['general-require_provisioned_account'], + ['general-allow_multiple_user_back_ends'], ) - ->willReturnOnConsecutiveCalls('saml', '0', '0'); + ->willReturnOnConsecutiveCalls(0, 0); $this->defaults ->expects($this->any()) ->method('getName') @@ -275,8 +281,8 @@ public function testGetFormWithSaml() { $params = $this->formDataProvider(); $params['type'] = 'saml'; - $params['general']['require_provisioned_account']['value'] = '0'; - $params['general']['allow_multiple_user_back_ends']['value'] = '0'; + $params['general']['require_provisioned_account']['value'] = 0; + $params['general']['allow_multiple_user_back_ends']['value'] = 0; $expected = new TemplateResponse('user_saml', 'admin', $params); $this->assertEquals($expected, $this->admin->getForm()); diff --git a/tests/unit/UserBackendTest.php b/tests/unit/UserBackendTest.php index 25a47a61f..1bf8a2cbc 100644 --- a/tests/unit/UserBackendTest.php +++ b/tests/unit/UserBackendTest.php @@ -1,5 +1,7 @@ config = $this->createMock(IConfig::class); + $this->appConfig = $this->createMock(IAppConfig::class); $this->urlGenerator = $this->createMock(IURLGenerator::class); $this->session = $this->createMock(ISession::class); $this->db = $this->createMock(IDBConnection::class); @@ -62,11 +56,15 @@ protected function setUp(): void { $this->eventDispatcher = $this->createMock(IEventDispatcher::class); } - public function getMockedBuilder(array $mockedFunctions = []) { + /** + * @psalm-assert UserBackend|MockObject $this->userBackend + */ + public function getMockedBuilder(array $mockedFunctions = []): void { if ($mockedFunctions !== []) { $this->userBackend = $this->getMockBuilder(UserBackend::class) ->setConstructorArgs([ $this->config, + $this->appConfig, $this->urlGenerator, $this->session, $this->db, @@ -82,6 +80,7 @@ public function getMockedBuilder(array $mockedFunctions = []) { } else { $this->userBackend = new UserBackend( $this->config, + $this->appConfig, $this->urlGenerator, $this->session, $this->db, @@ -95,21 +94,25 @@ public function getMockedBuilder(array $mockedFunctions = []) { } } - public function testGetBackendName() { + public function testGetBackendName(): void { $this->getMockedBuilder(); $this->assertSame('user_saml', $this->userBackend->getBackendName()); } - public function testUpdateAttributesWithoutAttributes() { + public function testUpdateAttributesWithoutAttributes(): void { $this->getMockedBuilder(['getDisplayName']); - /** @var IUser|MockObject $user */ $user = $this->createMock(IUser::class); - $this->config->method('getAppValue') - ->willReturnCallback(fn (string $appId, string $key, string $default) + $this->appConfig->method('getAppValueString') + ->willReturnCallback(fn (string $key, string $default) // Unused parameters are intentionally kept for clarity => $default); + $this->appConfig->method('getAppValueInt') + ->willReturnCallback(fn (string $key, int $default) + // Unused parameters are intentionally kept for clarity + => $default); + $this->userManager ->expects($this->once()) ->method('get') @@ -134,7 +137,7 @@ public function testUpdateAttributesWithoutAttributes() { $this->userBackend->updateAttributes('ExistingUser', []); } - public function testUpdateAttributesWithoutValidUser() { + public function testUpdateAttributesWithoutValidUser(): void { $this->getMockedBuilder(); $this->config->method('getAppValue') @@ -150,7 +153,7 @@ public function testUpdateAttributesWithoutValidUser() { $this->userBackend->updateAttributes('ExistingUser', []); } - public function testUpdateAttributes() { + public function testUpdateAttributes(): void { $this->getMockedBuilder(['getDisplayName', 'setDisplayName']); /** @var IUser|MockObject $user */ $user = $this->createMock(IUser::class); @@ -163,23 +166,16 @@ public function testUpdateAttributes() { ]; // Replace at() matcher with willReturnCallback to avoid deprecation warning - $this->config - ->method('getAppValue') - ->willReturnCallback(function ($appId, $key, $default) { - if ($appId === 'user_saml') { - switch ($key) { - case 'saml-attribute-mapping-email_mapping': - return 'email'; - case 'saml-attribute-mapping-displayName_mapping': - return 'displayname'; - case 'saml-attribute-mapping-quota_mapping': - return 'quota'; - case 'saml-attribute-mapping-group_mapping': - return 'groups'; - } - } - return $default; - }); + $this->appConfig + ->method('getAppValueString') + ->willReturnCallback(static fn (string $key, string $default) + => match ($key) { + 'saml-attribute-mapping-email_mapping' => 'email', + 'saml-attribute-mapping-displayName_mapping' => 'displayname', + 'saml-attribute-mapping-quota_mapping' => 'quota', + 'saml-attribute-mapping-group_mapping' => 'groups', + default => $default, + }); $this->userManager ->expects($this->once()) @@ -220,14 +216,14 @@ public function testUpdateAttributes() { $this->userBackend->updateAttributes('ExistingUser'); } - public function testUpdateAttributesQuotaDefaultFallback() { + public function testUpdateAttributesQuotaDefaultFallback(): void { $this->getMockedBuilder(['getDisplayName', 'setDisplayName']); /** @var IUser|MockObject $user */ $user = $this->createMock(IUser::class); $attributes = ['email' => 'new@example.com', 'displayname' => 'New Displayname', 'quota' => '']; - $this->config->method('getAppValue') - ->willReturnCallback(fn (string $appId, string $key, string $default) + $this->appConfig->method('getAppValueString') + ->willReturnCallback(static fn (string $key, string $default) // Unused $appId parameter is intentionally kept for clarity => match ($key) { 'saml-attribute-mapping-email_mapping' => 'email', diff --git a/vendor-bin/psalm/composer.json b/vendor-bin/psalm/composer.json index b205e3442..24414a384 100644 --- a/vendor-bin/psalm/composer.json +++ b/vendor-bin/psalm/composer.json @@ -1,12 +1,12 @@ { "require-dev": { - "nextcloud/ocp": "dev-stable28", + "nextcloud/ocp": "dev-stable30", "vimeo/psalm": "^5.26", "sabre/dav": "4.7.0" }, "config": { - "platform": { - "php": "8.1.32" - } + "platform": { + "php": "8.0.2" + } } } diff --git a/vendor-bin/psalm/composer.lock b/vendor-bin/psalm/composer.lock index bfa92e5e0..0c73f4456 100644 --- a/vendor-bin/psalm/composer.lock +++ b/vendor-bin/psalm/composer.lock @@ -4,21 +4,21 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "ed78ed32a8083cfab48ae511a90522ad", + "content-hash": "2194273f38cf70c0f59635d68154f249", "packages": [], "packages-dev": [ { "name": "amphp/amp", - "version": "v2.6.4", + "version": "v2.6.5", "source": { "type": "git", "url": "https://github.com/amphp/amp.git", - "reference": "ded3d9be08f526089eb7ee8d9f16a9768f9dec2d" + "reference": "d7dda98dae26e56f3f6fcfbf1c1f819c9a993207" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/amphp/amp/zipball/ded3d9be08f526089eb7ee8d9f16a9768f9dec2d", - "reference": "ded3d9be08f526089eb7ee8d9f16a9768f9dec2d", + "url": "https://api.github.com/repos/amphp/amp/zipball/d7dda98dae26e56f3f6fcfbf1c1f819c9a993207", + "reference": "d7dda98dae26e56f3f6fcfbf1c1f819c9a993207", "shasum": "" }, "require": { @@ -34,11 +34,6 @@ "vimeo/psalm": "^3.12" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.x-dev" - } - }, "autoload": { "files": [ "lib/functions.php", @@ -86,7 +81,7 @@ "support": { "irc": "irc://irc.freenode.org/amphp", "issues": "https://github.com/amphp/amp/issues", - "source": "https://github.com/amphp/amp/tree/v2.6.4" + "source": "https://github.com/amphp/amp/tree/v2.6.5" }, "funding": [ { @@ -94,7 +89,7 @@ "type": "github" } ], - "time": "2024-03-21T18:52:26+00:00" + "time": "2025-09-03T19:41:28+00:00" }, { "name": "amphp/byte-stream", @@ -248,16 +243,16 @@ }, { "name": "composer/semver", - "version": "3.4.3", + "version": "3.4.4", "source": { "type": "git", "url": "https://github.com/composer/semver.git", - "reference": "4313d26ada5e0c4edfbd1dc481a92ff7bff91f12" + "reference": "198166618906cb2de69b95d7d47e5fa8aa1b2b95" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/composer/semver/zipball/4313d26ada5e0c4edfbd1dc481a92ff7bff91f12", - "reference": "4313d26ada5e0c4edfbd1dc481a92ff7bff91f12", + "url": "https://api.github.com/repos/composer/semver/zipball/198166618906cb2de69b95d7d47e5fa8aa1b2b95", + "reference": "198166618906cb2de69b95d7d47e5fa8aa1b2b95", "shasum": "" }, "require": { @@ -309,7 +304,7 @@ "support": { "irc": "ircs://irc.libera.chat:6697/composer", "issues": "https://github.com/composer/semver/issues", - "source": "https://github.com/composer/semver/tree/3.4.3" + "source": "https://github.com/composer/semver/tree/3.4.4" }, "funding": [ { @@ -319,13 +314,9 @@ { "url": "https://github.com/composer", "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/composer/composer", - "type": "tidelift" } ], - "time": "2024-09-19T14:15:21+00:00" + "time": "2025-08-20T19:15:30+00:00" }, { "name": "composer/xdebug-handler", @@ -581,16 +572,16 @@ }, { "name": "fidry/cpu-core-counter", - "version": "1.2.0", + "version": "1.3.0", "source": { "type": "git", "url": "https://github.com/theofidry/cpu-core-counter.git", - "reference": "8520451a140d3f46ac33042715115e290cf5785f" + "reference": "db9508f7b1474469d9d3c53b86f817e344732678" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/theofidry/cpu-core-counter/zipball/8520451a140d3f46ac33042715115e290cf5785f", - "reference": "8520451a140d3f46ac33042715115e290cf5785f", + "url": "https://api.github.com/repos/theofidry/cpu-core-counter/zipball/db9508f7b1474469d9d3c53b86f817e344732678", + "reference": "db9508f7b1474469d9d3c53b86f817e344732678", "shasum": "" }, "require": { @@ -600,10 +591,10 @@ "fidry/makefile": "^0.2.0", "fidry/php-cs-fixer-config": "^1.1.2", "phpstan/extension-installer": "^1.2.0", - "phpstan/phpstan": "^1.9.2", - "phpstan/phpstan-deprecation-rules": "^1.0.0", - "phpstan/phpstan-phpunit": "^1.2.2", - "phpstan/phpstan-strict-rules": "^1.4.4", + "phpstan/phpstan": "^2.0", + "phpstan/phpstan-deprecation-rules": "^2.0.0", + "phpstan/phpstan-phpunit": "^2.0", + "phpstan/phpstan-strict-rules": "^2.0", "phpunit/phpunit": "^8.5.31 || ^9.5.26", "webmozarts/strict-phpunit": "^7.5" }, @@ -630,7 +621,7 @@ ], "support": { "issues": "https://github.com/theofidry/cpu-core-counter/issues", - "source": "https://github.com/theofidry/cpu-core-counter/tree/1.2.0" + "source": "https://github.com/theofidry/cpu-core-counter/tree/1.3.0" }, "funding": [ { @@ -638,7 +629,7 @@ "type": "github" } ], - "time": "2024-08-06T10:04:20+00:00" + "time": "2025-08-14T07:29:31+00:00" }, { "name": "netresearch/jsonmapper", @@ -693,16 +684,16 @@ }, { "name": "nextcloud/ocp", - "version": "dev-stable28", + "version": "dev-stable30", "source": { "type": "git", "url": "https://github.com/nextcloud-deps/ocp.git", - "reference": "53924b92b5e16225b0bc222068c29fe9e91d445a" + "reference": "d93fc10fea3db4b4896e37db312fae685cff54c4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nextcloud-deps/ocp/zipball/53924b92b5e16225b0bc222068c29fe9e91d445a", - "reference": "53924b92b5e16225b0bc222068c29fe9e91d445a", + "url": "https://api.github.com/repos/nextcloud-deps/ocp/zipball/d93fc10fea3db4b4896e37db312fae685cff54c4", + "reference": "d93fc10fea3db4b4896e37db312fae685cff54c4", "shasum": "" }, "require": { @@ -710,12 +701,12 @@ "psr/clock": "^1.0", "psr/container": "^2.0.2", "psr/event-dispatcher": "^1.0", - "psr/log": "^1.1.4" + "psr/log": "^2.0.0" }, "type": "library", "extra": { "branch-alias": { - "dev-stable28": "28.0.0-dev" + "dev-stable30": "30.0.0-dev" } }, "notification-url": "https://packagist.org/downloads/", @@ -731,22 +722,22 @@ "description": "Composer package containing Nextcloud's public API (classes, interfaces)", "support": { "issues": "https://github.com/nextcloud-deps/ocp/issues", - "source": "https://github.com/nextcloud-deps/ocp/tree/stable28" + "source": "https://github.com/nextcloud-deps/ocp/tree/stable30" }, - "time": "2025-03-05T00:45:45+00:00" + "time": "2025-12-02T00:53:40+00:00" }, { "name": "nikic/php-parser", - "version": "v4.19.4", + "version": "v4.19.5", "source": { "type": "git", "url": "https://github.com/nikic/PHP-Parser.git", - "reference": "715f4d25e225bc47b293a8b997fe6ce99bf987d2" + "reference": "51bd93cc741b7fc3d63d20b6bdcd99fdaa359837" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/715f4d25e225bc47b293a8b997fe6ce99bf987d2", - "reference": "715f4d25e225bc47b293a8b997fe6ce99bf987d2", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/51bd93cc741b7fc3d63d20b6bdcd99fdaa359837", + "reference": "51bd93cc741b7fc3d63d20b6bdcd99fdaa359837", "shasum": "" }, "require": { @@ -761,11 +752,6 @@ "bin/php-parse" ], "type": "library", - "extra": { - "branch-alias": { - "dev-master": "4.9-dev" - } - }, "autoload": { "psr-4": { "PhpParser\\": "lib/PhpParser" @@ -787,9 +773,9 @@ ], "support": { "issues": "https://github.com/nikic/PHP-Parser/issues", - "source": "https://github.com/nikic/PHP-Parser/tree/v4.19.4" + "source": "https://github.com/nikic/PHP-Parser/tree/v4.19.5" }, - "time": "2024-09-29T15:01:53+00:00" + "time": "2025-12-06T11:45:25+00:00" }, { "name": "phpdocumentor/reflection-common", @@ -846,16 +832,16 @@ }, { "name": "phpdocumentor/reflection-docblock", - "version": "5.6.2", + "version": "5.6.5", "source": { "type": "git", "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", - "reference": "92dde6a5919e34835c506ac8c523ef095a95ed62" + "reference": "90614c73d3800e187615e2dd236ad0e2a01bf761" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/92dde6a5919e34835c506ac8c523ef095a95ed62", - "reference": "92dde6a5919e34835c506ac8c523ef095a95ed62", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/90614c73d3800e187615e2dd236ad0e2a01bf761", + "reference": "90614c73d3800e187615e2dd236ad0e2a01bf761", "shasum": "" }, "require": { @@ -904,22 +890,22 @@ "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.", "support": { "issues": "https://github.com/phpDocumentor/ReflectionDocBlock/issues", - "source": "https://github.com/phpDocumentor/ReflectionDocBlock/tree/5.6.2" + "source": "https://github.com/phpDocumentor/ReflectionDocBlock/tree/5.6.5" }, - "time": "2025-04-13T19:20:35+00:00" + "time": "2025-11-27T19:50:05+00:00" }, { "name": "phpdocumentor/type-resolver", - "version": "1.10.0", + "version": "1.12.0", "source": { "type": "git", "url": "https://github.com/phpDocumentor/TypeResolver.git", - "reference": "679e3ce485b99e84c775d28e2e96fade9a7fb50a" + "reference": "92a98ada2b93d9b201a613cb5a33584dde25f195" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/679e3ce485b99e84c775d28e2e96fade9a7fb50a", - "reference": "679e3ce485b99e84c775d28e2e96fade9a7fb50a", + "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/92a98ada2b93d9b201a613cb5a33584dde25f195", + "reference": "92a98ada2b93d9b201a613cb5a33584dde25f195", "shasum": "" }, "require": { @@ -962,22 +948,22 @@ "description": "A PSR-5 based resolver of Class names, Types and Structural Element Names", "support": { "issues": "https://github.com/phpDocumentor/TypeResolver/issues", - "source": "https://github.com/phpDocumentor/TypeResolver/tree/1.10.0" + "source": "https://github.com/phpDocumentor/TypeResolver/tree/1.12.0" }, - "time": "2024-11-09T15:12:26+00:00" + "time": "2025-11-21T15:09:14+00:00" }, { "name": "phpstan/phpdoc-parser", - "version": "2.1.0", + "version": "2.3.0", "source": { "type": "git", "url": "https://github.com/phpstan/phpdoc-parser.git", - "reference": "9b30d6fd026b2c132b3985ce6b23bec09ab3aa68" + "reference": "1e0cd5370df5dd2e556a36b9c62f62e555870495" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/9b30d6fd026b2c132b3985ce6b23bec09ab3aa68", - "reference": "9b30d6fd026b2c132b3985ce6b23bec09ab3aa68", + "url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/1e0cd5370df5dd2e556a36b9c62f62e555870495", + "reference": "1e0cd5370df5dd2e556a36b9c62f62e555870495", "shasum": "" }, "require": { @@ -1009,9 +995,9 @@ "description": "PHPDoc parser with support for nullable, intersection and generic types", "support": { "issues": "https://github.com/phpstan/phpdoc-parser/issues", - "source": "https://github.com/phpstan/phpdoc-parser/tree/2.1.0" + "source": "https://github.com/phpstan/phpdoc-parser/tree/2.3.0" }, - "time": "2025-02-19T13:28:12+00:00" + "time": "2025-08-30T15:50:23+00:00" }, { "name": "psr/clock", @@ -1166,30 +1152,30 @@ }, { "name": "psr/log", - "version": "1.1.4", + "version": "2.0.0", "source": { "type": "git", "url": "https://github.com/php-fig/log.git", - "reference": "d49695b909c3b7628b6289db5479a1c204601f11" + "reference": "ef29f6d262798707a9edd554e2b82517ef3a9376" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11", - "reference": "d49695b909c3b7628b6289db5479a1c204601f11", + "url": "https://api.github.com/repos/php-fig/log/zipball/ef29f6d262798707a9edd554e2b82517ef3a9376", + "reference": "ef29f6d262798707a9edd554e2b82517ef3a9376", "shasum": "" }, "require": { - "php": ">=5.3.0" + "php": ">=8.0.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.1.x-dev" + "dev-master": "2.0.x-dev" } }, "autoload": { "psr-4": { - "Psr\\Log\\": "Psr/Log/" + "Psr\\Log\\": "src" } }, "notification-url": "https://packagist.org/downloads/", @@ -1210,9 +1196,9 @@ "psr-3" ], "support": { - "source": "https://github.com/php-fig/log/tree/1.1.4" + "source": "https://github.com/php-fig/log/tree/2.0.0" }, - "time": "2021-05-03T11:20:27+00:00" + "time": "2021-07-14T16:41:46+00:00" }, { "name": "sabre/dav", @@ -1365,16 +1351,16 @@ }, { "name": "sabre/http", - "version": "5.1.12", + "version": "5.1.13", "source": { "type": "git", "url": "https://github.com/sabre-io/http.git", - "reference": "dedff73f3995578bc942fa4c8484190cac14f139" + "reference": "7c2a14097d1a0de2347dcbdc91a02f38e338f4db" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sabre-io/http/zipball/dedff73f3995578bc942fa4c8484190cac14f139", - "reference": "dedff73f3995578bc942fa4c8484190cac14f139", + "url": "https://api.github.com/repos/sabre-io/http/zipball/7c2a14097d1a0de2347dcbdc91a02f38e338f4db", + "reference": "7c2a14097d1a0de2347dcbdc91a02f38e338f4db", "shasum": "" }, "require": { @@ -1386,7 +1372,7 @@ "sabre/uri": "^2.0" }, "require-dev": { - "friendsofphp/php-cs-fixer": "~2.17.1||^3.63", + "friendsofphp/php-cs-fixer": "~2.17.1||3.63.2", "phpstan/phpstan": "^0.12", "phpunit/phpunit": "^7.5 || ^8.5 || ^9.6" }, @@ -1424,7 +1410,7 @@ "issues": "https://github.com/sabre-io/http/issues", "source": "https://github.com/fruux/sabre-http" }, - "time": "2024-08-27T16:07:41+00:00" + "time": "2025-09-09T10:21:47+00:00" }, { "name": "sabre/uri", @@ -1728,16 +1714,16 @@ }, { "name": "spatie/array-to-xml", - "version": "3.4.0", + "version": "3.4.3", "source": { "type": "git", "url": "https://github.com/spatie/array-to-xml.git", - "reference": "7dcfc67d60b0272926dabad1ec01f6b8a5fb5e67" + "reference": "7b9202dccfe18d4e3a13303156d6bbcc1c61dabf" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/spatie/array-to-xml/zipball/7dcfc67d60b0272926dabad1ec01f6b8a5fb5e67", - "reference": "7dcfc67d60b0272926dabad1ec01f6b8a5fb5e67", + "url": "https://api.github.com/repos/spatie/array-to-xml/zipball/7b9202dccfe18d4e3a13303156d6bbcc1c61dabf", + "reference": "7b9202dccfe18d4e3a13303156d6bbcc1c61dabf", "shasum": "" }, "require": { @@ -1780,7 +1766,7 @@ "xml" ], "support": { - "source": "https://github.com/spatie/array-to-xml/tree/3.4.0" + "source": "https://github.com/spatie/array-to-xml/tree/3.4.3" }, "funding": [ { @@ -1792,20 +1778,20 @@ "type": "github" } ], - "time": "2024-12-16T12:45:15+00:00" + "time": "2025-11-27T09:08:26+00:00" }, { "name": "symfony/console", - "version": "v6.4.21", + "version": "v6.4.30", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "a3011c7b7adb58d89f6c0d822abb641d7a5f9719" + "reference": "1b2813049506b39eb3d7e64aff033fd5ca26c97e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/a3011c7b7adb58d89f6c0d822abb641d7a5f9719", - "reference": "a3011c7b7adb58d89f6c0d822abb641d7a5f9719", + "url": "https://api.github.com/repos/symfony/console/zipball/1b2813049506b39eb3d7e64aff033fd5ca26c97e", + "reference": "1b2813049506b39eb3d7e64aff033fd5ca26c97e", "shasum": "" }, "require": { @@ -1870,7 +1856,7 @@ "terminal" ], "support": { - "source": "https://github.com/symfony/console/tree/v6.4.21" + "source": "https://github.com/symfony/console/tree/v6.4.30" }, "funding": [ { @@ -1881,25 +1867,29 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-04-07T15:42:41+00:00" + "time": "2025-12-05T13:47:41+00:00" }, { "name": "symfony/deprecation-contracts", - "version": "v3.5.1", + "version": "v3.6.0", "source": { "type": "git", "url": "https://github.com/symfony/deprecation-contracts.git", - "reference": "74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6" + "reference": "63afe740e99a13ba87ec199bb07bbdee937a5b62" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6", - "reference": "74c71c939a79f7d5bf3c1ce9f5ea37ba0114c6f6", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/63afe740e99a13ba87ec199bb07bbdee937a5b62", + "reference": "63afe740e99a13ba87ec199bb07bbdee937a5b62", "shasum": "" }, "require": { @@ -1912,7 +1902,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.5-dev" + "dev-main": "3.6-dev" } }, "autoload": { @@ -1937,7 +1927,7 @@ "description": "A generic function and convention to trigger deprecation notices", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/deprecation-contracts/tree/v3.5.1" + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.6.0" }, "funding": [ { @@ -1953,20 +1943,20 @@ "type": "tidelift" } ], - "time": "2024-09-25T14:20:29+00:00" + "time": "2024-09-25T14:21:43+00:00" }, { "name": "symfony/filesystem", - "version": "v6.4.13", + "version": "v6.4.30", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", - "reference": "4856c9cf585d5a0313d8d35afd681a526f038dd3" + "reference": "441c6b69f7222aadae7cbf5df588496d5ee37789" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/filesystem/zipball/4856c9cf585d5a0313d8d35afd681a526f038dd3", - "reference": "4856c9cf585d5a0313d8d35afd681a526f038dd3", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/441c6b69f7222aadae7cbf5df588496d5ee37789", + "reference": "441c6b69f7222aadae7cbf5df588496d5ee37789", "shasum": "" }, "require": { @@ -2003,7 +1993,7 @@ "description": "Provides basic utilities for the filesystem", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/filesystem/tree/v6.4.13" + "source": "https://github.com/symfony/filesystem/tree/v6.4.30" }, "funding": [ { @@ -2014,16 +2004,20 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2024-10-25T15:07:50+00:00" + "time": "2025-11-26T14:43:45+00:00" }, { "name": "symfony/polyfill-ctype", - "version": "v1.31.0", + "version": "v1.33.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-ctype.git", @@ -2082,7 +2076,7 @@ "portable" ], "support": { - "source": "https://github.com/symfony/polyfill-ctype/tree/v1.31.0" + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.33.0" }, "funding": [ { @@ -2093,6 +2087,10 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" @@ -2102,16 +2100,16 @@ }, { "name": "symfony/polyfill-intl-grapheme", - "version": "v1.32.0", + "version": "v1.33.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-intl-grapheme.git", - "reference": "b9123926e3b7bc2f98c02ad54f6a4b02b91a8abe" + "reference": "380872130d3a5dd3ace2f4010d95125fde5d5c70" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/b9123926e3b7bc2f98c02ad54f6a4b02b91a8abe", - "reference": "b9123926e3b7bc2f98c02ad54f6a4b02b91a8abe", + "url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/380872130d3a5dd3ace2f4010d95125fde5d5c70", + "reference": "380872130d3a5dd3ace2f4010d95125fde5d5c70", "shasum": "" }, "require": { @@ -2160,7 +2158,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.32.0" + "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.33.0" }, "funding": [ { @@ -2171,16 +2169,20 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2024-09-09T11:45:10+00:00" + "time": "2025-06-27T09:58:17+00:00" }, { "name": "symfony/polyfill-intl-normalizer", - "version": "v1.32.0", + "version": "v1.33.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-intl-normalizer.git", @@ -2241,7 +2243,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.32.0" + "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.33.0" }, "funding": [ { @@ -2252,6 +2254,10 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" @@ -2261,7 +2267,7 @@ }, { "name": "symfony/polyfill-mbstring", - "version": "v1.32.0", + "version": "v1.33.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", @@ -2322,7 +2328,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.32.0" + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.33.0" }, "funding": [ { @@ -2333,6 +2339,10 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" @@ -2342,16 +2352,16 @@ }, { "name": "symfony/service-contracts", - "version": "v3.5.1", + "version": "v3.6.1", "source": { "type": "git", "url": "https://github.com/symfony/service-contracts.git", - "reference": "e53260aabf78fb3d63f8d79d69ece59f80d5eda0" + "reference": "45112560a3ba2d715666a509a0bc9521d10b6c43" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/service-contracts/zipball/e53260aabf78fb3d63f8d79d69ece59f80d5eda0", - "reference": "e53260aabf78fb3d63f8d79d69ece59f80d5eda0", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/45112560a3ba2d715666a509a0bc9521d10b6c43", + "reference": "45112560a3ba2d715666a509a0bc9521d10b6c43", "shasum": "" }, "require": { @@ -2369,7 +2379,7 @@ "name": "symfony/contracts" }, "branch-alias": { - "dev-main": "3.5-dev" + "dev-main": "3.6-dev" } }, "autoload": { @@ -2405,7 +2415,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/service-contracts/tree/v3.5.1" + "source": "https://github.com/symfony/service-contracts/tree/v3.6.1" }, "funding": [ { @@ -2416,25 +2426,29 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2024-09-25T14:20:29+00:00" + "time": "2025-07-15T11:30:57+00:00" }, { "name": "symfony/string", - "version": "v6.4.21", + "version": "v6.4.30", "source": { "type": "git", "url": "https://github.com/symfony/string.git", - "reference": "73e2c6966a5aef1d4892873ed5322245295370c6" + "reference": "50590a057841fa6bf69d12eceffce3465b9e32cb" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/string/zipball/73e2c6966a5aef1d4892873ed5322245295370c6", - "reference": "73e2c6966a5aef1d4892873ed5322245295370c6", + "url": "https://api.github.com/repos/symfony/string/zipball/50590a057841fa6bf69d12eceffce3465b9e32cb", + "reference": "50590a057841fa6bf69d12eceffce3465b9e32cb", "shasum": "" }, "require": { @@ -2448,7 +2462,6 @@ "symfony/translation-contracts": "<2.5" }, "require-dev": { - "symfony/error-handler": "^5.4|^6.0|^7.0", "symfony/http-client": "^5.4|^6.0|^7.0", "symfony/intl": "^6.2|^7.0", "symfony/translation-contracts": "^2.5|^3.0", @@ -2491,7 +2504,7 @@ "utf8" ], "support": { - "source": "https://github.com/symfony/string/tree/v6.4.21" + "source": "https://github.com/symfony/string/tree/v6.4.30" }, "funding": [ { @@ -2502,12 +2515,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-04-18T15:23:29+00:00" + "time": "2025-11-21T18:03:05+00:00" }, { "name": "vimeo/psalm", @@ -2621,28 +2638,28 @@ }, { "name": "webmozart/assert", - "version": "1.11.0", + "version": "1.12.1", "source": { "type": "git", "url": "https://github.com/webmozarts/assert.git", - "reference": "11cb2199493b2f8a3b53e7f19068fc6aac760991" + "reference": "9be6926d8b485f55b9229203f962b51ed377ba68" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/webmozarts/assert/zipball/11cb2199493b2f8a3b53e7f19068fc6aac760991", - "reference": "11cb2199493b2f8a3b53e7f19068fc6aac760991", + "url": "https://api.github.com/repos/webmozarts/assert/zipball/9be6926d8b485f55b9229203f962b51ed377ba68", + "reference": "9be6926d8b485f55b9229203f962b51ed377ba68", "shasum": "" }, "require": { "ext-ctype": "*", + "ext-date": "*", + "ext-filter": "*", "php": "^7.2 || ^8.0" }, - "conflict": { - "phpstan/phpstan": "<0.12.20", - "vimeo/psalm": "<4.6.1 || 4.6.2" - }, - "require-dev": { - "phpunit/phpunit": "^8.5.13" + "suggest": { + "ext-intl": "", + "ext-simplexml": "", + "ext-spl": "" }, "type": "library", "extra": { @@ -2673,9 +2690,9 @@ ], "support": { "issues": "https://github.com/webmozarts/assert/issues", - "source": "https://github.com/webmozarts/assert/tree/1.11.0" + "source": "https://github.com/webmozarts/assert/tree/1.12.1" }, - "time": "2022-06-03T18:03:27+00:00" + "time": "2025-10-29T15:56:20+00:00" } ], "aliases": [], From f3a29b582b4bc8a279df4a33690b5977a32c3097 Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Mon, 8 Dec 2025 20:00:19 +0100 Subject: [PATCH 2/2] refactor: Port more stuff to IAppConfig Signed-off-by: Carl Schwan --- lib/AppInfo/Application.php | 3 +- lib/Controller/SAMLController.php | 64 ++++----- lib/DavPlugin.php | 10 +- .../LoadAdditionalScriptsListener.php | 6 +- lib/Listener/SabrePluginEventListener.php | 18 ++- lib/Middleware/OnlyLoggedInMiddleware.php | 8 +- lib/Settings/Admin.php | 9 +- tests/unit/Controller/SAMLControllerTest.php | 128 +++++++----------- tests/unit/Settings/AdminTest.php | 12 +- 9 files changed, 121 insertions(+), 137 deletions(-) diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index 1d770f40b..0f7885b54 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -26,6 +26,7 @@ use OCP\AppFramework\Bootstrap\IBootstrap; use OCP\AppFramework\Bootstrap\IRegistrationContext; use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent; +use OCP\AppFramework\Services\IAppConfig; use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; use OCP\IDBConnection; @@ -55,7 +56,7 @@ public function register(IRegistrationContext $context): void { $context->registerEventListener(SabrePluginAddEvent::class, SabrePluginEventListener::class); $context->registerService(DavPlugin::class, fn (ContainerInterface $c) => new DavPlugin( $c->get(ISession::class), - $c->get(IConfig::class), + $c->get(IAppConfig::class), $_SERVER, $c->get(SAMLSettings::class) )); diff --git a/lib/Controller/SAMLController.php b/lib/Controller/SAMLController.php index c0045b66f..e7a89a089 100644 --- a/lib/Controller/SAMLController.php +++ b/lib/Controller/SAMLController.php @@ -22,6 +22,11 @@ use OCA\User_SAML\UserResolver; use OCP\AppFramework\Controller; use OCP\AppFramework\Http; +use OCP\AppFramework\Http\Attribute\NoAdminRequired; +use OCP\AppFramework\Http\Attribute\NoCSRFRequired; +use OCP\AppFramework\Http\Attribute\PublicPage; +use OCP\AppFramework\Http\Attribute\UseSession; +use OCP\AppFramework\Services\IAppConfig; use OCP\IConfig; use OCP\IL10N; use OCP\IRequest; @@ -50,6 +55,7 @@ public function __construct( private SAMLSettings $samlSettings, private UserBackend $userBackend, private IConfig $config, + private IAppConfig $appConfig, private IURLGenerator $urlGenerator, private LoggerInterface $logger, private IL10N $l, @@ -137,20 +143,19 @@ protected function assertGroupMemberships(): void { } /** - * @PublicPage - * @UseSession * @OnlyUnauthenticatedUsers - * @NoCSRFRequired - * * @throws Exception */ + #[PublicPage] + #[UseSession] + #[NoCSRFRequired] public function login(int $idp = 1): Http\RedirectResponse|Http\TemplateResponse { $originalUrl = (string)$this->request->getParam('originalUrl', ''); if (!$this->trustedDomainHelper->isTrustedUrl($originalUrl)) { $originalUrl = ''; } - $type = $this->config->getAppValue($this->appName, 'type'); + $type = $this->appConfig->getAppValueString('type'); switch ($type) { case 'saml': $settings = $this->samlSettings->getOneLoginSettingsArray($idp); @@ -273,10 +278,10 @@ public function login(int $idp = 1): Http\RedirectResponse|Http\TemplateResponse } /** - * @PublicPage - * @NoCSRFRequired * @throws Error */ + #[PublicPage] + #[NoCSRFRequired] public function getMetadata(int $idp = 1): Http\DataDownloadResponse { $settings = new Settings($this->samlSettings->getOneLoginSettingsArray($idp)); $metadata = $settings->getSPMetadata(); @@ -292,9 +297,6 @@ public function getMetadata(int $idp = 1): Http\DataDownloadResponse { } /** - * @PublicPage - * @NoCSRFRequired - * @UseSession * @OnlyUnauthenticatedUsers * @NoSameSiteCookieRequired * @@ -302,6 +304,9 @@ public function getMetadata(int $idp = 1): Http\DataDownloadResponse { * @throws Error * @throws ValidationError */ + #[PublicPage] + #[NoCSRFRequired] + #[UseSession] public function assertionConsumerService(): Http\RedirectResponse { // Fetch and decrypt the cookie $cookie = $this->request->getCookie('saml_data'); @@ -423,12 +428,12 @@ public function assertionConsumerService(): Http\RedirectResponse { } /** - * @PublicPage - * @NoAdminRequired - * @NoCSRFRequired - * @UseSession * @throws Error */ + #[PublicPage] + #[NoAdminRequired] + #[UseSession] + #[NoCSRFRequired] public function singleLogoutService(): Http\RedirectResponse { $isFromGS = ($this->config->getSystemValueBool('gs.enabled', false) && $this->config->getSystemValueString('gss.mode', '') === 'master'); @@ -506,7 +511,7 @@ public function singleLogoutService(): Http\RedirectResponse { } /** - * @returns [?string, ?Auth] + * @return array{0: ?string, 1: ?Auth} */ private function tryProcessSLOResponse(?int $idp): array { $idps = ($idp !== null) ? [$idp] : array_keys($this->samlSettings->getListOfIdps()); @@ -532,28 +537,28 @@ private function tryProcessSLOResponse(?int $idp): array { } /** - * @PublicPage - * @NoCSRFRequired * @OnlyUnauthenticatedUsers */ + #[PublicPage] + #[NoCSRFRequired] public function notProvisioned(): Http\TemplateResponse { return new Http\TemplateResponse($this->appName, 'notProvisioned', [], 'guest'); } /** - * @PublicPage - * @NoCSRFRequired * @OnlyUnauthenticatedUsers */ + #[PublicPage] + #[NoCSRFRequired] public function notPermitted(): Http\TemplateResponse { return new Http\TemplateResponse($this->appName, 'notPermitted', [], 'guest'); } /** - * @PublicPage - * @NoCSRFRequired * @OnlyUnauthenticatedUsers */ + #[PublicPage] + #[NoCSRFRequired] public function genericError(string $message): Http\TemplateResponse { if (empty($message)) { $message = $this->l->t('Unknown error, please check the log file for more details.'); @@ -562,17 +567,17 @@ public function genericError(string $message): Http\TemplateResponse { } /** - * @PublicPage - * @NoCSRFRequired * @OnlyUnauthenticatedUsers */ + #[PublicPage] + #[NoCSRFRequired] public function selectUserBackEnd(string $redirectUrl = ''): Http\TemplateResponse { $attributes = ['loginUrls' => []]; if ($this->samlSettings->allowMultipleUserBackEnds()) { $displayName = $this->l->t('Direct log in'); - $customDisplayName = $this->config->getAppValue('user_saml', 'directLoginName', ''); + $customDisplayName = $this->appConfig->getAppValueString('directLoginName'); if ($customDisplayName !== '') { $displayName = $customDisplayName; } @@ -584,10 +589,8 @@ public function selectUserBackEnd(string $redirectUrl = ''): Http\TemplateRespon } $attributes['loginUrls']['ssoLogin'] = $this->getIdps($redirectUrl); - $attributes['useCombobox'] = count($attributes['loginUrls']['ssoLogin']) > 4; - return new Http\TemplateResponse($this->appName, 'selectUserBackEnd', $attributes, 'guest'); } @@ -651,17 +654,14 @@ protected function getSSODisplayName(?string $displayName): string { * get Nextcloud login URL */ private function getDirectLoginUrl(string $redirectUrl): string { - $directUrl = $this->urlGenerator->linkToRouteAbsolute('core.login.tryLogin', [ + return $this->urlGenerator->linkToRouteAbsolute('core.login.tryLogin', [ 'direct' => '1', 'redirect_url' => $redirectUrl, ]); - return $directUrl; } - /** - * @PublicPage - * @NoCSRFRequired - */ + #[PublicPage] + #[NoCSRFRequired] public function base(): Http\TemplateResponse { $message = $this->l->t('This page should not be visited directly.'); return new Http\TemplateResponse($this->appName, 'error', ['message' => $message], 'guest'); diff --git a/lib/DavPlugin.php b/lib/DavPlugin.php index 118062d1d..85bcd0aa5 100644 --- a/lib/DavPlugin.php +++ b/lib/DavPlugin.php @@ -8,7 +8,7 @@ namespace OCA\User_SAML; use OCA\DAV\Connector\Sabre\Auth; -use OCP\IConfig; +use OCP\AppFramework\Services\IAppConfig; use OCP\ISession; use Sabre\DAV\Server; use Sabre\DAV\ServerPlugin; @@ -21,21 +21,21 @@ class DavPlugin extends ServerPlugin { public function __construct( private readonly ISession $session, - private readonly IConfig $config, + private readonly IAppConfig $config, private array $auth, private readonly SAMLSettings $samlSettings, ) { } - public function initialize(Server $server) { + public function initialize(Server $server): void { // before auth $server->on('beforeMethod:*', $this->beforeMethod(...), 9); $this->server = $server; } - public function beforeMethod(RequestInterface $request, ResponseInterface $response) { + public function beforeMethod(RequestInterface $request, ResponseInterface $response): void { if ( - $this->config->getAppValue('user_saml', 'type') === 'environment-variable' + $this->config->getAppValueString('type') === 'environment-variable' && !$this->session->exists('user_saml.samlUserData') ) { $uidMapping = $this->samlSettings->get(1)['general-uid_mapping']; diff --git a/lib/Listener/LoadAdditionalScriptsListener.php b/lib/Listener/LoadAdditionalScriptsListener.php index 14b24e54e..8d1276772 100644 --- a/lib/Listener/LoadAdditionalScriptsListener.php +++ b/lib/Listener/LoadAdditionalScriptsListener.php @@ -10,9 +10,9 @@ namespace OCA\User_SAML\Listener; use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent; +use OCP\Config\IUserConfig; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventListener; -use OCP\IConfig; use OCP\ISession; use OCP\IUserSession; use OCP\Util; @@ -22,7 +22,7 @@ class LoadAdditionalScriptsListener implements IEventListener { public function __construct( private readonly ISession $session, private readonly IUserSession $userSession, - private readonly IConfig $config, + private readonly IUserConfig $userConfig, ) { } @@ -39,7 +39,7 @@ public function handle(Event $event): void { if ($user === null) { return; // already checked by $event->isLoggedIn above } - $timezoneDB = $this->config->getUserValue($user->getUID(), 'core', 'timezone', ''); + $timezoneDB = $this->userConfig->getValueString($user->getUID(), 'core', 'timezone'); if ($timezoneDB === '' || !$this->session->exists('timezone')) { Util::addScript('user_saml', 'vendor/jstz.min'); diff --git a/lib/Listener/SabrePluginEventListener.php b/lib/Listener/SabrePluginEventListener.php index c30724ecd..095c633e7 100644 --- a/lib/Listener/SabrePluginEventListener.php +++ b/lib/Listener/SabrePluginEventListener.php @@ -11,16 +11,30 @@ use OCA\DAV\Events\SabrePluginAddEvent; use OCA\User_SAML\DavPlugin; +use OCA\User_SAML\SAMLSettings; +use OCP\AppFramework\Services\IAppConfig; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventListener; -use OCP\Server; +use OCP\ISession; /** @template-implements IEventListener */ class SabrePluginEventListener implements IEventListener { + public function __construct( + private readonly ISession $session, + private readonly IAppConfig $appConfig, + private readonly SAMLSettings $settings, + ) { + } + public function handle(Event $event): void { if (!$event instanceof SabrePluginAddEvent) { return; } - $event->getServer()->addPlugin(Server::get(DavPlugin::class)); + $event->getServer()->addPlugin(new DavPlugin( + $this->session, + $this->appConfig, + $_SERVER, + $this->settings, + )); } } diff --git a/lib/Middleware/OnlyLoggedInMiddleware.php b/lib/Middleware/OnlyLoggedInMiddleware.php index 21ee180af..c32216d81 100644 --- a/lib/Middleware/OnlyLoggedInMiddleware.php +++ b/lib/Middleware/OnlyLoggedInMiddleware.php @@ -12,6 +12,7 @@ use OCP\AppFramework\Utility\IControllerMethodReflector; use OCP\IURLGenerator; use OCP\IUserSession; +use Override; /** * Class OnlyLoggedInMiddleware prevents access to a controller method if the user @@ -33,7 +34,8 @@ public function __construct( * @param string $methodName * @throws \Exception */ - public function beforeController($controller, $methodName) { + #[Override] + public function beforeController($controller, $methodName): void { if ($this->reflector->hasAnnotation('OnlyUnauthenticatedUsers') && $this->userSession->isLoggedIn()) { throw new \Exception('User is already logged-in'); } @@ -43,10 +45,10 @@ public function beforeController($controller, $methodName) { * @param \OCP\AppFramework\Controller $controller * @param string $methodName * @param \Exception $exception - * @return RedirectResponse * @throws \Exception */ - public function afterException($controller, $methodName, \Exception $exception) { + #[Override] + public function afterException($controller, $methodName, \Exception $exception): RedirectResponse { if ($exception->getMessage() === 'User is already logged-in') { return new RedirectResponse($this->urlGenerator->getAbsoluteURL('/')); } diff --git a/lib/Settings/Admin.php b/lib/Settings/Admin.php index 4072baeda..d4656778a 100644 --- a/lib/Settings/Admin.php +++ b/lib/Settings/Admin.php @@ -83,11 +83,6 @@ public function getForm(): TemplateResponse { 'type' => 'line', 'required' => true, ], - 'require_provisioned_account' => [ - 'text' => $this->l10n->t('Only allow authentication if an account exists on some other backend (e.g. LDAP).'), - 'type' => 'checkbox', - 'global' => true, - ], ]; $attributeMappingSettings = [ 'displayName_mapping' => [ @@ -188,7 +183,7 @@ public function getForm(): TemplateResponse { $nameIdFormats[Constants::NAMEID_UNSPECIFIED]['selected'] = true; } - $type = $this->appConfig->getAppValueString( 'type'); + $type = $this->appConfig->getAppValueString('type'); $generalSettings['require_provisioned_account'] = [ 'text' => $this->l10n->t('Only allow authentication if an account exists on some other backend (e.g. LDAP).', [$this->defaults->getName()]), @@ -213,7 +208,7 @@ public function getForm(): TemplateResponse { 'type' => 'checkbox', 'hideForEnv' => true, 'global' => true, - 'value' => $this->appConfig->getAppValueInt('general-allow_multiple_user_back_ends' ) + 'value' => $this->appConfig->getAppValueInt('general-allow_multiple_user_back_ends') ]; } diff --git a/tests/unit/Controller/SAMLControllerTest.php b/tests/unit/Controller/SAMLControllerTest.php index dc06ad75e..e640d90d0 100644 --- a/tests/unit/Controller/SAMLControllerTest.php +++ b/tests/unit/Controller/SAMLControllerTest.php @@ -17,6 +17,7 @@ use OCA\User_SAML\UserResolver; use OCP\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Http\TemplateResponse; +use OCP\AppFramework\Services\IAppConfig; use OCP\IConfig; use OCP\IL10N; use OCP\IRequest; @@ -26,37 +27,26 @@ use OCP\IUserSession; use OCP\Security\ICrypto; use OCP\Security\ITrustedDomainHelper; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; class SAMLControllerTest extends TestCase { - /** @var UserResolver|\PHPUnit\Framework\MockObject\MockObject */ - protected $userResolver; - /** @var UserData|\PHPUnit\Framework\MockObject\MockObject */ - private $userData; - /** @var IRequest|\PHPUnit_Framework_MockObject_MockObject */ - private $request; - /** @var ISession|\PHPUnit_Framework_MockObject_MockObject */ - private $session; - /** @var IUserSession|\PHPUnit_Framework_MockObject_MockObject */ - private $userSession; - /** @var SAMLSettings|\PHPUnit_Framework_MockObject_MockObject */ - private $samlSettings; - /** @var UserBackend|\PHPUnit_Framework_MockObject_MockObject */ - private $userBackend; - /** @var IConfig|\PHPUnit_Framework_MockObject_MockObject */ - private $config; - /** @var IURLGenerator|\PHPUnit_Framework_MockObject_MockObject */ - private $urlGenerator; - /** @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ - private $logger; - /** @var IL10N|\PHPUnit_Framework_MockObject_MockObject */ - private $l; - /** @var ICrypto|MockObject */ - private $crypto; - /** @var SAMLController */ - private $samlController; + protected UserResolver&MockObject $userResolver; + private UserData&MockObject $userData; + private IRequest&MockObject $request; + private ISession&MockObject $session; + private IUserSession&MockObject $userSession; + private SAMLSettings&MockObject $samlSettings; + private UserBackend&MockObject $userBackend; + private IConfig&MockObject $config; + private IAppConfig&MockObject $appConfig; + private IURLGenerator&MockObject $urlGenerator; + private LoggerInterface&MockObject $logger; + private IL10N&MockObject $l; + private ICrypto&MockObject $crypto; + private SAMLController $samlController; private ITrustedDomainHelper|MockObject $trustedDomainController; protected function setUp(): void { @@ -68,6 +58,7 @@ protected function setUp(): void { $this->samlSettings = $this->createMock(SAMLSettings::class); $this->userBackend = $this->createMock(UserBackend::class); $this->config = $this->createMock(IConfig::class); + $this->appConfig = $this->createMock(IAppConfig::class); $this->urlGenerator = $this->createMock(IURLGenerator::class); $this->logger = $this->createMock(LoggerInterface::class); $this->l = $this->createMock(IL10N::class); @@ -77,11 +68,11 @@ protected function setUp(): void { $this->trustedDomainController = $this->createMock(ITrustedDomainHelper::class); $this->l->expects($this->any())->method('t')->willReturnCallback( - fn ($param) => $param + static fn ($param) => $param ); $this->config->expects($this->any())->method('getSystemValue') - ->willReturnCallback(fn ($key, $default) => $default); + ->willReturnCallback(static fn ($key, $default) => $default); $this->samlController = new SAMLController( 'user_saml', @@ -91,6 +82,7 @@ protected function setUp(): void { $this->samlSettings, $this->userBackend, $this->config, + $this->appConfig, $this->urlGenerator, $this->logger, $this->l, @@ -101,11 +93,11 @@ protected function setUp(): void { ); } - public function testLoginWithInvalidAppValue() { - $this->config + public function testLoginWithInvalidAppValue(): void { + $this->appConfig ->expects($this->once()) - ->method('getAppValue') - ->with('user_saml', 'type') + ->method('getAppValueString') + ->with('type') ->willReturn('UnknownValue'); $this->expectException(Exception::class); @@ -114,7 +106,7 @@ public function testLoginWithInvalidAppValue() { $this->samlController->login(1); } - public function samlUserDataProvider() { + public static function samlUserDataProvider(): array { $userNotExisting = 0; $userExisting = 1; $userLazyExisting = 2; @@ -196,22 +188,18 @@ public function samlUserDataProvider() { ]; } - /** - * @dataProvider samlUserDataProvider - */ - public function testLoginWithEnvVariable(array $samlUserData, string $redirect, int $userState, int $autoProvision) { - $this->config->expects($this->any()) - ->method('getAppValue') - ->willReturnCallback(function (string $app, string $key) { - if ($app === 'user_saml') { - if ($key === 'type') { - return 'environment-variable'; - } - if ($key === 'general-uid_mapping') { - return 'uid'; - } + #[DataProvider('samlUserDataProvider')] + public function testLoginWithEnvVariable(array $samlUserData, string $redirect, int $userState, int $autoProvision): void { + $this->appConfig->expects($this->any()) + ->method('getAppValueString') + ->willReturnCallback(function (string $key) { + if ($key === 'type') { + return 'environment-variable'; } - return null; + if ($key === 'general-uid_mapping') { + return 'uid'; + } + return ''; }); $this->session @@ -316,54 +304,40 @@ public function testLoginWithEnvVariable(array $samlUserData, string $redirect, $this->assertEquals($expected, $result); } - public function testNotPermitted() { + public function testNotPermitted(): void { $expected = new TemplateResponse('user_saml', 'notPermitted', [], 'guest'); $this->assertEquals($expected, $this->samlController->notPermitted()); } - public function testNotProvisioned() { + public function testNotProvisioned(): void { $expected = new TemplateResponse('user_saml', 'notProvisioned', [], 'guest'); $this->assertEquals($expected, $this->samlController->notProvisioned()); } - /** - * @dataProvider dataTestGenericError - * - * @param string $messageSend - * @param string $messageExpected - */ - public function testGenericError($messageSend, $messageExpected) { + #[DataProvider('dataTestGenericError')] + public function testGenericError(string $messageSend, string $messageExpected): void { $expected = new TemplateResponse('user_saml', 'error', ['message' => $messageExpected], 'guest'); $this->assertEquals($expected, $this->samlController->genericError($messageSend)); } - public function dataTestGenericError() { - return [ - ['messageSend' => '', 'messageExpected' => 'Unknown error, please check the log file for more details.'], - ['messageSend' => 'test message', 'messageExpected' => 'test message'], - ]; + public static function dataTestGenericError(): \Generator { + yield ['messageSend' => '', 'messageExpected' => 'Unknown error, please check the log file for more details.']; + yield ['messageSend' => 'test message', 'messageExpected' => 'test message']; } - /** - * @dataProvider dataTestGetSSODisplayName - * - * @param string $configuredDisplayName - * @param string $expected - */ - public function testGetSSODisplayName($configuredDisplayName, $expected) { + #[DataProvider('dataTestGetSSODisplayName')] + public function testGetSSODisplayName(string $configuredDisplayName, string $expected): void { $result = $this->invokePrivate($this->samlController, 'getSSODisplayName', [$configuredDisplayName]); $this->assertSame($expected, $result); } - public function dataTestGetSSODisplayName() { - return [ - ['My identity provider', 'My identity provider'], - ['', 'SSO & SAML log in'] - ]; + public static function dataTestGetSSODisplayName(): \Generator { + yield ['My identity provider', 'My identity provider']; + yield ['', 'SSO & SAML log in']; } - public function userFilterDataProvider(): array { + public static function userFilterDataProvider(): array { return [ [ // 0 - test rejection by membership 'Group C', @@ -390,9 +364,7 @@ public function userFilterDataProvider(): array { ]; } - /** - * @dataProvider userFilterDataProvider - */ + #[DataProvider('userFilterDataProvider')] public function testUserFilter(?string $rejectGroups, ?string $requireGroups, bool $isException, string $message = ''): void { $this->userData->expects($this->any()) ->method('getGroups') diff --git a/tests/unit/Settings/AdminTest.php b/tests/unit/Settings/AdminTest.php index ea70327f6..c5a614853 100644 --- a/tests/unit/Settings/AdminTest.php +++ b/tests/unit/Settings/AdminTest.php @@ -226,7 +226,7 @@ public function formDataProvider() { ]; } - public function testGetFormWithoutType() { + public function testGetFormWithoutType(): void { $this->settings->expects($this->once()) ->method('getListOfIdps') ->willReturn([ @@ -237,13 +237,13 @@ public function testGetFormWithoutType() { ->expects($this->exactly(1)) // 'type' ->method('getAppValueString') ->with($this->anything(), $this->anything()) - ->willReturn($this->returnArgument(1)); + ->willReturnArgument(1); $this->appConfig ->expects($this->exactly(1)) // 'general-require_provisioned_account' ->method('getAppValueInt') ->with($this->anything(), $this->anything()) - ->willReturn($this->returnArgument(1)); + ->willReturnArgument(1); $params = $this->formDataProvider(); unset($params['general']['idp0_display_name'], $params['general']['is_saml_request_using_post'], $params['general']['allow_multiple_user_back_ends']); @@ -253,7 +253,7 @@ public function testGetFormWithoutType() { $this->assertEquals($expected, $this->admin->getForm()); } - public function testGetFormWithSaml() { + public function testGetFormWithSaml(): void { $this->settings->expects($this->once()) ->method('getListOfIdps') ->willReturn([ @@ -288,11 +288,11 @@ public function testGetFormWithSaml() { $this->assertEquals($expected, $this->admin->getForm()); } - public function testGetSection() { + public function testGetSection(): void { $this->assertSame('saml', $this->admin->getSection()); } - public function testGetPriority() { + public function testGetPriority(): void { $this->assertSame(0, $this->admin->getPriority()); } }