|
4 | 4 | package util |
5 | 5 |
|
6 | 6 | import ( |
| 7 | + "strings" |
| 8 | + |
7 | 9 | "github.com/router-for-me/CLIProxyAPI/v6/internal/config" |
8 | 10 | "github.com/router-for-me/CLIProxyAPI/v6/internal/registry" |
9 | 11 | ) |
@@ -141,3 +143,48 @@ func HideAPIKey(apiKey string) string { |
141 | 143 | } |
142 | 144 | return apiKey |
143 | 145 | } |
| 146 | + |
| 147 | +// maskAuthorizationHeader masks the Authorization header value while preserving the auth type prefix. |
| 148 | +// Common formats: "Bearer <token>", "Basic <credentials>", "ApiKey <key>", etc. |
| 149 | +// It preserves the prefix (e.g., "Bearer ") and only masks the token/credential part. |
| 150 | +// |
| 151 | +// Parameters: |
| 152 | +// - value: The Authorization header value |
| 153 | +// |
| 154 | +// Returns: |
| 155 | +// - string: The masked Authorization value with prefix preserved |
| 156 | +func MaskAuthorizationHeader(value string) string { |
| 157 | + parts := strings.SplitN(strings.TrimSpace(value), " ", 2) |
| 158 | + if len(parts) < 2 { |
| 159 | + return HideAPIKey(value) |
| 160 | + } |
| 161 | + return parts[0] + " " + HideAPIKey(parts[1]) |
| 162 | +} |
| 163 | + |
| 164 | +// MaskSensitiveHeaderValue masks sensitive header values while preserving expected formats. |
| 165 | +// |
| 166 | +// Behavior by header key (case-insensitive): |
| 167 | +// - "Authorization": Preserve the auth type prefix (e.g., "Bearer ") and mask only the credential part. |
| 168 | +// - Headers containing "api-key": Mask the entire value using HideAPIKey. |
| 169 | +// - Others: Return the original value unchanged. |
| 170 | +// |
| 171 | +// Parameters: |
| 172 | +// - key: The HTTP header name to inspect (case-insensitive matching). |
| 173 | +// - value: The header value to mask when sensitive. |
| 174 | +// |
| 175 | +// Returns: |
| 176 | +// - string: The masked value according to the header type; unchanged if not sensitive. |
| 177 | +func MaskSensitiveHeaderValue(key, value string) string { |
| 178 | + lowerKey := strings.ToLower(strings.TrimSpace(key)) |
| 179 | + switch { |
| 180 | + case lowerKey == "authorization": |
| 181 | + return MaskAuthorizationHeader(value) |
| 182 | + case strings.Contains(lowerKey, "api-key"), |
| 183 | + strings.Contains(lowerKey, "apikey"), |
| 184 | + strings.Contains(lowerKey, "token"), |
| 185 | + strings.Contains(lowerKey, "secret"): |
| 186 | + return HideAPIKey(value) |
| 187 | + default: |
| 188 | + return value |
| 189 | + } |
| 190 | +} |
0 commit comments