Skip to content

Commit

Permalink
test websocket authz
Browse files Browse the repository at this point in the history
  • Loading branch information
finn-block committed Nov 8, 2023
1 parent 6e0509f commit 040069c
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 28 deletions.
8 changes: 7 additions & 1 deletion src/pow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ export class ProofOfWork {
return result.length > 0;
}

async authorizeTenant(tenant: string): Promise<void> {
await this.#db
.insertInto('authorizedTenants')
.values({ did: tenant })
.executeTakeFirst();
}

private async getChallenge(_req: Request, res: Response): Promise<void> {
const challenge = generateChallenge();
recentChallenges[challenge] = Date.now();
Expand All @@ -74,7 +81,6 @@ export class ProofOfWork {

const complexity = getComplexity();
const digest = hash.digest('hex');
console.log('digest: ', digest);
if (!digest.startsWith('0'.repeat(complexity))) {
res.status(401).json({ success: false });
return;
Expand Down
28 changes: 2 additions & 26 deletions tests/http-api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
} from '@tbd54566975/dwn-sdk-js';

import { expect } from 'chai';
import { createHash } from 'crypto';
import type { Server } from 'http';
import fetch from 'node-fetch';
import { webcrypto } from 'node:crypto';
Expand All @@ -33,6 +32,8 @@ import {
createRecordsWriteMessage,
getFileAsReadStream,
streamHttpRequest,
checkNonce,
generateNonce,
} from './utils.js';

if (!globalThis.crypto) {
Expand Down Expand Up @@ -633,28 +634,3 @@ describe('http api', function () {
});
});
});

const nonceChars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function generateNonce(size: number): string {
let challenge = '';
while (challenge.length < size) {
challenge += nonceChars.charAt(
Math.floor(Math.random() * nonceChars.length),
);
}
return challenge;
}

function checkNonce(
challenge: string,
nonce: string,
complexity: number,
): boolean {
const hash = createHash('sha256');
hash.update(challenge);
hash.update(nonce);

return hash.digest('hex').startsWith('0'.repeat(complexity));
}
26 changes: 26 additions & 0 deletions tests/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
RecordsWrite,
} from '@tbd54566975/dwn-sdk-js';

import { createHash } from 'crypto';
import type { ReadStream } from 'node:fs';
import fs from 'node:fs';
import http from 'node:http';
Expand Down Expand Up @@ -188,3 +189,28 @@ export async function sendWsMessage(
};
});
}

const nonceChars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

export function generateNonce(size: number): string {
let challenge = '';
while (challenge.length < size) {
challenge += nonceChars.charAt(
Math.floor(Math.random() * nonceChars.length),
);
}
return challenge;
}

export function checkNonce(
challenge: string,
nonce: string,
complexity: number,
): boolean {
const hash = createHash('sha256');
hash.update(challenge);
hash.update(nonce);

return hash.digest('hex').startsWith('0'.repeat(complexity));
}
10 changes: 9 additions & 1 deletion tests/ws-api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
createJsonRpcRequest,
JsonRpcErrorCodes,
} from '../src/lib/json-rpc.js';
import { ProofOfWork } from '../src/pow.js';
import { getDialectFromURI } from '../src/storage.js';
import { WsApi } from '../src/ws-api.js';
import { clear as clearDwn, dwn } from './test-dwn.js';
import {
Expand All @@ -20,14 +22,17 @@ import {

let server: http.Server;
let wsServer: WebSocketServer;
let pow: ProofOfWork;

describe('websocket api', function () {
before(async function () {
server = http.createServer();
server.listen(9002, '127.0.0.1');

const wsApi = new WsApi(server, dwn);
pow = new ProofOfWork(getDialectFromURI(new URL('sqlite://')));
const wsApi = new WsApi(server, dwn, pow);
wsServer = wsApi.start();
await pow.initialize();
});

afterEach(async function () {
Expand Down Expand Up @@ -61,6 +66,8 @@ describe('websocket api', function () {

it('handles RecordsWrite messages', async function () {
const alice = await createProfile();
pow.authorizeTenant(alice.did);

const { recordsWrite, dataStream } = await createRecordsWriteMessage(alice);
const dataBytes = await DataStream.toBytes(dataStream);
const encodedData = base64url.baseEncode(dataBytes);
Expand All @@ -78,6 +85,7 @@ describe('websocket api', function () {
);
const resp = JSON.parse(data.toString());
expect(resp.id).to.equal(requestId);
console.log(resp.error);
expect(resp.error).to.not.exist;

const { reply } = resp.result;
Expand Down

0 comments on commit 040069c

Please sign in to comment.