# Example nginx gate for API-key-protected RPC upstreams using the explorer access API.
# This pattern assumes the explorer config/API backend listens on 127.0.0.1:8081 and
# exposes GET /api/v1/access/internal/validate-key for nginx auth_request.
#
# Replace:
# - ACCESS_INTERNAL_SECRET_VALUE with a real shared secret
# - protected-rpc.example.org with the public host you are protecting
# - upstream IP:port with the actual RPC lane (e.g. 192.168.11.212:8545 or 192.168.11.217:8545)
#
# Clients should send the API key as:
# - X-API-Key: sk_live_...
# or
# - Authorization: Bearer sk_live_...

server {
    listen 443 ssl http2;
    server_name protected-rpc.example.org;

    # Internal subrequest used by auth_request.
    location = /__access_validate_rpc {
        internal;
        proxy_pass http://127.0.0.1:8081/api/v1/access/internal/validate-key;
        proxy_pass_request_body off;
        proxy_set_header Content-Length "";
        proxy_set_header X-Access-Internal-Secret "ACCESS_INTERNAL_SECRET_VALUE";
        proxy_set_header X-API-Key $http_x_api_key;
        proxy_set_header Authorization $http_authorization;
        proxy_set_header X-Access-Method $request_method;
        proxy_set_header X-Access-Request-Count "1";
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location / {
        auth_request /__access_validate_rpc;

        # Optional metadata exported from the validator for logging or rate decisions.
        auth_request_set $validated_product $upstream_http_x_validated_product;
        auth_request_set $validated_tier $upstream_http_x_validated_tier;
        auth_request_set $validated_scopes $upstream_http_x_validated_scopes;
        auth_request_set $quota_remaining $upstream_http_x_quota_remaining;

        proxy_pass http://192.168.11.217:8545;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # Helpful for downstream logs and operational tracing.
        proxy_set_header X-Validated-Product $validated_product;
        proxy_set_header X-Validated-Tier $validated_tier;
        proxy_set_header X-Validated-Scopes $validated_scopes;
        proxy_set_header X-Quota-Remaining $quota_remaining;
    }
}
