Skip to content

Demonstrate an identity-gated edge with Tunnel

Build a small HTTP service behind Access and Tunnel. Verify that an entitled browser user reaches its protected handler. Then test anonymous entry and a subject-level authorization denial. Use the design guide for the security requirements and production acceptance matrix.

Prerequisites and inputs

Use a dedicated test hostname, Access application, and Tunnel. Run Node.js 24 and a current cloudflared on the same isolated test host, without an existing connector service. Install cloudflared, configure an identity provider, and use a supported proxied DNS setup.

Input Example or requirement
Public hostname pilot.example.com, not an existing application hostname
Team domain https://your-team.cloudflareaccess.com, without a trailing slash
Application AUD The audience of this pilot's Access application
Pilot identity A dedicated browser user explicitly entitled by the Access policy
Origin listener 127.0.0.1:8080, reachable only on the connector host
Evidence Browser network panel and captured standard output from the handler
Resource inventory IDs of the dedicated application, policies, Tunnel, route, DNS record, and cache rule used by the pilot

The service listens at 127.0.0.1, an address reachable only from the same machine. This is called a loopback address. The connection from cloudflared to the service uses HTTP because it never leaves that machine. The browser-to-Cloudflare and Tunnel connections remain encrypted. Do not change the listener to 0.0.0.0, publish its port, or move the connector to another host without configuring the network restrictions and TLS validation described in the design guide.

Create the protected handler

  1. Create an empty, dedicated local directory. In that directory, save this package.json:

    {
      "private": true,
      "type": "module"
    }
  2. Install the JWT library. Keep the generated lockfile with your test record.

    npm i jose@6
  3. Save the following code as server.mjs. It verifies the signed Access assertion independently of cloudflared. A client-supplied identity header alone is not trusted.

    server.mjsjavascript
    import { createServer } from 'node:http';
    import { randomUUID } from 'node:crypto';
    import { createRemoteJWKSet, jwtVerify } from 'jose';
    
    const { TEAM_DOMAIN, ACCESS_AUD } = process.env;
    if (!TEAM_DOMAIN || !ACCESS_AUD) {
      throw new Error('Set TEAM_DOMAIN and ACCESS_AUD');
    }
    if (new URL(TEAM_DOMAIN).protocol !== 'https:') {
      throw new Error('TEAM_DOMAIN must use HTTPS');
    }
    const keys = createRemoteJWKSet(
      new URL('/cdn-cgi/access/certs', TEAM_DOMAIN),
    );
    
    createServer(async (request, response) => {
      const requestId = randomUUID();
      const reply = (status, body, stage) => {
        response.writeHead(status, {
          'content-type': 'application/json',
          'cache-control': 'no-store',
          'x-demo-request-id': requestId,
        });
        response.end(JSON.stringify({ ...body, requestId }));
        console.log(JSON.stringify({
          time: new Date().toISOString(), requestId, stage, status,
        }));
      };
    
      let identity;
      try {
        const assertion = request.headers['cf-access-jwt-assertion'];
        if (typeof assertion !== 'string') throw new Error('Missing JWT');
        const { payload } = await jwtVerify(assertion, keys, {
          issuer: TEAM_DOMAIN,
          audience: ACCESS_AUD,
          algorithms: ['RS256'],
          requiredClaims: ['exp', 'sub'],
        });
        if (typeof payload.sub !== 'string' || !payload.sub) {
          throw new Error('Missing subject');
        }
        identity = payload;
      } catch {
        reply(401, { error: 'Admission denied' }, 'admission');
        return;
      }
    
      let url;
      try {
        url = new URL(request.url, 'http://127.0.0.1');
      } catch {
        reply(400, { error: 'Invalid URL' }, 'handler');
        return;
      }
      if (request.method !== 'GET') {
        reply(405, { error: 'Use GET' }, 'handler');
      } else if (url.pathname === '/me') {
        const query = new URLSearchParams({ owner: identity.sub });
        reply(200, {
          subject: identity.sub,
          ownResource: `/records?${query}`,
        }, 'handler');
      } else if (url.pathname === '/records') {
        if (url.searchParams.get('owner') !== identity.sub) {
          reply(403, { error: 'Forbidden' }, 'handler');
          return;
        }
        reply(200, { message: 'Demonstration record' }, 'handler');
      } else {
        reply(404, { error: 'Not found' }, 'handler');
      }
    }).listen(8080, '127.0.0.1');

The admission log stage records requests rejected before application logic. The handler stage records requests that passed JWT validation, including application authorization denials. Responses and logs share a server-generated request ID. The code does not log assertions, cookies, or subjects. Treat the subject returned by /me as test-user information.

