-
Notifications
You must be signed in to change notification settings - Fork 14
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(certificates): implement certificate manager #89
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
101 changes: 101 additions & 0 deletions
101
src/certificates/certificate-manager/CertificateManager.spec.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
import { faker } from "@faker-js/faker"; | ||
|
||
import { CertificateManager } from "./CertificateManager"; | ||
|
||
describe("CertificateManager", () => { | ||
let certificateManager: CertificateManager; | ||
let address: string; | ||
|
||
beforeEach(() => { | ||
certificateManager = new CertificateManager(); | ||
address = `akash1${faker.string.alpha({ length: 38 })}`; | ||
}); | ||
|
||
describe("prototype.generateCertificate", () => { | ||
it("should generate certificate PEMs with the default validity range", () => { | ||
const now = new Date(); | ||
now.setMilliseconds(0); | ||
const inOneYear = getTime1yearFrom(now); | ||
const pem = certificateManager.generatePEM(address); | ||
const meta = certificateManager.parsePem(pem.cert); | ||
|
||
expect(pem).toMatchObject({ | ||
cert: expect.stringMatching(/^-----BEGIN CERTIFICATE-----[\s\S]*-----END CERTIFICATE-----\r\n$/), | ||
publicKey: expect.stringMatching(/^-----BEGIN EC PUBLIC KEY-----[\s\S]*-----END EC PUBLIC KEY-----\r\n$/), | ||
privateKey: expect.stringMatching(/^-----BEGIN PRIVATE KEY-----[\s\S]*-----END PRIVATE KEY-----\r\n$/) | ||
}); | ||
expect(new Date(meta.issuedOn).getTime()).toBeGreaterThanOrEqual(now.getTime()); | ||
expect(new Date(meta.issuedOn).getTime()).toBeLessThan(new Date().getTime()); | ||
expect(new Date(meta.expiresOn).getTime()).toBeGreaterThanOrEqual(inOneYear); | ||
expect(new Date(meta.issuedOn).getTime()).toBeLessThan(getTime1yearFrom(new Date())); | ||
}); | ||
}); | ||
|
||
it("should generate certificate PEMs with the provided validity range", () => { | ||
const now = new Date(); | ||
const MONTH = 1000 * 60 * 60 * 24 * 30; | ||
const inOneMonth = new Date(now.getTime() + MONTH); | ||
const inTwoMonths = new Date(now.getTime() + MONTH * 2); | ||
const pem = certificateManager.generatePEM(address, { | ||
validFrom: inOneMonth, | ||
validTo: inTwoMonths | ||
}); | ||
const meta = certificateManager.parsePem(pem.cert); | ||
|
||
expect(pem).toMatchObject({ | ||
cert: expect.stringMatching(/^-----BEGIN CERTIFICATE-----[\s\S]*-----END CERTIFICATE-----\r\n$/), | ||
publicKey: expect.stringMatching(/^-----BEGIN EC PUBLIC KEY-----[\s\S]*-----END EC PUBLIC KEY-----\r\n$/), | ||
privateKey: expect.stringMatching(/^-----BEGIN PRIVATE KEY-----[\s\S]*-----END PRIVATE KEY-----\r\n$/) | ||
}); | ||
|
||
inOneMonth.setMilliseconds(0); | ||
inTwoMonths.setMilliseconds(0); | ||
expect(new Date(meta.issuedOn).getTime()).toBe(inOneMonth.getTime()); | ||
expect(new Date(meta.expiresOn).getTime()).toBe(inTwoMonths.getTime()); | ||
}); | ||
|
||
describe("prototype.parsePem", () => { | ||
it("should extract certificate data", () => { | ||
const cert = certificateManager.parsePem(certificateManager.generatePEM(address).cert); | ||
|
||
expect(cert).toMatchObject({ | ||
hSerial: expect.any(String), | ||
sIssuer: expect.any(String), | ||
sSubject: expect.any(String), | ||
sNotBefore: expect.any(String), | ||
sNotAfter: expect.any(String), | ||
issuedOn: expect.any(Date), | ||
expiresOn: expect.any(Date) | ||
}); | ||
}); | ||
}); | ||
|
||
describe("prototype.strToDate", () => { | ||
it("should convert string to date", () => { | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
// @ts-expect-error | ||
const date = certificateManager.strToDate("240507122350Z"); | ||
|
||
expect(date).toBeInstanceOf(Date); | ||
expect(date.toISOString()).toBe("2024-05-07T12:23:50.000Z"); | ||
}); | ||
}); | ||
|
||
describe("prototype.dateToStr", () => { | ||
it("should convert date to string", () => { | ||
const date = new Date("2024-05-07T12:23:50.000Z"); | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
// @ts-expect-error | ||
const str = certificateManager.dateToStr(date); | ||
|
||
expect(str).toBe("240507122350Z"); | ||
}); | ||
}); | ||
}); | ||
|
||
function getTime1yearFrom(date = new Date()): number { | ||
const clone = new Date(date); | ||
const inOneYear = new Date(date); | ||
inOneYear.setFullYear(clone.getFullYear() + 1); | ||
return inOneYear.getTime(); | ||
} |
114 changes: 114 additions & 0 deletions
114
src/certificates/certificate-manager/CertificateManager.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
// @ts-expect-error | ||
import rs from "jsrsasign"; | ||
|
||
export interface CertificatePem { | ||
cert: string; | ||
publicKey: string; | ||
privateKey: string; | ||
} | ||
|
||
export interface CertificateInfo { | ||
hSerial: string; | ||
sIssuer: string; | ||
sSubject: string; | ||
sNotBefore: string; | ||
sNotAfter: string; | ||
issuedOn: Date; | ||
expiresOn: Date; | ||
} | ||
|
||
export interface ValidityRangeOptions { | ||
validFrom?: Date; | ||
validTo?: Date; | ||
} | ||
|
||
export class CertificateManager { | ||
parsePem(certPEM: string): CertificateInfo { | ||
const certificate = new rs.X509(); | ||
certificate.readCertPEM(certPEM); | ||
const hSerial: string = certificate.getSerialNumberHex(); | ||
const sIssuer: string = certificate.getIssuerString(); | ||
const sSubject: string = certificate.getSubjectString(); | ||
const sNotBefore: string = certificate.getNotBefore(); | ||
const sNotAfter: string = certificate.getNotAfter(); | ||
|
||
return { | ||
hSerial, | ||
sIssuer, | ||
sSubject, | ||
sNotBefore, | ||
sNotAfter, | ||
issuedOn: this.strToDate(sNotBefore), | ||
expiresOn: this.strToDate(sNotAfter) | ||
}; | ||
} | ||
|
||
generatePEM(address: string, options?: ValidityRangeOptions): CertificatePem { | ||
const { notBeforeStr, notAfterStr } = this.createValidityRange(options); | ||
const { prvKeyObj, pubKeyObj } = rs.KEYUTIL.generateKeypair("EC", "secp256r1"); | ||
const cert = new rs.KJUR.asn1.x509.Certificate({ | ||
version: 3, | ||
serial: { int: Math.floor(new Date().getTime() * 1000) }, | ||
issuer: { str: "/CN=" + address }, | ||
notbefore: notBeforeStr, | ||
notafter: notAfterStr, | ||
subject: { str: "/CN=" + address }, | ||
sbjpubkey: pubKeyObj, | ||
ext: [ | ||
{ extname: "keyUsage", critical: true, names: ["keyEncipherment", "dataEncipherment"] }, | ||
{ | ||
extname: "extKeyUsage", | ||
array: [{ name: "clientAuth" }] | ||
}, | ||
{ extname: "basicConstraints", cA: true, critical: true } | ||
], | ||
sigalg: "SHA256withECDSA", | ||
cakey: prvKeyObj | ||
}); | ||
const publicKey: string = rs.KEYUTIL.getPEM(pubKeyObj, "PKCS8PUB").replaceAll("PUBLIC KEY", "EC PUBLIC KEY"); | ||
const certPEM: string = cert.getPEM(); | ||
|
||
return { | ||
cert: certPEM, | ||
publicKey, | ||
privateKey: rs.KEYUTIL.getPEM(prvKeyObj, "PKCS8PRV") | ||
}; | ||
} | ||
|
||
private createValidityRange(options?: ValidityRangeOptions) { | ||
const notBefore = options?.validFrom || new Date(); | ||
const notAfter = options?.validTo || new Date(); | ||
|
||
if (!options?.validTo) { | ||
notAfter.setFullYear(notBefore.getFullYear() + 1); | ||
} | ||
|
||
const notBeforeStr = this.dateToStr(notBefore); | ||
const notAfterStr = this.dateToStr(notAfter); | ||
|
||
return { notBeforeStr, notAfterStr }; | ||
} | ||
|
||
private dateToStr(date: Date): string { | ||
const year = date.getUTCFullYear().toString().substring(2).padStart(2, "0"); | ||
const month = (date.getUTCMonth() + 1).toString().padStart(2, "0"); | ||
const day = date.getUTCDate().toString().padStart(2, "0"); | ||
const hours = date.getUTCHours().toString().padStart(2, "0"); | ||
const minutes = date.getUTCMinutes().toString().padStart(2, "0"); | ||
const secs = date.getUTCSeconds().toString().padStart(2, "0"); | ||
|
||
return `${year}${month}${day}${hours}${minutes}${secs}Z`; | ||
} | ||
|
||
private strToDate(str: string): Date { | ||
const year = parseInt(`20${str.substring(0, 2)}`); | ||
const month = parseInt(str.substring(2, 4)) - 1; | ||
const day = parseInt(str.substring(4, 6)); | ||
const hours = parseInt(str.substring(6, 8)); | ||
const minutes = parseInt(str.substring(8, 10)); | ||
const secs = parseInt(str.substring(10, 12)); | ||
|
||
return new Date(Date.UTC(year, month, day, hours, minutes, secs)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
import { CertificateManager } from "./CertificateManager"; | ||
|
||
const certificateManager = new CertificateManager(); | ||
|
||
export { CertificateManager, certificateManager }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No need to add right now, but it would be nice to be able to specify the expiry date when creating a cert.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
not a big deal, here u are https://github.com/akash-network/akashjs/pull/89/files#diff-dda604b0726bf284b6caf45c9edcb587ed8b9ce1c1cda250de7a39aed1eea1cbR79