//nefariousplan

CVE-2026-46490: samlify's JSDoc Named The Unescaped Branch As A Feature

vendor

pattern

cve

proof of concept

samlify's escapeTag has two return statements. One returns ${quote}${xmlEscape(text)}. The other returns text. The branch selector is whether the calling regex captured a " character immediately before the {Tag} placeholder. For name="{Tag}" the regex captures the " and the value is escaped. For <X>{Tag}</X> the regex captures the empty string and the value is returned raw. The JSDoc above the function, written into commit 3d5788a on 2026-04-23, named the second branch as a feature: "XML-escapes attribute values but leaves element text untouched so the caller can inject nested XML." The fix landed three weeks later, in commit b37a65c. From February 2024 through May 2026, samlify's outbound assertion-rendering path interpreted one preceding byte as the trust signal that selected whether user input was XML-escaped. The function called escapeTag had a branch that returned text, and the JSDoc named that branch as a feature.

The function has two branches. The switch is one byte.

CVE-2026-46490 is filed against samlify, the Node.js SAML single-sign-on library at tngan/samlify on npm. src/libsaml.ts exports a helper named replaceTagsByValue that rewrites {Tag} placeholders in an XML template using a caller-supplied map. The regex driving the rewrite is ("?)\{${t}\} with one capture group: an optional single " character before the placeholder. The replacement callback escapeTag receives that capture group as its quote argument.

/**
 * Replacer for {@link replaceTagsByValue}. XML-escapes attribute values
 * but leaves element text untouched so the caller can inject nested XML.
 */
function escapeTag(replacement: unknown): (...args: string[]) => string {
  return (_match: string, quote?: string) => {
    const text: string = replacement === null || replacement === undefined ? '' : String(replacement);
    return quote ? `${quote}${xmlEscape(text)}` : text;
  };
}

The ternary is the bug. When the regex matched a leading ", quote is the string " and the function returns the quote concatenated with the XML-escaped value. When the regex did not match a leading ", quote is undefined, and the function returns the value verbatim. The same text parameter, the same function, two return shapes, one byte of preceding context selecting between them.

The templates the library ships look like this:

<saml:Subject>
  <saml:NameID Format="{NameIDFormat}">{NameID}</saml:NameID>
</saml:Subject>

{NameIDFormat} is preceded by ". The substitution carries through xmlEscape. {NameID} is preceded by >. The substitution does not.

The JSDoc names the no-escape branch as a feature.

The comment above escapeTag is not load-bearing for the implementation. It is the maintainer documenting what the implementation does. The April 2026 refactor 3d5788a rewrote the function's inline comment into the JSDoc shown above; the inline comment it replaced, shipped in PR #523 on 2024-02-23, read:

// not having a quote means this interpolation isn't for an attribute,
// and so does not need escaping

The PR's commit message stated the same intent: "fix entity escaping to only escape tag attributes." The "only" was a constraint the author wrote down. Element-text positions were deliberately left raw.

The JSDoc above replaceTagsByValue, also written by the April refactor, said the same thing in the public-facing documentation:

Substitute {Tag} placeholders inside an XML template with the given
replacement map. Attribute values are XML-escaped; element text is not.

The "caller" the function's JSDoc names is not the user. It is entity-idp.ts, the IdP module inside the same library. The pre-patch initialisation in entity-idp.ts builds an <saml:AttributeStatement> XML fragment using attributeStatementBuilder, then calls replaceTagsByValue against the outer LoginResponse template with a one-key replacement map:

const replacement = {
  AttributeStatement: libsaml.attributeStatementBuilder(
    template.attributes!,
    attributeTemplate,
    attributeStatementTemplate,
  ),
};
entitySetting.loginResponseTemplate = {
  ...entitySetting.loginResponseTemplate,
  context: libsaml.replaceTagsByValue(entitySetting.loginResponseTemplate!.context!, replacement),
};

The value passed for AttributeStatement is a literal XML string: <saml:AttributeStatement>...</saml:AttributeStatement>. The placeholder {AttributeStatement} lives in element-text position inside the outer LoginResponse template:

...<saml:AudienceRestriction>
  <saml:Audience>{Audience}</saml:Audience>
</saml:AudienceRestriction></saml:Conditions>{AuthnStatement}{AttributeStatement}</saml:Assertion>

The byte preceding {AttributeStatement} is }, the closing brace of the prior placeholder. The regex captures no ". escapeTag falls into the second branch and returns the markup raw. The <saml:AttributeStatement> tags survive intact and become live XML in the rendered response. This is the use case the JSDoc was protecting. The maintainer wrote the no-escape branch so that replaceTagsByValue could be used as a markup-splicing primitive and a data-interpolation primitive from the same call site, with the position of the placeholder in the template selecting between them.

