Leon4gr45 commited on
Commit
c81af1b
·
verified ·
1 Parent(s): 1e04769

Upload folder using huggingface_hub (part 29)

Browse files
Files changed (43) hide show
  1. .gitattributes +3 -0
  2. plugins/LoginLdap/.github/scripts/setup_ldap.sh +345 -0
  3. plugins/LoginLdap/.github/workflows/matomo-ai-checklist.yml +32 -0
  4. plugins/LoginLdap/.github/workflows/matomo-tests.yml +78 -0
  5. plugins/LoginLdap/.github/workflows/phpcs.yml +43 -0
  6. plugins/LoginLdap/.gitignore +7 -0
  7. plugins/LoginLdap/phpcs.xml +36 -0
  8. plugins/LoginLdap/phpstan.neon +18 -0
  9. plugins/LoginLdap/screenshots/LoginLdap_Admin_admin_page.png +0 -0
  10. plugins/LoginLdap/tests/Integration/ApiTest.php +288 -0
  11. plugins/LoginLdap/tests/Integration/AuthenticationTest.php +243 -0
  12. plugins/LoginLdap/tests/Integration/BackwardsCompatibilityTest.php +49 -0
  13. plugins/LoginLdap/tests/Integration/Commands/SynchronizeUsersTest.php +143 -0
  14. plugins/LoginLdap/tests/Integration/LdapIntegrationTest.php +187 -0
  15. plugins/LoginLdap/tests/Integration/LdapUserSynchronizationTest.php +355 -0
  16. plugins/LoginLdap/tests/Integration/MultipleServersTest.php +82 -0
  17. plugins/LoginLdap/tests/Integration/PasswordConfirmationTest.php +232 -0
  18. plugins/LoginLdap/tests/Integration/SynchronizedAuthTest.php +222 -0
  19. plugins/LoginLdap/tests/Integration/WebServerAuthTest.php +201 -0
  20. plugins/LoginLdap/tests/Mocks/LdapFunctions.php +89 -0
  21. plugins/LoginLdap/tests/System/CheckDirectDependencyUseCommandTest.php +49 -0
  22. plugins/LoginLdap/tests/System/Output/TestOutput.php +15 -0
  23. plugins/LoginLdap/tests/System/SynchronizeUsersCommandTest.php +77 -0
  24. plugins/LoginLdap/tests/System/SystemAuthTest.php +208 -0
  25. plugins/LoginLdap/tests/System/expected/test_SynchronizeUsersCommandTest_no_purge__LoginLdap.getExistingLdapUsersFromDb.xml +6 -0
  26. plugins/LoginLdap/tests/System/expected/test_SynchronizeUsersCommandTest_purge__LoginLdap.getExistingLdapUsersFromDb.xml +5 -0
  27. plugins/LoginLdap/tests/UI/Admin_spec.js +126 -0
  28. plugins/LoginLdap/tests/UI/expected-ui-screenshots/LoginLdap_Admin_addNewToken_with_password.png +0 -0
  29. plugins/LoginLdap/tests/UI/expected-ui-screenshots/LoginLdap_Admin_addNewToken_with_password_non_ldap_user.png +0 -0
  30. plugins/LoginLdap/tests/UI/expected-ui-screenshots/LoginLdap_Admin_addNewToken_without_password.png +0 -0
  31. plugins/LoginLdap/tests/UI/expected-ui-screenshots/LoginLdap_Admin_admin_page.png +0 -0
  32. plugins/LoginLdap/tests/Unit/LdapClientTest.php +347 -0
  33. plugins/LoginLdap/tests/Unit/LdapUsersTest.php +515 -0
  34. plugins/LoginLdap/tests/Unit/ServerInfoTest.php +131 -0
  35. plugins/LoginLdap/tests/Unit/UserAccessAttributeParserTest.php +309 -0
  36. plugins/LoginLdap/tests/Unit/UserAccessMapperTest.php +182 -0
  37. plugins/LoginLdap/tests/Unit/UserMapperTest.php +283 -0
  38. plugins/LoginLdap/tests/Unit/UserSynchronizerTest.php +340 -0
  39. plugins/MarketingCampaignsReporting/.gitattributes +6 -0
  40. plugins/MarketingCampaignsReporting/.github/workflows/matomo-ai-checklist.yml +32 -0
  41. plugins/MarketingCampaignsReporting/.github/workflows/matomo-tests.yml +72 -0
  42. plugins/MarketingCampaignsReporting/.github/workflows/phpcs.yml +43 -0
  43. plugins/MarketingCampaignsReporting/.gitignore +6 -0
.gitattributes CHANGED
@@ -101,3 +101,6 @@ plugins/LogViewer/tests/UI/expected-ui-screenshots/LogViewer_filter_severity.png
101
  plugins/LogViewer/tests/UI/expected-ui-screenshots/LogViewer_info_no_supported_writer.png filter=lfs diff=lfs merge=lfs -text
102
  plugins/LogViewer/tests/UI/expected-ui-screenshots/LogViewer_logview_inital.png filter=lfs diff=lfs merge=lfs -text
103
  plugins/LogViewer/tests/UI/expected-ui-screenshots/LogViewer_search.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
101
  plugins/LogViewer/tests/UI/expected-ui-screenshots/LogViewer_info_no_supported_writer.png filter=lfs diff=lfs merge=lfs -text
102
  plugins/LogViewer/tests/UI/expected-ui-screenshots/LogViewer_logview_inital.png filter=lfs diff=lfs merge=lfs -text
103
  plugins/LogViewer/tests/UI/expected-ui-screenshots/LogViewer_search.png filter=lfs diff=lfs merge=lfs -text
