feat: add optional authentication logic for worker#331
Merged
Conversation
Signed-off-by: Ravindra Meena <rmeena840@gmail.com>
Contributor
Reviewer's GuideAdds 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 workersequenceDiagram
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
Updated class diagram for Env and authentication helperclassDiagram
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
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Contributor
There was a problem hiding this comment.
Hey - I've found 2 issues, and left some high level feedback:
- The
isAuthorizedhelper currently treats a missingAUTH_BEARER_TOKENas ‘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_TOKENas a secret (e.g.,SecretsStoreSecret) rather than a plain string in the worker env so it is handled consistently with other sensitive values likeNBTC_MINTING_SIGNER_MNEMONIC. - You currently return a plain-text
401response; if consumers expect structured errors, consider returning a small JSON error body and setting an appropriateContent-Typeheader 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>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
robert-zaremba
approved these changes
Feb 2, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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...
!to the type prefix if API or client breaking changeCHANGELOG.mdSummary by Sourcery
Add optional bearer-token based authentication to the btcindexer worker, controlled via a new AUTH_BEARER_TOKEN environment variable.
New Features:
Build: