@celljs/security 3.9.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +111 -1
  2. package/cell.yml +12 -7
  3. package/esm/node/access/access-protocol.d.ts +0 -4
  4. package/esm/node/access/access-protocol.js +0 -1
  5. package/esm/node/access/access-protocol.js.map +1 -1
  6. package/esm/node/access/index.d.ts +0 -1
  7. package/esm/node/access/index.js +0 -1
  8. package/esm/node/access/index.js.map +1 -1
  9. package/esm/node/access/policy-provider.js +2 -2
  10. package/esm/node/access/policy-resolver.d.ts +2 -1
  11. package/esm/node/access/policy-resolver.js +4 -4
  12. package/esm/node/access/policy-resolver.js.map +1 -1
  13. package/esm/node/access/resource-name-resolver.d.ts +3 -0
  14. package/esm/node/access/resource-name-resolver.js +10 -5
  15. package/esm/node/access/resource-name-resolver.js.map +1 -1
  16. package/esm/node/authentication/authentication-provider.d.ts +8 -0
  17. package/esm/node/authentication/authentication-provider.js +29 -2
  18. package/esm/node/authentication/authentication-provider.js.map +1 -1
  19. package/esm/node/authentication/authentication-success-handler.js +4 -0
  20. package/esm/node/authentication/authentication-success-handler.js.map +1 -1
  21. package/esm/node/crypto/keygen/base64-string-key-generator.d.ts +4 -0
  22. package/esm/node/crypto/keygen/base64-string-key-generator.js +6 -4
  23. package/esm/node/crypto/keygen/base64-string-key-generator.js.map +1 -1
  24. package/esm/node/crypto/password/password-encoder.d.ts +40 -3
  25. package/esm/node/crypto/password/password-encoder.js +80 -24
  26. package/esm/node/crypto/password/password-encoder.js.map +1 -1
  27. package/esm/node/crypto/password/password-protocol.d.ts +6 -0
  28. package/esm/node/module.d.ts +0 -1
  29. package/esm/node/module.js +0 -1
  30. package/esm/node/module.js.map +1 -1
  31. package/esm/node/user/user-protocol.d.ts +5 -0
  32. package/esm/node/user/user-service.d.ts +14 -0
  33. package/esm/node/user/user-service.js +33 -2
  34. package/esm/node/user/user-service.js.map +1 -1
  35. package/lib/node/access/access-protocol.d.ts +0 -4
  36. package/lib/node/access/access-protocol.d.ts.map +1 -1
  37. package/lib/node/access/access-protocol.js +1 -2
  38. package/lib/node/access/access-protocol.js.map +1 -1
  39. package/lib/node/access/expression-resolvers.spec.d.ts +2 -0
  40. package/lib/node/access/expression-resolvers.spec.d.ts.map +1 -0
  41. package/lib/node/access/expression-resolvers.spec.js +57 -0
  42. package/lib/node/access/expression-resolvers.spec.js.map +1 -0
  43. package/lib/node/access/index.d.ts +0 -1
  44. package/lib/node/access/index.d.ts.map +1 -1
  45. package/lib/node/access/index.js +0 -1
  46. package/lib/node/access/index.js.map +1 -1
  47. package/lib/node/access/policy-resolver.d.ts +2 -1
  48. package/lib/node/access/policy-resolver.d.ts.map +1 -1
  49. package/lib/node/access/policy-resolver.js +1 -1
  50. package/lib/node/access/policy-resolver.js.map +1 -1
  51. package/lib/node/access/resource-name-resolver.d.ts +3 -0
  52. package/lib/node/access/resource-name-resolver.d.ts.map +1 -1
  53. package/lib/node/access/resource-name-resolver.js +9 -3
  54. package/lib/node/access/resource-name-resolver.js.map +1 -1
  55. package/lib/node/authentication/authentication-provider.d.ts +8 -0
  56. package/lib/node/authentication/authentication-provider.d.ts.map +1 -1
  57. package/lib/node/authentication/authentication-provider.js +29 -1
  58. package/lib/node/authentication/authentication-provider.js.map +1 -1
  59. package/lib/node/authentication/authentication-success-handler.d.ts.map +1 -1
  60. package/lib/node/authentication/authentication-success-handler.js +4 -0
  61. package/lib/node/authentication/authentication-success-handler.js.map +1 -1
  62. package/lib/node/authentication/basic-authentication.spec.d.ts +2 -0
  63. package/lib/node/authentication/basic-authentication.spec.d.ts.map +1 -0
  64. package/lib/node/authentication/basic-authentication.spec.js +65 -0
  65. package/lib/node/authentication/basic-authentication.spec.js.map +1 -0
  66. package/lib/node/crypto/keygen/base64-string-key-generator.d.ts +4 -0
  67. package/lib/node/crypto/keygen/base64-string-key-generator.d.ts.map +1 -1
  68. package/lib/node/crypto/keygen/base64-string-key-generator.js +6 -3
  69. package/lib/node/crypto/keygen/base64-string-key-generator.js.map +1 -1
  70. package/lib/node/crypto/keygen/base64-string-key-generator.spec.d.ts +2 -0
  71. package/lib/node/crypto/keygen/base64-string-key-generator.spec.d.ts.map +1 -0
  72. package/lib/node/crypto/keygen/base64-string-key-generator.spec.js +15 -0
  73. package/lib/node/crypto/keygen/base64-string-key-generator.spec.js.map +1 -0
  74. package/lib/node/crypto/password/password-encoder.d.ts +40 -3
  75. package/lib/node/crypto/password/password-encoder.d.ts.map +1 -1
  76. package/lib/node/crypto/password/password-encoder.js +80 -23
  77. package/lib/node/crypto/password/password-encoder.js.map +1 -1
  78. package/lib/node/crypto/password/password-encoder.spec.d.ts +2 -0
  79. package/lib/node/crypto/password/password-encoder.spec.d.ts.map +1 -0
  80. package/lib/node/crypto/password/password-encoder.spec.js +147 -0
  81. package/lib/node/crypto/password/password-encoder.spec.js.map +1 -0
  82. package/lib/node/crypto/password/password-protocol.d.ts +6 -0
  83. package/lib/node/crypto/password/password-protocol.d.ts.map +1 -1
  84. package/lib/node/module.d.ts +0 -1
  85. package/lib/node/module.d.ts.map +1 -1
  86. package/lib/node/module.js +0 -1
  87. package/lib/node/module.js.map +1 -1
  88. package/lib/node/user/user-protocol.d.ts +5 -0
  89. package/lib/node/user/user-protocol.d.ts.map +1 -1
  90. package/lib/node/user/user-service.d.ts +14 -0
  91. package/lib/node/user/user-service.d.ts.map +1 -1
  92. package/lib/node/user/user-service.js +33 -2
  93. package/lib/node/user/user-service.js.map +1 -1
  94. package/lib/node/user/user-service.spec.d.ts +2 -0
  95. package/lib/node/user/user-service.spec.d.ts.map +1 -0
  96. package/lib/node/user/user-service.spec.js +44 -0
  97. package/lib/node/user/user-service.spec.js.map +1 -0
  98. package/package.json +17 -31
  99. package/src/node/access/access-protocol.ts +0 -5
  100. package/src/node/access/expression-resolvers.spec.ts +37 -0
  101. package/src/node/access/index.ts +0 -1
  102. package/src/node/access/policy-resolver.ts +2 -2
  103. package/src/node/access/resource-name-resolver.ts +10 -4
  104. package/src/node/authentication/authentication-provider.ts +26 -2
  105. package/src/node/authentication/authentication-success-handler.ts +4 -0
  106. package/src/node/authentication/basic-authentication.spec.ts +68 -0
  107. package/src/node/crypto/keygen/base64-string-key-generator.spec.ts +13 -0
  108. package/src/node/crypto/keygen/base64-string-key-generator.ts +6 -3
  109. package/src/node/crypto/password/password-encoder.spec.ts +162 -0
  110. package/src/node/crypto/password/password-encoder.ts +99 -21
  111. package/src/node/crypto/password/password-protocol.ts +6 -0
  112. package/src/node/module.ts +0 -1
  113. package/src/node/user/user-protocol.ts +5 -0
  114. package/src/node/user/user-service.spec.ts +46 -0
  115. package/src/node/user/user-service.ts +32 -2
  116. package/esm/node/access/jexl-engine-provider.d.ts +0 -5
  117. package/esm/node/access/jexl-engine-provider.js +0 -22
  118. package/esm/node/access/jexl-engine-provider.js.map +0 -1
  119. package/lib/node/access/jexl-engine-provider.d.ts +0 -6
  120. package/lib/node/access/jexl-engine-provider.d.ts.map +0 -1
  121. package/lib/node/access/jexl-engine-provider.js +0 -25
  122. package/lib/node/access/jexl-engine-provider.js.map +0 -1
  123. package/src/node/access/jexl-engine-provider.ts +0 -18