The user is also a caller.

The inner attribute template the IdP ships looks like this:

const defaultAttributeTemplate: AttributeTemplate = {
  context: '<saml:Attribute Name="{Name}" NameFormat="{NameFormat}"><saml:AttributeValue xmlns:xs="{ValueXmlnsXs}" xmlns:xsi="{ValueXmlnsXsi}" xsi:type="{ValueXsiType}">{Value}</saml:AttributeValue></saml:Attribute>',
};

{Value} is in element-text position. attributeStatementBuilder rewrites {Value} to a per-attribute placeholder name like {attrUserEmail} or {attrUserRole}, derived by camel-casing the attribute's valueTag. The placeholder still lives in element-text position. The byte preceding it is still >.

At login-response time src/binding-post.ts calls replaceTagsByValue against the assembled template with the value map:

const tvalue: TagReplacementMap = {
  // ...
  NameID: user.email || '',
  // ...
  attrUserEmail: user.email,
  attrUserRole: user.role,
};
// ...
rawSamlResponse = libsaml.replaceTagsByValue(baseTemplate, tvalue);

user.email and user.role are values the application reads from its own store and hands to samlify. The store typically reflects values the user supplied at registration or in an edit-profile flow; SAML attribute mappings in the wild routinely carry email, displayName, givenName, and similar self-asserted fields. The values flow through the same replaceTagsByValue that handled the AttributeStatement splice, into element-text positions where the same regex captures no ", where the same escapeTag falls into the same second branch, where the same JSDoc says the caller is permitted to inject nested XML.

The maintainer's "caller" was entity-idp.ts. The user is also a caller. The function cannot distinguish them, because the function's signal is the byte before the placeholder, and that byte does not carry trust information about anything that follows.

The signature is computed after the substitution.

createLoginResponse in src/binding-post.ts calls replaceTagsByValue first and constructSAMLSignature second. The reference XPath the signer is told to sign is the entire <saml:Assertion> subtree:

rawSamlResponse = libsaml.replaceTagsByValue(baseTemplate, tvalue);
// ...
if (metadata.sp.isWantAssertionsSigned()) {
  rawSamlResponse = libsaml.constructSAMLSignature({
    ...config,
    rawSamlMessage: rawSamlResponse,
    transformationAlgorithms: spSetting.transformationAlgorithms,
    referenceTagXPath: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']",
    signatureConfig: {
      prefix: 'ds',
      location: { reference: "/*[local-name(.)='Response']/*[local-name(.)='Assertion']/*[local-name(.)='Issuer']", action: 'after' },
    },
  });
}

Substitution at line 215, signature at line 227. The signer canonicalises whatever XML the substitution emitted and produces a signature over those bytes. Any markup the user inserted at line 215 sits inside the subtree the signer signs at line 227. The downstream SP, given the signed envelope, verifies the signature against the IdP's certificate and accepts the contained <saml:Attribute> elements as authoritative. The IdP's private key has signed the user's injected attributes. The cryptographic boundary the SP trusts ran through escapeTag. The function's two branches were the function's two trust levels.

The same replaceTagsByValue drives every outbound message samlify emits: LoginRequest, LoginResponse, LogoutRequest, and LogoutResponse, across the POST, redirect, and HTTP-SimpleSign bindings. The library's bindings file src/binding-post.ts calls it four times. src/binding-redirect.ts calls it five. src/binding-simplesign.ts calls it four. Every outbound assertion or request the library has produced since February 2024 went through the same one-byte detector. The CVE names attribute injection into the LoginResponse because that is the path the regression test demonstrates and the path the GHSA writeup walks. The branch the detector selects is the same branch in the other twelve call sites.

The payload is the shape the patch's regression test names.

The injection the patch's new test asserts is rejected, but which the pre-patch code accepts, sets the user's role to a string that closes the legitimate <saml:AttributeValue> and <saml:Attribute> tags, opens a new <saml:Attribute Name="admin"> with body true, then opens a fresh <saml:Attribute Name="role"> with body user so the trailing legitimate closing tags balance:

