├── .github └── workflows │ └── ci.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── pom.xml └── src ├── main ├── java │ └── org │ │ └── sonar │ │ └── plugins │ │ └── crowd │ │ ├── CrowdAuthenticator.java │ │ ├── CrowdConfiguration.java │ │ ├── CrowdGroupsProvider.java │ │ ├── CrowdPlugin.java │ │ ├── CrowdRealm.java │ │ └── CrowdUsersProvider.java └── resources │ └── crowd-ehcache.xml └── test └── java └── org └── sonar └── plugins └── crowd ├── CrowdAuthenticatorTest.java ├── CrowdConfigurationTest.java ├── CrowdGroupsProviderTest.java └── CrowdUsersProviderTest.java /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Java CI 2 | 3 | on: [push, workflow_dispatch] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v2 11 | - name: Set up JDK 11 12 | uses: actions/setup-java@v2 13 | with: 14 | java-version: '11' 15 | distribution: 'adopt' 16 | - name: Build with Maven 17 | run: mvn --batch-mode --update-snapshots verify org.jacoco:jacoco-maven-plugin:prepare-agent sonar:sonar -Dsonar.organization=deepy -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=$SONAR_TOKEN 18 | env: 19 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #Maven 2 | /target 3 | #Eclipse 4 | /.project 5 | /.classpath 6 | /.settings 7 | #IntelliJ IDEA 8 | *.iml 9 | /.idea 10 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | 167 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Crowd Plugin for SonarQube 2 | [![Build](https://github.com/deepy/sonar-crowd/actions/workflows/ci.yml/badge.svg)](https://github.com/deepy/sonar-crowd/actions/workflows/ci.yml) 3 | 4 | This plugin allows the delegation of SonarQube authentication and authorization to Atlassian Crowd. 5 | The previous version of this plugin has been changed to provide the same functionality as the SonarQube LDAP plugin: 6 | 7 | * Password checking against the external authentication engine. 8 | * Automatic synchronization of usernames and emails. 9 | * Automatic synchronization of relationships between users and groups (authorization). 10 | * Ability to authenticate against both the external and the internal authentication systems 11 | (for instance, technical SonarQube user accounts do not need to be defined in Crowd as there is an automatic 12 | fallback on SonarQube engine if the user is not defined in Crowd or if the Crowd server is down). 13 | 14 | During the first authentication trial, if the password is correct, the SonarQube database is automatically 15 | populated with the new user. Each time a user logs into SonarQube, the username, the email and the 16 | groups this user belongs to that are refreshed in the SonarQube database. 17 | 18 | # Requirements 19 | 20 | This plugin requires Atlassian Crowd 2.1.0 or later. 21 | 22 | # Installation 23 | 24 | Go to Administration > Marketplace > Search for "Crowd" > Install > Restart the SonarQube server 25 | 26 | # Usage 27 | 28 | 1. Configure the crowd plugin by editing the _SONARQUBE_HOME/conf/sonar.properties_ file 29 | 1. Restart the SonarQube server and check the log file for: 30 | 31 | org.sonar.INFO Security realm: Crowd 32 | ... 33 | o.s.p.c.CrowdRealm Crowd configuration is valid, connection test successful. 34 | 35 | 1. Log into SonarQube 36 | 37 | # Configuration 38 | 39 | 40 | 41 | 42 | 43 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 |
PropertyDescriptionDefault valueMandatoryExample
sonar.security.realmTo first try to authenticate against the external sytem. If the external system is not reachable or if the user is not defined in the external system, the authentication will be performed through the SonarQube internal system.
44 | Available since SonarQube 3.6. It replaces the property sonar.authenticator.class usage.
None YesCrowd (only possible value)
sonar.security.savePasswordTo save the user password in the SonarQube database. Then, users will be able to log into SonarQube even when the Crowd server is not reachable. falseNo
sonar.authenticator.createUsersBy default, the SonarQube database is automatically populated when a new user logs into SonarQube. Setting this value to false, makes it mandatory for a System administrator to first declare a user through the SonarQube web interface before allowing this user to log into SonarQube.trueNo
sonar.security.updateUserAttributesIf set to true, at each login, user's attributes (name and email) are re-synchronized. If set to false, user's attributes are not re-synchronized.
62 | Note that if set to false, user's attributes are synchronized just once, at the very first login.
63 | Available since SonarQube 3.6.
trueNo
sonar.authenticator.downcaseSet to true when connecting to a Crowd server using a case-insensitive setup.falseNo
crowd.urlURL of the Crowd server. Note that if you are using https with a self certified certificate, then you should install the server certificate into the Java truststore. Since version 2.0 of the plugin the url must be the root URL of your crowd instance and not the /services/ endpoint like for previous versions of the plugin.NoneYeshttps://my.company.com/crowd/
crowd.applicationApplication name defined in Crowd to authenticate your sonar instance.NoneNosonar
crowd.passwordApplication password defined in Crowd to authenticate your sonar instance.NoneNo
90 | 91 | ### Example of CROWD Configuration 92 | ``` 93 | #------------------- 94 | # Sonar Crowd Plugin 95 | #------------------- 96 | 97 | 98 | # To first try to authenticate against the external sytem. 99 | # If the external system is not reachable or if the user is not defined in the external system, the authentication will be performed through the SonarQube internal system. 100 | sonar.security.realm=Crowd 101 | 102 | # URL of the Crowd server. 103 | crowd.url=https://my.company.com/crowd/ 104 | 105 | 106 | # Crowd application name. 107 | # Default is 'sonar'. 108 | crowd.application=sonar-prod 109 | 110 | 111 | # Crowd application password. 112 | crowd.password=bar 113 | 114 | 115 | # Don't use crowd for sonar account 116 | sonar.security.localUsers=admin,sonar 117 | ``` 118 | 119 | ## Upgrades 120 | ### to SonarQube 5.0 121 | * Only crowd plugin 2.0+ supports SonarQube 5.0+ 122 | * sonar.security.realm must be used instead of sonar.authenticator.class (deprecated since SonarQube 3.6 and removed in SonarQube 5.0) 123 | 124 | 125 | ### from Crowd plugin 1.0 to 2.0 126 | * Crowd plugin 2.0+ uses the REST API provided by Crowd. The crowd url used in the configuration (crowd.url) must be the main URL of your crowd instance and not its /services/ end point (used with the previous SOAP integration) 127 | * Crowd plugin 2.0+ synchronises groups from Crowd thus take care to create a group sonar-administrators in your Crowd directory and add in this group all users you'll want to use to administer SonarQube. You can also define some accounts to not synchronise with the property sonar.security.localUsers 128 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | cm.xd.sonar-plugins 5 | sonar-crowd-plugin 6 | 2.2.0 7 | sonar-plugin 8 | Sonar Crowd Plugin 9 | Delegates authentication to Atlassian Crowd. 10 | https://github.com/deepy/sonar-crowd 11 | 2009 12 | 13 | 14 | 15 | GNU LGPL 3 16 | http://www.gnu.org/licenses/lgpl.txt 17 | repo 18 | 19 | 20 | 21 | 22 | 23 | godin 24 | Evgeny Mandrikov 25 | +3 26 | 27 | 28 | aheritier 29 | Arnaud Héritier 30 | https://github.com/aheritier 31 | 32 | 33 | deepy 34 | Alex Nordlund 35 | https://github.com/deepy 36 | 37 | 38 | 39 | 40 | 41 | Ferdinand Hübner 42 | https://github.com/ferdinandhuebner 43 | 44 | 45 | 46 | 47 | scm:git:https://github.com/deepy/sonar-crowd.git 48 | scm:git:git@github.com:deepy/sonar-crowd.git 49 | https://github.com/deepy/sonar-crowd 50 | HEAD 51 | 52 | 53 | 54 | GitHub Issues 55 | https://github.com/deepy/sonar-crowd/issues 56 | 57 | 58 | 59 | UTF-8 60 | 8.9.0.43852 61 | Crowd 62 | org.sonar.plugins.crowd.CrowdPlugin 63 | 1.8 64 | 1.8 65 | 66 | 67 | 68 | 69 | org.sonarsource.sonarqube 70 | sonar-plugin-api 71 | ${sonar.version} 72 | provided 73 | 74 | 75 | com.atlassian.crowd 76 | crowd-integration-client-rest 77 | 2.7.2 78 | 79 | 80 | 81 | commons-logging 82 | commons-logging 83 | 84 | 85 | log4j 86 | log4j 87 | 88 | 89 | 90 | 91 | org.slf4j 92 | jcl-over-slf4j 93 | 1.7.25 94 | 95 | 96 | javax.xml.bind 97 | jaxb-api 98 | 2.3.0 99 | 100 | 101 | javax.activation 102 | activation 103 | 1.1 104 | 105 | 106 | org.glassfish.jaxb 107 | jaxb-runtime 108 | 2.3.0 109 | 110 | 111 | com.sun.xml.bind 112 | jaxb-core 113 | 2.3.0 114 | 115 | 116 | 117 | org.sonarsource.sonarqube 118 | sonar-testing-harness 119 | ${sonar.version} 120 | test 121 | 122 | 123 | org.mockito 124 | mockito-core 125 | 2.18.0 126 | test 127 | 128 | 129 | org.hamcrest 130 | hamcrest-all 131 | test 132 | 1.3 133 | 134 | 135 | junit 136 | junit 137 | 4.13.1 138 | test 139 | 140 | 141 | org.sonarsource.sonarqube 142 | sonar-plugin-api-impl 143 | ${sonar.version} 144 | test 145 | 146 | 147 | 148 | 149 | 150 | atlassian 151 | https://packages.atlassian.com/maven-public-legacy-local 152 | 153 | 154 | 155 | 156 | 157 | 158 | org.apache.maven.plugins 159 | maven-compiler-plugin 160 | 3.8.1 161 | 162 | 8 163 | 8 164 | 165 | 166 | 167 | org.sonarsource.sonar-packaging-maven-plugin 168 | sonar-packaging-maven-plugin 169 | 1.17 170 | true 171 | 172 | ${sonar.pluginClass} 173 | 174 | 175 | 176 | 177 | 178 | -------------------------------------------------------------------------------- /src/main/java/org/sonar/plugins/crowd/CrowdAuthenticator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Sonar Crowd Plugin 3 | * Copyright (C) 2009 ${owner} 4 | * dev@sonar.codehaus.org 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU Lesser General Public 8 | * License as published by the Free Software Foundation; either 9 | * version 3 of the License, or (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public 17 | * License along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 19 | */ 20 | package org.sonar.plugins.crowd; 21 | 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | import org.sonar.api.security.Authenticator; 25 | 26 | import com.atlassian.crowd.exception.ApplicationPermissionException; 27 | import com.atlassian.crowd.exception.ExpiredCredentialException; 28 | import com.atlassian.crowd.exception.InactiveAccountException; 29 | import com.atlassian.crowd.exception.InvalidAuthenticationException; 30 | import com.atlassian.crowd.exception.OperationFailedException; 31 | import com.atlassian.crowd.exception.UserNotFoundException; 32 | import com.atlassian.crowd.service.client.CrowdClient; 33 | 34 | /** 35 | * @author Evgeny Mandrikov 36 | */ 37 | public class CrowdAuthenticator extends Authenticator { 38 | 39 | private static final Logger LOG = LoggerFactory.getLogger(CrowdAuthenticator.class); 40 | 41 | private final CrowdClient client; 42 | 43 | public CrowdAuthenticator(CrowdClient client) { 44 | this.client = client; 45 | } 46 | 47 | @Override 48 | public boolean doAuthenticate(final Context context) { 49 | final String username = context.getUsername(); 50 | final String password = context.getPassword(); 51 | return authenticate(username, password); 52 | } 53 | 54 | 55 | public boolean authenticate(String login, String password) { 56 | // Had to add that as from "not really a good idea" in 57 | // https://stackoverflow.com/questions/51518781/jaxb-not-available-on-tomcat-9-and-java-9-10 58 | ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader(); 59 | try { 60 | // This will enforce the crowClient to use the plugin classloader 61 | Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); 62 | try { 63 | client.authenticateUser(login, password); 64 | return true; 65 | } catch (UserNotFoundException e) { 66 | LOG.debug("User {} not found", login); 67 | return false; 68 | } catch (InactiveAccountException e) { 69 | LOG.debug("User {} is not active", login); 70 | return false; 71 | } catch (ExpiredCredentialException e) { 72 | LOG.debug("Credentials of user {} have expired", login); 73 | return false; 74 | } catch (ApplicationPermissionException e) { 75 | LOG.error("The application is not permitted to perform the requested operation" 76 | + " on the crowd server", e); 77 | return false; 78 | } catch (InvalidAuthenticationException e) { 79 | LOG.debug("Invalid credentials for user {}", login); 80 | return false; 81 | } catch (OperationFailedException e) { 82 | LOG.error("Unable to authenticate user " + login, e); 83 | return false; 84 | } 85 | } finally { 86 | // Bring back the original class loader for the thread 87 | Thread.currentThread().setContextClassLoader(threadClassLoader); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/org/sonar/plugins/crowd/CrowdConfiguration.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Sonar Crowd Plugin 3 | * Copyright (C) 2009 ${owner} 4 | * dev@sonar.codehaus.org 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU Lesser General Public 8 | * License as published by the Free Software Foundation; either 9 | * version 3 of the License, or (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public 17 | * License along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 19 | */ 20 | package org.sonar.plugins.crowd; 21 | 22 | import org.sonar.api.config.Configuration; 23 | import org.sonar.api.server.ServerSide; 24 | 25 | /** 26 | * @author Evgeny Mandrikov 27 | */ 28 | @ServerSide 29 | public class CrowdConfiguration { 30 | 31 | static final String KEY_CROWD_URL = "crowd.url"; 32 | static final String KEY_CROWD_APP_NAME = "crowd.application"; 33 | static final String KEY_CROWD_APP_PASSWORD = "crowd.password"; 34 | static final String FALLBACK_NAME = "sonar"; 35 | private final Configuration settings; 36 | 37 | /** 38 | * Creates new instance of CrowdConfiguration. 39 | * 40 | * @param settings configuration 41 | */ 42 | public CrowdConfiguration(Configuration settings) { 43 | this.settings = settings; 44 | } 45 | 46 | /** 47 | * The name that the application will use when authenticating with the Crowd server.
48 | * Uses the settings key {@value #KEY_CROWD_APP_NAME} 49 | */ 50 | public String getCrowdApplicationName() { 51 | return settings.get(KEY_CROWD_APP_NAME).orElse(FALLBACK_NAME); 52 | } 53 | 54 | /** 55 | * The password that the application will use when authenticating with the Crowd server.
56 | * Uses the settings key {@value #KEY_CROWD_APP_PASSWORD} 57 | */ 58 | public String getCrowdApplicationPassword() { 59 | return settings 60 | .get(KEY_CROWD_APP_PASSWORD) 61 | .orElseThrow(() -> new IllegalArgumentException(KEY_CROWD_APP_PASSWORD + " is not set")); 62 | } 63 | 64 | /** 65 | * The base URL of the crowd server, e.g. http://127.0.0.1:8095/crowd}.
66 | * Uses the settings key {@value #KEY_CROWD_URL} 67 | */ 68 | public String getCrowdUrl() { 69 | return settings 70 | .get(KEY_CROWD_URL) 71 | .orElseThrow(() -> new IllegalArgumentException(KEY_CROWD_URL + " is not set")); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/org/sonar/plugins/crowd/CrowdGroupsProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Sonar Crowd Plugin 3 | * Copyright (C) 2009 ${owner} 4 | * dev@sonar.codehaus.org 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU Lesser General Public 8 | * License as published by the Free Software Foundation; either 9 | * version 3 of the License, or (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public 17 | * License along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 19 | */ 20 | package org.sonar.plugins.crowd; 21 | 22 | import static com.google.common.collect.Collections2.transform; 23 | 24 | import java.util.Collection; 25 | import java.util.LinkedHashSet; 26 | import java.util.List; 27 | 28 | import org.slf4j.Logger; 29 | import org.slf4j.LoggerFactory; 30 | import org.sonar.api.security.ExternalGroupsProvider; 31 | import org.sonar.api.utils.SonarException; 32 | 33 | import com.atlassian.crowd.exception.ApplicationPermissionException; 34 | import com.atlassian.crowd.exception.InvalidAuthenticationException; 35 | import com.atlassian.crowd.exception.OperationFailedException; 36 | import com.atlassian.crowd.exception.UserNotFoundException; 37 | import com.atlassian.crowd.model.group.Group; 38 | import com.atlassian.crowd.service.client.CrowdClient; 39 | import com.google.common.base.Function; 40 | import com.google.common.collect.ImmutableList; 41 | 42 | import javax.annotation.CheckForNull; 43 | 44 | /** 45 | * External groups provider implementation for Atlassian Crowd. 46 | */ 47 | public class CrowdGroupsProvider extends ExternalGroupsProvider { 48 | 49 | private static final Logger LOG = LoggerFactory.getLogger(CrowdGroupsProvider.class); 50 | private static final int PAGING_SIZE = 100; // no idea what a reasonable size might be 51 | private static final Function GROUP_TO_STRING = new Function() { 52 | public String apply(Group input) { 53 | return input.getName(); 54 | } 55 | }; 56 | private final CrowdClient crowdClient; 57 | 58 | public CrowdGroupsProvider(CrowdClient crowdClient) { 59 | this.crowdClient = crowdClient; 60 | } 61 | 62 | private Collection getGroupsForUser(String username, int start, int pageSize) 63 | throws UserNotFoundException, OperationFailedException, InvalidAuthenticationException, 64 | ApplicationPermissionException { 65 | // Had to add that as from "not really a good idea" in 66 | // https://stackoverflow.com/questions/51518781/jaxb-not-available-on-tomcat-9-and-java-9-10 67 | ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader(); 68 | try { 69 | // This will enforce the crowClient to use the plugin classloader 70 | Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); 71 | return transform(crowdClient.getGroupsForNestedUser(username, start, pageSize), GROUP_TO_STRING); 72 | } finally { 73 | // Bring back the original class loader for the thread 74 | Thread.currentThread().setContextClassLoader(threadClassLoader); 75 | } 76 | } 77 | 78 | private List getGroupsForUser(String username) 79 | throws UserNotFoundException, 80 | OperationFailedException, InvalidAuthenticationException, 81 | ApplicationPermissionException { 82 | 83 | Collection groups = new LinkedHashSet(); 84 | boolean mightHaveMore = true; 85 | int groupIndex = 0; 86 | Collection newGroups; 87 | 88 | while (mightHaveMore) { 89 | newGroups = getGroupsForUser(username, groupIndex, PAGING_SIZE); 90 | if (newGroups.size() < PAGING_SIZE) { 91 | mightHaveMore = false; 92 | } 93 | groups.addAll(newGroups); 94 | groupIndex += newGroups.size(); 95 | } 96 | return ImmutableList.copyOf(groups); 97 | } 98 | 99 | @Override 100 | public Collection doGetGroups(final Context context) 101 | { 102 | return doGetGroups(context.getUsername()); 103 | } 104 | 105 | public Collection doGetGroups(String username) { 106 | LOG.debug("Looking up user groups for user {}", username); 107 | 108 | try { 109 | return getGroupsForUser(username); 110 | } catch (UserNotFoundException e) { 111 | return null; // API contract for ExternalGroupsProvider 112 | } catch (OperationFailedException e) { 113 | throw new SonarException("Unable to retrieve groups for user" + username + " from crowd.", e); 114 | } catch (ApplicationPermissionException e) { 115 | throw new SonarException("Unable to retrieve groups for user" + username 116 | + " from crowd. The application name and password are incorrect.", e); 117 | } catch (InvalidAuthenticationException e) { 118 | throw new SonarException( 119 | "Unable to retrieve groups for user" + username 120 | + " from crowd. The application is not permitted to perform the " 121 | + "requested operation on the crowd server.", e); 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/org/sonar/plugins/crowd/CrowdPlugin.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Sonar Crowd Plugin 3 | * Copyright (C) 2009 ${owner} 4 | * dev@sonar.codehaus.org 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU Lesser General Public 8 | * License as published by the Free Software Foundation; either 9 | * version 3 of the License, or (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public 17 | * License along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 19 | */ 20 | package org.sonar.plugins.crowd; 21 | 22 | import org.sonar.api.Plugin; 23 | 24 | /** 25 | * @author Evgeny Mandrikov 26 | */ 27 | public class CrowdPlugin implements Plugin { 28 | public void define(final Context context) { 29 | context.addExtensions(CrowdRealm.class, CrowdConfiguration.class); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/sonar/plugins/crowd/CrowdRealm.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Sonar Crowd Plugin 3 | * Copyright (C) 2009 ${owner} 4 | * dev@sonar.codehaus.org 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU Lesser General Public 8 | * License as published by the Free Software Foundation; either 9 | * version 3 of the License, or (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public 17 | * License along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 19 | */ 20 | package org.sonar.plugins.crowd; 21 | 22 | import java.util.Properties; 23 | 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | import org.sonar.api.security.Authenticator; 27 | import org.sonar.api.security.ExternalGroupsProvider; 28 | import org.sonar.api.security.ExternalUsersProvider; 29 | import org.sonar.api.security.SecurityRealm; 30 | import org.sonar.api.utils.SonarException; 31 | 32 | import com.atlassian.crowd.exception.ApplicationPermissionException; 33 | import com.atlassian.crowd.exception.InvalidAuthenticationException; 34 | import com.atlassian.crowd.exception.OperationFailedException; 35 | import com.atlassian.crowd.integration.rest.service.factory.RestCrowdClientFactory; 36 | import com.atlassian.crowd.service.client.ClientProperties; 37 | import com.atlassian.crowd.service.client.ClientPropertiesImpl; 38 | import com.atlassian.crowd.service.client.CrowdClient; 39 | 40 | /** 41 | * Sonar security realm for Atlassian Crowd. 42 | */ 43 | public class CrowdRealm extends SecurityRealm { 44 | 45 | private static final Logger LOG = LoggerFactory.getLogger(CrowdRealm.class); 46 | 47 | private final CrowdConfiguration crowdConfiguration; 48 | 49 | private CrowdClient crowdClient; 50 | private CrowdAuthenticator authenticator; 51 | private CrowdUsersProvider usersProvider; 52 | private CrowdGroupsProvider groupsProvider; 53 | 54 | public CrowdRealm(CrowdConfiguration crowdConfiguration) { 55 | this.crowdConfiguration = crowdConfiguration; 56 | } 57 | 58 | private CrowdClient createCrowdClient(CrowdConfiguration configuration) { 59 | Properties crowdProperties = new Properties(); 60 | // The name that the application will use when authenticating with the Crowd server. 61 | crowdProperties.setProperty("application.name", configuration.getCrowdApplicationName()); 62 | // The password that the application will use when authenticating with the Crowd server. 63 | crowdProperties.setProperty("application.password", configuration.getCrowdApplicationPassword()); 64 | // Crowd will redirect the user to this URL if their authentication token expires or is invalid due to security restrictions. 65 | // crowdProperties.setProperty("application.login.url", ""); 66 | // The URL to use when connecting with the integration libraries to communicate with the Crowd server. 67 | // crowdProperties.setProperty("crowd.server.url", ""); 68 | // The URL used by Crowd to create the full URL to be sent to users that reset their passwords. 69 | crowdProperties.setProperty("crowd.base.url", configuration.getCrowdUrl()); 70 | // The session key to use when storing a Boolean value indicating whether the user is authenticated or not. 71 | crowdProperties.setProperty("session.isauthenticated", "session.isauthenticated"); 72 | // The session key to use when storing a String value of the user's authentication token. 73 | crowdProperties.setProperty("session.tokenkey", "session.tokenkey"); 74 | // The number of minutes to cache authentication validation in the session. If this value is set to 0, each HTTP request will be 75 | // authenticated with the Crowd server. 76 | crowdProperties.setProperty("session.validationinterval", "1"); 77 | // The session key to use when storing a Date value of the user's last authentication. 78 | crowdProperties.setProperty("session.lastvalidation", "session.lastvalidation"); 79 | // Perhaps more things to let users to configure in the future 80 | // (see https://confluence.atlassian.com/display/CROWD/The+crowd.properties+file) 81 | ClientProperties clientProperties = ClientPropertiesImpl.newInstanceFromProperties(crowdProperties); 82 | return new RestCrowdClientFactory().newInstance(clientProperties); 83 | } 84 | 85 | @Override 86 | public String getName() { 87 | return "Crowd"; 88 | } 89 | 90 | @Override 91 | public void init() { 92 | this.crowdClient = createCrowdClient(crowdConfiguration); 93 | this.authenticator = new CrowdAuthenticator(crowdClient); 94 | this.usersProvider = new CrowdUsersProvider(crowdClient); 95 | this.groupsProvider = new CrowdGroupsProvider(crowdClient); 96 | // Had to add that as from "not really a good idea" in 97 | // https://stackoverflow.com/questions/51518781/jaxb-not-available-on-tomcat-9-and-java-9-10 98 | ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader(); 99 | try { 100 | // This will enforce the crowClient to use the plugin classloader 101 | Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); 102 | try { 103 | crowdClient.testConnection(); 104 | LOG.info("Crowd configuration is valid, connection test successful."); 105 | } catch (OperationFailedException e) { 106 | throw new SonarException("Unable to test connection to crowd", e); 107 | } catch (InvalidAuthenticationException e) { 108 | throw new SonarException("Application name and password are incorrect", e); 109 | } catch (ApplicationPermissionException e) { 110 | throw new SonarException("The application is not permitted to perform the requested " 111 | + "operation on the crowd server", e); 112 | } 113 | } finally { 114 | // Bring back the original class loader for the thread 115 | Thread.currentThread().setContextClassLoader(threadClassLoader); 116 | } 117 | } 118 | 119 | @Override 120 | public Authenticator doGetAuthenticator() { 121 | return authenticator; 122 | } 123 | 124 | @Override 125 | public ExternalGroupsProvider getGroupsProvider() { 126 | return groupsProvider; 127 | } 128 | 129 | @Override 130 | public ExternalUsersProvider getUsersProvider() { 131 | return usersProvider; 132 | } 133 | 134 | } 135 | -------------------------------------------------------------------------------- /src/main/java/org/sonar/plugins/crowd/CrowdUsersProvider.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Sonar Crowd Plugin 3 | * Copyright (C) 2009 ${owner} 4 | * dev@sonar.codehaus.org 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU Lesser General Public 8 | * License as published by the Free Software Foundation; either 9 | * version 3 of the License, or (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public 17 | * License along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 19 | */ 20 | package org.sonar.plugins.crowd; 21 | 22 | import com.atlassian.crowd.exception.ApplicationPermissionException; 23 | import com.atlassian.crowd.exception.InvalidAuthenticationException; 24 | import com.atlassian.crowd.exception.OperationFailedException; 25 | import com.atlassian.crowd.exception.UserNotFoundException; 26 | import com.atlassian.crowd.model.user.User; 27 | import com.atlassian.crowd.service.client.CrowdClient; 28 | import org.slf4j.Logger; 29 | import org.slf4j.LoggerFactory; 30 | import org.sonar.api.security.ExternalUsersProvider; 31 | import org.sonar.api.security.UserDetails; 32 | import org.sonar.api.utils.SonarException; 33 | 34 | /** 35 | * External users provider implementation for Atlassian Crowd. 36 | */ 37 | public class CrowdUsersProvider extends ExternalUsersProvider { 38 | 39 | private static final Logger LOG = LoggerFactory.getLogger(CrowdUsersProvider.class); 40 | 41 | private final CrowdClient crowdClient; 42 | 43 | public CrowdUsersProvider(CrowdClient crowdClient) { 44 | this.crowdClient = crowdClient; 45 | } 46 | 47 | @Override 48 | public UserDetails doGetUserDetails(final Context context) 49 | { 50 | return doGetUserDetails(context.getUsername()); 51 | } 52 | 53 | public UserDetails doGetUserDetails(String username) { 54 | LOG.debug("Looking up user details for user {}", username); 55 | // Had to add that as from "not really a good idea" in 56 | // https://stackoverflow.com/questions/51518781/jaxb-not-available-on-tomcat-9-and-java-9-10 57 | ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader(); 58 | try { 59 | // This will enforce the crowClient to use the plugin classloader 60 | Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); 61 | try { 62 | User user = crowdClient.getUser(username); 63 | UserDetails details = new UserDetails(); 64 | if (user.getDisplayName() != null) { 65 | details.setName(user.getDisplayName()); 66 | } 67 | if (user.getEmailAddress() != null) { 68 | details.setEmail(user.getEmailAddress()); 69 | } 70 | return details; 71 | } catch (UserNotFoundException e) { 72 | return null; // API contract for ExternalUsersProvider 73 | } catch (OperationFailedException e) { 74 | throw new SonarException("Unable to retrieve user details for user" + username 75 | + " from crowd.", e); 76 | } catch (ApplicationPermissionException e) { 77 | throw new SonarException( 78 | "Unable to retrieve user details for user" + username 79 | + " from crowd. The application is not permitted to perform the " 80 | + "requested operation on the crowd server.", e); 81 | } catch (InvalidAuthenticationException e) { 82 | throw new SonarException("Unable to retrieve user details for user" + username 83 | + " from crowd. The application name and password are incorrect.", e); 84 | } 85 | } finally { 86 | // Bring back the original class loader for the thread 87 | Thread.currentThread().setContextClassLoader(threadClassLoader); 88 | } 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/resources/crowd-ehcache.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 39 | 47 | 49 | 57 | 59 | 67 | 69 | 77 | 79 | 87 | 89 | 97 | 101 | 109 | 111 | 119 | 121 | 129 | 131 | 139 | 141 | 149 | 150 | 151 | -------------------------------------------------------------------------------- /src/test/java/org/sonar/plugins/crowd/CrowdAuthenticatorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Sonar Crowd Plugin 3 | * Copyright (C) 2009 ${owner} 4 | * dev@sonar.codehaus.org 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU Lesser General Public 8 | * License as published by the Free Software Foundation; either 9 | * version 3 of the License, or (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public 17 | * License along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 19 | */ 20 | package org.sonar.plugins.crowd; 21 | 22 | import com.atlassian.crowd.exception.InvalidAuthenticationException; 23 | import com.atlassian.crowd.exception.UserNotFoundException; 24 | import com.atlassian.crowd.model.user.User; 25 | import com.atlassian.crowd.service.client.CrowdClient; 26 | import org.junit.Test; 27 | 28 | import static org.hamcrest.Matchers.is; 29 | import static org.junit.Assert.assertThat; 30 | import static org.mockito.Matchers.anyString; 31 | import static org.mockito.Matchers.eq; 32 | import static org.mockito.Mockito.mock; 33 | import static org.mockito.Mockito.when; 34 | 35 | public class CrowdAuthenticatorTest { 36 | 37 | @Test 38 | public void authenticatorReturnsTrueForSuccessfulLogin() throws Exception { 39 | CrowdClient client = mock(CrowdClient.class); 40 | User user = mock(User.class); 41 | CrowdAuthenticator authenticator = new CrowdAuthenticator(client); 42 | 43 | when(client.authenticateUser(eq("user1"), eq("secret"))).thenReturn(user); 44 | assertThat(authenticator.authenticate("user1", "secret"), is(true)); 45 | 46 | when(client.authenticateUser(anyString(), anyString())) 47 | .thenThrow(new UserNotFoundException("")); 48 | assertThat(authenticator.authenticate("user2", "secret"), is(false)); 49 | } 50 | 51 | @Test 52 | public void authenticatorReturnsFalseForInvalidPassword() throws Exception { 53 | CrowdClient client = mock(CrowdClient.class); 54 | CrowdAuthenticator authenticator = new CrowdAuthenticator(client); 55 | 56 | when(client.authenticateUser(anyString(), anyString())).thenThrow( 57 | new InvalidAuthenticationException("")); 58 | assertThat(authenticator.authenticate("user1", "secret"), is(false)); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/org/sonar/plugins/crowd/CrowdConfigurationTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Sonar Crowd Plugin 3 | * Copyright (C) 2009 ${owner} 4 | * dev@sonar.codehaus.org 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU Lesser General Public 8 | * License as published by the Free Software Foundation; either 9 | * version 3 of the License, or (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public 17 | * License along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 19 | */ 20 | package org.sonar.plugins.crowd; 21 | 22 | import static org.hamcrest.Matchers.is; 23 | import static org.junit.Assert.assertThat; 24 | 25 | import org.junit.Test; 26 | import org.sonar.api.config.internal.MapSettings; 27 | 28 | public class CrowdConfigurationTest { 29 | 30 | @Test(expected = IllegalArgumentException.class) 31 | public void crowdUrlMissing() { 32 | MapSettings settings = new MapSettings(); 33 | new CrowdConfiguration(settings.asConfig()).getCrowdUrl(); 34 | } 35 | 36 | @Test(expected = IllegalArgumentException.class) 37 | public void applicationPasswordMissing() { 38 | MapSettings settings = new MapSettings(); 39 | settings.setProperty(CrowdConfiguration.KEY_CROWD_URL, "http://localhost:8095"); 40 | new CrowdConfiguration(settings.asConfig()).getCrowdApplicationPassword(); 41 | } 42 | 43 | @Test 44 | public void usesFallbackForUnsetApplicationName() { 45 | MapSettings settings = new MapSettings(); 46 | settings.setProperty(CrowdConfiguration.KEY_CROWD_URL, "http://localhost:8095"); 47 | settings.setProperty(CrowdConfiguration.KEY_CROWD_APP_PASSWORD, "secret"); 48 | CrowdConfiguration crowdConfiguration = new CrowdConfiguration(settings.asConfig()); 49 | assertThat(crowdConfiguration.getCrowdApplicationName(), is(CrowdConfiguration.FALLBACK_NAME)); 50 | } 51 | 52 | @Test 53 | public void createsClientProperties() { 54 | MapSettings settings = new MapSettings(); 55 | settings.setProperty(CrowdConfiguration.KEY_CROWD_URL, "http://localhost:8095"); 56 | settings.setProperty(CrowdConfiguration.KEY_CROWD_APP_NAME, "SonarQube"); 57 | settings.setProperty(CrowdConfiguration.KEY_CROWD_APP_PASSWORD, "secret"); 58 | CrowdConfiguration crowdConfiguration = new CrowdConfiguration(settings.asConfig()); 59 | 60 | assertThat(crowdConfiguration.getCrowdUrl(), is("http://localhost:8095")); 61 | assertThat(crowdConfiguration.getCrowdApplicationName(), is("SonarQube")); 62 | assertThat(crowdConfiguration.getCrowdApplicationPassword(), is("secret")); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/test/java/org/sonar/plugins/crowd/CrowdGroupsProviderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Sonar Crowd Plugin 3 | * Copyright (C) 2009 ${owner} 4 | * dev@sonar.codehaus.org 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU Lesser General Public 8 | * License as published by the Free Software Foundation; either 9 | * version 3 of the License, or (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public 17 | * License along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 19 | */ 20 | package org.sonar.plugins.crowd; 21 | 22 | import com.atlassian.crowd.exception.OperationFailedException; 23 | import com.atlassian.crowd.exception.UserNotFoundException; 24 | import com.atlassian.crowd.model.group.Group; 25 | import com.atlassian.crowd.service.client.CrowdClient; 26 | import com.google.common.collect.ImmutableList.Builder; 27 | import com.google.common.collect.Lists; 28 | import org.junit.Test; 29 | import org.sonar.api.utils.SonarException; 30 | 31 | import java.util.LinkedList; 32 | import java.util.List; 33 | 34 | import static org.hamcrest.Matchers.is; 35 | import static org.hamcrest.Matchers.nullValue; 36 | import static org.junit.Assert.assertThat; 37 | import static org.mockito.Matchers.anyInt; 38 | import static org.mockito.Matchers.anyString; 39 | import static org.mockito.Matchers.eq; 40 | import static org.mockito.Mockito.*; 41 | 42 | public class CrowdGroupsProviderTest { 43 | 44 | @Test 45 | public void returnsNullIfTheUserWasNotFound() throws Exception { 46 | CrowdClient client = mock(CrowdClient.class); 47 | when(client.getGroupsForNestedUser(anyString(), anyInt(), anyInt())).thenThrow( 48 | new UserNotFoundException("")); 49 | assertThat(new CrowdGroupsProvider(client).doGetGroups("user"), is(nullValue())); 50 | } 51 | 52 | @Test(expected = SonarException.class) 53 | public void throwsSonarExceptionIfCommunicationWithCrowdFails() throws Exception { 54 | CrowdClient client = mock(CrowdClient.class); 55 | when(client.getGroupsForNestedUser(anyString(), anyInt(), anyInt())).thenThrow( 56 | new OperationFailedException("")); 57 | new CrowdGroupsProvider(client).doGetGroups("user"); 58 | } 59 | 60 | private List makeGroups(int count, int offset) { 61 | Builder builder = new Builder(); 62 | for (int i = 0; i < count; i++) { 63 | Group group = mock(Group.class); 64 | when(group.getName()).thenReturn("group" + (offset + i)); 65 | builder.add(group); 66 | } 67 | return builder.build(); 68 | } 69 | 70 | private List makeGroups(int count) { 71 | return makeGroups(count, 0); 72 | } 73 | 74 | @Test 75 | public void returnsGroups() throws Exception { 76 | CrowdClient client = mock(CrowdClient.class); 77 | 78 | List groups = makeGroups(10); 79 | when(client.getGroupsForNestedUser(anyString(), anyInt(), anyInt())).thenReturn(groups); 80 | 81 | List resolvedGroups = 82 | Lists.newLinkedList(new CrowdGroupsProvider(client).doGetGroups("user")); 83 | assertThat(resolvedGroups.size(), is(groups.size())); 84 | for (int i = 0; i < groups.size(); i++) { 85 | assertThat(resolvedGroups.get(i), is(groups.get(i).getName())); 86 | } 87 | verify(client, times(1)).getGroupsForNestedUser(anyString(), anyInt(), anyInt()); 88 | } 89 | 90 | @Test 91 | public void performsPagination() throws Exception { 92 | CrowdClient client = mock(CrowdClient.class); 93 | 94 | List firstGroups = makeGroups(100); 95 | List secondGroups = makeGroups(25, 100); 96 | List allGroups = new LinkedList(); 97 | allGroups.addAll(firstGroups); 98 | allGroups.addAll(secondGroups); 99 | when(client.getGroupsForNestedUser(anyString(), eq(0), anyInt())).thenReturn(firstGroups); 100 | when(client.getGroupsForNestedUser(anyString(), eq(100), anyInt())).thenReturn(secondGroups); 101 | 102 | List resolvedGroups = 103 | Lists.newLinkedList(new CrowdGroupsProvider(client).doGetGroups("user")); 104 | assertThat(resolvedGroups.size(), is(125)); 105 | for (int i = 0; i < resolvedGroups.size(); i++) { 106 | assertThat(resolvedGroups.get(i), is(allGroups.get(i).getName())); 107 | } 108 | verify(client, times(2)).getGroupsForNestedUser(anyString(), anyInt(), anyInt()); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/test/java/org/sonar/plugins/crowd/CrowdUsersProviderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Sonar Crowd Plugin 3 | * Copyright (C) 2009 ${owner} 4 | * dev@sonar.codehaus.org 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU Lesser General Public 8 | * License as published by the Free Software Foundation; either 9 | * version 3 of the License, or (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 | * Lesser General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU Lesser General Public 17 | * License along with this program; if not, write to the Free Software 18 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 19 | */ 20 | package org.sonar.plugins.crowd; 21 | 22 | import com.atlassian.crowd.exception.OperationFailedException; 23 | import com.atlassian.crowd.exception.UserNotFoundException; 24 | import com.atlassian.crowd.model.user.User; 25 | import com.atlassian.crowd.service.client.CrowdClient; 26 | import org.junit.Test; 27 | import org.sonar.api.security.UserDetails; 28 | import org.sonar.api.utils.SonarException; 29 | 30 | import static org.hamcrest.Matchers.*; 31 | import static org.junit.Assert.assertThat; 32 | import static org.mockito.Matchers.anyString; 33 | import static org.mockito.Mockito.mock; 34 | import static org.mockito.Mockito.when; 35 | 36 | public class CrowdUsersProviderTest { 37 | 38 | @Test 39 | public void returnsNullIfTheUserWasNotFound() throws Exception { 40 | CrowdClient client = mock(CrowdClient.class); 41 | when(client.getUser(anyString())).thenThrow(new UserNotFoundException("")); 42 | 43 | CrowdUsersProvider provider = new CrowdUsersProvider(client); 44 | assertThat(provider.doGetUserDetails("user"), is(nullValue())); 45 | } 46 | 47 | @Test 48 | public void returnsTheCrowdDisplayNameAndEmailAddress() throws Exception { 49 | CrowdClient client = mock(CrowdClient.class); 50 | User user = mock(User.class); 51 | when(user.getDisplayName()).thenReturn("display name"); 52 | when(user.getEmailAddress()).thenReturn("foo@acme.corp"); 53 | when(client.getUser(anyString())).thenReturn(user); 54 | 55 | CrowdUsersProvider provider = new CrowdUsersProvider(client); 56 | UserDetails userDetails = provider.doGetUserDetails("user"); 57 | assertThat(userDetails, is(notNullValue())); 58 | assertThat(userDetails.getEmail(), is("foo@acme.corp")); 59 | assertThat(userDetails.getName(), is("display name")); 60 | } 61 | 62 | @Test(expected = SonarException.class) 63 | public void throwsSonarExceptionIfCrowdCommunicationFails() throws Exception { 64 | CrowdClient client = mock(CrowdClient.class); 65 | when(client.getUser(anyString())).thenThrow(new OperationFailedException("")); 66 | new CrowdUsersProvider(client).doGetUserDetails("user"); 67 | } 68 | } 69 | --------------------------------------------------------------------------------