Skip to content

feat: add optional authentication logic for worker#331

Merged
rmeena840 merged 1 commit intomasterfrom
330-add-optional-authentication-logic-for-workers
Feb 3, 2026
Merged

feat: add optional authentication logic for worker#331
rmeena840 merged 1 commit intomasterfrom
330-add-optional-authentication-logic-for-workers

Conversation

@rmeena840
Copy link
Contributor

@rmeena840 rmeena840 commented Feb 2, 2026

Description

Closes: #330


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title
  • added ! to the type prefix if API or client breaking change
  • added appropriate labels to the PR
  • provided a link to the relevant issue or specification
  • added a changelog entry to CHANGELOG.md
  • included doc comments for public functions
  • updated the relevant documentation or specification
  • reviewed "Files changed" and left comments if necessary

Summary by Sourcery

Add optional bearer-token based authentication to the btcindexer worker, controlled via a new AUTH_BEARER_TOKEN environment variable.

New Features:

  • Introduce optional Authorization header validation for the btcindexer worker, returning 401 for unauthorized requests when AUTH_BEARER_TOKEN is set.

Build:

  • Extend worker environment and NodeJS process typings to include the AUTH_BEARER_TOKEN configuration value.

Signed-off-by: Ravindra Meena <rmeena840@gmail.com>
@rmeena840 rmeena840 self-assigned this Feb 2, 2026
@rmeena840 rmeena840 requested a review from a team as a code owner February 2, 2026 11:49
@rmeena840 rmeena840 linked an issue Feb 2, 2026 that may be closed by this pull request
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Feb 2, 2026

Reviewer's Guide

Adds optional bearer-token-based authentication in the btcindexer worker, controlled by a new AUTH_BEARER_TOKEN env binding, so that the endpoint can be protected when desired while remaining public by default.

Sequence diagram for optional bearer token authentication in btcindexer worker

sequenceDiagram
    actor Client
    participant Worker as BtcIndexerWorker
    participant Env
    participant Router

    Client->>Worker: HTTP request
    Worker->>Env: Read AUTH_BEARER_TOKEN
    alt AUTH_BEARER_TOKEN is not set
        Note over Worker,Env: Endpoint is public
        Worker->>Router: router.fetch(req, env, indexer)
        Router-->>Worker: Response
        Worker-->>Client: 200 OK (or other router response)
    else AUTH_BEARER_TOKEN is set
        Worker->>Worker: isAuthorized(req, env)
        alt Authorization header missing/invalid or token mismatch
            Worker-->>Client: 401 Unauthorized
        else Authorization header has matching Bearer token
            Worker->>Router: router.fetch(req, env, indexer)
            Router-->>Worker: Response
            Worker-->>Client: 200 OK (or other router response)
        end
    end
Loading

Updated class diagram for Env and authentication helper

classDiagram
    class Env {
        +string AUTH_BEARER_TOKEN
    }

    class ProcessEnv {
        +string AUTH_BEARER_TOKEN
    }

    class AuthHelper {
        +boolean isAuthorized(Request req, Env env)
    }

    AuthHelper ..> Env : reads
    ProcessEnv <|.. Env : build time mapping of bindings
Loading

File-Level Changes

Change Details Files
Introduce optional bearer-token authorization gate in the worker fetch handler.
  • Add isAuthorized helper that validates the Authorization header against AUTH_BEARER_TOKEN, treating missing env token as public access
  • Short-circuit fetch handler to return 401 Unauthorized when the request fails authorization before constructing the indexer and routing the request
packages/btcindexer/src/index.ts
Extend worker environment typing and configuration to support the AUTH_BEARER_TOKEN binding.
  • Add AUTH_BEARER_TOKEN to Cloudflare.Env typings and include it in NodeJS.ProcessEnv pick for local/dev usage
  • Update generated Wrangler type hash and minor whitespace/formatting in generated d.ts
  • (Implied) Update wrangler.jsonc worker configuration to declare the AUTH_BEARER_TOKEN binding
packages/btcindexer/worker-configuration.d.ts
packages/btcindexer/wrangler.jsonc

Assessment against linked issues

Issue Objective Addressed Explanation
#330 Add a new AUTH_BEARER_TOKEN environment variable (including typing/config) for the Cloudflare worker.
#330 Add optional authentication logic (middleware) to the worker’s HTTPS handler that, when AUTH_BEARER_TOKEN is set, validates the Authorization: Bearer header and rejects unauthorized requests.

