HIGH api key exposurerestifysaml

Api Key Exposure in Restify with Saml

Api Key Exposure in Restify with Saml — how this specific combination creates or exposes the vulnerability

When Restify is used to serve an API that relies on SAML-based identity federation, developers sometimes inadvertently expose API keys through the SAML flow or through relaxed CORS and route handling. This specific combination can occur when an API key is embedded in a SAML assertion attribute, passed in an HTTP header, or stored in a query parameter that is preserved across the SAML redirect chain. If the SAML consumer endpoint in Restify does not explicitly validate and restrict the exposure of these values, an API key may be reflected in responses, logged, or returned to browser-based clients.

For example, if a Restify route extracts a SAML attribute such as NameID or a custom attribute like saml:api_key and uses it directly to construct responses or to sign requests without redaction, an authenticated user can read that key via a crafted request or a compromised browser session. Insecure route definitions that do not limit HTTP methods or that mirror query parameters can further amplify the exposure by echoing the SAML context back to the caller, including the API key, in JSON or form payloads.

Another common scenario involves service providers that accept unsolicited SAML assertions and then reuse identity metadata to authorize access to administrative endpoints. If those endpoints also return debug information, configuration snippets, or introspection data, an API key that was intended for server-to-server use may be surfaced to less-privileged callers. Because Restify often handles both the SAML protocol bindings and the API routing layer, the boundary between identity validation and resource exposure becomes critical to secure correctly.

The risk is elevated when CORS headers are too permissive, allowing a browser-based application that received a SAML-sourced API key to make cross-origin requests that expose the key to JavaScript or to log entries that capture the full request including the key. Without strict input validation on SAML attributes and disciplined separation of identity claims from sensitive credentials, the API key becomes reachable through standard API paths that were not designed to handle privileged material.

middleBrick scans this attack surface by testing unauthenticated endpoints and, where applicable, authenticated flows that involve SAML redirects and metadata. It checks whether API keys are reflected in responses, headers, or logs, and whether SAML attributes are handled with appropriate caution. The scan provides severity-ranked findings and remediation guidance tailored to the detected exposure patterns, helping teams understand exactly where the SAML-Restify interaction introduces risk.

Saml-Specific Remediation in Restify — concrete code fixes

To prevent API key exposure when using SAML with Restify, apply strict validation and isolation between identity attributes and sensitive credentials. Do not echo SAML attributes directly into API responses, and ensure that any keys used for downstream services are stored server-side and never returned to clients.

Use environment variables or a secure vault to store API keys and reference them server-side based on the resolved identity, rather than passing them through SAML assertions. When constructing SAML responses or service provider metadata, avoid including API keys as attributes.

Below are concrete Restify code examples that demonstrate secure handling of SAML attributes and prevention of API key leakage.

// server.js — secure Restify service with SAML handling
const restify = require('restify');
const samlStrategy = require('passport-saml').Strategy;
const passport = require('passport');

const server = restify.createServer();
server.use(restify.plugins.bodyParser());
server.use(passport.initialize());

// Configure SAML strategy without exposing keys in attributes
passport.use(new samlStrategy({
  entryPoint: 'https://idp.example.com/sso',
  issuer: 'https://sp.example.com',
  cert: process.env.SAML_CERT,
  privateKey: process.env.SAML_PRIVATE_KEY,
  callbackUrl: 'https://sp.example.com/saml/consume',
  identifierFormat: 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress',
  // Do not request or expect API keys in SAML attributes
  skipRequestCompression: true
}, (profile, done) => {
  // Map profile to local user, do not include API keys here
  return done(null, { id: profile.nameID, email: profile.email });
}));

// A protected route that uses identity but does not expose credentials
server.get('/api/resource', passport.authenticate('saml', { session: false }), (req, res, next) => {
  if (!req.user) { return next(new restify.UnauthorizedError('Unauthorized'));
  }
  // Use server-side stored API key for downstream calls, never from SAML
  const apiKey = process.env.DOWNSTREAM_API_KEY;
  // Perform authorized operation using apiKey on the server
  res.send({ data: 'secure resource', user: req.user.email });
  return next();
});

// Ensure CORS does not expose sensitive headers
server.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'https://app.example.com');
  res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type');
  res.setHeader('Access-Control-Expose-Headers', 'X-Request-ID');
  return next();
});

server.listen(8080, () => {
  console.log('Service listening on port 8080');
});

In this example, the SAML strategy does not request or trust API keys as attributes, and the route explicitly uses a server-side API key instead of reflecting any SAML-supplied value. The CORS configuration avoids exposing sensitive headers to browser contexts, reducing the chance of key leakage through client-side scripts or logs.

Additionally, audit and validation of incoming SAML assertions should enforce that unexpected or sensitive attributes are rejected. This prevents attackers from injecting a crafted attribute that could trick the server into including an API key in a response.

middleBrick’s LLM/AI Security checks can detect scenarios where system prompts or outputs might inadvertently reference API keys, and its standard scans validate whether SAML-related endpoints reflect sensitive values. By following these patterns and using the tooling to continuously monitor the API surface, teams can reduce the likelihood of accidental key exposure while maintaining compatibility with SAML-based workflows.

Frequently Asked Questions

Can SAML attributes safely carry service credentials like API keys?
No. SAML attributes should represent identity claims, not service credentials. API keys must be stored and used server-side and never embedded in SAML assertions or returned to clients.
How does middleBrick detect API key exposure in SAML flows?
middleBrick tests unauthenticated and authenticated routes, including SAML redirect chains, and checks whether API keys are reflected in responses, headers, or logs. It reports findings with severity and remediation guidance.