const injection = [
  'user',
  '</saml:AttributeValue></saml:Attribute>',
  '<saml:Attribute Name="admin" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">',
  '<saml:AttributeValue xmlns:xs="..." xmlns:xsi="..." xsi:type="xs:string">true</saml:AttributeValue>',
  '</saml:Attribute>',
  '<saml:Attribute Name="role" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">',
  '<saml:AttributeValue xmlns:xs="..." xmlns:xsi="..." xsi:type="xs:string">user',
].join('');

const user = { email: '[email protected]', role: injection };

replaceTagsByValue substitutes this into the role attribute's element-text position. The pre-patch escapeTag returns the string raw because the regex captured no ". The emitted assertion contains three <saml:Attribute> elements where the template described two. The IdP signs the assertion. The SP parses the signature, finds it valid, parses the assertion, and reads three attributes. One is admin=true. SPs that use SAML attributes as authorisation inputs, the typical pattern for cloud-application role and group mappings, grant the attacker the admin role on the strength of an attribute the user wrote into their own profile.

The injection costs the attacker no credentials they did not have, no requests beyond a normal login, and no SP interaction. The user signs in, and the IdP and SP between them sign and accept the role the user named.

The patch removes the branch and splits the call sites.

The fix in commit b37a65c is two diff hunks. The first removes the second branch of escapeTag:

- return quote ? `${quote}${xmlEscape(text)}` : text;
+ return quote ? `${quote}${xmlEscape(text)}` : xmlEscape(text);

Both branches now escape. The function's name now matches the function's behaviour. The JSDoc is rewritten to match:

Replacer for replaceTagsByValue. Always XML-escapes the replacement
text, in both attribute and element-text contexts, to prevent SAML
attribute/element injection through user-controlled template values.

The second hunk is in src/entity-idp.ts. With escapeTag now always escaping, the framework's prebuilt <saml:AttributeStatement> markup can no longer flow through replaceTagsByValue; the markup would render as &lt;saml:AttributeStatement&gt;.... The fix routes the markup through a direct String.prototype.replace instead:

- const replacement = {
-   AttributeStatement: libsaml.attributeStatementBuilder(
-     template.attributes!,
-     attributeTemplate,
-     attributeStatementTemplate,
-   ),
- };
- entitySetting.loginResponseTemplate = {
-   ...entitySetting.loginResponseTemplate,
-   context: libsaml.replaceTagsByValue(entitySetting.loginResponseTemplate!.context!, replacement),
- };
+ const attributeStatement = libsaml.attributeStatementBuilder(
+   template.attributes!,
+   attributeTemplate,
+   attributeStatementTemplate,
+ );
+ entitySetting.loginResponseTemplate = {
+   ...entitySetting.loginResponseTemplate,
+   context: entitySetting.loginResponseTemplate!.context!.replace('{AttributeStatement}', attributeStatement),
+ };

The framework's markup-splicing call site and the user's data-interpolation call site now use different functions. String.prototype.replace does the literal-substring substitution the framework needs without applying any escape. replaceTagsByValue does the placeholder rewrite the user data needs with xmlEscape always applied. Two purposes, two functions. The branch-selection problem that lived in escapeTag is removed because the branches are now separate code paths that different callers reach.

This is the shape the catalog names as the-shell-was-not-the-sink: a sanitisation function correctly written for one threat model, applied uniformly to inputs whose destination encodes a different one. The catalog's closest sibling is the exiftool-vendored exhibit, where htmlEncode ran on the value half of a -${key}=${enc(val)} interpolation loop and not on the key half. samlify's escapeTag ran xmlEscape on the half of a regex match where a " preceded the placeholder, and not on the half where it did not. Same regex, two slots, sanitiser on one. Where exiftool's halves were syntactic positions in a TypeScript template literal, samlify's were positions in an XML template detected by a one-byte preceding-character regex. The function's name encoded the threat model the author was thinking about. The branch the author wrote down as a feature was the branch the user reached.

The function called escapeTag had a branch that returned text.

The maintainer who shipped the patch for CVE-2026-46490 in commit b37a65c on 2026-05-15 was the same maintainer who promoted the unsafe behaviour from an inline comment to a JSDoc in commit 3d5788a on 2026-04-23, twenty-two days earlier. The JSDoc was not buried. It was attached to a function whose name the IDE hover showed every time another file called it, in a refactor whose commit message stated that JSDoc had been added to every exported function. The function called escapeTag had a branch that returned text, and the JSDoc named that branch as a feature.

PoC: tngan/samlify@b37a65c

The function called escapeTag had a branch that returned text, and the JSDoc named that branch as a feature.