Possibly linked issues

  • Add optional authentication logic for workers #330: PR introduces AUTH_BEARER_TOKEN env var and request authorization middleware, directly implementing the issue’s proposal.
  • #backend-workers: PR adds optional AUTH_BEARER_TOKEN-based auth to btcindexer worker, matching issue’s configurable Bearer authentication requirement.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues, and left some high level feedback:

  • The isAuthorized helper currently treats a missing AUTH_BEARER_TOKEN as ‘public mode’; if this is meant to be a hard security control rather than a convenience, consider requiring an explicit flag or failing fast when the token is not configured to avoid accidentally exposing the endpoint in misconfigured environments.
  • Given this is an authentication token, it may be safer to bind AUTH_BEARER_TOKEN as a secret (e.g., SecretsStoreSecret) rather than a plain string in the worker env so it is handled consistently with other sensitive values like NBTC_MINTING_SIGNER_MNEMONIC.
  • You currently return a plain-text 401 response; if consumers expect structured errors, consider returning a small JSON error body and setting an appropriate Content-Type header for consistency with the rest of the API.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `isAuthorized` helper currently treats a missing `AUTH_BEARER_TOKEN` as ‘public mode’; if this is meant to be a hard security control rather than a convenience, consider requiring an explicit flag or failing fast when the token is not configured to avoid accidentally exposing the endpoint in misconfigured environments.
- Given this is an authentication token, it may be safer to bind `AUTH_BEARER_TOKEN` as a secret (e.g., `SecretsStoreSecret`) rather than a plain string in the worker env so it is handled consistently with other sensitive values like `NBTC_MINTING_SIGNER_MNEMONIC`.
- You currently return a plain-text `401` response; if consumers expect structured errors, consider returning a small JSON error body and setting an appropriate `Content-Type` header for consistency with the rest of the API.

## Individual Comments

### Comment 1
<location> `packages/btcindexer/src/index.ts:24-26` </location>
<code_context>
+/**
+ * Validates the Authorization header against the AUTH_BEARER_TOKEN env var.
+ */
+function isAuthorized(req: Request, env: Env): boolean {
+	// If the token isn't set in the environment, we assume the endpoint is public
+	if (!env.AUTH_BEARER_TOKEN) return true;
+
+	const authHeader = req.headers.get("Authorization");
</code_context>

<issue_to_address>
**issue (bug_risk):** Reconsider treating an empty AUTH_BEARER_TOKEN as making the endpoint public.

Because this check treats any falsy AUTH_BEARER_TOKEN as "not set", an empty string (which the types allow) will silently make the endpoint public. That turns a simple misconfiguration into an auth bypass. Consider treating a defined-but-empty token as invalid (e.g., throw at startup or reject all requests) and only treating the endpoint as public when the binding is truly absent/undefined.
</issue_to_address>

### Comment 2
<location> `packages/btcindexer/src/index.ts:37-41` </location>
<code_context>
 export default {
 	async fetch(req: Request, env: Env, _ctx: ExecutionContext): Promise<Response> {
 		try {
+			if (!isAuthorized(req, env)) {
+				return new Response("Unauthorized", { status: 401 });
+			}
 			const indexer = await indexerFromEnv(env);
</code_context>

<issue_to_address>
**suggestion:** Consider returning a more standard 401 response with a WWW-Authenticate header.

In particular, include a `WWW-Authenticate: Bearer` header (and optionally a machine-readable body) on 401 responses so generic HTTP auth clients can detect that bearer authentication is required and integrate more smoothly.

```suggestion
		try {
			if (!isAuthorized(req, env)) {
				return new Response(
					JSON.stringify({
						error: "unauthorized",
						error_description: "Missing or invalid bearer token",
					}),
					{
						status: 401,
						headers: {
							"WWW-Authenticate": 'Bearer realm="btcindexer"',
							"Content-Type": "application/json",
						},
					},
				);
			}
			const indexer = await indexerFromEnv(env);
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@rmeena840 rmeena840 merged commit a65b82f into master Feb 3, 2026
13 checks passed
@rmeena840 rmeena840 deleted the 330-add-optional-authentication-logic-for-workers branch February 3, 2026 10:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add optional authentication logic for workers

2 participants