Skip to content
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
9 changes: 7 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,12 +253,17 @@ export function createOptionalCallbackFunction<T, A extends unknown[]>(
return ((...args: A | [...A, ErrorFirstCallback<T>]) => {
const possibleCallback = args[args.length - 1];
if (isErrorFirstCallback(possibleCallback)) {
let result: T;
// Only `syncVersion` may run inside the `try`. Invoking the callback there would let an
// exception thrown *by the callback* land in the `catch` and invoke it a second time.
// https://github.com/node-saml/xml-crypto/issues/527
try {
const result = syncVersion(...(args.slice(0, -1) as A));
possibleCallback(null, result);
result = syncVersion(...(args.slice(0, -1) as A));
} catch (err) {
possibleCallback(err instanceof Error ? err : new Error("Unknown error"));
return;
}
possibleCallback(null, result);
} else {
return syncVersion(...(args as A));
}
Expand Down
28 changes: 28 additions & 0 deletions test/types-tests.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { SignedXml, type ErrorFirstCallback } from "../src/index";
import * as fs from "fs";
import { expect } from "chai";

describe("Callback invocation", function () {
// https://github.com/node-saml/xml-crypto/issues/527
it("invokes the callback once when the callback throws", function () {
const xml = `<x xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd' Id='_1'></x>`;
const sig = new SignedXml();
sig.privateKey = fs.readFileSync("./test/static/client.pem");
sig.addReference({
xpath: "//*[local-name(.)='x']",
digestAlgorithm: "http://www.w3.org/2000/09/xmldsig#sha1",
transforms: ["http://www.w3.org/2001/10/xml-exc-c14n#"],
});
sig.canonicalizationAlgorithm = "http://www.w3.org/2001/10/xml-exc-c14n#";
sig.signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

const errorsSeen: (string | null)[] = [];
const callback: ErrorFirstCallback<SignedXml> = (err) => {
errorsSeen.push(err ? err.message : null);
throw new Error("Error Thrown");
};

expect(() => sig.computeSignature(xml, callback)).to.throw("Error Thrown");
expect(errorsSeen).to.deep.equal([null]);
});
});