पाठ 27 / 32

Securing Serverless and Edge Apps

यह पाठ अभी हिंदी में अनुवादित नहीं है, इसलिए अंग्रेज़ी में दिखाया जा रहा है।

Apply least privilege, manage secrets, validate every event, and verify tokens and webhooks early at the edge.

लेखक: · 15 साल से वेब डेवलपर

Your half of the shared responsibility

The provider patches the OS and runtime, but the shared responsibility model leaves your code, configuration, identities and data with you. Give each function its own role with least privilege: only the actions and resources it needs, never wildcard * permissions copied from a tutorial. Keep secrets in a secrets manager or the platform's encrypted secret bindings, not in source code or plain-text configuration committed to Git, and load them at init with caching. Treat every event as untrusted input: an S3 key, a queue message or a webhook body can carry injection payloads just like an HTTP form, so validate it against a schema. Verify webhook signatures and JWTs before doing any work; the edge is a good place to reject bad tokens early, before they cost you compute. Keep dependencies updated and scanned, since a function's package is a large part of its attack surface, and do not give internal functions public URLs.

Verifying a JWT with Web Crypto

This HS256 check uses only Web-standard APIs, so it runs on edge runtimes and in Node.js alike. Production code should also check the header's alg, the issuer and the audience, or use a well-tested library.

// Verify an HS256 JWT with the Web Crypto API: works in edge runtimes and Node alike.
const enc = new TextEncoder();
const toB64url = (bytes) =>
  btoa(String.fromCharCode(...new Uint8Array(bytes)))
    .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
const fromB64url = (s) =>
  Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));

const hmacKey = (secret) => crypto.subtle.importKey('raw', enc.encode(secret),
  { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);

async function sign(payload, secret) {
  const head = toB64url(enc.encode(JSON.stringify({ alg: 'HS256', typ: 'JWT' })));
  const body = toB64url(enc.encode(JSON.stringify(payload)));
  const sig = await crypto.subtle.sign('HMAC', await hmacKey(secret), enc.encode(`${head}.${body}`));
  return `${head}.${body}.${toB64url(sig)}`;
}

async function verify(token, secret) {
  const [head, body, sig] = token.split('.');
  const ok = await crypto.subtle.verify('HMAC', await hmacKey(secret),
    fromB64url(sig), enc.encode(`${head}.${body}`));
  if (!ok) return null;
  const claims = JSON.parse(new TextDecoder().decode(fromB64url(body)));
  return claims.exp > Date.now() / 1000 ? claims : null; // reject expired tokens
}

const token = await sign({ sub: 'user-7', exp: Math.floor(Date.now() / 1000) + 300 }, 'dev-secret');
console.log('valid  :', (await verify(token, 'dev-secret'))?.sub);
console.log('forged :', await verify(token, 'wrong-secret'));

Output:

valid  : user-7
forged : null

A least-privilege policy

This role can read one table in one region and nothing else. Compare it with "Action": "dynamodb:*", "Resource": "*", which would let a bug or an attacker delete every table in the account.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["dynamodb:GetItem", "dynamodb:Query"],
      "Resource": "arn:aws:dynamodb:ap-south-1:123456789012:table/Students"
    }
  ]
}

Signed webhooks are not optional

Payment gateways and other providers sign their webhooks with a shared secret. If your function skips the signature check, anyone who discovers the URL can mark orders as paid. Verify the signature over the raw request body, and reject old timestamps to stop replays.

त्वरित जाँच: Which practice best follows least privilege for a function that only reads one DynamoDB table?

  • Attach the AdministratorAccess policy during development and remove it later
  • Allow `dynamodb:*` on `*` so future features work without changes
  • Allow only the needed read actions on that one table's ARN
  • Share one role across all functions to keep things simple
Answer

Allow only the needed read actions on that one table's ARN — Grant the minimum actions on the specific resource. Broad or shared roles turn any bug into an account-wide risk.