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

feat: Rotate WebRTC Direct certificates #2997

Open
wants to merge 2 commits into
base: main
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
1 change: 1 addition & 0 deletions packages/transport-webrtc/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ export interface TransportCertificate {
* The hash of the certificate
*/
certhash: string
notAfter: string
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would be better as a number so we don't have to convert the string back to a date in order to see if the cert is about to expire, instead it can just be compared to Date.now() - threshold .

}

export type { WebRTCTransportDirectInit, WebRTCDirectTransportComponents }
Expand Down
19 changes: 14 additions & 5 deletions packages/transport-webrtc/src/private-to-public/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export interface WebRTCDirectListenerInit {
dataChannel?: DataChannelOptions
rtcConfiguration?: RTCConfiguration | (() => RTCConfiguration | Promise<RTCConfiguration>)
useLibjuice?: boolean
certificateDuration?: number
}

export interface WebRTCListenerMetrics {
Expand Down Expand Up @@ -83,6 +84,15 @@ export class WebRTCDirectListener extends TypedEventEmitter<ListenerEvents> impl
}
}

private isCertificateExpiring (): boolean {
if (this.certificate == null) return true
const expiryDate = new Date(this.certificate.notAfter)
const now = new Date()
const timeToExpiry = expiryDate.getTime() - now.getTime()
const threshold = 30 * 24 * 60 * 60 * 1000
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

threshold should be configurable.

return timeToExpiry < threshold
}

async listen (ma: Multiaddr): Promise<void> {
const parts = ma.stringTuples()
const ipVersion = IP4.matches(ma) ? 4 : 6
Expand Down Expand Up @@ -154,20 +164,19 @@ export class WebRTCDirectListener extends TypedEventEmitter<ListenerEvents> impl
server: Promise.resolve()
.then(async (): Promise<StunServer> => {
// ensure we have a certificate
if (this.certificate == null) {
if (this.certificate == null || this.isCertificateExpiring()) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check will only run when the node is started.

If the certificate expires while the node is running it will continue using it and connections will start to fail.

Instead a timeout should be set that fires a short(ish) time before the certificate expiry that creates a new certificate, restarts the server with the new cert and emits the "listening" event.

this.log.trace('creating TLS certificate')
const keyPair = await crypto.subtle.generateKey({
name: 'ECDSA',
namedCurve: 'P-256'
}, true, ['sign', 'verify'])

const certificate = await generateTransportCertificate(keyPair, {
days: 365 * 10
days: this.init.certificateDuration ?? 365 * 10
})
this.safeDispatchEvent('listening')

if (this.certificate == null) {
this.certificate = certificate
}
this.certificate = certificate
}

if (port === 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export async function generateTransportCertificate (keyPair: CryptoKeyPair, opti
return {
privateKey: privateKeyPem,
pem: cert.toString('pem'),
certhash: base64url.encode((await sha256.digest(new Uint8Array(cert.rawData))).bytes)
certhash: base64url.encode((await sha256.digest(new Uint8Array(cert.rawData))).bytes),
notAfter: notAfter.toISOString()
}
}
80 changes: 80 additions & 0 deletions packages/transport-webrtc/test/certificate.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Crypto } from '@peculiar/webcrypto'
import { expect } from 'aegir/utils/chai.js'
import sinon from 'sinon'
import { WebRTCDirectListener, type WebRTCDirectListenerInit } from '../src/private-to-public/listener.js'
import { type WebRTCDirectTransportComponents } from '../src/private-to-public/transport.js'
import { generateTransportCertificate } from '../src/private-to-public/utils/generate-certificates.js'
import type { TransportCertificate } from '../src/index.js'

const crypto = new Crypto()

describe('WebRTCDirectListener', () => {
let listener: WebRTCDirectListener
let components: WebRTCDirectTransportComponents
let init: WebRTCDirectListenerInit

beforeEach(() => {
components = {
peerId: { toB58String: () => 'QmPeerId' } as any,
privateKey: {} as any,
logger: {
forComponent: () => ({
trace: () => {},
error: () => {}
})
} as any,
Comment on lines +18 to +25
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These fields can be filled using actual values, see other tests here for an example.

transportManager: {} as any
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use stubInterface<TransportManager>() from sinon-ts here to avoid casting to any.

}

init = {
certificateDuration: 10,
upgrader: {} as any
}

listener = new WebRTCDirectListener(components, init)
})

afterEach(() => {
sinon.restore()
})

it('should generate a certificate with the configured duration', async () => {
const keyPair = await crypto.subtle.generateKey({
name: 'ECDSA',
namedCurve: 'P-256'
}, true, ['sign', 'verify'])

const certificate: TransportCertificate = await generateTransportCertificate(keyPair, {
days: init.certificateDuration!
})

expect(new Date(certificate.notAfter).getTime()).to.be.closeTo(
new Date().getTime() + init.certificateDuration! * 86400000,
1000
)
})

it('should re-emit listening event when a new certificate is generated', async () => {
const emitSpy = sinon.spy(listener as any, 'safeDispatchEvent')
const generateCertificateSpy = sinon.spy(generateTransportCertificate)

await (listener as any).startUDPMuxServer('127.0.0.1', 0)

expect(generateCertificateSpy.called).to.be.true
expect(emitSpy.calledWith('listening')).to.be.true
})

it('should generate a new certificate before expiry', async () => {
(listener as any).certificate = {
notAfter: new Date(Date.now() + 5 * 86400000).toISOString()
}

const isCertificateExpiringSpy = sinon.spy(listener as any, 'isCertificateExpiring')
const generateCertificateSpy = sinon.spy(generateTransportCertificate)

await (listener as any).startUDPMuxServer('127.0.0.1', 0)

expect(isCertificateExpiringSpy.returned(true)).to.be.true
expect(generateCertificateSpy.called).to.be.true
})
})