@@ -1,7 +1,6 @@
1
1
  import { MethodSecurityMetadataContext, ResourceNameResolver } from './access-protocol';
2
- import { Component, Value, TENANT_ENABLED, getOwnMetadata } from '@celljs/core';
2
+ import { Component, Value, Autowired, TENANT_ENABLED, getOwnMetadata, JexlEngineProvider } from '@celljs/core';
3
3
  import { METADATA_KEY } from '../constants';
4
- import { evalSync } from 'jexl';
5
4
  import { Context } from '@celljs/web/lib/node';
6
5
 
7
6
  @Component(ResourceNameResolver)
@@ -10,6 +9,13 @@ export class DefaultResourceNameResolver implements ResourceNameResolver {
10
9
  @Value(TENANT_ENABLED)
11
10
  protected tenantEnabled: boolean;
12
11
 
12
+ @Autowired(JexlEngineProvider)
13
+ protected readonly jexlEngineProvider: JexlEngineProvider<any>;
14
+
15
+ protected evalSync(expression: string, ctx: MethodSecurityMetadataContext): any {
16
+ return this.jexlEngineProvider.provide().evalSync(expression, ctx);
17
+ }
18
+
13
19
  async resolve(ctx: MethodSecurityMetadataContext): Promise<string[]> {
14
20
  const classResources: string[] = getOwnMetadata(METADATA_KEY.resource, ctx.target.constructor);
15
21
  const methodResources: string[] = getOwnMetadata(METADATA_KEY.resource, ctx.target.constructor, ctx.method);
@@ -17,11 +23,11 @@ export class DefaultResourceNameResolver implements ResourceNameResolver {
17
23
  if (classResources.length && methodResources.length) {
18
24
  for (const resource of methodResources) {
19
25
  // eslint-disable-next-line no-eval
20
- resources.push(`${classResources[0]}:${evalSync(resource?.toString(), ctx)}`);
26
+ resources.push(`${classResources[0]}:${this.evalSync(resource?.toString(), ctx)}`);
21
27
  }
22
28
  } else if (methodResources.length) {
23
29
  // eslint-disable-next-line no-eval
24
- resources = methodResources.map(r => evalSync(r?.toString(), ctx)?.toString());
30
+ resources = methodResources.map(r => this.evalSync(r?.toString(), ctx)?.toString());
25
31
  } else if (classResources.length) {
26
32
  resources = classResources;
27
33
  } else {
@@ -1,4 +1,4 @@
1
- import { Component, Autowired, Value } from '@celljs/core';
1
+ import { Component, Autowired, Value, Logger } from '@celljs/core';
2
2
  import { AuthenticationProvider, Authentication, USERNAME_PASSWORD_AUTHENTICATION_PROVIDER_PRIORITY,
3
3
  BASE_AUTHENTICATION_PROVIDER_PRIORITY, AUTHENTICATION_SCHEME_BASIC } from './authentication-protocol';
4
4
  import { Context, RequestMatcher, RedirectStrategy } from '@celljs/web/lib/node';
@@ -10,6 +10,22 @@ import { PathResolver } from '@celljs/web';
10
10
 
11
11
  import { User } from '../../common';
12
12
 
13
+ /**
14
+ * After a password matched: when its stored hash is in a legacy format and the UserService can store
15
+ * passwords, store a new hash of it. A failure is logged and does not fail the login.
16
+ */
17
+ export async function upgradePasswordHash(passwordEncoder: PasswordEncoder, userService: UserService<any, User>, user: User,
18
+ rawPassword: string, logger: Logger): Promise<void> {
19
+ if (!userService.updatePassword || !passwordEncoder.needsUpgrade?.(user.password)) {
20
+ return;
21
+ }
22
+ try {
23
+ await userService.updatePassword(user, await passwordEncoder.encode(rawPassword));
24
+ } catch (error) {
25
+ logger.warn(`Could not upgrade the password hash of ${user.username}: ${(error as Error)?.message ?? error}`);
26
+ }
27
+ }
28
+
13
29
  @Component(AuthenticationProvider)
14
30
  export class UsernamePasswordAuthenticationProvider implements AuthenticationProvider {
15
31
 
@@ -37,6 +53,9 @@ export class UsernamePasswordAuthenticationProvider implements AuthenticationPro
37
53
  @Autowired(RedirectStrategy)
38
54
  protected readonly redirectStrategy: RedirectStrategy;
39
55
 
56
+ @Autowired(Logger)
57
+ protected readonly logger: Logger;
58
+
40
59
  priority = USERNAME_PASSWORD_AUTHENTICATION_PROVIDER_PRIORITY;
41
60
 
42
61
  async authenticate(): Promise<Authentication | undefined> {
@@ -50,6 +69,7 @@ export class UsernamePasswordAuthenticationProvider implements AuthenticationPro
50
69
  if (!await this.passwordEncoder.matches(password, user.password)) {
51
70
  throw new BadCredentialsError('Bad credentials');
52
71
  }
72
+ await upgradePasswordHash(this.passwordEncoder, this.userService, user, password, this.logger);
53
73
  await this.userMapper.map(user);
54
74
  return {
55
75
  name: user.username,
@@ -100,6 +120,9 @@ export class BasicAuthenticationProvider implements AuthenticationProvider {
100
120
  @Autowired(RedirectStrategy)
101
121
  protected readonly redirectStrategy: RedirectStrategy;
102
122
 
123
+ @Autowired(Logger)
124
+ protected readonly logger: Logger;
125
+
103
126
  priority = BASE_AUTHENTICATION_PROVIDER_PRIORITY;
104
127
 
105
128
  async authenticate(): Promise<Authentication | undefined> {
@@ -115,7 +138,7 @@ export class BasicAuthenticationProvider implements AuthenticationProvider {
115
138
  throw new BadCredentialsError('Invalid basic authentication token');
116
139
  }
117
140
  const username = token.substring(0, delim);
118
- const password = token.substring(delim);
141
+ const password = token.substring(delim + 1);
119
142
  if (!password || !username) {
120
143
  throw new BadCredentialsError('Bad credentials');
121
144
  }
@@ -124,6 +147,7 @@ export class BasicAuthenticationProvider implements AuthenticationProvider {
124
147
  if (!await this.passwordEncoder.matches(password, user.password)) {
125
148
  throw new BadCredentialsError('Bad credentials');
126
149
  }
150
+ await upgradePasswordHash(this.passwordEncoder, this.userService, user, password, this.logger);
127
151
 
128
152
  await this.userMapper.map(user);
129
153
 
@@ -29,6 +29,10 @@ export class DefaultAuthenticationSuccessHandler implements AuthenticationSucces
29
29
  protected readonly requestCache: RequestCache;
30
30
 
31
31
  async onAuthenticationSuccess(authentication: Authentication): Promise<void> {
32
+ // Authentication that goes on to the requested resource (Basic): nothing to redirect to.
33
+ if (authentication.next) {
34
+ return;
35
+ }
32
36
  const response = Context.getResponse();
33
37
  if (Context.getRequest().get(HttpHeaders.X_REQUESTED_WITH) === XML_HTTP_REQUEST) {
34
38
  return;
@@ -0,0 +1,68 @@
1
+ import { describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { Context } from '@celljs/web/lib/node';
4
+ import { BadCredentialsError } from '../error';
5
+ import { BasicAuthenticationProvider } from './authentication-provider';
6
+ import { DefaultAuthenticationSuccessHandler } from './authentication-success-handler';
7
+
8
+ function inRequest<T>(authorization: string | undefined, fn: () => Promise<T>): Promise<T> {
9
+ return new Promise((resolve, reject) => {
10
+ Context.run(async () => {
11
+ try {
12
+ const headers: Record<string, string> = authorization ? { authorization } : {};
13
+ Context.setCurrent(new Context({ headers, get: (name: string) => headers[name.toLowerCase()] } as any, {} as any));
14
+ resolve(await fn());
15
+ } catch (error) {
16
+ reject(error);
17
+ }
18
+ });
19
+ });
20
+ }
21
+
22
+ const basic = (user: string, password: string) => `Basic ${Buffer.from(`${user}:${password}`).toString('base64')}`;
23
+
24
+ function provider(): BasicAuthenticationProvider {
25
+ const instance = new BasicAuthenticationProvider();
26
+ Object.assign(instance, {
27
+ passwordEncoder: { matches: async (raw: string, encoded: string) => raw === encoded },
28
+ userService: { load: async (username: string) => ({ username, password: 'pa:ss', policies: [] }) },
29
+ userChecker: { check: async () => undefined },
30
+ userMapper: { map: async () => undefined },
31
+ logger: { warn: () => undefined },
32
+ });
33
+ return instance;
34
+ }
35
+
36
+ describe('BasicAuthenticationProvider', () => {
37
+ it('authenticates with the password after the first colon (which may contain colons)', async () => {
38
+ const result = await inRequest(basic('tom', 'pa:ss'), () => provider().authenticate());
39
+ expect(result?.authenticated).to.equal(true);
40
+ expect(result?.name).to.equal('tom');
41
+ // Basic goes on to the requested resource.
42
+ expect(result?.next).to.equal(true);
43
+ });
44
+
45
+ it('rejects a wrong password', async () => {
46
+ let error: unknown;
47
+ await inRequest(basic('tom', 'wrong'), () => provider().authenticate()).catch(e => {
48
+ error = e;
49
+ });
50
+ expect(error).to.be.instanceOf(BadCredentialsError);
51
+ });
52
+
53
+ it('is only used with a Basic authorization header', async () => {
54
+ expect(await inRequest(basic('tom', 'x'), () => provider().support())).to.equal(true);
55
+ expect(await inRequest('Bearer abc', () => provider().support())).to.equal(false);
56
+ expect(await inRequest(undefined, () => provider().support())).to.equal(false);
57
+ });
58
+ });
59
+
60
+ describe('DefaultAuthenticationSuccessHandler', () => {
61
+ it('does not redirect an authentication that goes on to the requested resource', async () => {
62
+ const handler = new DefaultAuthenticationSuccessHandler();
63
+ let redirected = false;
64
+ Object.assign(handler, { loginSuccessUrl: '/', redirectStrategy: { send: async () => { redirected = true; } } });
65
+ await inRequest(basic('tom', 'x'), () => handler.onAuthenticationSuccess({ next: true, authenticated: true } as any));
66
+ expect(redirected).to.equal(false);
67
+ });
68
+ });
@@ -0,0 +1,13 @@
1
+ import { describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { Base64StringKeyGenerator } from './base64-string-key-generator';
4
+
5
+ describe('Base64StringKeyGenerator', () => {
6
+ it('generates URL-safe keys of the requested number of random bytes', async () => {
7
+ const generator = Object.assign(new Base64StringKeyGenerator(), { keyLength: 32 });
8
+ const key = await generator.generateKey();
9
+ expect(key).to.match(/^[A-Za-z0-9_-]{43}$/);
10
+ expect(await generator.generateKey(96)).to.match(/^[A-Za-z0-9_-]{128}$/);
11
+ expect(await generator.generateKey()).to.not.equal(key);
12
+ });
13
+ });
@@ -1,7 +1,11 @@
1
+ import { randomBytes } from 'node:crypto';
1
2
  import { StringKeyGenerator } from './keygen-protocol';
2
- import { enc, lib } from 'crypto-js';
3
3
  import { Value, Component } from '@celljs/core';
4
4
 
5
+ /**
6
+ * Random keys (OAuth2 `state`, PKCE `code_verifier`, OIDC `nonce`) in base64url without padding,
7
+ * so they can go into a URL as they are (RFC 7636 §4.1 allows only unreserved characters).
8
+ */
5
9
  @Component(StringKeyGenerator)
6
10
  export class Base64StringKeyGenerator implements StringKeyGenerator {
7
11
 
@@ -9,7 +13,6 @@ export class Base64StringKeyGenerator implements StringKeyGenerator {
9
13
  protected readonly keyLength: number;
10
14
 
11
15
  async generateKey(keyLength?: number) {
12
- const key = lib.WordArray.random(keyLength || this.keyLength);
13
- return enc.Base64.stringify(key);
16
+ return randomBytes(keyLength || this.keyLength).toString('base64url');
14
17
  }
15
18
  }
@@ -0,0 +1,162 @@
1
+ import { describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { Pbkdf2PasswordEncoder, Pbkdf2PasswordEncoderOptions } from './password-encoder';
4
+ import { upgradePasswordHash } from '../../authentication/authentication-provider';
5
+
6
+ /**
7
+ * Golden vectors: legacy hashes made by the crypto-js implementation of this encoder (crypto-js 4.2.0, main 6a87acfc0)
8
+ * for fixed salts, with cell-refactor/stage1/t10-password-vectors/generate.cjs. Stored hashes like these must keep matching.
9
+ */
10
+ const LEGACY: { options: Pbkdf2PasswordEncoderOptions; password: string; salt: string; encoded: string }[] = [
11
+ { options: {"encodeHashAsBase64": true}, password: "123456", salt: "0123456789abcdef", encoded: "MDEyMzQ1Njc4OWFiY2RlZjA1NjVhMGQzZmI4ZDlhY2U3ZmY5YTY4OTE1YTFiOTll" },
12
+ { options: {"encodeHashAsBase64": true}, password: "P@ss w0rd!#$%^&*()_+-=[]{}|;:'\",.<>/?`~\\", salt: "a1b2c3d4e5f60718", encoded: "YTFiMmMzZDRlNWY2MDcxODE5NWZjMWI0ODk3YjBlMDBjMjU1YTVjNjcxZTUxOGIx" },
13
+ { options: {"encodeHashAsBase64": true}, password: "中文密码🔐", salt: "ffffffff00000000", encoded: "ZmZmZmZmZmYwMDAwMDAwMDc2MjIyMDk5NzdkMDRjMzdkY2JlYjBhZjNkNjg2NDQ3" },
14
+ { options: {"encodeHashAsBase64": false}, password: "123456", salt: "a1b2c3d4e5f60718", encoded: "a1b2c3d4e5f60718c1ef95056e13cce639b1b172f002e7ae" },
15
+ { options: {"encodeHashAsBase64": false}, password: "P@ss w0rd!#$%^&*()_+-=[]{}|;:'\",.<>/?`~\\", salt: "ffffffff00000000", encoded: "ffffffff0000000018bbdc72579e0a3093f5f6ea06b82033" },
16
+ { options: {"encodeHashAsBase64": false}, password: "中文密码🔐", salt: "0123456789abcdef", encoded: "0123456789abcdef066fc4596441dd6bdb884678496ef9fc" },
17
+ { options: {"encodeHashAsBase64": true, "secret": "s3cr3t"}, password: "123456", salt: "ffffffff00000000", encoded: "ZmZmZmZmZmYwMDAwMDAwMDg4Zjc0NzAyM2E1NjE1NWVjNzU1NzlkZTUxNmQ1Mjhi" },
18
+ { options: {"encodeHashAsBase64": true, "secret": "s3cr3t"}, password: "P@ss w0rd!#$%^&*()_+-=[]{}|;:'\",.<>/?`~\\", salt: "0123456789abcdef", encoded: "MDEyMzQ1Njc4OWFiY2RlZjY4ZGI3ZWU2NGFmMjVhNjdkNWU0MWU0ZTFlZTEyZGY0" },
19
+ { options: {"encodeHashAsBase64": true, "secret": "s3cr3t"}, password: "中文密码🔐", salt: "a1b2c3d4e5f60718", encoded: "YTFiMmMzZDRlNWY2MDcxODAxYTBjZDMxYTgxZmE0N2UyMDQxNWUzNDJiOTg5ZGMx" },
20
+ { options: {"encodeHashAsBase64": true, "secret": 123456}, password: "123456", salt: "0123456789abcdef", encoded: "MDEyMzQ1Njc4OWFiY2RlZjZkNGE0MGRkMDU4MmRmMGI1MjVkM2MxZjE0NjVkNjY5" },
21
+ { options: {"encodeHashAsBase64": true, "secret": 123456}, password: "P@ss w0rd!#$%^&*()_+-=[]{}|;:'\",.<>/?`~\\", salt: "a1b2c3d4e5f60718", encoded: "YTFiMmMzZDRlNWY2MDcxOGM5ZWY5NjgzNzExMDUwNWUwNWVlYzlkYTRhMjkyYmZj" },
22
+ { options: {"encodeHashAsBase64": true, "secret": 123456}, password: "中文密码🔐", salt: "ffffffff00000000", encoded: "ZmZmZmZmZmYwMDAwMDAwMDFkZWZlYjdjYjkxNTNlMzk1YWFiZGUzNWM3NDBjNjg0" },
23
+ { options: {"encodeHashAsBase64": false, "secret": "密钥🔑", "iterations": 1000}, password: "123456", salt: "a1b2c3d4e5f60718", encoded: "a1b2c3d4e5f6071822b7276a5d78c8e4111547a26aada7f1" },
24
+ { options: {"encodeHashAsBase64": false, "secret": "密钥🔑", "iterations": 1000}, password: "P@ss w0rd!#$%^&*()_+-=[]{}|;:'\",.<>/?`~\\", salt: "ffffffff00000000", encoded: "ffffffff0000000068f9b165d52e8bc615b2ebcc6654d149" },
25
+ { options: {"encodeHashAsBase64": false, "secret": "密钥🔑", "iterations": 1000}, password: "中文密码🔐", salt: "0123456789abcdef", encoded: "0123456789abcdef27ac13cc586b34fbf24700ef8f5cd54b" },
26
+ { options: {"encodeHashAsBase64": true, "iterations": 1, "keySize": 8}, password: "123456", salt: "ffffffff00000000", encoded: "ZmZmZmZmZmYwMDAwMDAwMGYyMjdkNzNkODMwNWU3OWZjOGM2YTc1ZjdmZjZhMGRhNDgwMWFlYTZlZjcxYWM4Mjc0MmIyYzlhNTQyZjJhM2Q=" },
27
+ { options: {"encodeHashAsBase64": true, "iterations": 1, "keySize": 8}, password: "P@ss w0rd!#$%^&*()_+-=[]{}|;:'\",.<>/?`~\\", salt: "0123456789abcdef", encoded: "MDEyMzQ1Njc4OWFiY2RlZmFmZGEwNTA0YzA5YjJlYjBjNTExOTA3ZWRlZThiNzRmODVhNGU0NWZjODg0ZmZjOGU5NDA3Y2JiNTljZDA4ZWQ=" },
28
+ { options: {"encodeHashAsBase64": true, "iterations": 1, "keySize": 8}, password: "中文密码🔐", salt: "a1b2c3d4e5f60718", encoded: "YTFiMmMzZDRlNWY2MDcxOGI2MTgyZGI1YWFkOThjMDNmOGRlZDllYTNkYjUzNTVlM2YwZDhlMmU0NDQ3ZTE5ZjY5NDBjOWUzOTRlOTE1ODM=" },
29
+ ];
30
+
31
+ class TestEncoder extends Pbkdf2PasswordEncoder {
32
+ constructor(options: Pbkdf2PasswordEncoderOptions = {}, protected readonly newIterations = 1000) {
33
+ super();
34
+ Object.defineProperty(this, 'options', { value: options });
35
+ }
36
+
37
+ protected override get iterations(): number {
38
+ return this.newIterations;
39
+ }
40
+
41
+ /** What the crypto-js implementation stored for a fixed salt. */
42
+ async legacyHash(rawPassword: string, salt: string): Promise<string> {
43
+ const text = await this.legacyEncode(rawPassword, salt);
44
+ return this.options?.encodeHashAsBase64 ? Buffer.from(text, 'utf8').toString('base64') : text;
45
+ }
46
+ }
47
+
48
+ const name = (v: (typeof LEGACY)[number]) => `${JSON.stringify(v.options)} ${JSON.stringify(v.password)}`;
49
+
50
+ describe('Pbkdf2PasswordEncoder', () => {
51
+ describe('legacy hashes of the crypto-js implementation', () => {
52
+ for (const vector of LEGACY) {
53
+ it(`match, and a wrong password does not: ${name(vector)}`, async () => {
54
+ const encoder = new TestEncoder(vector.options);
55
+ expect(await encoder.matches(vector.password, vector.encoded)).to.equal(true);
56
+ expect(await encoder.matches(`${vector.password}x`, vector.encoded)).to.equal(false);
57
+ expect(await encoder.matches('', vector.encoded)).to.equal(false);
58
+ });
59
+
60
+ it(`are reproduced byte for byte: ${name(vector)}`, async () => {
61
+ expect(await new TestEncoder(vector.options).legacyHash(vector.password, vector.salt)).to.equal(vector.encoded);
62
+ });
63
+ }
64
+
65
+ it('need an upgrade', () => {
66
+ for (const vector of LEGACY) {
67
+ expect(new TestEncoder(vector.options).needsUpgrade(vector.encoded)).to.equal(true);
68
+ }
69
+ });
70
+
71
+ it('only match with the secret they were made with (none means the text "undefined")', async () => {
72
+ const vector = LEGACY.find(v => v.options.secret === undefined && v.options.encodeHashAsBase64)!;
73
+ expect(await new TestEncoder({ ...vector.options, secret: 'undefined' }).matches(vector.password, vector.encoded)).to.equal(true);
74
+ expect(await new TestEncoder({ ...vector.options, secret: 'pepper' }).matches(vector.password, vector.encoded)).to.equal(false);
75
+ });
76
+ });
77
+
78
+ describe('new hashes', () => {
79
+ it('record their parameters and use a fresh salt', async () => {
80
+ const encoder = new TestEncoder({ encodeHashAsBase64: true });
81
+ const a = await encoder.encode('secret');
82
+ const b = await encoder.encode('secret');
83
+ expect(a).to.match(/^pbkdf2-sha256\$1000\$[A-Za-z0-9+/]{22}==\$[A-Za-z0-9+/]{43}=$/);
84
+ expect(a).to.not.equal(b);
85
+ });
86
+
87
+ it('match the right password only', async () => {
88
+ const encoder = new TestEncoder();
89
+ const hash = await encoder.encode('中文密码🔐');
90
+ expect(await encoder.matches('中文密码🔐', hash)).to.equal(true);
91
+ expect(await encoder.matches('中文密码', hash)).to.equal(false);
92
+ });
93
+
94
+ it('do not depend on encodeHashAsBase64, and a missing secret is not the text "undefined"', async () => {
95
+ const hash = await new TestEncoder({ encodeHashAsBase64: true }).encode('secret');
96
+ expect(await new TestEncoder({ encodeHashAsBase64: false }).matches('secret', hash)).to.equal(true);
97
+ expect(await new TestEncoder({ secret: 'undefined' }).matches('secret', hash)).to.equal(false);
98
+ });
99
+
100
+ it('mix the secret in', async () => {
101
+ const hash = await new TestEncoder({ secret: 'pepper' }).encode('secret');
102
+ expect(await new TestEncoder({ secret: 'pepper' }).matches('secret', hash)).to.equal(true);
103
+ expect(await new TestEncoder({ secret: 'other' }).matches('secret', hash)).to.equal(false);
104
+ expect(await new TestEncoder().matches('secret', hash)).to.equal(false);
105
+ });
106
+
107
+ it('check with the iterations they record, and need an upgrade when that is fewer than new hashes get', async () => {
108
+ const old = await new TestEncoder({}, 1000).encode('secret');
109
+ const encoder = new TestEncoder({}, 2000);
110
+ expect(await encoder.matches('secret', old)).to.equal(true);
111
+ expect(encoder.needsUpgrade(old)).to.equal(true);
112
+ expect(encoder.needsUpgrade(await encoder.encode('secret'))).to.equal(false);
113
+ });
114
+
115
+ it('get 600000 iterations by default', async () => {
116
+ expect(await new Pbkdf2PasswordEncoder().encode('secret')).to.match(/^pbkdf2-sha256\$600000\$/);
117
+ });
118
+ });
119
+
120
+ it('rejects malformed hashes instead of throwing', async () => {
121
+ for (const options of [{ encodeHashAsBase64: true }, { encodeHashAsBase64: false }]) {
122
+ const encoder = new TestEncoder(options);
123
+ for (const hash of ['', 'abc', '!!!!', '0123456789abcdef', 'pbkdf2-sha256$x$a$b', 'pbkdf2-sha256$1000$$', 'pbkdf2-sha256$1000$YQ==$YQ==',
124
+ 'pbkdf2-sha256$1000$YQ==$YQ==$x', undefined as unknown as string, null as unknown as string]) {
125
+ expect(await encoder.matches('secret', hash), String(hash)).to.equal(false);
126
+ }
127
+ }
128
+ });
129
+
130
+ describe('upgradePasswordHash', () => {
131
+ const legacy = LEGACY.find(v => v.options.encodeHashAsBase64 && v.options.secret === undefined)!;
132
+ const user = () => ({ username: 'tom', password: legacy.encoded }) as any;
133
+ const logger = (warnings: string[]) => ({ warn: (m: string) => warnings.push(m) }) as any;
134
+
135
+ it('stores a new hash of a legacy one through UserService.updatePassword', async () => {
136
+ const encoder = new TestEncoder(legacy.options);
137
+ const stored: string[] = [];
138
+ const service = { load: async () => user(), updatePassword: async (_: unknown, hash: string) => { stored.push(hash); } };
139
+ await upgradePasswordHash(encoder, service, user(), legacy.password, logger([]));
140
+ expect(stored).to.have.length(1);
141
+ expect(encoder.needsUpgrade(stored[0])).to.equal(false);
142
+ expect(await encoder.matches(legacy.password, stored[0])).to.equal(true);
143
+ });
144
+
145
+ it('does nothing when the hash is current or the UserService cannot store passwords', async () => {
146
+ const encoder = new TestEncoder(legacy.options);
147
+ const stored: string[] = [];
148
+ const service = { load: async () => user(), updatePassword: async (_: unknown, hash: string) => { stored.push(hash); } };
149
+ await upgradePasswordHash(encoder, service, { ...user(), password: await encoder.encode(legacy.password) }, legacy.password, logger([]));
150
+ await upgradePasswordHash(encoder, { load: async () => user() }, user(), legacy.password, logger([]));
151
+ expect(stored).to.have.length(0);
152
+ });
153
+
154
+ it('logs a failure to store instead of failing the login', async () => {
155
+ const warnings: string[] = [];
156
+ const service = { load: async () => user(), updatePassword: async () => { throw new Error('read-only'); } };
157
+ await upgradePasswordHash(new TestEncoder(legacy.options), service, user(), legacy.password, logger(warnings));
158
+ expect(warnings).to.have.length(1);
159
+ expect(warnings[0]).to.include('read-only');
160
+ });
161
+ });
162
+ });
@@ -1,39 +1,117 @@
1
- import { PasswordEncoder } from './password-protocol';
2
- import { PBKDF2, lib, enc} from 'crypto-js';
1
+ import { pbkdf2, randomBytes, timingSafeEqual } from 'node:crypto';
2
+ import { promisify } from 'node:util';
3
3
  import { Value, Component } from '@celljs/core';
4
+ import { PasswordEncoder } from './password-protocol';
5
+
6
+ const pbkdf2Async = promisify(pbkdf2);
4
7
 
8
+ export interface Pbkdf2PasswordEncoderOptions {
9
+ /** Optional pepper. New hashes mix it into the salt when it is set; legacy hashes were made with `String(secret)`. */
10
+ secret?: string | number;
11
+ /** Legacy hashes only: they are base64 of the hex text. */
12
+ encodeHashAsBase64?: boolean;
13
+ /** Legacy hashes only: PBKDF2 iterations they were made with. Default 250000 (crypto-js 4.2.0). */
14
+ iterations?: number;
15
+ /** Legacy hashes only: derived key length in 32-bit words. Default 4 (16 bytes, crypto-js 4.2.0). */
16
+ keySize?: number;
17
+ }
18
+
19
+ /**
20
+ * Password hashes with PBKDF2-HMAC-SHA256 on node:crypto, compared in constant time.
21
+ *
22
+ * New hashes: `pbkdf2-sha256$<iterations>$<salt, base64>$<key, base64>` with 600000 iterations, a 16-byte
23
+ * random salt (followed by the UTF-8 bytes of `secret` when one is set) and a 32-byte key.
24
+ *
25
+ * Legacy hashes (no prefix), as the crypto-js 4.2.0 implementation of 4.x stored them, keep matching:
26
+ * optionally base64 of a text that is a 16-character hex salt followed by the hex key; the key is
27
+ * PBKDF2(password, salt + String(secret)) with SHA-256, `iterations` (default 250000) and `keySize` words
28
+ * (default 4). Without a secret the salt text ends in `undefined`, which is how those hashes were made.
29
+ * Hashes made with crypto-js 4.1 or older (SHA-1, 1 iteration) are not supported.
30
+ * {@link needsUpgrade} is true for legacy hashes, so a login replaces them with a new hash.
31
+ */
5
32
  @Component(PasswordEncoder)
6
33
  export class Pbkdf2PasswordEncoder implements PasswordEncoder {
7
34
 
35
+ static readonly PREFIX = 'pbkdf2-sha256';
36
+ static readonly ITERATIONS = 600000;
37
+ static readonly SALT_BYTES = 16;
38
+ static readonly KEY_BYTES = 32;
39
+
40
+ static readonly LEGACY_ITERATIONS = 250000;
41
+ static readonly LEGACY_KEY_SIZE = 4;
42
+ static readonly LEGACY_SALT_LENGTH = 16;
43
+
8
44
  @Value('cell.security.passwordEncoder')
9
- protected readonly options: any;
45
+ protected readonly options: Pbkdf2PasswordEncoderOptions | undefined;
46
+
47
+ /** Iterations of new hashes. */
48
+ protected get iterations(): number {
49
+ return Pbkdf2PasswordEncoder.ITERATIONS;
50
+ }
10
51
 
11
52
  async encode(rawPassword: string): Promise<string> {
12
- const { encodeHashAsBase64 } = this.options;
13
- const salt = lib.WordArray.random(8);
14
- const encoded = this.doEncode(rawPassword, salt.toString());
15
- if (encodeHashAsBase64) {
16
- return enc.Base64.stringify(enc.Utf8.parse(encoded));
53
+ const salt = randomBytes(Pbkdf2PasswordEncoder.SALT_BYTES);
54
+ const key = await pbkdf2Async(rawPassword, this.pepper(salt), this.iterations, Pbkdf2PasswordEncoder.KEY_BYTES, 'sha256');
55
+ return [Pbkdf2PasswordEncoder.PREFIX, this.iterations, salt.toString('base64'), key.toString('base64')].join('$');
56
+ }
57
+
58
+ async matches(rawPassword: string, encodedPassword: string): Promise<boolean> {
59
+ if (typeof encodedPassword !== 'string' || typeof rawPassword !== 'string') {
60
+ return false;
17
61
  }
18
- return encoded;
62
+ return this.isCurrent(encodedPassword) ? this.matchesCurrent(rawPassword, encodedPassword) : this.matchesLegacy(rawPassword, encodedPassword);
19
63
  }
20
64
 
21
- protected doEncode(rawPassword: string, salt: string): string {
22
- const { secret } = this.options;
23
- return salt + PBKDF2(rawPassword, salt + secret, this.options).toString();
65
+ needsUpgrade(encodedPassword: string): boolean {
66
+ if (!this.isCurrent(encodedPassword)) {
67
+ return true;
68
+ }
69
+ return Number(encodedPassword.split('$')[1]) < this.iterations;
24
70
  }
25
71
 
26
- async matches(rawPassword: string, encodedPassword: string): Promise<boolean> {
27
- const digested = this.doDecode(encodedPassword);
28
- const salt = digested.substring(0, 16);
29
- return digested === this.doEncode(rawPassword, salt);
72
+ protected isCurrent(encodedPassword: string): boolean {
73
+ return encodedPassword.startsWith(`${Pbkdf2PasswordEncoder.PREFIX}$`);
30
74
  }
31
75
 
32
- protected doDecode(encoded: string): string {
33
- const { encodeHashAsBase64 } = this.options;
34
- if (encodeHashAsBase64) {
35
- return enc.Base64.parse(encoded).toString(enc.Utf8);
76
+ protected pepper(salt: Buffer): Buffer {
77
+ const secret = this.options?.secret;
78
+ return secret === undefined || secret === null || secret === '' ? salt : Buffer.concat([salt, Buffer.from(String(secret), 'utf8')]);
79
+ }
80
+
81
+ protected async matchesCurrent(rawPassword: string, encodedPassword: string): Promise<boolean> {
82
+ const [, iterationsText, saltText, keyText, ...rest] = encodedPassword.split('$');
83
+ const iterations = Number(iterationsText);
84
+ if (rest.length > 0 || !Number.isSafeInteger(iterations) || iterations < 1 || !saltText || !keyText) {
85
+ return false;
86
+ }
87
+ const expected = Buffer.from(keyText, 'base64');
88
+ if (expected.length !== Pbkdf2PasswordEncoder.KEY_BYTES) {
89
+ return false;
36
90
  }
37
- return encoded;
91
+ const actual = await pbkdf2Async(rawPassword, this.pepper(Buffer.from(saltText, 'base64')), iterations, Pbkdf2PasswordEncoder.KEY_BYTES, 'sha256');
92
+ return timingSafeEqual(actual, expected);
93
+ }
94
+
95
+ protected async matchesLegacy(rawPassword: string, encodedPassword: string): Promise<boolean> {
96
+ const digested = this.options?.encodeHashAsBase64 ? Buffer.from(encodedPassword, 'base64').toString('utf8') : encodedPassword;
97
+ if (digested.length <= Pbkdf2PasswordEncoder.LEGACY_SALT_LENGTH) {
98
+ return false;
99
+ }
100
+ const expected = Buffer.from(await this.legacyEncode(rawPassword, digested.substring(0, Pbkdf2PasswordEncoder.LEGACY_SALT_LENGTH)), 'utf8');
101
+ const actual = Buffer.from(digested, 'utf8');
102
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
103
+ }
104
+
105
+ /** The text the crypto-js implementation stored (before the optional base64): salt + hex key. */
106
+ protected async legacyEncode(rawPassword: string, salt: string): Promise<string> {
107
+ const { secret, iterations, keySize } = this.options ?? {};
108
+ const key = await pbkdf2Async(
109
+ rawPassword,
110
+ `${salt}${secret}`,
111
+ Number(iterations ?? Pbkdf2PasswordEncoder.LEGACY_ITERATIONS),
112
+ Number(keySize ?? Pbkdf2PasswordEncoder.LEGACY_KEY_SIZE) * 4,
113
+ 'sha256',
114
+ );
115
+ return salt + key.toString('hex');
38
116
  }
39
117
  }
@@ -3,4 +3,10 @@ export const PasswordEncoder = Symbol('PasswordEncoder');
3
3
  export interface PasswordEncoder {
4
4
  encode(rawPassword: string): Promise<string>;
5
5
  matches(rawPassword: string, encodedPassword: string): Promise<boolean>;
6
+ /**
7
+ * Whether a stored hash should be replaced by `encode()` of the password once it matched (a legacy
8
+ * format, or weaker parameters than new hashes get). Login does so when the UserService can
9
+ * store passwords (`UserService.updatePassword`).
10
+ */
11
+ needsUpgrade?(encodedPassword: string): boolean;
6
12
  }
@@ -1,4 +1,3 @@
1
- import 'reflect-metadata';
2
1
  import { autoBind } from '@celljs/core';
3
2
  import './index';
4
3
 
@@ -9,6 +9,11 @@ export const USER_MIDDLEWARE_PRIORITY = SECURITY_CONTEXT_MIDDLEWARE_PRIORITY - 1
9
9
 
10
10
  export interface UserService<R, U extends User> {
11
11
  load(userRequest: R): Promise<U>;
12
+ /**
13
+ * Stores a new password hash of `user`. Optional: when a service has it, a login whose stored hash
14
+ * `PasswordEncoder.needsUpgrade()` saves the hash in the current format.
15
+ */
16
+ updatePassword?(user: U, encodedPassword: string): Promise<void>;
12
17
  }
13
18
 
14
19
  export interface UserChecker {
@@ -0,0 +1,46 @@
1
+ import { describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { UserServiceImpl, UserSourceCheck } from './user-service';
4
+ import { UsernameNotFoundError } from '../error';
5
+
6
+ function check(userService: unknown): string[] {
7
+ const warnings: string[] = [];
8
+ const lifecycle = new UserSourceCheck();
9
+ Object.assign(lifecycle, { userService, logger: { warn: (m: string) => warnings.push(m) } });
10
+ lifecycle.initialize();
11
+ return warnings;
12
+ }
13
+
14
+ function service(options: Record<string, unknown>): UserServiceImpl {
15
+ return Object.assign(new UserServiceImpl(), { options });
16
+ }
17
+
18
+ describe('UserServiceImpl', () => {
19
+ it('has no built-in user', async () => {
20
+ let error: unknown;
21
+ try {
22
+ await service({}).load('admin');
23
+ } catch (e) {
24
+ error = e;
25
+ }
26
+ expect(error).to.be.instanceOf(UsernameNotFoundError);
27
+ });
28
+
29
+ it('loads the user of cell.security', async () => {
30
+ const user = await service({ username: 'tom', password: 'hash' }).load('tom');
31
+ expect(user.username).to.equal('tom');
32
+ expect(user.password).to.equal('hash');
33
+ });
34
+ });
35
+
36
+ describe('UserSourceCheck', () => {
37
+ it('warns when the default UserService has no configured user', () => {
38
+ expect(check(service({}))).to.have.length(1);
39
+ expect(check(service({ username: 'tom' }))).to.have.length(1);
40
+ });
41
+
42
+ it('is quiet with a configured user or a UserService of the application', () => {
43
+ expect(check(service({ username: 'tom', password: 'hash' }))).to.have.length(0);
44
+ expect(check({ load: async () => ({}) })).to.have.length(0);
45
+ });
46
+ });