joe-cole1/pangolin-ip-rule-manager
Sobre
Automatically manage temporary Pangolin IP bypass rules for devices that can't use SSO (like smart TVs). Bootstraps trust from authenticated devices using real-time role validation and a fail-closed security architecture.
Segurança e privacidadeCrescimento medido de estrelas
- em 24 h
- 0
- em 7 dias
- 0
- em 15 dias
- Coletando histórico
- em 1 mês
- Coletando histórico
Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.
README.md
OriginalPangolin IP Rule Manager
A lightweight Python service that automatically manages Pangolin IP bypass rules and (optionally) CrowdSec allowlist entries based on observed client IPs. It bootstraps trust from an authenticated device (like a phone) to a device that cannot authenticate (like a TV), while honoring each user's role-based permissions in Pangolin.
Upgrading
| Upgrade path | Required action |
|---|---|
| v3.0.0 or v3.0.1 → v3.1.0 | No new env vars, API permissions, or state-file migration for valid v3.0.x configs. Review the pre-flight checks (stricter startup validation, fail-closed /update JSON status codes, outbound transport & optional socket-proxy updates), keep the persistent volume, and replace the container with the new image once published. |
| v2.x or earlier → v3.x | Complete the v3.0.0 migration: Badger v1.4.1 or newer, List Users permission, and the shared proxy secret. |
See the v3.1.0 release notes and upgrade guide for deployment, verification, and rollback. Published versions are listed in GitHub Releases.
Table of Contents
- Upgrading
- Overview
- The Problem It Solves
- How It Works
- Prerequisites
- Quick Start
- Configuration Reference
- Pangolin Resource Setup
- Pangolin Compatibility
- CrowdSec Integration
- Advanced Features
- Behaviour Reference
- Security Notes
- Disclaimer
Overview
When a service sits behind Pangolin user authentication, every request must be authenticated. That works for browsers, but native TV apps (Roku, Android TV, Fire TV) have no way to complete a browser-based login flow. This service solves that by letting an already-authenticated device register its public IP, which creates a temporary, per-resource bypass rule so other devices sharing that IP can reach the service directly. Both Pangolin-managed users and users from an external OIDC provider such as Authentik are supported.
Crucially, it does this without weakening your security posture: it identifies who is checking in, intersects their Pangolin role permissions against the resources you've configured, and only ever whitelists resources that user is actually entitled to. If it cannot positively identify the user, it creates nothing.
The Problem It Solves
Jellyfin's native apps (and many others like it) cannot authenticate through Pangolin's SSO flow — they have no browser context to complete the challenge. The standard workaround, making the service fully public, removes authentication entirely. That is not acceptable if you want your service protected by default.
This service bridges the gap:
- A check-in URL is placed behind Pangolin user authentication — your phone can reach it after logging in
- You visit that URL on your phone and authenticate with Pangolin
- The service identifies you, confirms which resources you are permitted in Pangolin, records your public IP, and creates a bypass rule for each permitted resource
- Your TV, on the same network and sharing the same public IP, can now reach those services without authenticating
- Rules expire automatically after a configurable TTL
Known limitation: This approach requires the phone and TV to share the same public IP address (e.g., both on home Wi-Fi). This is a known design constraint, not a bug. Carrier-grade NAT (CGNAT) weakens the trust model but does not cause a functional failure.
Sharing Wi-Fi does not always mean sharing a public IP. A phone using a full-tunnel VPN, a Pangolin exit node, mobile data, or a privacy relay may send its check-in through a different Internet connection from the TV. Compare the IP on the HTML check-in page with the TV network's public IP. If they differ, route the phone's check-in through the same connection as the TV and check in again. A split-tunnel VPN only affects this if it routes the check-in traffic through a different connection.
How It Works
To understand what this service does, it helps to understand how Pangolin protects resources, what an IP rule changes, and how the service uses your Pangolin roles to decide what to whitelist.
Pangolin IP Rules Explained
When a resource is placed behind Pangolin, every request to it is intercepted. Pangolin checks whether the requester is authenticated — typically via SSO — and if not, redirects them to a login page before they can reach the service. This is what you want... your service is protected, and only authenticated users get through.
Pangolin also supports IP-based bypass rules on a per-resource basis. When an IP rule exists for a given resource, Pangolin skips the authentication check for requests originating from that IP and forwards them directly to the service. This is the mechanism this service manages.
It does not weaken your overall setup. The protected resource remains behind auth for everyone else. The service selectively grants pass-through for specific IPs, for a configurable period, then automatically revokes it.
Role-Based Access Control
The service does not blindly whitelist every configured resource for every visitor. It enforces a two-layer model:
RESOURCE_IDSis the administrative safety gate — the complete set of resources that the service is ever permitted to manage.- Each user's Pangolin account is the per-user entitlement filter — what that specific person is allowed to reach, either via their role or by adding them in the resource's user's access control.
On each check-in, the service computes the intersection of these two: the resources you've configured to allow whitelisting and the resources the checking-in user's account in Pangolin permits. Only that intersection is whitelisted.
This means a family member with a limited role only ever bootstraps access to the resources their role allows, even if the service is configured to manage many more. An administrator with broader permissions bootstraps access to more of them.
Fail-closed by design. If the Pangolin proxy secret is absent or invalid, either Remote-User-Id or Remote-User is absent, the two identity values do not match Pangolin's organization user record, or any required Pangolin API call fails, the service whitelists nothing. It never falls back to whitelisting everything. This is a deliberate security property: a misconfiguration or API hiccup results in no access granted, never over-broad access granted.
Prerequisites
Pangolin Integration API
This service uses the Pangolin Integration API. You must enable it and generate a token in your Pangolin instance before proceeding.
PANGOLIN_URL is the dedicated Integration API endpoint you configure when enabling the API (e.g., https://api.yourdomain.com) — not your general Pangolin instance URL. All API calls are made to /v1/ paths under this URL.
API Token Permissions
Create a Pangolin API token with the following permissions:
- List Users — find the current organization user, verify both identity headers, and read the user's current roles
- List Resources — discover resources in the organization (used at startup)
- Get Resource — fetch each resource's name and public domain
- List Allowed Resource Roles — read which roles are permitted on each resource
- List Resource Rules — read existing rules for managed resources
- List Resource Users — read users directly assigned to a resource
- Create Resource Rule — create IP bypass rules
- Delete Resource Rule — remove expired rules during cleanup
Quick Start
Accomplish the Pangolin pre-requisites above.
Recommended: Pull the pre-built image from GHCR rather than building locally. Multi-arch images (
linux/amd64,linux/arm64) are published automatically on each release.
Docker Compose Reference
services:
pangolin-ip-rule-manager:
image: ghcr.io/joe-cole1/pangolin-ip-rule-manager:latest
container_name: pangolin-ip-rule-manager
environment:
# Network
LISTEN_PORT: "8080"
# Pangolin connection — inject via secrets, not hardcoded
PANGOLIN_URL: ${PANGOLIN_URL}
PANGOLIN_TOKEN: ${PANGOLIN_TOKEN}
ORG_ID: ${ORG_ID}
RESOURCE_IDS: ${RESOURCE_IDS}
PROXY_SHARED_SECRET: ${PROXY_SHARED_SECRET:?set PROXY_SHARED_SECRET}
# Retention and cleanup
RETENTION_MINUTES: "1440" # 1 day
CLEANUP_INTERVAL_MINUTES: "60"
RULE_PRIORITY: "0"
RULES_CACHE_TTL_SECONDS: "3600"
# State
STATE_FILE: /data/state.json
# Branding
SITE_NAME: "" # shown in HTML page header/footer; leave empty to omit
# ---------------------------------------------------------------------------
# Resource Launcher Integration
# ---------------------------------------------------------------------------
REDIRECT_TO_LAUNCHER: "false"
REDIRECT_DELAY_SECONDS: "3"
# PANGOLIN_DASHBOARD_URL: "https://pangolin.yourdomain.com/your_org_id"
# ---------------------------------------------------------------------------
# CrowdSec integration (optional — disabled by default)
# ---------------------------------------------------------------------------
# Use the socket-proxy block in docker-compose.yml when enabling this.
CROWDSEC_ENABLED: "false"
CROWDSEC_ALLOWLIST_NAME: pangolin-ip-rule-manager
CROWDSEC_CACHE_TTL_SECONDS: "3600"
CROWDSEC_CMD_PREFIX: "docker exec crowdsec"
CROWDSEC_CSCLI_BIN: cscli
# Optional endpoints (disabled by default)
UPDATE_ENDPOINT_ENABLED: "false"
user: "100:101"
init: true
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
tmpfs:
- /tmp:rw,noexec,nosuid,nodev,size=16m,mode=1777
pids_limit: 128
cpus: "0.5"
mem_limit: "256M"
volumes:
- pangolin-ip-rule-manager-data:/data
restart: unless-stopped
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
volumes:
pangolin-ip-rule-manager-data: {}
Set environment variables via a .env file or directly in Portainer/your orchestration tool. Never hardcode credentials.
The named volume is created and permissioned by Docker from the image metadata;
the non-root entrypoint also tightens volumes from earlier releases to mode
0700 automatically. Fresh installs and upgrades require no host-side chmod,
chown, directory creation, or other setup commands.
The image includes its own /healthz health check, so Docker and Compose report
container health without a healthcheck override in the Compose file.
Finding Your Resource IDs
Start the container once with RESOURCE_IDS set to any placeholder. On startup, the service queries Pangolin and prints all resources for your org with their IDs:
[pangolin] These are the resources for org 'your_org_id'. Use the resourceId numbers for your configuration:
- Jellyfin (resourceId=3)
- Immich (resourceId=5)
Set RESOURCE_IDS to the correct IDs and restart.
Minimum Required Variables
At minimum you need:
PANGOLIN_URL,PANGOLIN_TOKEN,ORG_ID,RESOURCE_IDS,PROXY_SHARED_SECRET
The app will refuse to start if PANGOLIN_URL, RESOURCE_IDS, or PROXY_SHARED_SECRET are missing or empty. The API token and organization ID are also required for successful check-ins.
Configuration Reference
Pangolin Connection
| Variable | Default | Required | Description |
|---|---|---|---|
PANGOLIN_URL |
— | Yes | The URL of your Pangolin Integration API endpoint (e.g. https://api.yourdomain.com) — not your general instance URL. All API calls are made to /v1/ paths under this URL. |
PANGOLIN_TOKEN |
— | Yes | Bearer token for the Pangolin API. Rules will not be created or deleted without this. |
ORG_ID |
— | Yes | Your Pangolin organization ID. Used to list resources at startup and to look up users during check-in. |
RESOURCE_IDS |
— | Yes | Comma-separated list of Pangolin resource IDs the service is permitted to manage (e.g., 3,5,12). This is the administrative safety gate; per-user role permissions further filter it. |
PROXY_SHARED_SECRET |
— | Yes | Random secret shared by Pangolin and this app. Add the same value to the app environment and the Pangolin resource's X-Proxy-Secret custom request header. |
Behaviour
| Variable | Default | Required | Description |
|---|---|---|---|
LISTEN_PORT |
8080 |
No | Port the HTTP server listens on inside the container. |
RETENTION_MINUTES |
1440 |
No | How long after the last check-in (in minutes) before a rule is considered stale and removed. |
CLEANUP_INTERVAL_MINUTES |
60 |
No | How frequently (in minutes) the cleanup background thread runs. |
RULE_PRIORITY |
0 |
No | Priority assigned to created Pangolin IP rules. Lower numbers run first; the first matching enabled rule wins. See HTTP Method Rules and Priority. |
RULES_CACHE_TTL_SECONDS |
3600 |
No | How long (in seconds) to cache Pangolin rule existence checks before re-querying. Reduces API traffic. |
RATE_LIMIT_SECONDS |
300 |
No | Minimum seconds between Pangolin API fan-out calls for the same IP. Repeat check-ins within this window return a cached result without calling Pangolin. Set to 0 to disable. |
STATE_FILE |
/data/state.json |
No | Path to the persistent state file. Mount a volume at the parent directory to survive restarts. |
Resource Launcher Integration
This feature allows you to seamlessly redirect users to the Pangolin Resource Launcher (dashboard) after a successful check-in. Instead of showing the check-in confirmation page indefinitely, users are bounced to the launcher where they can launch the resources they just unlocked. If a check-in fails, the redirection is bypassed so the user can see the error.
| Variable | Default | Required | Description |
|---|---|---|---|
REDIRECT_TO_LAUNCHER |
false |
No | Set to true to enable automatic redirection to the Pangolin Resource Launcher upon successful check-in. |
REDIRECT_DELAY_SECONDS |
3 |
No | How long (in seconds) to display the check-in success page before redirecting. Set to 0 for an immediate, invisible HTTP 302 redirect. When > 0, a visual countdown timer is shown, and the individual app list is hidden. |
PANGOLIN_DASHBOARD_URL |
(empty) | No | Explicitly override the destination URL for the launcher. If left empty, it is automatically derived from PANGOLIN_URL by stripping API paths and appending your ORG_ID. Example: https://pangolin.yourdomain.com/your_org_id. |
CrowdSec
CrowdSec integration is disabled by default. When enabled, the service adds IPs to a named CrowdSec allowlist on check-in and removes them on expiry. See CrowdSec Integration for setup details.
| Variable | Default | Required | Description |
|---|---|---|---|
CROWDSEC_ENABLED |
false |
No | Set to true to enable CrowdSec integration. |
CROWDSEC_ALLOWLIST_NAME |
pangolin-ip-rule-manager |
No | Name of the CrowdSec allowlist to manage. Created automatically if it doesn't exist. |
CROWDSEC_CACHE_TTL_SECONDS |
3600 |
No | How long (in seconds) to cache CrowdSec allowlist membership before re-querying via cscli. |
CROWDSEC_CMD_PREFIX |
(empty) | No | Command prefix for running cscli. Example: docker exec crowdsec. |
CROWDSEC_CSCLI_BIN |
cscli |
No | Path or name of the cscli binary inside the CrowdSec container. |
Optional
| Variable | Default | Required | Description |
|---|---|---|---|
SITE_NAME |
(empty) | No | Name shown in the card header and footer of the HTML check-in and error pages (e.g. yourdomain.com). When empty, the subtitle and footer domain are omitted. |
UPDATE_ENDPOINT_ENABLED |
false |
No | Enables the /update?ip=... endpoint. See Manual IP Override. |
DEBUG_LOG_HEADERS |
false |
No | Logs incoming request headers for debugging (preserving duplicate headers and sanitizing control characters) with sensitive headers redacted. Leave false in production. |
Pangolin Resource Setup
This service must be exposed through a Pangolin resource so that Pangolin handles authentication and forwards requests to the container.
Pangolin User Authentication Requirement
This is the most important and most easily missed part of the setup.
The resource fronting this service must use Pangolin user authentication. The user may have a Pangolin-managed account or may sign in through an external provider such as Authentik. Both types of account follow the same check-in process.
Resource passwords, PINs, share links, and authentication bypasses are not supported because they do not identify a Pangolin user. Badger v1.4.1 or newer is required so Pangolin can send the user information the app needs.
The app checks both identity values against Pangolin before granting access. If the ID and username do not belong to the same current Pangolin user, the check-in is rejected.
Set the Pangolin Proxy Secret
PROXY_SHARED_SECRET is required. Pangolin and the app must use the same secret value.
Generate a random secret. It should be at least 32 characters long. One way to generate one is:
openssl rand -hex 32Save that value in your secret manager.
Set the app's
PROXY_SHARED_SECRETenvironment variable to that value. If you use the provided Compose file, add it to your.envfile:PROXY_SHARED_SECRET=your-generated-secretIn Pangolin, open the resource for this app and find Additional Proxy Settings.
In Custom Request Headers, add this line, replacing the example text with the same secret:
X-Proxy-Secret: your-generated-secretClick Save Settings.

The screenshot uses placeholder text. Do not copy that placeholder into your live configuration, and do not publish a screenshot containing your real secret.
Pangolin adds this header before sending the request to the app. The app rejects any check-in that does not contain the matching value. This helps prevent someone from reaching the app directly and supplying fake Pangolin identity headers.
Pangolin 1.24 has separate Custom Request Headers and Custom Response Headers fields. Keep X-Proxy-Secret in Custom Request Headers. Putting it in response headers sends the secret to the client and does not authenticate the request to this app. The upgrade migrates existing request headers; confirm the entry is still in the request field after upgrading.
Do not make the app's port directly accessible from the Internet. The app should only be reachable through Pangolin. If you use the provided Compose file, no change is needed; it already keeps the port private.
Resource Setup Steps
- In Pangolin, create a resource for the app (for example,
checkin.yourdomain.com) and set its target to this app on port8080 - Configure the resource for Pangolin user authentication; internal accounts and external OIDC providers are both supported
- Confirm Badger is v1.4.1 or newer
- Follow Set the Pangolin Proxy Secret
- Make sure the app is reachable only through Pangolin, not directly from the Internet
- Confirm your API token has all the required permissions
Pangolin Compatibility
Live Integration API compatibility is verified against real disposable Pangolin containers (both CE and unlicensed EE) across Pangolin 1.24.0 through 1.27.2. The v3.0.0 prerequisites — including Badger v1.4.1 or newer, List Users permission, and PROXY_SHARED_SECRET — apply to all versions below.
| Pangolin version | Editions | Scope verified | Evidence |
|---|---|---|---|
1.27.2 (latest tested) |
CE, EE | All 8 Integration API contracts, auth, rule CRUD & cleanup | CI run #56 |
1.26.0 |
CE, EE | All 8 Integration API contracts, auth, rule CRUD & cleanup | CI run |
1.24.0 (baseline) |
CE, EE | All 8 Integration API contracts, auth, rule CRUD & cleanup (digest-pinned CE baseline) | CI run |
Automated compatibility runs spin up real disposable Pangolin CE and EE containers and exercise all eight Integration API endpoints, fail-closed auth checks, and rule lifecycle/cleanup (see docs/pangolin-compatibility.md). Badger/Traefik header forwarding and licensed EE-only features are validated separately via the manual checks below.
Pangolin 1.24+ Notes
Starting with Pangolin 1.24.0, no new app environment variables or API permissions are required. The app uses the existing IP rule API and reads only resource display metadata, so the requestHeaders and responseHeaders resource fields do not change its check-in flow.
HTTP Method Rules and Priority
Pangolin 1.24 adds METHOD rules, such as GET or POST,PUT. The manager creates IP / ACCEPT rules and leaves METHOD rules alone. Pangolin checks enabled rules from lowest to highest priority number and uses the first match:
| Action | What happens when the rule matches |
|---|---|
ACCEPT |
Bypass Pangolin authentication. |
DROP |
Deny the request. |
PASS |
Stop checking rules and continue through the resource's normal authentication. |
For example, on a managed Jellyfin resource:
| Priority | Rule | Result for a POST from the checked-in IP |
|---|---|---|
0 |
IP / ACCEPT for the checked-in IP |
Matches first; Pangolin authentication is bypassed. |
10 |
METHOD / PASS for POST,PUT |
Never reached for that IP. |
Moving the METHOD / PASS rule ahead of the IP rule makes matching methods require normal authentication, even from a checked-in IP. This can prevent a native TV app from working. Separate IP and METHOD rules do not mean "this IP AND this method." Review the intended order, use distinct priorities, and test the TV app before changing RULE_PRIORITY or adding METHOD rules. Changing RULE_PRIORITY affects newly created rules; it does not reorder existing ones.
Keep the check-in resource itself behind Pangolin user authentication. Do not add it to RESOURCE_IDS or add an authentication bypass such as METHOD / ACCEPT for GET. A bypassed request lacks the verified user identity needed to grant access; an HTTP 200 or a returned check-in image alone does not prove that a rule was created.
Response Headers and Caching
Leave the check-in resource's custom response headers empty unless you need a deliberate override. The app already sends Cache-Control: no-store, no-cache, must-revalidate, max-age=0, Pragma: no-cache, Expires: 0, and browser security headers. A proxy or CDN cache override can serve an old page or image without reaching the app, so the visit will not refresh the IP's expiry time.
The HTML page uses inline styles and scripts for its layout, bookmark button, technical-details toggle, and optional redirect countdown. A stricter Content-Security-Policy response override can block these features. Confirm the delivered response still has the intended cache and security headers after any override.
Upgrade Validation
For a repeatable real-API check, run the disposable compatibility suite. It provisions its own Pangolin installation and credentials and checks the application's API, authorization, rule lifecycle, and ownership behavior. It is separate from ordinary unit/image CI. The workflow can test CE, EE or both with separate results and verifies the running server's edition. EE uses the actual Enterprise image without license activation; licensed Enterprise features remain outside these core API checks. The manual proxy checks below still cover Badger/Traefik behavior outside that suite's scope.
Unit tests use a mocked Pangolin API; the separate compatibility suite uses real disposable Pangolin instances. Neither replaces checking the deployed proxy configuration. For the manual checks below, use a separate test container, a throwaway Pangolin resource, and test credentials. Keep CrowdSec disabled for this check so it cannot modify a live allowlist.
- Confirm
X-Proxy-Secretis in Custom Request Headers and the check-in resource uses Pangolin user authentication. Keep its custom response headers empty for this check. - Check in as a user with limited access. Confirm the displayed IP is correct, only permitted resources gain an IP /
ACCEPTrule, and the phone and TV use the same public IP. Read the HTML result and inspect the rules rather than relying on HTTP 200. - On a throwaway managed resource, add a METHOD rule with a distinct priority. Check in again and confirm it survives alongside the IP rule. Exercise the TV app's read and write operations to verify the intended first-match order.
- In the test container only, set a short retention and cleanup interval and
RATE_LIMIT_SECONDS=0. Wait for expiry, confirm only manager-created IP rules disappear, then check in again and confirm the IP rule is recreated. METHOD rules and pre-existing IP rules must remain. - Inspect the check-in response in browser developer tools: it should retain
Cache-Control: no-storeand the app's security headers. Confirm the page controls and any enabled redirect countdown work.
Upstream changes: request and response headers (#3172), HTTP method rules (#3704), and client IP configuration (#3811). If you change Pangolin's trusted-proxy or custom-IP-header settings, verify the IP shown by the check-in page before granting access; these are Pangolin settings, not new app environment variables.
CrowdSec Integration
CrowdSec integration is optional and disabled by default. When enabled, the service adds each checked-in IP to a named CrowdSec allowlist on check-in and removes it when the rule expires.
Pangolin and CrowdSec are handled independently. If one succeeds and the other fails, the HTML success page shows the status of each integration separately. A CrowdSec failure does not roll back a successful Pangolin rule, and vice versa.
Setup
Runs cscli inside the CrowdSec container via docker exec; docker-cli is
always available in the image. Use the socket-proxy block in the checked-in
docker-compose.yml so the application receives only the Docker API operations
needed for exec.
CROWDSEC_ENABLED: "true"
CROWDSEC_CMD_PREFIX: "docker exec crowdsec"
CROWDSEC_CSCLI_BIN: cscli
Security note: A read-only bind mount does not make the Docker API read-only. Direct access to
/var/run/docker.sockis effectively host-root access; the isolated socket proxy indocker-compose.ymlis strongly recommended.
Advanced Features
Manual IP Override (/update endpoint)
When UPDATE_ENDPOINT_ENABLED=true, a /update?ip=<address> endpoint is available. This lets you manually specify which IP to allowlist rather than using the requester's IP — useful when the phone and TV are on different networks.
The endpoint is protected by the same role-based, fail-closed identity check as all other requests. When disabled (the default), the endpoint returns 404 and gives no indication it exists.
GET /update?ip=203.0.113.42
The IP must be a valid, globally routable address. Loopback, private, and link-local addresses are rejected.
There is no separate administrator-only role setting for this endpoint. An authenticated user can register an IP only for resources their Pangolin account permits. Any future change to this access model will be documented in that release's migration notes.
Invisible Check-in via CSS
If you want check-in to happen automatically whenever someone loads a service's web UI — without any user action — you can embed a CSS-triggered image request. The browser fetches the check-in URL invisibly as part of rendering the page, registering the IP without any visible change to the interface. This is the original motivation for the 1×1 transparent image design.
Add the following to the web UI's custom CSS (in Jellyfin: Dashboard → General → Custom CSS):
body::after {
content: "";
position: fixed;
inset: -9999px;
width: 1px;
height: 1px;
pointer-events: none;
background-image: url("https://checkin.yourdomain.com/checkin.png");
background-repeat: no-repeat;
}
Replace the URL with your actual check-in domain. The path can be anything as long as it ends in .png or .gif.
Note: This only works in a web UI. Native apps (Roku, Android TV, etc.) do not execute CSS, which is why the phone-based check-in flow exists in the first place. The two approaches complement each other.
Invisible requests do not display the HTML result or authorization errors. Use an explicit authenticated check-in and inspect the managed rules when verifying that access was granted.
Behaviour Reference
Startup
On startup the service:
- Validates that
PANGOLIN_URL,RESOURCE_IDS, andPROXY_SHARED_SECRETare set — exits with an error if not - Warns (but does not exit) if
PANGOLIN_TOKENis empty orORG_IDis unset - Checks that the state file directory exists and is writable
- Loads existing state from the state file
- Queries Pangolin and prints all resources for
ORG_IDwith their IDs, which also serves as a startup connectivity/auth check - If CrowdSec is enabled, ensures the named allowlist exists (creates it if needed)
- Starts the background cleanup thread
- Begins serving HTTP on
LISTEN_PORT
On Each Check-in Request
X-Proxy-Secretmust exactly matchPROXY_SHARED_SECRET. A missing or incorrect value receives HTTP 403 before any state write or Pangolin API call- Exactly one non-empty
Remote-User-Idand one non-emptyRemote-Userheader must be present. Duplicate, malformed, or missing identity headers fail closed - The client IP is extracted in priority order:
X-Real-IP→ first entry ofX-Forwarded-For→ socket address. Header IPs must be globally routable (private, loopback, link-local, and multicast addresses are rejected and the next candidate is tried) - The service searches Pangolin's organization user list for
Remote-User, then requires the returned permanent user ID and username to exactly matchRemote-User-IdandRemote-User. It reads the user's current roles only after both values match - For each resource in
RESOURCE_IDS, the service checks whether the user's role is permitted on that resource or whether the user is directly assigned to it — mirroring Pangolin's own OR logic. Any API failure here causes a fail-closed error — nothing is whitelisted - For each authorized resource, a Pangolin IP rule is created (if one does not already exist), and the resource's name and domain are fetched for the success-page link
- If CrowdSec is enabled and the IP is not already in the allowlist cache, it is added via
cscli - The response depends on the request's
Acceptheader:Accept: text/html→ styled status page showing per-target results, the IP, the expiry time, and an "Open <Name>" link for each whitelisted resource- All other requests → 1×1 transparent image (PNG or GIF depending on the path extension)
Cleanup
The background cleanup thread runs every CLEANUP_INTERVAL_MINUTES. For each IP in state whose last_seen is older than RETENTION_MINUTES:
- The service deletes any Pangolin rules it created (tracked by a
created_by_usflag). Rules that existed before the service touched them are left alone - If CrowdSec is enabled, the IP is removed from the allowlist
- The IP is removed from state
The delete logic distinguishes "rule already absent" (safe to clear from state) from "delete failed" (retained for retry on the next cycle), so a transient API failure never strands a permanent state entry.
State File
State is stored as JSON at STATE_FILE (default /data/state.json). Mount a named Docker volume at /data to persist it across restarts. The file is written atomically (write to .tmp, then os.replace) to prevent corruption on crash or restart.
Security Notes
- Required Pangolin proxy secret: Every check-in must carry the
X-Proxy-Secretvalue configured on the Pangolin resource. The app port must remain private so callers cannot bypass Pangolin. - Authenticated identity headers: Badger v1.4.1 or newer must strip client-supplied
Remote-*headers and forward bothRemote-User-IdandRemote-Useronly after Pangolin user authentication. - Fail-closed identity: If either identity header is missing, duplicated, or malformed, or any Pangolin API call fails during authorization, the service whitelists nothing. It never falls back to granting broad access.
- Role intersection: A user only ever bootstraps access to resources their Pangolin account permits, regardless of how many resources
RESOURCE_IDScontains. - Live identity validation: Every check-in searches the current Pangolin organization user list. The returned permanent user ID and username must exactly match both trusted identity headers before current role assignments are accepted.
- IP validation: IPs from
X-Real-IPandX-Forwarded-Forare validated and must be globally routable. The socket address fallback is not validated, as it is controlled by the OS/kernel rather than the caller. - Header redaction and log sanitization:
Authorization,Proxy-Authorization,X-Proxy-Secret,Cookie,Set-Cookie,X-Api-Key,X-Auth-Token,X-Csrf-Token,X-Xsrf-Token, and any header name containingcookie,secret,token,auth,api-key,apikey, orpasswordare redacted in debug log output, and control characters / Unicode line separators are sanitized before logging. - Secrets: All credentials should be stored in a secrets manager (e.g., Bitwarden) and injected at runtime. Never hardcode them in compose files or Dockerfiles.
- Scope of deletions: The service only deletes Pangolin rules it created itself. It will never touch rules that existed before it ran.
- Docker socket: Only required for CrowdSec integration (
docker exec crowdsec cscli ...). Prefer the isolated socket proxy indocker-compose.yml; mounting the raw socket read-only does not restrict Docker API operations.
Disclaimer
This project was created and is largely maintained with the assistance of AI tools. All generated code has been reviewed, tested, and quality-checked by the project owner before being committed. While kept intentionally simple and audited for security and correctness, it may still contain mistakes or omissions.
Always review the code, configuration, and security posture before deploying to production. Use at your own risk. Contributions, bug reports, and independent review are welcome.
Explore projetos relacionados
Carregando…