Skip to content

[TT-17585] MinTokenLength: apply the default floor of 3 to the create-time guard#8346

Merged
imogenkraak merged 3 commits into
masterfrom
TT-17585-mintokenlength-create-guard-default-floor
Jun 25, 2026
Merged

[TT-17585] MinTokenLength: apply the default floor of 3 to the create-time guard#8346
imogenkraak merged 3 commits into
masterfrom
TT-17585-mintokenlength-create-guard-default-floor

Conversation

@sedkis

@sedkis sedkis commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

What

Follow-up to TT-17065. The create-time custom-key guard added there only engages when min_token_length is explicitly configured (minLen > 0). The auth-time gate, CheckSessionAndIdentityForValidKey, falls back to a minimum of 3 when min_token_length is unset (issue #1681). The two used different effective floors at default config, leaving a gap:

min_token_length custom ID len create (before) auth net (before)
unset (→ 3 at auth) 1–2 200 403 (AKI) silent-accept ❌
unset ≥3 200 200 fine
set = N < N 400 rejected ✓ (TT-17065)

A 1–2 char custom key ID at default config was accepted at create but unreachable at auth — the same silent-accept trap TT-17065 set out to close, just at the default-config boundary. Reported in TT-17585.

Change

gateway/api.go — in handleAddOrUpdate's POST (create) branch, apply the same min_token_length == 0 → 3 fallback the auth gate uses, so the create guard rejects custom IDs shorter than the effective floor:

minLen := gw.GetConfig().MinTokenLength
if minLen == 0 {
    minLen = 3 // mirror the auth-time floor (issue #1681)
}
if keyName != "" && len(keyName) < minLen {
    return apiError(...), http.StatusBadRequest
}

The Dashboard /api/keys path inherits this automatically — it proxies to the gateway's /tyk/keys and bubbles up the 4xx, so no Dashboard change is needed (TT-17585 was originally filed as a Dashboard gap; it is not).

Tests

  • Added TestKeyHandler_DefaultMinTokenLengthFloorOnCreate: at default/unset min_token_length, custom ID len 2 → 400, len 3 → 200.
  • Existing TestKeyHandler_RejectCustomKeyBelowMinTokenLength (explicit MinTokenLength=32) unchanged and still passes.
  • Full TestKeyHandler* group passes. A repo-wide search confirmed no existing test creates a 1–2 char custom key ID at default config (shortest is "user", 4 chars), so nothing else is affected.

Backwards compatibility

  • Pure tightening at the very bottom of the range: only POST /tyk/keys/<id> creates with a 1–2 char custom ID at default config change behaviour (now 400 instead of 200). Such keys were already unusable — they 403 at auth — so no previously-working key creation is affected.
  • Explicit min_token_length, autogenerated creates (POST /tyk/keys/create), PUT/update, and all existing keys are unchanged.

Verification on a real stack

Reproduced and validated on a matched 5.8.15-rc1 tyk-demo (gateway-ee + dashboard):

  • min_token_length=32: gateway POST /tyk/keys/ee400; dashboard POST /api/keys/ee403 (gateway message bubbled up).
  • default config (before this PR): both surfaces → 200, then 403 at traffic. This PR closes that window.

Refs: TT-17585, TT-17065 (#8154)

🤖 Generated with Claude Code

https://claude.ai/code/session_01KdwVB9D3hGDjeTR58pWZMn

…-time guard

The create-time custom-key guard added in TT-17065 only fired when
min_token_length was explicitly configured (`minLen > 0`), while the
auth-time gate (CheckSessionAndIdentityForValidKey) falls back to a
minimum of 3 when min_token_length is unset (issue #1681). This left a
gap at default config: a 1-2 char custom key ID was accepted at create
(200) but unreachable at auth (403/AKI) — the same silent-accept trap
TT-17065 closed, just at the default-config boundary reported in TT-17585.

Mirror the auth gate's fallback in handleAddOrUpdate so the create guard
uses the same effective floor of 3 when min_token_length is unset. The
Dashboard /api/keys path inherits this automatically: it proxies to the
gateway's /tyk/keys and bubbles up the 4xx (verified on 5.8.15-rc1).

- gateway/api.go: fall back to minLen=3 when MinTokenLength is 0.
- gateway/api_test.go: add TestKeyHandler_DefaultMinTokenLengthFloorOnCreate
  (custom ID len 2 -> 400, len 3 -> 200 at default/unset min_token_length).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KdwVB9D3hGDjeTR58pWZMn
@github-actions

github-actions Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

🎯 Recommended Merge Targets

Based on JIRA ticket TT-17585: [Innersource] Create custom key API doesn't respect default minimum token length

Fix Version: Tyk 5.8.15

Required:

  • release-5.8.15 - Exact version branch for Tyk 5.8.15 - specific patch release
  • release-5.8 - Minor version branch for 5.8.x patches - required for creating Tyk 5.8.15
  • master - Main development branch - ensures fix is in all future releases

Fix Version: Tyk 5.13.1

Required:

  • release-5.13.1 - Exact version branch for Tyk 5.13.1 - specific patch release
  • release-5.13 - Minor version branch for 5.13.x patches - required for creating Tyk 5.13.1
  • master - Main development branch - ensures fix is in all future releases

Fix Version: Tyk 5.14.0

Required:

  • release-5.14.0 - Exact version branch for Tyk 5.14.0 - specific patch release
  • master - Main development branch - ensures fix is in all future releases

Recommended:

  • release-5.14 - Minor version branch for 5.14.x releases

📋 Workflow

  1. Merge this PR to master first

  2. Cherry-pick to release branches by commenting on the merged PR:

    • /release to release-5.8.15
    • /release to release-5.8
    • /release to release-5.13.1
    • /release to release-5.13
    • /release to release-5.14.0
    • /release to release-5.14
  3. Automated backport - The bot will automatically create backport PRs to the specified release branches

@probelabs

probelabs Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

This PR addresses a bug where custom API keys with IDs shorter than 3 characters could be created but would subsequently fail authentication. The fix aligns the validation logic at key creation with the existing authentication logic by enforcing a default minimum token length of 3, even when not explicitly configured.

Files Changed Analysis

The changes are focused and well-contained across three files:

  • gateway/middleware.go: Introduces a new constant defaultMinTokenLength and a helper function effectiveMinTokenLength. This centralizes the logic for determining the minimum token length, removing a hardcoded value from the authentication middleware and making the logic reusable. The existing CheckSessionAndIdentityForValidKey function is refactored to use this new helper.
  • gateway/api.go: The core fix is applied here. The handleAddOrUpdate function, which handles key creation, is updated to use effectiveMinTokenLength. This ensures that the same minimum length validation (defaulting to 3) is applied when a new key with a custom ID is created.
  • gateway/api_test.go: A new test, TestKeyHandler_DefaultMinTokenLengthFloorOnCreate, is added to explicitly verify the fix. It confirms that attempts to create keys with IDs shorter than the default floor of 3 are rejected (400 Bad Request), while keys with IDs of length 3 are accepted.

Architecture & Impact Assessment

  • What this PR accomplishes: It closes a loophole that allowed the creation of unusable API keys. By enforcing the minimum token length at the creation endpoint, it provides immediate, clear feedback to the user instead of allowing a key to be created that would later fail silently during use.

  • Key technical changes introduced: The primary change is the harmonization of validation logic. By refactoring the default minimum length logic into a shared function (effectiveMinTokenLength) and applying it to both the key creation and authentication paths, the PR ensures consistent behavior throughout the key lifecycle.

  • Affected system components: The change directly affects the Gateway's key creation API (POST /tyk/keys/:key_id). Indirectly, it affects any client of this API, such as the Tyk Dashboard, which will now correctly surface validation errors for short key IDs.

Flow Diagram: Before vs. After

sequenceDiagram
    participant Client
    participant Gateway API

    rect rgb(255, 230, 230)
        note over Client, Gateway API: Old Behavior (min_token_length unset)
        Client->>Gateway API: POST /tyk/keys/ab (2-char ID)
        Gateway API-->>Client: 200 OK (Key created)
        Client->>Gateway API: Use key "ab" for auth
        Gateway API-->>Client: 403 Forbidden (Key unusable)
    end

    rect rgb(230, 255, 230)
        note over Client, Gateway API: New Behavior (min_token_length unset)
        Client->>Gateway API: POST /tyk/keys/ab (2-char ID)
        Gateway API-->>Client: 400 Bad Request (Rejected upfront)
    end
Loading

Scope Discovery & Context Expansion

The issue stemmed from a discrepancy between two key functions within the gateway:

  1. Key Creation: gateway/api.go in handleAddOrUpdate previously had no default minimum length check if min_token_length was unset.
  2. Key Authentication: gateway/middleware.go in CheckSessionAndIdentityForValidKey already enforced a default minimum length of 3.

This PR resolves this inconsistency by creating a shared source of truth for the validation logic (effectiveMinTokenLength) and applying it in both places. The impact is confined to the gateway's key management system. No other services or modules are directly affected, as the change is internal to how the gateway validates incoming key creation requests.

Metadata
  • Review Effort: 2 / 5
  • Primary Label: bug

Powered by Visor from Probelabs

Last updated: 2026-06-25T10:43:26.148Z | Triggered by: pr_updated | Commit: f7e312f

💡 TIP: You can chat with Visor using /visor ask <your question>

@probelabs

probelabs Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

✅ Security Check Passed

No security issues found – changes LGTM.

✅ Performance Check Passed

No performance issues found – changes LGTM.

✅ Security Check Passed

No security issues found – changes LGTM.

\n\n \n\n

✅ Performance Check Passed

No performance issues found – changes LGTM.

\n\n

✅ Quality Check Passed

No quality issues found – changes LGTM.


Powered by Visor from Probelabs

Last updated: 2026-06-25T10:43:23.446Z | Triggered by: pr_updated | Commit: f7e312f

💡 TIP: You can chat with Visor using /visor ask <your question>

The default floor of 3 (issue #1681) was duplicated in the auth-time gate
(middleware.go) and the create-time guard (api.go) — the exact divergence
that caused TT-17585. Hoist it into a single defaultMinTokenLength const
plus an effectiveMinTokenLength helper used by both sites, so the
read-config-then-fallback logic can no longer drift between the two.

Pure refactor, no behaviour change; both min-token tests remain green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01KdwVB9D3hGDjeTR58pWZMn
@sentinelone-cnapp-eu1

Copy link
Copy Markdown

SentinelOne CNS Hardcoded Secret Detector
✅ Congratulations, your code is safe

SentinelOne CNS is a cloud-agnostic, agentless CSPM & CWPP solution that continuously detects and prevents vulnerabilities that have the highest probability of being exploited in Azure, AWS, Google Cloud, and Kubernetes.

@github-actions

Copy link
Copy Markdown
Contributor

🚨 Jira Linter Failed

Commit: f7e312f
Failed at: 2026-06-25 10:42:41 UTC

The Jira linter failed to validate your PR. Please check the error details below:

🔍 Click to view error details
failed to get Jira issue: failed to fetch Jira issue TT-17585: Issue does not exist or you do not have permission to see it.: request failed. Please analyze the request body for more details. Status code: 404

Next Steps

  • Ensure your branch name contains a valid Jira ticket ID (e.g., ABC-123)
  • Verify your PR title matches the branch's Jira ticket ID
  • Check that the Jira ticket exists and is accessible

This comment will be automatically deleted once the linter passes.

@imogenkraak
imogenkraak enabled auto-merge (squash) June 25, 2026 11:06
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Passed Quality Gate passed

Issues
0 New issues
0 Accepted issues

Measures
0 Security Hotspots
100.0% Coverage on New Code
0.0% Duplication on New Code

See analysis details on SonarQube Cloud

@imogenkraak
imogenkraak merged commit c2b4264 into master Jun 25, 2026
54 of 56 checks passed
@imogenkraak
imogenkraak deleted the TT-17585-mintokenlength-create-guard-default-floor branch June 25, 2026 11:49
@imogenkraak

Copy link
Copy Markdown
Contributor

/release to release-5.8

@probelabs

probelabs Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

✅ Cherry-pick successful. A PR was created: #8371

@imogenkraak

Copy link
Copy Markdown
Contributor

/release to release-5.8.15

@probelabs

probelabs Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

✅ Cherry-pick successful. A PR was created: #8372

@imogenkraak

Copy link
Copy Markdown
Contributor

/release to release-5.13

@probelabs

probelabs Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

✅ Cherry-pick successful. A PR was created: #8373

@imogenkraak

Copy link
Copy Markdown
Contributor

/release to release-5.13.1

@probelabs

probelabs Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

✅ Cherry-pick successful. A PR was created: #8374

@imogenkraak

Copy link
Copy Markdown
Contributor

/release to release-5.14

@imogenkraak

Copy link
Copy Markdown
Contributor

/release to release-5.14.0

@probelabs

probelabs Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

✅ Cherry-pick successful. A PR was created: #8375

@probelabs

probelabs Bot commented Jun 25, 2026

Copy link
Copy Markdown
Contributor

✅ Cherry-pick successful. A PR was created: #8376

imogenkraak pushed a commit that referenced this pull request Jun 25, 2026
imogenkraak pushed a commit that referenced this pull request Jun 25, 2026
imogenkraak pushed a commit that referenced this pull request Jun 25, 2026
imogenkraak pushed a commit that referenced this pull request Jun 25, 2026
imogenkraak pushed a commit that referenced this pull request Jun 25, 2026
imogenkraak pushed a commit that referenced this pull request Jun 25, 2026
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.

3 participants