CoolFace
Apppublic

Ramasani/redis

sourceHugging Faceupdated 4mo agoView on Hugging Face
0likes
App README

HF Redis Rust Gateway

Run a private Redis instance inside a Hugging Face Docker Space and access it from anywhere over HTTPS using API keys.

Public base URL:

text
https://ramasani-redis.hf.space

What This Space Provides

  • —A local Redis server bound to 127.0.0.1, not exposed directly to the internet.
  • —A Rust Axum/Tokio HTTPS gateway for Redis reads, writes, expiry, deletes, and safe raw commands.
  • —Per-client API keys passed with Authorization: Bearer <api_key>.
  • —Admin key creation, listing, and revocation.
  • —Hashed API-key storage for new keys, plus migration support for older raw keys.
  • —Bounded Redis memory settings with an LRU eviction policy by default.

Rust Optimizations

The Space now uses a compiled Rust gateway instead of Python/FastAPI.

  • —Lower runtime overhead for request handling.
  • —Tokio async networking for concurrent requests.
  • —A multiplexed Redis connection for lightweight command execution.
  • —Constant-time admin/API token comparisons.
  • —Safer command parsing and Redis result serialization.
  • —Docker release build with a small Debian runtime image.

The public API contract is intentionally kept the same, so existing /api/get, /api/set, /api/delete, /api/expire, and /api/cmd calls continue to work.

Important Security Note

Do not put Hugging Face tokens, admin tokens, or Redis API keys in this README, source code, screenshots, or public commits.

If a secret has been shared in chat, logs, or a public place, rotate it immediately.

For Hugging Face:

  1. 1.Go to Settings -> Access Tokens.
  2. 2.Revoke the exposed token.
  3. 3.Create a new token with the minimum required scope.
  4. 4.Store it only in your local environment or Space secrets.

Space Secrets

Set these in Space -> Settings -> Variables and secrets.

NameRequiredExampleDescription
MASTER_ADMIN_TOKENYesuse-a-long-random-stringPassword for the admin console and admin API.
ALLOW_DANGEROUS_COMMANDSNofalseKeep false in production. Allows only safe Redis command allow-list.
MAX_COMMAND_ARGSNo64Maximum number of arguments accepted by /api/cmd.
REDIS_PORTNo6379Local Redis port inside the container.
REDIS_DATA_DIRNo/home/user/redis-dataRedis append-only data directory.
REDIS_MAXMEMORYNo128mbRedis memory cap inside the Space container.
REDIS_MAXMEMORY_POLICYNoallkeys-lruEviction policy when Redis reaches the memory cap.

Generate a strong admin token locally:

bash
python -c "import secrets; print(secrets.token_urlsafe(48))"

Persistence

This Space starts Redis inside the container. Redis is configured with append-only persistence, periodic snapshots, a memory cap, and allkeys-lru eviction by default. Hugging Face storage behavior still depends on your Space plan.

For durable production data, enable persistent storage for the Space or use this as a lightweight cache/control-plane store rather than a primary database.

Create An API Key

Open the admin console:

text
https://ramasani-redis.hf.space/?admin_token=YOUR_MASTER_ADMIN_TOKEN

Create a key from the UI. The full key is shown only once.

You can also create one with the admin API:

bash
curl -X POST "https://ramasani-redis.hf.space/admin/keys/json" \
  -H "X-Admin-Token: YOUR_MASTER_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name":"production-app"}'

Response:

json
{
  "api_key": "hk_redis_...",
  "name": "production-app",
  "message": "Copy this key now; it is returned only once."
}

Use The REST API

All Redis API routes require:

text
Authorization: Bearer hk_redis_...

Health Check

bash
curl "https://ramasani-redis.hf.space/health"

Set A Value

bash
curl -X POST "https://ramasani-redis.hf.space/api/set/user:1" \
  -H "Authorization: Bearer hk_redis_..." \
  -H "Content-Type: application/json" \
  -d '{"value":{"name":"Ada","plan":"pro"},"ex":3600}'

Get A Value