Deploy the pilot

  1. Create a dedicated self-hosted Access application for pilot.example.com, covering all paths. Add an Allow policy for the dedicated test identity. Configure the IdP, MFA, cookie, and session requirements from the design guide. Inspect overlapping applications and policies. Do not add Bypass, anonymous paths, or machine credentials for this browser-only pilot.

  2. Record the application's AUD. In the local demonstration directory, create .env with your values:

    .envsh
    TEAM_DOMAIN=https://[your-team].cloudflareaccess.com
    ACCESS_AUD=replace-with-pilot-application-audience

    Replace [your-team], including the brackets, with your Access team name. Replace the ACCESS_AUD example with the pilot application's audience. Do not commit .env, tunnel credentials, or browser cookies. Keep the directory private to the test operator.

  3. On the connector host, start the handler in a terminal. Keep its standard output available for correlation:

    node --env-file=.env server.mjs

    From that host, request http://127.0.0.1:8080/me without an assertion. Expect 401, an Admission denied response, and a matching admission log. Confirm the listener is loopback-only and no port forwarding exposes it. This is a deployed local admission check, not an Access edge test.

  4. Create a dedicated remotely managed Tunnel. Install its connector on the handler host using the dashboard instructions. Protect the tunnel token and record the connector version. Do not publish the application until its Access configuration exists.

  5. Follow the remotely managed configuration path. Publish only pilot.example.com, using service URL http://127.0.0.1:8080. Turn on Protect with Access, set the team and pilot AUD, and inspect the saved remote configuration before testing. Audit other routes for alternate access to the listener.

    Alternatively, follow the locally managed configuration path. Use the pilot hostname and http://127.0.0.1:8080 service in that example. Retain per-rule JWT validation and the rejecting catch-all. Complete the linked local Tunnel setup before creating its DNS route. Do not configure both management paths for the same tunnel.

  6. Inspect cache rules. Configure a cache bypass for the dedicated pilot hostname, and ensure no conflicting rule or Worker overrides it. Authentication controls who can request a response. It does not make a personalized response safe to cache. If a cache rule stores a response without separating users, another user could receive it. The handler also returns Cache-Control: no-store. Record the effective cache configuration. This does not establish two-user cache isolation.

The local HTTP connection is specific to this demonstration. For an origin on another machine, use HTTPS, preserve certificate verification, and configure the expected origin server name and CA trust.

Verify the legitimate-user positive control

Do this before interpreting negative tests or missing log entries.

  1. In the entitled user's browser, open the network panel and preserve the request history. Visit https://pilot.example.com/me and complete manual IdP authentication.
  2. Confirm the final response is the demonstration's 200 JSON, not an Access page. Record its requestId or X-Demo-Request-Id response header.
  3. Find the same ID in the origin's standard output. Require stage: handler and status: 200. Record UTC time and the configuration version. A redirect alone is not a successful positive control.
  4. On the same hostname, open the ownResource path returned by /me. Require 200 with Demonstration record. Match that response's ID to another handler log.

If the positive control fails, investigate the deployment or evidence collection first. Do not call a negative test successful based on empty logs. Repeat the positive control after configuration changes and after the negative-test batch to bound the logging window.

Do not export cookies, JWTs, tunnel tokens, or unredacted browser archives into the evidence record. Request IDs and redacted status records are sufficient for this demonstration.

Run minimum pilot verification

Run these checks against the deployed pilot. They are not unit simulations. Start every result as not tested and use the test record format.

ID and action Required persona or credential Test location Expected evidence Applicability
P1: Complete sign-in; request /me and its ownResource Entitled browser user with valid Access session External browser through the pilot hostname Two 200 responses with matching origin request IDs, handler stages, and statuses Required positive control
P2: Request /me without signing in Separate fresh browser profile without Access or IdP credentials External browser through the pilot hostname Access redirects or denies; no demonstration response or protected-handler entry during the bounded window; P1 confirms logging works Required anonymous-entry check
P3: Request /records?owner=not-this-subject after confirming that value differs from /me's subject P1's entitled browser session External browser through the pilot hostname 403 from the demonstration with a matching handler log Required application authorization check
P4: Request /me without an assertion No credential Connector host, directly to 127.0.0.1:8080 401 with a matching admission log and no handler entry for that ID Required local admission check

For P2, stop at the Access response. Do not complete authentication. If the profile signs in automatically, it is not an anonymous test. For P3, a mismatched owner value demonstrates one ownership comparison. It does not require, or establish isolation between, two authenticated users.

To run the checks, replace pilot.example.com with your pilot hostname:

  1. P1: In the signed-in browser used for the positive control, visit https://pilot.example.com/me. Copy the ownResource path from the JSON response and open it on the same hostname. Use the browser network panel to check both response statuses and match their request IDs to the handler logs.

  2. P2: Open a fresh browser profile without Access or IdP credentials and visit https://pilot.example.com/me. Stop at the login page or denial. Check the network panel for the redirect or denial, and confirm no corresponding protected-handler request appears in the service logs.

  3. P3: Return to P1's signed-in browser. Confirm that not-this-subject differs from the subject returned by /me, then visit https://pilot.example.com/records?owner=not-this-subject. Check for 403 in the network panel and a matching handler log.

  4. P4: On the machine running the service, open a terminal and run:

    curl --include http://127.0.0.1:8080/me

    In Windows PowerShell, use curl.exe instead of curl. Do not add an Access assertion header. Expect 401 and match the response's requestId to an admission log, with no handler entry for that ID.

A successful browser pilot establishes only the tested route and outcomes. It does not establish binding-cookie replay protection, session expiry or revocation, weak-method denial, unentitled-user denial, or two-user cache isolation. Keep those checks not tested until independently exercised with the required personas and evidence. Continue with production acceptance.

Next steps

Use the production acceptance matrix before adapting the pattern to a real application. Add production authorization, data handling, observability, availability, and operational controls. A local test or browser demonstration does not replace deployed validation of those controls.

Was this helpful?