Skip to content

fix(licensing): accept an already exchanged api_key on /license/activate - #2815

Closed
daniloleonecarneiro wants to merge 1 commit into
developfrom
fix/license-activate-accepts-api-key
Closed

daniloleonecarneiro wants to merge 1 commit into
developfrom
fix/license-activate-accepts-api-key

Conversation

@daniloleonecarneiro

@daniloleonecarneiro daniloleonecarneiro commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

📋 Description

When a registration starts without redirect_uri, the licensing success page shows the authorization code. If that code is traded for an api_key outside the instance (POST /v1/register/exchange), it is burnt, and /license/activate?code= then fails with authorization code expired or already used for both the code and the resulting api_key.

activateWithCode now falls back to treating the value as an api_key when the exchange fails, the same way completeActivation already resolves "code or key". The value is stored only after /v1/activate accepts it, so a wrong code is never saved as the license. If both fail, the original exchange error is returned (still 400 Invalid or expired code; network errors still 502).

🧪 Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)

🧪 Testing

Local licensing server (current main and the next version) + API bundle pointing to it, direct GET /license/register, login, code traded by hand:

call develop this branch
/license/activate?code=<burnt code> 400 400
/license/activate?code=<api_key from the manual exchange> 400 200, active
/license/activate?code=<garbage> 400 400, nothing stored in RuntimeConfig
restart after activating with the api_key — active from the stored license
  • Normal code flow (manager callback) still activates through the exchange.
  • tsc --noEmit, eslint (pre-commit) and npm run build + lint:check (pre-push)

✅ Checklist

  • I have performed a self-review of my code
  • My changes generate no new warnings

Summary by Sourcery

Bug Fixes:

  • Allow /license/activate to activate with an API key that was already exchanged for the submitted authorization code, while preserving the existing exchange-error response if the value is not accepted.

The licensing success page lets the operator trade the authorization code
for an api_key by hand, which burns the code. /license/activate then
failed with "authorization code expired or already used" for both the code
and the api_key. When the exchange fails, try the value as an api_key and
store it only after the licensing server accepts it.
@sourcery-ai

sourcery-ai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Add fallback activation using the submitted value as an API key after exchange failure, persisting it only once the licensing server accepts it.

  • src/licensing/runtime.ts L393-423, L514-535

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

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've found 5 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/licensing/runtime.ts" line_range="533" />
<code_context>
-  await completeActivation(rc, result.api_key, result.tier, result.customer_id);
+  // The code may already have been traded for an api_key outside the instance,
+  // which burns it; accept that api_key as well.
+  if (await activateWithApiKey(rc, code)) return;
+
+  throw exchangeErr ?? new Error('Invalid or expired code');
</code_context>
<issue_to_address>
**API keys leak through activation URLs**

When an operator submits an already-exchanged API key in the `code` query parameter, `activateWithCode` passes the raw query value to `activateWithApiKey`, which sends the reusable credential in a URL retained in browser history and access logs; anyone who reads those records can reuse the key.

Move API-key activation out of the query string and send the credential in a request body or another channel that does not expose it in URLs.
</issue_to_address>

### Comment 2
<location path="src/licensing/runtime.ts" line_range="406" />
<code_context>
+  try {
+    await activateInstance(rc);
+  } catch (err) {
+    rc.apiKey = '';
+    logger.debug(`Value is not a valid api_key either: ${readErrorMessage(err)}`);
+    return false;
</code_context>
<issue_to_address>
**Failed activations corrupt the active key**

When an active instance receives an invalid key, or overlapping activation requests include one accepted key and one rejected value, `activateWithApiKey` writes candidates to shared `rc.apiKey` and clears it on failure, so an existing key or an accepted request's key is lost; `markActivated` can then hash the wrong key and gated requests fail.

Keep each candidate separate from shared runtime state during activation, and update `rc.apiKey` and the active context only after that candidate is accepted.

Also at `src/licensing/runtime.ts:395`.
</issue_to_address>

### Comment 3
<location path="src/licensing/runtime.ts" line_range="414-417" />
<code_context>
+  rc.registerUrl = '';
+  rc.registerToken = '';
+  try {
+    await saveRuntimeData({ apiKey, tier: rc.tier, customerId: 0 });
+  } catch (err) {
+    logger.warn(`Could not save license: ${readErrorMessage(err)}`);
+  }
+
+  markActivated(rc, apiKey, rc.tier);
</code_context>
<issue_to_address>
**Failed saves still report activation success**

When the database rejects the API-key write, `activateWithApiKey` catches the `saveRuntimeData` error, then calls `markActivated` and returns success; the route reports a successful activation even though the license is lost on restart.

Do not mark the runtime active or report success when saving the API key fails; propagate an activation error instead.
</issue_to_address>

### Comment 4
<location path="src/licensing/runtime.ts" line_range="405" />
<code_context>
+  rc.apiKey = apiKey;
+  try {
+    await activateInstance(rc);
+  } catch (err) {
+    rc.apiKey = '';
+    logger.debug(`Value is not a valid api_key either: ${readErrorMessage(err)}`);
</code_context>
<issue_to_address>
**Licensing outages appear as invalid codes**

When the code exchange reports an expired code and the fallback API-key activation fails with a timeout or server error, `activateWithApiKey` discards the fallback error, so `activateWithCode` throws the earlier exchange error and the route returns 400 instead of a retryable 502.

Preserve and propagate the fallback activation error when it indicates a service failure, rather than returning the earlier exchange error.
</issue_to_address>

### Comment 5
<location path="src/licensing/runtime.ts" line_range="414" />
<code_context>
+  rc.registerUrl = '';
+  rc.registerToken = '';
+  try {
+    await saveRuntimeData({ apiKey, tier: rc.tier, customerId: 0 });
+  } catch (err) {
+    logger.warn(`Could not save license: ${readErrorMessage(err)}`);
</code_context>
<issue_to_address>
**Stored customer ID survives key replacement**

When runtimeConfig has a leftover customer_id row but no API key when this fallback succeeds, `saveRuntimeData` receives `customerId: 0`, but its customer-ID write runs only for positive values, so `loadRuntimeData` pairs the newly accepted key with the previous customer ID.

Clear the stored customer_id when saving a license whose customer ID is unknown.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and if the fallback is wrong, a value accepted as an API key can activate the instance and be saved as its license credential. Reverting the code will not itself clear that saved credential or undo an activation that already occurred.

Blocking findings: src/licensing/runtime.ts:533, src/licensing/runtime.ts:406, src/licensing/runtime.ts:417, src/licensing/runtime.ts:405


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/licensing/runtime.ts Resolved
Comment thread src/licensing/runtime.ts Resolved
Comment thread src/licensing/runtime.ts Resolved
Comment thread src/licensing/runtime.ts Resolved
Comment thread src/licensing/runtime.ts Resolved
@daniloleonecarneiro

Copy link
Copy Markdown
Collaborator Author

Closing without merging. Accepting an already exchanged api_key on the public GET /license/activate would put a reusable credential in URLs and access logs, and races with an in-flight activation on the shared runtime state. A burnt code does not need it: opening the same registration link again and logging in issues a new code that activates the instance, and the licensing success page now tells the operator to send the code to /license/activate instead of exchanging it by hand. An existing key can still be used through AUTHENTICATION_API_KEY.

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.

1 participant