Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

switch password generation lib #15

Merged
merged 7 commits into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,16 @@
"jsonSchema:generate": "typescript-json-schema tsconfig.json PolicyDeclaration --noExtraProps --required > src/policy/schema.json && prettier --write src/policy/schema.json"
},
"devDependencies": {
"@types/crypto-js": "^4.2.2",
"@types/debug": "^4.1.8",
"@types/js-sha1": "^0.6.0",
"@types/node": "^20.14.9",
"@types/randomatic": "^3.1.3",
"@types/verror": "^1.10.6",
"@types/yargs": "^17.0.24",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"@vitest/coverage-v8": "^1.6.0",
"crypto-js": "^4.2.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^8.10.0",
"eslint-plugin-prettier": "^4.2.1",
Expand Down Expand Up @@ -100,7 +101,6 @@
"license-checker-rseidelsohn": "^4.3.0",
"ora": "^5.4.1",
"pretty-error": "^4.0.0",
"randomatic": "^3.1.1",
ins0 marked this conversation as resolved.
Show resolved Hide resolved
"typescript-json-schema": "^0.61.0",
"verror": "^1.10.1",
"yaml": "^2.3.2",
Expand Down
210 changes: 100 additions & 110 deletions src/cli/cli.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { execa as command } from "execa";
import { describe, expect, test } from "vitest";

describe("CLI", () => {
test("yarn password-tools-js", () => {
return expect(command("yarn", ["password-tools-js"])).rejects.toThrowErrorMatchingInlineSnapshot(`
describe(
"CLI",
() => {
test("yarn password-tools-js", () => {
return expect(command("yarn", ["password-tools-js"])).rejects.toThrowErrorMatchingInlineSnapshot(`
[ExecaError: Command failed with exit code 1: yarn password-tools-js

password-validation <cmd> [options]
Expand All @@ -26,116 +28,104 @@ describe("CLI", () => {

Choose one of the commands above ^]
`);
});
test("validate-passwords", async () => {
const processResult =
await command`yarn password-tools-js validate-passwords -P test/testPolicy.yaml -p my,.-P4ssw0rd†!`;
return expect(processResult.stdout).toMatchInlineSnapshot(`
"Password: my,.-P4ssw0rd†! -> Result: {
"isValid": true,
"ruleResults": [
{
"isValid": true,
"length": 15,
"ruleType": "length",
"min": 8,
"max": 64
},
{
"isValid": true,
"ruleType": "regex",
"matches": 0,
"pattern": "^\\\\.",
"translationKey": "beginsWithDot",
"max": 0
},
{
"isValid": true,
"ruleType": "charPool",
"charPools": [
{
"charPool": "special",
"occurrences": 4
},
{
"charPool": "numbers",
"occurrences": 2
}
],
"totalOccurrences": 6,
"min": 3
},
{
"isValid": true,
"chars": [
{
"char": "#",
"occurrences": 0
},
{
"char": "!",
"occurrences": 1
}
],
"totalOccurrences": 1,
"ruleType": "char",
"min": 1
},
{
"isValid": true,
"ruleType": "blocklist",
"substringMatch": true
}
],
"complexity": {
"actual": 3,
"min": 0,
"warning": null
});
test("validate-passwords", async () => {
const processResult =
await command`yarn password-tools-js validate-passwords -P test/testPolicy.yaml -p my,.-P4ssw0rd†!`;
return expect(processResult.stdout).toMatchInlineSnapshot(`
"Password: my,.-P4ssw0rd†! -> Result: {
"isValid": true,
"ruleResults": [
{
"isValid": true,
"length": 15,
"ruleType": "length",
"min": 8,
"max": 64
},
{
"isValid": true,
"ruleType": "regex",
"matches": 0,
"pattern": "^\\\\.",
"translationKey": "beginsWithDot",
"max": 0
},
{
"isValid": true,
"ruleType": "charPool",
"charPools": [
{
"charPool": "special",
"occurrences": 4
},
{
"charPool": "numbers",
"occurrences": 2
}
}"
`);
});
test("validate-passwords --booleanOnly", async () => {
const processResult =
await command`yarn password-tools-js validate-passwords -P test/testPolicy.yaml -p foo my,.-P4ssw0rd†! -b`;
return expect(processResult.stdout).toMatchInlineSnapshot(`
],
"totalOccurrences": 6,
"min": 3
},
{
"isValid": true,
"ruleType": "blocklist",
"substringMatch": true
}
],
"complexity": {
"actual": 3,
"min": 0,
"warning": null
}
}"
`);
});
test("validate-passwords --booleanOnly", async () => {
const processResult =
await command`yarn password-tools-js validate-passwords -P test/testPolicy.yaml -p foo my,.-P4ssw0rd†! -b`;
return expect(processResult.stdout).toMatchInlineSnapshot(`
"Password: foo -> Result: false
Password: my,.-P4ssw0rd†! -> Result: true"
`);
});
test("generate-password", async () => {
const processResult = await command`yarn password-tools-js generate-password -P test/testPolicy.yaml`;
return expect(processResult.stdout).toContain("Password: ");
});
test("generate-any-password", async () => {
const processResult = await command`yarn password-tools-js generate-any-password`;
return expect(processResult.stdout).toContain("Password: ");
});
test("generate-passphrase", async () => {
const processResult = await command`yarn password-tools-js generate-passphrase -P test/testPolicy.yaml`;
return expect(processResult.stdout).toContain("Passphrase: ");
});
test("generate-any-passphrase", async () => {
const processResult = await command`yarn password-tools-js generate-any-passphrase`;
return expect(processResult.stdout).toContain("Passphrase: ");
});
test("validate-policies", () => {
const processResultColorless = command({
env: { FORCE_COLOR: "0" },
})`yarn password-tools-js validate-policies -P test`;
});
test("generate-password", async () => {
const processResult = await command`yarn password-tools-js generate-password -P test/testPolicy.yaml -T 30`;
return expect(processResult.stdout).toContain("Password: ");
});
test("generate-any-password", async () => {
const processResult = await command`yarn password-tools-js generate-any-password`;
return expect(processResult.stdout).toContain("Password: ");
});
test("generate-passphrase", async () => {
const processResult = await command`yarn password-tools-js generate-passphrase -P test/testPolicy.yaml`;
return expect(processResult.stdout).toContain("Passphrase: ");
});
test("generate-any-passphrase", async () => {
const processResult = await command`yarn password-tools-js generate-any-passphrase`;
return expect(processResult.stdout).toContain("Passphrase: ");
});
test("validate-policies", () => {
const processResultColorless = command({
env: { FORCE_COLOR: "0" },
})`yarn password-tools-js validate-policies -P test`;

return expect(processResultColorless).rejects.toThrowErrorMatchingInlineSnapshot(`
[ExecaError: Command failed with exit code 1: yarn password-tools-js validate-policies -P test
return expect(processResultColorless).rejects.toThrowErrorMatchingInlineSnapshot(`
[ExecaError: Command failed with exit code 1: yarn password-tools-js validate-policies -P test

ℹ Validating password policies in: test ...
- brokenPolicy.yaml
✖ brokenPolicy.yaml: Error: must have required property 'ruleType',must have required property 'ruleType',must have required property 'blocklist',must have required property 'ruleType',must have required property 'chars',must have required property 'charPools',must have required property 'pattern',must match a schema in anyOf
- mittwald.yaml
✔ mittwald.yaml
- subDir/anotherPolicy.yaml
✔ subDir/anotherPolicy.yaml
- testPolicy.yaml
✔ testPolicy.yaml]
`);
});
});
ℹ Validating password policies in: test ...
- brokenPolicy.yaml
✖ brokenPolicy.yaml: Error: must have required property 'ruleType',must have required property 'ruleType',must have required property 'blocklist',must have required property 'ruleType',must have required property 'chars',must have required property 'charPools',must have required property 'pattern',must match a schema in anyOf
- mittwald.yaml
✔ mittwald.yaml
- subDir/anotherPolicy.yaml
✔ subDir/anotherPolicy.yaml
- testPolicy.yaml
✔ testPolicy.yaml
- testPolicyFull.yaml
✔ testPolicyFull.yaml]
`);
});
},
{ timeout: 20000 },
);
112 changes: 63 additions & 49 deletions src/generator/Generator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,59 +9,73 @@ import { Generator } from "./Generator";
import { LocalPolicyYamlLoader } from "../policy/loader/LocalPolicyYamlLoader";
import { describe, expect, test } from "vitest";

describe(Generator.name, () => {
const testGeneratePassphraseByPolicy = async (policy: Policy, test: (generated: string) => void): Promise<void> => {
const generator = new Generator(policy);
for (let i = 0; i < 333; i++) {
describe(
Generator.name,
() => {
const testGeneratePassphraseByPolicy = async (
policy: Policy,
test: (generated: string) => void,
): Promise<void> => {
const generator = new Generator(policy);
test(await generator.generatePassphrase());
}
};
const testGeneratePasswordByPolicy = async (policy: Policy, test: (generated: string) => void): Promise<void> => {
const generator = new Generator(policy);
for (let i = 0; i < 333; i++) {
};
const testGeneratePasswordByPolicy = async (
policy: Policy,
test: (generated: string) => void,
): Promise<void> => {
const generator = new Generator(policy);
test(await generator.generatePassword());
}
};
};

const generateTestsForGenerateStringFunction = (testAgainstPolicy: typeof testGeneratePassphraseByPolicy): void => {
test("from mittwald.yaml (without hibp)", async () => {
const policy = Policy.fromDeclaration(new LocalPolicyYamlLoader("test").loadPolicy("mittwald"));
await testAgainstPolicy(policy, (passphrase) => expect(policy.validate(passphrase).isValid).toBeTruthy());
const generateTestsForGenerateStringFunction = (
testAgainstPolicy: typeof testGeneratePassphraseByPolicy,
): void => {
test("from mittwald.yaml (without hibp)", async () => {
const policy = Policy.fromDeclaration(new LocalPolicyYamlLoader("test").loadPolicy("mittwald"));
await testAgainstPolicy(policy, (passphrase) =>
expect(policy.validate(passphrase).isValid).toBeTruthy(),
);
});
test("from policy: lengthRule with min 10", async () => {
const policy = new Policy([new LengthRule({ min: 10 })]);
await testAgainstPolicy(policy, (passphrase) =>
expect(policy.validate(passphrase).isValid).toBeTruthy(),
);
});
test("from policy: have length of at least 10, no special, number, or nonAscii, no 'a', 'b', 'c' and do not start with and d", async () => {
const policy = new Policy([
new LengthRule({ min: 10 }),
new CharPoolRule({ charPools: ["special", "numbers", "nonAscii"], max: 0 }),
new CharRule({ chars: "abc", max: 0 }),
new RegexRule({ pattern: "^d", max: 0 }),
]);

await testAgainstPolicy(policy, (passphrase) => expect(passphrase));
});
test("throw an error when loop limit is reached", async () => {
const policy = new Policy([
new BlocklistRule({ substringMatch: true, blocklist: ["password"] }),
new RegexRule({ pattern: "password" }),
]);
await expect(new Generator(policy).generatePassphrase()).rejects.toThrowError(
new PasswordGenerationError(policy, 10),
);
});
};
describe("generatePassphrase", () => {
generateTestsForGenerateStringFunction(testGeneratePassphraseByPolicy);
});
test("from policy: lengthRule with min 10", async () => {
const policy = new Policy([new LengthRule({ min: 10 })]);
await testAgainstPolicy(policy, (passphrase) => expect(policy.validate(passphrase).isValid).toBeTruthy());
describe("generatePassword", () => {
generateTestsForGenerateStringFunction(testGeneratePasswordByPolicy);
});
test("from policy: have length of at least 10, no special, number, or nonAscii, no 'a', 'b', 'c' and do not start with and d", async () => {
const policy = new Policy([
new LengthRule({ min: 10 }),
new CharPoolRule({ charPools: ["special", "numbers", "nonAscii"], max: 0 }),
new CharRule({ chars: "abc", max: 0 }),
new RegexRule({ pattern: "^d", max: 0 }),
]);

await testAgainstPolicy(policy, (passphrase) => expect(passphrase));
test(`expect ${Generator.generateAnyPassphrase.name} not to throw`, () => {
expect(Generator.generateAnyPassphrase());
});
test("throw an error when loop limit is reached", async () => {
const policy = new Policy([
new BlocklistRule({ substringMatch: true, blocklist: ["password"] }),
new RegexRule({ pattern: "password" }),
]);
await expect(new Generator(policy).generatePassphrase()).rejects.toThrowError(
new PasswordGenerationError(policy, 10),
);
test(`expect ${Generator.generateAnyPassword.name} not to throw`, () => {
expect(Generator.generateAnyPassword().length).toBeGreaterThanOrEqual(12);
});
};
describe("generatePassphrase", () => {
generateTestsForGenerateStringFunction(testGeneratePassphraseByPolicy);
});
describe("generatePassword", () => {
generateTestsForGenerateStringFunction(testGeneratePasswordByPolicy);
});
test(`expect ${Generator.generateAnyPassphrase.name} not to throw`, () => {
expect(Generator.generateAnyPassphrase());
});
test(`expect ${Generator.generateAnyPassword.name} not to throw`, () => {
expect(Generator.generateAnyPassword().length).toBeGreaterThanOrEqual(12);
});
});
},
{
timeout: 20000,
},
);
Loading