Skip to content

feats:replace GLM-4v authentication headers to support customize api key - #1536

Merged
Calcium-Ion merged 1 commit into
QuantumNous:alphafrom
Yincmewy:alpha
Aug 9, 2025
Merged

feats:replace GLM-4v authentication headers to support customize api key#1536
Calcium-Ion merged 1 commit into
QuantumNous:alphafrom
Yincmewy:alpha

Conversation

@Yincmewy

@Yincmewy Yincmewy commented Aug 8, 2025

Copy link
Copy Markdown
Contributor

According to the official documentation (https://docs.bigmodel.cn/cn/guide/develop/http/introduction), JWT generation is not required, so it has been replaced with a more compatible approach.

Summary by CodeRabbit

  • Refactor

    • Simplified authentication by using the API key directly in the authorization header, removing the previous token generation and caching process.
  • Chores

    • Cleaned up code by removing obsolete token-related logic and dependencies.
  • Chores

    • Streamlined the Docker image build workflow to target Docker Hub exclusively, removing multi-registry support and related permissions.

@coderabbitai

coderabbitai Bot commented Aug 8, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes remove the getZhipuToken function and its associated JWT token generation and caching logic from the codebase. The SetupRequestHeader method now directly sets the "Authorization" header using the API key, eliminating the need for token parsing, JWT creation, and caching mechanisms. Additionally, the GitHub Actions workflow was simplified to push only to Docker Hub, removing steps and permissions related to other registries.

Changes

Cohort / File(s) Change Summary
Adaptor Header Setup
relay/channel/zhipu_4v/adaptor.go
Modified SetupRequestHeader to set the "Authorization" header directly as "Bearer ", removing the call to getZhipuToken.
Token Generation & Caching Removal
relay/channel/zhipu_4v/relay-zhipu_v4.go
Removed the getZhipuToken function, the JWT token generation, token caching logic, and related imports.
GitHub Actions Workflow Simplification
.github/workflows/docker-image-alpha.yml
Simplified workflow to push only to Docker Hub, removed GitHub Container Registry login, permissions, and adjusted metadata and job naming accordingly.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Suggested reviewers

  • Calcium-Ion

Poem

The token cache is gone, oh my!
No JWTs to sign or store nearby.
Now headers are set, so simple and neat,
Just "Bearer" and key—a straightforward treat.
The code is lighter, the logic more clear,
A bunny hops forward, full of cheer! 🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 962c40c and 15cb2f1.

📒 Files selected for processing (2)
  • relay/channel/zhipu_4v/adaptor.go (1 hunks)
  • relay/channel/zhipu_4v/relay-zhipu_v4.go (0 hunks)
💤 Files with no reviewable changes (1)
  • relay/channel/zhipu_4v/relay-zhipu_v4.go
🔇 Additional comments (1)
relay/channel/zhipu_4v/adaptor.go (1)

57-57: Auth header change aligns with BigModel HTTP auth (Bearer API key).

Directly setting Authorization: Bearer <apiKey> is consistent with the provider’s HTTP docs and removes unnecessary JWT complexity. Good simplification.

channel.SetupApiRequestHeader(info, c, req)
token := getZhipuToken(info.ApiKey)
req.Set("Authorization", token)
req.Set("Authorization", "Bearer "+info.ApiKey)

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.

💡 Verification agent

🧩 Analysis chain

Harden header construction: trim, handle pre-prefixed keys, and empty key guard.

Minor robustness improvements:

  • Return an explicit error if info.ApiKey is empty to avoid a guaranteed 401.
  • Trim whitespace and avoid double “Bearer ” when the configured key is already prefixed.

Apply this diff within SetupRequestHeader:

-  req.Set("Authorization", "Bearer "+info.ApiKey)
+  if strings.TrimSpace(info.ApiKey) == "" {
+    return errors.New("missing API key for Zhipu channel")
+  }
+  ak := strings.TrimSpace(info.ApiKey)
+  if strings.HasPrefix(strings.ToLower(ak), "bearer ") {
+    req.Set("Authorization", ak)
+  } else {
+    req.Set("Authorization", "Bearer "+ak)
+  }

And add the import:

import "strings"

Verification (ensure no stale JWT usage remains and check for already-prefixed keys):


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find any references to the removed JWT helper to prevent build-time surprises.
rg -n --hidden --glob '!*dist*' --glob '!*build*' 'getZhipuToken|jwt' || echo "No references to getZhipuToken/jwt found."

# Spot other Authorization constructions for consistency.
rg -n 'Authorization"\s*,\s*"Bearer\s*\+.*ApiKey' -A2 -B2 || true

# Find places where API keys may already include 'Bearer ' to gauge risk.
rg -n 'ApiKey.*Bearer' -A2 -B2 || true

Length of output: 2387


Let's locate and inspect SetupRequestHeader in the zhipu_4v adapter to verify if the trimming/prefix patch has already been applied:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the zhipu_4v adaptor file
echo "Searching for zhipu_4v/adaptor.go..."
find relay/channel -type f | grep 'zhipu_4v/adaptor.go' || true

# Show the SetupRequestHeader implementation around line 57
echo "Extracting SetupRequestHeader definition from zhipu_4v/adaptor.go..."
rg -n -A5 -B5 'func SetupRequestHeader' relay/channel/zhipu_4v/adaptor.go || true

Length of output: 422


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Search for occurrences of info.ApiKey to locate the header setup
echo "Searching for info.ApiKey usages..."
rg -n 'info\.ApiKey' -A5 -B5

Length of output: 28759


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Display the package declaration and imports for relay/channel/zhipu_4v/adaptor.go
sed -n '1,60p' relay/channel/zhipu_4v/adaptor.go

Length of output: 1700


Improve Zhipu 4v Authorization header handling

Please harden SetupRequestHeader in relay/channel/zhipu_4v/adaptor.go to guard against empty or already-prefixed API keys:

• Return an explicit error when info.ApiKey is blank.
• Trim surrounding whitespace.
• Detect and avoid double-“Bearer ” prefixes.

Apply this patch:

diff --git a/relay/channel/zhipu_4v/adaptor.go b/relay/channel/zhipu_4v/adaptor.go
index abc1234..def5678 100644
--- a/relay/channel/zhipu_4v/adaptor.go
+++ b/relay/channel/zhipu_4v/adaptor.go
@@ -1,7 +1,8 @@
 import (
     "errors"
+    "strings"
     "fmt"
     "io"
     "net/http"
@@ -55,7 +56,16 @@ func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) error {
     channel.SetupApiRequestHeader(info, c, req)
-    req.Set("Authorization", "Bearer "+info.ApiKey)
+    // Guard empty key
+    if strings.TrimSpace(info.ApiKey) == "" {
+        return errors.New("missing API key for Zhipu channel")
+    }
+    // Trim and handle existing Bearer prefix
+    ak := strings.TrimSpace(info.ApiKey)
+    if strings.HasPrefix(strings.ToLower(ak), "bearer ") {
+        req.Set("Authorization", ak)
+    } else {
+        req.Set("Authorization", "Bearer "+ak)
+    }
     return nil
 }

This ensures consistent behavior and clearer errors when the key is invalid.

🤖 Prompt for AI Agents
In relay/channel/zhipu_4v/adaptor.go at line 57, improve the SetupRequestHeader
function by first checking if info.ApiKey is empty or only whitespace and return
an explicit error if so. Then trim any surrounding whitespace from info.ApiKey.
Before setting the Authorization header, detect if the key already starts with
"Bearer " to avoid double prefixing. If it does not, prepend "Bearer " to the
trimmed key. This ensures the header is set consistently and errors are clear
when the API key is invalid.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
.github/workflows/docker-image-alpha.yml (1)

43-50: Ensure reliable multi-arch builds and faster CI: add QEMU and Buildx cache.

  • Without QEMU, cross-building arm64 on amd64 runners can fail or be slow.
  • GHA cache drastically speeds up rebuilds.

Add QEMU setup (insert after “Set up Docker Buildx” step):

- name: Set up QEMU
  uses: docker/setup-qemu-action@v3

Augment the build step with cache:

       - name: Build and push Docker image
         uses: docker/build-push-action@v5
         with:
           context: .
           platforms: linux/amd64,linux/arm64
           push: true
           tags: ${{ steps.meta.outputs.tags }}
           labels: ${{ steps.meta.outputs.labels }}
+          cache-from: type=gha
+          cache-to: type=gha,mode=max
🧹 Nitpick comments (2)
.github/workflows/docker-image-alpha.yml (2)

38-38: Avoid hard-coding the Docker Hub namespace; parameterize the image name.

This makes the workflow portable across forks/environments and removes a hard dependency on a specific account.

-          images: calciumion/new-api
+          images: docker.io/${{ secrets.DOCKERHUB_USERNAME }}/new-api

If you prefer non-secret config, consider a repo variable instead:

# Settings → Variables → Actions
# vars.DOCKERHUB_NAMESPACE="calciumion"
with:
  images: docker.io/${{ vars.DOCKERHUB_NAMESPACE }}/new-api

43-50: Optional: add SBOM and provenance attestations for supply-chain integrity.

If you want traceability, enable these in the build step.

       - name: Build and push Docker image
         uses: docker/build-push-action@v5
         with:
           context: .
           platforms: linux/amd64,linux/arm64
           push: true
           tags: ${{ steps.meta.outputs.tags }}
           labels: ${{ steps.meta.outputs.labels }}
+          sbom: true
+          provenance: true
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 15cb2f1 and b38d15d.

📒 Files selected for processing (1)
  • .github/workflows/docker-image-alpha.yml (2 hunks)
🔇 Additional comments (2)
.github/workflows/docker-image-alpha.yml (2)

14-15: Scope reduction to Docker Hub-only looks good.

Job rename and focus on Docker Hub are consistent and straightforward.


34-41: Metadata step is fine for alpha tagging.

Tags and labels from docker/metadata-action are configured appropriately for alpha and date+sha tags.

Comment on lines 14 to 16
push_to_dockerhub:
name: Push Docker image to Docker Hub
runs-on: ubuntu-latest

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.

🛠️ Refactor suggestion

Pin least-privilege GITHUB_TOKEN permissions at the job level.

Now that GHCR push is removed, explicitly constrain token permissions to avoid unexpected future defaults.

 jobs:
   push_to_dockerhub:
     name: Push Docker image to Docker Hub
+    permissions:
+      contents: read
     runs-on: ubuntu-latest
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
push_to_dockerhub:
name: Push Docker image to Docker Hub
runs-on: ubuntu-latest
push_to_dockerhub:
name: Push Docker image to Docker Hub
permissions:
contents: read
runs-on: ubuntu-latest
🤖 Prompt for AI Agents
In .github/workflows/docker-image-alpha.yml around lines 14 to 16, the job
push_to_dockerhub lacks explicit GITHUB_TOKEN permission settings. To enforce
least-privilege access, add a permissions block at the job level specifying only
the necessary permissions for this job, such as write access to packages if
pushing images, and remove any broader default permissions. This prevents
unexpected permission escalations in the future.

@Calcium-Ion
Calcium-Ion merged commit df72ac1 into QuantumNous:alpha Aug 9, 2025
4 checks passed
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
feats:replace GLM-4v authentication headers to support customize 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.

2 participants