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

Utilise Eddsa signature in the application #790

Closed
wants to merge 16 commits into from
Closed
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
2 changes: 1 addition & 1 deletion examples/bri-3/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ model BpiAccountStateTreeLeafValue {
}

model PublicKey {
id String @id @default(uuid())
id String @id @default(uuid())
type PublicKeyType
value String @unique
bpiSubjectId String
Expand Down
40 changes: 28 additions & 12 deletions examples/bri-3/prisma/seed.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { PrismaClient } from '@prisma/client';
import { PrismaClient, PublicKeyType } from '@prisma/client';

const prisma = new PrismaClient();

Expand All @@ -21,19 +21,35 @@ async function main() {
},
});

await prisma.bpiSubject.create({
const internalBpiSubject = await prisma.bpiSubject.create({
data: {
name: 'BpiAdmin',
description: 'Internal Bpi Subject of this Bpi',
publicKey: '0x044e851fa6118d0d33f11ebf8d4cae2a25dca959f06c1ab87b8fec9ccbf0ca0021b7efc27c786f9480f9f11cfe8df1ae991329654308611148a35a2277ba5909fe',
// private key 0x0fbdb56ab0fecb2f406fa807d9e6558baedacc1c15c0e2703b77d4c08441e4fe, used for testing purposes only
loginNonce: '',
roles: {
connect: {
id: internalBpiSubjectRole.id
},
name: 'BpiAdmin',
description: 'Internal Bpi Subject of this Bpi',
// private key 0x0fbdb56ab0fecb2f406fa807d9e6558baedacc1c15c0e2703b77d4c08441e4fe, used for testing purposes only
loginNonce: '',
roles: {
connect: {
id: internalBpiSubjectRole.id,
},
}
},
},
});

await prisma.publicKey.createMany({
data: [
{
type: PublicKeyType.ECDSA,
value:
'0x044e851fa6118d0d33f11ebf8d4cae2a25dca959f06c1ab87b8fec9ccbf0ca0021b7efc27c786f9480f9f11cfe8df1ae991329654308611148a35a2277ba5909fe',
bpiSubjectId: internalBpiSubject.id,
},
{
type: PublicKeyType.EDDSA,
value:
'0x044e851fa6118d0d33f11ebf8d4cae2a25dca959f06c1ab87b8fec9ccbf0ca0021b7efc27c786f9480f9f11cfe8df1ae991329654308611148a35a2277ba5909fe',
bpiSubjectId: internalBpiSubject.id,
},
],
});
}
main()
Expand Down
42 changes: 40 additions & 2 deletions examples/bri-3/src/bri/auth/agent/auth.agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { BpiSubject } from '../../../bri/identity/bpiSubjects/models/bpiSubject'
import { LoggingService } from '../../../shared/logging/logging.service';
import { INVALID_SIGNATURE, USER_NOT_AUTHORIZED } from '../api/err.messages';
import { jwtConstants } from '../constants';
import { buildBabyjub, buildEddsa } from 'circomlibjs';
import * as crypto from 'crypto';

@Injectable()
export class AuthAgent {
Expand All @@ -23,12 +25,14 @@ export class AuthAgent {
signature: string,
publicKey: string,
): void {
if (!this.verifySignatureAgainstPublicKey(message, signature, publicKey)) {
if (
!this.verifyEcdsaSignatureAgainstPublicKey(message, signature, publicKey)
) {
throw new UnauthorizedException(INVALID_SIGNATURE);
}
}

verifySignatureAgainstPublicKey(
verifyEcdsaSignatureAgainstPublicKey(
message: string,
signature: string,
senderPublicKey: string,
Expand Down Expand Up @@ -63,6 +67,40 @@ export class AuthAgent {
return isValid;
}

async verifyEddsaSignatureAgainstPublicKey(
message: string,
signature: string,
senderPublicKey: string,
): Promise<boolean> {
const eddsa = await buildEddsa();
const babyJub = await buildBabyjub();

const hashedPayload = crypto
.createHash(`${process.env.MERKLE_TREE_HASH_ALGH}`)
.update(JSON.stringify(message))
.digest();

const publicKey = Uint8Array.from(Buffer.from(signature, 'hex'));
const publicKeyPoints = babyJub.unpackPoint(publicKey);

const eddsaSignature = Uint8Array.from(Buffer.from(signature, 'hex'));
const unpackedSignature = eddsa.unpackSignature(eddsaSignature);

const isValid = eddsa.verifyPedersen(
hashedPayload,
unpackedSignature,
publicKeyPoints,
);

if (!isValid) {
this.logger.logWarn(
`Signature: ${signature} for public key ${senderPublicKey} is invalid.`,
);
}

return isValid;
}

async getBpiSubjectByPublicKey(publicKey: string) {
return this.bpiSubjectStorageAgent.getBpiSubjectByPublicKey(publicKey);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ import { MessageController } from './messages.controller';
import { mockDeep, DeepMockProxy } from 'jest-mock-extended';
import { PrismaService } from '../../../shared/prisma/prisma.service';
import { PrismaClient } from '@prisma/client';
import {
PublicKey,
PublicKeyType,
} from '../../identity/bpiSubjects/models/publicKey';

describe('MessageController', () => {
let mController: MessageController;
Expand All @@ -52,20 +56,37 @@ describe('MessageController', () => {
});

beforeEach(async () => {
existingBpiSubject1 = new BpiSubject(
'',
'name',
'desc',
'0x047a197a795a747c154dd92b217a048d315ef9ca1bfa9c15bfefe4e02fb338a70af23e7683b565a8dece5104a85ed24a50d791d8c5cb09ee21aabc927c98516539',
[],
);
existingBpiSubject2 = new BpiSubject(
'',
'name2',
'desc2',
'0x04203db7d27bab8d711acc52479efcfa9d7846e4e176d82389689f95cf06a51818b0b9ab1c2c8d72f1a32e236e6296c91c922a0dc3d0cb9afc269834fc5646b980',
[],
);
const publicKeys1 = [
new PublicKey(
'111',
PublicKeyType.ECDSA,
'0x047a197a795a747c154dd92b217a048d315ef9ca1bfa9c15bfefe4e02fb338a70af23e7683b565a8dece5104a85ed24a50d791d8c5cb09ee21aabc927c98516539',
'123',
),
new PublicKey(
'112',
PublicKeyType.EDDSA,
'0x047a197a795a747c154dd92b217a048d315ef9ca1bfa9c15bfefe4e02fb338a70af23e7683b565a8dece5104a85ed24a50d791d8c5cb09ee21aabc927c98516539',
'123',
),
];
existingBpiSubject1 = new BpiSubject('', 'name', 'desc', publicKeys1, []);

const publicKeys2 = [
new PublicKey(
'111',
PublicKeyType.ECDSA,
'0x04203db7d27bab8d711acc52479efcfa9d7846e4e176d82389689f95cf06a51818b0b9ab1c2c8d72f1a32e236e6296c91c922a0dc3d0cb9afc269834fc5646b980',
'123',
),
new PublicKey(
'112',
PublicKeyType.EDDSA,
'0x04203db7d27bab8d711acc52479efcfa9d7846e4e176d82389689f95cf06a51818b0b9ab1c2c8d72f1a32e236e6296c91c922a0dc3d0cb9afc269834fc5646b980',
'123',
),
];
existingBpiSubject2 = new BpiSubject('', 'name2', 'desc2', publicKeys2, []);

existingBpiMessage = new BpiMessage(
'f3e4295d-6a2a-4f04-8477-02f781eb93f8',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { BpiMessageAgent } from '../../agents/bpiMessages.agent';
import { BpiMessageStorageAgent } from '../../agents/bpiMessagesStorage.agent';
import { MessagingAgent } from '../../agents/messaging.agent';
import { CreateBpiMessageCommand } from './createBpiMessage.command';
import { PublicKeyType } from '../../../identity/bpiSubjects/models/publicKey';

@CommandHandler(CreateBpiMessageCommand)
export class CreateBpiMessageCommandHandler
Expand All @@ -30,7 +31,9 @@ export class CreateBpiMessageCommandHandler
this.authAgent.throwIfSignatureVerificationFails(
command.content,
command.signature,
fromBpiSubject.publicKey,
fromBpiSubject.publicKeys.filter(
(key) => key.type == PublicKeyType.ECDSA,
)[0].value,
);

const newBpiMessageCandidate = this.agent.createNewBpiMessage(
Expand All @@ -47,7 +50,9 @@ export class CreateBpiMessageCommandHandler
);

await this.messagingAgent.publishMessage(
toBpiSubject.publicKey,
toBpiSubject.publicKeys.filter(
(key) => key.type == PublicKeyType.ECDSA,
)[0].value,
this.messagingAgent.serializeBpiMessage(newBpiMessage),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { BpiMessageAgent } from '../../agents/bpiMessages.agent';
import { BpiMessageStorageAgent } from '../../agents/bpiMessagesStorage.agent';
import { MessagingAgent } from '../../agents/messaging.agent';
import { ProcessInboundBpiMessageCommand } from './processInboundMessage.command';
import { PublicKeyType } from '../../../identity/bpiSubjects/models/publicKey';

// Difference between this and the create bpi message command handler is that this one does not
// stop the execution flow by throwing a nestjs exception (which results in 404 response in the other handler)
Expand Down Expand Up @@ -31,11 +32,14 @@ export class ProcessInboundMessageCommandHandler
return false;
}

const isSignatureValid = this.authAgent.verifySignatureAgainstPublicKey(
command.content,
command.signature,
fromBpiSubject.publicKey,
);
const isSignatureValid =
this.authAgent.verifyEddsaSignatureAgainstPublicKey(
command.content,
command.signature,
fromBpiSubject.publicKeys.filter(
(key) => key.type == PublicKeyType.EDDSA,
)[0].value,
);

if (!isSignatureValid) {
return false;
Expand All @@ -55,7 +59,9 @@ export class ProcessInboundMessageCommandHandler
);

await this.messagingAgent.publishMessage(
toBpiSubject.publicKey,
toBpiSubject.publicKeys.filter(
(key) => key.type == PublicKeyType.ECDSA,
)[0].value,
this.messagingAgent.serializeBpiMessage(newBpiMessage),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { SubjectsProfile } from '../../bpiSubjects/subjects.profile';
import { mockDeep, DeepMockProxy } from 'jest-mock-extended';
import { BpiSubjectAccount } from '../models/bpiSubjectAccount';
import { uuid } from 'uuidv4';
import { PublicKey, PublicKeyType } from '../../bpiSubjects/models/publicKey';

describe('SubjectAccountController', () => {
let subjectAccountController: SubjectAccountController;
Expand Down Expand Up @@ -66,18 +67,22 @@ describe('SubjectAccountController', () => {
});

const createBpiSubjectAccount = async () => {
const publicKeys = [
new PublicKey('111', PublicKeyType.ECDSA, 'ecdsaPk', '123'),
new PublicKey('112', PublicKeyType.EDDSA, 'eddsaPk', '123'),
];
const ownerBpiSubject = new BpiSubject(
'123',
'owner',
'desc',
'publicKey',
publicKeys,
[],
);
const creatorBpiSubject = new BpiSubject(
'321',
'creator',
'desc',
'publicKey',
publicKeys,
[],
);

Expand Down Expand Up @@ -191,11 +196,15 @@ describe('SubjectAccountController', () => {
describe('createBpiSubjectAccount', () => {
it('should throw BadRequest if non existent creator provided', async () => {
// Arrange
const publicKeys = [
new PublicKey('111', PublicKeyType.ECDSA, 'ecdsaPk', '123'),
new PublicKey('112', PublicKeyType.EDDSA, 'eddsaPk', '123'),
];
const ownerBpiSubject = new BpiSubject(
'123',
'owner',
'desc',
'publicKey',
publicKeys,
[],
);
const creatorBpiSubjectId = 'not-existing-id';
Expand All @@ -215,11 +224,15 @@ describe('SubjectAccountController', () => {

it('should throw BadRequest if non existent owner provided', async () => {
// Arrange
const publicKeys = [
new PublicKey('111', PublicKeyType.ECDSA, 'ecdsaPk', '123'),
new PublicKey('112', PublicKeyType.EDDSA, 'eddsaPk', '123'),
];
const creatorBpiSubject = new BpiSubject(
'123',
'creator',
'desc',
'publicKey',
publicKeys,
[],
);
const ownerBpiSubjectId = 'not-existing-id';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
} from '../api/err.messages';
import { BpiSubjectStorageAgent } from './bpiSubjectsStorage.agent';
import { BpiSubjectRoleName } from '../models/bpiSubjectRole';
import { PublicKey } from '../models/publicKey';

Check warning on line 14 in examples/bri-3/src/bri/identity/bpiSubjects/agents/bpiSubjects.agent.ts

View workflow job for this annotation

GitHub Actions / ci (ubuntu-latest, 17.0.0)

'PublicKey' is defined but never used

// Agent methods have extremely declarative names and perform a single task
@Injectable()
Expand All @@ -27,12 +28,11 @@
public async createNewExternalBpiSubject(
name: string,
description: string,
publicKey: string,
): Promise<BpiSubject> {
const externalRole = await this.storageAgent.getBpiSubjectRoleByName(
BpiSubjectRoleName.EXTERNAL_BPI_SUBJECT,
);
return new BpiSubject(v4(), name, description, publicKey, [externalRole]);
return new BpiSubject(v4(), name, description, [], [externalRole]);
}

public async fetchUpdateCandidateAndThrowIfUpdateValidationFails(
Expand Down Expand Up @@ -64,11 +64,9 @@
bpiSubjectToUpdate: BpiSubject,
name: string,
description: string,
publicKey: string,
) {
bpiSubjectToUpdate.updateName(name);
bpiSubjectToUpdate.updateDescription(description);
bpiSubjectToUpdate.updatePublicKey(publicKey);
}

public async fetchDeleteCandidateAndThrowIfDeleteValidationFails(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ export class BpiSubjectStorageAgent extends PrismaService {
};
}),
},
publicKey: {
publicKeys: {
connect: bpiSubject.publicKeys.map((pk) => {
return {
id: pk.id,
Expand All @@ -131,7 +131,7 @@ export class BpiSubjectStorageAgent extends PrismaService {
};
}),
},
publicKey: {
publicKeys: {
connect: bpiSubject.publicKeys.map((pk) => {
return {
id: pk.id,
Expand All @@ -152,14 +152,14 @@ export class BpiSubjectStorageAgent extends PrismaService {
async getBpiSubjectByPublicKey(publicKeyValue: string): Promise<BpiSubject> {
const bpiSubjectModel = await this.prisma.bpiSubject.findFirst({
where: {
publicKey: {
publicKeys: {
some: {
value: publicKeyValue,
},
},
},
include: {
publicKey: true,
publicKeys: true,
},
});

Expand Down
Loading
Loading