bash
curl "https://ramasani-redis.hf.space/api/get/user:1" \
  -H "Authorization: Bearer hk_redis_..."

Set Expiry

bash
curl -X POST "https://ramasani-redis.hf.space/api/expire/user:1" \
  -H "Authorization: Bearer hk_redis_..." \
  -H "Content-Type: application/json" \
  -d '{"seconds":300}'

Delete A Key

bash
curl -X DELETE "https://ramasani-redis.hf.space/api/delete/user:1" \
  -H "Authorization: Bearer hk_redis_..."

Run A Safe Redis Command

bash
curl -X POST "https://ramasani-redis.hf.space/api/cmd" \
  -H "Authorization: Bearer hk_redis_..." \
  -H "Content-Type: application/json" \
  -d '{"cmd":["HSET","profile:1","name","Ada","role","engineer"]}'

Then read it:

bash
curl -X POST "https://ramasani-redis.hf.space/api/cmd" \
  -H "Authorization: Bearer hk_redis_..." \
  -H "Content-Type: application/json" \
  -d '{"cmd":["HGETALL","profile:1"]}'

JavaScript Client Example

js
const REDIS_BASE_URL = "https://ramasani-redis.hf.space";
const REDIS_API_KEY = process.env.HF_REDIS_API_KEY;

async function redisCommand(cmd) {
  const response = await fetch(`${REDIS_BASE_URL}/api/cmd`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${REDIS_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ cmd }),
  });

  if (!response.ok) {
    throw new Error(await response.text());
  }

  return response.json();
}

await redisCommand(["SET", "hello", "world"]);
console.log(await redisCommand(["GET", "hello"]));

Python Client Example

python
import os
import requests

BASE_URL = "https://ramasani-redis.hf.space"
API_KEY = os.environ["HF_REDIS_API_KEY"]

def redis_command(cmd):
    response = requests.post(
        f"{BASE_URL}/api/cmd",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={"cmd": cmd},
        timeout=20,
    )
    response.raise_for_status()
    return response.json()

redis_command(["SET", "hello", "world"])
print(redis_command(["GET", "hello"]))

Command Safety

By default, /api/cmd allows common read/write commands and blocks dangerous commands such as:

text
CONFIG, FLUSHALL, FLUSHDB, EVAL, SCRIPT, SHUTDOWN, DEBUG, MODULE, KEYS

Keep ALLOW_DANGEROUS_COMMANDS=false for production. Even when enabled, explicitly blocked commands stay blocked.

Admin API

List keys:

bash
curl "https://ramasani-redis.hf.space/admin/keys" \
  -H "X-Admin-Token: YOUR_MASTER_ADMIN_TOKEN"

Revoke a key:

bash
curl -X DELETE "https://ramasani-redis.hf.space/admin/keys/<key_hash>" \
  -H "X-Admin-Token: YOUR_MASTER_ADMIN_TOKEN"

Limitations

  • —This is a REST gateway, not a native Redis TCP endpoint. Standard Redis clients like ioredis cannot connect to it directly from outside the Space.
  • —Hugging Face Spaces may sleep or restart depending on plan/settings.
  • —Cold starts can add latency.
  • —Use persistent storage if the data must survive restarts.
  • —For high-throughput production Redis, use a managed Redis provider. This Space is best for lightweight shared state, demos, agents, rate-limit counters, queues with modest traffic, and private tools.

Local Development

Build and run locally:

bash
docker build -t hf-redis-rest .
docker run --rm -p 7860:7860 \
  -e MASTER_ADMIN_TOKEN=dev-admin-token \
  -e REDIS_MAXMEMORY=128mb \
  hf-redis-rest

Open:

text
http://localhost:7860

Operations Checklist

  1. 1.Set MASTER_ADMIN_TOKEN as a Space secret.
  2. 2.Restart the Space.
  3. 3.Open /health and verify status is healthy.
  4. 4.Open /?admin_token=... and create an API key.
  5. 5.Store the API key as HF_REDIS_API_KEY in your app secrets.
  6. 6.Test /api/set/{key} and /api/get/{key}.
  7. 7.Rotate leaked keys immediately.