Third-Party Integration Security: APIs, SDKs, and Dependencies

TL;DR

The habit that matters most is auditing a dependency before you add it. After that, commit your lockfiles and pin versions, scan for vulnerabilities automatically, give API keys only the access they need, and plan for the day a service goes down. Your app is only as secure as everything it depends on.

"The security of your application is only as strong as its weakest dependency."

Best Practice 1: Audit Dependencies Before Adding 3 min

Check these before a new package goes in, not after:

  • Check maintenance status (recent commits, releases)
  • Review open security issues and CVEs
  • Check download counts and community adoption
  • Review the dependency's own dependencies
  • Verify the package is the official one (typosquatting)
Dependency audit commands
# npm - check for vulnerabilities
npm audit
npm audit --audit-level=high

# Check package info
npm info package-name

# See dependency tree
npm ls package-name

# Yarn
yarn audit

# pnpm
pnpm audit

# Python
pip-audit
safety check

# Snyk (comprehensive)
snyk test
Red FlagRiskAction
No updates in 2+ yearsUnmaintained, vulnerabilitiesFind alternative
Few downloadsLess vetted, possible typosquatVerify legitimacy
Many open security issuesKnown vulnerabilitiesAssess severity
Excessive permissionsOver-privileged accessReview necessity
Obfuscated codeHidden malicious codeAvoid

Best Practice 2: Lock Dependencies 2 min

A version you didn't choose shouldn't be able to slip in on the next install:

Lockfile management
# Always commit lockfiles
git add package-lock.json  # npm
git add yarn.lock          # Yarn
git add pnpm-lock.yaml     # pnpm

# Use exact versions in package.json
{
  "dependencies": {
    "express": "4.18.2",        // Exact version
    "lodash": "^4.17.21"        // Avoid caret for security-critical
  }
}

# Install from lockfile in CI/CD
npm ci                    # Not npm install
yarn install --frozen-lockfile
pnpm install --frozen-lockfile

# Enable Dependabot or Renovate for updates
# .github/dependabot.yml
version: 2
updates:
  - package-ecosystem: "npm"
    directory: "/"
    schedule:
      interval: "weekly"
    open-pull-requests-limit: 10

Best Practice 3: Minimize Permissions 2 min

Give each service only the access it actually needs:

Least privilege for API keys
// WRONG: Using admin/root API keys
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);  // Full access

// CORRECT: Use restricted keys where possible
// Stripe: Create restricted keys with specific permissions
// - Can only create charges
// - Cannot access customer data
// - Cannot modify account settings

// AWS: Use IAM roles with minimal permissions
{
  "Effect": "Allow",
  "Action": [
    "s3:GetObject",
    "s3:PutObject"
  ],
  "Resource": "arn:aws:s3:::my-bucket/uploads/*"
  // Not s3:* or arn:aws:s3:::*
}

// GitHub: Use fine-grained personal access tokens
// - Specific repositories only
// - Read-only where possible
// - Short expiration

// Firebase: Use security rules, not admin SDK when possible
// Client SDK respects rules; admin SDK bypasses them

Best Practice 4: Handle Third-Party Failures 3 min

Their outage shouldn't become yours. Wrap external calls so a failure degrades instead of crashing:

Resilient third-party calls
import CircuitBreaker from 'opossum';

// Circuit breaker for external APIs
const paymentBreaker = new CircuitBreaker(processPayment, {
  timeout: 10000,           // 10 second timeout
  errorThresholdPercentage: 50,
  resetTimeout: 30000,      // Try again after 30s
});

paymentBreaker.fallback(() => {
  // Queue for retry or show user-friendly error
  return { status: 'pending', message: 'Payment processing delayed' };
});

paymentBreaker.on('open', () => {
  alertOps('Payment provider circuit breaker opened');
});

// Timeout wrapper for any external call
async function withTimeout(promise, ms, fallback) {
  const timeout = new Promise((_, reject) =>
    setTimeout(() => reject(new Error('Timeout')), ms)
  );

  try {
    return await Promise.race([promise, timeout]);
  } catch (error) {
    if (fallback) return fallback;
    throw error;
  }
}

// Usage
const userData = await withTimeout(
  thirdPartyApi.getUser(userId),
  5000,
  { name: 'Unknown', cached: true }
);

Best Practice 5: Secure Third-Party Scripts 2 min

Client-side scripts are the riskiest kind, since they run inside your page:

Secure third-party script loading
<!-- Use Subresource Integrity (SRI) -->
<script
  src="https://cdn.example.com/library.js"
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/ux..."
  crossorigin="anonymous">
</script>

<!-- Load analytics asynchronously, non-blocking -->
<script async src="https://analytics.example.com/script.js"></script>

<!-- Content Security Policy to limit script sources -->
<meta http-equiv="Content-Security-Policy"
  content="script-src 'self' https://trusted-cdn.com https://analytics.example.com">

<!-- Sandbox iframes for third-party widgets -->
<iframe
  src="https://widget.example.com"
  sandbox="allow-scripts allow-same-origin"
  loading="lazy">
</iframe>
  • Use SRI hashes for all external scripts
  • Implement strict CSP to limit script sources
  • Load non-critical scripts asynchronously
  • Sandbox third-party iframes
  • Review third-party scripts periodically
  • Self-host critical scripts when possible

Best Practice 6: Monitor Third-Party Security 2 min

Nobody emails you when a dependency gets a CVE. Automate the watching:

Automated vulnerability monitoring
# GitHub: Enable Dependabot alerts
# Settings > Security > Code security and analysis
# Enable: Dependency graph, Dependabot alerts, Dependabot security updates

# Snyk in CI/CD
# .github/workflows/security.yml
- name: Run Snyk to check for vulnerabilities
  uses: snyk/actions/node@master
  env:
    SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
  with:
    args: --severity-threshold=high

# npm audit in CI
- name: Security audit
  run: npm audit --audit-level=high

# Socket.dev for supply chain attacks
# Detects typosquatting, malicious packages, etc.
- name: Socket Security
  uses: socketsecurity/socket-action@v1

Supply Chain Attacks: Attackers increasingly target popular packages. Popular isn't the same as safe: event-stream, the ua-parser-js compromise and the colors.js sabotage all hit packages with huge download counts. Use lockfiles, watch for unusual updates, and consider a tool like Socket.dev that analyzes what a package actually does.

Should I vendor (copy) dependencies?

Vendoring gives you maximum control, but updates become your job. It's worth it for critical dependencies or ones you need to patch. For everything else, lockfiles and an automated update tool are the better deal.

How do I handle a vulnerability in a dependency?

Check whether a patched version exists, and update if it does. If it doesn't, look for a workaround or mitigation. If your app never touches the vulnerable code path, write that down and accept the risk for now. A critical vulnerability with no fix is usually a reason to remove or replace the dependency.

Should I trust AI-generated dependency recommendations?

Not blindly. AI tools can suggest outdated packages, or ones that don't exist at all (hallucinations). Verify that a recommended package exists, is actively maintained, and is the official one. Check npm or PyPI directly before installing anything.

Further Reading

Put these practices into action with our step-by-step guides.

Scan Your Dependencies

Check for vulnerabilities in your third-party dependencies.

Best Practices

Third-Party Integration Security: APIs, SDKs, and Dependencies