Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Redis

Bảo mật Website: IP Whitelisting & Blocking tại Edge với Cloudflare Workers & Upstash Redis

Thường gặp nhu cầu hạn chế truy cập website chỉ cho một số IP cụ thể. Bài viết này hướng dẫn implement IP Allow/Deny list dùng Edge computing. Trước tiên giới thiệu Cloudflare Workers.

Cloudflare Workers

Cloudflare Workers công nghệ phổ biến gần đây. Publicly available từ 2017, Cloudflare KV storage từ 2019.

Tóm gọn: Cloudflare Workers cho phép intercept HTTP request ở edge level, thực thi code snippets, manipulate request/response. Cũng dùng KV storage để put/get dictionary native trong Workers. Thử nhanh playground environment.

Ngoài Cloudflare KV, developer có thể cần advanced data structures hơn. Cũng có thể muốn truy cập KV từ bên ngoài (backend, API, SDK clients). Gần đây chúng tôi enable REST API Upstash.

Bây giờ bạn truy cập Upstash Redis database bằng:

  • Upstash Rest API trong Cloudflare Workers
  • redis-cli trong terminal command line
  • Bất kỳ redis client nào cho ngôn ngữ lập trình cụ thể

Click nút connect ở trang chi tiết database để xem sample code và commands.

Bảo mật Website: IP Whitelisting & Blocking tại Edge với Cloudflare Workers & Upstash Redis

Hãy làm một ứng dụng nhỏ dùng Cloudflare Workers và khám phá Upstash Redis Rest API.

Ứng dụng

IP Allow/Deny trong Cloudflare Worker dùng Redis làm source of truth.

Yêu cầu

:::note Chọn Global Database khi tạo Upstash database. Global database replicate data sang nhiều region giảm latency từ edge functions. :::

Tạo Cloudflare worker và intercept request. Worker mới tạo sẽ có sample code sẵn.

Triển khai

Lấy IP address của visitor:

async function handleRequest(request) {
  const ip = request.headers.get("cf-connecting-ip");
  return new Response(ip);
}

Lấy visitor IP từ header. Kiểm tra IP có trong allowed list không. Gọi REST API đơn giản:

async function handleRequest(request) {
  const ip = request.headers.get("cf-connecting-ip");
  res = await fetch(
    "https://YOUR_DATABASE_ENDPOINT/sismember/allowed-set/" + ip + "?_token=YOUR_REST_API_TOKEN"
  );
  if ((await res.text()).includes("1")) {
    return new Response(ip + " is allowed.");
  }
  return new Response(ip + " is not allowed.");
}

Gọi REST API tới Upstash Redis Server kiểm tra IP trong set. Kết quả chứa "1" có nghĩa là trong list, ngược lại không.

Cập nhật Redis set dùng redis-cli:

sadd allowed-set $IP_ADDRESS

Kết luận và Tương lai

Bây giờ có thể truy cập Redis instance qua REST API. Chúng tôi hỗ trợ hầu hết commands qua REST API. Xem documentation chi tiết. Với Cloudflare KV, bạn bị giới hạn chỉ KV dictionary API và khó truy cập từ 3rd party apps. Nhưng Redis có hàng trăm Client SDKs và redis-cli. Cũng tại Upstash bạn truy cập Redis database qua REST API.

Ứng dụng đơn giản này có thể mở rộng thành security guard trong Cloudflare Workers. Users thay đổi config values trong Redis database và Cloudflare Worker đọc config từ Redis.