HIGH api key exposurekoasaml

Api Key Exposure in Koa with Saml

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

When an API built with Koa uses SAML for identity federation, developers may inadvertently expose API keys through SAML assertions or session handling. API keys are long-lived credentials intended for machine-to-machine authentication, whereas SAML is designed for user identity and session-based access. Mixing these patterns can create a path where an API key is embedded into a SAML response, logged by the Koa app, or stored in browser-side state that is later transmitted to an endpoint that does not enforce strict authentication.

In a Koa application, middleware typically inspects headers such as Authorization: Bearer . If a SAML-based login flow sets a session cookie and the client then calls an API route without stripping or rotating the key, the same key can be reused across identity and API boundaries. For example, a key provisioned for a service account might be passed as a query parameter or stored in local storage, and a SAML authentication flow that redirects back to the same origin can replay or expose that key in URLs or logs. This becomes particularly risky when SAML assertions carry user attributes that are mapped directly into API scopes without additional validation or key rotation.

Another exposure vector stems from metadata exposure. Many Koa apps expose debugging or health endpoints that return configuration, including which keys are active or how SAML is integrated. If those endpoints do not require separate authentication, an attacker who can reach the app (for example via an open redirect or a misconfigured route) can enumerate environment variables or configuration files that reference API keys. Because SAML often relies on XML payloads and redirects, improperly configured route handlers can echo metadata or SAML request artifacts into logs, creating searchable artifacts that include keys.

Cross-site request forgery (CSRF) against SAML flows can also lead to unintended use of an API key. If a Koa route expects an API key in a header but also maintains a SAML-based session, a malicious site can trigger authenticated requests via image tags or fetch requests that reuse the session. The route might validate the session cookie but not the origin, causing the request to be executed with the privileges associated with the key bound to that session. This is especially relevant when keys are used for administrative operations rather than per-user authorization.

Compliance mappings highlight the risk. OWASP API Top 10 A07:2021 identifies security misconfiguration as a common issue, and exposing API keys via identity flows fits this category. PCI-DSS and SOC2 emphasize separation of duties and key protection; storing or transmitting API keys in SAML contexts can violate these principles. Regular scanning with tools that understand both API and identity protocols, such as middleBrick, can surface these misconfigurations before they are exploited in the wild.

Saml-Specific Remediation in Koa — concrete code fixes

To reduce exposure, isolate API keys from SAML flows and enforce strict validation at each boundary. Avoid embedding API keys in SAML assertions or allowing them to be set via user-controlled attributes. Instead, use short-lived tokens for API access and keep API keys in server-side vaults that are only accessed by backend services.

Ensure your Koa routes that handle SAML do not leak keys in logs, URLs, or error messages. Below is a minimal Koa example that demonstrates a secure pattern: using SAML for authentication while requiring an additional, separately managed credential for sensitive operations.

const Koa = require('koa');
const Router = require('@koa/router');
const passport = require('koa-passport');
const SamlStrategy = require('passport-saml').Strategy;

const app = new Koa();
const router = new Router();

// SAML strategy configuration
passport.use(new SamlStrategy({
  entryPoint: 'https://idp.example.com/sso',
  issuer: 'https://sp.example.com',
  cert: processIdP_CERT,
  privateKey: process.env.SP_PRIVATE_KEY,
  callbackUrl: 'https://sp.example.com/saml/acs',
}, (profile, done) => {
  // Map SAML attributes to a local user, do not include API keys here
  return done(null, { userId: profile.nameID, roles: profile.roles });
}));

app.use(passport.initialize());

// Route protected by SAML session
router.get('/profile', passport.authenticate('saml', { session: true }), (ctx) => {
  ctx.body = { userId: ctx.state.user.userId, message: 'Profile accessible via SAML' };
});

// Sensitive operation requiring an additional API key validated server-side
router.post('/admin/rotate', async (ctx) => {
  const providedKey = ctx.request.header['x-api-key'];
  if (!providedKey) {
    ctx.status = 401;
    ctx.body = { error: 'API key required' };
    return;
  }
  const valid = await validateApiKeyServerSide(providedKey); // e.g., call Vault or DB
  if (!valid) {
    ctx.status = 403;
    ctx.body = { error: 'Invalid API key' };
    return;
  }
  // Proceed with admin action
  ctx.body = { status: 'rotation initiated' });
});

async function validateApiKeyServerSide(key) {
  // Implement server-side check; do not compare keys in client-side code
  const stored = await fetchKeyFromVault(key);
  return stored && stored.scope === 'admin' && stored.active === true;
}

app.use(router.routes()).use(router.allowedMethods());

module.exports = app;

In this pattern, SAML establishes identity and session, but sensitive operations require a server-validated API key passed in a dedicated header. The key is never returned to the client in SAML responses, and validation occurs server-side, reducing the chance of accidental exposure in URLs or logs.

Additionally, configure your SAML service provider to avoid including secrets in assertions. Ensure that NameID and attributes do not contain keys or tokens. Enforce strict audience and destination validation in your SAML middleware so that responses are only accepted for your intended endpoints, mitigating the risk of token replay or metadata leakage that could indirectly expose keys.

For ongoing safety, integrate scanning into your workflow. Use the middleBrick CLI to scan from terminal with middlebrick scan <url>, add API security checks to your CI/CD pipeline with the GitHub Action, or scan APIs directly from your AI coding assistant via the MCP Server. These integrations help detect misconfigurations early and keep SAML-based flows aligned with secure key management practices.

Frequently Asked Questions

Can SAML assertions safely carry API keys if they are encrypted?
No. Even if encrypted, embedding API keys in SAML assertions couples identity and machine credentials, increasing exposure risk and complicating key rotation. Keep keys separate and use SAML only for authentication.
How can I detect accidental API key exposure in SAML flows?
Use a scanner that understands both API and identity protocols. middleBrick scans unauthenticated attack surfaces and maps findings to frameworks like OWASP API Top 10, helping identify misconfigurations where keys might be exposed through SAML metadata or logging.