Skip to content

Commit 56c2b96

Browse files
patryk-kucharzpivovarit
authored andcommitted
BAEL-2165 (eugenp#5317)
* BAEL-2165: Guide to Passay * BAEL-2165: Guide to Passay eugenp#2 * BAEL-2165: Guide to Passay eugenp#3 Fixed formatting.
1 parent 51914a0 commit 56c2b96

6 files changed

Lines changed: 368 additions & 0 deletions

File tree

‎libraries-security/pom.xml‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,16 @@
3838
<version>${junit.version}</version>
3939
<scope>test</scope>
4040
</dependency>
41+
<dependency>
42+
<groupId>org.passay</groupId>
43+
<artifactId>passay</artifactId>
44+
<version>1.3.1</version>
45+
</dependency>
46+
<dependency>
47+
<groupId>org.cryptacular</groupId>
48+
<artifactId>cryptacular</artifactId>
49+
<version>1.2.2</version>
50+
</dependency>
4151

4252
</dependencies>
4353

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
package com.baeldung.passay;
2+
3+
import org.cryptacular.bean.EncodingHashBean;
4+
import org.cryptacular.spec.CodecSpec;
5+
import org.cryptacular.spec.DigestSpec;
6+
import org.junit.Assert;
7+
import org.junit.Test;
8+
import org.passay.DictionaryRule;
9+
import org.passay.DictionarySubstringRule;
10+
import org.passay.DigestHistoryRule;
11+
import org.passay.EnglishSequenceData;
12+
import org.passay.HistoryRule;
13+
import org.passay.IllegalCharacterRule;
14+
import org.passay.IllegalRegexRule;
15+
import org.passay.IllegalSequenceRule;
16+
import org.passay.NumberRangeRule;
17+
import org.passay.PasswordData;
18+
import org.passay.PasswordValidator;
19+
import org.passay.RepeatCharacterRegexRule;
20+
import org.passay.RuleResult;
21+
import org.passay.SourceRule;
22+
import org.passay.UsernameRule;
23+
import org.passay.WhitespaceRule;
24+
import org.passay.dictionary.ArrayWordList;
25+
import org.passay.dictionary.WordListDictionary;
26+
27+
import java.util.Arrays;
28+
import java.util.List;
29+
30+
import static org.junit.Assert.assertEquals;
31+
import static org.junit.Assert.assertFalse;
32+
33+
public class NegativeMatchingRulesUnitTest {
34+
35+
@Test
36+
public void givenDictionaryRules_whenValidatePassword_thenFoundIllegalWordsFromDictionary() {
37+
ArrayWordList arrayWordList = new ArrayWordList(new String[] { "bar", "foobar" });
38+
39+
WordListDictionary wordListDictionary = new WordListDictionary(arrayWordList);
40+
41+
DictionaryRule dictionaryRule = new DictionaryRule(wordListDictionary);
42+
DictionarySubstringRule dictionarySubstringRule = new DictionarySubstringRule(wordListDictionary);
43+
44+
PasswordValidator passwordValidator = new PasswordValidator(dictionaryRule, dictionarySubstringRule);
45+
RuleResult validate = passwordValidator.validate(new PasswordData("foobar"));
46+
47+
assertFalse(validate.isValid());
48+
assertEquals("ILLEGAL_WORD:{matchingWord=foobar}", getDetail(validate, 0));
49+
assertEquals("ILLEGAL_WORD:{matchingWord=bar}", getDetail(validate, 1));
50+
}
51+
52+
@Test
53+
public void givenHistoryRule_whenValidatePassword_thenFoundIllegalWordsFromHistory() {
54+
HistoryRule historyRule = new HistoryRule();
55+
56+
PasswordData passwordData = new PasswordData("123");
57+
passwordData.setPasswordReferences(new PasswordData.HistoricalReference("12345"), new PasswordData.HistoricalReference("1234"), new PasswordData.HistoricalReference("123"));
58+
59+
PasswordValidator passwordValidator = new PasswordValidator(historyRule);
60+
61+
RuleResult validate = passwordValidator.validate(passwordData);
62+
63+
assertFalse(validate.isValid());
64+
assertEquals("HISTORY_VIOLATION:{historySize=3}", getDetail(validate, 0));
65+
}
66+
67+
@Test
68+
public void givenSeveralIllegalRules_whenValidatePassword_thenFoundSeveralIllegalPatterns() {
69+
IllegalCharacterRule illegalCharacterRule = new IllegalCharacterRule(new char[] { 'a' });
70+
IllegalRegexRule illegalRegexRule = new IllegalRegexRule("\\w{2}\\d{2}");
71+
IllegalSequenceRule illegalSequenceRule = new IllegalSequenceRule(EnglishSequenceData.Alphabetical, 3, true);
72+
NumberRangeRule numberRangeRule = new NumberRangeRule(1, 10);
73+
WhitespaceRule whitespaceRule = new WhitespaceRule();
74+
75+
PasswordValidator passwordValidator = new PasswordValidator(illegalCharacterRule, illegalRegexRule, illegalSequenceRule, numberRangeRule, whitespaceRule);
76+
77+
RuleResult validate = passwordValidator.validate(new PasswordData("abcd22 "));
78+
79+
assertFalse(validate.isValid());
80+
assertEquals("ILLEGAL_CHAR:{illegalCharacter=a, matchBehavior=contains}", getDetail(validate, 0));
81+
assertEquals("ILLEGAL_MATCH:{match=cd22, pattern=\\w{2}\\d{2}}", getDetail(validate, 1));
82+
assertEquals("ILLEGAL_ALPHABETICAL_SEQUENCE:{sequence=abc}", getDetail(validate, 2));
83+
assertEquals("ILLEGAL_ALPHABETICAL_SEQUENCE:{sequence=bcd}", getDetail(validate, 3));
84+
assertEquals("ILLEGAL_NUMBER_RANGE:{number=2, matchBehavior=contains}", getDetail(validate, 4));
85+
assertEquals("ILLEGAL_WHITESPACE:{whitespaceCharacter= , matchBehavior=contains}", getDetail(validate, 5));
86+
}
87+
88+
@Test
89+
public void givenSourceRule_whenValidatePassword_thenFoundIllegalWordsFromSource() {
90+
SourceRule sourceRule = new SourceRule();
91+
92+
PasswordData passwordData = new PasswordData("password");
93+
passwordData.setPasswordReferences(new PasswordData.SourceReference("source", "password"));
94+
95+
PasswordValidator passwordValidator = new PasswordValidator(sourceRule);
96+
RuleResult validate = passwordValidator.validate(passwordData);
97+
98+
assertFalse(validate.isValid());
99+
assertEquals("SOURCE_VIOLATION:{source=source}", getDetail(validate, 0));
100+
}
101+
102+
@Test
103+
public void givenRepeatCharacterRegexRuleRule_whenValidatePassword_thenFoundIllegalPatternMatches() {
104+
RepeatCharacterRegexRule repeatCharacterRegexRule = new RepeatCharacterRegexRule(3);
105+
106+
PasswordValidator passwordValidator = new PasswordValidator(repeatCharacterRegexRule);
107+
108+
RuleResult validate = passwordValidator.validate(new PasswordData("aaabbb"));
109+
110+
assertFalse(validate.isValid());
111+
assertEquals("ILLEGAL_MATCH:{match=aaa, pattern=([^\\x00-\\x1F])\\1{2}}", getDetail(validate, 0));
112+
assertEquals("ILLEGAL_MATCH:{match=bbb, pattern=([^\\x00-\\x1F])\\1{2}}", getDetail(validate, 1));
113+
}
114+
115+
@Test
116+
public void givenUserNameRule_whenValidatePassword_thenFoundUserNameInPassword() {
117+
PasswordValidator passwordValidator = new PasswordValidator(new UsernameRule());
118+
119+
PasswordData passwordData = new PasswordData("testuser1234");
120+
passwordData.setUsername("testuser");
121+
122+
RuleResult validate = passwordValidator.validate(passwordData);
123+
124+
assertFalse(validate.isValid());
125+
assertEquals("ILLEGAL_USERNAME:{username=testuser, matchBehavior=contains}", getDetail(validate, 0));
126+
}
127+
128+
@Test
129+
public void givenPasswordAndHashBeanAndEncryptedReferences_whenValidate_thenPasswordValidationShouldPass() {
130+
List<PasswordData.Reference> historicalReferences = Arrays.asList(new PasswordData.HistoricalReference("SHA256", "2e4551de804e27aacf20f9df5be3e8cd384ed64488b21ab079fb58e8c90068ab"));
131+
PasswordData passwordData = new PasswordData("example!");
132+
passwordData.setPasswordReferences(historicalReferences);
133+
134+
EncodingHashBean encodingHashBean = new EncodingHashBean(new CodecSpec("Base64"), new DigestSpec("SHA256"), 1, false);
135+
136+
PasswordValidator passwordValidator = new PasswordValidator(new DigestHistoryRule(encodingHashBean));
137+
138+
RuleResult validate = passwordValidator.validate(passwordData);
139+
140+
Assert.assertTrue(validate.isValid());
141+
}
142+
143+
private String getDetail(RuleResult validate, int i) {
144+
return validate.getDetails()
145+
.get(i)
146+
.toString();
147+
}
148+
149+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.baeldung.passay;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
import org.passay.CharacterData;
6+
import org.passay.CharacterRule;
7+
import org.passay.EnglishCharacterData;
8+
import org.passay.PasswordGenerator;
9+
10+
import java.util.stream.Stream;
11+
12+
public class PasswordGeneratorUnitTest {
13+
14+
@Test
15+
public void givenDigitsGenerator_whenGeneratingPassword_thenPasswordContainsDigitsHasLength10() {
16+
CharacterRule digits = new CharacterRule(EnglishCharacterData.Digit);
17+
18+
PasswordGenerator passwordGenerator = new PasswordGenerator();
19+
String password = passwordGenerator.generatePassword(10, digits);
20+
21+
Assert.assertTrue(password.length() == 10);
22+
Assert.assertTrue(containsOnlyCharactersFromSet(password, "0123456789"));
23+
}
24+
25+
@Test
26+
public void givenCustomizedRule_whenGenerating_thenGeneratedPasswordContainsCustomizedCharacters() {
27+
CharacterRule specialCharacterRule = new CharacterRule(new CharacterData() {
28+
@Override
29+
public String getErrorCode() {
30+
return "SAMPLE_ERROR_CODE";
31+
}
32+
33+
@Override
34+
public String getCharacters() {
35+
return "ABCxyz123!@#";
36+
}
37+
});
38+
39+
PasswordGenerator passwordGenerator = new PasswordGenerator();
40+
String password = passwordGenerator.generatePassword(10, specialCharacterRule);
41+
42+
Assert.assertTrue(containsOnlyCharactersFromSet(password, "ABCxyz123!@#"));
43+
}
44+
45+
private boolean containsOnlyCharactersFromSet(String password, String setOfCharacters) {
46+
return Stream.of(password.split(""))
47+
.allMatch(it -> setOfCharacters.contains(it));
48+
}
49+
50+
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package com.baeldung.passay;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
import org.passay.LengthRule;
6+
import org.passay.MessageResolver;
7+
import org.passay.PasswordData;
8+
import org.passay.PasswordValidator;
9+
import org.passay.PropertiesMessageResolver;
10+
import org.passay.RuleResult;
11+
import org.passay.RuleResultDetail;
12+
import org.passay.RuleResultMetadata;
13+
import org.passay.WhitespaceRule;
14+
15+
import java.io.FileInputStream;
16+
import java.io.IOException;
17+
import java.net.URL;
18+
import java.util.Properties;
19+
20+
import static org.junit.Assert.assertEquals;
21+
import static org.junit.Assert.assertFalse;
22+
23+
public class PasswordValidatorUnitTest {
24+
25+
@Test
26+
public void givenPasswordValidatorWithLengthRule_whenValidation_thenTooShortPassword() {
27+
PasswordData passwordData = new PasswordData("1234");
28+
29+
PasswordValidator passwordValidator = new PasswordValidator(new LengthRule(5));
30+
31+
RuleResult validate = passwordValidator.validate(passwordData);
32+
assertEquals(false, validate.isValid());
33+
34+
RuleResultDetail ruleResultDetail = validate.getDetails()
35+
.get(0);
36+
assertEquals("TOO_SHORT", ruleResultDetail.getErrorCode());
37+
assertEquals(5, ruleResultDetail.getParameters()
38+
.get("minimumLength"));
39+
assertEquals(5, ruleResultDetail.getParameters()
40+
.get("maximumLength"));
41+
42+
Integer lengthCount = validate.getMetadata()
43+
.getCounts()
44+
.get(RuleResultMetadata.CountCategory.Length);
45+
assertEquals(Integer.valueOf(4), lengthCount);
46+
}
47+
48+
@Test
49+
public void givenPasswordValidatorWithLengthRule_whenValidation_thenTooLongPassword() {
50+
PasswordData passwordData = new PasswordData("123456");
51+
52+
PasswordValidator passwordValidator = new PasswordValidator(new LengthRule(5));
53+
54+
RuleResult validate = passwordValidator.validate(passwordData);
55+
assertFalse(validate.isValid());
56+
Assert.assertEquals("TOO_LONG", validate.getDetails()
57+
.get(0)
58+
.getErrorCode());
59+
}
60+
61+
@Test
62+
public void givenPasswordValidatorWithLengthRule_whenValidation_thenCustomizedMeesagesAvailable() throws IOException {
63+
URL resource = this.getClass()
64+
.getClassLoader()
65+
.getResource("messages.properties");
66+
Properties props = new Properties();
67+
props.load(new FileInputStream(resource.getPath()));
68+
69+
MessageResolver resolver = new PropertiesMessageResolver(props);
70+
PasswordValidator validator = new PasswordValidator(resolver, new LengthRule(8, 16), new WhitespaceRule());
71+
72+
RuleResult tooShort = validator.validate(new PasswordData("XXXX"));
73+
RuleResult tooLong = validator.validate(new PasswordData("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"));
74+
75+
assertEquals("Password must not contain less characters than 16.", validator.getMessages(tooShort)
76+
.get(0));
77+
assertEquals("Password must not have more characters than 16.", validator.getMessages(tooLong)
78+
.get(0));
79+
}
80+
81+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.baeldung.passay;
2+
3+
import org.junit.Test;
4+
import org.passay.AllowedCharacterRule;
5+
import org.passay.AllowedRegexRule;
6+
import org.passay.CharacterCharacteristicsRule;
7+
import org.passay.CharacterRule;
8+
import org.passay.EnglishCharacterData;
9+
import org.passay.LengthComplexityRule;
10+
import org.passay.LengthRule;
11+
import org.passay.PasswordData;
12+
import org.passay.PasswordValidator;
13+
import org.passay.RuleResult;
14+
15+
import static org.junit.Assert.*;
16+
17+
public class PositiveMatchingRulesUnitTest {
18+
19+
@Test
20+
public void givenPasswordValidationRules_whenValidatingPassword_thenPosswordIsNotValidWithSeveralErrors() {
21+
PasswordValidator passwordValidator = new PasswordValidator(new AllowedCharacterRule(new char[] { 'a', 'b', 'c' }), new AllowedRegexRule("\\d{2}\\w{10}"), new CharacterRule(EnglishCharacterData.LowerCase, 5), new LengthRule(8, 10));
22+
23+
RuleResult validate = passwordValidator.validate(new PasswordData("12abc"));
24+
25+
assertFalse(validate.isValid());
26+
assertEquals("ALLOWED_CHAR:{illegalCharacter=1, matchBehavior=contains}", getDetail(validate, 0));
27+
assertEquals("ALLOWED_CHAR:{illegalCharacter=2, matchBehavior=contains}", getDetail(validate, 1));
28+
assertEquals("ALLOWED_MATCH:{pattern=\\d{2}\\w{10}}", getDetail(validate, 2));
29+
assertEquals("INSUFFICIENT_LOWERCASE:{" + "minimumRequired=5, matchingCharacterCount=3, " + "validCharacters=abcdefghijklmnopqrstuvwxyz, " + "matchingCharacters=abc}", getDetail(validate, 3));
30+
assertEquals("TOO_SHORT:{minimumLength=8, maximumLength=10}", getDetail(validate, 4));
31+
}
32+
33+
@Test
34+
public void givenRulesForDifferentPasswordLength_whenValidatingTwoDifferentPassword_thenBothOfThemAreInvalid() {
35+
PasswordData shortPassword = new PasswordData("12ab");
36+
PasswordData longPassword = new PasswordData("1234abcde");
37+
38+
LengthComplexityRule lengthComplexityRule = new LengthComplexityRule();
39+
lengthComplexityRule.addRules("[1,5]", new CharacterRule(EnglishCharacterData.LowerCase, 5));
40+
lengthComplexityRule.addRules("[6,10]", new AllowedCharacterRule(new char[] { 'a', 'b', 'c', 'd' }));
41+
42+
PasswordValidator passwordValidator = new PasswordValidator(lengthComplexityRule);
43+
44+
RuleResult validateShort = passwordValidator.validate(shortPassword);
45+
RuleResult validateLong = passwordValidator.validate(longPassword);
46+
47+
assertFalse(validateShort.isValid());
48+
assertFalse(validateLong.isValid());
49+
50+
assertEquals("INSUFFICIENT_LOWERCASE:{" + "minimumRequired=5, " + "matchingCharacterCount=2, " + "validCharacters=abcdefghijklmnopqrstuvwxyz, " + "matchingCharacters=ab}", getDetail(validateShort, 0));
51+
assertEquals("ALLOWED_CHAR:{illegalCharacter=1, matchBehavior=contains}", getDetail(validateLong, 0));
52+
}
53+
54+
@Test
55+
public void givenCharacterCharacteristicsRule_whenValidatingPassword_thenItIsInvalidAsItBreaksToManyRules() {
56+
PasswordData shortPassword = new PasswordData();
57+
shortPassword.setPassword("12345abcde!");
58+
59+
CharacterCharacteristicsRule characterCharacteristicsRule = new CharacterCharacteristicsRule(4, new CharacterRule(EnglishCharacterData.LowerCase, 5), new CharacterRule(EnglishCharacterData.UpperCase, 5), new CharacterRule(EnglishCharacterData.Digit),
60+
new CharacterRule(EnglishCharacterData.Special));
61+
62+
PasswordValidator passwordValidator = new PasswordValidator(characterCharacteristicsRule);
63+
64+
RuleResult validate = passwordValidator.validate(shortPassword);
65+
assertFalse(validate.isValid());
66+
67+
assertEquals("INSUFFICIENT_UPPERCASE:{" + "minimumRequired=5, " + "matchingCharacterCount=0, " + "validCharacters=ABCDEFGHIJKLMNOPQRSTUVWXYZ, " + "matchingCharacters=}", getDetail(validate, 0));
68+
assertEquals("INSUFFICIENT_CHARACTERISTICS:{" + "successCount=3, " + "minimumRequired=4, " + "ruleCount=4}", getDetail(validate, 1));
69+
}
70+
71+
private String getDetail(RuleResult validate, int i) {
72+
return validate.getDetails()
73+
.get(i)
74+
.toString();
75+
}
76+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
TOO_LONG=Password must not have more characters than %2$s.
2+
TOO_SHORT=Password must not contain less characters than %2$s.

0 commit comments

Comments
 (0)