104
+ plugins/LoginLdap/screenshots/LoginLdap_Admin_admin_page.png filter=lfs diff=lfs merge=lfs -text
105
+ plugins/LoginLdap/tests/UI/expected-ui-screenshots/LoginLdap_Admin_addNewToken_without_password.png filter=lfs diff=lfs merge=lfs -text
106
+ plugins/LoginLdap/tests/UI/expected-ui-screenshots/LoginLdap_Admin_admin_page.png filter=lfs diff=lfs merge=lfs -text
plugins/LoginLdap/.github/scripts/setup_ldap.sh ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # install LDAP
4
+ echo "Installing LDAP..."
5
+ sudo apt-get update > /dev/null
6
+ if ! sudo apt-get install slapd ldap-utils -y -qq > /dev/null; then
7
+ echo "Failed to install OpenLDAP!"
8
+ fi
9
+
10
+ # configure LDAP
11
+ echo ""
12
+ echo "Configuring LDAP..."
13
+
14
+ mkdir -p /tmp/ldap
15
+ sudo chmod -R 777 /tmp/ldap
16
+
17
+ ADMIN_USER=fury
18
+ ADMIN_PASS=secrets
19
+ ADMIN_PASS_HASH=`slappasswd -h {md5} -s $ADMIN_PASS`
20
+ BASE_DN="dc=avengers,dc=shield,dc=org"
21
+ MODULE_PATH="/usr/lib/ldap"
22
+ if [ -d "/usr/lib/ldap/modules" ]; then
23
+ MODULE_PATH="/usr/lib/ldap/modules"
24
+ fi
25
+
26
+ STR_OID="1.3.6.1.4.1.1466.115.121.1.15"
27
+ VIEW_OID="2.16.840.1.113730.3.1.1.1"
28
+ ADMIN_OID="2.16.840.1.113730.3.1.1.2"
29
+ SUPERUSER_OID="2.16.840.1.113730.3.1.1.3"
30
+ DB_DN="olcDatabase={1}mdb,cn=config"
31
+ MODULE_DN="cn=module{0},cn=config"
32
+
33
+ sudo ldapmodify -Y EXTERNAL -H ldapi:/// <<EOF
34
+
35
+ dn: cn=config
36
+ changetype: modify
37
+ replace: olcLogLevel
38
+ olcLogLevel: -1
39
+ -
40
+ add: olcDisallows
41
+ olcDisallows: bind_anon
42
+
43
+ EOF
44
+
45
+ if [ "$?" -ne "0" ]; then
46
+ echo "Failed to change config olcLogLevel or olcDisallows!"
47
+ echo ""
48
+ echo "slapd log:"
49
+ sudo grep slapd /var/log/syslog
50
+
51
+ exit 1
52
+ fi
53
+
54
+ sudo ldapadd -Y EXTERNAL -H ldapi:/// <<EOF
55
+
56
+ # modules
57
+ dn: $MODULE_DN
58
+ changetype: modify
59
+ add: olcModuleLoad
60
+ olcModuleLoad: memberof.so
61
+ -
62
+ add: olcModuleLoad
63
+ olcModuleLoad: refint.so
64
+
65
+ EOF
66
+
67
+ if [ "$?" -ne "0" ]; then
68
+ echo "Failed to change config modules!"
69
+ echo ""
70
+ echo "slapd log:"
71
+ sudo grep slapd /var/log/syslog
72
+
73
+ exit 1
74
+ fi
75
+
76
+ sudo ldapmodify -Y EXTERNAL -H ldapi:/// <<EOF
77
+
78
+ # database (suffix first to allow rootdn/rootpw)
79
+ dn: $DB_DN
80
+ changetype: modify
81
+ replace: olcSuffix
82
+ olcSuffix: $BASE_DN
83
+
84
+ EOF
85
+
86
+ if [ "$?" -ne "0" ]; then
87
+ echo "Failed to change config database suffix!"
88
+ echo ""
89
+ echo "slapd log:"
90
+ sudo grep slapd /var/log/syslog
91
+
92
+ exit 1
93
+ fi
94
+
95
+ sudo ldapmodify -Y EXTERNAL -H ldapi:/// <<EOF
96
+
97
+ # database
98
+ dn: $DB_DN
99
+ changetype: modify
100
+ replace: olcRootDN
101
+ olcRootDN: cn=$ADMIN_USER,$BASE_DN
102
+ -
103
+ replace: olcRootPW
104
+ olcRootPW: $ADMIN_PASS_HASH
105
+ -
106
+ replace: olcDbDirectory
107
+ olcDbDirectory: /var/lib/ldap
108
+ -
109
+ replace: olcAccess
110
+ olcAccess: {0}to attrs=userPassword,shadowLastChange by self write by dn="cn=$ADMIN_USER,$BASE_DN" write by * auth
111
+ olcAccess: {1}to dn.base="" by dn="cn=$ADMIN_USER,$BASE_DN" write by * read
112
+ olcAccess: {2}to * by self write by dn="cn=$ADMIN_USER,$BASE_DN" write by * read
113
+ -
114
+ replace: olcRequires
115
+ olcRequires: authc
116
+ -
117
+ replace: olcLastMod
118
+ olcLastMod: TRUE
119
+ -
120
+ replace: olcDbCheckpoint
121
+ olcDbCheckpoint: 512 30
122
+ -
123
+ replace: olcDbIndex
124
+ olcDbIndex: objectClass eq
125
+
126
+ EOF
127
+
128
+ if [ "$?" -ne "0" ]; then
129
+ echo "Failed to change config database!"
130
+ echo ""
131
+ echo "slapd log:"
132
+ sudo grep slapd /var/log/syslog
133
+
134
+ exit 1
135
+ fi
136
+
137
+ MEMBEROF_DN="olcOverlay={0}memberof,$DB_DN"
138
+ sudo ldapadd -Y EXTERNAL -H ldapi:/// <<EOF
139
+ dn: $MEMBEROF_DN
140
+ objectClass: olcConfig
141
+ objectClass: olcMemberOf
142
+ objectClass: olcOverlayConfig
143
+ objectClass: top
144
+ olcOverlay: memberof
145
+ EOF
146
+
147
+ REFINT_DN="olcOverlay={1}refint,$DB_DN"
148
+ sudo ldapadd -Y EXTERNAL -H ldapi:/// <<EOF
149
+ dn: $REFINT_DN
150
+ objectClass: olcConfig
151
+ objectClass: olcOverlayConfig
152
+ objectClass: olcRefintConfig
153
+ objectClass: top
154
+ olcOverlay: {1}refint
155
+ olcRefintAttribute: memberof member manager owner
156
+ EOF
157
+
158
+ sudo ldapadd -Y EXTERNAL -H ldapi:/// <<EOF
159
+
160
+ # custom LDAP schema for Matomo access
161
+ dn: cn=matomo,cn=schema,cn=config
162
+ objectClass: olcSchemaConfig
163
+ cn: matomo
164
+ olcAttributeTypes: ( $VIEW_OID
165
+ NAME 'view'
166
+ DESC 'Describes site IDs user has view access to.'
167
+ EQUALITY caseIgnoreMatch
168
+ ORDERING caseIgnoreOrderingMatch
169
+ SYNTAX $STR_OID )
170
+ olcAttributeTypes: ( $ADMIN_OID
171
+ NAME 'admin'
172
+ DESC 'Describes site IDs user has admin access to.'
173
+ EQUALITY caseIgnoreMatch
174
+ ORDERING caseIgnoreOrderingMatch
175
+ SYNTAX $STR_OID )
176
+ olcAttributeTypes: ( $SUPERUSER_OID
177
+ NAME 'superuser'
178
+ DESC 'Marks user as superuser if present.'
179
+ EQUALITY caseIgnoreMatch
180
+ ORDERING caseIgnoreOrderingMatch
181
+ SYNTAX $STR_OID )
182
+ olcObjectClasses: ( 2.16.840.1.113730.3.2.3
183
+ NAME 'piwikPerson'
184
+ DESC 'Piwik User'
185
+ SUP inetOrgPerson
186
+ STRUCTURAL
187
+ MAY ( view $ admin $ superuser )
188
+ )
189
+
190
+ EOF
191
+
192
+ if [ "$?" -ne "0" ]; then
193
+ echo "Failed to add custom attributes!"
194
+ echo ""
195
+ echo "slapd log:"
196
+ sudo grep slapd /var/log/syslog
197
+
198
+ exit 1
199
+ fi
200
+
201
+ echo "Configured."
202
+
203
+ # add entries to LDAP
204
+ echo ""
205
+ echo "Adding entries to LDAP..."
206
+
207
+ sudo ldapadd -xv -w $ADMIN_PASS -D cn=$ADMIN_USER,$BASE_DN <<EOF
208
+
209
+ # base dn
210
+ dn: $BASE_DN
211
+ objectClass: domain
212
+ objectClass: top
213
+ dc: avengers
214
+
215
+ # ou entry
216
+ dn: ou=Groups,$BASE_DN
217
+ objectclass: organizationalunit
218
+ ou: Groups
219
+ description: all groups
220
+
221
+ # USER ENTRY (pwd: piedpiper)
222
+ dn: cn=Tony Stark,$BASE_DN
223
+ cn: Tony Stark
224
+ sn: Stark
225
+ givenName: Tony
226
+ objectClass: piwikPerson
227
+ objectClass: top
228
+ uid: ironman
229
+ userPassword: `slappasswd -h {md5} -s piedpiper`
230
+ mobile: 555-555-5555
231
+ mail: billionairephilanthropistplayboy@starkindustries.com
232
+ view: 1,2
233
+ view: 3
234
+ admin: 3
235
+
236
+ # USER ENTRY (pwd: piedpiper)
237
+ dn: cn=Tony Stark1,$BASE_DN
238
+ cn: Tony Stark1
239
+ sn: Stark1
240
+ givenName: Tony1
241
+ objectClass: piwikPerson
242
+ objectClass: top
243
+ uid: ironman2
244
+ userPassword: `slappasswd -h {md5} -s piedpiper`
245
+ mobile: 555-555-5556
246
+ mail: billionairephilanthropistplayboy2@starkindustries.com
247
+ view: 1,2
248
+ view: 3
249
+ admin: 3
250
+
251
+ # USER ENTRY (pwd: redledger)
252
+ dn: cn=Natalia Romanova,$BASE_DN
253
+ cn: Natalia Romanova
254
+ objectClass: top
255
+ objectClass: piwikPerson
256
+ sn: Romanova
257
+ givenName: Natalia
258
+ uid: blackwidow
259
+ userPassword: `slappasswd -h {md5} -s redledger`
260
+ mobile: none
261
+ view: myPiwik:1,2;anotherPiwik:3,4
262
+ admin: myPiwik:3,4
263
+ admin: anotherPiwik:5,6
264
+
265
+ # USER ENTRY (pwd: thaifood)
266
+ dn: cn=Steve Rodgers,$BASE_DN
267
+ cn: Steve Rodgers
268
+ objectClass: top
269
+ objectClass: piwikPerson
270
+ sn: Rodgers
271
+ givenName: Steve
272
+ uid: captainamerica
273
+ userPassword: `slappasswd -h {md5} -s thaifood`
274
+ mobile: 123-456-7890
275
+ mail: srodgers@aol.com
276
+ superuser: 1
277
+ superuser: anotherPiwik
278
+
279
+ # USER ENTRY (pwd: bilgesnipe)
280
+ dn: cn=Thor,$BASE_DN
281
+ cn: Thor
282
+ objectClass: top
283
+ objectClass: piwikPerson
284
+ sn: Odinson
285
+ givenName: Thor
286
+ uid: thor
287
+ userPassword: `slappasswd -h {md5} -s bilgesnipe`
288
+ view: localhost:1,2;whatever.com:3,4
289
+ admin: whatever.com:1,2
290
+ admin: localhost:3,4
291
+ superuser: myPiwik:myOtherPiwik;localhost
292
+
293
+ # USER ENTRY (pwd: enrogue)
294
+ dn: cn=Ms Marvel,$BASE_DN
295
+ objectClass: top
296
+ objectClass: piwikPerson
297
+ cn: Ms Marvel
298
+ uid: msmarvel
299
+ userPassword: `slappasswd -h {md5} -s enrogue`
300
+ sn: Danvers
301
+
302
+ # group entry
303
+ dn: cn=avengers,$BASE_DN
304
+ cn: avengers
305
+ objectClass: groupOfNames
306
+ objectClass: top
307
+ member: cn=Tony Stark,$BASE_DN
308
+ member: cn=Natalia Romanova,$BASE_DN
309
+ member: cn=Steve Rodgers,$BASE_DN
310
+ member: cn=Thor,$BASE_DN
311
+
312
+ # another group entry
313
+ dn: cn=S.H.I.E.L.D.,$BASE_DN
314
+ cn: S.H.I.E.L.D.
315
+ objectClass: groupOfNames
316
+ objectClass: top
317
+ member: cn=Natalia Romanova,$BASE_DN
318
+
319
+ # USER ENTRY (pwd: cherry)
320
+ dn: cn=Rogue,$BASE_DN
321
+ objectClass: top
322
+ objectClass: piwikPerson
323
+ cn: Rogue
324
+ uid: rogue@xmansion.org
325
+ userPassword: `slappasswd -h {md5} -s cherry`
326
+ sn: Doesnthaveone
327
+
328
+ EOF
329
+
330
+ if [ "$?" -eq "0" ]; then
331
+ echo "Added entries."
332
+ else
333
+ echo "Failed to add entries."
334
+ echo ""
335
+ echo "slapd log:"
336
+ sudo grep slapd /var/log/syslog
337
+
338
+ exit 1
339
+ fi
340
+
341
+ echo ldapsearch -x -D "cn=Tony Stark,$BASE_DN" -w "piedpiper" -b "$BASE_DN" "(uid=ironman)" memberOf
342
+ ldapsearch -x -D "cn=Tony Stark,$BASE_DN" -w "piedpiper" -b "$BASE_DN" "(uid=ironman)" memberOf
343
+
344
+ echo ldapsearch -x -D "cn=$ADMIN_USER,$BASE_DN" -w "$ADMIN_PASS" -b "$BASE_DN"
345
+ ldapsearch -x -D "cn=$ADMIN_USER,$BASE_DN" -w "$ADMIN_PASS" -b "$BASE_DN"
plugins/LoginLdap/.github/workflows/matomo-ai-checklist.yml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Action for running tests
2
+
3
+ name: AI Checklist
4
+
5
+ on:
6
+ pull_request:
7
+ types: [opened, synchronize, reopened, edited]
8
+
9
+ permissions:
10
+ actions: read
11
+ checks: none
12
+ contents: none
13
+ deployments: none
14
+ issues: none
15
+ packages: none
16
+ pull-requests: read
17
+ repository-projects: none
18
+ security-events: none
19
+ statuses: none
20
+
21
+ concurrency:
22
+ group: ${{ github.workflow }}-${{ github.ref }}
23
+ cancel-in-progress: true
24
+
25
+ jobs:
26
+ AiChecklist:
27
+ runs-on: ubuntu-24.04
28
+ strategy:
29
+ fail-fast: false
30
+ steps:
31
+ - name: Run tests
32
+ uses: matomo-org/github-action-checklist-gate@main
plugins/LoginLdap/.github/workflows/matomo-tests.yml ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Action for running tests
2
+ # This file has been automatically created.
3
+ # To recreate it you can run this command
4
+ # ./console generate:test-action --plugin="LoginLdap" --php-versions="matomo5_min_php,matomo5_max_php" --setup-script=".github/scripts/setup_ldap.sh" --has-submodules --schedule-cron="25 3 * * 6"
5
+
6
+ name: Plugin LoginLdap Tests
7
+
8
+ on:
9
+ pull_request:
10
+ types: [opened, synchronize]
11
+ push:
12
+ branches:
13
+ - '**.x-dev'
14
+ workflow_dispatch:
15
+ schedule:
16
+ - cron: "25 3 * * 6"
17
+
18
+ permissions:
19
+ actions: read
20
+ checks: none
21
+ contents: read
22
+ deployments: none
23
+ issues: read
24
+ packages: none
25
+ pull-requests: read
26
+ repository-projects: none
27
+ security-events: none
28
+ statuses: none
29
+
30
+ concurrency:
31
+ group: php-${{ github.ref }}
32
+ cancel-in-progress: true
33
+
34
+ jobs:
35
+ PluginTests:
36
+ runs-on: ubuntu-24.04
37
+ strategy:
38
+ fail-fast: false
39
+ matrix:
40
+ php: [ 'matomo5_min_php', 'matomo5_max_php' ]
41
+ target: ['minimum_required_matomo', 'maximum_supported_matomo']
42
+ steps:
43
+ - uses: actions/checkout@v3
44
+ with:
45
+ lfs: true
46
+ persist-credentials: false
47
+ submodules: true
48
+ - name: Install package ripgrep
49
+ run: sudo apt-get install ripgrep
50
+ - name: Run tests
51
+ uses: matomo-org/github-action-tests@main
52
+ with:
53
+ plugin-name: 'LoginLdap'
54
+ php-version: ${{ matrix.php }}
55
+ test-type: 'PluginTests'
56
+ matomo-test-branch: ${{ matrix.target }}
57
+ setup-script: '.github/scripts/setup_ldap.sh'
58
+ artifacts-pass: ${{ secrets.ARTIFACTS_PASS }}
59
+ upload-artifacts: ${{ matrix.php == 'matomo5_min_php' && matrix.target == 'maximum_supported_matomo' }}
60
+ UI:
61
+ runs-on: ubuntu-24.04
62
+ steps:
63
+ - uses: actions/checkout@v3
64
+ with:
65
+ lfs: true
66
+ persist-credentials: false
67
+ submodules: true
68
+ - name: running tests
69
+ uses: matomo-org/github-action-tests@main
70
+ with:
71
+ plugin-name: 'LoginLdap'
72
+ matomo-test-branch: 'maximum_supported_matomo'
73
+ setup-script: '.github/scripts/setup_ldap.sh'
74
+ test-type: 'UI'
75
+ php-version: 'matomo5_min_php'
76
+ node-version: '16'
77
+ artifacts-pass: ${{ secrets.ARTIFACTS_PASS }}
78
+ upload-artifacts: true
plugins/LoginLdap/.github/workflows/phpcs.yml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: PHPCS check
2
+
3
+ on: pull_request
4
+
5
+ permissions:
6
+ actions: read
7
+ checks: read
8
+ contents: read
9
+ deployments: none
10
+ issues: read
11
+ packages: none
12
+ pull-requests: read
13
+ repository-projects: none
14
+ security-events: none
15
+ statuses: read
16
+
17
+ jobs:
18
+ phpcs:
19
+ name: PHPCS
20
+ runs-on: ubuntu-24.04
21
+ steps:
22
+ - uses: actions/checkout@v4
23
+ with:
24
+ lfs: false
25
+ persist-credentials: false
26
+ - name: Setup PHP
27
+ uses: shivammathur/setup-php@v2
28
+ with:
29
+ php-version: '7.4'
30
+ tools: cs2pr
31
+ - name: Install dependencies
32
+ run:
33
+ composer init --name=matomo/loginldap --quiet;
34
+ composer --no-plugins config allow-plugins.dealerdirect/phpcodesniffer-composer-installer true -n;
35
+ composer config repositories.matomo-coding-standards vcs https://github.com/matomo-org/matomo-coding-standards -n;
36
+ composer require matomo-org/matomo-coding-standards:dev-master;
37
+ composer install --dev --prefer-dist --no-progress --no-suggest
38
+ - name: Check PHP code styles
39
+ id: phpcs
40
+ run: ./vendor/bin/phpcs --report-full --standard=phpcs.xml --report-checkstyle=./phpcs-report.xml
41
+ - name: Show PHPCS results in PR
42
+ if: ${{ always() && steps.phpcs.outcome == 'failure' }}
43
+ run: cs2pr ./phpcs-report.xml --prepend-filename
plugins/LoginLdap/.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ tests/System/processed/*xml
2
+ /tests/UI/processed-ui-screenshots/
3
+ /vue/dist/demo.html
4
+ /vue/dist/*.common.js
5
+ /vue/dist/*.map
6
+ /vue/dist/*.development.*
7
+ .codex
plugins/LoginLdap/phpcs.xml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <ruleset name="loginLdap" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd">
3
+
4
+ <description>Matomo Coding Standard for LoginLdap plugin</description>
5
+
6
+ <arg name="extensions" value="php" />
7
+
8
+ <file>.</file>
9
+
10
+ <exclude-pattern>tests/javascript/*</exclude-pattern>
11
+ <exclude-pattern>*/vendor/*</exclude-pattern>
12
+
13
+ <rule ref="Matomo"></rule>
14
+
15
+ <rule ref="Generic.Files.LineLength">
16
+ <properties>
17
+ <property name="lineLimit" value="250" />
18
+ </properties>
19
+ <exclude-pattern>tests/*</exclude-pattern>
20
+ </rule>
21
+
22
+ <rule ref="Squiz.Classes.ValidClassName.NotCamelCaps">
23
+ <!-- Classnames for our update files don't match PascalCase, this can't be changed easily -->
24
+ <exclude-pattern>Updates/*</exclude-pattern>
25
+ </rule>
26
+
27
+ <rule ref="PSR1.Methods.CamelCapsMethodName.NotCamelCaps">
28
+ <!-- Allow using method name without camel caps in tests as long as some methods are named test_* -->
29
+ <exclude-pattern>tests/*</exclude-pattern>
30
+ </rule>
31
+
32
+ <rule ref="PSR1.Classes.ClassDeclaration.MultipleClasses">
33
+ <!-- Allow using multiple classes in one file for tests -->
34
+ <exclude-pattern>tests/*</exclude-pattern>
35
+ </rule>
36
+ </ruleset>
plugins/LoginLdap/phpstan.neon ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ parameters:
2
+ level: 5
3
+ phpVersion: 70200
4
+ tmpDir: /tmp/phpstan/LoginLdap/main
5
+ paths:
6
+ - .
7
+ excludePaths:
8
+ - tests/*
9
+ - vendor/
10
+ - github-action-tests/
11
+ bootstrapFiles:
12
+ - ../../bootstrap-phpstan.php
13
+ universalObjectCratesClasses:
14
+ - Piwik\Config
15
+ - Piwik\View
16
+ - Piwik\ViewDataTable\Config
17
+ scanDirectories:
18
+ - ../../
plugins/LoginLdap/screenshots/LoginLdap_Admin_admin_page.png ADDED
plugins/LoginLdap/tests/Integration/ApiTest.php ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Integration;
12
+
13
+ use Piwik\Config;
14
+ use Piwik\Plugins\LoginLdap\API;
15
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserSynchronizer;
16
+
17
+ /**
18
+ * @group LoginLdap
19
+ * @group LoginLdap_Integration
20
+ * @group LoginLdap_ApiTest
21
+ */
22
+ class ApiTest extends LdapIntegrationTest
23
+ {
24
+ /**
25
+ * @var API
26
+ */
27
+ private $api;
28
+
29
+ public function setUp(): void
30
+ {
31
+ parent::setUp();
32
+
33
+ // ApiTest only verifies config/server persistence, not the password confirmation flow
34
+ // (that is covered by PasswordConfirmationTest). Skip the confirmation so saving a config
35
+ // that enables password confirmation does not require re-authentication here.
36
+ UserSynchronizer::$skipPasswordConfirmation = true;
37
+
38
+ $this->api = new API();
39
+ }
40
+
41
+ public function tearDown(): void
42
+ {
43
+ UserSynchronizer::$skipPasswordConfirmation = false;
44
+
45
+ parent::tearDown();
46
+ }
47
+
48
+ public function test_getCountOfUsersMemberOf_ReturnsZero_WhenNoUsersAreMemberOfGroup()
49
+ {
50
+ $count = $this->api->getCountOfUsersMemberOf("not()hing");
51
+ $this->assertEquals(0, $count);
52
+ }
53
+
54
+ public function test_getCountOfUsersMemberOf_ReturnsCorrectResponse_WhenUsersAreMemberOfGroup()
55
+ {
56
+ $count = $this->api->getCountOfUsersMemberOf("cn=avengers," . self::SERVER_BASE_DN);
57
+ $this->assertEquals(4, $count);
58
+ }
59
+
60
+ public function test_getCountOfUsersMatchingFilter_ReturnsZero_WhenNoUsersMatchTheFilter()
61
+ {
62
+ $count = $this->api->getCountOfUsersMemberOf("(objectClass=whatever)");
63
+ $this->assertEquals(0, $count);
64
+ }
65
+
66
+ public function test_getCountOfUsersMatchingFilter_Throws_WhenFilterIsInvalid()
67
+ {
68
+ $this->expectException(\Exception::class);
69
+ $this->expectExceptionMessage('Invalid filter');
70
+
71
+ $this->api->getCountOfUsersMatchingFilter("lksjdf()a;sk");
72
+ }
73
+
74
+ public function test_getCountOfUsersMatchingFilter_ReturnsCorrectResult_WhenUsersMatchFilter()
75
+ {
76
+ $count = $this->api->getCountOfUsersMatchingFilter("(objectClass=person)");
77
+ $this->assertEquals(7, $count);
78
+ }
79
+
80
+ public function test_saveLdapConfig_SavesConfigToINIFile_AndIgnoresInvalidConfigNames()
81
+ {
82
+ $_SERVER['REQUEST_METHOD'] = 'POST';
83
+
84
+ Config::getInstance()->LoginLdap['servers'] = array();
85
+
86
+ $configToSave = array(
87
+ 'use_ldap_for_authentication' => 0,
88
+ 'synchronize_users_after_login' => 0,
89
+ 'enable_synchronize_access_from_ldap' => 1,
90
+ 'enable_password_confirmation' => 0,
91
+ 'new_user_default_sites_view_access' => '10,11,13',
92
+ 'servers' => 'abc',
93
+ 'nonconfigoption' => 'def'
94
+ );
95
+
96
+ $this->api->saveLdapConfig(json_encode($configToSave));
97
+
98
+ $ldapConfig = Config::getInstance()->LoginLdap;
99
+ $this->assertEquals(0, $ldapConfig['use_ldap_for_authentication']);
100
+ $this->assertEquals(0, $ldapConfig['synchronize_users_after_login']);
101
+ $this->assertEquals(0, $ldapConfig['enable_password_confirmation']);
102
+ $this->assertEquals(1, $ldapConfig['enable_synchronize_access_from_ldap']);
103
+ $this->assertEquals('10,11,13', $ldapConfig['new_user_default_sites_view_access']);
104
+ $this->assertTrue(empty($ldapConfig['servers']));
105
+ $this->assertTrue(empty($ldapConfig['nonconfigoption']));
106
+ }
107
+
108
+ public function test_saveLdapConfig_SavesConfigToINIFile_AndIgnoresInvalidConfigNames2()
109
+ {
110
+ $_SERVER['REQUEST_METHOD'] = 'POST';
111
+
112
+ Config::getInstance()->LoginLdap['servers'] = array();
113
+
114
+ $configToSave = array(
115
+ 'use_ldap_for_authentication' => 0,
116
+ 'synchronize_users_after_login' => 0,
117
+ 'enable_synchronize_access_from_ldap' => 1,
118
+ 'enable_password_confirmation' => 1,
119
+ 'new_user_default_sites_view_access' => '10,11,13',
120
+ 'servers' => 'abc',
121
+ 'nonconfigoption' => 'def'
122
+ );
123
+
124
+ $this->api->saveLdapConfig(json_encode($configToSave));
125
+
126
+ $ldapConfig = Config::getInstance()->LoginLdap;
127
+ $this->assertEquals(0, $ldapConfig['use_ldap_for_authentication']);
128
+ $this->assertEquals(0, $ldapConfig['synchronize_users_after_login']);
129
+ $this->assertEquals(1, $ldapConfig['enable_password_confirmation']);
130
+ $this->assertEquals(1, $ldapConfig['enable_synchronize_access_from_ldap']);
131
+ $this->assertEquals('10,11,13', $ldapConfig['new_user_default_sites_view_access']);
132
+ $this->assertTrue(empty($ldapConfig['servers']));
133
+ $this->assertTrue(empty($ldapConfig['nonconfigoption']));
134
+ }
135
+
136
+ public function test_saveServersInfo_SavesConfigToINIFile_AndIgnoresInvalidServerInfo()
137
+ {
138
+ $_SERVER['REQUEST_METHOD'] = 'POST';
139
+
140
+ $serverInfos = array(
141
+ array(
142
+ 'name' => 'server1',
143
+ 'hostname' => 'ahost.com',
144
+ 'port' => 389,
145
+ 'base_dn' => 'somedn',
146
+ 'start_tls' => false
147
+ ),
148
+ array(
149
+ 'invaliddata' => 'sdfjklsdj',
150
+ 'name' => 'server2',
151
+ 'hostname' => 'thehost.com',
152
+ 'port' => 456,
153
+ 'base_dn' => 'thedn',
154
+ 'admin_user' => 'admin',
155
+ 'admin_pass' => 'pass',
156
+ 'start_tls' => false
157
+ ),
158
+ );
159
+
160
+ $this->api->saveServersInfo(json_encode($serverInfos));
161
+
162
+ $this->assertEquals(array(
163
+ 'hostname' => 'ahost.com',
164
+ 'port' => 389,
165
+ 'base_dn' => 'somedn',
166
+ 'admin_user' => null,
167
+ 'admin_pass' => null,
168
+ 'start_tls' => null
169
+ ), Config::getInstance()->LoginLdap_server1);
170
+
171
+ $this->assertEquals(array(
172
+ 'hostname' => 'thehost.com',
173
+ 'port' => 456,
174
+ 'base_dn' => 'thedn',
175
+ 'admin_user' => 'admin',
176
+ 'admin_pass' => 'pass',
177
+ 'start_tls' => null
178
+ ), Config::getInstance()->LoginLdap_server2);
179
+ }
180
+
181
+ public function test_saveServersInfo_DoesNotOverwritePassword_IfPasswordFieldBlank()
182
+ {
183
+ $_SERVER['REQUEST_METHOD'] = 'POST';
184
+
185
+ Config::getInstance()->LoginLdap_server2 = array(
186
+ 'hostname' => 'thehost.com',
187
+ 'port' => 456,
188
+ 'base_dn' => 'thedn',
189
+ 'admin_user' => 'admin',
190
+ 'admin_pass' => 'firstpass',
191
+ 'start_tls' => false
192
+ );
193
+
194
+ $serverInfos = array(
195
+ array(
196
+ 'name' => 'server2',
197
+ 'hostname' => 'thehost.com',
198
+ 'port' => 456,
199
+ 'base_dn' => 'thedn',
200
+ 'admin_user' => 'admin',
201
+ 'admin_pass' => '',
202
+ 'start_tls' => false
203
+ ),
204
+ );
205
+
206
+ $this->api->saveServersInfo(json_encode($serverInfos));
207
+
208
+ $this->assertEquals(array(
209
+ 'hostname' => 'thehost.com',
210
+ 'port' => 456,
211
+ 'base_dn' => 'thedn',
212
+ 'admin_user' => 'admin',
213
+ 'admin_pass' => 'firstpass',
214
+ 'start_tls' => null
215
+ ), Config::getInstance()->LoginLdap_server2);
216
+ }
217
+
218
+ public function test_saveServersInfo_OverwritesPassword_IfPasswordFieldNotBlank()
219
+ {
220
+ $_SERVER['REQUEST_METHOD'] = 'POST';
221
+
222
+ Config::getInstance()->LoginLdap_server2 = array(
223
+ 'hostname' => 'thehost.com',
224
+ 'port' => 456,
225
+ 'base_dn' => 'thedn',
226
+ 'admin_user' => 'admin',
227
+ 'admin_pass' => 'firstpass',
228
+ 'start_tls' => false
229
+ );
230
+
231
+ $serverInfos = array(
232
+ array(
233
+ 'name' => 'server2',
234
+ 'hostname' => 'thehost.com',
235
+ 'port' => 456,
236
+ 'base_dn' => 'thedn',
237
+ 'admin_user' => 'admin',
238
+ 'admin_pass' => 'pass',
239
+ 'start_tls' => false
240
+ ),
241
+ );
242
+
243
+ $this->api->saveServersInfo(json_encode($serverInfos));
244
+
245
+ $this->assertEquals(array(
246
+ 'hostname' => 'thehost.com',
247
+ 'port' => 456,
248
+ 'base_dn' => 'thedn',
249
+ 'admin_user' => 'admin',
250
+ 'admin_pass' => 'pass',
251
+ 'start_tls' => null
252
+ ), Config::getInstance()->LoginLdap_server2);
253
+ }
254
+
255
+ public function test_getPluginOptionValuesWithDefaults_UsesDisabledPasswordConfirmationByDefault()
256
+ {
257
+ unset(Config::getInstance()->LoginLdap['enable_password_confirmation']);
258
+
259
+ $ldapConfig = \Piwik\Plugins\LoginLdap\Config::getPluginOptionValuesWithDefaults();
260
+
261
+ $this->assertSame(0, $ldapConfig['enable_password_confirmation']);
262
+ }
263
+
264
+ public function test_synchronizeUser_Throws_WhenLdapUserDoesNotExist()
265
+ {
266
+ $this->expectException(\Exception::class);
267
+ $this->expectExceptionMessage('User "unknownuser" not found!');
268
+
269
+ $this->api->synchronizeUser('unknownuser');
270
+ }
271
+
272
+ public function test_synchronizeUser_Succeeds_WhenLdapUserExistsAndIsValid()
273
+ {
274
+ $this->api->synchronizeUser(self::TEST_LOGIN);
275
+ $this->assertStarkSynchronized();
276
+ }
277
+
278
+ public function test_getExistingLdapUsersFromDb_should_return_empty_result()
279
+ {
280
+ $this->assertEmpty($this->api->getExistingLdapUsersFromDb());
281
+ }
282
+
283
+ public function test_getExistingLdapUsersFromDb_should_return_result()
284
+ {
285
+ $this->api->synchronizeUser(self::TEST_LOGIN);
286
+ $this->assertSame([self::TEST_LOGIN], $this->api->getExistingLdapUsersFromDb());
287
+ }
288
+ }
plugins/LoginLdap/tests/Integration/AuthenticationTest.php ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Integration;
12
+
13
+ use Piwik\Auth;
14
+ use Piwik\AuthResult;
15
+ use Piwik\Config;
16
+ use Piwik\Container\StaticContainer;
17
+ use Piwik\Plugins\LoginLdap\Auth\LdapAuth;
18
+ use Piwik\Plugins\UsersManager\API as UsersManagerAPI;
19
+ use Piwik\Tests\Framework\Fixture;
20
+
21
+ /**
22
+ * @group LoginLdap
23
+ * @group LoginLdap_Integration
24
+ * @group LoginLdap_AuthenticationTest
25
+ */
26
+ class AuthenticationTest extends LdapIntegrationTest
27
+ {
28
+ private $nonLdapUserAppPassword;
29
+ private $nonLdapNormalUserAppPassword;
30
+
31
+ public function setUp(): void
32
+ {
33
+ parent::setUp();
34
+
35
+ // test superusers should not have {LDAP} password to test that superusers can
36
+ // login, even if they are not in LDAP
37
+ $this->addPreexistingSuperUser();
38
+
39
+ $this->addNonLdapUsers();
40
+ Fixture::createSuperUser();
41
+
42
+ $this->nonLdapUserAppPassword = UsersManagerAPI::getInstance()->createAppSpecificTokenAuth(
43
+ self::NON_LDAP_USER,
44
+ self::NON_LDAP_PASS,
45
+ 'test'
46
+ );
47
+ $this->nonLdapNormalUserAppPassword = UsersManagerAPI::getInstance()->createAppSpecificTokenAuth(
48
+ self::NON_LDAP_NORMAL_USER,
49
+ self::NON_LDAP_NORMAL_PASS,
50
+ 'test'
51
+ );
52
+ }
53
+
54
+ public function test_LdapAuth_AuthenticatesUser_WithCorrectCredentials()
55
+ {
56
+ $ldapAuth = LdapAuth::makeConfigured();
57
+ $ldapAuth->setLogin(self::TEST_LOGIN);
58
+ $ldapAuth->setPassword(self::TEST_PASS);
59
+ $authResult = $ldapAuth->authenticate();
60
+
61
+ $this->assertEquals(1, $authResult->getCode());
62
+
63
+ StaticContainer::getContainer()->set(Auth::class, $ldapAuth); // set global auth for createAppSpecificTokenAuth() to work properly
64
+ }
65
+
66
+ public function test_LdapAuth_DoesNotAuthenticateUser_WithIncorrectPassword()
67
+ {
68
+ $ldapAuth = LdapAuth::makeConfigured();
69
+ $ldapAuth->setLogin(self::TEST_LOGIN);
70
+ $ldapAuth->setPassword('slkdjfsd');
71
+ $authResult = $ldapAuth->authenticate();
72
+
73
+ $this->assertEquals(0, $authResult->getCode());
74
+ }
75
+
76
+ public function test_LdapAuth_DoesNotAuthenticateUser_WithNonexistantUser()
77
+ {
78
+ $ldapAuth = LdapAuth::makeConfigured();
79
+ $ldapAuth->setLogin('skldfjsd');
80
+ $ldapAuth->setPassword(self::TEST_PASS);
81
+ $authResult = $ldapAuth->authenticate();
82
+
83
+ $this->assertEquals(0, $authResult->getCode());
84
+ }
85
+
86
+ public function test_LdapAuth_ChecksMemberOf_WhenAuthenticating()
87
+ {
88
+ Config::getInstance()->LoginLdap['memberOf'] = "cn=S.H.I.E.L.D.," . self::SERVER_BASE_DN;
89
+
90
+ $ldapAuth = LdapAuth::makeConfigured();
91
+ $ldapAuth->setLogin(self::TEST_LOGIN);
92
+ $ldapAuth->setPassword(self::TEST_PASS);
93
+ $authResult = $ldapAuth->authenticate();
94
+
95
+ $this->assertEquals(0, $authResult->getCode());
96
+
97
+ Config::getInstance()->LoginLdap['memberOf'] = "cn=avengers," . self::SERVER_BASE_DN;
98
+
99
+ $ldapAuth = LdapAuth::makeConfigured();
100
+ $ldapAuth->setLogin(self::TEST_LOGIN);
101
+ $ldapAuth->setPassword(self::TEST_PASS);
102
+ $authResult = $ldapAuth->authenticate();
103
+
104
+ $this->assertEquals(1, $authResult->getCode());
105
+ }
106
+
107
+ public function test_LdapAuth_UsesConfiguredFilter_WhenAuthenticating()
108
+ {
109
+ Config::getInstance()->LoginLdap['filter'] = "(!(mobile=none))";
110
+
111
+ $ldapAuth = LdapAuth::makeConfigured();
112
+ $ldapAuth->setLogin(self::TEST_LOGIN);
113
+ $ldapAuth->setPassword(self::TEST_PASS);
114
+ $authResult = $ldapAuth->authenticate();
115
+
116
+ $this->assertEquals(1, $authResult->getCode());
117
+
118
+ $ldapAuth = LdapAuth::makeConfigured();
119
+ $ldapAuth->setLogin(self::OTHER_TEST_LOGIN);
120
+ $ldapAuth->setPassword(self::OTHER_TEST_PASS);
121
+ $authResult = $ldapAuth->authenticate();
122
+
123
+ $this->assertEquals(0, $authResult->getCode());
124
+ }
125
+
126
+ public function test_LdapAuth_ReturnsCorrectCode_WhenAuthenticatingSuperUsers()
127
+ {
128
+ $ldapAuth = LdapAuth::makeConfigured();
129
+ $ldapAuth->setLogin(self::TEST_SUPERUSER_LOGIN);
130
+ $ldapAuth->setPassword(self::TEST_SUPERUSER_PASS);
131
+ $authResult = $ldapAuth->authenticate();
132
+
133
+ $this->assertEquals(AuthResult::SUCCESS_SUPERUSER_AUTH_CODE, $authResult->getCode());
134
+ }
135
+
136
+ public function test_LdapAuth_ReturnsCorrectCode_WhenAuthenticatingNonLdapSuperUsers()
137
+ {
138
+ $ldapAuth = LdapAuth::makeConfigured();
139
+ $ldapAuth->setLogin(self::NON_LDAP_USER);
140
+ $ldapAuth->setPassword(self::NON_LDAP_PASS);
141
+ $authResult = $ldapAuth->authenticate();
142
+
143
+ $this->assertEquals(AuthResult::SUCCESS_SUPERUSER_AUTH_CODE, $authResult->getCode());
144
+
145
+ $ldapAuth = LdapAuth::makeConfigured();
146
+ $ldapAuth->setTokenAuth($this->getNonLdapUserTokenAuth());
147
+ $authResult = $ldapAuth->authenticate();
148
+
149
+ $this->assertEquals(self::NON_LDAP_USER, $authResult->getIdentity());
150
+ $this->assertEquals(AuthResult::SUCCESS_SUPERUSER_AUTH_CODE, $authResult->getCode());
151
+ }
152
+
153
+ public function test_LdapAuth_ReturnsCorrectCode_WhenAuthenticatingNonLdapNormalUsers()
154
+ {
155
+ $ldapAuth = LdapAuth::makeConfigured();
156
+ $ldapAuth->setLogin(self::NON_LDAP_NORMAL_USER);
157
+ $ldapAuth->setPassword(self::NON_LDAP_NORMAL_PASS);
158
+ $authResult = $ldapAuth->authenticate();
159
+
160
+ $this->assertEquals(AuthResult::SUCCESS, $authResult->getCode());
161
+
162
+ $ldapAuth = LdapAuth::makeConfigured();
163
+ $ldapAuth->setTokenAuth($this->getNonLdapNormalUserTokenAuth());
164
+ $authResult = $ldapAuth->authenticate();
165
+
166
+ $this->assertEquals(self::NON_LDAP_NORMAL_USER, $authResult->getIdentity());
167
+ $this->assertEquals(AuthResult::SUCCESS, $authResult->getCode());
168
+ }
169
+
170
+ public function test_LdapAuth_AuthenticatesSuccessfully_WhenTokenAuthOnlyAuthenticationUsed()
171
+ {
172
+ $this->test_LdapAuth_AuthenticatesUser_WithCorrectCredentials();
173
+
174
+ $testLoginTokenAuth = UsersManagerAPI::getInstance()->createAppSpecificTokenAuth(
175
+ self::TEST_LOGIN,
176
+ self::TEST_PASS,
177
+ 'test'
178
+ );
179
+
180
+ $ldapAuth = LdapAuth::makeConfigured();
181
+ $ldapAuth->setLogin(self::TEST_LOGIN);
182
+ $ldapAuth->setTokenAuth($testLoginTokenAuth);
183
+ $authResult = $ldapAuth->authenticate();
184
+
185
+ $this->assertEquals(1, $authResult->getCode());
186
+ }
187
+
188
+ public function test_LdapAuth_AuthenticatesSuccessfully_WhenAuthenticatingNormalPiwikSuperUser()
189
+ {
190
+ UsersManagerAPI::getInstance()->addUser('zola', 'hydra___', 'zola@shield.org');
191
+ $this->setSuperUserAccess('zola', true);
192
+
193
+ $ldapAuth = LdapAuth::makeConfigured();
194
+ $ldapAuth->setLogin('zola');
195
+ $ldapAuth->setPassword('hydra___');
196
+ $authResult = $ldapAuth->authenticate();
197
+
198
+ $this->assertEquals(AuthResult::SUCCESS_SUPERUSER_AUTH_CODE, $authResult->getCode());
199
+ }
200
+
201
+ public function test_LdapAuth_AuthenticatesSuccessfully_WhenAuthenticatingNormalPiwikNonSuperUser()
202
+ {
203
+ UsersManagerAPI::getInstance()->addUser('pcoulson', 'thispasswordwillbechanged', 'pcoulson@shield.org');
204
+ UsersManagerAPI::getInstance()->updateUser('pcoulson', 'vintage', false, false, self::TEST_SUPERUSER_PASS);
205
+
206
+ $ldapAuth = LdapAuth::makeConfigured();
207
+ $ldapAuth->setLogin('pcoulson');
208
+ $ldapAuth->setPassword('vintage');
209
+ $authResult = $ldapAuth->authenticate();
210
+
211
+ $this->assertEquals(AuthResult::SUCCESS, $authResult->getCode());
212
+ }
213
+
214
+ public function test_LdapAuth_DoesNotAuthenticate_WhenEmptyLoginProvided()
215
+ {
216
+ $ldapAuth = LdapAuth::makeConfigured();
217
+ $ldapAuth->setLogin('');
218
+ $ldapAuth->setPassword('lsakjdfdslj');
219
+ $authResult = $ldapAuth->authenticate();
220
+
221
+ $this->assertEquals(0, $authResult->getCode());
222
+ }
223
+
224
+ public function test_LdapAuth_DoesNotAuthenticate_WhenAnonymousLoginProvided()
225
+ {
226
+ $ldapAuth = LdapAuth::makeConfigured();
227
+ $ldapAuth->setLogin('anonymous');
228
+ $ldapAuth->setPassword('lsakjdfdslj');
229
+ $authResult = $ldapAuth->authenticate();
230
+
231
+ $this->assertEquals(0, $authResult->getCode());
232
+ }
233
+
234
+ private function getNonLdapUserTokenAuth()
235
+ {
236
+ return $this->nonLdapUserAppPassword;
237
+ }
238
+
239
+ private function getNonLdapNormalUserTokenAuth()
240
+ {
241
+ return $this->nonLdapNormalUserAppPassword;
242
+ }
243
+ }
plugins/LoginLdap/tests/Integration/BackwardsCompatibilityTest.php ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Integration;
12
+
13
+ use Piwik\Config;
14
+ use Piwik\Plugins\LoginLdap\Auth\LdapAuth;
15
+ use Piwik\Plugins\UsersManager\API as UsersManagerAPI;
16
+
17
+ /**
18
+ * @group LoginLdap
19
+ * @group LoginLdap_Integration
20
+ * @group LoginLdap_BackwardsCompatibilityTest
21
+ */
22
+ class BackwardsCompatibilityTest extends LdapIntegrationTest
23
+ {
24
+ public function setUp(): void
25
+ {
26
+ parent::setUp();
27
+
28
+ Config::getInstance()->LoginLdap = array(
29
+ 'serverUrl' => @Config::getInstance()->LoginLdap_testserver['hostname'] ?: self::SERVER_HOST_NAME,
30
+ 'ldapPort' => @Config::getInstance()->LoginLdap_testserver['port'] ?: self::SERVER_PORT,
31
+ 'baseDn' => self::SERVER_BASE_DN,
32
+ 'adminUser' => 'cn=fury,' . self::SERVER_BASE_DN,
33
+ 'adminPass' => 'secrets',
34
+ 'useKerberos' => 'false'
35
+ );
36
+
37
+ UsersManagerAPI::getInstance()->addUser(self::TEST_LOGIN, self::TEST_PASS, 'billionairephilanthropistplayboy@starkindustries.com');
38
+ }
39
+
40
+ public function testAuthenticationWithOldServerConfig()
41
+ {
42
+ $ldapAuth = LdapAuth::makeConfigured();
43
+ $ldapAuth->setLogin(self::TEST_LOGIN);
44
+ $ldapAuth->setPassword(self::TEST_PASS);
45
+ $authResult = $ldapAuth->authenticate();
46
+
47
+ $this->assertEquals(1, $authResult->getCode());
48
+ }
49
+ }
plugins/LoginLdap/tests/Integration/Commands/SynchronizeUsersTest.php ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Integration\Commands;
12
+
13
+ use Piwik\Common;
14
+ use Piwik\Config;
15
+ use Piwik\Console;
16
+ use Piwik\Db;
17
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserMapper;
18
+ use Piwik\Plugins\LoginLdap\tests\Integration\LdapIntegrationTest;
19
+ use Symfony\Component\Console\Tester\ApplicationTester;
20
+
21
+ /**
22
+ * @group LoginLdap
23
+ * @group LoginLdap_Integration
24
+ * @group LoginLdap_SynchronizeUsersTest
25
+ */
26
+ class SynchronizeUsersTest extends LdapIntegrationTest
27
+ {
28
+ /**
29
+ * @var ApplicationTester
30
+ */
31
+ protected $applicationTester = null;
32
+
33
+ public function setUp(): void
34
+ {
35
+ parent::setUp();
36
+
37
+ $plugins = Config::getInstance()->Plugins;
38
+ $plugins['Plugins'][] = 'LoginLdap';
39
+ Config::getInstance()->Plugins = $plugins;
40
+
41
+ $application = new Console(self::$fixture->piwikEnvironment);
42
+ $application->setAutoExit(false);
43
+
44
+ $this->applicationTester = new ApplicationTester($application);
45
+ }
46
+
47
+ protected function getCommandDisplayOutputErrorMessage()
48
+ {
49
+ return "Command did not behave as expected. Command output: " . $this->applicationTester->getDisplay();
50
+ }
51
+
52
+ public function test_CommandSynchronizesAllUsers_WhenLoginNotSpecified()
53
+ {
54
+ $result = $this->applicationTester->run(array(
55
+ 'command' => 'loginldap:synchronize-users',
56
+ '-v' => true
57
+ ));
58
+
59
+ $this->assertEquals(0, $result, $this->getCommandDisplayOutputErrorMessage());
60
+
61
+ $users = $this->getLdapUserLogins();
62
+ $this->assertEquals(array('blackwidow', 'captainamerica', 'ironman', 'ironman2', 'msmarvel', 'rogue@xmansion.org', 'thor'), $users);
63
+ }
64
+
65
+ public function test_CommandSynchronizesOneUser_WhenLoginSpecified()
66
+ {
67
+ $result = $this->applicationTester->run(array(
68
+ 'command' => 'loginldap:synchronize-users',
69
+ '--login' => array('ironman'),
70
+ '-v' => true
71
+ ));
72
+
73
+ $this->assertEquals(0, $result, $this->getCommandDisplayOutputErrorMessage());
74
+
75
+ $users = $this->getLdapUserLogins();
76
+ $this->assertEquals(array('ironman'), $users);
77
+ }
78
+
79
+ public function test_CommandSynchronizesMultipleUsers_WhenMultipleLoginsSpecified()
80
+ {
81
+ $result = $this->applicationTester->run(array(
82
+ 'command' => 'loginldap:synchronize-users',
83
+ '--login' => array('ironman', 'blackwidow'),
84
+ '-v' => true
85
+ ));
86
+
87
+ $this->assertEquals(0, $result, $this->getCommandDisplayOutputErrorMessage());
88
+
89
+ $users = $this->getLdapUserLogins();
90
+ $this->assertEquals(array('blackwidow', 'ironman'), $users);
91
+ }
92
+
93
+ public function test_CommandReportsUsersThatAreNotSynchronized_WhenUserMissing_AndUserInfoBrokenInLdap()
94
+ {
95
+ $this->markTestSkipped("Can't find a way to inject broken data into result of Ldap\\Client::fetchAll. Waiting for DI.");
96
+
97
+ $result = $this->applicationTester->run(array(
98
+ 'command' => 'loginldap:synchronize-users',
99
+ '--login' => array('ironman', 'blackwidow', 'missinguser', 'msmarvel'),
100
+ '-v' => true
101
+ ));
102
+
103
+ $this->assertEquals(2, $result, $this->getCommandDisplayOutputErrorMessage());
104
+
105
+ $users = $this->getLdapUserLogins();
106
+ $this->assertEquals(array('blackwidow', 'ironman'), $users);
107
+
108
+ $this->assertRegExp("/^.*missinguser.*User.*not found.*$/", $this->applicationTester->getDisplay());
109
+ $this->assertRegExp("/^.*msmarvel.*LDAP entity missing required.*$/", $this->applicationTester->getDisplay());
110
+ }
111
+
112
+ public function test_CommandSkipsExisitingUsers_IfSkipExistingOptionUsed()
113
+ {
114
+ $this->addPreexistingSuperUser();
115
+
116
+ $result = $this->applicationTester->run(array(
117
+ 'command' => 'loginldap:synchronize-users',
118
+ '--login' => array('ironman', 'captainamerica'),
119
+ '--skip-existing' => true,
120
+ '-v' => true
121
+ ));
122
+
123
+ $this->assertEquals(0, $result, $this->getCommandDisplayOutputErrorMessage());
124
+ self::assertStringContainsString("Skipping 'captainamerica', already exists in Piwik...", $this->applicationTester->getDisplay());
125
+
126
+ $users = $this->getLdapUserLogins();
127
+ $this->assertEquals(array('ironman'), $users);
128
+ }
129
+
130
+ private function getLdapUserLogins()
131
+ {
132
+ $rows = Db::fetchAll("SELECT login from " . Common::prefixTable('user') . ' ORDER BY login');
133
+ $userMapper = new UserMapper();
134
+
135
+ $result = array();
136
+ foreach ($rows as $row) {
137
+ if ($userMapper->isUserLdapUser($row['login'])) {
138
+ $result[] = $row['login'];
139
+ }
140
+ }
141
+ return $result;
142
+ }
143
+ }
plugins/LoginLdap/tests/Integration/LdapIntegrationTest.php ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Integration;
12
+
13
+ use Piwik\Log\Logger;
14
+ use Piwik\Access;
15
+ use Piwik\Auth\Password;
16
+ use Piwik\Common;
17
+ use Piwik\Container\StaticContainer;
18
+ use Piwik\Db;
19
+ use Piwik\Config;
20
+ use Piwik\Log\LoggerInterface;
21
+ use Piwik\Plugins\LoginLdap\Ldap\LdapFunctions;
22
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserMapper;
23
+ use Piwik\Plugins\UsersManager\UserUpdater;
24
+ use Piwik\Tests\Framework\Fixture;
25
+ use Piwik\Plugins\UsersManager\API as UsersManagerAPI;
26
+ use Piwik\Tests\Framework\TestCase\IntegrationTestCase;
27
+
28
+ require_once PIWIK_INCLUDE_PATH . '/plugins/LoginLdap/tests/Mocks/LdapFunctions.php';
29
+
30
+ abstract class LdapIntegrationTest extends IntegrationTestCase
31
+ {
32
+ public const SERVER_HOST_NAME = 'localhost';
33
+ public const SERVER_PORT = 389;
34
+ public const SERVER_BASE_DN = "dc=avengers,dc=shield,dc=org";
35
+ public const GROUP_NAME = 'cn=avengers,dc=avengers,dc=shield,dc=org';
36
+
37
+ public const TEST_LOGIN = 'ironman';
38
+ public const TEST_PASS = 'piedpiper';
39
+ public const TEST_PASS_LDAP = '{MD5}Dv6yiT/W4FvaM5gBdqHwlQ==';
40
+
41
+ public const TEST_LOGIN2 = 'ironman2';
42
+
43
+ public const OTHER_TEST_LOGIN = 'blackwidow';
44
+ public const OTHER_TEST_PASS = 'redledger';
45
+
46
+ public const TEST_SUPERUSER_LOGIN = 'captainamerica';
47
+ public const TEST_SUPERUSER_PASS = 'thaifood';
48
+
49
+ public const NON_LDAP_USER = 'stan';
50
+ public const NON_LDAP_PASS = 'whereisthefourthwall?';
51
+
52
+ public const NON_LDAP_NORMAL_USER = 'amber';
53
+ public const NON_LDAP_NORMAL_PASS = 'crossingthefourthwall';
54
+
55
+ public function setUp(): void
56
+ {
57
+ if (empty(getenv('PLUGIN_NAME'))) {
58
+ $this->markTestSkipped('LDAP tests can only be run as plugin tests.');
59
+ return;
60
+ }
61
+
62
+ if (!function_exists('ldap_bind')) {
63
+ throw new \Exception("PHP not compiled w/ --with-ldap!");
64
+ }
65
+
66
+ if (!$this->isLdapServerRunning()) {
67
+ throw new \Exception("LDAP server not found on port localhost:389. For integration tests, an LDAP server must be running with the "
68
+ . "data and configuration found in tests/travis/setup_ldap.sh script. An OpenLDAP server is expected, but any "
69
+ . "will work assuming the attributes names & data are the same.");
70
+ }
71
+
72
+ parent::setUp();
73
+
74
+ Config::getInstance()->LoginLdap = Config::getInstance()->LoginLdapTest + array(
75
+ 'servers' => 'testserver',
76
+ 'use_webserver_auth' => 'false',
77
+ 'new_user_default_sites_view_access' => '1,2',
78
+ 'synchronize_users_after_login' => 1
79
+ );
80
+
81
+ Config::getInstance()->LoginLdap_testserver = Config::getInstance()->LoginLdap_testserver + array(
82
+ 'hostname' => self::SERVER_HOST_NAME,
83
+ 'port' => self::SERVER_PORT,
84
+ 'base_dn' => self::SERVER_BASE_DN,
85
+ 'admin_user' => 'cn=fury,' . self::SERVER_BASE_DN,
86
+ 'admin_pass' => 'secrets',
87
+ 'start_tls' => false
88
+ );
89
+
90
+ LdapFunctions::$phpUnitMock = null;
91
+
92
+ // create sites referenced in setup_ldap.sh
93
+ Fixture::createWebsite('2013-01-01 00:00:00');
94
+ Fixture::createWebsite('2013-01-01 00:00:00');
95
+ Fixture::createWebsite('2013-01-01 00:00:00');
96
+
97
+ Fixture::loadAllTranslations();
98
+ }
99
+
100
+ public function tearDown(): void
101
+ {
102
+ Fixture::resetTranslations();
103
+
104
+ parent::tearDown();
105
+ }
106
+
107
+ protected function addPreexistingSuperUser()
108
+ {
109
+ UsersManagerAPI::getInstance()->addUser(self::TEST_SUPERUSER_LOGIN, self::TEST_SUPERUSER_PASS, 'srodgers@aol.com');
110
+ $this->setSuperUserAccess(self::TEST_SUPERUSER_LOGIN, true);
111
+
112
+ $auth = StaticContainer::get('Piwik\Auth');
113
+ $auth->setLogin(self::TEST_SUPERUSER_LOGIN);
114
+ $auth->setPassword(self::TEST_SUPERUSER_PASS);
115
+ Access::getInstance()->setSuperUserAccess(false);
116
+ Access::getInstance()->reloadAccess(StaticContainer::get('Piwik\Auth'));
117
+ }
118
+
119
+ protected function addNonLdapUsers()
120
+ {
121
+ UsersManagerAPI::getInstance()->addUser(self::NON_LDAP_USER, self::NON_LDAP_PASS, 'whatever@aol.com');
122
+ $this->setSuperUserAccess(self::NON_LDAP_USER, true);
123
+ UsersManagerAPI::getInstance()->addUser(self::NON_LDAP_NORMAL_USER, self::NON_LDAP_NORMAL_PASS, 'witchy@sdhs.edu');
124
+ }
125
+
126
+ protected function getUser($login)
127
+ {
128
+ return Db::fetchRow("SELECT login, password, email FROM " . Common::prefixTable('user') . " WHERE login = ?", array($login));
129
+ }
130
+
131
+ protected function assertStarkSynchronized($expectedDomain = 'starkindustries.com')
132
+ {
133
+ $user = $this->getUser(self::TEST_LOGIN);
134
+ $this->assertNotEmpty($user);
135
+ $passwordHelper = new Password();
136
+ $this->assertTrue($passwordHelper->verify(md5(self::TEST_PASS_LDAP), $user['password']));
137
+ unset($user['password']);
138
+ $this->assertEquals(array(
139
+ 'login' => self::TEST_LOGIN,
140
+ 'email' => 'billionairephilanthropistplayboy@' . $expectedDomain,
141
+ ), $user);
142
+ $userMapper = new UserMapper();
143
+ $this->assertTrue($userMapper->isUserLdapUser(self::TEST_LOGIN));
144
+ }
145
+
146
+ protected function assertRomanovSynchronized($expectedDomain)
147
+ {
148
+ $user = $this->getUser('blackwidow');
149
+ $this->assertNotEmpty($user);
150
+ unset($user['password']);
151
+ $this->assertEquals(array(
152
+ 'login' => 'blackwidow',
153
+ 'email' => 'blackwidow@' . $expectedDomain,
154
+ ), $user);
155
+ $userMapper = new UserMapper();
156
+ $this->assertTrue($userMapper->isUserLdapUser('blackwidow'));
157
+ }
158
+
159
+ private function isLdapServerRunning()
160
+ {
161
+ $fp = @fsockopen(self::SERVER_HOST_NAME, self::SERVER_PORT, $errno, $errstr, 5);
162
+ if (empty($fp)) {
163
+ return false;
164
+ } else {
165
+ fclose($fp);
166
+ return true;
167
+ }
168
+ }
169
+
170
+ public function provideContainerConfig()
171
+ {
172
+ return array(
173
+ LoggerInterface::class => \Piwik\DI::get(Logger::class),
174
+ 'log.level' => Logger::DEBUG,
175
+ );
176
+ }
177
+
178
+ protected function setSuperUserAccess($user, $hasAccess)
179
+ {
180
+ $userUpdater = new UserUpdater();
181
+ if (method_exists($userUpdater, 'setSuperUserAccessWithoutCurrentPassword')) {
182
+ $userUpdater->setSuperUserAccessWithoutCurrentPassword($user, $hasAccess);
183
+ } else {
184
+ UsersManagerAPI::getInstance()->setSuperUserAccess($user, $hasAccess);
185
+ }
186
+ }
187
+ }
plugins/LoginLdap/tests/Integration/LdapUserSynchronizationTest.php ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Integration;
12
+
13
+ use Piwik\Access;
14
+ use Piwik\Auth\Password;
15
+ use Piwik\Config;
16
+ use Piwik\Db;
17
+ use Piwik\Common;
18
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserMapper;
19
+ use Piwik\Plugins\UsersManager\API as UsersManagerAPI;
20
+ use Piwik\Plugins\LoginLdap\Auth\LdapAuth;
21
+ use Piwik\SettingsPiwik;
22
+ use Piwik\Tests\Framework\Fixture;
23
+
24
+ /**
25
+ * @group LoginLdap
26
+ * @group LoginLdap_Integration
27
+ * @group LoginLdap_LdapUserSynchronizationTest
28
+ */
29
+ class LdapUserSynchronizationTest extends LdapIntegrationTest
30
+ {
31
+ public function setUp(): void
32
+ {
33
+ parent::setUp();
34
+
35
+ // create extra sites that users won't have access to
36
+ Fixture::createWebsite('2013-01-01 00:00:00');
37
+ Fixture::createWebsite('2013-01-01 00:00:00');
38
+ Fixture::createWebsite('2013-01-01 00:00:00');
39
+
40
+ Access::getInstance()->setSuperUserAccess(false);
41
+ }
42
+
43
+ public function tearDown(): void
44
+ {
45
+ Access::getInstance()->setSuperUserAccess(true);
46
+
47
+ parent::tearDown();
48
+ }
49
+
50
+ public function test_PiwikUserIsCreated_WhenLdapLoginSucceeds_ButPiwikUserDoesntExist()
51
+ {
52
+ $this->authenticateViaLdap();
53
+
54
+ $this->assertStarkSynchronized();
55
+
56
+ $superusers = $this->getSuperUsers();
57
+ $this->assertEquals(array(), $superusers);
58
+
59
+ $access = $this->getAccessFor(self::TEST_LOGIN); // access added due to new_user_default_sites_view_access option
60
+ $this->assertEquals(array(
61
+ array('site' => '1', 'access' => 'view'),
62
+ array('site' => '2', 'access' => 'view')
63
+ ), $access);
64
+ }
65
+
66
+ public function test_PiwikUserIsCreated_WithEmailSuffixed_ButNotUser_IfShouldAppendEmailIsOff()
67
+ {
68
+ Config::getInstance()->LoginLdap['append_user_email_suffix_to_username'] = 0;
69
+ Config::getInstance()->LoginLdap['user_email_suffix'] = '@matthers.com';
70
+
71
+ $this->authenticateViaLdap('blackwidow', 'redledger');
72
+
73
+ $this->assertRomanovSynchronized('matthers.com');
74
+ }
75
+
76
+ public function test_PiwikUserIsCreatedWithAccessToAllSites_WhenLdapLoginSucceeds_AndDefaultSitesToAddIsAll()
77
+ {
78
+ Config::getInstance()->LoginLdap['new_user_default_sites_view_access'] = 'all';
79
+
80
+ $this->authenticateViaLdap();
81
+
82
+ $this->assertStarkSynchronized();
83
+
84
+ $access = $this->getAccessFor(self::TEST_LOGIN); // access added due to new_user_default_sites_view_access option
85
+ $this->assertEquals(array(
86
+ array('site' => '1', 'access' => 'view'),
87
+ array('site' => '2', 'access' => 'view'),
88
+ array('site' => '3', 'access' => 'view'),
89
+ array('site' => '4', 'access' => 'view'),
90
+ array('site' => '5', 'access' => 'view'),
91
+ array('site' => '6', 'access' => 'view')
92
+ ), $access);
93
+ }
94
+
95
+ public function test_PiwikUserIsNotCreated_IfPiwikUserAlreadyExists()
96
+ {
97
+ Access::getInstance()->setSuperUserAccess(true);
98
+ UsersManagerAPI::getInstance()->addUser(self::TEST_LOGIN, self::TEST_PASS, 'billionairephilanthropistplayboy@starkindustries.com');
99
+ Access::getInstance()->setSuperUserAccess(false);
100
+
101
+ $this->authenticateViaLdap();
102
+
103
+ $user = Db::fetchRow("SELECT login, password, email FROM " . Common::prefixTable('user') . " WHERE login = ?", array(self::TEST_LOGIN));
104
+ $this->assertNotEmpty($user);
105
+ $passwordHelper = new Password();
106
+ $this->assertTrue($passwordHelper->verify(md5(self::TEST_PASS), $user['password']));
107
+ unset($user['password']);
108
+ $this->assertEquals(array(
109
+ 'login' => self::TEST_LOGIN,
110
+ 'email' => 'billionairephilanthropistplayboy@starkindustries.com',
111
+ ), $user);
112
+
113
+ $this->assertNoAccessInDb();
114
+ }
115
+
116
+ public function test_PiwikUserIsNotCreated_IfPiwikUserAlreadyExistsAutoAcceptInviteIfPresent()
117
+ {
118
+ Access::getInstance()->setSuperUserAccess(true);
119
+ $email = 'billionairephilanthropistplayboy2@starkindustries.com';
120
+ UsersManagerAPI::getInstance()->inviteUser(self::TEST_LOGIN2, $email, 1);
121
+ Access::getInstance()->setSuperUserAccess(false);
122
+
123
+ $this->authenticateViaLdap(self::TEST_LOGIN2, self::TEST_PASS);
124
+
125
+ $user = Db::fetchRow("SELECT login, password, email, invite_token, invite_link_token, invite_expired_at, invite_accept_at FROM " . Common::prefixTable('user') . " WHERE login = ?", array(self::TEST_LOGIN2));
126
+ $inviteAcceptAt = $user['invite_accept_at'];
127
+ $this->assertNotEmpty($user);
128
+ unset($user['password']);
129
+ unset($user['invite_accept_at']);
130
+ $this->assertEquals(array(
131
+ 'login' => self::TEST_LOGIN2,
132
+ 'email' => $email,
133
+ 'invite_token' => null,
134
+ 'invite_link_token' => null,
135
+ 'invite_expired_at' => null,
136
+ ), $user);
137
+
138
+ $this->assertNotEmpty($inviteAcceptAt);
139
+
140
+ $access = $this->getAccessFor(self::TEST_LOGIN2);
141
+
142
+ $this->assertEquals([
143
+ [
144
+ 'site' => 1,
145
+ 'access' => 'view',
146
+ ]
147
+ ], $access);
148
+ }
149
+
150
+ public function test_PiwikUserIsUpdated_IfLdapUserAlreadySynchronized_ButLdapUserInfoIsDifferent()
151
+ {
152
+ Access::doAsSuperUser(function () {
153
+ UsersManagerAPI::getInstance()->addUser(
154
+ LdapUserSynchronizationTest::TEST_LOGIN,
155
+ LdapUserSynchronizationTest::TEST_PASS_LDAP,
156
+ 'something@domain.com',
157
+ $isPasswordHashed = false
158
+ );
159
+ });
160
+
161
+ $userMapper = new UserMapper();
162
+ $userMapper->markUserAsLdapUser(self::TEST_LOGIN);
163
+
164
+ $this->authenticateViaLdap();
165
+
166
+ $this->assertStarkSynchronized();
167
+ }
168
+
169
+ public function test_LdapSuperUserHasSuperUserAccess_WhenUserIsSynchronized()
170
+ {
171
+ $this->enableAccessSynchronization();
172
+
173
+ $this->authenticateViaLdap(self::TEST_SUPERUSER_LOGIN, self::TEST_SUPERUSER_PASS);
174
+
175
+ $superusers = $this->getSuperUsers();
176
+ $this->assertEquals(array(self::TEST_SUPERUSER_LOGIN), $superusers);
177
+ }
178
+
179
+ public function test_AdminAndViewAccessAddedForLdapUser_WhenLdapUserHasAccess_AndUserIsSynchronizedForFirstTime()
180
+ {
181
+ $this->enableAccessSynchronization();
182
+
183
+ $this->authenticateViaLdap();
184
+
185
+ $this->assertStarkAccessSynchronized();
186
+ }
187
+
188
+ public function test_AdminAndViewAccessUpdated_WhenLdapUserALreadySynchronized_ButLdapAccessInfoIsDifferent()
189
+ {
190
+ $this->enableAccessSynchronization();
191
+
192
+ Access::doAsSuperUser(function () {
193
+ UsersManagerAPI::getInstance()->addUser(
194
+ LdapUserSynchronizationTest::TEST_LOGIN,
195
+ md5('anypass'),
196
+ 'something@domain.com',
197
+ $isPasswordHashed = true
198
+ );
199
+ UsersManagerAPI::getInstance()->setUserAccess(LdapUserSynchronizationTest::TEST_LOGIN, 'view', array(4,5));
200
+ UsersManagerAPI::getInstance()->setUserAccess(LdapUserSynchronizationTest::TEST_LOGIN, 'admin', array(6));
201
+ });
202
+
203
+ $this->authenticateViaLdap();
204
+
205
+ $this->assertStarkAccessSynchronized();
206
+ }
207
+
208
+ public function test_AdminAndViewAccessSynchronized_WhenLdapAccessInfoPresent_AndInstanceNameUsed()
209
+ {
210
+ Config::getInstance()->LoginLdap['instance_name'] = 'myPiwik';
211
+
212
+ $this->enableAccessSynchronization();
213
+
214
+ $this->authenticateViaLdap('blackwidow', 'redledger');
215
+
216
+ $access = $this->getAccessFor('blackwidow');
217
+ $this->assertEquals(array(
218
+ array('site' => '1', 'access' => 'view'),
219
+ array('site' => '2', 'access' => 'view'),
220
+ array('site' => '3', 'access' => 'admin'),
221
+ array('site' => '4', 'access' => 'admin'),
222
+ ), $access);
223
+ }
224
+
225
+ public function test_SuperUserAccessSynchronized_WhenLdapAccessInfoPresent_AndInstanceNameUsed_AndUserIsSuperUser()
226
+ {
227
+ Config::getInstance()->LoginLdap['instance_name'] = 'myPiwik';
228
+ $this->enableAccessSynchronization();
229
+
230
+ $this->authenticateViaLdap('thor', 'bilgesnipe');
231
+
232
+ $superusers = $this->getSuperUsers();
233
+ $this->assertEquals(array('thor'), $superusers);
234
+ }
235
+
236
+ public function test_AdminAndViewAccessSynchronized_WhenLdapAccessInfoPresent_AndInstancePiwikUrlUsed()
237
+ {
238
+ $this->setPiwikInstanceUrl('http://localhost/');
239
+ Config::getInstance()->LoginLdap['ldap_superuser_access_field'] = 'isasuperuser'; // disable superuser check so we can check user's normal access
240
+
241
+ $this->enableAccessSynchronization();
242
+
243
+ $this->authenticateViaLdap('thor', 'bilgesnipe');
244
+
245
+ $access = $this->getAccessFor('thor');
246
+ $this->assertEquals(array(
247
+ array('site' => '1', 'access' => 'view'),
248
+ array('site' => '2', 'access' => 'view'),
249
+ array('site' => '3', 'access' => 'admin'),
250
+ array('site' => '4', 'access' => 'admin'),
251
+ ), $access);
252
+ }
253
+
254
+ public function test_SuperUserAccessSynchronized_WhenLdapAccessInfoPresent_AndInstancePiwikUrlUsed_AndUserIsSuperUser()
255
+ {
256
+ $this->setPiwikInstanceUrl('http://localhost/');
257
+ $this->enableAccessSynchronization();
258
+
259
+ $this->authenticateViaLdap('thor', 'bilgesnipe');
260
+
261
+ $superusers = $this->getSuperUsers();
262
+ $this->assertEquals(array('thor'), $superusers);
263
+ }
264
+
265
+ public function test_RandomPasswordGenerated()
266
+ {
267
+ $passwordManager = new Password();
268
+
269
+ $this->authenticateViaLdap();
270
+
271
+ $user = $this->getUser(self::TEST_LOGIN);
272
+
273
+ $this->assertTrue($passwordManager->verify(md5(self::TEST_PASS_LDAP), $user['password']));
274
+
275
+ // test that password doesn't change after re-synchronizing
276
+ $this->authenticateViaLdap();
277
+
278
+ $userAgain = $this->getUser(self::TEST_LOGIN);
279
+
280
+ $this->assertTrue($passwordManager->verify(md5(self::TEST_PASS_LDAP), $userAgain['password']));
281
+ }
282
+
283
+ public function test_CorrectExistingUserUpdated_WhenUserEmailSuffixUsed()
284
+ {
285
+ Config::getInstance()->LoginLdap['user_email_suffix'] = '@xmansion.org';
286
+
287
+ // authenticate via ldap to add the user w/ the email suffix
288
+ $this->authenticateViaLdap($login = 'rogue', $pass = 'cherry');
289
+
290
+ $user = $this->getUser('rogue@xmansion.org');
291
+
292
+ $this->assertNotEmpty($user);
293
+
294
+ // authenticate again to make sure the correct user is updated and we didn't try to add again
295
+ $this->authenticateViaLdap($login = 'rogue', $pass = 'cherry');
296
+ }
297
+
298
+ private function assertNoAccessInDb($login = self::TEST_LOGIN)
299
+ {
300
+ $access = $this->getAccessFor($login);
301
+ $this->assertEquals(array(), $access);
302
+
303
+ $superusers = $this->getSuperUsers();
304
+ $this->assertEquals(array(), $superusers);
305
+ }
306
+
307
+ private function getAccessFor($login)
308
+ {
309
+ return Access::doAsSuperUser(function () use ($login) {
310
+ return UsersManagerAPI::getInstance()->getSitesAccessFromUser($login);
311
+ });
312
+ }
313
+
314
+ private function getSuperUsers()
315
+ {
316
+ $result = array();
317
+ foreach (Db::fetchAll("SELECT login FROM " . Common::prefixTable('user') . " WHERE superuser_access = 1") as $row) {
318
+ $result[] = $row['login'];
319
+ }
320
+ return $result;
321
+ }
322
+
323
+ private function authenticateViaLdap($login = self::TEST_LOGIN, $pass = self::TEST_PASS)
324
+ {
325
+ $ldapAuth = LdapAuth::makeConfigured();
326
+ $ldapAuth->setLogin($login);
327
+ $ldapAuth->setPassword($pass);
328
+ $authResult = $ldapAuth->authenticate();
329
+
330
+ $this->assertEquals(1, $authResult->getCode());
331
+
332
+ return $authResult;
333
+ }
334
+
335
+ private function enableAccessSynchronization()
336
+ {
337
+ Config::getInstance()->LoginLdap['enable_synchronize_access_from_ldap'] = 1;
338
+ }
339
+
340
+ private function assertStarkAccessSynchronized()
341
+ {
342
+ $access = $this->getAccessFor(self::TEST_LOGIN);
343
+
344
+ $this->assertEquals(array(
345
+ array('site' => '1', 'access' => 'view'),
346
+ array('site' => '2', 'access' => 'view'),
347
+ array('site' => '3', 'access' => 'admin')
348
+ ), $access);
349
+ }
350
+
351
+ private function setPiwikInstanceUrl($url)
352
+ {
353
+ SettingsPiwik::overwritePiwikUrl($url);
354
+ }
355
+ }
plugins/LoginLdap/tests/Integration/MultipleServersTest.php ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Integration;
12
+
13
+ use Piwik\Config;
14
+ use Piwik\Plugins\LoginLdap\Auth\LdapAuth;
15
+
16
+ /**
17
+ * @group LoginLdap
18
+ * @group LoginLdap_Integration
19
+ * @group LoginLdap_MultipleServersTest
20
+ */
21
+ class MultipleServersTest extends LdapIntegrationTest
22
+ {
23
+ public function setUp(): void
24
+ {
25
+ parent::setUp();
26
+
27
+ Config::getInstance()->LoginLdap_dummyserver1 = array(
28
+ 'hostname' => "notanldaphost.com",
29
+ 'port' => self::SERVER_PORT,
30
+ 'base_dn' => self::SERVER_BASE_DN,
31
+ 'admin_user' => 'cn=fury,' . self::SERVER_BASE_DN,
32
+ 'admin_pass' => 'secrets',
33
+ 'start_tls' => false
34
+ );
35
+ Config::getInstance()->LoginLdap_dummyserver2 = array(
36
+ 'hostname' => "localhost",
37
+ 'port' => 999,
38
+ 'base_dn' => self::SERVER_BASE_DN,
39
+ 'admin_user' => 'cn=fury,' . self::SERVER_BASE_DN,
40
+ 'admin_pass' => 'secrets',
41
+ 'start_tls' => false
42
+ );
43
+ }
44
+
45
+ public function testAuthenticateSucceedsWhenFirstServerWorksButOthersFailToConnect()
46
+ {
47
+ Config::getInstance()->LoginLdap['servers'] = array('testserver', 'dummyserver1', 'dummyserver2');
48
+
49
+ $this->doAuthTest();
50
+ }
51
+
52
+ public function testAuthenticateSucceedsWhenOneServerSucceedsButOthersFailToConnect()
53
+ {
54
+ Config::getInstance()->LoginLdap['servers'] = array('dummyserver1', 'testserver', 'dummyserver2');
55
+
56
+ $this->doAuthTest();
57
+
58
+ Config::getInstance()->LoginLdap['servers'] = array('dummyserver1', 'dummyserver2', 'testserver');
59
+
60
+ $this->doAuthTest();
61
+ }
62
+
63
+ public function testAuthenticateFailsWhenAllServersFailToConnect()
64
+ {
65
+ $this->expectException(\Piwik\Plugins\LoginLdap\Ldap\Exceptions\ConnectionException::class);
66
+ $this->expectExceptionMessage('Could not connect to any of the');
67
+
68
+ Config::getInstance()->LoginLdap['servers'] = array('dummyserver1', 'dummyserver2');
69
+
70
+ $this->doAuthTest($expectCode = 0);
71
+ }
72
+
73
+ private function doAuthTest($expectCode = 1)
74
+ {
75
+ $ldapAuth = LdapAuth::makeConfigured();
76
+ $ldapAuth->setLogin(self::TEST_LOGIN);
77
+ $ldapAuth->setPassword(self::TEST_PASS);
78
+ $authResult = $ldapAuth->authenticate();
79
+
80
+ $this->assertEquals($expectCode, $authResult->getCode());
81
+ }
82
+ }
plugins/LoginLdap/tests/Integration/PasswordConfirmationTest.php ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ */
9
+
10
+ namespace Piwik\Plugins\LoginLdap\tests\Integration;
11
+
12
+ use Piwik\Access;
13
+ use Piwik\Container\StaticContainer;
14
+ use Piwik\Piwik;
15
+ use Piwik\Plugins\LoginLdap\API;
16
+ use Piwik\Plugins\LoginLdap\Controller;
17
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserMapper;
18
+ use Piwik\Plugins\Login\PasswordVerifier;
19
+
20
+ /**
21
+ * @group LoginLdap
22
+ * @group LoginLdap_Integration
23
+ * @group LoginLdap_PasswordConfirmationTest
24
+ */
25
+ class PasswordConfirmationTest extends LdapIntegrationTest
26
+ {
27
+ /**
28
+ * @var PasswordVerifier
29
+ */
30
+ private $passwordVerifier;
31
+
32
+ /**
33
+ * @var API
34
+ */
35
+ private $api;
36
+
37
+ public function setUp(): void
38
+ {
39
+ parent::setUp();
40
+
41
+ \Zend_Session::$_unitTestEnabled = true;
42
+
43
+ \Piwik\Config::getInstance()->LoginLdap['enable_password_confirmation'] = 0;
44
+ $this->addNonLdapUsers();
45
+ $this->passwordVerifier = new PasswordVerifier();
46
+ $this->passwordVerifier->setDisableRedirect();
47
+ StaticContainer::getContainer()->set('Piwik\Plugins\Login\PasswordVerifier', $this->passwordVerifier);
48
+ $this->api = new API();
49
+ }
50
+
51
+ public function testPasswordConfirmationStillRequiredForNonLdapUsersWhenDisabledInConfig()
52
+ {
53
+ $this->setCurrentUser(self::NON_LDAP_USER, self::NON_LDAP_PASS);
54
+
55
+ $this->assertTrue(Piwik::doesUserRequirePasswordConfirmation(self::NON_LDAP_USER));
56
+
57
+ $this->passwordVerifier->requirePasswordVerifiedRecently(['module' => 'Login', 'action' => 'test']);
58
+ $plugin = new \Piwik\Plugins\LoginLdap\LoginLdap();
59
+ $plugin->checkIfPasswordConfirmationCanBeSkipped();
60
+
61
+ $this->assertFalse($this->passwordVerifier->hasBeenVerified());
62
+
63
+ $controller = new Controller(null, null, null, $this->passwordVerifier);
64
+ $result = $controller->confirmPassword();
65
+
66
+ $this->assertIsString($result);
67
+ $this->assertStringContainsString('confirmPasswordForm', $result);
68
+ $this->assertFalse($this->passwordVerifier->hasBeenVerified());
69
+ }
70
+
71
+ public function testPasswordConfirmationCanStillBeSkippedForLdapUsersWhenDisabledInConfig()
72
+ {
73
+ $this->addLdapUser(self::TEST_LOGIN, self::TEST_PASS);
74
+ $this->setCurrentUser(self::TEST_LOGIN, self::TEST_PASS);
75
+
76
+ $this->assertFalse(Piwik::doesUserRequirePasswordConfirmation(self::TEST_LOGIN));
77
+
78
+ $this->passwordVerifier->requirePasswordVerifiedRecently(['module' => 'Login', 'action' => 'test']);
79
+ $plugin = new \Piwik\Plugins\LoginLdap\LoginLdap();
80
+ $plugin->checkIfPasswordConfirmationCanBeSkipped();
81
+
82
+ $this->assertTrue($this->passwordVerifier->hasBeenVerified());
83
+
84
+ $this->passwordVerifier->forgetVerifiedPassword();
85
+ $this->passwordVerifier->requirePasswordVerifiedRecently(['module' => 'Login', 'action' => 'test']);
86
+
87
+ $controller = new Controller(null, null, null, $this->passwordVerifier);
88
+ $result = $controller->confirmPassword();
89
+
90
+ $this->assertNull($result);
91
+ $this->assertTrue($this->passwordVerifier->hasBeenVerified());
92
+ }
93
+
94
+ public function testSaveLdapConfigRequiresPasswordConfirmationWhenEnabled()
95
+ {
96
+ $_SERVER['REQUEST_METHOD'] = 'POST';
97
+ \Piwik\Config::getInstance()->LoginLdap['enable_password_confirmation'] = 1;
98
+ $this->setCurrentUser(self::NON_LDAP_USER, self::NON_LDAP_PASS);
99
+
100
+ $this->expectException(\Exception::class);
101
+ $this->api->saveLdapConfig(json_encode(array(
102
+ 'use_ldap_for_authentication' => 1,
103
+ )));
104
+ }
105
+
106
+ public function testSaveLdapConfigRequiresPasswordConfirmationWhenDisabledForNonLdapUsers()
107
+ {
108
+ $_SERVER['REQUEST_METHOD'] = 'POST';
109
+ \Piwik\Config::getInstance()->LoginLdap['enable_password_confirmation'] = 0;
110
+ $this->setCurrentUser(self::NON_LDAP_USER, self::NON_LDAP_PASS);
111
+
112
+ $this->expectException(\Exception::class);
113
+ $this->api->saveLdapConfig(json_encode(array(
114
+ 'use_ldap_for_authentication' => 0,
115
+ )));
116
+ }
117
+
118
+ public function testSaveLdapConfigSucceedsWithoutPasswordConfirmationWhenDisabledForLdapUsers()
119
+ {
120
+ $_SERVER['REQUEST_METHOD'] = 'POST';
121
+ \Piwik\Config::getInstance()->LoginLdap['enable_password_confirmation'] = 0;
122
+ $this->addLdapUser(self::TEST_LOGIN, self::TEST_PASS);
123
+ $this->setSuperUserAccess(self::TEST_LOGIN, true);
124
+ $this->setCurrentUser(self::TEST_LOGIN, self::TEST_PASS);
125
+
126
+ $result = $this->api->saveLdapConfig(json_encode(array(
127
+ 'use_ldap_for_authentication' => 0,
128
+ )));
129
+
130
+ $this->assertSame('success', $result['result']);
131
+ }
132
+
133
+ public function testSaveLdapConfigSucceedsWithPasswordConfirmationWhenEnabled()
134
+ {
135
+ $_SERVER['REQUEST_METHOD'] = 'POST';
136
+ \Piwik\Config::getInstance()->LoginLdap['enable_password_confirmation'] = 1;
137
+ $this->setCurrentUser(self::NON_LDAP_USER, self::NON_LDAP_PASS);
138
+
139
+ $result = $this->api->saveLdapConfig(
140
+ json_encode(array(
141
+ 'use_ldap_for_authentication' => 0,
142
+ 'password_confirmation' => self::NON_LDAP_PASS,
143
+ ))
144
+ );
145
+
146
+ $this->assertSame('success', $result['result']);
147
+ }
148
+
149
+ public function testSaveServersInfoRequiresPasswordConfirmationWhenEnabled()
150
+ {
151
+ $_SERVER['REQUEST_METHOD'] = 'POST';
152
+ \Piwik\Config::getInstance()->LoginLdap['enable_password_confirmation'] = 1;
153
+ $this->setCurrentUser(self::NON_LDAP_USER, self::NON_LDAP_PASS);
154
+
155
+ $this->expectException(\Exception::class);
156
+ $this->api->saveServersInfo(json_encode($this->getServerPayload()));
157
+ }
158
+
159
+ public function testSaveServersInfoSucceedsAfterPasswordConfirmationWhenEnabled()
160
+ {
161
+ $_SERVER['REQUEST_METHOD'] = 'POST';
162
+ \Piwik\Config::getInstance()->LoginLdap['enable_password_confirmation'] = 1;
163
+ $this->setCurrentUser(self::NON_LDAP_USER, self::NON_LDAP_PASS);
164
+
165
+ $result = $this->api->saveServersInfo(json_encode($this->getServerPayload()), self::NON_LDAP_PASS);
166
+
167
+ $this->assertSame('success', $result['result']);
168
+ }
169
+
170
+ public function testSaveServersInfoRequiresPasswordConfirmationWhenDisabledForNonLdapUsers()
171
+ {
172
+ $_SERVER['REQUEST_METHOD'] = 'POST';
173
+ \Piwik\Config::getInstance()->LoginLdap['enable_password_confirmation'] = 0;
174
+ $this->setCurrentUser(self::NON_LDAP_USER, self::NON_LDAP_PASS);
175
+
176
+ $this->expectException(\Exception::class);
177
+ $this->api->saveServersInfo(json_encode($this->getServerPayload()));
178
+ }
179
+
180
+ public function testSaveServersInfoSucceedsWithoutPasswordConfirmationWhenDisabledForLdapUsers()
181
+ {
182
+ $_SERVER['REQUEST_METHOD'] = 'POST';
183
+ \Piwik\Config::getInstance()->LoginLdap['enable_password_confirmation'] = 0;
184
+ $this->addLdapUser(self::TEST_LOGIN, self::TEST_PASS);
185
+ $this->setSuperUserAccess(self::TEST_LOGIN, true);
186
+ $this->setCurrentUser(self::TEST_LOGIN, self::TEST_PASS);
187
+
188
+ $result = $this->api->saveServersInfo(json_encode($this->getServerPayload()));
189
+
190
+ $this->assertSame('success', $result['result']);
191
+ }
192
+
193
+ private function addLdapUser(string $login, string $password): void
194
+ {
195
+ \Piwik\Plugins\UsersManager\API::getInstance()->addUser(
196
+ $login,
197
+ $password,
198
+ $login . '@shield.org'
199
+ );
200
+
201
+ $userMapper = new UserMapper();
202
+ $userMapper->markUserAsLdapUser($login);
203
+
204
+ \Piwik\Access::doAsSuperUser(function () use ($login) {
205
+ \Piwik\Plugins\UsersManager\API::getInstance()->setUserAccess($login, 'view', [1]);
206
+ });
207
+ }
208
+
209
+ private function setCurrentUser(string $login, string $password): void
210
+ {
211
+ $auth = StaticContainer::get('Piwik\Auth');
212
+ $auth->setLogin($login);
213
+ $auth->setPassword($password);
214
+ Access::getInstance()->setSuperUserAccess(false);
215
+ Access::getInstance()->reloadAccess($auth);
216
+ }
217
+
218
+ private function getServerPayload(): array
219
+ {
220
+ return array(
221
+ array(
222
+ 'name' => 'server1',
223
+ 'hostname' => 'localhost',
224
+ 'port' => 389,
225
+ 'base_dn' => 'dc=avengers,dc=shield,dc=org',
226
+ 'admin_user' => 'cn=fury,dc=avengers,dc=shield,dc=org',
227
+ 'admin_pass' => 'secrets',
228
+ 'start_tls' => false,
229
+ ),
230
+ );
231
+ }
232
+ }
plugins/LoginLdap/tests/Integration/SynchronizedAuthTest.php ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ */
9
+
10
+ namespace Piwik\Plugins\LoginLdap\tests\Integration;
11
+
12
+ use Piwik\Auth;
13
+ use Piwik\Auth\Password;
14
+ use Piwik\Config;
15
+ use Piwik\Container\StaticContainer;
16
+ use Piwik\Plugins\LoginLdap\Auth\SynchronizedAuth;
17
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserMapper;
18
+ use Piwik\Plugins\UsersManager\API as UsersManagerAPI;
19
+ use Piwik\Log\LoggerInterface;
20
+
21
+ /**
22
+ * @group LoginLdap
23
+ * @group LoginLdap_Integration
24
+ * @group LoginLdap_SynchronizedAuthTest
25
+ */
26
+ class SynchronizedAuthTest extends LdapIntegrationTest
27
+ {
28
+ private $testUserTokenAuth;
29
+
30
+ public function setUp(): void
31
+ {
32
+ parent::setUp();
33
+
34
+ Config::getInstance()->LoginLdap_brokenserver = array(
35
+ 'hostname' => "localhost",
36
+ 'port' => 999,
37
+ 'base_dn' => self::SERVER_BASE_DN,
38
+ 'admin_user' => 'cn=fury,' . self::SERVER_BASE_DN,
39
+ 'admin_pass' => 'secrets',
40
+ 'start_tls' => false
41
+ );
42
+ }
43
+
44
+ public function test_SynchronizedLdapUsersCanLogin_WithoutConnectingToLdap_WhenUsersExistInPiwikDB()
45
+ {
46
+ Config::getInstance()->LoginLdap['servers'] = array('brokenserver');
47
+
48
+ $this->addPreSynchronizedUser();
49
+
50
+ $this->doAuthTest($code = 1);
51
+ }
52
+
53
+ public function test_NormalPiwikUsersCanLogin_WithoutConnectingToLdap()
54
+ {
55
+ Config::getInstance()->LoginLdap['servers'] = array('brokenserver');
56
+
57
+ $this->addNonLdapUsers();
58
+
59
+ $this->doAuthTest($code = 42, self::NON_LDAP_USER, self::NON_LDAP_PASS);
60
+ $this->doAuthTest($code = 1, self::NON_LDAP_NORMAL_USER, self::NON_LDAP_NORMAL_PASS);
61
+ }
62
+
63
+ public function test_SynchronizedLdapUsersCanLogin_WithoutConnectingToLdap_ByTokenAuth()
64
+ {
65
+ Config::getInstance()->LoginLdap['servers'] = array('brokenserver');
66
+
67
+ $this->addPreSynchronizedUser();
68
+
69
+ $this->doAuthTestByTokenAuth($code = 1, self::TEST_LOGIN, self::TEST_PASS, $this->testUserTokenAuth);
70
+ }
71
+
72
+ public function test_NormalPiwikUsersCanLogin_WithoutConnectingToLdap_ByTokenAuth()
73
+ {
74
+ Config::getInstance()->LoginLdap['servers'] = array('brokenserver');
75
+
76
+ $this->addNonLdapUsers();
77
+
78
+ $this->doAuthTestByTokenAuth($code = 42, self::NON_LDAP_USER, self::NON_LDAP_PASS);
79
+ $this->doAuthTestByTokenAuth($code = 1, self::NON_LDAP_NORMAL_USER, self::NON_LDAP_NORMAL_PASS);
80
+ }
81
+
82
+ public function test_SynchronizedLdapUsersCanLogin_WithoutConnectingToLdap_ByPasswordHash()
83
+ {
84
+ Config::getInstance()->LoginLdap['servers'] = array('brokenserver');
85
+
86
+ $this->addPreSynchronizedUser();
87
+
88
+ $this->doAuthTestByPasswordHash($code = 1);
89
+ }
90
+
91
+ public function test_NormalPiwikUsersCanLogin_WithoutConnectingToLdap_ByPasswordHash()
92
+ {
93
+ StaticContainer::get(LoggerInterface::class)->info("NEXT TEST");
94
+ Config::getInstance()->LoginLdap['servers'] = array('brokenserver');
95
+
96
+ $this->addNonLdapUsers();
97
+
98
+ $this->doAuthTestByPasswordHash($code = 42, self::NON_LDAP_USER, self::NON_LDAP_PASS);
99
+ $this->doAuthTestByPasswordHash($code = 1, self::NON_LDAP_NORMAL_USER, self::NON_LDAP_NORMAL_PASS);
100
+ }
101
+
102
+ public function test_LdapUsersCannotLogin_IfUnsynchronized_AndLdapServerBroken()
103
+ {
104
+ $this->expectException(\Piwik\Plugins\LoginLdap\Ldap\Exceptions\ConnectionException::class);
105
+
106
+ Config::getInstance()->LoginLdap['servers'] = ['brokenserver'];
107
+
108
+ $this->doAuthTest($code = 0);
109
+ }
110
+
111
+ public function test_LdapUserCannotLogin_IfUserNotInDb_SynchronizingAfterLoginDisabled()
112
+ {
113
+ Config::getInstance()->LoginLdap['synchronize_users_after_login'] = 0;
114
+
115
+ $this->doAuthTest($code = 0);
116
+ }
117
+
118
+ public function test_LdapUserCannotLogin_IfUserNotInDb_AndAuthenticatingByTokenAuth()
119
+ {
120
+ Config::getInstance()->LoginLdap['synchronize_users_after_login'] = 0;
121
+
122
+ $this->doAuthTestByTokenAuth($code = 0, self::TEST_LOGIN, self::TEST_PASS, 'garbagetokenauth');
123
+ }
124
+
125
+ public function test_LdapUserCannotLogin_IfUserNotInDb_AndAuthtenticatingByPasswordHash()
126
+ {
127
+ Config::getInstance()->LoginLdap['synchronize_users_after_login'] = 0;
128
+
129
+ $this->doAuthTestByPasswordHash($code = 0);
130
+ }
131
+
132
+ public function test_AuthenticationFails_WhenUserNotInDb_AndUserNotInLdap()
133
+ {
134
+ $this->doAuthTest($code = 0, self::NON_LDAP_USER, self::NON_LDAP_PASS);
135
+ }
136
+
137
+ public function test_AuthenticationFails_WhenUserNotInDb_AndUserInLdap_AndOnlyTokenAuthTested()
138
+ {
139
+ $this->doAuthTest($code = 0, self::TEST_LOGIN, null, $this->getLdapUserTokenAuth());
140
+ }
141
+
142
+ public function test_LdapUserPasswordUpdated_AfterSuccessfulLoginViaLdap()
143
+ {
144
+ $this->addLdapUserWithWrongPassword();
145
+
146
+ $this->doAuthTest($code = 1);
147
+
148
+ $user = $this->getUser(self::TEST_LOGIN);
149
+
150
+ $passwordHelper = new Password();
151
+ $this->assertTrue($passwordHelper->verify(\Piwik\Plugins\UsersManager\UsersManager::getPasswordHash(self::TEST_PASS), $user['password']));
152
+ }
153
+
154
+ private function addPreSynchronizedUser($pass = self::TEST_PASS)
155
+ {
156
+ UsersManagerAPI::getInstance()->addUser(
157
+ self::TEST_LOGIN,
158
+ $pass,
159
+ 'billionairephilanthropistplayboy@starkindustries.com'
160
+ );
161
+
162
+ $userMapper = new UserMapper();
163
+ $userMapper->markUserAsLdapUser(self::TEST_LOGIN);
164
+
165
+ $this->testUserTokenAuth = UsersManagerAPI::getInstance()->createAppSpecificTokenAuth(
166
+ self::TEST_LOGIN,
167
+ $pass,
168
+ 'test'
169
+ );
170
+ }
171
+
172
+ private function addLdapUserWithWrongPassword()
173
+ {
174
+ $this->addPreSynchronizedUser('averywrongpassword');
175
+ }
176
+
177
+ private function doAuthTest($expectCode, $login = self::TEST_LOGIN, $pass = self::TEST_PASS, $token_auth = null)
178
+ {
179
+ $auth = SynchronizedAuth::makeConfigured();
180
+ if (!empty($login)) {
181
+ $auth->setLogin($login);
182
+ }
183
+ if (!empty($pass)) {
184
+ $auth->setPassword($pass);
185
+ }
186
+ if (!empty($token_auth)) {
187
+ $auth->setTokenAuth($token_auth);
188
+ }
189
+ $result = $auth->authenticate();
190
+
191
+ $this->assertEquals($expectCode, $result->getCode());
192
+ }
193
+
194
+ private function doAuthTestByTokenAuth($expectCode, $login = self::TEST_LOGIN, $pass = self::TEST_PASS, $tokenAuth = null)
195
+ {
196
+ $auth = SynchronizedAuth::makeConfigured();
197
+ StaticContainer::getContainer()->set(Auth::class, $auth);
198
+
199
+ $tokenAuth = $tokenAuth ?: UsersManagerAPI::getInstance()->createAppSpecificTokenAuth($login, $pass, 'test');
200
+
201
+ $auth->setLogin($login);
202
+ $auth->setTokenAuth($tokenAuth);
203
+ $result = $auth->authenticate();
204
+
205
+ $this->assertEquals($expectCode, $result->getCode());
206
+ }
207
+
208
+ private function doAuthTestByPasswordHash($expectCode, $login = self::TEST_LOGIN, $pass = self::TEST_PASS)
209
+ {
210
+ $auth = SynchronizedAuth::makeConfigured();
211
+ $auth->setLogin($login);
212
+ $auth->setPasswordHash(md5($pass));
213
+ $result = $auth->authenticate();
214
+
215
+ $this->assertEquals($expectCode, $result->getCode());
216
+ }
217
+
218
+ private function getLdapUserTokenAuth()
219
+ {
220
+ return $this->testUserTokenAuth;
221
+ }
222
+ }
plugins/LoginLdap/tests/Integration/WebServerAuthTest.php ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Integration;
12
+
13
+ use Piwik\AuthResult;
14
+ use Piwik\Config;
15
+ use Piwik\Plugins\LoginLdap\Auth\WebServerAuth;
16
+ use Piwik\Plugins\UsersManager\API as UsersManagerAPI;
17
+ use Piwik\Session;
18
+ use Piwik\Session\SessionAuth;
19
+ use Piwik\Session\SessionFingerprint;
20
+
21
+ /**
22
+ * @group LoginLdap
23
+ * @group LoginLdap_Integration
24
+ * @group LoginLdap_WebServerAuthTest
25
+ */
26
+ class WebServerAuthTest extends LdapIntegrationTest
27
+ {
28
+ private $testSuperUserTokenAuth;
29
+
30
+ public function setUp(): void
31
+ {
32
+ parent::setUp();
33
+
34
+ $this->addPreexistingSuperUser();
35
+ $this->testSuperUserTokenAuth = UsersManagerAPI::getInstance()->createAppSpecificTokenAuth(
36
+ self::TEST_SUPERUSER_LOGIN,
37
+ self::TEST_SUPERUSER_PASS,
38
+ 'test'
39
+ );
40
+ }
41
+
42
+ public function test_WebServerAuth_Works_IfUserExists_RegardlessOfPassword()
43
+ {
44
+ Config::getInstance()->LoginLdap['use_webserver_auth'] = 1;
45
+
46
+ $_SERVER['REMOTE_USER'] = self::TEST_LOGIN;
47
+
48
+ $ldapAuth = WebServerAuth::makeConfigured();
49
+ $ldapAuth->setPassword('slkdjfdslf');
50
+ $authResult = $ldapAuth->authenticate();
51
+
52
+ $this->assertEquals(1, $authResult->getCode());
53
+
54
+ $ldapAuth = WebServerAuth::makeConfigured();
55
+ $ldapAuth->setPassword(self::TEST_PASS);
56
+ $authResult = $ldapAuth->authenticate();
57
+
58
+ $this->assertEquals(1, $authResult->getCode());
59
+ }
60
+
61
+ public function test_WebServerAuth_Fails_IfUserDoesNotExist()
62
+ {
63
+ Config::getInstance()->LoginLdap['use_webserver_auth'] = 1;
64
+
65
+ $_SERVER['REMOTE_USER'] = 'abcdefghijk';
66
+
67
+ $ldapAuth = WebServerAuth::makeConfigured();
68
+ $authResult = $ldapAuth->authenticate();
69
+
70
+ $this->assertEquals(0, $authResult->getCode());
71
+ }
72
+
73
+ public function test_WebServerAuth_Fails_IfUserIsNotPartOfRequiredGroup()
74
+ {
75
+ Config::getInstance()->LoginLdap['use_webserver_auth'] = 1;
76
+ Config::getInstance()->LoginLdap['memberOf'] = "cn=S.H.I.E.L.D.," . self::SERVER_BASE_DN;
77
+
78
+ $_SERVER['REMOTE_USER'] = self::TEST_LOGIN;
79
+
80
+ $ldapAuth = WebServerAuth::makeConfigured();
81
+ $authResult = $ldapAuth->authenticate();
82
+
83
+ $this->assertEquals(0, $authResult->getCode());
84
+ }
85
+
86
+ public function test_WebServerAuth_Fails_IfUserIsNotMatchedByCustomFilter()
87
+ {
88
+ Config::getInstance()->LoginLdap['use_webserver_auth'] = 1;
89
+ Config::getInstance()->LoginLdap['filter'] = "(mobile=none)";
90
+
91
+ $_SERVER['REMOTE_USER'] = self::TEST_LOGIN;
92
+
93
+ $ldapAuth = WebServerAuth::makeConfigured();
94
+ $authResult = $ldapAuth->authenticate();
95
+
96
+ $this->assertEquals(0, $authResult->getCode());
97
+ }
98
+
99
+ public function test_WebServerAuth_Fails_IfUserNoRemoteUserExists_AndNoUserSpecifiedThroughAuth()
100
+ {
101
+ Config::getInstance()->LoginLdap['use_webserver_auth'] = 1;
102
+
103
+ unset($_SERVER['REMOTE_USER']);
104
+
105
+ $ldapAuth = WebServerAuth::makeConfigured();
106
+ $authResult = $ldapAuth->authenticate();
107
+
108
+ $this->assertEquals(0, $authResult->getCode());
109
+ }
110
+
111
+ public function test_WebServerAuth_UsesCorrectFallbackAuth_IfNoRemoteUserExists_AndAuthDetailsSpecified()
112
+ {
113
+ Config::getInstance()->LoginLdap['use_webserver_auth'] = 1;
114
+
115
+ unset($_SERVER['REMOTE_USER']);
116
+
117
+ $ldapAuth = WebServerAuth::makeConfigured();
118
+ $ldapAuth->setLogin(self::TEST_LOGIN);
119
+ $ldapAuth->setPassword(self::TEST_PASS);
120
+ $authResult = $ldapAuth->authenticate();
121
+
122
+ $this->assertEquals(1, $authResult->getCode());
123
+ }
124
+
125
+ public function test_WebServerAuth_ReturnsCorrectCodeForSuperUsers()
126
+ {
127
+ Config::getInstance()->LoginLdap['use_webserver_auth'] = 1;
128
+
129
+ $_SERVER['REMOTE_USER'] = self::TEST_SUPERUSER_LOGIN;
130
+
131
+ $ldapAuth = WebServerAuth::makeConfigured();
132
+ $authResult = $ldapAuth->authenticate();
133
+
134
+ $this->assertEquals(AuthResult::SUCCESS_SUPERUSER_AUTH_CODE, $authResult->getCode());
135
+ }
136
+
137
+ public function test_SuperUsersCanLogin_IfWebServerAuthUsed_AndWebServerAuthSetupIncorrectly()
138
+ {
139
+ unset($_SERVER['REMOTE_USER']);
140
+
141
+ $ldapAuth = WebServerAuth::makeConfigured();
142
+ $ldapAuth->setLogin(self::TEST_SUPERUSER_LOGIN);
143
+ $ldapAuth->setPassword(self::TEST_SUPERUSER_PASS);
144
+ $authResult = $ldapAuth->authenticate();
145
+
146
+ $this->assertEquals(AuthResult::SUCCESS_SUPERUSER_AUTH_CODE, $authResult->getCode());
147
+
148
+ $ldapAuth = WebServerAuth::makeConfigured();
149
+ $ldapAuth->setLogin(self::TEST_SUPERUSER_LOGIN);
150
+ $ldapAuth->setTokenAuth($this->testSuperUserTokenAuth);
151
+ $authResult = $ldapAuth->authenticate();
152
+
153
+ $this->assertEquals(AuthResult::SUCCESS_SUPERUSER_AUTH_CODE, $authResult->getCode());
154
+ }
155
+
156
+ public function test_WebServerAuth_Fails_IfDomainNotStrippedCorrectly()
157
+ {
158
+ Config::getInstance()->LoginLdap['use_webserver_auth'] = 1;
159
+
160
+ Config::getInstance()->LoginLdap['strip_domain_from_web_auth'] = 1;
161
+ $_SERVER['REMOTE_USER'] = self::TEST_LOGIN . '@shield.org';
162
+ $ldapAuth = WebServerAuth::makeConfigured();
163
+ $authResult = $ldapAuth->authenticate();
164
+ $this->assertEquals(AuthResult::SUCCESS, $authResult->getCode());
165
+
166
+ Config::getInstance()->LoginLdap['strip_domain_from_web_auth'] = 0;
167
+ $_SERVER['REMOTE_USER'] = self::TEST_LOGIN . '@shield.org';
168
+ $ldapAuth = WebServerAuth::makeConfigured();
169
+ $authResult = $ldapAuth->authenticate();
170
+ $this->assertEquals(AuthResult::FAILURE, $authResult->getCode());
171
+ }
172
+
173
+ /**
174
+ * @runInSeparateProcess
175
+ */
176
+ public function test_WebServerAuth_CreatesReusableAuthenticatedSession()
177
+ {
178
+ Config::getInstance()->LoginLdap['use_webserver_auth'] = 1;
179
+
180
+ Session::start();
181
+ $originalSessionId = session_id();
182
+
183
+ $_SERVER['REMOTE_USER'] = self::TEST_LOGIN;
184
+
185
+ $ldapAuth = WebServerAuth::makeConfigured();
186
+ $authResult = $ldapAuth->authenticate();
187
+
188
+ $this->assertEquals(AuthResult::SUCCESS, $authResult->getCode());
189
+ $this->assertNotSame($originalSessionId, session_id());
190
+
191
+ $sessionFingerprint = new SessionFingerprint();
192
+ $this->assertEquals(self::TEST_LOGIN, $sessionFingerprint->getUser());
193
+ $this->assertSame($authResult->getTokenAuth(), $sessionFingerprint->getSessionTokenAuth());
194
+
195
+ $sessionAuth = new SessionAuth(null, false);
196
+ $sessionAuthResult = $sessionAuth->authenticate();
197
+
198
+ $this->assertEquals(AuthResult::SUCCESS, $sessionAuthResult->getCode());
199
+ $this->assertSame(self::TEST_LOGIN, $sessionAuthResult->getIdentity());
200
+ }
201
+ }
plugins/LoginLdap/tests/Mocks/LdapFunctions.php ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\Ldap;
12
+
13
+ // mocks ldap_* functions for Ldap\Client class
14
+ class LdapFunctions
15
+ {
16
+ /** @var \PHPUnit\Framework\MockObject\MockObject */
17
+ public static $phpUnitMock;
18
+
19
+ public static function __callStatic($name, $arguments)
20
+ {
21
+ if (isset(self::$phpUnitMock)) {
22
+ return call_user_func_array(array(self::$phpUnitMock, $name), $arguments);
23
+ } else {
24
+ return call_user_func_array("\\" . $name, $arguments);
25
+ }
26
+ }
27
+ }
28
+
29
+ function ldap_connect($hostname = null, $port = null)
30
+ {
31
+ /** @noinspection PhpUndefinedMethodInspection */
32
+ if (version_compare(PHP_VERSION, 8.3, '>=')) {
33
+ return LdapFunctions::ldap_connect($hostname);
34
+ }
35
+
36
+ return LdapFunctions::ldap_connect($hostname, $port);
37
+ }
38
+
39
+ function ldap_set_option($connection = null, $optionName = null, $optionValue = null)
40
+ {
41
+ /** @noinspection PhpUndefinedMethodInspection */
42
+ return LdapFunctions::ldap_set_option($connection, $optionName, $optionValue);
43
+ }
44
+
45
+ function ldap_error($link_identifier)
46
+ {
47
+ /** @noinspection PhpUndefinedMethodInspection */
48
+ return LdapFunctions::ldap_error($link_identifier);
49
+ }
50
+
51
+ function ldap_bind($connection = null, $resourceDn = null, $password = null)
52
+ {
53
+ /** @noinspection PhpUndefinedMethodInspection */
54
+ return LdapFunctions::ldap_bind($connection, $resourceDn, $password);
55
+ }
56
+
57
+ function ldap_search($connection = null, $baseDn = null, $filter = null)
58
+ {
59
+ /** @noinspection PhpUndefinedMethodInspection */
60
+ return LdapFunctions::ldap_search($connection, $baseDn, $filter);
61
+ }
62
+
63
+ function ldap_get_entries($connection = null, $searchResultResource = null)
64
+ {
65
+ /** @noinspection PhpUndefinedMethodInspection */
66
+ return LdapFunctions::ldap_get_entries($connection, $searchResultResource);
67
+ }
68
+
69
+ function ldap_close($connection = null)
70
+ {
71
+ /** @noinspection PhpUndefinedMethodInspection */
72
+ return LdapFunctions::ldap_close($connection);
73
+ }
74
+
75
+ function ldap_count_entries($connection = null, $searchResultResource = null)
76
+ {
77
+ /** @noinspection PhpUndefinedMethodInspection */
78
+ return LdapFunctions::ldap_count_entries($connection, $searchResultResource);
79
+ }
80
+
81
+ if (!defined('LDAP_OPT_PROTOCOL_VERSION')) {
82
+ define('LDAP_OPT_PROTOCOL_VERSION', 1);
83
+ }
84
+ if (!defined('LDAP_OPT_REFERRALS')) {
85
+ define('LDAP_OPT_REFERRALS', 1);
86
+ }
87
+ if (!defined('LDAP_OPT_NETWORK_TIMEOUT')) {
88
+ define('LDAP_OPT_NETWORK_TIMEOUT', 1);
89
+ }
plugins/LoginLdap/tests/System/CheckDirectDependencyUseCommandTest.php ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ */
9
+
10
+ namespace Piwik\Plugins\LoginLdap\tests\System;
11
+
12
+ use Piwik\Plugins\TestRunner\Commands\CheckDirectDependencyUse;
13
+ use Piwik\Tests\Framework\TestCase\SystemTestCase;
14
+ use Piwik\Version;
15
+ use Symfony\Component\Console\Input\ArrayInput;
16
+ use Symfony\Component\Console\Output\NullOutput;
17
+
18
+ class CheckDirectDependencyUseCommandTest extends SystemTestCase
19
+ {
20
+ public function testCommand()
21
+ {
22
+ if (version_compare(Version::VERSION, '5.0.3', '<=') && !file_exists(PIWIK_INCLUDE_PATH . '/plugins/TestRunner/Commands/CheckDirectDependencyUse.php')) {
23
+ $this->markTestSkipped('tests:check-direct-dependency-use is not available in this version');
24
+ }
25
+ $pluginName = 'LoginLdap';
26
+ $console = new \Piwik\Console(self::$fixture->piwikEnvironment);
27
+ $checkDirectDependencyUse = new CheckDirectDependencyUse();
28
+ $console->addCommands([$checkDirectDependencyUse]);
29
+ $command = $console->find('tests:check-direct-dependency-use');
30
+ $arguments = array(
31
+ 'command' => 'tests:check-direct-dependency-use',
32
+ '--plugin' => $pluginName
33
+ );
34
+ $inputObject = new ArrayInput($arguments);
35
+ $command->run($inputObject, new NullOutput());
36
+
37
+ $this->assertEquals([
38
+ 'DI' => [
39
+ 'LoginLdap/tests/Integration/Commands/SynchronizeUsersTest.php'
40
+ ],
41
+ 'Symfony\Component\Console' => [
42
+ 'LoginLdap/tests/Integration/Commands/SynchronizeUsersTest.php',
43
+ 'LoginLdap/tests/System/CheckDirectDependencyUseCommandTest.php',
44
+ 'LoginLdap/tests/System/Output/TestOutput.php',
45
+ 'LoginLdap/tests/System/SynchronizeUsersCommandTest.php',
46
+ ]
47
+ ], $checkDirectDependencyUse->usesFoundList[$pluginName]);
48
+ }
49
+ }
plugins/LoginLdap/tests/System/Output/TestOutput.php ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ namespace Piwik\Plugins\LoginLdap\tests\System\Output;
4
+
5
+ use Symfony\Component\Console\Output\NullOutput;
6
+
7
+ class TestOutput extends NullOutput
8
+ {
9
+ public $output = [];
10
+
11
+ public function writeln($messages, int $options = self::OUTPUT_NORMAL)
12
+ {
13
+ $this->output[] = $messages;
14
+ }
15
+ }
plugins/LoginLdap/tests/System/SynchronizeUsersCommandTest.php ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ */
9
+
10
+ namespace Piwik\Plugins\LoginLdap\tests\System;
11
+
12
+ use Piwik\Plugins\LoginLdap\Commands\SynchronizeUsers;
13
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserMapper;
14
+ use Piwik\Plugins\LoginLdap\tests\System\Output\TestOutput;
15
+ use Piwik\Plugins\UsersManager\API as UsersManagerAPI;
16
+ use Piwik\Tests\Framework\TestCase\SystemTestCase;
17
+ use Symfony\Component\Console\Input\ArrayInput;
18
+
19
+ class SynchronizeUsersCommandTest extends SystemTestCase
20
+ {
21
+ public static function setUpBeforeClass(): void
22
+ {
23
+ parent::setUpBeforeClass(); // TODO: Change the autogenerated stub
24
+ $userMapper = UserMapper::makeConfigured();
25
+ $userManagerAPI = UsersManagerAPI::getInstance();
26
+ $userManagerAPI->addUser($user1 = 'user1', 'random12345', 'user1@starkindustries.com');
27
+ $userMapper->markUserAsLdapUser($user1);
28
+ $userManagerAPI->addUser($user2 = 'user2', 'random123456', 'user2@starkindustries.com');
29
+ $userMapper->markUserAsLdapUser($user2);
30
+ $userManagerAPI->addUser($user3 = 'user3', 'random123457', 'user3@starkindustries.com');
31
+ $userMapper->markUserAsLdapUser($user3);
32
+ }
33
+
34
+ public function test_sync_command_will_not_purge_old_users()
35
+ {
36
+ $console = new \Piwik\Console(self::$fixture->piwikEnvironment);
37
+ $synchronizeUsers = new SynchronizeUsers();
38
+ $console->addCommands([$synchronizeUsers]);
39
+ $command = $console->find('loginldap:synchronize-users');
40
+ $arguments = array(
41
+ 'command' => 'loginldap:synchronize-users',
42
+ '--login' => ['user1','user2']
43
+ );
44
+ $inputObject = new ArrayInput($arguments);
45
+ $output = new TestOutput();
46
+ $command->run($inputObject, $output);
47
+ $outputAsString = json_encode($output->output);
48
+ $this->assertStringNotContainsString('Purging user', $outputAsString);
49
+
50
+ $this->runApiTests(['LoginLdap.getExistingLdapUsersFromDb'], ['testSuffix' => '_no_purge']);
51
+ }
52
+
53
+ public function test_sync_command_will_purge_old_users()
54
+ {
55
+ $console = new \Piwik\Console(self::$fixture->piwikEnvironment);
56
+ $synchronizeUsers = new SynchronizeUsers();
57
+ $console->addCommands([$synchronizeUsers]);
58
+ $command = $console->find('loginldap:synchronize-users');
59
+ $arguments = array(
60
+ 'command' => 'loginldap:synchronize-users',
61
+ '--login' => ['user1','user2'],
62
+ '--purge-non-existent-users' => null
63
+ );
64
+ $inputObject = new ArrayInput($arguments);
65
+ $output = new TestOutput();
66
+ $command->run($inputObject, $output);
67
+ $outputAsString = json_encode($output->output);
68
+ $this->assertStringContainsString('Purging user user3', $outputAsString);
69
+
70
+ $this->runApiTests(['LoginLdap.getExistingLdapUsersFromDb'], ['testSuffix' => '_purge']);
71
+ }
72
+
73
+ public static function getPathToTestDirectory()
74
+ {
75
+ return dirname(__FILE__);
76
+ }
77
+ }
plugins/LoginLdap/tests/System/SystemAuthTest.php ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ */
9
+
10
+ namespace Piwik\Plugins\LoginLdap\tests\System;
11
+
12
+ use Piwik\Auth;
13
+ use Piwik\AuthResult;
14
+ use Piwik\Common;
15
+ use Piwik\Config;
16
+ use Piwik\Container\StaticContainer;
17
+ use Piwik\Date;
18
+ use Piwik\Db;
19
+ use Piwik\Plugins\LoginLdap\LoginLdap;
20
+ use Piwik\Plugins\LoginLdap\Auth\LdapAuth;
21
+ use Piwik\Plugins\LoginLdap\Auth\SynchronizedAuth;
22
+ use Piwik\Plugins\LoginLdap\Auth\WebServerAuth;
23
+ use Piwik\Plugins\LoginLdap\tests\Integration\LdapIntegrationTest;
24
+ use Piwik\Plugins\UsersManager\API;
25
+ use Piwik\Tests\Framework\Fixture;
26
+ use Piwik\Tests\Framework\TestingEnvironmentVariables;
27
+
28
+ /**
29
+ * @group LoginLdap
30
+ * @group LoginLdap_System
31
+ * @group LoginLdap_SystemAuthTest
32
+ */
33
+ class SystemAuthTest extends LdapIntegrationTest
34
+ {
35
+ private $superUserTokenAuth;
36
+
37
+ public function getAuthModesToTest()
38
+ {
39
+ return array(
40
+ array('ldap_only'),
41
+ array('synchronized'),
42
+ array('web_server'),
43
+ );
44
+ }
45
+
46
+ public function setUp(): void
47
+ {
48
+ parent::setUp();
49
+
50
+ $this->addPreexistingSuperUser();
51
+ $this->superUserTokenAuth = API::getInstance()->createAppSpecificTokenAuth(
52
+ self::TEST_SUPERUSER_LOGIN,
53
+ self::TEST_SUPERUSER_PASS,
54
+ 'test'
55
+ );
56
+ }
57
+
58
+ public function tearDown(): void
59
+ {
60
+ parent::tearDown();
61
+
62
+ unset($_SERVER['REMOTE_USER']);
63
+ }
64
+
65
+ /**
66
+ * @dataProvider getAuthModesToTest
67
+ */
68
+ public function test_LdapAuthentication_WorksForNormalTrackingRequest($authStrategy)
69
+ {
70
+ $this->setUpLdap($authStrategy);
71
+
72
+ $superUserTokenAuth = $this->getSuperUserTokenAuth();
73
+
74
+ $date = Date::factory('2015-01-01 00:00:00');
75
+
76
+ $tracker = Fixture::getTracker($idSite = 1, $date->addHour(1)->getDatetime());
77
+ $tracker->setTokenAuth($superUserTokenAuth);
78
+
79
+ $tracker->setUrl('http://shield.org/protocol/theta');
80
+ Fixture::checkResponse($tracker->doTrackPageView('I Am A Robot Tourist'));
81
+
82
+ // authentication is required to track dates in the past, so to verify we
83
+ // authenticated, we check the tracked visit times
84
+ $expectedDateTimes = array('2015-01-01 01:00:00');
85
+ $actualDateTimes = $this->getVisitDateTimes();
86
+
87
+ $this->assertEquals($expectedDateTimes, $actualDateTimes);
88
+ }
89
+
90
+ /**
91
+ * @dataProvider getAuthModesToTest
92
+ */
93
+ public function test_LdapAuthentication_WorksDuringBulkTracking($authStrategy)
94
+ {
95
+ $this->setUpLdap($authStrategy);
96
+
97
+ $superUserTokenAuth = $this->getSuperUserTokenAuth();
98
+
99
+ $date = Date::factory('2015-01-01 00:00:00');
100
+
101
+ $tracker = Fixture::getTracker($idSite = 1, $date->getDatetime());
102
+ $tracker->setTokenAuth($superUserTokenAuth);
103
+ $tracker->enableBulkTracking();
104
+
105
+ $tracker->setForceVisitDateTime($date->getDatetime());
106
+ $tracker->setUrl('http://shield.org/level/10/dandr/pcoulson');
107
+ $tracker->doTrackPageView('Death & Recovery');
108
+
109
+ $tracker->setForceVisitDateTime($date->addHour(1)->getDatetime());
110
+ $tracker->setUrl('http://shield.org/logout');
111
+ $tracker->doTrackPageView('Going dark');
112
+
113
+ Fixture::checkBulkTrackingResponse($tracker->doBulkTrack());
114
+
115
+ // authentication is required to track dates in the past, so to verify we
116
+ // authenticated, we check the tracked visit times
117
+ $expectedDateTimes = array('2015-01-01 00:00:00', '2015-01-01 01:00:00');
118
+ $actualDateTimes = $this->getVisitDateTimes();
119
+
120
+ $this->assertEquals($expectedDateTimes, $actualDateTimes);
121
+ }
122
+
123
+ private function getVisitDateTimes()
124
+ {
125
+ $rows = Db::fetchAll("SELECT visit_last_action_time FROM " . Common::prefixTable('log_visit')
126
+ . " ORDER BY visit_last_action_time ASC");
127
+
128
+ $dates = array();
129
+ foreach ($rows as $row) {
130
+ $dates[] = $row['visit_last_action_time'];
131
+ }
132
+ return $dates;
133
+ }
134
+
135
+ private function setUpLdap($authStrategy)
136
+ {
137
+ $testVars = new TestingEnvironmentVariables();
138
+ $configOverride = $testVars->configOverride;
139
+
140
+ if ($authStrategy == 'ldap_only') {
141
+ Config::getInstance()->LoginLdap['use_ldap_for_authentication'] = 1;
142
+ $configOverride['LoginLdap']['use_ldap_for_authentication'] = 1;
143
+ } elseif ($authStrategy == 'synchronized') {
144
+ Config::getInstance()->LoginLdap['use_ldap_for_authentication'] = 0;
145
+ $configOverride['LoginLdap']['use_ldap_for_authentication'] = 0;
146
+ } elseif ($authStrategy == 'web_server') {
147
+ Config::getInstance()->LoginLdap['use_webserver_auth'] = 1;
148
+ $configOverride['LoginLdap']['use_webserver_auth'] = 1;
149
+ } else {
150
+ throw new \Exception("Unknown LDAP auth strategy $authStrategy.");
151
+ }
152
+
153
+ $configOverride['Tracker']['debug_on_demand'] = 1;
154
+
155
+ $testVars->configOverride = $configOverride;
156
+ $testVars->save();
157
+
158
+ // make sure our superuser is synchronized before hand
159
+ $this->authenticateUserOnce($authStrategy);
160
+ }
161
+
162
+ private function getSuperUserTokenAuth()
163
+ {
164
+ return $this->superUserTokenAuth;
165
+ }
166
+
167
+ private function authenticateUserOnce($authStrategy)
168
+ {
169
+ $auth = null;
170
+ if ($authStrategy == 'ldap_only') {
171
+ $auth = LdapAuth::makeConfigured();
172
+ } elseif ($authStrategy == 'synchronized') {
173
+ $auth = SynchronizedAuth::makeConfigured();
174
+ } elseif ($authStrategy == 'web_server') {
175
+ $auth = WebServerAuth::makeConfigured();
176
+
177
+ $_SERVER['REMOTE_USER'] = self::TEST_SUPERUSER_LOGIN;
178
+ } else {
179
+ throw new \Exception("Unknown LDAP auth strategy $authStrategy.");
180
+ }
181
+
182
+ StaticContainer::getContainer()->set(Auth::class, $auth);
183
+
184
+ $auth->setLogin(self::TEST_SUPERUSER_LOGIN);
185
+ $auth->setPassword(self::TEST_SUPERUSER_PASS);
186
+ $result = $auth->authenticate();
187
+
188
+ $this->assertNotEquals(AuthResult::FAILURE, $result->getCode());
189
+
190
+ $this->setSuperUserAccess(self::TEST_SUPERUSER_LOGIN, true);
191
+ }
192
+
193
+ public function testLdapUserPassChange()
194
+ {
195
+ $this->expectException(\Exception::class);
196
+ $this->expectExceptionMessage('Changing your password is not supported for LDAP users');
197
+
198
+ $auth = LdapAuth::makeConfigured();
199
+ $auth->setLogin(self::TEST_LOGIN);
200
+ $auth->setPassword(self::TEST_PASS);
201
+ $result = $auth->authenticate();
202
+
203
+ $this->assertNotEquals(AuthResult::FAILURE, $result->getCode());
204
+
205
+ $loginLdap = new LoginLdap();
206
+ $loginLdap->disablePasswordChangeForLdapUsers($auth);
207
+ }
208
+ }
plugins/LoginLdap/tests/System/expected/test_SynchronizeUsersCommandTest_no_purge__LoginLdap.getExistingLdapUsersFromDb.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="utf-8" ?>
2
+ <result>
3
+ <row>user1</row>
4
+ <row>user2</row>
5
+ <row>user3</row>
6
+ </result>
plugins/LoginLdap/tests/System/expected/test_SynchronizeUsersCommandTest_purge__LoginLdap.getExistingLdapUsersFromDb.xml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="utf-8" ?>
2
+ <result>
3
+ <row>user1</row>
4
+ <row>user2</row>
5
+ </result>
plugins/LoginLdap/tests/UI/Admin_spec.js ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*!
2
+ * Matomo - free/libre analytics platform
3
+ *
4
+ * LoginLdap admin page screenshot tests.
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ */
9
+
10
+ describe("LoginLdap_Admin", function () {
11
+ this.timeout(0);
12
+
13
+ this.fixture = "Piwik\\Tests\\Fixtures\\OneVisitorTwoVisits";
14
+
15
+ before(function () {
16
+ testEnvironment.pluginsToLoad = ['LoginLdap'];
17
+ testEnvironment.configOverride = {
18
+ LoginLdap: {
19
+ servers: ['testserver'],
20
+ new_user_default_sites_view_access: '1,2',
21
+ enable_synchronize_access_from_ldap: 1
22
+ },
23
+ LoginLdap_testserver: {
24
+ hostname: 'localhost',
25
+ port: 389,
26
+ base_dn: 'dc=avengers,dc=shield,dc=org',
27
+ admin_user: 'cn=fury,dc=avengers,dc=shield,dc=org',
28
+ admin_pass: 'secrets',
29
+ start_tls: false
30
+ }
31
+ };
32
+ testEnvironment.save();
33
+ });
34
+
35
+ var ldapAdminUrl = "?module=LoginLdap&action=admin&idSite=1&period=day&date=yesterday";
36
+ var addNewTokenUrl = "?module=UsersManager&action=addNewToken&idSite=1&period=day&date=yesterday";
37
+
38
+ it("should load correctly and allow testing the filter and group fields", async function () {
39
+ await page.goto(ldapAdminUrl);
40
+ await page.waitForFunction("$('input[name=required_member_of]').length > 0");
41
+
42
+ await page.evaluate(function () {
43
+ $('input#required_member_of').val('cn=avengers,dc=avengers,dc=shield,dc=org').trigger('change');
44
+ $('input#ldap_user_filter').val('(objectClass=person)').trigger('change');
45
+ });
46
+
47
+ await page.evaluate(function () {
48
+ $('.loginLdapTestableField .matomo-save-button input').click();
49
+ });
50
+
51
+ await page.waitForNetworkIdle();
52
+
53
+ var elem = await page.jQuery('#content');
54
+ expect(await elem.screenshot()).to.matchImage('admin_page');
55
+ });
56
+
57
+ it("should show the password confirmation screen when add new token screen is called", async function () {
58
+ testEnvironment.configOverride.LoginLdap = { enable_password_confirmation: 1 };
59
+ testEnvironment.save();
60
+ await page.goto(addNewTokenUrl);
61
+ await page.waitForNetworkIdle();
62
+ var elem = await page.jQuery('#loginPage');
63
+
64
+ // Assert that the button starts off disabled.
65
+ await page.waitForSelector('#login_form_submit[disabled]');
66
+
67
+ // Button enabled with password entered.
68
+ await page.type('#login_form_password', 'p');
69
+ await page.waitForSelector('#login_form_submit:not([disabled])');
70
+
71
+ expect(await elem.screenshot()).to.matchImage('addNewToken_with_password');
72
+ });
73
+
74
+ it("should still show the password confirmation screen for non-LDAP users when password confirmation is disabled", async function () {
75
+ testEnvironment.configOverride.LoginLdap = { enable_password_confirmation: 0 };
76
+ testEnvironment.save();
77
+ await page.goto(addNewTokenUrl);
78
+ await page.waitForNetworkIdle();
79
+ var elem = await page.jQuery('#loginPage');
80
+ await page.waitForSelector('#login_form_submit[disabled]');
81
+ expect(await elem.screenshot()).to.matchImage('addNewToken_with_password_non_ldap_user');
82
+ });
83
+
84
+ it("should require password confirmation when saving LDAP settings from the admin page", async function () {
85
+ testEnvironment.configOverride.LoginLdap = {
86
+ servers: ['testserver'],
87
+ new_user_default_sites_view_access: '1,2',
88
+ enable_synchronize_access_from_ldap: 1,
89
+ enable_password_confirmation: 1,
90
+ };
91
+ testEnvironment.save();
92
+
93
+ await page.goto(ldapAdminUrl);
94
+ await page.waitForFunction("$('input[name=required_member_of]').length > 0");
95
+
96
+ await page.evaluate(function () {
97
+ // Exclude the TestableField save buttons (filter/group "test" buttons) so we click the
98
+ // actual "Save LDAP config" button, which is what triggers the password confirmation.
99
+ $('.matomo-save-button input')
100
+ .not('.loginLdapTestableField .matomo-save-button input')
101
+ .eq(0)
102
+ .click();
103
+ });
104
+
105
+ await page.waitForSelector('.confirm-password-modal.modal.open', { visible: true });
106
+ });
107
+
108
+ it("should require password confirmation when saving LDAP servers from the admin page", async function () {
109
+ testEnvironment.configOverride.LoginLdap = {
110
+ servers: ['testserver'],
111
+ new_user_default_sites_view_access: '1,2',
112
+ enable_synchronize_access_from_ldap: 1,
113
+ enable_password_confirmation: 1,
114
+ };
115
+ testEnvironment.save();
116
+
117
+ await page.goto(ldapAdminUrl);
118
+ await page.waitForFunction("$('input[name=required_member_of]').length > 0");
119
+
120
+ await page.evaluate(function () {
121
+ $('.matomo-save-button input').last().click();
122
+ });
123
+
124
+ await page.waitForSelector('.confirm-password-modal.modal.open', { visible: true });
125
+ });
126
+ });
plugins/LoginLdap/tests/UI/expected-ui-screenshots/LoginLdap_Admin_addNewToken_with_password.png ADDED
plugins/LoginLdap/tests/UI/expected-ui-screenshots/LoginLdap_Admin_addNewToken_with_password_non_ldap_user.png ADDED
plugins/LoginLdap/tests/UI/expected-ui-screenshots/LoginLdap_Admin_addNewToken_without_password.png ADDED
plugins/LoginLdap/tests/UI/expected-ui-screenshots/LoginLdap_Admin_admin_page.png ADDED
plugins/LoginLdap/tests/Unit/LdapClientTest.php ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Unit;
12
+
13
+ use Piwik\ErrorHandler;
14
+ use Piwik\Plugins\LoginLdap\Ldap\Client as LdapClient;
15
+ use Piwik\Plugins\LoginLdap\Ldap\LdapFunctions;
16
+ use PHPUnit\Framework\TestCase;
17
+
18
+ require_once PIWIK_INCLUDE_PATH . '/plugins/LoginLdap/tests/Mocks/LdapFunctions.php';
19
+
20
+ /**
21
+ * @group LoginLdap
22
+ * @group LoginLdap_Unit
23
+ * @group LoginLdap_LdapClientTest
24
+ */
25
+ class LdapClientTest extends TestCase
26
+ {
27
+ public const ERROR_MESSAGE = "triggered error";
28
+
29
+ public function setUp(): void
30
+ {
31
+ parent::setUp();
32
+
33
+ LdapFunctions::$phpUnitMock = $this->getMockBuilder('stdClass')
34
+ ->addMethods(array('ldap_connect', 'ldap_close',
35
+ 'ldap_bind', 'ldap_search', 'ldap_set_option',
36
+ 'ldap_get_entries', 'ldap_count_entries', 'ldap_error'))
37
+ ->getMock();
38
+ }
39
+
40
+ public function tearDown(): void
41
+ {
42
+ restore_error_handler();
43
+
44
+ LdapFunctions::$phpUnitMock = null;
45
+
46
+ parent::tearDown();
47
+ }
48
+
49
+ public function test_construction_WithNoArguments_DoesNotConnect()
50
+ {
51
+ $ldapClient = new LdapClient();
52
+
53
+ $this->assertFalse($ldapClient->isOpen());
54
+ }
55
+
56
+ public function test_construction_WithHostnameAndPort_AttemptsToConnect()
57
+ {
58
+ $this->addLdapConnectMethodMock("hostname", 1234);
59
+
60
+ $ldapClient = new LdapClient("hostname", 1234);
61
+
62
+ $this->assertTrue($ldapClient->isOpen());
63
+ }
64
+
65
+ public function test_connect_Closes_IfConnectionCurrentlyOpen()
66
+ {
67
+ $this->addLdapConnectMethodMock();
68
+
69
+ LdapFunctions::$phpUnitMock->expects($this->exactly(1))->method('ldap_close')
70
+ ->withConsecutive(
71
+ array($this->equalTo("connection_resource_hostname_1234")),
72
+ array($this->equalTo("connection_resource_hostname2_4567"))
73
+ );
74
+
75
+ $ldapClient = new LdapClient("hostname", 1234);
76
+ $this->assertTrue($ldapClient->isOpen());
77
+
78
+ $ldapClient->connect("hostname2", 4567);
79
+ $this->assertTrue($ldapClient->isOpen());
80
+ }
81
+
82
+ public function test_connect_ThrowsPhpErrors()
83
+ {
84
+ $this->expectException(\Piwik\Exception\ErrorException::class);
85
+ $this->expectExceptionMessage('triggered error');
86
+
87
+ $this->setPiwikErrorHandling();
88
+
89
+ $this->addLdapMethodThatTriggersPhpError('ldap_connect');
90
+
91
+ $ldapClient = new LdapClient();
92
+ $ldapClient->connect("hostname", 1234);
93
+ }
94
+
95
+ public function test_close_Succeeds_IfConnectionAlreadyClosed()
96
+ {
97
+ $ldapClient = new LdapClient();
98
+ $ldapClient->close();
99
+
100
+ self::assertTrue(true);
101
+ }
102
+
103
+ public function test_close_ThrowsPhpErrors()
104
+ {
105
+ $this->expectException(\Piwik\Exception\ErrorException::class);
106
+ $this->expectExceptionMessage('triggered error');
107
+
108
+ $this->setPiwikErrorHandling();
109
+
110
+ $this->addLdapConnectMethodMock();
111
+ $this->addLdapMethodThatTriggersPhpError('ldap_close');
112
+
113
+ $ldapClient = new LdapClient("hostname", 1234);
114
+ $ldapClient->close();
115
+ }
116
+
117
+ public function test_bind_ForwardsLdapBindResult()
118
+ {
119
+ LdapFunctions::$phpUnitMock->expects($this->once())->method('ldap_bind')->will($this->returnValue("ldap_bind result"));
120
+
121
+ $ldapClient = new LdapClient();
122
+ $result = $ldapClient->bind("resource", "password");
123
+ $this->assertEquals("ldap_bind result", $result);
124
+ }
125
+
126
+ public function test_bind_ThrowsPhpErrors()
127
+ {
128
+ $this->expectException(\Piwik\Exception\ErrorException::class);
129
+ $this->expectExceptionMessage('triggered error');
130
+
131
+ $this->setPiwikErrorHandling();
132
+
133
+ $this->addLdapMethodThatTriggersPhpError('ldap_bind');
134
+
135
+ $ldapClient = new LdapClient();
136
+ $ldapClient->bind("resource", "password");
137
+ }
138
+
139
+ public function test_fetchAll_ThrowsPhpErrors()
140
+ {
141
+ $this->expectException(\Piwik\Exception\ErrorException::class);
142
+ $this->expectExceptionMessage('triggered error');
143
+
144
+ $this->setPiwikErrorHandling();
145
+
146
+ $this->addLdapMethodThatTriggersPhpError('ldap_search');
147
+ $this->addLdapMethodThatTriggersPhpError('ldap_get_entries');
148
+
149
+ $ldapClient = new LdapClient();
150
+ $ldapClient->fetchAll("base dn", "filter");
151
+ }
152
+
153
+ public function test_fetchAll_ReturnsNull_IfLdapSearchFailsSilently()
154
+ {
155
+ LdapFunctions::$phpUnitMock->expects($this->any())->method('ldap_search')->will($this->returnValue(null));
156
+
157
+ $ldapClient = new LdapClient();
158
+ $result = $ldapClient->fetchAll("base dn", "filter");
159
+
160
+ $this->assertNull($result);
161
+ }
162
+
163
+ public function test_fetchAll_CorrectlyEscapesFilterParameters()
164
+ {
165
+ $escapedFilter = null;
166
+
167
+ LdapFunctions::$phpUnitMock->expects($this->any())->method('ldap_search')->will($this->returnCallback(
168
+ function ($conn, $dn, $filter) use (&$escapedFilter) {
169
+ $escapedFilter = $filter;
170
+ }
171
+ ));
172
+ LdapFunctions::$phpUnitMock->expects($this->any())->method('ldap_get_entries')->will($this->returnValue("result"));
173
+
174
+ $ldapClient = new LdapClient();
175
+
176
+ $ldapClient->fetchAll("base dn", "(uid=name?)");
177
+ $this->assertEquals("(uid=name?)", $escapedFilter);
178
+
179
+ $ldapClient->fetchAll("base dn", "(uid=?)", array("na(m)e?'!"));
180
+ $this->assertEquals('(uid=na\\28m\\29e?\'!)', $escapedFilter);
181
+
182
+ $ldapClient->fetchAll("base dn", "(&(uid=?,?)(whatev=?))", array("on()e", "tw?", "(thre"));
183
+ $this->assertEquals("(&(uid=on\\28\\29e,tw?)(whatev=\\28thre))", $escapedFilter);
184
+
185
+ $ldapClient->fetchAll("base dn", "(&(uid=?,?)(whatev=?))", array("t*w()o", "t\\hr??e"));
186
+ $this->assertEquals("(&(uid=t\\2aw\\28\\29o,t\\5chr??e)(whatev=?))", $escapedFilter);
187
+ }
188
+
189
+ public function getLdapTransformTestData()
190
+ {
191
+ return array(
192
+ array(
193
+ array('count' => 0),
194
+ array()
195
+ ),
196
+ // test pair
197
+ array(
198
+ array(
199
+ 'count' => 1,
200
+ 0 => array(
201
+ 'count' => 2,
202
+ 'cn' => array('count' => 1, '0' => 'value'),
203
+ 'dn' => 'the dn',
204
+ 0 => 'cn',
205
+ 1 => 'dn'
206
+ )
207
+ ),
208
+ array(
209
+ array('cn' => 'value', 'dn' => 'the dn')
210
+ )
211
+ ),
212
+ // test pair
213
+ array(
214
+ array(
215
+ 'count' => 2,
216
+ 0 => array(
217
+ 'count' => 2,
218
+ 0 => 'cn',
219
+ 1 => 'objectClass',
220
+ 'cn' => array('count' => 1, '0' => 'value2'),
221
+ 'objectClass' => array('count' => '1', '0' => 'top'),
222
+ 'dn' => 'the dn'
223
+ ),
224
+ 1 => array(
225
+ 'count' => 2,
226
+ 'cn' => array('count' => 2, '0' => 'value3'),
227
+ 0 => 'objectclass',
228
+ 'objectclass' => array('count' => '2', '0' => 'top', '1' => 'inetOrgPersion'),
229
+ 1 => 'cn'
230
+ )
231
+ ),
232
+ array(
233
+ array('cn' => 'value2', 'objectclass' => 'top', 'dn' => 'the dn'),
234
+ array('objectclass' => array('top', 'inetOrgPersion'), 'cn' => 'value3'),
235
+ )
236
+ ),
237
+ // test pair
238
+ array(
239
+ array(
240
+ 'count' => 1,
241
+ 0 => array(
242
+ 'count' => 1,
243
+ 'superuser' => array(
244
+ 'count' => 2,
245
+ 0 => '1',
246
+ 1 => 'anotherpiwik'
247
+ ),
248
+ 0 => 'superuser'
249
+ )
250
+ ),
251
+ array(
252
+ array('superuser' => array('1', 'anotherpiwik'))
253
+ )
254
+ )
255
+ );
256
+ }
257
+
258
+ /**
259
+ * @dataProvider getLdapTransformTestData
260
+ */
261
+ public function test_fetchAll_CorrectlyProcessesLdapSearchResults($ldapData, $expectedData)
262
+ {
263
+ LdapFunctions::$phpUnitMock->expects($this->any())->method('ldap_search')->will($this->returnValue("resource"));
264
+ LdapFunctions::$phpUnitMock->expects($this->any())->method('ldap_get_entries')->will($this->returnValue($ldapData));
265
+
266
+ $ldapClient = new LdapClient();
267
+ $result = $ldapClient->fetchAll("base dn", "filter");
268
+ $this->assertEquals($expectedData, $result);
269
+ }
270
+
271
+ public function test_count_ThrowsPhpErrors()
272
+ {
273
+ $this->expectException(\Piwik\Exception\ErrorException::class);
274
+ $this->expectExceptionMessage('triggered error');
275
+
276
+ $this->setPiwikErrorHandling();
277
+
278
+ LdapFunctions::$phpUnitMock->expects($this->any())->method('ldap_search')->will($this->returnValue("resource"));
279
+ $this->addLdapMethodThatTriggersPhpError('ldap_count_entries');
280
+
281
+ $ldapClient = new LdapClient();
282
+ $ldapClient->count("base dn", "filter");
283
+ }
284
+
285
+ public function test_count_Throws_IfLdapSearchReturnsNull()
286
+ {
287
+ $this->expectException(\Exception::class);
288
+
289
+ $this->setPiwikErrorHandling();
290
+
291
+ LdapFunctions::$phpUnitMock->expects($this->any())->method('ldap_search')->will($this->returnValue(null));
292
+
293
+ $ldapClient = new LdapClient();
294
+ $ldapClient->count("base dn", "filter");
295
+ }
296
+
297
+ public function test_count_ReturnsCorrectValue()
298
+ {
299
+ LdapFunctions::$phpUnitMock->expects($this->any())->method('ldap_search')->will($this->returnValue("resource"));
300
+ LdapFunctions::$phpUnitMock->expects($this->any())->method('ldap_count_entries')->will($this->returnValue(8));
301
+
302
+ $ldapClient = new LdapClient();
303
+ $result = $ldapClient->count("base dn", "filter");
304
+ $this->assertEquals(8, $result);
305
+ }
306
+
307
+ private function addLdapConnectMethodMock($hostname = null, $port = null)
308
+ {
309
+ if (version_compare(PHP_VERSION, 8.3, '>=')) {
310
+ $getConnectionResource = function ($hostname) {
311
+ $name = str_replace(array('ldap://', ':'), array('','_'), $hostname);
312
+ return "connection_resource_$name";
313
+ };
314
+
315
+ $method = LdapFunctions::$phpUnitMock->expects($this->any())->method('ldap_connect');
316
+ if (!empty($hostname)) {
317
+ $method = $method->with($this->equalTo('ldap://' . $hostname . ':' . $port));
318
+ }
319
+ } else {
320
+ $getConnectionResource = function ($hostname, $port) {
321
+ return "connection_resource_$hostname" . '_' . $port;
322
+ };
323
+ $method = LdapFunctions::$phpUnitMock->expects($this->any())->method('ldap_connect');
324
+ if (!empty($hostname) || !empty($port)) {
325
+ $method = $method->with($this->equalTo($hostname), $this->equalTo($port));
326
+ }
327
+ }
328
+
329
+ $method->will($this->returnCallback($getConnectionResource));
330
+
331
+ LdapFunctions::$phpUnitMock->expects($this->any())->method('ldap_set_option')->will($this->returnValue(null));
332
+ }
333
+
334
+ private function addLdapMethodThatTriggersPhpError($methodName, $returnValue = null)
335
+ {
336
+ LdapFunctions::$phpUnitMock->expects($this->any())->method($methodName)->will($this->returnCallback(function () use ($returnValue) {
337
+ trigger_error(LdapClientTest::ERROR_MESSAGE, E_USER_ERROR);
338
+ return $returnValue;
339
+ }));
340
+ }
341
+
342
+ private function setPiwikErrorHandling()
343
+ {
344
+ ErrorHandler::registerErrorHandler();
345
+ error_reporting(E_ALL);
346
+ }
347
+ }
plugins/LoginLdap/tests/Unit/LdapUsersTest.php ADDED
@@ -0,0 +1,515 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Unit;
12
+
13
+ use Exception;
14
+ use InvalidArgumentException;
15
+ use Piwik\Plugins\LoginLdap\Ldap\ServerInfo;
16
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserMapper;
17
+ use Piwik\Plugins\LoginLdap\Model\LdapUsers;
18
+ use PHPUnit\Framework\TestCase;
19
+
20
+ /**
21
+ * @group LoginLdap
22
+ * @group LoginLdap_Unit
23
+ * @group LoginLdap_LdapUsersTest
24
+ */
25
+ class LdapUsersTest extends TestCase
26
+ {
27
+ public const TEST_USER = "rose";
28
+ public const PASSWORD = "bw";
29
+ public const TEST_ADMIN_USER = "who?";
30
+ public const TEST_BASE_DN = 'testbasedn';
31
+ public const TEST_EXTRA_FILTER = '(testfilter)';
32
+ public const TEST_MEMBER_OF = "member";
33
+ public const TEST_MEMBER_OF_FIELD = "memberOf";
34
+
35
+ /**
36
+ * @var LdapUsers
37
+ */
38
+ private $ldapUsers = null;
39
+
40
+ public function setUp(): void
41
+ {
42
+ parent::setUp();
43
+
44
+ $this->ldapUsers = new LdapUsers();
45
+ $this->ldapUsers->setLdapServers(array(new ServerInfo("localhost", "basedn")));
46
+ $this->ldapUsers->setLdapUserMapper(new UserMapper());
47
+ }
48
+
49
+ public function test_authenticate_ThrowsException_IfUsernameEmpty()
50
+ {
51
+ $this->expectException(InvalidArgumentException::class);
52
+
53
+ $this->ldapUsers->authenticate(null, self::PASSWORD);
54
+ $this->ldapUsers->authenticate("", self::PASSWORD);
55
+ }
56
+
57
+ public function test_authenticate_ReturnsNull_WhenPasswordIsEmpty()
58
+ {
59
+ $result = $this->ldapUsers->authenticate(self::TEST_USER, null);
60
+ $this->assertNull($result);
61
+
62
+ $result = $this->ldapUsers->authenticate(self::TEST_USER, "");
63
+ $this->assertNull($result);
64
+ }
65
+
66
+ public function test_authenticate_CreatesOneClient_WhenNoExistingClientSupplied()
67
+ {
68
+ $mockLdapClient = $this->makeMockLdapClient($forSuccess = true);
69
+ $mockLdapClient->expects($this->once())->method('connect');
70
+
71
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
72
+ $this->ldapUsers->authenticate(self::TEST_USER, self::PASSWORD);
73
+ }
74
+
75
+ public function test_authenticate_Fails_WhenUserDoesNotExist()
76
+ {
77
+ $mockLdapClient = $this->makeMockLdapClient();
78
+ $mockLdapClient->expects($this->any())->method('bind')->will($this->returnValue(true));
79
+ $mockLdapClient->expects($this->any())->method('fetchAll')->will($this->returnValue(array()));
80
+
81
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
82
+ $result = $this->ldapUsers->authenticate(self::TEST_USER, self::PASSWORD);
83
+
84
+ $this->assertNull($result);
85
+ }
86
+
87
+ public function test_authenticate_Fails_WhenUserDoesNotExist_AndWebServerAuthUsed()
88
+ {
89
+ $mockLdapClient = $this->makeMockLdapClient();
90
+ $mockLdapClient->expects($this->any())->method('bind')->will($this->returnValue(true));
91
+ $mockLdapClient->expects($this->any())->method('fetchAll')->will($this->returnValue(array()));
92
+
93
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
94
+ $result = $this->ldapUsers->authenticate(self::TEST_USER, self::PASSWORD, $alreadyAuthenticated = true);
95
+
96
+ $this->assertNull($result);
97
+ }
98
+
99
+ public function test_authenticate_SucceedsWithoutLdapBind_WhenWebServerAuthUsed_AndUserExists()
100
+ {
101
+ $mockLdapClient = $this->makeMockLdapClient();
102
+ $mockLdapClient->expects($this->any())->method('bind')->will($this->returnCallback(function () {
103
+ static $i = 0;
104
+
105
+ ++$i;
106
+
107
+ if ($i == 1) {
108
+ return true;
109
+ } else {
110
+ return false; // fail binding after first calls
111
+ }
112
+ }));
113
+ $mockLdapClient->expects($this->any())->method('fetchAll')->will($this->returnValue(array(array('uid' => self::TEST_USER))));
114
+
115
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
116
+ $result = $this->ldapUsers->authenticate(self::TEST_USER, self::PASSWORD, $alreadyAuthenticated = true);
117
+
118
+ $this->assertNotNull($result);
119
+ }
120
+
121
+ public function test_authenticate_Succeeds_WhenLdapBindSucceedsAndUserExists()
122
+ {
123
+ $mockLdapClient = $this->makeMockLdapClient($forSuccess = true);
124
+
125
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
126
+ $result = $this->ldapUsers->authenticate(self::TEST_USER, self::PASSWORD, $alreadyAuthenticated = false);
127
+
128
+ $this->assertNotNull($result);
129
+ }
130
+
131
+ public function test_authenticate_Fails_WhenLdapBindFails()
132
+ {
133
+ $mockLdapClient = $this->makeMockLdapClient();
134
+ $mockLdapClient->expects($this->any())->method('bind')->will($this->returnCallback(function () {
135
+ static $i = 0;
136
+
137
+ ++$i;
138
+
139
+ if ($i == 1) {
140
+ return true;
141
+ } else {
142
+ return false; // fail binding after first calls
143
+ }
144
+ }));
145
+ $mockLdapClient->expects($this->any())->method('fetchAll')->will($this->returnValue(array(array('uid' => self::TEST_USER, 'dn' => 'thedn'))));
146
+
147
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
148
+ $result = $this->ldapUsers->authenticate(self::TEST_USER, self::PASSWORD, $alreadyAuthenticated = false);
149
+
150
+ $this->assertNull($result);
151
+ }
152
+
153
+ public function test_authenticate_Fails_WhenLdapUserInfoDoesNotHaveDn()
154
+ {
155
+ $mockLdapClient = $this->makeMockLdapClient();
156
+ $mockLdapClient->expects($this->any())->method('bind')->will($this->returnValue(true));
157
+ $mockLdapClient->expects($this->any())->method('fetchAll')->will($this->returnValue(array(array('uid' => self::TEST_USER))));
158
+
159
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
160
+ $result = $this->ldapUsers->authenticate(self::TEST_USER, self::PASSWORD, $alreadyAuthenticated = false);
161
+
162
+ $this->assertNull($result);
163
+ }
164
+
165
+ public function test_authenticate_DoesNotPropagateErrors_WhenErrorsThrownByLdapClient()
166
+ {
167
+ $mockLdapClient = $this->makeMockLdapClient();
168
+ $mockLdapClient->expects($this->any())->method('bind')->will($this->returnCallback(function () {
169
+ throw new \Exception("dummy error");
170
+ }));
171
+
172
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
173
+ $result = $this->ldapUsers->authenticate(self::TEST_USER, self::PASSWORD, $alreadyAuthenticated = false);
174
+
175
+ $this->assertNull($result);
176
+ }
177
+
178
+ public function test_authenticate_AddsUsernameSuffix_IfOneIsConfigured()
179
+ {
180
+ $adminUserName = null;
181
+ $userName = null;
182
+ $filterUsed = null;
183
+ $filterBind = null;
184
+
185
+ $mockLdapClient = $this->makeMockLdapClient();
186
+ $mockLdapClient->expects($this->any())->method('bind')->will($this->returnCallback(function ($bindResource) use (&$adminUserName, &$userName) {
187
+ static $i = 0;
188
+
189
+ if ($i == 0) {
190
+ $adminUserName = $bindResource;
191
+ } else {
192
+ $userName = $bindResource;
193
+ }
194
+
195
+ ++$i;
196
+
197
+ return true;
198
+ }));
199
+ $mockLdapClient->expects($this->any())->method('fetchAll')->will($this->returnCallback(function ($baseDn, $filter, $bind) use (&$filterUsed, &$filterBind) {
200
+ $filterUsed = $filter;
201
+ $filterBind = $bind;
202
+
203
+ return array(array('uid' => LdapUsersTest::TEST_USER, 'dn' => 'thedn'));
204
+ }));
205
+
206
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
207
+ $this->setSingleLdapServer();
208
+ $this->ldapUsers->setAuthenticationUsernameSuffix('whoa');
209
+ $this->ldapUsers->authenticate(self::TEST_USER, self::PASSWORD);
210
+
211
+ $this->assertEquals(self::TEST_ADMIN_USER, $adminUserName);
212
+ $this->assertEquals('thedn', $userName);
213
+ self::assertStringContainsString("uid=?", $filterUsed);
214
+ $this->assertEquals(array(self::TEST_USER . 'whoa'), $filterBind);
215
+ }
216
+
217
+ public function test_getUser_Throws_IfAdminBindFails()
218
+ {
219
+ $this->expectException(\Exception::class);
220
+ $this->expectExceptionMessage('Could not bind as LDAP admin.');
221
+
222
+ $mockLdapClient = $this->makeMockLdapClient();
223
+ $this->makeMockLdapClientFailOnBind($mockLdapClient);
224
+
225
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
226
+ $this->setSingleLdapServer();
227
+ $this->ldapUsers->getUser(self::TEST_USER);
228
+ }
229
+
230
+ public function test_getUser_ReturnsNull_WhenThereIsNoUser()
231
+ {
232
+ $mockLdapClient = $this->makeMockLdapClient();
233
+ $mockLdapClient->expects($this->any())->method('bind')->will($this->returnValue(true));
234
+ $mockLdapClient->expects($this->any())->method('fetchAll')->will($this->returnValue(array()));
235
+
236
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
237
+ $result = $this->ldapUsers->getUser(self::TEST_USER);
238
+
239
+ $this->assertNull($result);
240
+ }
241
+
242
+ public function test_getUser_ReturnsTheUser_WhenAUserIsFound()
243
+ {
244
+ $mockLdapClient = $this->makeMockLdapClient($forSuccess = true);
245
+
246
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
247
+ $result = $this->ldapUsers->getUser(self::TEST_USER);
248
+
249
+ $this->assertEquals(array('uid' => self::TEST_USER, 'otherval' => 34, 'dn' => 'thedn'), $result);
250
+ }
251
+
252
+ public function test_getUser_UsesCorrectLDAPFilterAndBaseDn()
253
+ {
254
+ $usedBaseDn = null;
255
+ $usedFilter = null;
256
+ $filterBind = null;
257
+
258
+ $mockLdapClient = $this->makeMockLdapClient();
259
+ $mockLdapClient->expects($this->any())->method('bind')->will($this->returnValue(true));
260
+ $mockLdapClient->expects($this->any())->method('fetchAll')->will($this->returnCallback(function ($baseDn, $filter, $bind) use (&$usedBaseDn, &$usedFilter, &$filterBind) {
261
+ $usedBaseDn = $baseDn;
262
+ $usedFilter = $filter;
263
+ $filterBind = $bind;
264
+
265
+ return array(array('uid' => LdapUsersTest::TEST_USER));
266
+ }));
267
+
268
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
269
+ $this->setSingleLdapServer();
270
+ $this->ldapUsers->setAuthenticationLdapFilter(self::TEST_EXTRA_FILTER);
271
+ $this->ldapUsers->setAuthenticationRequiredMemberOf(self::TEST_MEMBER_OF);
272
+ $this->ldapUsers->setAuthenticationMemberOfField(self::TEST_MEMBER_OF_FIELD);
273
+ $this->ldapUsers->getUser(self::TEST_USER);
274
+
275
+ $this->assertEquals(self::TEST_BASE_DN, $usedBaseDn);
276
+ self::assertStringContainsString(self::TEST_EXTRA_FILTER, $usedFilter);
277
+ self::assertStringContainsString("(" . self::TEST_MEMBER_OF_FIELD . "=?)", $usedFilter);
278
+ self::assertTrue(in_array(self::TEST_MEMBER_OF, $filterBind));
279
+ }
280
+
281
+ public function test_getUser_CreatesOneClient_WhenNoExistingClientSupplied()
282
+ {
283
+ $mockLdapClient = $this->makeMockLdapClient($forSuccess = true);
284
+ $mockLdapClient->expects($this->once())->method('connect');
285
+
286
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
287
+ $this->ldapUsers->getUser(self::TEST_USER);
288
+ }
289
+
290
+ public function test_getUser_ThrowsException_WhenLdapClientThrows()
291
+ {
292
+ $this->expectException(\Exception::class);
293
+ $this->expectExceptionMessage('dummy error');
294
+
295
+ $mockLdapClient = $this->makeMockLdapClient();
296
+ $this->makeMockLdapClientThrowOnBind($mockLdapClient);
297
+
298
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
299
+ $this->ldapUsers->getUser(self::TEST_USER);
300
+ }
301
+
302
+ public function test_doWithCllient_CallsCallbackCorrectly_WhenFirstServerConnects()
303
+ {
304
+ $mockLdapClient = $this->makeMockLdapClient($forSuccess = true);
305
+ $mockLdapClient->expects($this->once())->method('connect');
306
+
307
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
308
+
309
+ $serverInfo = new ServerInfo("localhost", 389);
310
+ $this->ldapUsers->setLdapServers(array($serverInfo));
311
+
312
+ $passedLdapUsers = null;
313
+ $passedClient = null;
314
+ $passedServerInfo = null;
315
+ $result = $this->ldapUsers->doWithClient(function ($ldapUsers, $client, $serverInfo)
316
+ use (&$passedLdapUsers, &$passedClient, &$passedServerInfo) {
317
+
318
+ $passedLdapUsers = $ldapUsers;
319
+ $passedClient = $client;
320
+ $passedServerInfo = $serverInfo;
321
+
322
+ return "test result";
323
+ });
324
+
325
+ $this->assertEquals("test result", $result);
326
+ $this->assertSame($mockLdapClient, $passedClient);
327
+ $this->assertSame($this->ldapUsers, $passedLdapUsers);
328
+ $this->assertSame($serverInfo, $passedServerInfo);
329
+ }
330
+
331
+ public function test_doWithClient_CreatesAClientUsingFirstSuccessfulConnection()
332
+ {
333
+ $mockLdapClient = $this->makeMockLdapClient($forSuccess = true);
334
+ $mockLdapClient->expects($this->any())->method('connect')->will($this->returnCallback(function () {
335
+ static $i = 0;
336
+
337
+ ++$i;
338
+
339
+ if ($i != 3) {
340
+ throw new \Exception("fail connection");
341
+ } else {
342
+ return;
343
+ }
344
+ }));
345
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
346
+
347
+ $serverInfos = array(
348
+ new ServerInfo("localhost1", 1),
349
+ new ServerInfo("localhost2", 2),
350
+ new ServerInfo("localhost3", 3)
351
+ );
352
+ $this->ldapUsers->setLdapServers($serverInfos);
353
+
354
+ $passedLdapUsers = null;
355
+ $passedClient = null;
356
+ $passedServerInfo = null;
357
+ $this->ldapUsers->doWithClient(function ($ldapUsers, $client, $serverInfo)
358
+ use (&$passedLdapUsers, &$passedClient, &$passedServerInfo) {
359
+
360
+ $passedLdapUsers = $ldapUsers;
361
+ $passedClient = $client;
362
+ $passedServerInfo = $serverInfo;
363
+ });
364
+
365
+ $this->assertSame($mockLdapClient, $passedClient);
366
+ $this->assertSame($this->ldapUsers, $passedLdapUsers);
367
+ $this->assertSame($serverInfos[2], $passedServerInfo);
368
+ }
369
+
370
+ public function test_doWithClient_PropagatesCallbackExceptions()
371
+ {
372
+ $this->expectException(\Exception::class);
373
+ $this->expectExceptionMessage('test');
374
+
375
+ $mockLdapClient = $this->makeMockLdapClient($forSuccess = true);
376
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
377
+
378
+ $serverInfo = new ServerInfo("localhost", 389);
379
+ $this->ldapUsers->setLdapServers(array($serverInfo));
380
+
381
+ $this->ldapUsers->doWithClient(function () {
382
+ throw new Exception("test");
383
+ });
384
+ }
385
+
386
+ public function test_getCountOfUsersMatchingFilter_Throws_IfAdminBindFails()
387
+ {
388
+ $this->expectException(\Exception::class);
389
+ $this->expectExceptionMessage('Could not bind as LDAP admin.');
390
+
391
+ $mockLdapClient = $this->makeMockLdapClient();
392
+ $this->makeMockLdapClientFailOnBind($mockLdapClient);
393
+
394
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
395
+ $this->setSingleLdapServer();
396
+ $this->ldapUsers->getCountOfUsersMatchingFilter("dummy filter");
397
+ }
398
+
399
+ public function test_getCountOfUsersMatchingFilter_Throws_IfLdapClientConnectThrows()
400
+ {
401
+ $this->expectException(\Exception::class);
402
+ $this->expectExceptionMessage('dummy error');
403
+
404
+ $mockLdapClient = $this->makeMockLdapClient();
405
+ $this->makeMockLdapClientThrowOnBind($mockLdapClient);
406
+
407
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
408
+ $this->setSingleLdapServer();
409
+ $this->ldapUsers->getCountOfUsersMatchingFilter("dummy filter");
410
+ }
411
+
412
+ public function test_getCountOfUsersMatchingFilter_ReturnsLdapEntityCount()
413
+ {
414
+ $mockLdapClient = $this->makeMockLdapClient($forSuccess = true);
415
+
416
+ $passedFilter = null;
417
+ $mockLdapClient->expects($this->any())->method('count')->will($this->returnCallback(function ($baseDn, $filter) use (&$passedFilter) {
418
+ $passedFilter = $filter;
419
+ return 10;
420
+ }));
421
+
422
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
423
+ $this->setSingleLdapServer();
424
+ $count = $this->ldapUsers->getCountOfUsersMatchingFilter("dummy filter");
425
+
426
+ $this->assertEquals("dummy filter", $passedFilter);
427
+ $this->assertEquals(10, $count);
428
+ }
429
+
430
+ public function test_getAllUserLogins_Throws_IfAdminBindFails()
431
+ {
432
+ $this->expectException(\Exception::class);
433
+ $this->expectExceptionMessage('Could not bind as LDAP admin.');
434
+
435
+ $mockLdapClient = $this->makeMockLdapClient();
436
+ $this->makeMockLdapClientFailOnBind($mockLdapClient);
437
+
438
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
439
+ $this->setSingleLdapServer();
440
+ $this->ldapUsers->getAllUserLogins();
441
+ }
442
+
443
+ public function test_getAllUserLogins_Throws_IfLdapClientConnectThrows()
444
+ {
445
+ $this->expectException(\Exception::class);
446
+ $this->expectExceptionMessage('dummy error');
447
+
448
+ $mockLdapClient = $this->makeMockLdapClient();
449
+ $this->makeMockLdapClientThrowOnBind($mockLdapClient);
450
+
451
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
452
+ $this->setSingleLdapServer();
453
+ $this->ldapUsers->getAllUserLogins();
454
+ }
455
+
456
+ public function test_getAllUserLogins_ReturnsLdapEntities()
457
+ {
458
+ $mockLdapClient = $this->makeMockLdapClient($forSuccess = false);
459
+
460
+ $usedFilter = null;
461
+
462
+ $mockLdapClient->expects($this->any())->method('bind')->will($this->returnValue(true));
463
+ $mockLdapClient->expects($this->any())->method('fetchAll')->will($this->returnCallback(function ($baseDn, $filter, $bind) use (&$usedFilter) {
464
+ $usedFilter = $filter;
465
+
466
+ return array(array('uid' => LdapUsersTest::TEST_USER), array('uid' => LdapUsersTest::TEST_ADMIN_USER));
467
+ }));
468
+
469
+ $this->ldapUsers->setLdapClientClass($mockLdapClient);
470
+ $this->setSingleLdapServer();
471
+
472
+ $logins = $this->ldapUsers->getAllUserLogins();
473
+ $this->assertEquals(array(self::TEST_USER, self::TEST_ADMIN_USER), $logins);
474
+ }
475
+
476
+ private function makeMockLdapClient($forSuccess = false)
477
+ {
478
+ $methods = array('__construct', 'connect', 'close', 'bind', 'fetchAll', 'isOpen', 'count');
479
+
480
+ $mock = $this->getMockBuilder('Piwik\Plugins\LoginLdap\Ldap\Client')
481
+ ->disableOriginalConstructor()
482
+ ->onlyMethods($methods)
483
+ ->getMock();
484
+
485
+ if ($forSuccess) {
486
+ $mock->expects($this->any())->method('bind')->will($this->returnValue(true));
487
+ $mock->expects($this->any())->method('fetchAll')->will($this->returnValue(array(array('uid' => self::TEST_USER, 'otherval' => 34, 'dn' => 'thedn'))));
488
+ }
489
+
490
+ return $mock;
491
+ }
492
+
493
+ private function makeMockLdapClientFailOnBind(\PHPUnit\Framework\MockObject\MockObject $mockLdapClient)
494
+ {
495
+ $mockLdapClient->expects($this->any())->method('bind')->will($this->returnCallback(function ($bindResource) {
496
+ if ($bindResource == LdapUsersTest::TEST_ADMIN_USER) {
497
+ return false;
498
+ } else {
499
+ return true;
500
+ }
501
+ }));
502
+ }
503
+
504
+ private function makeMockLdapClientThrowOnBind(\PHPUnit\Framework\MockObject\MockObject $mockLdapClient)
505
+ {
506
+ $mockLdapClient->expects($this->any())->method('bind')->will($this->returnCallback(function () {
507
+ throw new Exception("dummy error");
508
+ }));
509
+ }
510
+
511
+ private function setSingleLdapServer()
512
+ {
513
+ $this->ldapUsers->setLdapServers(array(new ServerInfo("localhost", self::TEST_BASE_DN, 389, self::TEST_ADMIN_USER)));
514
+ }
515
+ }
plugins/LoginLdap/tests/Unit/ServerInfoTest.php ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Unit;
12
+
13
+ use PHPUnit\Framework\TestCase;
14
+ use Piwik\Plugins\LoginLdap\Ldap\ServerInfo;
15
+
16
+ /**
17
+ * @group LoginLdap
18
+ * @group LoginLdap_Unit
19
+ * @group LoginLdap_ServerInfoTest
20
+ */
21
+ class ServerInfoTest extends TestCase
22
+ {
23
+ public const TEST_HOST_NAME = 'some-host.com';
24
+ public const TEST_ADMIN_USER = 'who?';
25
+ public const TEST_ADMIN_PASS = 'pass123!';
26
+ public const TEST_BASE_DN = 'testbasedn';
27
+
28
+ public function testConstruct()
29
+ {
30
+ $serverInfo = new ServerInfo(
31
+ self::TEST_HOST_NAME,
32
+ self::TEST_BASE_DN,
33
+ ServerInfo::DEFAULT_LDAP_PORT,
34
+ self::TEST_ADMIN_USER,
35
+ self::TEST_ADMIN_PASS
36
+ );
37
+
38
+ $this->assertSame(self::TEST_HOST_NAME, $serverInfo->getServerHostname());
39
+ $this->assertSame(self::TEST_BASE_DN, $serverInfo->getBaseDn());
40
+ $this->assertSame(ServerInfo::DEFAULT_LDAP_PORT, $serverInfo->getServerPort());
41
+ $this->assertSame(self::TEST_ADMIN_USER, $serverInfo->getAdminUsername());
42
+ $this->assertSame(self::TEST_ADMIN_PASS, $serverInfo->getAdminPassword());
43
+ }
44
+
45
+ public function testConstructNoPort()
46
+ {
47
+ $serverInfo = new ServerInfo(
48
+ self::TEST_HOST_NAME,
49
+ self::TEST_BASE_DN
50
+ );
51
+
52
+ $this->assertSame(self::TEST_HOST_NAME, $serverInfo->getServerHostname());
53
+ $this->assertSame(self::TEST_BASE_DN, $serverInfo->getBaseDn());
54
+ $this->assertSame(ServerInfo::DEFAULT_LDAP_PORT, $serverInfo->getServerPort());
55
+ }
56
+
57
+ public function testConstructNoPortLdaps()
58
+ {
59
+ $ldapsHostName = 'ldaps://' . self::TEST_HOST_NAME;
60
+ $serverInfo = new ServerInfo(
61
+ $ldapsHostName,
62
+ self::TEST_BASE_DN
63
+ );
64
+
65
+ $this->assertSame($ldapsHostName, $serverInfo->getServerHostname());
66
+ $this->assertSame(self::TEST_BASE_DN, $serverInfo->getBaseDn());
67
+ $this->assertSame(ServerInfo::DEFAULT_LDAPS_PORT, $serverInfo->getServerPort());
68
+ }
69
+
70
+ public function testConstructSpecificPort()
71
+ {
72
+ $port = 1234;
73
+ $serverInfo = new ServerInfo(
74
+ self::TEST_HOST_NAME,
75
+ self::TEST_BASE_DN,
76
+ $port
77
+ );
78
+
79
+ $this->assertSame(self::TEST_HOST_NAME, $serverInfo->getServerHostname());
80
+ $this->assertSame(self::TEST_BASE_DN, $serverInfo->getBaseDn());
81
+ $this->assertSame($port, $serverInfo->getServerPort());
82
+ }
83
+
84
+ public function testConstructSpecificPortLdaps()
85
+ {
86
+ $ldapsHostName = 'ldaps://' . self::TEST_HOST_NAME;
87
+ $port = 1234;
88
+ $serverInfo = new ServerInfo(
89
+ $ldapsHostName,
90
+ self::TEST_BASE_DN,
91
+ $port
92
+ );
93
+
94
+ $this->assertSame($ldapsHostName, $serverInfo->getServerHostname());
95
+ $this->assertSame(self::TEST_BASE_DN, $serverInfo->getBaseDn());
96
+ $this->assertSame($port, $serverInfo->getServerPort());
97
+ }
98
+
99
+ public function testConstructWithQuoteInPassword()
100
+ {
101
+ $serverInfo = new ServerInfo(
102
+ self::TEST_HOST_NAME,
103
+ self::TEST_BASE_DN,
104
+ ServerInfo::DEFAULT_LDAP_PORT,
105
+ self::TEST_ADMIN_USER,
106
+ "some\'pass"
107
+ );
108
+
109
+ $this->assertSame(self::TEST_HOST_NAME, $serverInfo->getServerHostname());
110
+ $this->assertSame(self::TEST_BASE_DN, $serverInfo->getBaseDn());
111
+ $this->assertSame(ServerInfo::DEFAULT_LDAP_PORT, $serverInfo->getServerPort());
112
+ $this->assertSame(self::TEST_ADMIN_USER, $serverInfo->getAdminUsername());
113
+ $this->assertSame("some'pass", $serverInfo->getAdminPassword());
114
+ }
115
+
116
+ public function testSetAdminPassword()
117
+ {
118
+ $serverInfo = new ServerInfo(self::TEST_HOST_NAME, self::TEST_BASE_DN);
119
+ $this->assertEmpty($serverInfo->getAdminPassword());
120
+ $serverInfo->setAdminPassword(self::TEST_ADMIN_PASS);
121
+ $this->assertSame(self::TEST_ADMIN_PASS, $serverInfo->getAdminPassword());
122
+ }
123
+
124
+ public function testSetAdminPasswordWithQuoteInPassword()
125
+ {
126
+ $serverInfo = new ServerInfo(self::TEST_HOST_NAME, self::TEST_BASE_DN);
127
+ $this->assertEmpty($serverInfo->getAdminPassword());
128
+ $serverInfo->setAdminPassword("some\'pass");
129
+ $this->assertSame("some'pass", $serverInfo->getAdminPassword());
130
+ }
131
+ }
plugins/LoginLdap/tests/Unit/UserAccessAttributeParserTest.php ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Unit;
12
+
13
+ use PHPUnit\Framework\TestCase;
14
+ use Piwik\Config;
15
+ use Piwik\Option;
16
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserAccessAttributeParser;
17
+ use Piwik\Plugins\SitesManager\API as SitesManagerAPI;
18
+ use Piwik\SettingsPiwik;
19
+
20
+ /**
21
+ * @group LoginLdap
22
+ * @group LoginLdap_Unit
23
+ * @group LoginLdap_UserAccessAttributeParserTest
24
+ */
25
+ class UserAccessAttributeParserTest extends TestCase
26
+ {
27
+ /**
28
+ * @var UserAccessAttributeParser
29
+ */
30
+ private $userAccessAttributeParser;
31
+
32
+ public function setUp(): void
33
+ {
34
+ parent::setUp();
35
+
36
+ Config::getInstance()->LoginLdap = array();
37
+
38
+ $this->setSitesManagerApiMock();
39
+
40
+ $this->userAccessAttributeParser = new UserAccessAttributeParser();
41
+ }
42
+
43
+ public function tearDown(): void
44
+ {
45
+ Option::setSingletonInstance(null);
46
+ }
47
+
48
+ public function test_makeConfigured_CreatesCorrectInstance_WhenAllConfigOptionsSpecified()
49
+ {
50
+ Config::getInstance()->LoginLdap = array(
51
+ 'user_access_attribute_server_specification_delimiter' => '#',
52
+ 'user_access_attribute_server_separator' => '|',
53
+ 'instance_name' => 'myPiwik'
54
+ );
55
+
56
+ $parser = UserAccessAttributeParser::makeConfigured();
57
+
58
+ $this->assertEquals('#', $parser->getServerSpecificationDelimiter());
59
+ $this->assertEquals('|', $parser->getServerIdsSeparator());
60
+ $this->assertEquals('myPiwik', $parser->getThisPiwikInstanceName());
61
+ }
62
+
63
+ public function test_makeConfigured_CreatesCorrectInstance_WhenNoConfigOptionsSpecified()
64
+ {
65
+ $parser = UserAccessAttributeParser::makeConfigured();
66
+
67
+ $this->assertEquals(';', $parser->getServerSpecificationDelimiter());
68
+ $this->assertEquals(':', $parser->getServerIdsSeparator());
69
+ $this->assertNull($parser->getThisPiwikInstanceName());
70
+ }
71
+
72
+ public function getInstanceNamesToTest()
73
+ {
74
+ return array(
75
+ array('myPiwik'),
76
+ array(null)
77
+ );
78
+ }
79
+
80
+ public function getInstanceUrlVariationsToTest()
81
+ {
82
+ return array(
83
+ array("https://whatever.com", "whatever.com"),
84
+ array("https://whatever.com", "http://whatever.com"),
85
+ array("https://whatever.com", "https://whatever.com"),
86
+ array("https://whatever.com", "https://whatever.com:80"),
87
+ array("http://whatever.com/what/ever?abc", "whatever.com/what/ever"),
88
+ array("http://whatever.com/what/ever?abc", "https://whatever.com/what/ever"),
89
+ array("http://whatever.com/what/ever?abc", "http://whatever.com/what/ever"),
90
+ array("http://whatever.com/what/ever?abc", "whatever.com/what/ever?def"),
91
+ array("www.whatever.com", "www.whatever.com"),
92
+ array("www.whatever.com", "www.whatever.com?abc#def"),
93
+ array("http://whatever.com:80", "whatever.com"),
94
+ array("http://whatever.com/", "whatever.com"),
95
+ array("http://whatever.com/index.php", "whatever.com/index.php"),
96
+ array("http://whatever.com/index.php", "whatever.com/index.php/"),
97
+ );
98
+ }
99
+
100
+ /**
101
+ * @dataProvider getInstanceNamesToTest
102
+ */
103
+ public function test_getSiteIdsFromAccessAttribute_ReturnsCorrectSiteIdList_WhenNoInstanceUsed($instanceName)
104
+ {
105
+ $this->userAccessAttributeParser->setThisPiwikInstanceName($instanceName);
106
+
107
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute("1,2,3");
108
+ $this->assertEquals(array(1,2,3), $ids);
109
+
110
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute("2");
111
+ $this->assertEquals(array(2), $ids);
112
+
113
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute('all');
114
+ $this->assertEquals(array(1,2,3,4,5,6), $ids);
115
+ }
116
+
117
+ public function test_getSiteIdsFromAccessAttribute_ReturnsCorrectSiteIdList_WhenDifferentInstanceNamesUsed()
118
+ {
119
+ $this->userAccessAttributeParser->setThisPiwikInstanceName('myPiwik');
120
+
121
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute("myPiwik:1,2;otherPiwik:4;myPiwik:3");
122
+ $this->assertEquals(array(1,2,3), $ids);
123
+
124
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute(" myPiwik : 1,2 ; other:3 ");
125
+ $this->assertEquals(array(1,2), $ids);
126
+ }
127
+
128
+ public function test_getSiteIdsFromAccessAttribute_ReturnsCorrectSiteIdList_WhenAllStringUsed()
129
+ {
130
+ $this->userAccessAttributeParser->setThisPiwikInstanceName('myPiwik');
131
+
132
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute("otherPiwik:1,2;myPiwik:all;another:3");
133
+ $this->assertEquals(array(1,2,3,4,5,6), $ids);
134
+ }
135
+
136
+ /**
137
+ * @dataProvider getInstanceUrlVariationsToTest
138
+ */
139
+ public function test_getSiteIdsFromAccessAttribute_ReturnsCorrectSiteIdList_WhenDifferentInstanceUrlUsed($thisUrl, $instanceId)
140
+ {
141
+ $this->setThisPiwikUrl($thisUrl);
142
+ $this->userAccessAttributeParser->setServerIdsSeparator('|');
143
+
144
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute($instanceId . "|1,2,3");
145
+ $this->assertEquals(array(1,2,3), $ids);
146
+ }
147
+
148
+ public function test_getSiteIdsFromAccessAttribute_ReturnsCorrectSiteIdList_WhenAttributeValueIsMalformed_AndMatchingInstanceByUrl()
149
+ {
150
+ $this->setThisPiwikUrl("http://whatever.com/a?b=c");
151
+
152
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute(";;whatever.com/a:1,2,3;*{}@@.co?m:1,2;;");
153
+ $this->assertEquals(array(1,2,3), $ids);
154
+
155
+ $this->setThisPiwikUrl("ht??p://@@.com");
156
+
157
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute("whatever.com:1,2,3");
158
+ $this->assertEquals(array(), $ids);
159
+
160
+ $this->userAccessAttributeParser->setThisPiwikInstanceName("myPi|wik");
161
+
162
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute(" ; ; myPi|wik : 1,2 ; myPi|wik = view:3,def; myPi | wik:4,5 ; ; ");
163
+ $this->assertEquals(array(1,2,3), $ids);
164
+ }
165
+
166
+ public function test_getSiteIdsFromAccessAttribute_ReturnsCorrectSiteIdList_WhenCustomDelimitersAreUsed()
167
+ {
168
+ $this->userAccessAttributeParser->setThisPiwikInstanceName('myPiwik');
169
+ $this->userAccessAttributeParser->setServerSpecificationDelimiter('#');
170
+ $this->userAccessAttributeParser->setServerIdsSeparator('|');
171
+
172
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute("1,2");
173
+ $this->assertEquals(array(1,2), $ids);
174
+
175
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute("wrongPiwik|all#myPiwik|1,2#anotherPiwik|3,4");
176
+ $this->assertEquals(array(1,2), $ids);
177
+
178
+ $this->userAccessAttributeParser->setThisPiwikInstanceName(null);
179
+
180
+ $this->setThisPiwikUrl("http://whatever.com:80");
181
+
182
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute("whatever.com:80|1,2,3#whatever.com:8080|3,4");
183
+ $this->assertEquals(array(1,2,3), $ids);
184
+
185
+ $ids = $this->userAccessAttributeParser->getSiteIdsFromAccessAttribute("http://whatever.com:801|1,2#whatever.com:80|3,4#http://whatever.com:80|5,6");
186
+ $this->assertEquals(array(3,4,5,6), $ids);
187
+ }
188
+
189
+ public function test_getSuperUserAccessFromSuperUserAttribute_ReturnsTrue_IfNoInstanceSpecified()
190
+ {
191
+ $this->userAccessAttributeParser->setThisPiwikInstanceName('myPiwik');
192
+
193
+ $this->assertTrue($this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute(""));
194
+ $this->assertTrue($this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("1"));
195
+ $this->assertTrue($this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("true"));
196
+ $this->assertTrue($this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("tRuE"));
197
+
198
+ $this->assertFalse($this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("false"));
199
+ $this->assertFalse($this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("server"));
200
+ }
201
+
202
+ public function test_getSuperUserAccessFromSuperUserAttribute_ReturnsTrue_IfInstanceInSpecifiedList()
203
+ {
204
+ $this->userAccessAttributeParser->setThisPiwikInstanceName('myPiwik');
205
+
206
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("myPiwik");
207
+ $this->assertTrue($hasSuperUserAccess);
208
+
209
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("somePiwik;myPiwik;anotherPiwik");
210
+ $this->assertTrue($hasSuperUserAccess);
211
+
212
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("myPiwik : somePiwik : anotherPiwik");
213
+ $this->assertTrue($hasSuperUserAccess);
214
+
215
+ $this->userAccessAttributeParser->setThisPiwikInstanceName(null);
216
+ $this->userAccessAttributeParser->setServerIdsSeparator('|');
217
+ $this->setThisPiwikUrl("https://whatever.com/piwik");
218
+
219
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("whatever.com/piwik");
220
+ $this->assertTrue($hasSuperUserAccess);
221
+
222
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("http://whatever.com/piwik|anotherpiwik.com");
223
+ $this->assertTrue($hasSuperUserAccess);
224
+
225
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute(" anotherpiwik.com | https://whatever.com/piwik ");
226
+ $this->assertTrue($hasSuperUserAccess);
227
+ }
228
+
229
+ public function test_getSuperUserAccessFromSuperUserAttribute_ReturnsFalse_IfInstanceNotInAttribute()
230
+ {
231
+ $this->userAccessAttributeParser->setThisPiwikInstanceName('myPiwik');
232
+
233
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("whatever");
234
+ $this->assertFalse($hasSuperUserAccess);
235
+
236
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("one;two;three");
237
+ $this->assertFalse($hasSuperUserAccess);
238
+
239
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("one:two:three");
240
+ $this->assertFalse($hasSuperUserAccess);
241
+
242
+ $this->userAccessAttributeParser->setThisPiwikInstanceName(null);
243
+ $this->userAccessAttributeParser->setServerIdsSeparator('|');
244
+ $this->setThisPiwikUrl("https://whatever.com/piwik");
245
+
246
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("https://whatever.com:8080/piwik");
247
+ $this->assertFalse($hasSuperUserAccess);
248
+
249
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("https://whatever.com:8080");
250
+ $this->assertFalse($hasSuperUserAccess);
251
+ }
252
+
253
+ public function test_getSuperUserAccessFromSuperUserAttribute_ReturnsCorrectResult_IfAttributeValueIsMalformed()
254
+ {
255
+ $this->userAccessAttributeParser->setThisPiwikInstanceName('myPiwik');
256
+
257
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute(" myPiwik = superuser ; whatever");
258
+ $this->assertTrue($hasSuperUserAccess);
259
+
260
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("anothe; superuser = myPiwik ; whatever");
261
+ $this->assertTrue($hasSuperUserAccess);
262
+
263
+ $this->userAccessAttributeParser->setThisPiwikInstanceName(null);
264
+ $this->userAccessAttributeParser->setServerSpecificationDelimiter('|');
265
+ $this->setThisPiwikUrl("https://whatever.com/piwik");
266
+
267
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("whatever.com/piwik | @{}{}@ | /&/?//");
268
+ $this->assertTrue($hasSuperUserAccess);
269
+ }
270
+
271
+ public function test_getSuperUserAccessFromSuperUserAttribute_ReturnsCorrectResult_WhenCustomDelimetersAreUsed()
272
+ {
273
+ $this->userAccessAttributeParser->setThisPiwikInstanceName('myPiwik');
274
+ $this->userAccessAttributeParser->setServerSpecificationDelimiter('#');
275
+ $this->userAccessAttributeParser->setServerIdsSeparator('|');
276
+
277
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("anoth | myPiwik | whatever");
278
+ $this->assertTrue($hasSuperUserAccess);
279
+
280
+ $hasSuperUserAccess = $this->userAccessAttributeParser->getSuperUserAccessFromSuperUserAttribute("a # myPiwik # c");
281
+ $this->assertTrue($hasSuperUserAccess);
282
+ }
283
+
284
+ private function setSitesManagerApiMock()
285
+ {
286
+ $mock = $this->getMockBuilder('stdClass')
287
+ ->addMethods(array('getSitesIdWithAtLeastViewAccess', 'getAllSitesId'))
288
+ ->getMock();
289
+ $mock->expects($this->any())->method('getSitesIdWithAtLeastViewAccess')->willReturn(array(1,2,3,4,5,6));
290
+ $mock->expects($this->any())->method('getAllSitesId')->willReturn(array(1,2,3,4,5,6));
291
+ SitesManagerAPI::setSingletonInstance($mock);
292
+ }
293
+
294
+ private function setThisPiwikUrl($thisUrl)
295
+ {
296
+ $mock = $this->getMockBuilder('stdClass')
297
+ ->addMethods(array('getValue'))
298
+ ->getMock();
299
+ $mock->expects($this->any())->method('getValue')->willReturnCallback(function ($key) use ($thisUrl) {
300
+ if ($key == SettingsPiwik::OPTION_PIWIK_URL) {
301
+ return $thisUrl;
302
+ } else {
303
+ return "...";
304
+ }
305
+ });
306
+
307
+ Option::setSingletonInstance($mock);
308
+ }
309
+ }
plugins/LoginLdap/tests/Unit/UserAccessMapperTest.php ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Unit;
12
+
13
+ use PHPUnit\Framework\TestCase;
14
+ use Piwik\Config;
15
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserAccessAttributeParser;
16
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserAccessMapper;
17
+ use Piwik\Plugins\SitesManager\API as SitesManagerAPI;
18
+
19
+ /**
20
+ * @group LoginLdap
21
+ * @group LoginLdap_Unit
22
+ * @group LoginLdap_UserAccessMapperTest
23
+ */
24
+ class UserAccessMapperTest extends TestCase
25
+ {
26
+ /**
27
+ * @var UserAccessMapper
28
+ */
29
+ private $userAccessMapper;
30
+
31
+ public function setUp(): void
32
+ {
33
+ parent::setUp();
34
+
35
+ Config::getInstance()->LoginLdap = array();
36
+
37
+ $this->setSitesManagerApiMock();
38
+
39
+ $this->userAccessMapper = new UserAccessMapper();
40
+
41
+ $attributeParser = new UserAccessAttributeParser();
42
+ $attributeParser->setThisPiwikInstanceName('thisPiwik');
43
+ $this->userAccessMapper->setUserAccessAttributeParser($attributeParser);
44
+ }
45
+
46
+ public function tearDown(): void
47
+ {
48
+ SitesManagerAPI::unsetInstance();
49
+ }
50
+
51
+ public function test_makeConfigured_CreatesCorrectlyConfiguredInstance_WhenAllConfigSupplied()
52
+ {
53
+ Config::getInstance()->LoginLdap = array(
54
+ 'ldap_view_access_field' => 'viewaccessfield',
55
+ 'ldap_admin_access_field' => 'adminaccessfield',
56
+ 'ldap_superuser_access_field' => 'superuseraccessfield'
57
+ );
58
+
59
+ $userAccessMapper = UserAccessMapper::makeConfigured();
60
+ $this->assertEquals('viewaccessfield', $userAccessMapper->getViewAttributeName());
61
+ $this->assertEquals('adminaccessfield', $userAccessMapper->getAdminAttributeName());
62
+ $this->assertEquals('superuseraccessfield', $userAccessMapper->getSuperuserAttributeName());
63
+ }
64
+
65
+ public function test_makeConfigured_CreatesCorrectlyConfiguredInstance_WhenNoConfigOptionsPresent()
66
+ {
67
+ $userAccessMapper = UserAccessMapper::makeConfigured();
68
+ $this->assertEquals('view', $userAccessMapper->getViewAttributeName());
69
+ $this->assertEquals('admin', $userAccessMapper->getAdminAttributeName());
70
+ $this->assertEquals('superuser', $userAccessMapper->getSuperuserAttributeName());
71
+ }
72
+
73
+ public function test_getPiwikUserAccessForLdapUser_CorrectlyMapsAccess_WhenUserIsSuperUser()
74
+ {
75
+ $access = $this->userAccessMapper->getPiwikUserAccessForLdapUser(array(
76
+ 'superuser' => '1'
77
+ ));
78
+
79
+ $this->checkSuperUserAccess($access);
80
+
81
+ $access = $this->userAccessMapper->getPiwikUserAccessForLdapUser(array(
82
+ 'admin' => '1,2,3',
83
+ 'view' => '3,4,5',
84
+ 'superuser' => '1'
85
+ ));
86
+
87
+ $this->checkSuperUserAccess($access);
88
+
89
+ $access = $this->userAccessMapper->getPiwikUserAccessForLdapUser(array(
90
+ 'superuser' => null
91
+ ));
92
+
93
+ $this->checkSuperUserAccess($access);
94
+
95
+ $access = $this->userAccessMapper->getPiwikUserAccessForLdapUser(array(
96
+ 'superuser' => array()
97
+ ));
98
+
99
+ $this->assertEquals(array(), $access);
100
+ }
101
+
102
+ public function test_getPiwikUserAccessForLdapUser_CorrectlyMapsAccess_WhenUserHasViewAndAdminAccess()
103
+ {
104
+ $access = $this->userAccessMapper->getPiwikUserAccessForLdapUser(array(
105
+ 'view' => '3,4',
106
+ 'admin' => '1,2'
107
+ ));
108
+
109
+ $expectedAccess = array(
110
+ 'admin' => array(1,2),
111
+ 'view' => array(3,4)
112
+ );
113
+ $this->assertEquals($expectedAccess, $access);
114
+ }
115
+
116
+ public function test_getPiwikUserAccessForLdapUser_UsesHighestAccessLevel_WhenUserHasViewAndAdminAccessForSameSite()
117
+ {
118
+ $access = $this->userAccessMapper->getPiwikUserAccessForLdapUser(array(
119
+ 'view' => '1,4',
120
+ 'admin' => '1,2'
121
+ ));
122
+
123
+ $expectedAccess = array(
124
+ 'admin' => array(1,2),
125
+ 'view' => array(4)
126
+ );
127
+ $this->assertEquals($expectedAccess, $access);
128
+ }
129
+
130
+ public function test_getPiwikUserAccessForLdapUser_CorrectlyMapsAccess_WhenLdapAttributesAreArrays()
131
+ {
132
+ $access = $this->userAccessMapper->getPiwikUserAccessForLdapUser(array(
133
+ 'view' => array('3,5,6', 4),
134
+ 'admin' => array(1,'2')
135
+ ));
136
+
137
+ $expectedAccess = array(
138
+ 'admin' => array(1,2),
139
+ 'view' => array(3,5,6,4)
140
+ );
141
+ $this->assertEquals($expectedAccess, $access);
142
+ }
143
+
144
+ public function test_getPiwikUserAccessForLdapUser_CorrectlyMapsAccess_WhenLdapAttributeIsAllString()
145
+ {
146
+ $access = $this->userAccessMapper->getPiwikUserAccessForLdapUser(array(
147
+ 'view' => 'all',
148
+ 'admin' => 'all'
149
+ ));
150
+
151
+ $expectedAccess = array(
152
+ 'admin' => array(1,2,3,4,5,6)
153
+ );
154
+ $this->assertEquals($expectedAccess, $access);
155
+ }
156
+
157
+ public function test_getPiwikUserAccessForLdapUser_IgnoresSitesThatDoNotExist()
158
+ {
159
+ $access = $this->userAccessMapper->getPiwikUserAccessForLdapUser(array(
160
+ 'view' => array(15,16,'17,18'),
161
+ 'admin' => '11,12,13'
162
+ ));
163
+
164
+ $expectedAccess = array();
165
+ $this->assertEquals($expectedAccess, $access);
166
+ }
167
+
168
+ private function checkSuperUserAccess($access)
169
+ {
170
+ $this->assertEquals(array('superuser' => true), $access);
171
+ }
172
+
173
+ private function setSitesManagerApiMock()
174
+ {
175
+ $mock = $this->getMockBuilder('stdClass')
176
+ ->addMethods(array('getSitesIdWithAtLeastViewAccess', 'getAllSitesId'))
177
+ ->getMock();
178
+ $mock->expects($this->any())->method('getSitesIdWithAtLeastViewAccess')->willReturn(array(1,2,3,4,5,6));
179
+ $mock->expects($this->any())->method('getAllSitesId')->willReturn(array(1,2,3,4,5,6));
180
+ SitesManagerAPI::setSingletonInstance($mock);
181
+ }
182
+ }
plugins/LoginLdap/tests/Unit/UserMapperTest.php ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Unit;
12
+
13
+ use Exception;
14
+ use PHPUnit\Framework\TestCase;
15
+ use Piwik\Config;
16
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserMapper;
17
+
18
+ /**
19
+ * @group LoginLdap
20
+ * @group LoginLdap_Unit
21
+ * @group LoginLdap_UserMapperTest
22
+ */
23
+ class UserMapperTest extends TestCase
24
+ {
25
+ /**
26
+ * @var UserMapper
27
+ */
28
+ private $userMapper;
29
+
30
+ public function setUp(): void
31
+ {
32
+ parent::setUp();
33
+
34
+ $this->userMapper = new UserMapper();
35
+ }
36
+
37
+ public function test_makeConfigured_CreatesCorrectUserMapper_WhenAllConfigOptionsSupplied()
38
+ {
39
+ Config::getInstance()->LoginLdap = array(
40
+ 'ldap_user_id_field' => 'userIdField',
41
+ 'ldap_mail_field' => 'mailField',
42
+ 'ldap_password_field' => 'passwordField',
43
+ 'user_email_suffix' => 'userEmailSuffix',
44
+ );
45
+
46
+ $userMapper = UserMapper::makeConfigured();
47
+
48
+ $this->assertUserMapperIsCorrectlyConfigured($userMapper);
49
+ }
50
+
51
+ public function test_makeConfigured_CreatesCorrectUserMapper_WhenOldConfigNamesUsed()
52
+ {
53
+ Config::getInstance()->LoginLdap = array(
54
+ 'userIdField' => 'userIdField',
55
+ 'aliasField' => 'aliasField',
56
+ 'mailField' => 'mailField',
57
+ 'ldap_password_field' => 'passwordField',
58
+ 'usernameSuffix' => 'userEmailSuffix',
59
+ );
60
+
61
+ $userMapper = UserMapper::makeConfigured();
62
+
63
+ $this->assertUserMapperIsCorrectlyConfigured($userMapper);
64
+ }
65
+
66
+ public function test_makeConfigured_UsesCorrectDefaultValues()
67
+ {
68
+ Config::getInstance()->LoginLdap = array();
69
+
70
+ $userMapper = UserMapper::makeConfigured();
71
+
72
+ $this->assertUserMapperHasCorrectDefaultPropertyValues($userMapper);
73
+ }
74
+
75
+ public function test_createPiwikUserFromLdapUser_CreatesCorrectPiwikUser_WhenAllLdapUserFieldsArePresent()
76
+ {
77
+ $result = $this->userMapper->createPiwikUserFromLdapUser(array(
78
+ 'uid' => 'martha',
79
+ 'cn' => 'A real doctor',
80
+ 'sn' => 'Jones',
81
+ 'givenname' => 'Martha',
82
+ 'mail' => 'martha@unit.co.uk',
83
+ 'userpassword' => 'pass',
84
+ 'other' => 'sfdklsdjf'
85
+ ));
86
+
87
+ $this->assertEquals(array(
88
+ 'login' => 'martha',
89
+ 'password' => md5('pass'),
90
+ 'email' => 'martha@unit.co.uk',
91
+ ), $result);
92
+ }
93
+
94
+ public function test_createPiwikUserFromLdapUser_CreatesCorrectPiwikUser_WhenCustomLdapAttributesAreUsedAndPresent()
95
+ {
96
+ $this->userMapper->setLdapUserIdField('testfield2');
97
+ $this->userMapper->setLdapMailField('testfield3');
98
+ $this->userMapper->setLdapUserPasswordField('testfield6');
99
+
100
+ $result = $this->userMapper->createPiwikUserFromLdapUser(array(
101
+ 'testfield1' => 'am i bovvered?',
102
+ 'testfield2' => 'donna',
103
+ 'testfield3' => 'donna@rstad.com',
104
+ 'testfield4' => 'Donna',
105
+ 'testfield5' => 'Noble',
106
+ 'testfield6' => 'pass',
107
+ 'other3' => 'sdlfdsf'
108
+ ));
109
+
110
+ $this->assertEquals(array(
111
+ 'login' => 'donna',
112
+ 'password' => md5('pass'),
113
+ 'email' => 'donna@rstad.com'
114
+ ), $result);
115
+
116
+ $result = $this->userMapper->createPiwikUserFromLdapUser(array(
117
+ 'testfield2' => 'donna',
118
+ 'testfield3' => 'donna@rstad.com',
119
+ 'testfield4' => 'Donna',
120
+ 'testfield5' => 'Noble',
121
+ 'testfield6' => 'pass',
122
+ 'other3' => 'sdlfdsf'
123
+ ));
124
+
125
+ $this->assertEquals(array(
126
+ 'login' => 'donna',
127
+ 'password' => md5('pass'),
128
+ 'email' => 'donna@rstad.com'
129
+ ), $result);
130
+ }
131
+
132
+ public function test_createPiwikUserFromLdapUser_FailsToCreatePiwikUser_WhenUIDAttributeIsMissing()
133
+ {
134
+ $this->expectException(Exception::class);
135
+
136
+ $this->userMapper->createPiwikUserFromLdapUser(array(
137
+ 'cn' => 'the impossible girl',
138
+ 'sn' => 'Oswald',
139
+ 'givenname' => 'Clara',
140
+ 'mail' => 'clara@coalhill.co.uk',
141
+ 'userpassword' => 'pass'
142
+ ));
143
+ }
144
+
145
+ public function test_createPiwikUserFromLdapUser_CreatesPiwikUserWithRandomPassword_WhenUserPasswordIsMissing()
146
+ {
147
+ $result = $this->userMapper->createPiwikUserFromLdapUser(array(
148
+ 'uid' => 'clara',
149
+ 'sn' => 'Oswald',
150
+ 'givenname' => 'Clara',
151
+ 'mail' => 'clara@coalhill.co.uk'
152
+ ));
153
+
154
+ $this->assertNotEmpty($result['password']);
155
+ }
156
+
157
+ public function test_createPiwikUserFromLdapUser_SetsCorrectEmail_WhenUserHasNone()
158
+ {
159
+ $result = $this->userMapper->createPiwikUserFromLdapUser(array(
160
+ 'uid' => 'pond',
161
+ 'cn' => 'kissogram',
162
+ 'userpassword' => 'pass'
163
+ ));
164
+
165
+ $this->assertEquals(array(
166
+ 'login' => 'pond',
167
+ 'password' => md5('pass'),
168
+ 'email' => 'pond@mydomain.com'
169
+ ), $result);
170
+
171
+ $this->userMapper->setUserEmailSuffix('@royalleadworthhospital.co.uk');
172
+ $result = $this->userMapper->createPiwikUserFromLdapUser(array(
173
+ 'uid' => 'mrpond',
174
+ 'cn' => 'not quite Bond',
175
+ 'userpassword' => 'pass'
176
+ ));
177
+
178
+ $this->assertEquals(array(
179
+ 'login' => 'mrpond',
180
+ 'password' => md5('pass'),
181
+ 'email' => 'mrpond@royalleadworthhospital.co.uk'
182
+ ), $result);
183
+ }
184
+
185
+ public function test_createPiwikUserEntryForLdapUser_SetsCorrectAlias_WhenUserHasFirstAndLastName()
186
+ {
187
+ $result = $this->userMapper->createPiwikUserFromLdapUser(array(
188
+ 'uid' => 'harkness',
189
+ 'sn' => 'Harkness',
190
+ 'givenname' => 'Captain',
191
+ 'userpassword' => 'pass',
192
+ 'other' => 'sfdklsdjf'
193
+ ));
194
+
195
+ $this->assertEquals(array(
196
+ 'login' => 'harkness',
197
+ 'password' => md5('pass'),
198
+ 'email' => 'harkness@mydomain.com'
199
+ ), $result);
200
+ }
201
+
202
+ public function test_createPiwikUserEntryForLdapUser_CreatesCorrectPiwikUser_IfLdapUserInfoIsAnArray()
203
+ {
204
+ $result = $this->userMapper->createPiwikUserFromLdapUser(array(
205
+ 'uid' => array('rose'),
206
+ 'cn' => array('bad wolf'),
207
+ 'sn' => array('Tyler'),
208
+ 'givenname' => array('Rose'),
209
+ 'mail' => array('rose@linda.com'),
210
+ 'userpassword' => array('pass'),
211
+ 'other' => array('sfdklsdjf)')
212
+ ));
213
+
214
+ $this->assertEquals(array(
215
+ 'login' => 'rose',
216
+ 'password' => md5('pass'),
217
+ 'email' => 'rose@linda.com'
218
+ ), $result);
219
+ }
220
+
221
+ public function test_createPiwikUserEntryForLdapUser_UsesExistingPassword()
222
+ {
223
+ Config::getInstance()->LoginLdap['synchronize_users_after_login'] = 0;
224
+ $existingUser = array(
225
+ 'login' => 'broken',
226
+ 'email' => 'wrongmail',
227
+ 'password' => 'existingpass'
228
+ );
229
+
230
+ $result = $this->userMapper->createPiwikUserFromLdapUser(array(
231
+ 'uid' => 'leela',
232
+ 'cn' => 'Leela of the Sevateem',
233
+ 'mail' => 'leela@gallifrey.???',
234
+ 'userpassword' => 'pass'
235
+ ), $existingUser);
236
+
237
+ $this->assertEquals(array(
238
+ 'login' => 'leela',
239
+ 'password' => 'existingpass',
240
+ 'email' => 'leela@gallifrey.???'
241
+ ), $result);
242
+ }
243
+
244
+ public function test_createPiwikUserEntryForLdapUser_UpdatesExistingPassword()
245
+ {
246
+ Config::getInstance()->LoginLdap['synchronize_users_after_login'] = 1;
247
+ $existingUser = array(
248
+ 'login' => 'broken',
249
+ 'email' => 'wrongmail',
250
+ 'password' => 'existingpass'
251
+ );
252
+
253
+ $result = $this->userMapper->createPiwikUserFromLdapUser(array(
254
+ 'uid' => 'leela',
255
+ 'cn' => 'Leela of the Sevateem',
256
+ 'mail' => 'leela@gallifrey.???',
257
+ 'userpassword' => 'pass'
258
+ ), $existingUser);
259
+
260
+ $this->assertEquals(array(
261
+ 'login' => 'leela',
262
+ 'password' => '1a1dc91c907325c69271ddf0c944bc72',
263
+ 'email' => 'leela@gallifrey.???'
264
+ ), $result);
265
+ Config::getInstance()->LoginLdap['synchronize_users_after_login'] = 0;
266
+ }
267
+
268
+ private function assertUserMapperIsCorrectlyConfigured(UserMapper $userMapper)
269
+ {
270
+ $this->assertEquals('useridfield', $userMapper->getLdapUserIdField());
271
+ $this->assertEquals('mailfield', $userMapper->getLdapMailField());
272
+ $this->assertEquals('passwordfield', $userMapper->getLdapUserPasswordField());
273
+ $this->assertEquals('userEmailSuffix', $userMapper->getUserEmailSuffix());
274
+ }
275
+
276
+ private function assertUserMapperHasCorrectDefaultPropertyValues(UserMapper $userMapper)
277
+ {
278
+ $this->assertEquals('uid', $userMapper->getLdapUserIdField());
279
+ $this->assertEquals('mail', $userMapper->getLdapMailField());
280
+ $this->assertEquals('userpassword', $userMapper->getLdapUserPasswordField());
281
+ $this->assertEquals('@mydomain.com', $userMapper->getUserEmailSuffix());
282
+ }
283
+ }
plugins/LoginLdap/tests/Unit/UserSynchronizerTest.php ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Matomo - free/libre analytics platform
5
+ *
6
+ * @link https://matomo.org
7
+ * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8
+ *
9
+ */
10
+
11
+ namespace Piwik\Plugins\LoginLdap\tests\Unit;
12
+
13
+ use Exception;
14
+ use PHPUnit\Framework\TestCase;
15
+ use Piwik\Access;
16
+ use Piwik\Auth\Password;
17
+ use Piwik\Config;
18
+ use Piwik\Plugins\LoginLdap\LdapInterop\UserSynchronizer;
19
+ use Piwik\Plugins\UsersManager\Model;
20
+ use Piwik\Plugins\UsersManager\UserAccessFilter;
21
+
22
+ /**
23
+ * @group LoginLdap
24
+ * @group LoginLdap_Unit
25
+ * @group LoginLdap_UserSynchronizerTest
26
+ */
27
+ class UserSynchronizerTest extends TestCase
28
+ {
29
+ /**
30
+ * @var UserSynchronizer
31
+ */
32
+ private $userSynchronizer;
33
+
34
+ /**
35
+ * @var array
36
+ */
37
+ public $userAccess;
38
+
39
+ /**
40
+ * @var array
41
+ */
42
+ public $superUserAccess;
43
+
44
+ /**
45
+ * @var array
46
+ */
47
+ public $deleteUserAccess;
48
+ /**
49
+ * @var array
50
+ */
51
+ public $deleteSuperUserAccess;
52
+
53
+ public function setUp(): void
54
+ {
55
+ $this->userSynchronizer = new UserSynchronizer();
56
+ $this->userSynchronizer->setNewUserDefaultSitesWithViewAccess(array(1,2));
57
+ $this->setUserModelMock($this->getPiwikUserData());
58
+ $this->setUserMapperMock($this->getPiwikUserData());
59
+
60
+ $this->userAccess = array();
61
+ $this->superUserAccess = array();
62
+ $this->deleteUserAccess = array();
63
+ $this->deleteSuperUserAccess = array();
64
+
65
+ $config = Config::getInstance()->LoginLdap;
66
+ $config['enable_synchronize_access_from_ldap'] = 1;
67
+ Config::getInstance()->LoginLdap = $config;
68
+ }
69
+
70
+ public function test_makeConfigured_DoesNotThrow_WhenUserMapperCorrectlyConfigured()
71
+ {
72
+ Config::getInstance()->LoginLdap = array(
73
+ 'ldap_user_id_field' => 'userIdField',
74
+ 'ldap_mail_field' => 'mailField',
75
+ 'user_email_suffix' => 'userEmailSuffix',
76
+ );
77
+
78
+ $result = UserSynchronizer::makeConfigured();
79
+ $this->assertNotNull($result);
80
+ }
81
+
82
+ public function test_synchronizeLdapUser_Throws_IfUserMapperCannotCorrectlyCreatePiwikUser()
83
+ {
84
+ $this->expectException(Exception::class);
85
+ $this->expectExceptionMessage('dummy');
86
+
87
+ $this->setUserMapperMock($value = null, $throws = true);
88
+
89
+ $this->userSynchronizer->synchronizeLdapUser('piwikuser', array());
90
+ }
91
+
92
+ public function test_synchronizeLdapUser_ReturnsUserManagerApiResultWithoutPassword()
93
+ {
94
+ $this->setUserManagerApiMock($throws = false);
95
+ $this->setUserModelMock([]);
96
+
97
+ $result = $this->userSynchronizer->synchronizeLdapUser('piwikuser', array());
98
+
99
+ $this->assertTrue(empty($result['password']), "Password set in synchronizeLdapUser result, it shouldn't be.");
100
+ $this->assertEquals(array(
101
+ array('piwikuser', 'view', array(1,2))
102
+ ), $this->userAccess);
103
+ }
104
+
105
+ public function test_synchronizeLdapUser_Throws_IfUserManagerApiThrows()
106
+ {
107
+ $this->expectException(Exception::class);
108
+
109
+ $this->setUserManagerApiMock($throwsInAddUser = true, $throwsInUpdateUser = true);
110
+ $this->setUserModelMock([]);
111
+
112
+ $this->userSynchronizer->synchronizeLdapUser('piwikuser', array());
113
+ }
114
+
115
+ public function test_synchronizeLdapUser_Succeeds_IfUserDoesNotExistInDb()
116
+ {
117
+ $this->setUserManagerApiMock($throws = false);
118
+ $this->setUserModelMock([]);
119
+
120
+ $this->userSynchronizer->synchronizeLdapUser('piwikuser', array());
121
+
122
+ self::assertTrue(true);
123
+ }
124
+
125
+ public function test_synchronizePiwikAccessFromLdap_DoesNotSynchronizeUserAccessOnUpdate_WhenUserAccessMapperNotUsed()
126
+ {
127
+ $this->setUserManagerApiMock($throwsOnAdd = false, $throwsOnUpdate = false, $throwsOnSetAccess = true);
128
+
129
+ $this->userSynchronizer->synchronizePiwikAccessFromLdap('piwikuser', array());
130
+
131
+ self::assertTrue(true);
132
+ }
133
+
134
+ public function test_synchronizePiwikAccessFromLdap_WillSetAccessCorrectly()
135
+ {
136
+ $this->setUserManagerApiMock($throwsOnAdd = false);
137
+ $this->setUserAccessMapperMock(array(
138
+ 'superuser' => array(7,8,9),
139
+ 'view' => array(1,2,3),
140
+ 'admin' => array(4,5,6)
141
+ ));
142
+
143
+ $this->userSynchronizer->synchronizePiwikAccessFromLdap('piwikuser', array());
144
+
145
+ $this->assertEquals(array(
146
+ array('piwikuser', 'view', array(1,2,3)),
147
+ array('piwikuser', 'admin', array(4,5,6))
148
+ ), $this->userAccess);
149
+
150
+ $this->assertEquals(array(
151
+ array('piwikuser', true)
152
+ ), $this->superUserAccess);
153
+ }
154
+
155
+ public function test_synchronizePiwikAccessFromLdap_WillNotRemoveAccessWhenAccessEmptyButSyncDisabled()
156
+ {
157
+ $this->setUserManagerApiMock($throwsOnAdd = false);
158
+ // First iteration returns mapping
159
+ $this->setUserAccessMapperMock(array(
160
+ 'superuser' => array(7,8,9),
161
+ 'view' => array(1,2,3),
162
+ 'admin' => array(4,5,6)
163
+ ));
164
+ $this->userSynchronizer->synchronizePiwikAccessFromLdap('piwikuser', array());
165
+ // Verify access mapping is present
166
+ $this->assertEquals(array(
167
+ array('piwikuser', 'view', array(1,2,3)),
168
+ array('piwikuser', 'admin', array(4,5,6))
169
+ ), $this->userAccess);
170
+ $this->assertEquals(array(
171
+ array('piwikuser', true)
172
+ ), $this->superUserAccess);
173
+
174
+ // Second iteration returns no mapping for the user and since enable_synchronize_access_from_ldap=0, it should do nothing
175
+ $config = Config::getInstance()->LoginLdap;
176
+ $oldValue = $config['enable_synchronize_access_from_ldap'] ?? 0;
177
+ $config['enable_synchronize_access_from_ldap'] = 0;
178
+ Config::getInstance()->LoginLdap = $config;
179
+ $this->setUserAccessMapperMock([]);
180
+ $this->userSynchronizer->synchronizePiwikAccessFromLdap('piwikuser', array());
181
+ $this->assertEmpty($this->deleteUserAccess);
182
+ $this->assertEmpty($this->deleteSuperUserAccess);
183
+
184
+ $config['enable_synchronize_access_from_ldap'] = $oldValue;
185
+ Config::getInstance()->LoginLdap = $config;
186
+ }
187
+
188
+ public function test_synchronizePiwikAccessFromLdap_WillRemoveAccessWhenAccessEmptyAndSyncEnabled()
189
+ {
190
+ $this->setUserManagerApiMock($throwsOnAdd = false);
191
+ // First iteration returns mapping
192
+ $this->setUserAccessMapperMock(array(
193
+ 'superuser' => array(7,8,9),
194
+ 'view' => array(1,2,3),
195
+ 'admin' => array(4,5,6)
196
+ ));
197
+ $this->userSynchronizer->synchronizePiwikAccessFromLdap('piwikuser', array());
198
+ // Verify access mapping is present
199
+ $this->assertEquals(array(
200
+ array('piwikuser', 'view', array(1,2,3)),
201
+ array('piwikuser', 'admin', array(4,5,6))
202
+ ), $this->userAccess);
203
+ $this->assertEquals(array(
204
+ array('piwikuser', true)
205
+ ), $this->superUserAccess);
206
+
207
+ // Second iteration returns no mapping for the user and since enable_synchronize_access_from_ldap=0, it should do nothing
208
+ $config = Config::getInstance()->LoginLdap;
209
+ $oldValue = $config['enable_synchronize_access_from_ldap'] ?? 0;
210
+ $config['enable_synchronize_access_from_ldap'] = 1;
211
+ Config::getInstance()->LoginLdap = $config;
212
+ $this->setUserAccessMapperMock([]);
213
+ $this->userSynchronizer->synchronizePiwikAccessFromLdap('piwikuser', array());
214
+ $this->assertEquals(['piwikuser'], $this->deleteUserAccess);
215
+ $this->assertEquals(['piwikuser'], $this->deleteSuperUserAccess);
216
+
217
+ $config['enable_synchronize_access_from_ldap'] = $oldValue;
218
+ Config::getInstance()->LoginLdap = $config;
219
+ }
220
+
221
+ public function test_synchronizePiwikAccessFromLdap_Succeeds_IfLdapUserHasNoAccess()
222
+ {
223
+ $this->setUserManagerApiMock($throwsOnAdd = false);
224
+ $this->setUserAccessMapperMock(array());
225
+
226
+ $this->userSynchronizer->synchronizePiwikAccessFromLdap('piwikuser', array());
227
+ $this->assertEquals(array(), $this->userAccess);
228
+ $this->assertEquals(array(), $this->superUserAccess);
229
+ }
230
+
231
+ private function setUserManagerApiMock($throwsOnAddUser, $throwsOnUpdateUser = false, $throwsOnSetAccess = false)
232
+ {
233
+ $self = $this;
234
+ $model = new Model();
235
+
236
+ $mock = $this->getMockBuilder('Piwik\Plugins\UsersManager\API')
237
+ ->onlyMethods(array('addUser', 'updateUser', 'getUser', 'setUserAccess', 'setSuperUserAccess'))
238
+ ->setConstructorArgs(array($model, new UserAccessFilter($model, new Access()), new Password()))
239
+ ->getMock();
240
+ if ($throwsOnAddUser) {
241
+ $mock->expects($this->any())->method('addUser')->willThrowException(new Exception("dummy message"));
242
+ } else {
243
+ $mock->expects($this->any())->method('addUser');
244
+ }
245
+ if ($throwsOnSetAccess) {
246
+ $mock->expects($this->any())->method('setUserAccess')->willThrowException(new Exception("dummy message"));
247
+ } else {
248
+ $mock->expects($this->any())->method('setUserAccess')->willReturnCallback(function ($login, $access, $sites) use ($self) {
249
+ $key = array_search($login, $self->deleteUserAccess);
250
+ if ($key !== false) {
251
+ unset($self->deleteUserAccess[$key]);
252
+ $self->deleteUserAccess = array_values($self->deleteUserAccess);
253
+ }
254
+ $self->userAccess[] = array($login, $access, $sites);
255
+ });
256
+ }
257
+
258
+ // for previous version
259
+ $mock->expects($this->any())->method('setSuperUserAccess')->willReturnCallback(function ($login, $hasSuperUserAccess) use ($self) {
260
+ $key = array_search($login, $self->deleteSuperUserAccess);
261
+ if ($key !== false && $hasSuperUserAccess) {
262
+ unset($self->deleteSuperUserAccess[$key]);
263
+ $self->deleteSuperUserAccess = array_values($self->deleteSuperUserAccess);
264
+ }
265
+ $self->superUserAccess[] = array($login, $hasSuperUserAccess);
266
+ });
267
+
268
+ $this->userSynchronizer->setUsersManagerApi($mock);
269
+
270
+ $mock = $this->getMockBuilder('Piwik\Plugins\UsersManager\UserUpdater')
271
+ ->onlyMethods(array('updateUserWithoutCurrentPassword', 'setSuperUserAccessWithoutCurrentPassword'))
272
+ ->getMock();
273
+ if ($throwsOnUpdateUser) {
274
+ $mock->expects($this->any())->method('updateUserWithoutCurrentPassword')->willThrowException(new Exception("dummy message"));
275
+ } else {
276
+ $mock->expects($this->any())->method('updateUserWithoutCurrentPassword');
277
+ }
278
+
279
+ $mock->expects($this->any())->method('setSuperUserAccessWithoutCurrentPassword')->willReturnCallback(function ($login, $hasSuperUserAccess) use ($self) {
280
+ $key = array_search($login, $self->deleteSuperUserAccess);
281
+ if ($key !== false && $hasSuperUserAccess) {
282
+ unset($self->deleteSuperUserAccess[$key]);
283
+ $self->deleteSuperUserAccess = array_values($self->deleteSuperUserAccess);
284
+ }
285
+ $self->superUserAccess[] = array($login, $hasSuperUserAccess);
286
+ });
287
+
288
+ $this->userSynchronizer->setUserUpdater($mock);
289
+ }
290
+
291
+ private function getPiwikUserData()
292
+ {
293
+ return array(
294
+ 'login' => 'piwikuser',
295
+ 'password' => 'password',
296
+ 'email' => 'email'
297
+ );
298
+ }
299
+
300
+ private function setUserMapperMock($value, $throws = false)
301
+ {
302
+ $mock = $this->getMockBuilder('Piwik\Plugins\LoginLdap\LdapInterop\UserMapper')
303
+ ->onlyMethods(array('createPiwikUserFromLdapUser', 'markUserAsLdapUser'))
304
+ ->getMock();
305
+ if ($throws) {
306
+ $mock->expects($this->any())->method('createPiwikUserFromLdapUser')->will($this->throwException(new Exception("dummy")));
307
+ } else {
308
+ $mock->expects($this->any())->method('createPiwikUserFromLdapUser')->will($this->returnValue($value));
309
+ }
310
+ $this->userSynchronizer->setUserMapper($mock);
311
+ }
312
+
313
+ private function setUserAccessMapperMock($value)
314
+ {
315
+ $mock = $this->getMockBuilder('Piwik\Plugins\LoginLdap\LdapInterop\UserAccessMapper')
316
+ ->onlyMethods(array('getPiwikUserAccessForLdapUser'))
317
+ ->getMock();
318
+ $mock->expects($this->any())->method('getPiwikUserAccessForLdapUser')->will($this->returnValue($value));
319
+ $this->userSynchronizer->setUserAccessMapper($mock);
320
+ }
321
+
322
+ private function setUserModelMock($returnValue)
323
+ {
324
+ $mock = $this->getMockBuilder('Piwik\Plugins\UsersManager\Model')
325
+ ->onlyMethods(array('getUser', 'deleteUserAccess', 'setSuperUserAccess'))
326
+ ->getMock();
327
+ $mock->expects($this->any())->method('getUser')->will($this->returnValue($returnValue));
328
+ $self = $this;
329
+ $mock->expects($this->any())->method('deleteUserAccess')->willReturnCallback(function ($login) use ($self) {
330
+ $self->deleteUserAccess[] = $login;
331
+ });
332
+ $mock->expects($this->any())->method('setSuperUserAccess')->willReturnCallback(function ($login, $hasSuperUserAccess) use ($self) {
333
+ if (!$hasSuperUserAccess && !in_array($login, $self->deleteSuperUserAccess)) {
334
+ $self->deleteSuperUserAccess[] = $login;
335
+ }
336
+ });
337
+
338
+ $this->userSynchronizer->setUserModel($mock);
339
+ }
340
+ }
plugins/MarketingCampaignsReporting/.gitattributes ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Files excluded from git packages
2
+ tests/ export-ignore
3
+ .github/ export-ignore
4
+ .gitignore export-ignore
5
+ .gitattributes export-ignore
6
+ .travis.yml export-ignore
plugins/MarketingCampaignsReporting/.github/workflows/matomo-ai-checklist.yml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Action for running tests
2
+
3
+ name: AI Checklist
4
+
5
+ on:
6
+ pull_request:
7
+ types: [opened, synchronize, reopened, edited]
8
+
9
+ permissions:
10
+ actions: read
11
+ checks: none
12
+ contents: none
13
+ deployments: none
14
+ issues: none
15
+ packages: none
16
+ pull-requests: read
17
+ repository-projects: none
18
+ security-events: none
19
+ statuses: none
20
+
21
+ concurrency:
22
+ group: ${{ github.workflow }}-${{ github.ref }}
23
+ cancel-in-progress: true
24
+
25
+ jobs:
26
+ AiChecklist:
27
+ runs-on: ubuntu-24.04
28
+ strategy:
29
+ fail-fast: false
30
+ steps:
31
+ - name: Run tests
32
+ uses: matomo-org/github-action-checklist-gate@main
plugins/MarketingCampaignsReporting/.github/workflows/matomo-tests.yml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Action for running tests
2
+ # This file has been automatically created.
3
+ # To recreate it you can run this command
4
+ # ./console generate:test-action --plugin="MarketingCampaignsReporting" --php-versions="matomo5_min_php,matomo5_max_php" --schedule-cron="55 2 * * 6"
5
+
6
+ name: Plugin MarketingCampaignsReporting Tests
7
+
8
+ on:
9
+ pull_request:
10
+ types: [opened, synchronize]
11
+ push:
12
+ branches:
13
+ - '**.x-dev'
14
+ workflow_dispatch:
15
+ schedule:
16
+ - cron: "55 2 * * 6"
17
+
18
+ permissions:
19
+ actions: read
20
+ checks: none
21
+ contents: read
22
+ deployments: none
23
+ issues: read
24
+ packages: none
25
+ pull-requests: read
26
+ repository-projects: none
27
+ security-events: none
28
+ statuses: none
29
+
30
+ concurrency:
31
+ group: php-${{ github.ref }}
32
+ cancel-in-progress: true
33
+
34
+ jobs:
35
+ PluginTests:
36
+ runs-on: ubuntu-24.04
37
+ strategy:
38
+ fail-fast: false
39
+ matrix:
40
+ php: [ 'matomo5_min_php', 'matomo5_max_php' ]
41
+ target: ['minimum_required_matomo', 'maximum_supported_matomo']
42
+ steps:
43
+ - uses: actions/checkout@v3
44
+ with:
45
+ lfs: true
46
+ persist-credentials: false
47
+ - name: Run tests
48
+ uses: matomo-org/github-action-tests@main
49
+ with:
50
+ plugin-name: 'MarketingCampaignsReporting'
51
+ php-version: ${{ matrix.php }}
52
+ test-type: 'PluginTests'
53
+ matomo-test-branch: ${{ matrix.target }}
54
+ artifacts-pass: ${{ secrets.ARTIFACTS_PASS }}
55
+ upload-artifacts: ${{ matrix.php == 'matomo5_min_php' && matrix.target == 'maximum_supported_matomo' }}
56
+ UI:
57
+ runs-on: ubuntu-24.04
58
+ steps:
59
+ - uses: actions/checkout@v3
60
+ with:
61
+ lfs: true
62
+ persist-credentials: false
63
+ - name: running tests
64
+ uses: matomo-org/github-action-tests@main
65
+ with:
66
+ plugin-name: 'MarketingCampaignsReporting'
67
+ matomo-test-branch: 'maximum_supported_matomo'
68
+ test-type: 'UI'
69
+ php-version: 'matomo5_min_php'
70
+ node-version: '16'
71
+ artifacts-pass: ${{ secrets.ARTIFACTS_PASS }}
72
+ upload-artifacts: true
plugins/MarketingCampaignsReporting/.github/workflows/phpcs.yml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: PHPCS check
2
+
3
+ on: pull_request
4
+
5
+ permissions:
6
+ actions: read
7
+ checks: read
8
+ contents: read
9
+ deployments: none
10
+ issues: read
11
+ packages: none
12
+ pull-requests: read
13
+ repository-projects: none
14
+ security-events: none
15
+ statuses: read
16
+
17
+ jobs:
18
+ phpcs:
19
+ name: PHPCS
20
+ runs-on: ubuntu-24.04
21
+ steps:
22
+ - uses: actions/checkout@v4
23
+ with:
24
+ lfs: false
25
+ persist-credentials: false
26
+ - name: Setup PHP
27
+ uses: shivammathur/setup-php@v2
28
+ with:
29
+ php-version: '7.4'
30
+ tools: cs2pr
31
+ - name: Install dependencies
32
+ run:
33
+ composer init --name=matomo/marketingcampaignsreporting --quiet;
34
+ composer --no-plugins config allow-plugins.dealerdirect/phpcodesniffer-composer-installer true -n;
35
+ composer config repositories.matomo-coding-standards vcs https://github.com/matomo-org/matomo-coding-standards -n;
36
+ composer require matomo-org/matomo-coding-standards:dev-master;
37
+ composer install --dev --prefer-dist --no-progress --no-suggest
38
+ - name: Check PHP code styles
39
+ id: phpcs
40
+ run: ./vendor/bin/phpcs --report-full --standard=phpcs.xml --report-checkstyle=./phpcs-report.xml
41
+ - name: Show PHPCS results in PR
42
+ if: ${{ always() && steps.phpcs.outcome == 'failure' }}
43
+ run: cs2pr ./phpcs-report.xml --prepend-filename
plugins/MarketingCampaignsReporting/.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ /tests/processed/*.xml
2
+ /Test/Integration/processed/*
3
+ /Test/UI/processed-ui-screenshots/
4
+ /tests/System/processed/
5
+ /tests/UI/processed-ui-screenshots/
6
+ .codex