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

[discuss] Asymmetric authentication #812

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
27 changes: 27 additions & 0 deletions packages/asymmetric/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# @accounts/asymmetric

## Install

```
yarn add @accounts/asymmetric
```

## Usage

```js
import { AccountsServer } from '@accounts/server';
import { AccountsAsymmetric } from '@accounts/asymmetric';

export const accountsAsymmetric = new AccountsAsymmetric({
// options
});

const accountsServer = new AccountsServer(
{
// options
},
{
asymmetric: accountsAsymmetric,
}
);
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`AccountsAsymmetric throws error when the user is not found by public key 1`] = `[Error: User not found]`;
215 changes: 215 additions & 0 deletions packages/asymmetric/__tests__/accounts-asymmetric.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
import * as crypto from 'crypto';

import { PublicKeyType } from '../src/types';
import { AccountsAsymmetric } from '../src';

describe('AccountsAsymmetric', () => {
it('should update the public key', async () => {
const { publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 512,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
});

const service = new AccountsAsymmetric();

const setService = jest.fn(() => Promise.resolve(null));
service.setStore({ setService } as any);

const publicKeyParams: PublicKeyType = {
key: publicKey,
encoding: 'base64',
format: 'pem',
type: 'spki',
};

const res = await service.updatePublicKey('123', publicKeyParams);

expect(res).toBeTruthy();
expect(setService).toHaveBeenCalledWith('123', service.serviceName, {
id: publicKey,
...publicKeyParams,
});
});

it('throws error when the user is not found by public key', async () => {
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 512,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
});
const payload = 'some data to sign';

const sign = crypto.createSign('SHA256');
sign.write(payload);
sign.end();
const signature = sign.sign(privateKey, 'hex');

const service = new AccountsAsymmetric();

const findUserByServiceId = jest.fn(() => Promise.resolve(null));
service.setStore({ findUserByServiceId } as any);

await expect(
service.authenticate({
signature,
payload,
publicKey,
signatureAlgorithm: 'sha512',
signatureFormat: 'hex',
})
).rejects.toMatchSnapshot();
});

it('should return null when signature is invalid', async () => {
const { publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 512,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
});
const payload = 'some data to sign';

const service = new AccountsAsymmetric();

const publicKeyParams: PublicKeyType = {
key: publicKey,
encoding: 'base64',
format: 'pem',
type: 'pkcs1',
};

const user = {
id: '123',
services: {
[service.serviceName]: publicKeyParams,
},
};
const findUserByServiceId = jest.fn(() => Promise.resolve(user));
service.setStore({ findUserByServiceId } as any);

const userFromService = await service.authenticate({
signature: 'some signature',
payload,
publicKey: publicKey,
signatureAlgorithm: 'sha256',
signatureFormat: 'hex',
});

expect(userFromService).toBeNull();
});

it('should return user when verification is successful', async () => {
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 512,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
});
const payload = 'some data to sign';

const sign = crypto.createSign('sha256');
sign.write(payload);
sign.end();
const signature = sign.sign(privateKey, 'hex');

const service = new AccountsAsymmetric();

const publicKeyParams: PublicKeyType = {
key: publicKey,
encoding: 'base64',
format: 'pem',
type: 'pkcs1',
};

const user = {
id: '123',
services: {
[service.serviceName]: publicKeyParams,
},
};
const findUserByServiceId = jest.fn(() => Promise.resolve(user));
service.setStore({ findUserByServiceId } as any);

const userFromService = await service.authenticate({
signature,
payload,
publicKey: publicKey,
signatureAlgorithm: 'sha256',
signatureFormat: 'hex',
});

expect(userFromService).toEqual(user);
});

it('should return user when verification is successful using der format', async () => {
const { publicKey: publicKeyBuffer, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 512,
publicKeyEncoding: {
type: 'pkcs1',
format: 'der',
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
});
const publicKey = publicKeyBuffer.toString('base64');
const payload = 'some data to sign';

const sign = crypto.createSign('sha256');
sign.write(payload);
sign.end();
const signature = sign.sign(privateKey, 'hex');

const service = new AccountsAsymmetric();

const publicKeyParams: PublicKeyType = {
key: publicKey,
encoding: 'base64',
format: 'der',
type: 'pkcs1',
};

const user = {
id: '123',
services: {
[service.serviceName]: publicKeyParams,
},
};
const findUserByServiceId = jest.fn(() => Promise.resolve(user));
service.setStore({ findUserByServiceId } as any);

const userFromService = await service.authenticate({
signature,
payload,
publicKey,
signatureAlgorithm: 'sha256',
signatureFormat: 'hex',
});

expect(userFromService).toEqual(user);
});
});
36 changes: 36 additions & 0 deletions packages/asymmetric/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "@accounts/asymmetric",
"version": "0.19.1",
"license": "MIT",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"scripts": {
"clean": "rimraf lib",
"start": "tsc --watch",
"precompile": "yarn clean",
"compile": "tsc",
"prepublishOnly": "yarn compile",
"testonly": "jest",
"coverage": "jest --coverage"
},
"jest": {
"testEnvironment": "node",
"preset": "ts-jest"
},
"dependencies": {
"@accounts/types": "^0.19.0",
"node-forge": "^0.9.1",
"tslib": "1.10.0"
},
"devDependencies": {
"@accounts/server": "^0.19.0",
"@types/jest": "24.0.18",
"@types/node": "10.14.19",
"@types/node-forge": "^0.8.6",
"jest": "24.9.0",
"rimraf": "3.0.0"
},
"peerDependencies": {
"@accounts/server": "^0.19.0"
}
}
92 changes: 92 additions & 0 deletions packages/asymmetric/src/accounts-asymmetric.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import * as crypto from 'crypto';

import { AuthenticationService, DatabaseInterface } from '@accounts/types';
import { AccountsServer } from '@accounts/server';
import forge from 'node-forge';

import { AsymmetricLoginType, PublicKeyType, ErrorMessages } from './types';
import { errors } from './errors';

export interface AccountsAsymmetricOptions {
errors?: ErrorMessages;
}

const defaultOptions = {
errors,
};

export default class AccountsAsymmetric implements AuthenticationService {
public serviceName = 'asymmetric';
public server!: AccountsServer;
private db!: DatabaseInterface;
private options: AccountsAsymmetricOptions & typeof defaultOptions;

constructor(options: AccountsAsymmetricOptions = {}) {
this.options = { ...defaultOptions, ...options };
}

public setStore(store: DatabaseInterface) {
this.db = store;
}

public async updatePublicKey(
userId: string,
{ key, ...params }: PublicKeyType
): Promise<boolean> {
try {
await this.db.setService(userId, this.serviceName, { id: key, key, ...params });
return true;
} catch (e) {
return false;
}
}

public async authenticate(params: AsymmetricLoginType): Promise<any> {
const user = await this.db.findUserByServiceId(this.serviceName, params.publicKey);

if (!user) {
throw new Error(this.options.errors.userNotFound);
}

try {
const verify = crypto.createVerify(params.signatureAlgorithm);
verify.write(params.payload);
verify.end();

const publicKeyParams: PublicKeyType = (user.services as any)[this.serviceName];

const pemText =
publicKeyParams.format === 'pem' ? publicKeyParams.key : this.derToPem(publicKeyParams);

const isVerified = verify.verify(pemText, params.signature, params.signatureFormat);

return isVerified ? user : null;
} catch (e) {
throw new Error(this.options.errors.verificationFailed);
}
}

private derToPem(publicKeyParams: PublicKeyType): string {
let derKey;

switch (publicKeyParams.encoding) {
case 'utf8': {
derKey = forge.util.decodeUtf8(publicKeyParams.key);
break;
}
case 'hex': {
derKey = forge.util.hexToBytes(publicKeyParams.key);
break;
}
case 'base64':
default: {
derKey = forge.util.decode64(publicKeyParams.key);
break;
}
}

const asnObj = forge.asn1.fromDer(derKey);
const publicKey = forge.pki.publicKeyFromAsn1(asnObj);
return forge.pki.publicKeyToPem(publicKey);
}
}
6 changes: 6 additions & 0 deletions packages/asymmetric/src/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { ErrorMessages } from './types';

export const errors: ErrorMessages = {
userNotFound: 'User not found',
verificationFailed: 'Failed to verify signature',
};
5 changes: 5 additions & 0 deletions packages/asymmetric/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import AccountsAsymmetric from './accounts-asymmetric';
export * from './types';

export default AccountsAsymmetric;
export { AccountsAsymmetric };
7 changes: 7 additions & 0 deletions packages/asymmetric/src/types/asymmetric-login-type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export interface AsymmetricLoginType {
publicKey: string;
signature: string;
signatureAlgorithm: 'sha256' | 'sha512';
signatureFormat: 'hex' | 'base64';
payload: string;
}
Loading