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

Enable assertRequired to type narrow #62

Merged
merged 1 commit into from
Apr 14, 2022
Merged
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
5 changes: 3 additions & 2 deletions src/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { assertRequired } from "./utility";
export const keyToPEM = (
key: string | Buffer
): typeof key extends string | Buffer ? string | Buffer : Error => {
key = assertRequired(key, "key is required");
assertRequired(key, "key is required");

if (typeof key !== "string") return key;
if (key.split(/\r?\n/).length !== 1) return key;
Expand All @@ -26,7 +26,8 @@ export const keyToPEM = (

export const certToPEM = (cert: string): string => {
const lines = cert.match(/.{1,64}/g);
let pem = assertRequired(lines, "cert is invalid").join("\n");
assertRequired(lines, "cert is invalid");
let pem = lines.join("\n");

if (pem.indexOf("-BEGIN CERTIFICATE-") === -1) pem = "-----BEGIN CERTIFICATE-----\n" + pem;
if (pem.indexOf("-END CERTIFICATE-") === -1) pem = pem + "\n-----END CERTIFICATE-----\n";
Expand Down
36 changes: 17 additions & 19 deletions src/saml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,10 @@ class SAML {
throw new TypeError("SamlOptions required on construction");
}

const options = {
assertRequired(ctorOptions.issuer, "issuer is required");
assertRequired(ctorOptions.cert, "cert is required");

const options: SamlOptions = {
...ctorOptions,
passive: ctorOptions.passive ?? false,
disableRequestedAuthnContext: ctorOptions.disableRequestedAuthnContext ?? false,
Expand All @@ -145,7 +148,7 @@ class SAML {
maxAssertionAgeMs: ctorOptions.maxAssertionAgeMs ?? 0,
path: ctorOptions.path ?? "/saml/consume",
host: ctorOptions.host ?? "localhost",
issuer: assertRequired(ctorOptions.issuer, "issuer is required"),
issuer: ctorOptions.issuer,
audience: ctorOptions.audience ?? ctorOptions.issuer ?? "unknown_audience", // use issuer as default
identifierFormat:
ctorOptions.identifierFormat === undefined
Expand All @@ -156,7 +159,7 @@ class SAML {
"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport",
],
validateInResponseTo: ctorOptions.validateInResponseTo ?? ValidateInResponseTo.never,
cert: assertRequired(ctorOptions.cert, "cert is required"),
cert: ctorOptions.cert,
requestIdExpirationPeriodMs: ctorOptions.requestIdExpirationPeriodMs ?? 28800000, // 8 hours
cacheProvider:
ctorOptions.cacheProvider ??
Expand Down Expand Up @@ -205,7 +208,7 @@ class SAML {
}

private signRequest(samlMessage: querystring.ParsedUrlQueryInput): void {
this.options.privateKey = assertRequired(this.options.privateKey, "privateKey is required");
assertRequired(this.options.privateKey, "privateKey is required");

const samlMessageToSign: querystring.ParsedUrlQueryInput = {};
samlMessage.SigAlg = algorithms.getSigningAlgorithm(this.options.signatureAlgorithm);
Expand All @@ -231,7 +234,7 @@ class SAML {
isHttpPostBinding: boolean,
host: string | undefined
): Promise<string> {
this.options.entryPoint = assertRequired(this.options.entryPoint, "entryPoint is required");
assertRequired(this.options.entryPoint, "entryPoint is required");

const id = this.options.generateUniqueId();
const instant = generateInstant();
Expand Down Expand Up @@ -470,11 +473,9 @@ class SAML {
operation: string,
additionalParameters: querystring.ParsedUrlQuery
): Promise<string> {
this.options.entryPoint = assertRequired(this.options.entryPoint, "entryPoint is required");
const requestOrResponse = assertRequired(
request || response,
"either request or response is required"
);
assertRequired(this.options.entryPoint, "entryPoint is required");
const requestOrResponse = request || response;
assertRequired(requestOrResponse, "either request or response is required");

let buffer: Buffer;
if (this.options.skipRequestCompression) {
Expand Down Expand Up @@ -552,7 +553,7 @@ class SAML {
}

async getAuthorizeFormAsync(RelayState: string, host?: string): Promise<string> {
this.options.entryPoint = assertRequired(this.options.entryPoint, "entryPoint is required");
assertRequired(this.options.entryPoint, "entryPoint is required");

// The quoteattr() function is used in a context, where the result will not be evaluated by javascript
// but must be interpreted by an XML or HTML parser, and it must absolutely avoid breaking the syntax
Expand Down Expand Up @@ -680,7 +681,7 @@ class SAML {
checkedCerts = await util
.promisify(this.options.cert as CertCallback)()
.then((certs) => {
certs = assertRequired(certs, "callback didn't return cert");
assertRequired(certs, "callback didn't return cert");
if (!Array.isArray(certs)) {
certs = [certs];
}
Expand Down Expand Up @@ -798,10 +799,7 @@ class SAML {
}

if (encryptedAssertions.length == 1) {
this.options.decryptionPvk = assertRequired(
this.options.decryptionPvk,
"No decryption key for encrypted SAML response"
);
assertRequired(this.options.decryptionPvk, "No decryption key for encrypted SAML response");

const encryptedAssertionXml = encryptedAssertions[0].toString();

Expand Down Expand Up @@ -1316,7 +1314,7 @@ class SAML {
return promiseWithNameID(nameIds[0]);
}
if (encryptedIds.length === 1) {
self.options.decryptionPvk = assertRequired(
assertRequired(
self.options.decryptionPvk,
"No decryption key found getting name ID for encrypted SAML response"
);
Expand Down Expand Up @@ -1361,7 +1359,7 @@ class SAML {
if (this.options.decryptionPvk != null || this.options.privateKey != null) {
metadata.EntityDescriptor.SPSSODescriptor.KeyDescriptor = [];
if (isValidSamlSigningOptions(this.options)) {
signingCert = assertRequired(
assertRequired(
signingCert,
"Missing signingCert while generating metadata for signing service provider messages"
);
Expand All @@ -1383,7 +1381,7 @@ class SAML {
}

if (this.options.decryptionPvk != null) {
decryptionCert = assertRequired(
assertRequired(
decryptionCert,
"Missing decryptionCert while generating metadata for decrypting service provider"
);
Expand Down
4 changes: 1 addition & 3 deletions src/utility.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { SamlSigningOptions } from "./types";
import { signXml } from "./xml";

export function assertRequired<T>(value: T | null | undefined, error?: string): T {
export function assertRequired<T>(value: T | null | undefined, error?: string): asserts value {
if (value === undefined || value === null || (typeof value === "string" && value.length === 0)) {
throw new TypeError(error ?? "value does not exist");
} else {
return value;
}
}

Expand Down
3 changes: 2 additions & 1 deletion test/samlRequest.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ describe("SAML request", function () {
.then((formBody) => {
expect(formBody).to.match(/<!DOCTYPE html>[^]*<input.*name="SAMLRequest"[^]*<\/html>/);
const samlRequestMatchValues = formBody.match(/<input.*name="SAMLRequest" value="([^"]*)"/);
const encodedSamlRequest = assertRequired(samlRequestMatchValues?.[1]);
assertRequired(samlRequestMatchValues?.[1]);
const encodedSamlRequest = samlRequestMatchValues?.[1];

let buffer = Buffer.from(encodedSamlRequest, "base64");
if (!config.skipRequestCompression) {
Expand Down
24 changes: 12 additions & 12 deletions test/samlTests.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,28 +73,28 @@ describe("SAML.js", function () {

describe("getLogoutUrl", function () {
it("calls callback with right host", async () => {
req.user = assertRequired(req.user);
assertRequired(req.user);
const target = await saml.getLogoutUrlAsync(req.user, "", {});
expect(url.parse(target!).host!).to.equal("exampleidp.com");
});
it("calls callback with right protocol", async () => {
req.user = assertRequired(req.user);
assertRequired(req.user);
const target = await saml.getLogoutUrlAsync(req.user, "", {});
expect(url.parse(target!).protocol!).to.equal("https:");
expect(url.parse(target!).protocol!).to.equal("https:");
});
it("calls callback with right path", async () => {
req.user = assertRequired(req.user);
assertRequired(req.user);
const target = await saml.getLogoutUrlAsync(req.user, "", {});
expect(url.parse(target!).pathname!).to.equal("/path");
});
it("calls callback with original query string", async () => {
req.user = assertRequired(req.user);
assertRequired(req.user);
const target = await saml.getLogoutUrlAsync(req.user, "", {});
expect(url.parse(target!, true).query["key"]!).to.equal("value");
});
it("calls callback with additional run-time params in query string", async () => {
req.user = assertRequired(req.user);
assertRequired(req.user);
const target = await saml.getLogoutUrlAsync(req.user, "", options);
expect(Object.keys(url.parse(target!, true).query)).to.have.lengthOf(3);
expect(url.parse(target!, true).query["key"]!).to.equal("value");
Expand All @@ -103,7 +103,7 @@ describe("SAML.js", function () {
});
// NOTE: This test only tests existence of the assertion, not the correctness
it("calls callback with saml request object", async () => {
req.user = assertRequired(req.user);
assertRequired(req.user);
const target = await saml.getLogoutUrlAsync(req.user, "", {});
expect(url.parse(target!, true).query).have.property("SAMLRequest");
});
Expand All @@ -114,7 +114,7 @@ describe("SAML.js", function () {
saml.getLogoutResponseUrl(req.samlLogoutRequest, "", {}, true, function (err, target) {
expect(err).to.not.exist;
try {
target = assertRequired(target);
assertRequired(target);
const parsed = url.parse(target);
assert.strictEqual(parsed.host, "exampleidp.com");
done();
Expand All @@ -127,7 +127,7 @@ describe("SAML.js", function () {
saml.getLogoutResponseUrl(req.samlLogoutRequest, "", {}, true, function (err, target) {
expect(err).to.not.exist;
try {
target = assertRequired(target);
assertRequired(target);
const parsed = url.parse(target);
assert.strictEqual(parsed.protocol, "https:");
done();
Expand All @@ -140,7 +140,7 @@ describe("SAML.js", function () {
saml.getLogoutResponseUrl(req.samlLogoutRequest, "", {}, true, function (err, target) {
expect(err).to.not.exist;
try {
target = assertRequired(target);
assertRequired(target);
const parsed = url.parse(target);
assert.strictEqual(parsed.pathname, "/path");
done();
Expand All @@ -153,7 +153,7 @@ describe("SAML.js", function () {
saml.getLogoutResponseUrl(req.samlLogoutRequest, "", {}, true, function (err, target) {
expect(err).to.not.exist;
try {
target = assertRequired(target);
assertRequired(target);
const parsed = url.parse(target, true);
assert.strictEqual(parsed.query["key"], "value");
done();
Expand All @@ -166,7 +166,7 @@ describe("SAML.js", function () {
saml.getLogoutResponseUrl(req.samlLogoutRequest, "", options, true, function (err, target) {
expect(err).to.not.exist;
try {
target = assertRequired(target);
assertRequired(target);
const parsed = url.parse(target, true);
assert.strictEqual(parsed.query["key"], "value");
expect(parsed.query["SAMLResponse"]).to.exist;
Expand All @@ -182,7 +182,7 @@ describe("SAML.js", function () {
saml.getLogoutResponseUrl(req.samlLogoutRequest, "", {}, true, function (err, target) {
expect(err).to.not.exist;
try {
target = assertRequired(target);
assertRequired(target);
const parsed = url.parse(target, true);
expect(parsed.query).have.property("SAMLResponse");
done();
Expand Down