-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathCrawler.java
More file actions
1542 lines (1354 loc) · 60.2 KB
/
Crawler.java
File metadata and controls
1542 lines (1354 loc) · 60.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2008-2019 LabKey Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.labkey.test.util;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.map.CaseInsensitiveMap;
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.commons.lang3.mutable.MutableObject;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.hc.client5.http.classic.methods.HttpHead;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.assertj.core.api.Assertions;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Test;
import org.labkey.remoteapi.collections.CaseInsensitiveHashMap;
import org.labkey.test.BaseWebDriverTest;
import org.labkey.test.ExtraSiteWrapper;
import org.labkey.test.Locator;
import org.labkey.test.Locators;
import org.labkey.test.TestProperties;
import org.labkey.test.WebDriverWrapper;
import org.labkey.test.WebTestHelper;
import org.labkey.test.components.core.ProjectMenu;
import org.labkey.test.util.selenium.WebDriverUtils;
import org.openqa.selenium.UnhandledAlertException;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.labkey.test.WebTestHelper.makeRelativeUrl;
public class Crawler
{
private static final MultiValuedMap<ControllerActionId, String> _parametersInjected = new HashSetValuedHashMap<>();
private static final Set<ControllerActionId> _actionsVisited = new HashSet<>();
private static final Set<ControllerActionId> _actionsWithErrors = new HashSet<>();
private static final Set<String> _urlsChecked = new HashSet<>();
private static final Map<String, CrawlStats> _crawlStats = new LinkedHashMap<>();
private static final Set<ControllerActionId> _controllerFirstUrls = new HashSet<>();
// All parameters seen by the crawler. Used to randomly attempt injection against parameters not found in UI
private static final LinkedHashMap<String,String> _dictionary = new LinkedHashMap<>();
static
{
Arrays.asList("rowid", "name", "userId", "query.sort", "query.rowid~eq", "query.name~contains", "returnUrl")
.forEach(s -> _dictionary.put(s,""));
}
private final List<ControllerActionId> _excludedActions;
private final List<ControllerActionId> _terminalActions;
private final List<ControllerActionId> _actionsExcludedFromInjection;
private final List<ControllerActionId> _actionsMayLinkTo404;
private final List<Function<UrlToCheck, Boolean>> _specialCrawlExclusions;
private final Collection<String> _adminControllers;
private final Collection<String> _forbiddenWords;
private final boolean _prioritizeAdminPages;
private final ArrayList<UrlToCheck> _startingUrls = new ArrayList<>();
private final Duration _maxCrawlTime;
private final BaseWebDriverTest _test;
private final List<String> _warnings = new ArrayList<>();
private final boolean _injectionCheckEnabled;
private final Set<String> _projects = Collections.newSetFromMap(new CaseInsensitiveHashMap<>());
private final Set<String> _urlsVisited = new HashSet<>();
private int _remainingAttemptsToGetProjectLinks = 4;
private int _maxDepth = 4;
public Crawler(BaseWebDriverTest test, Duration crawlTime)
{
this(test, test.getContainerHelper().getCreatedProjects(), crawlTime, false);
}
public Crawler(BaseWebDriverTest test, Duration crawlTime, boolean injectionTest)
{
this(test, test.getContainerHelper().getCreatedProjects(), crawlTime, injectionTest);
}
public Crawler(BaseWebDriverTest test, Collection<String> projects, Duration crawlTime, boolean injectionTest)
{
_test = test;
_maxCrawlTime = crawlTime;
_adminControllers = Collections.unmodifiableCollection(getAdminControllers());
_forbiddenWords = getForbiddenWords();
_excludedActions = getDefaultExcludedActions();
_terminalActions = getDefaultTerminalActions();
_actionsExcludedFromInjection = getExcludedActionsFromInjection();
_actionsMayLinkTo404 = getAllowed404Sources();
_injectionCheckEnabled = injectionTest;
_specialCrawlExclusions = getSpecialCrawlExclusions();
for (String project : projects)
{
addProject(project);
}
if (projects.isEmpty())
{
_startingUrls.add(new UrlToCheck(null, "/admin-showAdmin.view#links", 0));
_startingUrls.add(new UrlToCheck(null, "/admin-spider.view", 2));
}
if (injectionTest)
{
test.getUrlsSeen().stream()
.filter(url -> !StringUtils.isBlank(url))
.map(url -> new UrlToCheck(null, url, 1))
.filter(UrlToCheck::isVisitableURL)
.filter(UrlToCheck::isInjectableURL)
.forEach(_startingUrls::add);
}
_prioritizeAdminPages = projects.isEmpty();
}
protected Set<String> getForbiddenWords()
{
return new HashSet<>();
}
protected List<ControllerActionId> getDefaultExcludedActions()
{
List<ControllerActionId> list = new ArrayList<>();
Collections.addAll(
list,
new ControllerActionId("admin", "actions"), // Gets hit often in normal testing
new ControllerActionId("admin", "addTab"),
new ControllerActionId("admin", "credits"), // Gets checked by BasicTest
new ControllerActionId("admin", "deleteFolder"),
new ControllerActionId("admin", "doCheck"),
new ControllerActionId("admin", "dumpHeap"),
new ControllerActionId("admin", "mapNetworkDrive"), // 404 on non-Windows
new ControllerActionId("admin", "memTracker"),
new ControllerActionId("admin", "queryStackTraces"),
new ControllerActionId("admin", "resetErrorMark"),
new ControllerActionId("admin", "resetQueryStatistics"),
new ControllerActionId("admin", "shortURLAdmin"),
new ControllerActionId("admin", "showAllErrors"),
new ControllerActionId("admin", "showErrorsSinceMark"), // Gets hit often in normal testing
new ControllerActionId("admin", "showPrimaryLog"), // Can take very long to load
new ControllerActionId("admin-sql", "saveReorderedScript"),
new ControllerActionId("assay", "assayDetailRedirect"),
new ControllerActionId("dumbster", "begin"),
new ControllerActionId("filetransfer", "auth"), // redirects to external site
new ControllerActionId("genotyping", "analyze"), // Crawler doesn't like NotFoundException that the test generates
new ControllerActionId("login", "logout"),
new ControllerActionId("login", "setAuthenticationParameter"),
new ControllerActionId("login", "setPassword"),
new ControllerActionId("ms2", "showList"),
new ControllerActionId("ms2", "showParamsFile"),
new ControllerActionId("nlp", "runPipeline"),
new ControllerActionId("pipeline-analysis", "analyze"), // Doesn't navigate
new ControllerActionId("project", "togglePageAdminMode"),
// Tested directly in XTandemTest
new ControllerActionId("protein", "doProteinSearch"),
new ControllerActionId("protein", "pepSearch"), // TODO: Issue 36995: Check for SQL injection in StatementWrapper is not precise enough
new ControllerActionId("publish", "sampleTypePublishConfirm"), // POST-only
new ControllerActionId("publish", "assayPublishConfirm"), // POST-only
new ControllerActionId("query", "printRows"), // Data region print button. 404s on "TargetedMS Runs" grid
new ControllerActionId("reports", "streamFile"),
new ControllerActionId("study", "manageStudyProperties"), // Intermittently triggers form dirty alert
// Disable crawler for single-page apps until we make the crawler able to navigate them
new ControllerActionId("biologics", "app"),
new ControllerActionId("cds", "app"),
new ControllerActionId("samplemanager", "app"),
new ControllerActionId("freezermanager", "app"),
// Actions that error from Admin->GoToModule->MoreModules when module is not enabled
new ControllerActionId("biologics", "begin"),
new ControllerActionId("datafinder", "begin"),
new ControllerActionId("ehr_compliancedb", "requirementDetails"),
new ControllerActionId("onprc_billingpublic", "begin"),
new ControllerActionId("reagent", "begin")
);
for (String controller : getExcludedControllers())
{
list.add(new ControllerActionId(controller, "*"));
}
for (String actionName : getExcludedActionNames())
{
list.add(new ControllerActionId("*", actionName));
}
return list;
}
protected Set<String> getExcludedControllers()
{
Set<String> controllers = Collections.newSetFromMap(new CaseInsensitiveMap<>());
// Don't crawl webdav
controllers.add("_webdav");
controllers.add("_webfiles");
// Don't crawl test modules
controllers.add("chartingapi");
controllers.add("crawlerTest");
controllers.add("editableModule");
controllers.add("ETLtest");
controllers.add("footerTest");
controllers.add("linkedschematest");
controllers.add("miniassay");
controllers.add("pipelinetest");
controllers.add("pipelinetest2");
controllers.add("restrictedModule");
controllers.add("scriptpad");
controllers.add("simpletest");
controllers.add("triggerTestModule");
controllers.add("test");
controllers.add("devtools");
// Don't crawl fake links
controllers.add("fake");
return controllers;
}
private List<Function<UrlToCheck, Boolean>> getSpecialCrawlExclusions()
{
final List<Function<UrlToCheck, Boolean>> urlVisitableChecks = new ArrayList<>();
// Don't crawl pipeline status if it will redirect.
final ControllerActionId pipelineStatusAction = new ControllerActionId("pipeline-status", "details");
urlVisitableChecks.add(url -> pipelineStatusAction.equals(url.getActionId()) && url.getRelativeURL().contains("redirect=1"));
return urlVisitableChecks;
}
protected List<ControllerActionId> getAllowed404Sources()
{
List<ControllerActionId> list = new ArrayList<>();
Collections.addAll(list, spiderAction,
new ControllerActionId("harvest", "begin"));
return list;
}
protected Set<String> getExcludedActionNames()
{
Set<String> actionNames = Collections.newSetFromMap(new CaseInsensitiveMap<>());
actionNames.add("expandCollapse");
return actionNames;
}
// These actions are likely to contain bad links but should, themselves, be crawled and injection checked
protected List<ControllerActionId> getDefaultTerminalActions()
{
List<ControllerActionId> list = new ArrayList<>();
Collections.addAll(list,
new ControllerActionId("admin", "caches"), // Just links to self and 404 pages
new ControllerActionId("core", "styleGuide"), // Contains fake actions for style demonstration
new ControllerActionId("pipeline-status", "showList") // Is likely to contain 404 links
);
return list;
}
protected List<ControllerActionId> getExcludedActionsFromInjection()
{
List<ControllerActionId> list = new ArrayList<>();
Collections.addAll(list,
new ControllerActionId("experiment", "showRunGraphDetail"),
new ControllerActionId("flow", "query"),
new ControllerActionId("flow-attribute", "createAlias"),
new ControllerActionId("flow-attribute", "details"),
new ControllerActionId("flow-attribute", "edit"),
new ControllerActionId("flow-attribute", "summary"),
new ControllerActionId("flow-run", "showRuns")
);
return list;
}
protected Map<ControllerActionId, List<String>> getExcludedParametersFromInjection()
{
Map<ControllerActionId, List<String>> map = new HashMap<>();
// Permanent exclusions
map.put(new ControllerActionId("plate", "designer"), Arrays.asList("colCount", "rowCount")); // 37208: Plate designer dumps stack trace from bad URL parameters
map.put(new ControllerActionId("reports", "runReport"), Arrays.asList(".lastFilter")); // Action triggers a POST, which logs an error. See `ViewServlet.requestActionURL`
map.put(new ControllerActionId("study", "dataset"), Arrays.asList(".lastFilter")); // Action triggers a POST, which logs an error. See `ViewServlet.requestActionURL`
return map;
}
public void addExcludedActions(Collection<ControllerActionId> action)
{
_excludedActions.addAll(action);
}
public void addProject(String project)
{
if (!_projects.contains(project))
{
_projects.add(project);
_startingUrls.add(new UrlToCheck(null, WebTestHelper.buildRelativeUrl("project", project, "start"), 0));
_startingUrls.add(new UrlToCheck(null, WebTestHelper.buildRelativeUrl("admin", project, "spider"), 2));
}
}
protected Collection<String> getAdminControllers()
{
Set<String> adminControllers = Collections.newSetFromMap(new CaseInsensitiveMap<>());
adminControllers.addAll(Arrays.asList("login", "admin", "security", "user"));
return adminControllers;
}
public Set<String> getUrlsVisited()
{
return new HashSet<>(_urlsVisited);
}
protected int getMaxDepth()
{
return _maxDepth;
}
protected int setMaxDepth(int maxDepth)
{
return _maxDepth = maxDepth;
}
public static Map<String, CrawlStats> getCrawlStats()
{
return _crawlStats;
}
public static class CrawlStats
{
private final int _newPages;
private final int _uniqueActions;
private final Duration _crawlTestLength;
private final int _maxDepth;
private final List<String> _warnings;
public CrawlStats(int maxDepth, int newPages, int uniqueActions, Duration crawlTestLength, List<String> warnings)
{
_newPages = newPages;
_uniqueActions = uniqueActions;
_crawlTestLength = crawlTestLength;
_maxDepth = maxDepth;
_warnings = new ArrayList<>(warnings);
}
public int getMaxDepth()
{
return _maxDepth;
}
public int getNewPages()
{
return _newPages;
}
public int getUniqueActions()
{
return _uniqueActions;
}
public Duration getCrawlTestLength()
{
return _crawlTestLength;
}
public List<String> getWarnings()
{
return _warnings;
}
}
private static String getURLBase(URL currentPageURL)
{
String urlString = stripQueryParams(currentPageURL.getPath());
int lastSlashIdx = urlString.lastIndexOf('/');
if (lastSlashIdx > 0)
urlString = urlString.substring(0, lastSlashIdx) + "/";
return urlString;
}
private static String stripQueryParams(String url)
{
int paramIdx = url.indexOf('?');
if (paramIdx > 0)
url = url.substring(0, paramIdx);
return url;
}
private static String stripHash(String url)
{
int paramIdx = url.indexOf('#');
if (paramIdx > 0)
url = url.substring(0, paramIdx);
return url;
}
private class UrlToCheck
{
public final float priority;
// Keep track of urls to check for breadth first crawl
private final URL _origin;
private final String _urlText;
private final String _relativeURL;
private final ControllerActionId _actionId;
private final int _depth;
private boolean _isFromForm = false;
public UrlToCheck(final URL origin, final String urlText, final int depth)
{
if (depth < 0)
{
throw new IllegalArgumentException("Invalid crawl depth: " + depth);
}
_origin = origin;
_urlText = urlText;
_depth = depth;
if (isLabKeyShortUrl(urlText)) // Don't crawl short URLs
{
_relativeURL = null;
}
else if (isAbsoluteUrl(urlText)) // Make sure it is a link to the site under test
{
String relativeURL;
try
{
relativeURL = WebTestHelper.makeRelativeUrl(urlText);
}
catch (IllegalArgumentException iae)
{
relativeURL = null;
}
_relativeURL = StringUtils.trimToNull(relativeURL);
}
else
{
// Make sure it is correctly formatted
if (urlText.startsWith("/"))
_relativeURL = urlText.substring(1);
else if (urlText.startsWith("#"))
_relativeURL = makeRelativeUrl(stripHash(origin.toString())) + urlText;
else if (urlText.startsWith("?"))
_relativeURL = makeRelativeUrl(stripQueryParams(origin.toString())) + urlText;
else
_relativeURL = makeRelativeUrl(getURLBase(origin)) + urlText;
}
if (_relativeURL != null)
{
ControllerActionId tempActionId = null;
try
{
tempActionId = new ControllerActionId(_relativeURL);
}
catch (IllegalArgumentException badUrl) {
if (!isAbsoluteUrl(urlText))
{
throw badUrl; // We should know how to handle all relative URLs
}
}
_actionId = tempActionId;
}
else
{
_actionId = null;
}
int p = _depth;
if (underCreatedProject())
p--;
// demote admin controllers
if (null != getActionId() && _adminControllers.contains(getActionId().getController()))
p += (_prioritizeAdminPages ? -1 : 1);
// demote root directory
if (null != getActionId() && StringUtils.isBlank(StringUtils.strip(getActionId().getContainerPath(),"/")))
p += (_prioritizeAdminPages ? -1 : 1);
priority = p + random.nextFloat();
checkControllerRelativeUrl();
try
{
isVisitableURL();
}
catch (RuntimeException ex)
{
// Get a more useful exception if we hit a URL that we REALLY don't understand
throw new IllegalArgumentException("Failed to parse action from URL [%s] found on page [%s]".formatted(getUrlText(), getOrigin()), ex);
}
}
private static boolean isAbsoluteUrl(String urlText)
{
return urlText.startsWith("http://") ||
urlText.startsWith("https://") ||
urlText.startsWith("javascript:") ||
urlText.startsWith("ftp://");
}
private boolean isLabKeyShortUrl(String urlText)
{
return urlText.endsWith(".url") && (urlText.startsWith(WebTestHelper.getBaseURL()) || !isAbsoluteUrl(urlText));
}
public boolean isFromForm()
{
return _isFromForm;
}
public UrlToCheck setFromForm(boolean fromForm)
{
_isFromForm = fromForm;
return this;
}
public URL getOrigin()
{
return _origin;
}
public String getUrlText()
{
return _urlText;
}
public int getDepth()
{
return _depth;
}
public String getRelativeURL()
{
return _relativeURL;
}
public ControllerActionId getActionId()
{
return _actionId;
}
public boolean underCreatedProject()
{
if (null == getActionId())
return false;
String folder = StringUtils.strip(getActionId().getContainerPath(), "/");
StringTokenizer st = new StringTokenizer(folder, "/");
if (!st.hasMoreElements())
return false;
String currentProject = st.nextToken();
if (StringUtils.isEmpty(currentProject))
return false;
return _projects.contains(currentProject);
}
private void checkControllerRelativeUrl()
{
if (_actionId != null && _actionId.isControllerFirstUrl() && WebTestHelper.isUseContainerRelativeUrl() && !_controllerFirstUrls.contains(_actionId))
{
_controllerFirstUrls.add(_actionId);
RuntimeException ex = new RuntimeException("Found a controller-first URL (%s) on %s".formatted(getUrlText(), getOrigin()));
if (TestProperties.isControllerFirstUrlFatal())
throw ex;
else
TestLogger.warn(ex.getMessage(), ex);
}
}
public boolean isVisitableURL()
{
if (StringUtils.isBlank(getRelativeURL()))
return false;
String strippedRelativeURL = stripQueryParams(getRelativeURL());
// never go to the exact same URL (minus query params) twice:
if (_urlsChecked.contains(EscapeUtil.decodeUriPath(strippedRelativeURL)))
return false;
if (getRelativeURL().contains("export=")) //Study report export uses same URL for export. But don't mark visited yet
return false;
if (getRelativeURL().contains("mailto:")) //Don't crawl mailto: links
return false;
if (getRelativeURL().contains("javascript:")) //Don't crawl javascript: links
return false;
// after navigating past the first N levels of links, we'll only try "new" actions:
if (getDepth() >= getMaxDepth() && _actionsVisited.contains(getActionId()))
return false;
if (spiderAction.equals(getActionId()) && TestProperties.isPrimaryUserAppAdmin())
return false; // SpiderAction is inaccessible to app admin
// Don't let a single bad action fail multiple tests
if (_actionsWithErrors.contains(getActionId()))
return false;
// never visit explicitly excluded actions:
if (_excludedActions.contains(getActionId()))
return false;
//skip excluded controllers
if (_excludedActions.contains(new ControllerActionId(getActionId().getController(), "*")))
return false;
// skip universally excluded actions.
if (_excludedActions.contains(new ControllerActionId("*", getActionId().getAction())))
return false;
// in addition to test projects, we'll crawl all admin functionality as well
// (otherwise this never gets covered).
if (_adminControllers.contains(getActionId().getController()) && !"home".equals(getActionId().getContainerPath()))
return true;
for (Function<UrlToCheck, Boolean> check : _specialCrawlExclusions)
{
// Exclude particular URLs based on other conditions
if (check.apply(this))
{
return false;
}
}
// always visit all links under projects created by the tests:
return underCreatedProject();
}
private boolean isInjectableURL()
{
return !_actionsExcludedFromInjection.contains(getActionId());
}
}
public static class ControllerActionId
{
@NotNull private final String _controller;
@NotNull private String _action = "";
private final String _containerPath;
private final boolean _controllerFirstUrl;
public ControllerActionId(@NotNull String controller, @NotNull String action)
{
_controller = controller;
_action = action;
_containerPath = null;
_controllerFirstUrl = false;
}
public ControllerActionId(@NotNull String url)
{
String rootRelativeURL = WebTestHelper.makeRelativeUrl(stripQueryParams(stripHash(url)));
if (rootRelativeURL.startsWith("_webdav/"))
{
_controllerFirstUrl = false;
_controller = "_webdav";
String path = EscapeUtil.decode(rootRelativeURL.substring("_webdav/".length()));
if (path.startsWith("@"))
{
_containerPath = "";
_action = path;
}
else
{
String[] splitPath = path.split("/@", 2); // container names can't begin with '@'
_containerPath = splitPath[0];
if (splitPath.length > 1)
{
_action = "@" + splitPath[1]; // Include file path as "action". e.g. "@files/folder/sample.txt"
}
}
return;
}
if (rootRelativeURL.startsWith("_webfiles/"))
{
_controllerFirstUrl = false;
_controller = "_webfiles";
_containerPath = EscapeUtil.decode(rootRelativeURL.substring("_webfiles/".length()));
return;
}
int actionIdx = rootRelativeURL.lastIndexOf('/');
String action = rootRelativeURL.substring(actionIdx + 1);
if (action.endsWith(".view") || action.endsWith(".api") || action.endsWith(".post"))
{
_action = action.substring(0,action.lastIndexOf("."));
rootRelativeURL = rootRelativeURL.substring(0, actionIdx+1);
}
else
{
_action = "";
}
if (_action.contains("-"))
{
/* folder/controller-action */
int dash = _action.lastIndexOf("-");
_controller = _action.substring(0,dash);
_action = _action.substring(dash+1);
_controllerFirstUrl = false;
}
else
{
/* controller/folders/action */
int postControllerSlashIdx = rootRelativeURL.indexOf('/');
if (-1 == postControllerSlashIdx)
throw new IllegalArgumentException("Unable to parse folder out of relative URL: \"" + rootRelativeURL + "\"");
_controller = rootRelativeURL.substring(0, postControllerSlashIdx);
rootRelativeURL = rootRelativeURL.substring(postControllerSlashIdx+1);
_controllerFirstUrl = true;
}
_containerPath = EscapeUtil.decode(StringUtils.strip(rootRelativeURL, "/"));
}
@NotNull public String getAction()
{
return _action;
}
@NotNull public String getController()
{
return _controller;
}
/**
* Folder is parsed out for convenience only. Is ignored for equality and hash calculations.
* @return decoded containerPath from parsed URL, with no leading or trailing '/'. `null` if instance was not generated from a URL.
*/
@Nullable
public String getContainerPath()
{
return _containerPath;
}
/**
* Allows us to track down pages that still create controller-first URLs
*/
public boolean isControllerFirstUrl()
{
return _controllerFirstUrl;
}
@Override
public String toString()
{
return _controller + "-" + _action;
}
@Override
public int hashCode()
{
return Objects.hash(_controller.toLowerCase(), _action.toLowerCase());
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ControllerActionId that = (ControllerActionId) o;
return _controller.equalsIgnoreCase(that._controller) &&
_action.equalsIgnoreCase(that._action);
}
}
@LogMethod
public void crawlAllLinks()
{
// quick unit-test
new ControllerActionIdTest().testControllerActionIdParsing();
TestLogger.log("Starting crawl...");
// Breadth first search
CrawlStats crawlStats = crawl();
_crawlStats.put(_test.getClass().getSimpleName(), crawlStats);
TestLogger.log("Crawl complete. " + crawlStats.getNewPages() + " pages visited, " + _actionsVisited.size() + " unique actions tested by all tests.");
_dictionary.keySet().forEach(TestLogger::debug);
TestLogger.debug("Injected:");
TestLogger.increaseIndent();
for (ControllerActionId aid : _parametersInjected.keySet())
{
TestLogger.debug(aid.toString());
TestLogger.increaseIndent();
for (String param : _parametersInjected.get(aid))
{
TestLogger.debug(param);
}
TestLogger.decreaseIndent();
}
TestLogger.decreaseIndent();
}
private CrawlStats crawl()
{
// Breadth first crawl
int linkCount = 0;
int maxDepth = 0;
final Timer crawlTimer = new Timer(_maxCrawlTime);
PriorityQueue<UrlToCheck> urlsToCheck = new PriorityQueue<>(Comparator.comparingDouble(u -> u.priority));
urlsToCheck.addAll(_startingUrls);
// Loop through links in list until its empty or time runs out
while (!urlsToCheck.isEmpty() && !crawlTimer.isTimedOut())
{
UrlToCheck urlToCheck = urlsToCheck.poll();
if (urlToCheck != null && urlToCheck.isVisitableURL())
{
maxDepth = Math.max(urlToCheck.getDepth(), maxDepth);
urlsToCheck.addAll(crawlLink(urlToCheck));
linkCount++;
}
}
return new CrawlStats(maxDepth, linkCount, _actionsVisited.size(), crawlTimer.elapsed(), _warnings);
}
@LogMethod
public void validatePage(@LoggedParam String url)
{
crawlLink(new UrlToCheck(null, url, 0));
}
/**
* Open the specified URL in the current browser
* @param relativeUrl URL to navigate to
* @return 'true' if opening the URL navigated
*/
private boolean beginAt(String relativeUrl)
{
_urlsVisited.add(relativeUrl);
// Escape brackets to prevent 400 errors
relativeUrl = relativeUrl
.replace("[", "%5B")
.replace("]", "%5D")
.replace("{", "%7B")
.replace("}", "%7D");
relativeUrl = makeRelativeUrl(relativeUrl);
String logMessage = "";
Mutable<File[]> downloadedFiles = new MutableObject<>();
try
{
String messagePrefix = "Navigating to ";
if (relativeUrl.isEmpty())
{
logMessage = messagePrefix + "root";
}
else
{
logMessage = messagePrefix + relativeUrl;
if (relativeUrl.charAt(0) != '/')
{
relativeUrl = "/" + relativeUrl;
}
}
final String fullURL = WebTestHelper.getBaseURL() + relativeUrl;
Mutable<Boolean> navigated = new MutableObject<>(true);
final File downloadDir = BaseWebDriverTest.getDownloadDir();
final File[] existingDownloads = downloadDir.listFiles();
long elapsedTime = _test.doAndMaybeWaitForPageToLoad(WebDriverWrapper.WAIT_FOR_PAGE, () -> {
final String initialUrl = _test.getDriver().getCurrentUrl();
final WebElement mightGoStale = Locators.documentRoot.findElement(_test.getDriver());
ExpectedCondition<Boolean> stalenessOf = ExpectedConditions.stalenessOf(mightGoStale);
// 'getDriver().navigate().to(fullURL)' assumes navigation and fails for file downloads
_test.executeScript("document.location = arguments[0]", fullURL);
if (!WebDriverWrapper.waitFor(() -> {
boolean stale;
try
{
stale = stalenessOf.apply(null);
}
catch (NullPointerException npe)
{
// Staleness check throws NPE sometimes when there's an alert present
_test.executeScript("return;"); // Try to trigger 'UnhandledAlertException'
return false;
}
if (stale)
{
// Wait for page to load when element goes stale
return true; // Stop waiting
}
else if (downloadDir.isDirectory()) // Don't check for download if dir doesn't exist
{
File[] filesArray = WebDriverWrapper.getNewFiles(0, downloadDir, existingDownloads);
downloadedFiles.setValue(filesArray);
if (downloadedFiles.getValue().length > 0)
{
navigated.setValue(false); // Don't wait for page load when a download occurs
return true; // Stop waiting
}
}
String currentUrl = _test.getDriver().getCurrentUrl();
if (!currentUrl.equals(initialUrl) && stripHash(currentUrl).equals(stripHash(initialUrl)))
{
// URL changed without document going stale.
// Probably a single-page app navigation or page anchor navigation.
navigated.setValue(false);
return true; // Stop waiting
}
return false; // No navigation or download detected. Continue waiting.
}, WebDriverWrapper.WAIT_FOR_PAGE))
{
TestLogger.warn("URL didn't trigger a download or navigation: " + fullURL);
}
return navigated.getValue();
});
if (!navigated.getValue())
{
logMessage = logMessage.replace(messagePrefix, "Downloading from ");
}
logMessage += TestLogger.formatElapsedTime(elapsedTime);
return navigated.getValue();
}
finally
{
TestLogger.info(logMessage); // log after navigation to
if (downloadedFiles.getValue() != null)
{
Arrays.stream(downloadedFiles.getValue()).forEach(file -> {
TestLogger.info(" \u2517" + file.getName()); // Log downloaded files
FileUtils.deleteQuietly(file); // Clean up crawled downloads
});
}
}
}
private List<UrlToCheck> crawlLink(final UrlToCheck urlToCheck)
{
String relativeURL = urlToCheck.getRelativeURL();
ControllerActionId actionId = new ControllerActionId(relativeURL);
URL actualUrl; // URL might redirect
boolean navigated = true; // URL might download