Upload 839 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- cmd/fetch_antigravity_models/main.go +305 -0
- cmd/fetch_codex_models/main.go +336 -0
- cmd/fetch_codex_models/main_test.go +48 -0
- cmd/server/main.go +826 -0
- cmd/server/main_test.go +137 -0
- cmd/validate_codex_models/main.go +32 -0
- go.mod +122 -0
- go.sum +291 -0
- internal/access/config_access/provider.go +141 -0
- internal/access/reconcile.go +127 -0
- internal/api/buffered_conn.go +32 -0
- internal/api/handlers/management/api_key_usage.go +117 -0
- internal/api/handlers/management/api_key_usage_test.go +142 -0
- internal/api/handlers/management/api_tools.go +640 -0
- internal/api/handlers/management/api_tools_test.go +224 -0
- internal/api/handlers/management/auth_files.go +2810 -0
- internal/api/handlers/management/auth_files_batch_test.go +194 -0
- internal/api/handlers/management/auth_files_delete_test.go +172 -0
- internal/api/handlers/management/auth_files_download_test.go +60 -0
- internal/api/handlers/management/auth_files_download_windows_test.go +50 -0
- internal/api/handlers/management/auth_files_filter_test.go +260 -0
- internal/api/handlers/management/auth_files_patch_fields_test.go +278 -0
- internal/api/handlers/management/auth_files_plugin_oauth_test.go +259 -0
- internal/api/handlers/management/auth_files_project_id_test.go +155 -0
- internal/api/handlers/management/auth_files_recent_requests_test.go +93 -0
- internal/api/handlers/management/auth_files_upload_test.go +69 -0
- internal/api/handlers/management/config_apikey_disable.go +94 -0
- internal/api/handlers/management/config_apikey_disable_test.go +84 -0
- internal/api/handlers/management/config_auth_index.go +308 -0
- internal/api/handlers/management/config_basic.go +328 -0
- internal/api/handlers/management/config_lists.go +1561 -0
- internal/api/handlers/management/config_lists_delete_keys_test.go +194 -0
- internal/api/handlers/management/config_openai_compat_test.go +55 -0
- internal/api/handlers/management/config_xai_key_test.go +52 -0
- internal/api/handlers/management/handler.go +459 -0
- internal/api/handlers/management/handler_test.go +88 -0
- internal/api/handlers/management/logs.go +1310 -0
- internal/api/handlers/management/logs_test.go +736 -0
- internal/api/handlers/management/model_definitions.go +33 -0
- internal/api/handlers/management/oauth_callback.go +148 -0
- internal/api/handlers/management/oauth_callback_test.go +148 -0
- internal/api/handlers/management/oauth_codex_concurrency_test.go +111 -0
- internal/api/handlers/management/oauth_sessions.go +463 -0
- internal/api/handlers/management/oauth_sessions_test.go +344 -0
- internal/api/handlers/management/plugin_store.go +937 -0
- internal/api/handlers/management/plugin_store_test.go +1436 -0
- internal/api/handlers/management/plugins.go +713 -0
- internal/api/handlers/management/plugins_test.go +852 -0
- internal/api/handlers/management/quota.go +69 -0
- internal/api/handlers/management/quota_test.go +134 -0
cmd/fetch_antigravity_models/main.go
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Command fetch_antigravity_models connects to the Antigravity API using the
|
| 2 |
+
// stored auth credentials and saves the dynamically fetched model list to a
|
| 3 |
+
// JSON file for inspection or offline use.
|
| 4 |
+
//
|
| 5 |
+
// Usage:
|
| 6 |
+
//
|
| 7 |
+
// go run ./cmd/fetch_antigravity_models [flags]
|
| 8 |
+
//
|
| 9 |
+
// Flags:
|
| 10 |
+
//
|
| 11 |
+
// --auths-dir <path> Directory containing auth JSON files (default: config auth-dir)
|
| 12 |
+
// --config <path> Config file path (default: "config.yaml")
|
| 13 |
+
// --output <path> Output JSON file path (default: "antigravity_models.json")
|
| 14 |
+
// --pretty Pretty-print the output JSON (default: true)
|
| 15 |
+
package main
|
| 16 |
+
|
| 17 |
+
import (
|
| 18 |
+
"context"
|
| 19 |
+
"encoding/json"
|
| 20 |
+
"flag"
|
| 21 |
+
"fmt"
|
| 22 |
+
"io"
|
| 23 |
+
"net/http"
|
| 24 |
+
"os"
|
| 25 |
+
"path/filepath"
|
| 26 |
+
"strings"
|
| 27 |
+
"time"
|
| 28 |
+
|
| 29 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 30 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
|
| 31 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/misc"
|
| 32 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
| 33 |
+
sdkauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
| 34 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 35 |
+
"github.com/router-for-me/CLIProxyAPI/v7/sdk/proxyutil"
|
| 36 |
+
log "github.com/sirupsen/logrus"
|
| 37 |
+
"github.com/tidwall/gjson"
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
const (
|
| 41 |
+
antigravityBaseURLDaily = "https://daily-cloudcode-pa.googleapis.com"
|
| 42 |
+
antigravitySandboxBaseURLDaily = "https://daily-cloudcode-pa.sandbox.googleapis.com"
|
| 43 |
+
antigravityBaseURLProd = "https://cloudcode-pa.googleapis.com"
|
| 44 |
+
antigravityModelsPath = "/v1internal:fetchAvailableModels"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
func init() {
|
| 48 |
+
logging.SetupBaseLogger()
|
| 49 |
+
log.SetLevel(log.InfoLevel)
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
// modelOutput wraps the fetched model list with fetch metadata.
|
| 53 |
+
type modelOutput struct {
|
| 54 |
+
Models []modelEntry `json:"models"`
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
// modelEntry contains only the fields we want to keep for static model definitions.
|
| 58 |
+
type modelEntry struct {
|
| 59 |
+
ID string `json:"id"`
|
| 60 |
+
Object string `json:"object"`
|
| 61 |
+
OwnedBy string `json:"owned_by"`
|
| 62 |
+
Type string `json:"type"`
|
| 63 |
+
DisplayName string `json:"display_name"`
|
| 64 |
+
Name string `json:"name"`
|
| 65 |
+
Description string `json:"description"`
|
| 66 |
+
ContextLength int `json:"context_length,omitempty"`
|
| 67 |
+
MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
func main() {
|
| 71 |
+
var authsDir string
|
| 72 |
+
var configPath string
|
| 73 |
+
var outputPath string
|
| 74 |
+
var pretty bool
|
| 75 |
+
|
| 76 |
+
flag.StringVar(&authsDir, "auths-dir", "", "Directory containing auth JSON files (overrides config auth-dir)")
|
| 77 |
+
flag.StringVar(&configPath, "config", "", "Configure File Path")
|
| 78 |
+
flag.StringVar(&outputPath, "output", "antigravity_models.json", "Output JSON file path")
|
| 79 |
+
flag.BoolVar(&pretty, "pretty", true, "Pretty-print the output JSON")
|
| 80 |
+
flag.Parse()
|
| 81 |
+
authsDirOverridden := false
|
| 82 |
+
flag.Visit(func(f *flag.Flag) {
|
| 83 |
+
if f.Name == "auths-dir" {
|
| 84 |
+
authsDirOverridden = true
|
| 85 |
+
}
|
| 86 |
+
})
|
| 87 |
+
|
| 88 |
+
wd, err := os.Getwd()
|
| 89 |
+
if err != nil {
|
| 90 |
+
fmt.Fprintf(os.Stderr, "error: cannot get working directory: %v\n", err)
|
| 91 |
+
os.Exit(1)
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
if strings.TrimSpace(configPath) == "" {
|
| 95 |
+
configPath = filepath.Join(wd, "config.yaml")
|
| 96 |
+
}
|
| 97 |
+
cfg, err := config.LoadConfigOptional(configPath, false)
|
| 98 |
+
if err != nil {
|
| 99 |
+
fmt.Fprintf(os.Stderr, "error: failed to load config file %s: %v\n", configPath, err)
|
| 100 |
+
os.Exit(1)
|
| 101 |
+
}
|
| 102 |
+
if cfg == nil {
|
| 103 |
+
cfg = &config.Config{}
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
if !authsDirOverridden {
|
| 107 |
+
authsDir = cfg.AuthDir
|
| 108 |
+
} else if strings.TrimSpace(authsDir) != "" && !strings.HasPrefix(strings.TrimSpace(authsDir), "~") && !filepath.IsAbs(authsDir) {
|
| 109 |
+
authsDir = filepath.Join(wd, authsDir)
|
| 110 |
+
}
|
| 111 |
+
if authsDir, err = util.ResolveAuthDir(authsDir); err != nil {
|
| 112 |
+
fmt.Fprintf(os.Stderr, "error: failed to resolve auth directory: %v\n", err)
|
| 113 |
+
os.Exit(1)
|
| 114 |
+
}
|
| 115 |
+
if !filepath.IsAbs(outputPath) {
|
| 116 |
+
outputPath = filepath.Join(wd, outputPath)
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
fmt.Printf("Scanning auth files in: %s\n", authsDir)
|
| 120 |
+
|
| 121 |
+
// Load all auth records from the directory.
|
| 122 |
+
fileStore := sdkauth.NewFileTokenStore()
|
| 123 |
+
fileStore.SetBaseDir(authsDir)
|
| 124 |
+
|
| 125 |
+
ctx := context.Background()
|
| 126 |
+
auths, err := fileStore.List(ctx)
|
| 127 |
+
if err != nil {
|
| 128 |
+
fmt.Fprintf(os.Stderr, "error: failed to list auth files: %v\n", err)
|
| 129 |
+
os.Exit(1)
|
| 130 |
+
}
|
| 131 |
+
if len(auths) == 0 {
|
| 132 |
+
fmt.Fprintf(os.Stderr, "error: no auth files found in %s\n", authsDir)
|
| 133 |
+
os.Exit(1)
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
// Find the first enabled antigravity auth.
|
| 137 |
+
var chosen *coreauth.Auth
|
| 138 |
+
for _, a := range auths {
|
| 139 |
+
if a == nil || a.Disabled {
|
| 140 |
+
continue
|
| 141 |
+
}
|
| 142 |
+
if strings.EqualFold(strings.TrimSpace(a.Provider), "antigravity") {
|
| 143 |
+
chosen = a
|
| 144 |
+
break
|
| 145 |
+
}
|
| 146 |
+
}
|
| 147 |
+
if chosen == nil {
|
| 148 |
+
fmt.Fprintf(os.Stderr, "error: no enabled antigravity auth found in %s\n", authsDir)
|
| 149 |
+
os.Exit(1)
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
fmt.Printf("Using auth: id=%s label=%s\n", chosen.ID, chosen.Label)
|
| 153 |
+
|
| 154 |
+
// Fetch models from the upstream Antigravity API.
|
| 155 |
+
fmt.Println("Fetching Antigravity model list from upstream...")
|
| 156 |
+
|
| 157 |
+
fetchCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
| 158 |
+
defer cancel()
|
| 159 |
+
|
| 160 |
+
models := fetchModels(fetchCtx, chosen)
|
| 161 |
+
if len(models) == 0 {
|
| 162 |
+
fmt.Fprintln(os.Stderr, "warning: no models returned (API may be unavailable or token expired)")
|
| 163 |
+
} else {
|
| 164 |
+
fmt.Printf("Fetched %d models.\n", len(models))
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
// Build the output payload.
|
| 168 |
+
out := modelOutput{
|
| 169 |
+
Models: models,
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
// Marshal to JSON.
|
| 173 |
+
var raw []byte
|
| 174 |
+
if pretty {
|
| 175 |
+
raw, err = json.MarshalIndent(out, "", " ")
|
| 176 |
+
} else {
|
| 177 |
+
raw, err = json.Marshal(out)
|
| 178 |
+
}
|
| 179 |
+
if err != nil {
|
| 180 |
+
fmt.Fprintf(os.Stderr, "error: failed to marshal JSON: %v\n", err)
|
| 181 |
+
os.Exit(1)
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
if err = os.WriteFile(outputPath, raw, 0o644); err != nil {
|
| 185 |
+
fmt.Fprintf(os.Stderr, "error: failed to write output file %s: %v\n", outputPath, err)
|
| 186 |
+
os.Exit(1)
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
fmt.Printf("Model list saved to: %s\n", outputPath)
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
func fetchModels(ctx context.Context, auth *coreauth.Auth) []modelEntry {
|
| 193 |
+
accessToken := metaStringValue(auth.Metadata, "access_token")
|
| 194 |
+
if accessToken == "" {
|
| 195 |
+
fmt.Fprintln(os.Stderr, "error: no access token found in auth")
|
| 196 |
+
return nil
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
baseURLs := []string{antigravityBaseURLProd, antigravityBaseURLDaily, antigravitySandboxBaseURLDaily}
|
| 200 |
+
|
| 201 |
+
for _, baseURL := range baseURLs {
|
| 202 |
+
modelsURL := baseURL + antigravityModelsPath
|
| 203 |
+
|
| 204 |
+
var payload []byte
|
| 205 |
+
if auth != nil && auth.Metadata != nil {
|
| 206 |
+
if pid, ok := auth.Metadata["project_id"].(string); ok && strings.TrimSpace(pid) != "" {
|
| 207 |
+
payload = []byte(fmt.Sprintf(`{"project": "%s"}`, strings.TrimSpace(pid)))
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
if len(payload) == 0 {
|
| 211 |
+
payload = []byte(`{}`)
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
httpReq, errReq := http.NewRequestWithContext(ctx, http.MethodPost, modelsURL, strings.NewReader(string(payload)))
|
| 215 |
+
if errReq != nil {
|
| 216 |
+
continue
|
| 217 |
+
}
|
| 218 |
+
httpReq.Close = true
|
| 219 |
+
httpReq.Header.Set("Content-Type", "application/json")
|
| 220 |
+
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
|
| 221 |
+
httpReq.Header.Set("User-Agent", misc.AntigravityUserAgent())
|
| 222 |
+
|
| 223 |
+
httpClient := &http.Client{Timeout: 30 * time.Second}
|
| 224 |
+
if transport, _, errProxy := proxyutil.BuildHTTPTransport(auth.ProxyURL); errProxy == nil && transport != nil {
|
| 225 |
+
httpClient.Transport = transport
|
| 226 |
+
}
|
| 227 |
+
httpResp, errDo := httpClient.Do(httpReq)
|
| 228 |
+
if errDo != nil {
|
| 229 |
+
continue
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
bodyBytes, errRead := io.ReadAll(httpResp.Body)
|
| 233 |
+
httpResp.Body.Close()
|
| 234 |
+
if errRead != nil {
|
| 235 |
+
continue
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
if httpResp.StatusCode < http.StatusOK || httpResp.StatusCode >= http.StatusMultipleChoices {
|
| 239 |
+
continue
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
result := gjson.GetBytes(bodyBytes, "models")
|
| 243 |
+
if !result.Exists() {
|
| 244 |
+
continue
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
var models []modelEntry
|
| 248 |
+
|
| 249 |
+
for originalName, modelData := range result.Map() {
|
| 250 |
+
modelID := strings.TrimSpace(originalName)
|
| 251 |
+
if modelID == "" {
|
| 252 |
+
continue
|
| 253 |
+
}
|
| 254 |
+
// Skip internal/experimental models
|
| 255 |
+
switch modelID {
|
| 256 |
+
case "chat_20706", "chat_23310", "tab_flash_lite_preview", "tab_jump_flash_lite_preview", "gemini-2.5-flash-thinking", "gemini-2.5-pro":
|
| 257 |
+
continue
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
displayName := modelData.Get("displayName").String()
|
| 261 |
+
if displayName == "" {
|
| 262 |
+
displayName = modelID
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
entry := modelEntry{
|
| 266 |
+
ID: modelID,
|
| 267 |
+
Object: "model",
|
| 268 |
+
OwnedBy: "antigravity",
|
| 269 |
+
Type: "antigravity",
|
| 270 |
+
DisplayName: displayName,
|
| 271 |
+
Name: modelID,
|
| 272 |
+
Description: displayName,
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
if maxTok := modelData.Get("maxTokens").Int(); maxTok > 0 {
|
| 276 |
+
entry.ContextLength = int(maxTok)
|
| 277 |
+
}
|
| 278 |
+
if maxOut := modelData.Get("maxOutputTokens").Int(); maxOut > 0 {
|
| 279 |
+
entry.MaxCompletionTokens = int(maxOut)
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
models = append(models, entry)
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
return models
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
return nil
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
func metaStringValue(m map[string]interface{}, key string) string {
|
| 292 |
+
if m == nil {
|
| 293 |
+
return ""
|
| 294 |
+
}
|
| 295 |
+
v, ok := m[key]
|
| 296 |
+
if !ok {
|
| 297 |
+
return ""
|
| 298 |
+
}
|
| 299 |
+
switch val := v.(type) {
|
| 300 |
+
case string:
|
| 301 |
+
return val
|
| 302 |
+
default:
|
| 303 |
+
return ""
|
| 304 |
+
}
|
| 305 |
+
}
|
cmd/fetch_codex_models/main.go
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Command fetch_codex_models connects to the Codex API using stored auth
|
| 2 |
+
// credentials and saves the dynamically fetched Codex client model catalog to a
|
| 3 |
+
// JSON file for inspection or offline use.
|
| 4 |
+
//
|
| 5 |
+
// Usage:
|
| 6 |
+
//
|
| 7 |
+
// go run ./cmd/fetch_codex_models [flags]
|
| 8 |
+
//
|
| 9 |
+
// Flags:
|
| 10 |
+
//
|
| 11 |
+
// --auths-dir <path> Directory containing auth JSON files (default: config auth-dir)
|
| 12 |
+
// --config <path> Config file path (default: "config.yaml")
|
| 13 |
+
// --output <path> Output JSON file path (default: "codex_client_models.json")
|
| 14 |
+
// --client-version <ver> Codex client_version query value (default: "0.144.1")
|
| 15 |
+
// --pretty Pretty-print the output JSON (default: true)
|
| 16 |
+
package main
|
| 17 |
+
|
| 18 |
+
import (
|
| 19 |
+
"bytes"
|
| 20 |
+
"context"
|
| 21 |
+
"encoding/json"
|
| 22 |
+
"flag"
|
| 23 |
+
"fmt"
|
| 24 |
+
"io"
|
| 25 |
+
"net/http"
|
| 26 |
+
"net/url"
|
| 27 |
+
"os"
|
| 28 |
+
"path/filepath"
|
| 29 |
+
"strings"
|
| 30 |
+
"time"
|
| 31 |
+
|
| 32 |
+
codexauth "github.com/router-for-me/CLIProxyAPI/v7/internal/auth/codex"
|
| 33 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 34 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
|
| 35 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
| 36 |
+
sdkauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
| 37 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 38 |
+
"github.com/router-for-me/CLIProxyAPI/v7/sdk/proxyutil"
|
| 39 |
+
log "github.com/sirupsen/logrus"
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
const (
|
| 43 |
+
codexModelsBaseURL = "https://chatgpt.com/backend-api/codex"
|
| 44 |
+
codexModelsPath = "/models"
|
| 45 |
+
defaultClientVersion = "0.144.1"
|
| 46 |
+
defaultCodexUserAgent = "codex_cli_rs/0.144.1 (Mac OS 26.3.1; arm64) iTerm.app/3.6.9"
|
| 47 |
+
defaultCodexOriginator = "codex_cli_rs"
|
| 48 |
+
accessTokenRefreshLeeway = 30 * time.Second
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
func init() {
|
| 52 |
+
logging.SetupBaseLogger()
|
| 53 |
+
log.SetLevel(log.InfoLevel)
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
func main() {
|
| 57 |
+
var authsDir string
|
| 58 |
+
var configPath string
|
| 59 |
+
var outputPath string
|
| 60 |
+
var clientVersion string
|
| 61 |
+
var pretty bool
|
| 62 |
+
|
| 63 |
+
flag.StringVar(&authsDir, "auths-dir", "", "Directory containing auth JSON files (overrides config auth-dir)")
|
| 64 |
+
flag.StringVar(&configPath, "config", "", "Configure File Path")
|
| 65 |
+
flag.StringVar(&outputPath, "output", "codex_client_models.json", "Output JSON file path")
|
| 66 |
+
flag.StringVar(&clientVersion, "client-version", defaultClientVersion, "Codex client_version query value")
|
| 67 |
+
flag.BoolVar(&pretty, "pretty", true, "Pretty-print the output JSON")
|
| 68 |
+
flag.Parse()
|
| 69 |
+
authsDirOverridden := false
|
| 70 |
+
flag.Visit(func(f *flag.Flag) {
|
| 71 |
+
if f.Name == "auths-dir" {
|
| 72 |
+
authsDirOverridden = true
|
| 73 |
+
}
|
| 74 |
+
})
|
| 75 |
+
|
| 76 |
+
wd, err := os.Getwd()
|
| 77 |
+
if err != nil {
|
| 78 |
+
fmt.Fprintf(os.Stderr, "error: cannot get working directory: %v\n", err)
|
| 79 |
+
os.Exit(1)
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
if strings.TrimSpace(configPath) == "" {
|
| 83 |
+
configPath = filepath.Join(wd, "config.yaml")
|
| 84 |
+
}
|
| 85 |
+
cfg, err := config.LoadConfigOptional(configPath, false)
|
| 86 |
+
if err != nil {
|
| 87 |
+
fmt.Fprintf(os.Stderr, "error: failed to load config file %s: %v\n", configPath, err)
|
| 88 |
+
os.Exit(1)
|
| 89 |
+
}
|
| 90 |
+
if cfg == nil {
|
| 91 |
+
cfg = &config.Config{}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
if !authsDirOverridden {
|
| 95 |
+
authsDir = cfg.AuthDir
|
| 96 |
+
} else if strings.TrimSpace(authsDir) != "" && !strings.HasPrefix(strings.TrimSpace(authsDir), "~") && !filepath.IsAbs(authsDir) {
|
| 97 |
+
authsDir = filepath.Join(wd, authsDir)
|
| 98 |
+
}
|
| 99 |
+
if authsDir, err = util.ResolveAuthDir(authsDir); err != nil {
|
| 100 |
+
fmt.Fprintf(os.Stderr, "error: failed to resolve auth directory: %v\n", err)
|
| 101 |
+
os.Exit(1)
|
| 102 |
+
}
|
| 103 |
+
if !filepath.IsAbs(outputPath) {
|
| 104 |
+
outputPath = filepath.Join(wd, outputPath)
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
fmt.Printf("Scanning auth files in: %s\n", authsDir)
|
| 108 |
+
|
| 109 |
+
fileStore := sdkauth.NewFileTokenStore()
|
| 110 |
+
fileStore.SetBaseDir(authsDir)
|
| 111 |
+
|
| 112 |
+
ctx := context.Background()
|
| 113 |
+
auths, err := fileStore.List(ctx)
|
| 114 |
+
if err != nil {
|
| 115 |
+
fmt.Fprintf(os.Stderr, "error: failed to list auth files: %v\n", err)
|
| 116 |
+
os.Exit(1)
|
| 117 |
+
}
|
| 118 |
+
if len(auths) == 0 {
|
| 119 |
+
fmt.Fprintf(os.Stderr, "error: no auth files found in %s\n", authsDir)
|
| 120 |
+
os.Exit(1)
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
chosen := findCodexAuth(auths)
|
| 124 |
+
if chosen == nil {
|
| 125 |
+
fmt.Fprintf(os.Stderr, "error: no enabled codex auth found in %s\n", authsDir)
|
| 126 |
+
os.Exit(1)
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
fmt.Printf("Using auth: id=%s label=%s\n", chosen.ID, chosen.Label)
|
| 130 |
+
|
| 131 |
+
accessToken, refreshed, err := ensureAccessToken(ctx, fileStore, chosen)
|
| 132 |
+
if err != nil {
|
| 133 |
+
fmt.Fprintf(os.Stderr, "error: failed to prepare codex access token: %v\n", err)
|
| 134 |
+
os.Exit(1)
|
| 135 |
+
}
|
| 136 |
+
if refreshed {
|
| 137 |
+
fmt.Println("Refreshed Codex access token.")
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
fmt.Println("Fetching Codex model list from upstream...")
|
| 141 |
+
|
| 142 |
+
raw, count, err := fetchModels(ctx, chosen, accessToken, clientVersion)
|
| 143 |
+
if err != nil {
|
| 144 |
+
fmt.Fprintf(os.Stderr, "error: failed to fetch codex models: %v\n", err)
|
| 145 |
+
os.Exit(1)
|
| 146 |
+
}
|
| 147 |
+
fmt.Printf("Fetched %d models.\n", count)
|
| 148 |
+
|
| 149 |
+
if pretty {
|
| 150 |
+
raw, err = prettyJSON(raw)
|
| 151 |
+
if err != nil {
|
| 152 |
+
fmt.Fprintf(os.Stderr, "error: failed to format JSON: %v\n", err)
|
| 153 |
+
os.Exit(1)
|
| 154 |
+
}
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
if err = os.WriteFile(outputPath, raw, 0o644); err != nil {
|
| 158 |
+
fmt.Fprintf(os.Stderr, "error: failed to write output file %s: %v\n", outputPath, err)
|
| 159 |
+
os.Exit(1)
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
fmt.Printf("Model list saved to: %s\n", outputPath)
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
func findCodexAuth(auths []*coreauth.Auth) *coreauth.Auth {
|
| 166 |
+
for _, auth := range auths {
|
| 167 |
+
if auth == nil || auth.Disabled {
|
| 168 |
+
continue
|
| 169 |
+
}
|
| 170 |
+
if !strings.EqualFold(strings.TrimSpace(auth.Provider), "codex") {
|
| 171 |
+
continue
|
| 172 |
+
}
|
| 173 |
+
if metaStringValue(auth.Metadata, "access_token") == "" && metaStringValue(auth.Metadata, "refresh_token") == "" {
|
| 174 |
+
continue
|
| 175 |
+
}
|
| 176 |
+
return auth
|
| 177 |
+
}
|
| 178 |
+
return nil
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
func ensureAccessToken(ctx context.Context, store *sdkauth.FileTokenStore, auth *coreauth.Auth) (string, bool, error) {
|
| 182 |
+
accessToken := metaStringValue(auth.Metadata, "access_token")
|
| 183 |
+
if accessToken != "" {
|
| 184 |
+
if expiresAt, ok := auth.ExpirationTime(); !ok || time.Now().Add(accessTokenRefreshLeeway).Before(expiresAt) {
|
| 185 |
+
return accessToken, false, nil
|
| 186 |
+
}
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
refreshToken := metaStringValue(auth.Metadata, "refresh_token")
|
| 190 |
+
if refreshToken == "" {
|
| 191 |
+
if accessToken != "" {
|
| 192 |
+
return accessToken, false, nil
|
| 193 |
+
}
|
| 194 |
+
return "", false, fmt.Errorf("missing access_token and refresh_token")
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
svc := codexauth.NewCodexAuthWithProxyURL(nil, auth.ProxyURL)
|
| 198 |
+
tokenData, errRefresh := svc.RefreshTokensWithRetry(ctx, refreshToken, 3)
|
| 199 |
+
if errRefresh != nil {
|
| 200 |
+
return "", false, errRefresh
|
| 201 |
+
}
|
| 202 |
+
if strings.TrimSpace(tokenData.AccessToken) == "" {
|
| 203 |
+
return "", false, fmt.Errorf("refresh response did not include access_token")
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
if auth.Metadata == nil {
|
| 207 |
+
auth.Metadata = make(map[string]any)
|
| 208 |
+
}
|
| 209 |
+
auth.Metadata["id_token"] = tokenData.IDToken
|
| 210 |
+
auth.Metadata["access_token"] = tokenData.AccessToken
|
| 211 |
+
if tokenData.RefreshToken != "" {
|
| 212 |
+
auth.Metadata["refresh_token"] = tokenData.RefreshToken
|
| 213 |
+
}
|
| 214 |
+
if tokenData.AccountID != "" {
|
| 215 |
+
auth.Metadata["account_id"] = tokenData.AccountID
|
| 216 |
+
}
|
| 217 |
+
if tokenData.Email != "" {
|
| 218 |
+
auth.Metadata["email"] = tokenData.Email
|
| 219 |
+
}
|
| 220 |
+
auth.Metadata["expired"] = tokenData.Expire
|
| 221 |
+
auth.Metadata["type"] = "codex"
|
| 222 |
+
auth.Metadata["last_refresh"] = time.Now().Format(time.RFC3339)
|
| 223 |
+
|
| 224 |
+
if _, errSave := store.Save(ctx, auth); errSave != nil {
|
| 225 |
+
return "", false, fmt.Errorf("failed to save refreshed auth: %w", errSave)
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
return tokenData.AccessToken, true, nil
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
func fetchModels(ctx context.Context, auth *coreauth.Auth, accessToken, clientVersion string) ([]byte, int, error) {
|
| 232 |
+
modelsURL, errURL := codexModelsURL(clientVersion)
|
| 233 |
+
if errURL != nil {
|
| 234 |
+
return nil, 0, errURL
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
httpReq, errReq := http.NewRequestWithContext(ctx, http.MethodGet, modelsURL, nil)
|
| 238 |
+
if errReq != nil {
|
| 239 |
+
return nil, 0, errReq
|
| 240 |
+
}
|
| 241 |
+
httpReq.Close = true
|
| 242 |
+
httpReq.Header.Set("Accept", "application/json")
|
| 243 |
+
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
|
| 244 |
+
httpReq.Header.Set("Originator", defaultCodexOriginator)
|
| 245 |
+
httpReq.Header.Set("User-Agent", defaultCodexUserAgent)
|
| 246 |
+
if accountID := metaStringValue(auth.Metadata, "account_id"); accountID != "" {
|
| 247 |
+
httpReq.Header.Set("Chatgpt-Account-Id", accountID)
|
| 248 |
+
}
|
| 249 |
+
if auth != nil {
|
| 250 |
+
util.ApplyCustomHeadersFromAttrs(httpReq, auth.Attributes)
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
httpClient := &http.Client{}
|
| 254 |
+
if auth != nil {
|
| 255 |
+
if transport, _, errProxy := proxyutil.BuildHTTPTransport(auth.ProxyURL); errProxy == nil && transport != nil {
|
| 256 |
+
httpClient.Transport = transport
|
| 257 |
+
}
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
httpResp, errDo := httpClient.Do(httpReq)
|
| 261 |
+
if errDo != nil {
|
| 262 |
+
return nil, 0, errDo
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
bodyBytes, errRead := io.ReadAll(httpResp.Body)
|
| 266 |
+
if errClose := httpResp.Body.Close(); errClose != nil && errRead == nil {
|
| 267 |
+
errRead = errClose
|
| 268 |
+
}
|
| 269 |
+
if errRead != nil {
|
| 270 |
+
return nil, 0, errRead
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
if httpResp.StatusCode < http.StatusOK || httpResp.StatusCode >= http.StatusMultipleChoices {
|
| 274 |
+
return nil, 0, fmt.Errorf("models request failed with status %d: %s", httpResp.StatusCode, strings.TrimSpace(string(bodyBytes)))
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
count, errCount := countModels(bodyBytes)
|
| 278 |
+
if errCount != nil {
|
| 279 |
+
return nil, 0, errCount
|
| 280 |
+
}
|
| 281 |
+
return bodyBytes, count, nil
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
func codexModelsURL(clientVersion string) (string, error) {
|
| 285 |
+
u, err := url.Parse(codexModelsBaseURL + codexModelsPath)
|
| 286 |
+
if err != nil {
|
| 287 |
+
return "", err
|
| 288 |
+
}
|
| 289 |
+
if strings.TrimSpace(clientVersion) != "" {
|
| 290 |
+
q := u.Query()
|
| 291 |
+
q.Set("client_version", strings.TrimSpace(clientVersion))
|
| 292 |
+
u.RawQuery = q.Encode()
|
| 293 |
+
}
|
| 294 |
+
return u.String(), nil
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
func countModels(raw []byte) (int, error) {
|
| 298 |
+
var payload struct {
|
| 299 |
+
Models []json.RawMessage `json:"models"`
|
| 300 |
+
}
|
| 301 |
+
if err := json.Unmarshal(raw, &payload); err != nil {
|
| 302 |
+
return 0, fmt.Errorf("failed to parse response JSON: %w", err)
|
| 303 |
+
}
|
| 304 |
+
// Keep this check intentionally loose: fetch_codex_models dumps the upstream
|
| 305 |
+
// Codex API payload. Strict CPA catalog validation belongs in
|
| 306 |
+
// cmd/validate_codex_models and registry.ValidateCodexClientModelsJSON.
|
| 307 |
+
if payload.Models == nil {
|
| 308 |
+
return 0, fmt.Errorf("response JSON does not contain models array")
|
| 309 |
+
}
|
| 310 |
+
return len(payload.Models), nil
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
func prettyJSON(raw []byte) ([]byte, error) {
|
| 314 |
+
var buf bytes.Buffer
|
| 315 |
+
if err := json.Indent(&buf, raw, "", " "); err != nil {
|
| 316 |
+
return nil, err
|
| 317 |
+
}
|
| 318 |
+
buf.WriteByte('\n')
|
| 319 |
+
return buf.Bytes(), nil
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
func metaStringValue(m map[string]any, key string) string {
|
| 323 |
+
if m == nil {
|
| 324 |
+
return ""
|
| 325 |
+
}
|
| 326 |
+
v, ok := m[key]
|
| 327 |
+
if !ok {
|
| 328 |
+
return ""
|
| 329 |
+
}
|
| 330 |
+
switch val := v.(type) {
|
| 331 |
+
case string:
|
| 332 |
+
return strings.TrimSpace(val)
|
| 333 |
+
default:
|
| 334 |
+
return ""
|
| 335 |
+
}
|
| 336 |
+
}
|
cmd/fetch_codex_models/main_test.go
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import "testing"
|
| 4 |
+
|
| 5 |
+
func TestCodexModelsURL(t *testing.T) {
|
| 6 |
+
got, err := codexModelsURL(" 0.144.1 ")
|
| 7 |
+
if err != nil {
|
| 8 |
+
t.Fatalf("codexModelsURL: %v", err)
|
| 9 |
+
}
|
| 10 |
+
want := "https://chatgpt.com/backend-api/codex/models?client_version=0.144.1"
|
| 11 |
+
if got != want {
|
| 12 |
+
t.Fatalf("codexModelsURL = %q, want %q", got, want)
|
| 13 |
+
}
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
func TestCountModels(t *testing.T) {
|
| 17 |
+
count, err := countModels([]byte(`{"models":[{"slug":"a"},{"slug":"b"}]}`))
|
| 18 |
+
if err != nil {
|
| 19 |
+
t.Fatalf("countModels(valid): %v", err)
|
| 20 |
+
}
|
| 21 |
+
if count != 2 {
|
| 22 |
+
t.Fatalf("countModels(valid) = %d, want 2", count)
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
// Upstream dumps may omit CPA catalog-required fields; counting must still work.
|
| 26 |
+
count, err = countModels([]byte(`{"models":[{"slug":"gpt-5.6-sol"}]}`))
|
| 27 |
+
if err != nil {
|
| 28 |
+
t.Fatalf("countModels(incomplete upstream model): %v", err)
|
| 29 |
+
}
|
| 30 |
+
if count != 1 {
|
| 31 |
+
t.Fatalf("countModels(incomplete upstream model) = %d, want 1", count)
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
count, err = countModels([]byte(`{"models":[]}`))
|
| 35 |
+
if err != nil {
|
| 36 |
+
t.Fatalf("countModels(empty): %v", err)
|
| 37 |
+
}
|
| 38 |
+
if count != 0 {
|
| 39 |
+
t.Fatalf("countModels(empty) = %d, want 0", count)
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
if _, err := countModels([]byte(`{"models":`)); err == nil {
|
| 43 |
+
t.Fatal("countModels(malformed) error = nil, want error")
|
| 44 |
+
}
|
| 45 |
+
if _, err := countModels([]byte(`{}`)); err == nil {
|
| 46 |
+
t.Fatal("countModels(missing models) error = nil, want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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package main provides the entry point for the CLI Proxy API server.
|
| 2 |
+
// This server acts as a proxy that provides OpenAI/Gemini/Claude compatible API interfaces
|
| 3 |
+
// for CLI models, allowing CLI models to be used with tools and libraries designed for standard AI APIs.
|
| 4 |
+
package main
|
| 5 |
+
|
| 6 |
+
import (
|
| 7 |
+
"context"
|
| 8 |
+
"errors"
|
| 9 |
+
"flag"
|
| 10 |
+
"fmt"
|
| 11 |
+
"io"
|
| 12 |
+
"io/fs"
|
| 13 |
+
"net/url"
|
| 14 |
+
"os"
|
| 15 |
+
"path/filepath"
|
| 16 |
+
"strings"
|
| 17 |
+
"time"
|
| 18 |
+
|
| 19 |
+
"github.com/joho/godotenv"
|
| 20 |
+
configaccess "github.com/router-for-me/CLIProxyAPI/v7/internal/access/config_access"
|
| 21 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/api"
|
| 22 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/buildinfo"
|
| 23 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/cmd"
|
| 24 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 25 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/home"
|
| 26 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/homeplugins"
|
| 27 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
|
| 28 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/managementasset"
|
| 29 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/misc"
|
| 30 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
|
| 31 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/redisqueue"
|
| 32 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
|
| 33 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/safemode"
|
| 34 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/store"
|
| 35 |
+
_ "github.com/router-for-me/CLIProxyAPI/v7/internal/translator"
|
| 36 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/tui"
|
| 37 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
| 38 |
+
sdkAuth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
| 39 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 40 |
+
sdkpluginstore "github.com/router-for-me/CLIProxyAPI/v7/sdk/pluginstore"
|
| 41 |
+
log "github.com/sirupsen/logrus"
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
var (
|
| 45 |
+
Version = "dev"
|
| 46 |
+
Commit = "none"
|
| 47 |
+
BuildDate = "unknown"
|
| 48 |
+
DefaultConfigPath = ""
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
// init initializes the shared logger setup.
|
| 52 |
+
func init() {
|
| 53 |
+
logging.SetupBaseLogger()
|
| 54 |
+
buildinfo.Version = Version
|
| 55 |
+
buildinfo.Commit = Commit
|
| 56 |
+
buildinfo.BuildDate = BuildDate
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
func shouldEnableExampleAPIKeySafeMode(cfg *config.Config, commandMode, tuiMode, standalone, cloudConfigMissing, homeMode bool) bool {
|
| 60 |
+
if cfg == nil || commandMode || homeMode || cloudConfigMissing {
|
| 61 |
+
return false
|
| 62 |
+
}
|
| 63 |
+
if tuiMode && !standalone {
|
| 64 |
+
return false
|
| 65 |
+
}
|
| 66 |
+
return safemode.HasExampleAPIKeys(cfg.APIKeys)
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
// main is the entry point of the application.
|
| 70 |
+
// It parses command-line flags, loads configuration, and starts the appropriate
|
| 71 |
+
// service based on the provided flags (login, codex-login, or server mode).
|
| 72 |
+
func main() {
|
| 73 |
+
fmt.Printf("CLIProxyAPI Version: %s, Commit: %s, BuiltAt: %s\n", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate)
|
| 74 |
+
|
| 75 |
+
// Command-line flags to control the application's behavior.
|
| 76 |
+
var codexLogin bool
|
| 77 |
+
var codexDeviceLogin bool
|
| 78 |
+
var claudeLogin bool
|
| 79 |
+
var noBrowser bool
|
| 80 |
+
var oauthCallbackPort int
|
| 81 |
+
var antigravityLogin bool
|
| 82 |
+
var kimiLogin bool
|
| 83 |
+
var xaiLogin bool
|
| 84 |
+
var vertexImport string
|
| 85 |
+
var vertexImportPrefix string
|
| 86 |
+
var configPath string
|
| 87 |
+
var password string
|
| 88 |
+
var homeJWT string
|
| 89 |
+
var homeDisableClusterDiscovery bool
|
| 90 |
+
var tuiMode bool
|
| 91 |
+
var standalone bool
|
| 92 |
+
var localModel bool
|
| 93 |
+
|
| 94 |
+
// Define command-line flags for different operation modes.
|
| 95 |
+
flag.BoolVar(&codexLogin, "codex-login", false, "Login to Codex using OAuth")
|
| 96 |
+
flag.BoolVar(&codexDeviceLogin, "codex-device-login", false, "Login to Codex using device code flow")
|
| 97 |
+
flag.BoolVar(&claudeLogin, "claude-login", false, "Login to Claude using OAuth")
|
| 98 |
+
flag.BoolVar(&noBrowser, "no-browser", false, "Don't open browser automatically for OAuth")
|
| 99 |
+
flag.IntVar(&oauthCallbackPort, "oauth-callback-port", 0, "Override OAuth callback port (defaults to provider-specific port)")
|
| 100 |
+
flag.BoolVar(&antigravityLogin, "antigravity-login", false, "Login to Antigravity using OAuth")
|
| 101 |
+
flag.BoolVar(&kimiLogin, "kimi-login", false, "Login to Kimi using OAuth")
|
| 102 |
+
flag.BoolVar(&xaiLogin, "xai-login", false, "Login to xAI using OAuth")
|
| 103 |
+
flag.StringVar(&configPath, "config", DefaultConfigPath, "Configure File Path")
|
| 104 |
+
flag.StringVar(&vertexImport, "vertex-import", "", "Import Vertex service account key JSON file")
|
| 105 |
+
flag.StringVar(&vertexImportPrefix, "vertex-import-prefix", "", "Prefix for Vertex model namespacing (use with -vertex-import)")
|
| 106 |
+
flag.StringVar(&password, "password", "", "")
|
| 107 |
+
flag.StringVar(&homeJWT, "home-jwt", "", "Home control plane JWT for mTLS certificate bootstrap and connection")
|
| 108 |
+
flag.BoolVar(&homeDisableClusterDiscovery, "home-disable-cluster-discovery", false, "Disable Home CLUSTER NODES discovery and keep using the configured -home-jwt address")
|
| 109 |
+
flag.BoolVar(&tuiMode, "tui", false, "Start with terminal management UI")
|
| 110 |
+
flag.BoolVar(&standalone, "standalone", false, "In TUI mode, start an embedded local server")
|
| 111 |
+
flag.BoolVar(&localModel, "local-model", false, "Use embedded models.json and codex_client_models.json only, skip remote model catalog fetching")
|
| 112 |
+
|
| 113 |
+
flag.CommandLine.Usage = func() {
|
| 114 |
+
out := flag.CommandLine.Output()
|
| 115 |
+
_, _ = fmt.Fprintf(out, "Usage of %s\n", os.Args[0])
|
| 116 |
+
flag.CommandLine.VisitAll(func(f *flag.Flag) {
|
| 117 |
+
if f.Name == "password" {
|
| 118 |
+
return
|
| 119 |
+
}
|
| 120 |
+
s := fmt.Sprintf(" -%s", f.Name)
|
| 121 |
+
name, unquoteUsage := flag.UnquoteUsage(f)
|
| 122 |
+
if name != "" {
|
| 123 |
+
s += " " + name
|
| 124 |
+
}
|
| 125 |
+
if len(s) <= 4 {
|
| 126 |
+
s += " "
|
| 127 |
+
} else {
|
| 128 |
+
s += "\n "
|
| 129 |
+
}
|
| 130 |
+
if unquoteUsage != "" {
|
| 131 |
+
s += unquoteUsage
|
| 132 |
+
}
|
| 133 |
+
if f.DefValue != "" && f.DefValue != "false" && f.DefValue != "0" {
|
| 134 |
+
s += fmt.Sprintf(" (default %s)", f.DefValue)
|
| 135 |
+
}
|
| 136 |
+
_, _ = fmt.Fprint(out, s+"\n")
|
| 137 |
+
})
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
pluginHost := pluginhost.New()
|
| 141 |
+
if bootstrapCfg := loadPluginBootstrapConfig(pluginBootstrapConfigPath(os.Args[1:], DefaultConfigPath)); bootstrapCfg != nil {
|
| 142 |
+
pluginHost.ApplyConfig(context.Background(), bootstrapCfg)
|
| 143 |
+
pluginHost.RegisterCommandLineFlags(context.Background(), flag.CommandLine)
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
// Parse the command-line flags.
|
| 147 |
+
flag.Parse()
|
| 148 |
+
|
| 149 |
+
// Core application variables.
|
| 150 |
+
var err error
|
| 151 |
+
var cfg *config.Config
|
| 152 |
+
var isCloudDeploy bool
|
| 153 |
+
var configLoadedFromHome bool
|
| 154 |
+
var homeClient *home.Client
|
| 155 |
+
var homePluginSyncReport homeplugins.SyncReport
|
| 156 |
+
var homePluginStatusReady bool
|
| 157 |
+
var (
|
| 158 |
+
usePostgresStore bool
|
| 159 |
+
pgStoreDSN string
|
| 160 |
+
pgStoreSchema string
|
| 161 |
+
pgStoreLocalPath string
|
| 162 |
+
pgStoreInst *store.PostgresStore
|
| 163 |
+
useGitStore bool
|
| 164 |
+
gitStoreRemoteURL string
|
| 165 |
+
gitStoreUser string
|
| 166 |
+
gitStorePassword string
|
| 167 |
+
gitStoreBranch string
|
| 168 |
+
gitStoreLocalPath string
|
| 169 |
+
gitStoreInst *store.GitTokenStore
|
| 170 |
+
gitStoreRoot string
|
| 171 |
+
useObjectStore bool
|
| 172 |
+
objectStoreEndpoint string
|
| 173 |
+
objectStoreAccess string
|
| 174 |
+
objectStoreSecret string
|
| 175 |
+
objectStoreBucket string
|
| 176 |
+
objectStoreLocalPath string
|
| 177 |
+
objectStoreInst *store.ObjectTokenStore
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
wd, err := os.Getwd()
|
| 181 |
+
if err != nil {
|
| 182 |
+
log.Errorf("failed to get working directory: %v", err)
|
| 183 |
+
return
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
// Load environment variables from .env if present.
|
| 187 |
+
if errLoad := godotenv.Load(filepath.Join(wd, ".env")); errLoad != nil {
|
| 188 |
+
if !errors.Is(errLoad, os.ErrNotExist) {
|
| 189 |
+
log.WithError(errLoad).Warn("failed to load .env file")
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
lookupEnv := func(keys ...string) (string, bool) {
|
| 194 |
+
for _, key := range keys {
|
| 195 |
+
if value, ok := os.LookupEnv(key); ok {
|
| 196 |
+
if trimmed := strings.TrimSpace(value); trimmed != "" {
|
| 197 |
+
return trimmed, true
|
| 198 |
+
}
|
| 199 |
+
}
|
| 200 |
+
}
|
| 201 |
+
return "", false
|
| 202 |
+
}
|
| 203 |
+
writableBase := util.WritablePath()
|
| 204 |
+
|
| 205 |
+
if strings.TrimSpace(homeJWT) == "" {
|
| 206 |
+
if v, ok := lookupEnv("HOME_JWT", "home_jwt"); ok {
|
| 207 |
+
homeJWT = v
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
if value, ok := lookupEnv("PGSTORE_DSN", "pgstore_dsn"); ok {
|
| 212 |
+
usePostgresStore = true
|
| 213 |
+
pgStoreDSN = value
|
| 214 |
+
}
|
| 215 |
+
if usePostgresStore {
|
| 216 |
+
if value, ok := lookupEnv("PGSTORE_SCHEMA", "pgstore_schema"); ok {
|
| 217 |
+
pgStoreSchema = value
|
| 218 |
+
}
|
| 219 |
+
if value, ok := lookupEnv("PGSTORE_LOCAL_PATH", "pgstore_local_path"); ok {
|
| 220 |
+
pgStoreLocalPath = value
|
| 221 |
+
}
|
| 222 |
+
if pgStoreLocalPath == "" {
|
| 223 |
+
if writableBase != "" {
|
| 224 |
+
pgStoreLocalPath = writableBase
|
| 225 |
+
} else {
|
| 226 |
+
pgStoreLocalPath = wd
|
| 227 |
+
}
|
| 228 |
+
}
|
| 229 |
+
useGitStore = false
|
| 230 |
+
}
|
| 231 |
+
if value, ok := lookupEnv("GITSTORE_GIT_URL", "gitstore_git_url"); ok {
|
| 232 |
+
useGitStore = true
|
| 233 |
+
gitStoreRemoteURL = value
|
| 234 |
+
}
|
| 235 |
+
if value, ok := lookupEnv("GITSTORE_GIT_USERNAME", "gitstore_git_username"); ok {
|
| 236 |
+
gitStoreUser = value
|
| 237 |
+
}
|
| 238 |
+
if value, ok := lookupEnv("GITSTORE_GIT_TOKEN", "gitstore_git_token"); ok {
|
| 239 |
+
gitStorePassword = value
|
| 240 |
+
}
|
| 241 |
+
if value, ok := lookupEnv("GITSTORE_LOCAL_PATH", "gitstore_local_path"); ok {
|
| 242 |
+
gitStoreLocalPath = value
|
| 243 |
+
}
|
| 244 |
+
if value, ok := lookupEnv("GITSTORE_GIT_BRANCH", "gitstore_git_branch"); ok {
|
| 245 |
+
gitStoreBranch = value
|
| 246 |
+
}
|
| 247 |
+
if value, ok := lookupEnv("OBJECTSTORE_ENDPOINT", "objectstore_endpoint"); ok {
|
| 248 |
+
useObjectStore = true
|
| 249 |
+
objectStoreEndpoint = value
|
| 250 |
+
}
|
| 251 |
+
if value, ok := lookupEnv("OBJECTSTORE_ACCESS_KEY", "objectstore_access_key"); ok {
|
| 252 |
+
objectStoreAccess = value
|
| 253 |
+
}
|
| 254 |
+
if value, ok := lookupEnv("OBJECTSTORE_SECRET_KEY", "objectstore_secret_key"); ok {
|
| 255 |
+
objectStoreSecret = value
|
| 256 |
+
}
|
| 257 |
+
if value, ok := lookupEnv("OBJECTSTORE_BUCKET", "objectstore_bucket"); ok {
|
| 258 |
+
objectStoreBucket = value
|
| 259 |
+
}
|
| 260 |
+
if value, ok := lookupEnv("OBJECTSTORE_LOCAL_PATH", "objectstore_local_path"); ok {
|
| 261 |
+
objectStoreLocalPath = value
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
// Check for cloud deploy mode only on first execution
|
| 265 |
+
// Read env var name in uppercase: DEPLOY
|
| 266 |
+
deployEnv := os.Getenv("DEPLOY")
|
| 267 |
+
if deployEnv == "cloud" {
|
| 268 |
+
isCloudDeploy = true
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
// Determine and load the configuration file.
|
| 272 |
+
// Prefer the Postgres store when configured, otherwise fallback to git or local files.
|
| 273 |
+
var configFilePath string
|
| 274 |
+
if strings.TrimSpace(homeJWT) != "" {
|
| 275 |
+
configLoadedFromHome = true
|
| 276 |
+
ctxHome, cancelHome := context.WithTimeout(context.Background(), 30*time.Second)
|
| 277 |
+
homeCfg, errHomeCfg := home.ConfigFromJWT(ctxHome, homeJWT)
|
| 278 |
+
cancelHome()
|
| 279 |
+
if errHomeCfg != nil {
|
| 280 |
+
log.Errorf("invalid -home-jwt: %v", errHomeCfg)
|
| 281 |
+
return
|
| 282 |
+
}
|
| 283 |
+
if homeDisableClusterDiscovery {
|
| 284 |
+
homeCfg.DisableClusterDiscovery = true
|
| 285 |
+
}
|
| 286 |
+
homeClient = home.New(homeCfg)
|
| 287 |
+
defer homeClient.Close()
|
| 288 |
+
|
| 289 |
+
ctxHomeConfig, cancelHomeConfig := context.WithTimeout(context.Background(), 30*time.Second)
|
| 290 |
+
raw, errGetConfig := homeClient.GetConfig(ctxHomeConfig)
|
| 291 |
+
cancelHomeConfig()
|
| 292 |
+
if errGetConfig != nil {
|
| 293 |
+
log.Errorf("failed to fetch config from home: %v", errGetConfig)
|
| 294 |
+
return
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
parsed, errParseConfig := config.ParseConfigBytes(raw)
|
| 298 |
+
if errParseConfig != nil {
|
| 299 |
+
log.Errorf("failed to parse config payload from home: %v", errParseConfig)
|
| 300 |
+
return
|
| 301 |
+
}
|
| 302 |
+
if parsed == nil {
|
| 303 |
+
parsed = &config.Config{}
|
| 304 |
+
}
|
| 305 |
+
parsed.Home = homeCfg
|
| 306 |
+
parsed.Port = 8317 // Default to 8317 for home mode, can be overridden by home config
|
| 307 |
+
parsed.UsageStatisticsEnabled = true
|
| 308 |
+
pluginSyncCfg := *parsed
|
| 309 |
+
parsed.Plugins.StoreAuth = nil
|
| 310 |
+
var errHomePlugins error
|
| 311 |
+
platform := homeplugins.CurrentPlatform()
|
| 312 |
+
if pluginSyncCfg.Plugins.Enabled {
|
| 313 |
+
ctxHomePlugins, cancelHomePlugins := context.WithTimeout(context.Background(), 30*time.Second)
|
| 314 |
+
installedVersions, errInstalledPlugins := homeplugins.InstalledVersions(&pluginSyncCfg)
|
| 315 |
+
if errInstalledPlugins != nil {
|
| 316 |
+
homePluginStatusReady = true
|
| 317 |
+
errHomePlugins = errInstalledPlugins
|
| 318 |
+
homePluginSyncReport = homeplugins.CompletedSyncReport(platform, errInstalledPlugins)
|
| 319 |
+
} else {
|
| 320 |
+
pluginSyncRequest := sdkpluginstore.PluginSyncRequest{
|
| 321 |
+
SchemaVersion: sdkpluginstore.PluginSyncSchemaVersion,
|
| 322 |
+
GOOS: platform.GOOS,
|
| 323 |
+
GOARCH: platform.GOARCH,
|
| 324 |
+
InstalledVersions: installedVersions,
|
| 325 |
+
}
|
| 326 |
+
pluginSyncResponse, errFetchPlugins := homeClient.GetPluginSync(ctxHomePlugins, pluginSyncRequest)
|
| 327 |
+
errHomePlugins = errFetchPlugins
|
| 328 |
+
switch {
|
| 329 |
+
case errHomePlugins == nil:
|
| 330 |
+
homePluginStatusReady = true
|
| 331 |
+
homePluginSyncReport, errHomePlugins = homeplugins.SyncResolvedWithReport(ctxHomePlugins, &pluginSyncCfg, pluginSyncResponse.Items, pluginSyncResponse.ExpiresAt, pluginSyncRequest.InstalledVersions, pluginHost)
|
| 332 |
+
case errors.Is(errHomePlugins, home.ErrPluginSyncUnsupported):
|
| 333 |
+
homePluginStatusReady = true
|
| 334 |
+
homePluginSyncReport, errHomePlugins = homeplugins.SyncWithReport(ctxHomePlugins, &pluginSyncCfg, pluginHost)
|
| 335 |
+
default:
|
| 336 |
+
homePluginStatusReady = true
|
| 337 |
+
homePluginSyncReport = homeplugins.CompletedSyncReport(platform, errHomePlugins)
|
| 338 |
+
}
|
| 339 |
+
pluginSyncRequest.Clear()
|
| 340 |
+
pluginSyncResponse.Clear()
|
| 341 |
+
}
|
| 342 |
+
cancelHomePlugins()
|
| 343 |
+
} else {
|
| 344 |
+
homePluginStatusReady = true
|
| 345 |
+
homePluginSyncReport = homeplugins.CompletedSyncReport(platform, nil)
|
| 346 |
+
}
|
| 347 |
+
if errHomePlugins != nil {
|
| 348 |
+
log.Errorf("failed to sync plugins from home: %v", errHomePlugins)
|
| 349 |
+
}
|
| 350 |
+
if homePluginStatusReady {
|
| 351 |
+
errReportPlugins := home.ReportPluginStatus(context.Background(), homeClient, homeCfg.NodeID, homePluginSyncReport)
|
| 352 |
+
if errReportPlugins != nil {
|
| 353 |
+
log.Warnf("failed to report home plugin sync status: %v", errReportPlugins)
|
| 354 |
+
}
|
| 355 |
+
}
|
| 356 |
+
if errHomePlugins != nil {
|
| 357 |
+
return
|
| 358 |
+
}
|
| 359 |
+
cfg = parsed
|
| 360 |
+
|
| 361 |
+
// Keep a non-empty config path for downstream components (log paths, management assets, etc),
|
| 362 |
+
// but do not require the file to exist when loading config from home.
|
| 363 |
+
if strings.TrimSpace(configPath) != "" {
|
| 364 |
+
configFilePath = configPath
|
| 365 |
+
} else {
|
| 366 |
+
configFilePath = filepath.Join(wd, "config.yaml")
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
// Local stores are intentionally disabled when config is loaded from home.
|
| 370 |
+
usePostgresStore = false
|
| 371 |
+
useObjectStore = false
|
| 372 |
+
useGitStore = false
|
| 373 |
+
} else if usePostgresStore {
|
| 374 |
+
if pgStoreLocalPath == "" {
|
| 375 |
+
pgStoreLocalPath = wd
|
| 376 |
+
}
|
| 377 |
+
pgStoreLocalPath = filepath.Join(pgStoreLocalPath, "pgstore")
|
| 378 |
+
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
| 379 |
+
pgStoreInst, err = store.NewPostgresStore(ctx, store.PostgresStoreConfig{
|
| 380 |
+
DSN: pgStoreDSN,
|
| 381 |
+
Schema: pgStoreSchema,
|
| 382 |
+
SpoolDir: pgStoreLocalPath,
|
| 383 |
+
})
|
| 384 |
+
cancel()
|
| 385 |
+
if err != nil {
|
| 386 |
+
log.Errorf("failed to initialize postgres token store: %v", err)
|
| 387 |
+
return
|
| 388 |
+
}
|
| 389 |
+
examplePath := filepath.Join(wd, "config.example.yaml")
|
| 390 |
+
ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
|
| 391 |
+
if errBootstrap := pgStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil {
|
| 392 |
+
cancel()
|
| 393 |
+
log.Errorf("failed to bootstrap postgres-backed config: %v", errBootstrap)
|
| 394 |
+
return
|
| 395 |
+
}
|
| 396 |
+
cancel()
|
| 397 |
+
configFilePath = pgStoreInst.ConfigPath()
|
| 398 |
+
cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy)
|
| 399 |
+
if err == nil {
|
| 400 |
+
cfg.AuthDir = pgStoreInst.AuthDir()
|
| 401 |
+
log.Infof("postgres-backed token store enabled, workspace path: %s", pgStoreInst.WorkDir())
|
| 402 |
+
}
|
| 403 |
+
} else if useObjectStore {
|
| 404 |
+
if objectStoreLocalPath == "" {
|
| 405 |
+
if writableBase != "" {
|
| 406 |
+
objectStoreLocalPath = writableBase
|
| 407 |
+
} else {
|
| 408 |
+
objectStoreLocalPath = wd
|
| 409 |
+
}
|
| 410 |
+
}
|
| 411 |
+
objectStoreRoot := filepath.Join(objectStoreLocalPath, "objectstore")
|
| 412 |
+
resolvedEndpoint := strings.TrimSpace(objectStoreEndpoint)
|
| 413 |
+
useSSL := true
|
| 414 |
+
if strings.Contains(resolvedEndpoint, "://") {
|
| 415 |
+
parsed, errParse := url.Parse(resolvedEndpoint)
|
| 416 |
+
if errParse != nil {
|
| 417 |
+
log.Errorf("failed to parse object store endpoint %q: %v", objectStoreEndpoint, errParse)
|
| 418 |
+
return
|
| 419 |
+
}
|
| 420 |
+
switch strings.ToLower(parsed.Scheme) {
|
| 421 |
+
case "http":
|
| 422 |
+
useSSL = false
|
| 423 |
+
case "https":
|
| 424 |
+
useSSL = true
|
| 425 |
+
default:
|
| 426 |
+
log.Errorf("unsupported object store scheme %q (only http and https are allowed)", parsed.Scheme)
|
| 427 |
+
return
|
| 428 |
+
}
|
| 429 |
+
if parsed.Host == "" {
|
| 430 |
+
log.Errorf("object store endpoint %q is missing host information", objectStoreEndpoint)
|
| 431 |
+
return
|
| 432 |
+
}
|
| 433 |
+
resolvedEndpoint = parsed.Host
|
| 434 |
+
if parsed.Path != "" && parsed.Path != "/" {
|
| 435 |
+
resolvedEndpoint = strings.TrimSuffix(parsed.Host+parsed.Path, "/")
|
| 436 |
+
}
|
| 437 |
+
}
|
| 438 |
+
resolvedEndpoint = strings.TrimRight(resolvedEndpoint, "/")
|
| 439 |
+
objCfg := store.ObjectStoreConfig{
|
| 440 |
+
Endpoint: resolvedEndpoint,
|
| 441 |
+
Bucket: objectStoreBucket,
|
| 442 |
+
AccessKey: objectStoreAccess,
|
| 443 |
+
SecretKey: objectStoreSecret,
|
| 444 |
+
LocalRoot: objectStoreRoot,
|
| 445 |
+
UseSSL: useSSL,
|
| 446 |
+
PathStyle: true,
|
| 447 |
+
}
|
| 448 |
+
objectStoreInst, err = store.NewObjectTokenStore(objCfg)
|
| 449 |
+
if err != nil {
|
| 450 |
+
log.Errorf("failed to initialize object token store: %v", err)
|
| 451 |
+
return
|
| 452 |
+
}
|
| 453 |
+
examplePath := filepath.Join(wd, "config.example.yaml")
|
| 454 |
+
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
| 455 |
+
if errBootstrap := objectStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil {
|
| 456 |
+
cancel()
|
| 457 |
+
log.Errorf("failed to bootstrap object-backed config: %v", errBootstrap)
|
| 458 |
+
return
|
| 459 |
+
}
|
| 460 |
+
cancel()
|
| 461 |
+
configFilePath = objectStoreInst.ConfigPath()
|
| 462 |
+
cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy)
|
| 463 |
+
if err == nil {
|
| 464 |
+
if cfg == nil {
|
| 465 |
+
cfg = &config.Config{}
|
| 466 |
+
}
|
| 467 |
+
cfg.AuthDir = objectStoreInst.AuthDir()
|
| 468 |
+
log.Infof("object-backed token store enabled, bucket: %s", objectStoreBucket)
|
| 469 |
+
}
|
| 470 |
+
} else if useGitStore {
|
| 471 |
+
if gitStoreLocalPath == "" {
|
| 472 |
+
if writableBase != "" {
|
| 473 |
+
gitStoreLocalPath = writableBase
|
| 474 |
+
} else {
|
| 475 |
+
gitStoreLocalPath = wd
|
| 476 |
+
}
|
| 477 |
+
}
|
| 478 |
+
gitStoreRoot = filepath.Join(gitStoreLocalPath, "gitstore")
|
| 479 |
+
authDir := filepath.Join(gitStoreRoot, "auths")
|
| 480 |
+
gitStoreInst = store.NewGitTokenStore(gitStoreRemoteURL, gitStoreUser, gitStorePassword, gitStoreBranch)
|
| 481 |
+
gitStoreInst.SetBaseDir(authDir)
|
| 482 |
+
if errRepo := gitStoreInst.EnsureRepository(); errRepo != nil {
|
| 483 |
+
log.Errorf("failed to prepare git token store: %v", errRepo)
|
| 484 |
+
return
|
| 485 |
+
}
|
| 486 |
+
configFilePath = gitStoreInst.ConfigPath()
|
| 487 |
+
if configFilePath == "" {
|
| 488 |
+
configFilePath = filepath.Join(gitStoreRoot, "config", "config.yaml")
|
| 489 |
+
}
|
| 490 |
+
if _, statErr := os.Stat(configFilePath); errors.Is(statErr, fs.ErrNotExist) {
|
| 491 |
+
examplePath := filepath.Join(wd, "config.example.yaml")
|
| 492 |
+
if _, errExample := os.Stat(examplePath); errExample != nil {
|
| 493 |
+
log.Errorf("failed to find template config file: %v", errExample)
|
| 494 |
+
return
|
| 495 |
+
}
|
| 496 |
+
if errCopy := misc.CopyConfigTemplate(examplePath, configFilePath); errCopy != nil {
|
| 497 |
+
log.Errorf("failed to bootstrap git-backed config: %v", errCopy)
|
| 498 |
+
return
|
| 499 |
+
}
|
| 500 |
+
if errCommit := gitStoreInst.PersistConfig(context.Background()); errCommit != nil {
|
| 501 |
+
log.Errorf("failed to commit initial git-backed config: %v", errCommit)
|
| 502 |
+
return
|
| 503 |
+
}
|
| 504 |
+
log.Infof("git-backed config initialized from template: %s", configFilePath)
|
| 505 |
+
} else if statErr != nil {
|
| 506 |
+
log.Errorf("failed to inspect git-backed config: %v", statErr)
|
| 507 |
+
return
|
| 508 |
+
}
|
| 509 |
+
cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy)
|
| 510 |
+
if err == nil {
|
| 511 |
+
cfg.AuthDir = gitStoreInst.AuthDir()
|
| 512 |
+
log.Infof("git-backed token store enabled, repository path: %s", gitStoreRoot)
|
| 513 |
+
}
|
| 514 |
+
} else if configPath != "" {
|
| 515 |
+
configFilePath = configPath
|
| 516 |
+
cfg, err = config.LoadConfigOptional(configPath, isCloudDeploy)
|
| 517 |
+
} else {
|
| 518 |
+
wd, err = os.Getwd()
|
| 519 |
+
if err != nil {
|
| 520 |
+
log.Errorf("failed to get working directory: %v", err)
|
| 521 |
+
return
|
| 522 |
+
}
|
| 523 |
+
configFilePath = filepath.Join(wd, "config.yaml")
|
| 524 |
+
cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy)
|
| 525 |
+
}
|
| 526 |
+
if err != nil {
|
| 527 |
+
log.Errorf("failed to load config: %v", err)
|
| 528 |
+
return
|
| 529 |
+
}
|
| 530 |
+
if cfg == nil {
|
| 531 |
+
cfg = &config.Config{}
|
| 532 |
+
}
|
| 533 |
+
|
| 534 |
+
// In cloud deploy mode, check if we have a valid configuration
|
| 535 |
+
var configFileExists bool
|
| 536 |
+
if isCloudDeploy {
|
| 537 |
+
if configLoadedFromHome && cfg != nil {
|
| 538 |
+
configFileExists = cfg.Port != 0
|
| 539 |
+
} else {
|
| 540 |
+
if info, errStat := os.Stat(configFilePath); errStat != nil {
|
| 541 |
+
// Don't mislead: API server will not start until configuration is provided.
|
| 542 |
+
log.Info("Cloud deploy mode: No configuration file detected; standing by for configuration")
|
| 543 |
+
configFileExists = false
|
| 544 |
+
} else if info.IsDir() {
|
| 545 |
+
log.Info("Cloud deploy mode: Config path is a directory; standing by for configuration")
|
| 546 |
+
configFileExists = false
|
| 547 |
+
} else if cfg.Port == 0 {
|
| 548 |
+
// LoadConfigOptional returns empty config when file is empty or invalid.
|
| 549 |
+
// Config file exists but is empty or invalid; treat as missing config
|
| 550 |
+
log.Info("Cloud deploy mode: Configuration file is empty or invalid; standing by for valid configuration")
|
| 551 |
+
configFileExists = false
|
| 552 |
+
} else {
|
| 553 |
+
log.Info("Cloud deploy mode: Configuration file detected; starting service")
|
| 554 |
+
configFileExists = true
|
| 555 |
+
}
|
| 556 |
+
}
|
| 557 |
+
}
|
| 558 |
+
redisqueue.SetUsageStatisticsEnabled(cfg.UsageStatisticsEnabled)
|
| 559 |
+
redisqueue.SetRetentionSeconds(cfg.RedisUsageQueueRetentionSeconds)
|
| 560 |
+
coreauth.SetQuotaCooldownDisabled(cfg.DisableCooling)
|
| 561 |
+
coreauth.SetTransientErrorCooldownSeconds(cfg.TransientErrorCooldownSeconds)
|
| 562 |
+
|
| 563 |
+
if err = logging.ConfigureLogOutput(cfg); err != nil {
|
| 564 |
+
log.Errorf("failed to configure log output: %v", err)
|
| 565 |
+
return
|
| 566 |
+
}
|
| 567 |
+
|
| 568 |
+
log.Infof("CLIProxyAPI Version: %s, Commit: %s, BuiltAt: %s", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate)
|
| 569 |
+
|
| 570 |
+
// Set the log level based on the configuration.
|
| 571 |
+
util.SetLogLevel(cfg)
|
| 572 |
+
|
| 573 |
+
if resolvedAuthDir, errResolveAuthDir := util.ResolveAuthDir(cfg.AuthDir); errResolveAuthDir != nil {
|
| 574 |
+
log.Errorf("failed to resolve auth directory: %v", errResolveAuthDir)
|
| 575 |
+
return
|
| 576 |
+
} else {
|
| 577 |
+
cfg.AuthDir = resolvedAuthDir
|
| 578 |
+
}
|
| 579 |
+
managementasset.SetCurrentConfig(cfg)
|
| 580 |
+
|
| 581 |
+
// Create login options to be used in authentication flows.
|
| 582 |
+
options := &cmd.LoginOptions{
|
| 583 |
+
NoBrowser: noBrowser,
|
| 584 |
+
CallbackPort: oauthCallbackPort,
|
| 585 |
+
}
|
| 586 |
+
|
| 587 |
+
commandMode := vertexImport != "" || antigravityLogin || codexLogin || codexDeviceLogin || claudeLogin || kimiLogin || xaiLogin
|
| 588 |
+
cloudConfigMissing := isCloudDeploy && !configFileExists
|
| 589 |
+
homeMode := configLoadedFromHome || (cfg != nil && cfg.Home.Enabled)
|
| 590 |
+
exampleAPIKeySafeMode := shouldEnableExampleAPIKeySafeMode(cfg, commandMode, tuiMode, standalone, cloudConfigMissing, homeMode)
|
| 591 |
+
serverOptions := []api.ServerOption(nil)
|
| 592 |
+
if exampleAPIKeySafeMode {
|
| 593 |
+
matches := safemode.ExampleAPIKeys(cfg.APIKeys)
|
| 594 |
+
log.WithField("api_keys", strings.Join(matches, ",")).Error("unsafe example API key configured; proxy API endpoints disabled until api-keys is updated")
|
| 595 |
+
serverOptions = append(serverOptions, api.WithExampleAPIKeySafeMode())
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
// Register the shared token store once so all components use the same persistence backend.
|
| 599 |
+
if usePostgresStore {
|
| 600 |
+
sdkAuth.RegisterTokenStore(pgStoreInst)
|
| 601 |
+
} else if useObjectStore {
|
| 602 |
+
sdkAuth.RegisterTokenStore(objectStoreInst)
|
| 603 |
+
} else if useGitStore {
|
| 604 |
+
sdkAuth.RegisterTokenStore(gitStoreInst)
|
| 605 |
+
} else {
|
| 606 |
+
sdkAuth.RegisterTokenStore(sdkAuth.NewFileTokenStore())
|
| 607 |
+
}
|
| 608 |
+
|
| 609 |
+
// Register built-in access providers before constructing services.
|
| 610 |
+
configaccess.Register(&cfg.SDKConfig)
|
| 611 |
+
pluginHost.ApplyConfig(context.Background(), cfg)
|
| 612 |
+
if configLoadedFromHome && homePluginStatusReady {
|
| 613 |
+
errHomePluginLoad := homeplugins.MarkLoadResults(&homePluginSyncReport, pluginHost)
|
| 614 |
+
errReportPlugins := home.ReportPluginStatus(context.Background(), homeClient, cfg.Home.NodeID, homePluginSyncReport)
|
| 615 |
+
if errHomePluginLoad != nil {
|
| 616 |
+
log.Errorf("failed to load home plugins: %v", errHomePluginLoad)
|
| 617 |
+
}
|
| 618 |
+
if errReportPlugins != nil {
|
| 619 |
+
log.Warnf("failed to report home plugin load status: %v", errReportPlugins)
|
| 620 |
+
}
|
| 621 |
+
if errHomePluginLoad != nil {
|
| 622 |
+
return
|
| 623 |
+
}
|
| 624 |
+
}
|
| 625 |
+
if pluginHost.HasTriggeredCommandLineFlags() {
|
| 626 |
+
if exitCode, handled := pluginHost.ExecuteCommandLine(context.Background(), os.Args[0], os.Args[1:], configFilePath, flag.CommandLine); handled {
|
| 627 |
+
if exitCode != 0 {
|
| 628 |
+
os.Exit(exitCode)
|
| 629 |
+
}
|
| 630 |
+
return
|
| 631 |
+
}
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
// Handle different command modes based on the provided flags.
|
| 635 |
+
|
| 636 |
+
if vertexImport != "" {
|
| 637 |
+
// Handle Vertex service account import
|
| 638 |
+
cmd.DoVertexImport(cfg, vertexImport, vertexImportPrefix)
|
| 639 |
+
} else if antigravityLogin {
|
| 640 |
+
// Handle Antigravity login
|
| 641 |
+
cmd.DoAntigravityLogin(cfg, options)
|
| 642 |
+
} else if codexLogin {
|
| 643 |
+
// Handle Codex login
|
| 644 |
+
cmd.DoCodexLogin(cfg, options)
|
| 645 |
+
} else if codexDeviceLogin {
|
| 646 |
+
// Handle Codex device-code login
|
| 647 |
+
cmd.DoCodexDeviceLogin(cfg, options)
|
| 648 |
+
} else if claudeLogin {
|
| 649 |
+
// Handle Claude login
|
| 650 |
+
cmd.DoClaudeLogin(cfg, options)
|
| 651 |
+
} else if kimiLogin {
|
| 652 |
+
cmd.DoKimiLogin(cfg, options)
|
| 653 |
+
} else if xaiLogin {
|
| 654 |
+
cmd.DoXAILogin(cfg, options)
|
| 655 |
+
} else {
|
| 656 |
+
// In cloud deploy mode without config file, just wait for shutdown signals
|
| 657 |
+
if isCloudDeploy && !configFileExists {
|
| 658 |
+
// No config file available, just wait for shutdown
|
| 659 |
+
cmd.WaitForCloudDeploy()
|
| 660 |
+
return
|
| 661 |
+
}
|
| 662 |
+
if localModel && (!tuiMode || standalone) {
|
| 663 |
+
log.Info("Local model mode: using embedded model catalogs, remote model updates disabled")
|
| 664 |
+
}
|
| 665 |
+
if tuiMode {
|
| 666 |
+
if standalone {
|
| 667 |
+
// Standalone mode: start an embedded local server and connect TUI client to it.
|
| 668 |
+
managementasset.StartAutoUpdater(context.Background(), configFilePath)
|
| 669 |
+
misc.StartAntigravityVersionUpdater(context.Background())
|
| 670 |
+
startModelCatalogUpdaters(localModel, cfg.Home.Enabled)
|
| 671 |
+
hook := tui.NewLogHook(2000)
|
| 672 |
+
hook.SetFormatter(&logging.LogFormatter{})
|
| 673 |
+
log.AddHook(hook)
|
| 674 |
+
|
| 675 |
+
origStdout := os.Stdout
|
| 676 |
+
origStderr := os.Stderr
|
| 677 |
+
origLogOutput := log.StandardLogger().Out
|
| 678 |
+
log.SetOutput(io.Discard)
|
| 679 |
+
|
| 680 |
+
devNull, errOpenDevNull := os.Open(os.DevNull)
|
| 681 |
+
if errOpenDevNull == nil {
|
| 682 |
+
os.Stdout = devNull
|
| 683 |
+
os.Stderr = devNull
|
| 684 |
+
}
|
| 685 |
+
|
| 686 |
+
restoreIO := func() {
|
| 687 |
+
os.Stdout = origStdout
|
| 688 |
+
os.Stderr = origStderr
|
| 689 |
+
log.SetOutput(origLogOutput)
|
| 690 |
+
if devNull != nil {
|
| 691 |
+
_ = devNull.Close()
|
| 692 |
+
}
|
| 693 |
+
}
|
| 694 |
+
|
| 695 |
+
localMgmtPassword := fmt.Sprintf("tui-%d-%d", os.Getpid(), time.Now().UnixNano())
|
| 696 |
+
if password == "" {
|
| 697 |
+
password = localMgmtPassword
|
| 698 |
+
}
|
| 699 |
+
|
| 700 |
+
cancel, done := cmd.StartServiceBackgroundWithPluginHost(cfg, configFilePath, password, pluginHost, serverOptions...)
|
| 701 |
+
|
| 702 |
+
client := tui.NewClient(cfg.Port, password)
|
| 703 |
+
ready := false
|
| 704 |
+
backoff := 100 * time.Millisecond
|
| 705 |
+
for i := 0; i < 30; i++ {
|
| 706 |
+
if _, errGetConfig := client.GetConfig(); errGetConfig == nil {
|
| 707 |
+
ready = true
|
| 708 |
+
break
|
| 709 |
+
}
|
| 710 |
+
time.Sleep(backoff)
|
| 711 |
+
if backoff < time.Second {
|
| 712 |
+
backoff = time.Duration(float64(backoff) * 1.5)
|
| 713 |
+
}
|
| 714 |
+
}
|
| 715 |
+
|
| 716 |
+
if !ready {
|
| 717 |
+
restoreIO()
|
| 718 |
+
cancel()
|
| 719 |
+
<-done
|
| 720 |
+
fmt.Fprintf(os.Stderr, "TUI error: embedded server is not ready\n")
|
| 721 |
+
return
|
| 722 |
+
}
|
| 723 |
+
|
| 724 |
+
if errRun := tui.Run(cfg.Port, password, hook, origStdout); errRun != nil {
|
| 725 |
+
restoreIO()
|
| 726 |
+
fmt.Fprintf(os.Stderr, "TUI error: %v\n", errRun)
|
| 727 |
+
} else {
|
| 728 |
+
restoreIO()
|
| 729 |
+
}
|
| 730 |
+
|
| 731 |
+
cancel()
|
| 732 |
+
<-done
|
| 733 |
+
} else {
|
| 734 |
+
// Default TUI mode: pure management client.
|
| 735 |
+
// The proxy server must already be running.
|
| 736 |
+
if errRun := tui.Run(cfg.Port, password, nil, os.Stdout); errRun != nil {
|
| 737 |
+
fmt.Fprintf(os.Stderr, "TUI error: %v\n", errRun)
|
| 738 |
+
}
|
| 739 |
+
}
|
| 740 |
+
} else {
|
| 741 |
+
// Start the main proxy service
|
| 742 |
+
managementasset.StartAutoUpdater(context.Background(), configFilePath)
|
| 743 |
+
misc.StartAntigravityVersionUpdater(context.Background())
|
| 744 |
+
startModelCatalogUpdaters(localModel, cfg.Home.Enabled)
|
| 745 |
+
cmd.StartServiceWithPluginHost(cfg, configFilePath, password, pluginHost, serverOptions...)
|
| 746 |
+
}
|
| 747 |
+
}
|
| 748 |
+
}
|
| 749 |
+
|
| 750 |
+
// modelCatalogUpdaterPlan decides which remote model catalogs should refresh.
|
| 751 |
+
// Codex client templates still refresh under Home mode because the model list
|
| 752 |
+
// comes from Home IDs while template metadata stays edge-local.
|
| 753 |
+
func modelCatalogUpdaterPlan(localModel, homeEnabled bool) (startModels, startCodexClient bool) {
|
| 754 |
+
if localModel {
|
| 755 |
+
return false, false
|
| 756 |
+
}
|
| 757 |
+
return !homeEnabled, true
|
| 758 |
+
}
|
| 759 |
+
|
| 760 |
+
func startModelCatalogUpdaters(localModel, homeEnabled bool) {
|
| 761 |
+
startModels, startCodexClient := modelCatalogUpdaterPlan(localModel, homeEnabled)
|
| 762 |
+
if startCodexClient {
|
| 763 |
+
registry.StartCodexClientModelsUpdater(context.Background())
|
| 764 |
+
}
|
| 765 |
+
if startModels {
|
| 766 |
+
registry.StartModelsUpdater(context.Background())
|
| 767 |
+
} else if homeEnabled {
|
| 768 |
+
log.Info("Home mode: remote models.json updates disabled; Codex client model list follows Home model IDs")
|
| 769 |
+
}
|
| 770 |
+
}
|
| 771 |
+
|
| 772 |
+
func pluginBootstrapConfigPath(args []string, defaultPath string) string {
|
| 773 |
+
for i := 0; i < len(args); i++ {
|
| 774 |
+
arg := args[i]
|
| 775 |
+
switch {
|
| 776 |
+
case arg == "--":
|
| 777 |
+
return defaultPluginBootstrapConfigPath(defaultPath)
|
| 778 |
+
case arg == "-config" || arg == "--config":
|
| 779 |
+
if i+1 < len(args) {
|
| 780 |
+
return args[i+1]
|
| 781 |
+
}
|
| 782 |
+
return defaultPluginBootstrapConfigPath(defaultPath)
|
| 783 |
+
case strings.HasPrefix(arg, "-config="):
|
| 784 |
+
return strings.TrimPrefix(arg, "-config=")
|
| 785 |
+
case strings.HasPrefix(arg, "--config="):
|
| 786 |
+
return strings.TrimPrefix(arg, "--config=")
|
| 787 |
+
}
|
| 788 |
+
}
|
| 789 |
+
return defaultPluginBootstrapConfigPath(defaultPath)
|
| 790 |
+
}
|
| 791 |
+
|
| 792 |
+
func defaultPluginBootstrapConfigPath(defaultPath string) string {
|
| 793 |
+
if strings.TrimSpace(defaultPath) != "" {
|
| 794 |
+
return defaultPath
|
| 795 |
+
}
|
| 796 |
+
wd, errGetwd := os.Getwd()
|
| 797 |
+
if errGetwd != nil {
|
| 798 |
+
return "config.yaml"
|
| 799 |
+
}
|
| 800 |
+
return filepath.Join(wd, "config.yaml")
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
func loadPluginBootstrapConfig(path string) *config.Config {
|
| 804 |
+
raw, errReadFile := os.ReadFile(path)
|
| 805 |
+
if errReadFile != nil {
|
| 806 |
+
if !errors.Is(errReadFile, os.ErrNotExist) {
|
| 807 |
+
log.Warnf("failed to read plugin bootstrap config: %v", errReadFile)
|
| 808 |
+
}
|
| 809 |
+
cfg := &config.Config{}
|
| 810 |
+
cfg.NormalizePluginsConfig()
|
| 811 |
+
return cfg
|
| 812 |
+
}
|
| 813 |
+
if len(strings.TrimSpace(string(raw))) == 0 {
|
| 814 |
+
cfg := &config.Config{}
|
| 815 |
+
cfg.NormalizePluginsConfig()
|
| 816 |
+
return cfg
|
| 817 |
+
}
|
| 818 |
+
cfg, errParseConfig := config.ParseConfigBytes(raw)
|
| 819 |
+
if errParseConfig != nil {
|
| 820 |
+
log.Warnf("failed to parse plugin bootstrap config: %v", errParseConfig)
|
| 821 |
+
cfg = &config.Config{}
|
| 822 |
+
cfg.NormalizePluginsConfig()
|
| 823 |
+
return cfg
|
| 824 |
+
}
|
| 825 |
+
return cfg
|
| 826 |
+
}
|
cmd/server/main_test.go
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package main
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"testing"
|
| 5 |
+
|
| 6 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
func TestShouldEnableExampleAPIKeySafeMode(t *testing.T) {
|
| 10 |
+
cfgWithExampleKey := &config.Config{
|
| 11 |
+
SDKConfig: config.SDKConfig{
|
| 12 |
+
APIKeys: []string{"real-key", " your-api-key-1 "},
|
| 13 |
+
},
|
| 14 |
+
}
|
| 15 |
+
cfgWithRealKey := &config.Config{
|
| 16 |
+
SDKConfig: config.SDKConfig{
|
| 17 |
+
APIKeys: []string{"real-key"},
|
| 18 |
+
},
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
tests := []struct {
|
| 22 |
+
name string
|
| 23 |
+
cfg *config.Config
|
| 24 |
+
commandMode bool
|
| 25 |
+
tuiMode bool
|
| 26 |
+
standalone bool
|
| 27 |
+
cloudConfigMissing bool
|
| 28 |
+
homeMode bool
|
| 29 |
+
want bool
|
| 30 |
+
}{
|
| 31 |
+
{
|
| 32 |
+
name: "normal server with example key",
|
| 33 |
+
cfg: cfgWithExampleKey,
|
| 34 |
+
want: true,
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
name: "standalone tui with example key",
|
| 38 |
+
cfg: cfgWithExampleKey,
|
| 39 |
+
tuiMode: true,
|
| 40 |
+
standalone: true,
|
| 41 |
+
want: true,
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
name: "pure tui client is not blocked",
|
| 45 |
+
cfg: cfgWithExampleKey,
|
| 46 |
+
tuiMode: true,
|
| 47 |
+
standalone: false,
|
| 48 |
+
commandMode: false,
|
| 49 |
+
want: false,
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
name: "one-shot command is not blocked",
|
| 53 |
+
cfg: cfgWithExampleKey,
|
| 54 |
+
commandMode: true,
|
| 55 |
+
want: false,
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
name: "home mode is not blocked",
|
| 59 |
+
cfg: cfgWithExampleKey,
|
| 60 |
+
homeMode: true,
|
| 61 |
+
want: false,
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
name: "cloud standby without config is not blocked",
|
| 65 |
+
cfg: cfgWithExampleKey,
|
| 66 |
+
cloudConfigMissing: true,
|
| 67 |
+
want: false,
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
name: "normal server with real key",
|
| 71 |
+
cfg: cfgWithRealKey,
|
| 72 |
+
want: false,
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
name: "nil config",
|
| 76 |
+
cfg: nil,
|
| 77 |
+
want: false,
|
| 78 |
+
},
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
for _, tt := range tests {
|
| 82 |
+
t.Run(tt.name, func(t *testing.T) {
|
| 83 |
+
got := shouldEnableExampleAPIKeySafeMode(tt.cfg, tt.commandMode, tt.tuiMode, tt.standalone, tt.cloudConfigMissing, tt.homeMode)
|
| 84 |
+
if got != tt.want {
|
| 85 |
+
t.Fatalf("shouldEnableExampleAPIKeySafeMode() = %t, want %t", got, tt.want)
|
| 86 |
+
}
|
| 87 |
+
})
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
func TestModelCatalogUpdaterPlan(t *testing.T) {
|
| 92 |
+
tests := []struct {
|
| 93 |
+
name string
|
| 94 |
+
localModel bool
|
| 95 |
+
homeEnabled bool
|
| 96 |
+
wantModels bool
|
| 97 |
+
wantCodexClient bool
|
| 98 |
+
}{
|
| 99 |
+
{
|
| 100 |
+
name: "normal CPA refreshes both catalogs",
|
| 101 |
+
localModel: false,
|
| 102 |
+
homeEnabled: false,
|
| 103 |
+
wantModels: true,
|
| 104 |
+
wantCodexClient: true,
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
name: "home mode keeps models.json local and refreshes codex templates",
|
| 108 |
+
localModel: false,
|
| 109 |
+
homeEnabled: true,
|
| 110 |
+
wantModels: false,
|
| 111 |
+
wantCodexClient: true,
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
name: "local-model disables both remote catalogs",
|
| 115 |
+
localModel: true,
|
| 116 |
+
homeEnabled: false,
|
| 117 |
+
wantModels: false,
|
| 118 |
+
wantCodexClient: false,
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
name: "local-model disables both remote catalogs even under home",
|
| 122 |
+
localModel: true,
|
| 123 |
+
homeEnabled: true,
|
| 124 |
+
wantModels: false,
|
| 125 |
+
wantCodexClient: false,
|
| 126 |
+
},
|
| 127 |
+
}
|
| 128 |
+
for _, tt := range tests {
|
| 129 |
+
t.Run(tt.name, func(t *testing.T) {
|
| 130 |
+
gotModels, gotCodex := modelCatalogUpdaterPlan(tt.localModel, tt.homeEnabled)
|
| 131 |
+
if gotModels != tt.wantModels || gotCodex != tt.wantCodexClient {
|
| 132 |
+
t.Fatalf("modelCatalogUpdaterPlan(%v, %v) = (%v, %v), want (%v, %v)",
|
| 133 |
+
tt.localModel, tt.homeEnabled, gotModels, gotCodex, tt.wantModels, tt.wantCodexClient)
|
| 134 |
+
}
|
| 135 |
+
})
|
| 136 |
+
}
|
| 137 |
+
}
|
cmd/validate_codex_models/main.go
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Command validate_codex_models validates a Codex client model catalog file.
|
| 2 |
+
package main
|
| 3 |
+
|
| 4 |
+
import (
|
| 5 |
+
"flag"
|
| 6 |
+
"fmt"
|
| 7 |
+
"os"
|
| 8 |
+
"strings"
|
| 9 |
+
|
| 10 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
func main() {
|
| 14 |
+
var inputPath string
|
| 15 |
+
flag.StringVar(&inputPath, "file", "", "Codex client model catalog JSON file")
|
| 16 |
+
flag.Parse()
|
| 17 |
+
|
| 18 |
+
if strings.TrimSpace(inputPath) == "" {
|
| 19 |
+
fmt.Fprintln(os.Stderr, "error: --file is required")
|
| 20 |
+
os.Exit(2)
|
| 21 |
+
}
|
| 22 |
+
data, err := os.ReadFile(inputPath)
|
| 23 |
+
if err != nil {
|
| 24 |
+
fmt.Fprintf(os.Stderr, "error: read %s: %v\n", inputPath, err)
|
| 25 |
+
os.Exit(1)
|
| 26 |
+
}
|
| 27 |
+
if err = registry.ValidateCodexClientModelsJSON(data); err != nil {
|
| 28 |
+
fmt.Fprintf(os.Stderr, "error: invalid Codex client model catalog %s: %v\n", inputPath, err)
|
| 29 |
+
os.Exit(1)
|
| 30 |
+
}
|
| 31 |
+
fmt.Printf("Validated Codex client model catalog: %s\n", inputPath)
|
| 32 |
+
}
|
go.mod
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
module github.com/router-for-me/CLIProxyAPI/v7
|
| 2 |
+
|
| 3 |
+
go 1.26.0
|
| 4 |
+
|
| 5 |
+
require (
|
| 6 |
+
github.com/andybalholm/brotli v1.0.6
|
| 7 |
+
github.com/atotto/clipboard v0.1.4
|
| 8 |
+
github.com/charmbracelet/bubbles v1.0.0
|
| 9 |
+
github.com/charmbracelet/bubbletea v1.3.10
|
| 10 |
+
github.com/charmbracelet/lipgloss v1.1.0
|
| 11 |
+
github.com/fsnotify/fsnotify v1.9.0
|
| 12 |
+
github.com/gin-gonic/gin v1.10.1
|
| 13 |
+
github.com/go-git/go-git/v6 v6.0.0-alpha.4.0.20260520124234-0860a7d8a164
|
| 14 |
+
github.com/google/uuid v1.6.0
|
| 15 |
+
github.com/gorilla/websocket v1.5.3
|
| 16 |
+
github.com/jackc/pgx/v5 v5.9.2
|
| 17 |
+
github.com/joho/godotenv v1.5.1
|
| 18 |
+
github.com/klauspost/compress v1.17.4
|
| 19 |
+
github.com/minio/minio-go/v7 v7.0.66
|
| 20 |
+
github.com/pion/ice/v4 v4.3.0
|
| 21 |
+
github.com/pion/interceptor v0.1.45
|
| 22 |
+
github.com/pion/rtp v1.10.4
|
| 23 |
+
github.com/pion/sdp/v3 v3.0.19
|
| 24 |
+
github.com/pion/stun/v3 v3.1.6
|
| 25 |
+
github.com/pion/webrtc/v4 v4.2.17
|
| 26 |
+
github.com/redis/go-redis/v9 v9.19.0
|
| 27 |
+
github.com/refraction-networking/utls v1.8.2
|
| 28 |
+
github.com/sirupsen/logrus v1.9.3
|
| 29 |
+
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966
|
| 30 |
+
github.com/tidwall/gjson v1.18.0
|
| 31 |
+
github.com/tidwall/sjson v1.2.5
|
| 32 |
+
github.com/tiktoken-go/tokenizer v0.8.1
|
| 33 |
+
golang.org/x/crypto v0.54.0
|
| 34 |
+
golang.org/x/net v0.57.0
|
| 35 |
+
golang.org/x/oauth2 v0.30.0
|
| 36 |
+
golang.org/x/sync v0.22.0
|
| 37 |
+
golang.org/x/sys v0.47.0
|
| 38 |
+
gopkg.in/natefinch/lumberjack.v2 v2.2.1
|
| 39 |
+
gopkg.in/yaml.v3 v3.0.1
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
require (
|
| 43 |
+
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
| 44 |
+
github.com/dlclark/regexp2/v2 v2.5.1 // indirect
|
| 45 |
+
github.com/pion/datachannel v1.6.2 // indirect
|
| 46 |
+
github.com/pion/dtls/v3 v3.1.5 // indirect
|
| 47 |
+
github.com/pion/logging v0.2.4 // indirect
|
| 48 |
+
github.com/pion/mdns/v2 v2.1.0 // indirect
|
| 49 |
+
github.com/pion/randutil v0.1.0 // indirect
|
| 50 |
+
github.com/pion/rtcp v1.2.17 // indirect
|
| 51 |
+
github.com/pion/sctp v1.11.0 // indirect
|
| 52 |
+
github.com/pion/srtp/v3 v3.0.12 // indirect
|
| 53 |
+
github.com/pion/transport/v4 v4.0.2 // indirect
|
| 54 |
+
github.com/pion/turn/v5 v5.0.12 // indirect
|
| 55 |
+
github.com/rogpeppe/go-internal v1.15.0 // indirect
|
| 56 |
+
github.com/wlynxg/anet v0.0.5 // indirect
|
| 57 |
+
go.uber.org/atomic v1.11.0 // indirect
|
| 58 |
+
golang.org/x/time v0.14.0 // indirect
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
require (
|
| 62 |
+
cloud.google.com/go/compute/metadata v0.3.0 // indirect
|
| 63 |
+
github.com/Microsoft/go-winio v0.6.2 // indirect
|
| 64 |
+
github.com/ProtonMail/go-crypto v1.4.1 // indirect
|
| 65 |
+
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
| 66 |
+
github.com/bytedance/sonic v1.11.6 // indirect
|
| 67 |
+
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
| 68 |
+
github.com/charmbracelet/colorprofile v0.4.1 // indirect
|
| 69 |
+
github.com/charmbracelet/x/ansi v0.11.6 // indirect
|
| 70 |
+
github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
|
| 71 |
+
github.com/charmbracelet/x/term v0.2.2 // indirect
|
| 72 |
+
github.com/clipperhouse/displaywidth v0.9.0 // indirect
|
| 73 |
+
github.com/clipperhouse/stringish v0.1.1 // indirect
|
| 74 |
+
github.com/clipperhouse/uax29/v2 v2.5.0 // indirect
|
| 75 |
+
github.com/cloudflare/circl v1.6.3 // indirect
|
| 76 |
+
github.com/cloudwego/base64x v0.1.4 // indirect
|
| 77 |
+
github.com/cloudwego/iasm v0.2.0 // indirect
|
| 78 |
+
github.com/dustin/go-humanize v1.0.1 // indirect
|
| 79 |
+
github.com/emirpasic/gods v1.18.1 // indirect
|
| 80 |
+
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
|
| 81 |
+
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
| 82 |
+
github.com/gin-contrib/sse v0.1.0 // indirect
|
| 83 |
+
github.com/go-git/gcfg/v2 v2.0.2 // indirect
|
| 84 |
+
github.com/go-git/go-billy/v6 v6.0.0-alpha.1.0.20260519112248-0095b064a6c6 // indirect
|
| 85 |
+
github.com/go-playground/locales v0.14.1 // indirect
|
| 86 |
+
github.com/go-playground/universal-translator v0.18.1 // indirect
|
| 87 |
+
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
| 88 |
+
github.com/goccy/go-json v0.10.2 // indirect
|
| 89 |
+
github.com/jackc/pgpassfile v1.0.0 // indirect
|
| 90 |
+
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
| 91 |
+
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
| 92 |
+
github.com/json-iterator/go v1.1.12 // indirect
|
| 93 |
+
github.com/kevinburke/ssh_config v1.6.0 // indirect
|
| 94 |
+
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
| 95 |
+
github.com/leodido/go-urn v1.4.0 // indirect
|
| 96 |
+
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
|
| 97 |
+
github.com/mattn/go-isatty v0.0.20 // indirect
|
| 98 |
+
github.com/mattn/go-localereader v0.0.1 // indirect
|
| 99 |
+
github.com/mattn/go-runewidth v0.0.19 // indirect
|
| 100 |
+
github.com/minio/md5-simd v1.1.2 // indirect
|
| 101 |
+
github.com/minio/sha256-simd v1.0.1 // indirect
|
| 102 |
+
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
| 103 |
+
github.com/modern-go/reflect2 v1.0.2 // indirect
|
| 104 |
+
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
|
| 105 |
+
github.com/muesli/cancelreader v0.2.2 // indirect
|
| 106 |
+
github.com/muesli/termenv v0.16.0 // indirect
|
| 107 |
+
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
| 108 |
+
github.com/pierrec/xxHash v0.1.5
|
| 109 |
+
github.com/pjbgf/sha1cd v0.6.0 // indirect
|
| 110 |
+
github.com/rivo/uniseg v0.4.7 // indirect
|
| 111 |
+
github.com/rs/xid v1.5.0 // indirect
|
| 112 |
+
github.com/sergi/go-diff v1.4.0 // indirect
|
| 113 |
+
github.com/tidwall/match v1.1.1 // indirect
|
| 114 |
+
github.com/tidwall/pretty v1.2.0 // indirect
|
| 115 |
+
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
| 116 |
+
github.com/ugorji/go/codec v1.2.12 // indirect
|
| 117 |
+
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
| 118 |
+
golang.org/x/arch v0.8.0 // indirect
|
| 119 |
+
golang.org/x/text v0.40.0 // indirect
|
| 120 |
+
google.golang.org/protobuf v1.34.1
|
| 121 |
+
gopkg.in/ini.v1 v1.67.0 // indirect
|
| 122 |
+
)
|
go.sum
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc=
|
| 2 |
+
cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=
|
| 3 |
+
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
| 4 |
+
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
| 5 |
+
github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM=
|
| 6 |
+
github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo=
|
| 7 |
+
github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI=
|
| 8 |
+
github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
| 9 |
+
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
|
| 10 |
+
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
|
| 11 |
+
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
|
| 12 |
+
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
|
| 13 |
+
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
|
| 14 |
+
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
| 15 |
+
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
|
| 16 |
+
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
|
| 17 |
+
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
| 18 |
+
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
| 19 |
+
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
| 20 |
+
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
| 21 |
+
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
| 22 |
+
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
| 23 |
+
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
| 24 |
+
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
| 25 |
+
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
| 26 |
+
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
| 27 |
+
github.com/charmbracelet/bubbles v1.0.0 h1:12J8/ak/uCZEMQ6KU7pcfwceyjLlWsDLAxB5fXonfvc=
|
| 28 |
+
github.com/charmbracelet/bubbles v1.0.0/go.mod h1:9d/Zd5GdnauMI5ivUIVisuEm3ave1XwXtD1ckyV6r3E=
|
| 29 |
+
github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
|
| 30 |
+
github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
|
| 31 |
+
github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk=
|
| 32 |
+
github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk=
|
| 33 |
+
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
|
| 34 |
+
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
|
| 35 |
+
github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8=
|
| 36 |
+
github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=
|
| 37 |
+
github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI=
|
| 38 |
+
github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q=
|
| 39 |
+
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
|
| 40 |
+
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
|
| 41 |
+
github.com/clipperhouse/displaywidth v0.9.0 h1:Qb4KOhYwRiN3viMv1v/3cTBlz3AcAZX3+y9OLhMtAtA=
|
| 42 |
+
github.com/clipperhouse/displaywidth v0.9.0/go.mod h1:aCAAqTlh4GIVkhQnJpbL0T/WfcrJXHcj8C0yjYcjOZA=
|
| 43 |
+
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
|
| 44 |
+
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
|
| 45 |
+
github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U=
|
| 46 |
+
github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
|
| 47 |
+
github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
|
| 48 |
+
github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
|
| 49 |
+
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
| 50 |
+
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
| 51 |
+
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
| 52 |
+
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
| 53 |
+
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
| 54 |
+
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
| 55 |
+
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
| 56 |
+
github.com/dlclark/regexp2/v2 v2.5.1 h1:E5Ug7Dh264W1ymdySmiHNcDG7fmsR307APCE5R07a20=
|
| 57 |
+
github.com/dlclark/regexp2/v2 v2.5.1/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU=
|
| 58 |
+
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
| 59 |
+
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
| 60 |
+
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
|
| 61 |
+
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
|
| 62 |
+
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
|
| 63 |
+
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
|
| 64 |
+
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
| 65 |
+
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
| 66 |
+
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
| 67 |
+
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
| 68 |
+
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
| 69 |
+
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
| 70 |
+
github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ=
|
| 71 |
+
github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
| 72 |
+
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
|
| 73 |
+
github.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=
|
| 74 |
+
github.com/go-git/gcfg/v2 v2.0.2 h1:MY5SIIfTGGEMhdA7d7JePuVVxtKL7Hp+ApGDJAJ7dpo=
|
| 75 |
+
github.com/go-git/gcfg/v2 v2.0.2/go.mod h1:/lv2NsxvhepuMrldsFilrgct6pxzpGdSRC13ydTLSLs=
|
| 76 |
+
github.com/go-git/go-billy/v6 v6.0.0-alpha.1.0.20260519112248-0095b064a6c6 h1:AaQOU2NVLxnBGWkv5YSoxomcDCqlaqfCW0t00pNKtnk=
|
| 77 |
+
github.com/go-git/go-billy/v6 v6.0.0-alpha.1.0.20260519112248-0095b064a6c6/go.mod h1:eaCUpHbedW7//EwcYmUDfJe2N6sJC9O12AT0OTqJR1E=
|
| 78 |
+
github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1 h1:gmqi2jvsreu0s8JMLylYDFq4sbjHwwlhktMw0DUg3mA=
|
| 79 |
+
github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1/go.mod h1:ECf1MqJlBdYpKggBrOXjo/0EnvRZx6D++I86UYjPgAQ=
|
| 80 |
+
github.com/go-git/go-git/v6 v6.0.0-alpha.4.0.20260520124234-0860a7d8a164 h1:chk74EHqDOHvIx/WH43JfdLImedxN98qGvEFd7WYgus=
|
| 81 |
+
github.com/go-git/go-git/v6 v6.0.0-alpha.4.0.20260520124234-0860a7d8a164/go.mod h1:OTUSi3RzPFoC0j/+uxHdVG1X/xXz84QCxLzYvXRvyXk=
|
| 82 |
+
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
| 83 |
+
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
| 84 |
+
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
| 85 |
+
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
| 86 |
+
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
| 87 |
+
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
| 88 |
+
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
|
| 89 |
+
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
| 90 |
+
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
| 91 |
+
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
| 92 |
+
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
| 93 |
+
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
| 94 |
+
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
| 95 |
+
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
| 96 |
+
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
| 97 |
+
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
| 98 |
+
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
| 99 |
+
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
| 100 |
+
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
| 101 |
+
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
| 102 |
+
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
| 103 |
+
github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
|
| 104 |
+
github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
| 105 |
+
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
| 106 |
+
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
| 107 |
+
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
| 108 |
+
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
| 109 |
+
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
| 110 |
+
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
| 111 |
+
github.com/kevinburke/ssh_config v1.6.0 h1:J1FBfmuVosPHf5GRdltRLhPJtJpTlMdKTBjRgTaQBFY=
|
| 112 |
+
github.com/kevinburke/ssh_config v1.6.0/go.mod h1:q2RIzfka+BXARoNexmF9gkxEX7DmvbW9P4hIVx2Kg4M=
|
| 113 |
+
github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4=
|
| 114 |
+
github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=
|
| 115 |
+
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
| 116 |
+
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
| 117 |
+
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
| 118 |
+
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
| 119 |
+
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
| 120 |
+
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
| 121 |
+
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
| 122 |
+
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
| 123 |
+
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
| 124 |
+
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
| 125 |
+
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
| 126 |
+
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
| 127 |
+
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
| 128 |
+
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
| 129 |
+
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
|
| 130 |
+
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
| 131 |
+
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
| 132 |
+
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
| 133 |
+
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
|
| 134 |
+
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
|
| 135 |
+
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
|
| 136 |
+
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
| 137 |
+
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
| 138 |
+
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
| 139 |
+
github.com/minio/minio-go/v7 v7.0.66 h1:bnTOXOHjOqv/gcMuiVbN9o2ngRItvqE774dG9nq0Dzw=
|
| 140 |
+
github.com/minio/minio-go/v7 v7.0.66/go.mod h1:DHAgmyQEGdW3Cif0UooKOyrT3Vxs82zNdV6tkKhRtbs=
|
| 141 |
+
github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM=
|
| 142 |
+
github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8=
|
| 143 |
+
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
| 144 |
+
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
| 145 |
+
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
| 146 |
+
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
| 147 |
+
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
| 148 |
+
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
|
| 149 |
+
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
|
| 150 |
+
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
| 151 |
+
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
| 152 |
+
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
|
| 153 |
+
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
|
| 154 |
+
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
| 155 |
+
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
| 156 |
+
github.com/pierrec/xxHash v0.1.5 h1:n/jBpwTHiER4xYvK3/CdPVnLDPchj8eTJFFLUb4QHBo=
|
| 157 |
+
github.com/pierrec/xxHash v0.1.5/go.mod h1:w2waW5Zoa/Wc4Yqe0wgrIYAGKqRMf7czn2HNKXmuL+I=
|
| 158 |
+
github.com/pion/datachannel v1.6.2 h1:7EXQ8TH3vTouBUdRWYbcX2edSx9Yj6k5zl5P+qyxEPc=
|
| 159 |
+
github.com/pion/datachannel v1.6.2/go.mod h1:pzbdAZvyGtXbcHM1hBbsFaOTf40lZizU/dNlvVOak6E=
|
| 160 |
+
github.com/pion/dtls/v3 v3.1.5 h1:9xJtVsHwMYeSjPp5Hh1FTis4DchnQWtnOa5o+6ygqfc=
|
| 161 |
+
github.com/pion/dtls/v3 v3.1.5/go.mod h1:gz1K4jg6c+fq86oQMH4pilpCEOEPwmEr2jY+VcF/mkU=
|
| 162 |
+
github.com/pion/ice/v4 v4.3.0 h1:X8l4s9zV2HeTKX33nulWAFXAEo5KhIVzOsY62/3t/LM=
|
| 163 |
+
github.com/pion/ice/v4 v4.3.0/go.mod h1:obAyD+J+Hzs7QA7Y8YXHp5uIn6gb7z87pKedXZkrcFU=
|
| 164 |
+
github.com/pion/interceptor v0.1.45 h1:6PUo/5829bIfRFIPPJQzuDn8EjxRTSB/CSD7QVCOaqo=
|
| 165 |
+
github.com/pion/interceptor v0.1.45/go.mod h1:gNDYM/uFKcLe/B3gS2/7+aw6z+RDiMy2qKTnF1LO31w=
|
| 166 |
+
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
|
| 167 |
+
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
|
| 168 |
+
github.com/pion/mdns/v2 v2.1.0 h1:3IJ9+Xio6tWYjhN6WwuY142P/1jA0D5ERaIqawg/fOY=
|
| 169 |
+
github.com/pion/mdns/v2 v2.1.0/go.mod h1:pcez23GdynwcfRU1977qKU0mDxSeucttSHbCSfFOd9A=
|
| 170 |
+
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
|
| 171 |
+
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
|
| 172 |
+
github.com/pion/rtcp v1.2.17 h1:PxiT6L79yPZKtXIsXdG1eakBl6dtBj4x+4oVEL0DlSw=
|
| 173 |
+
github.com/pion/rtcp v1.2.17/go.mod h1:7kBpuBJaWwax4hzc/pgexY8vkOpvh8atgYDbaKZq0iU=
|
| 174 |
+
github.com/pion/rtp v1.10.4 h1:4sCUwUd35Nllcpyp8V7lRgb4DV/ulHJaRTjbrkAcpQ4=
|
| 175 |
+
github.com/pion/rtp v1.10.4/go.mod h1:Au8fc6cEByy8RLTwKTQTEeQqDB/SJDxwL4mZuxYA5Pk=
|
| 176 |
+
github.com/pion/sctp v1.11.0 h1:sAxv9Qp3uIcaF5wu1XntwshtnW93CEuxhpkYzSbnfMs=
|
| 177 |
+
github.com/pion/sctp v1.11.0/go.mod h1:7KFmTwLcoYgJs/Z+99nJvsWL0qDpuyloSI0RbAqlrz0=
|
| 178 |
+
github.com/pion/sdp/v3 v3.0.19 h1:1VMKs3gIkTQV5M3hNKfTAPrDXSNrYtOlmOD8+mSZUGQ=
|
| 179 |
+
github.com/pion/sdp/v3 v3.0.19/go.mod h1:dE5WOSlzXrtiE/iuZqe9n+AcEbOjtAd3k5m5NtlV/qU=
|
| 180 |
+
github.com/pion/srtp/v3 v3.0.12 h1:U7V17bckl7sI4mb3sepiojByDuBY0wNCqQE+6IlQBbc=
|
| 181 |
+
github.com/pion/srtp/v3 v3.0.12/go.mod h1:EeZOi/sd6glM1EXapg051gdNWO9yWT1YSsgQ4SlJkns=
|
| 182 |
+
github.com/pion/stun/v3 v3.1.6 h1:WnhsD0eHCiwCfKNkVx0VJJwr2Y3eV4Ueih3KJ+dfZy8=
|
| 183 |
+
github.com/pion/stun/v3 v3.1.6/go.mod h1:zRUghXSQU32Lx5orJsz3uYMkIihweXb3mu5gIns02fs=
|
| 184 |
+
github.com/pion/transport/v3 v3.1.1 h1:Tr684+fnnKlhPceU+ICdrw6KKkTms+5qHMgw6bIkYOM=
|
| 185 |
+
github.com/pion/transport/v3 v3.1.1/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ=
|
| 186 |
+
github.com/pion/transport/v4 v4.0.2 h1:ifYlPqNwsy6aKQ9y8yzxXlHae5431ZrH2avkD/Rn6Tk=
|
| 187 |
+
github.com/pion/transport/v4 v4.0.2/go.mod h1:06hFI+jCFcok2X2MekVufNZ/uzNZXivGBPfviSVcjgM=
|
| 188 |
+
github.com/pion/turn/v5 v5.0.12 h1:6+b69ivQQXSlyfkp2AKripqD2k3W32qXK8QzCzpJWPI=
|
| 189 |
+
github.com/pion/turn/v5 v5.0.12/go.mod h1:CQACsRDJtjQ+6RSrGHrS2PCIerLwbW3uqXRqOvtjAFg=
|
| 190 |
+
github.com/pion/webrtc/v4 v4.2.17 h1:no7rmszKV1jkGz7GvErGp/VlnzGu/koVHO9CRjItiVU=
|
| 191 |
+
github.com/pion/webrtc/v4 v4.2.17/go.mod h1:xRtWZDJ0FbyW98WVCCgOvxaBM5gxqqJa7pCc4f+x/LI=
|
| 192 |
+
github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU=
|
| 193 |
+
github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
|
| 194 |
+
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
| 195 |
+
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
| 196 |
+
github.com/redis/go-redis/v9 v9.19.0 h1:XPVaaPSnG6RhYf7p+rmSa9zZfeVAnWsH5h3lxthOm/k=
|
| 197 |
+
github.com/redis/go-redis/v9 v9.19.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
|
| 198 |
+
github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEvV+S9iJ2IdQo=
|
| 199 |
+
github.com/refraction-networking/utls v1.8.2/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM=
|
| 200 |
+
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
| 201 |
+
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
| 202 |
+
github.com/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc=
|
| 203 |
+
github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
|
| 204 |
+
github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc=
|
| 205 |
+
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
| 206 |
+
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
|
| 207 |
+
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
| 208 |
+
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
| 209 |
+
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
| 210 |
+
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA=
|
| 211 |
+
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog=
|
| 212 |
+
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
| 213 |
+
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
| 214 |
+
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
| 215 |
+
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
| 216 |
+
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
| 217 |
+
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
| 218 |
+
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
| 219 |
+
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
| 220 |
+
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
| 221 |
+
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
| 222 |
+
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
| 223 |
+
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
| 224 |
+
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
| 225 |
+
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
| 226 |
+
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
| 227 |
+
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
| 228 |
+
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
| 229 |
+
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
| 230 |
+
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
| 231 |
+
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
|
| 232 |
+
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
| 233 |
+
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
|
| 234 |
+
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
| 235 |
+
github.com/tiktoken-go/tokenizer v0.8.1 h1:4obDoB6/dhdBt9xMweX4nww5cjdOq/nYF4ecwPq2+mg=
|
| 236 |
+
github.com/tiktoken-go/tokenizer v0.8.1/go.mod h1:eLA0t6nGvn9mDc7gt90qt7pMat+gE9ViqwQ6l9B+tA4=
|
| 237 |
+
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
| 238 |
+
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
| 239 |
+
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
| 240 |
+
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
| 241 |
+
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
|
| 242 |
+
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
|
| 243 |
+
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
|
| 244 |
+
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
| 245 |
+
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
| 246 |
+
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
| 247 |
+
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
| 248 |
+
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
| 249 |
+
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
| 250 |
+
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
| 251 |
+
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
| 252 |
+
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
| 253 |
+
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
| 254 |
+
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
|
| 255 |
+
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
|
| 256 |
+
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
| 257 |
+
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
| 258 |
+
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
|
| 259 |
+
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
|
| 260 |
+
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
| 261 |
+
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
| 262 |
+
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
| 263 |
+
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
| 264 |
+
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
| 265 |
+
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
| 266 |
+
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
| 267 |
+
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
| 268 |
+
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
| 269 |
+
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
| 270 |
+
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
| 271 |
+
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
| 272 |
+
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
| 273 |
+
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
| 274 |
+
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
| 275 |
+
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
| 276 |
+
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
| 277 |
+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
| 278 |
+
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
| 279 |
+
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
| 280 |
+
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
| 281 |
+
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
| 282 |
+
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
| 283 |
+
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
| 284 |
+
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
| 285 |
+
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
| 286 |
+
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
| 287 |
+
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
| 288 |
+
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
| 289 |
+
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviU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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package configaccess
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"net/http"
|
| 6 |
+
"strings"
|
| 7 |
+
|
| 8 |
+
sdkaccess "github.com/router-for-me/CLIProxyAPI/v7/sdk/access"
|
| 9 |
+
sdkconfig "github.com/router-for-me/CLIProxyAPI/v7/sdk/config"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
// Register ensures the config-access provider is available to the access manager.
|
| 13 |
+
func Register(cfg *sdkconfig.SDKConfig) {
|
| 14 |
+
if cfg == nil {
|
| 15 |
+
sdkaccess.UnregisterProvider(sdkaccess.AccessProviderTypeConfigAPIKey)
|
| 16 |
+
return
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
keys := normalizeKeys(cfg.APIKeys)
|
| 20 |
+
if len(keys) == 0 {
|
| 21 |
+
sdkaccess.UnregisterProvider(sdkaccess.AccessProviderTypeConfigAPIKey)
|
| 22 |
+
return
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
sdkaccess.RegisterProvider(
|
| 26 |
+
sdkaccess.AccessProviderTypeConfigAPIKey,
|
| 27 |
+
newProvider(sdkaccess.DefaultAccessProviderName, keys),
|
| 28 |
+
)
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
type provider struct {
|
| 32 |
+
name string
|
| 33 |
+
keys map[string]struct{}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
func newProvider(name string, keys []string) *provider {
|
| 37 |
+
providerName := strings.TrimSpace(name)
|
| 38 |
+
if providerName == "" {
|
| 39 |
+
providerName = sdkaccess.DefaultAccessProviderName
|
| 40 |
+
}
|
| 41 |
+
keySet := make(map[string]struct{}, len(keys))
|
| 42 |
+
for _, key := range keys {
|
| 43 |
+
keySet[key] = struct{}{}
|
| 44 |
+
}
|
| 45 |
+
return &provider{name: providerName, keys: keySet}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
func (p *provider) Identifier() string {
|
| 49 |
+
if p == nil || p.name == "" {
|
| 50 |
+
return sdkaccess.DefaultAccessProviderName
|
| 51 |
+
}
|
| 52 |
+
return p.name
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
func (p *provider) Authenticate(_ context.Context, r *http.Request) (*sdkaccess.Result, *sdkaccess.AuthError) {
|
| 56 |
+
if p == nil {
|
| 57 |
+
return nil, sdkaccess.NewNotHandledError()
|
| 58 |
+
}
|
| 59 |
+
if len(p.keys) == 0 {
|
| 60 |
+
return nil, sdkaccess.NewNotHandledError()
|
| 61 |
+
}
|
| 62 |
+
authHeader := r.Header.Get("Authorization")
|
| 63 |
+
authHeaderGoogle := r.Header.Get("X-Goog-Api-Key")
|
| 64 |
+
authHeaderAnthropic := r.Header.Get("X-Api-Key")
|
| 65 |
+
queryKey := ""
|
| 66 |
+
queryAuthToken := ""
|
| 67 |
+
if r.URL != nil {
|
| 68 |
+
queryKey = r.URL.Query().Get("key")
|
| 69 |
+
queryAuthToken = r.URL.Query().Get("auth_token")
|
| 70 |
+
}
|
| 71 |
+
if authHeader == "" && authHeaderGoogle == "" && authHeaderAnthropic == "" && queryKey == "" && queryAuthToken == "" {
|
| 72 |
+
return nil, sdkaccess.NewNoCredentialsError()
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
apiKey := extractBearerToken(authHeader)
|
| 76 |
+
|
| 77 |
+
candidates := []struct {
|
| 78 |
+
value string
|
| 79 |
+
source string
|
| 80 |
+
}{
|
| 81 |
+
{apiKey, "authorization"},
|
| 82 |
+
{authHeaderGoogle, "x-goog-api-key"},
|
| 83 |
+
{authHeaderAnthropic, "x-api-key"},
|
| 84 |
+
{queryKey, "query-key"},
|
| 85 |
+
{queryAuthToken, "query-auth-token"},
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
for _, candidate := range candidates {
|
| 89 |
+
if candidate.value == "" {
|
| 90 |
+
continue
|
| 91 |
+
}
|
| 92 |
+
if _, ok := p.keys[candidate.value]; ok {
|
| 93 |
+
return &sdkaccess.Result{
|
| 94 |
+
Provider: p.Identifier(),
|
| 95 |
+
Principal: candidate.value,
|
| 96 |
+
Metadata: map[string]string{
|
| 97 |
+
"source": candidate.source,
|
| 98 |
+
},
|
| 99 |
+
}, nil
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
return nil, sdkaccess.NewInvalidCredentialError()
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
func extractBearerToken(header string) string {
|
| 107 |
+
if header == "" {
|
| 108 |
+
return ""
|
| 109 |
+
}
|
| 110 |
+
parts := strings.SplitN(header, " ", 2)
|
| 111 |
+
if len(parts) != 2 {
|
| 112 |
+
return header
|
| 113 |
+
}
|
| 114 |
+
if strings.ToLower(parts[0]) != "bearer" {
|
| 115 |
+
return header
|
| 116 |
+
}
|
| 117 |
+
return strings.TrimSpace(parts[1])
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
func normalizeKeys(keys []string) []string {
|
| 121 |
+
if len(keys) == 0 {
|
| 122 |
+
return nil
|
| 123 |
+
}
|
| 124 |
+
normalized := make([]string, 0, len(keys))
|
| 125 |
+
seen := make(map[string]struct{}, len(keys))
|
| 126 |
+
for _, key := range keys {
|
| 127 |
+
trimmedKey := strings.TrimSpace(key)
|
| 128 |
+
if trimmedKey == "" {
|
| 129 |
+
continue
|
| 130 |
+
}
|
| 131 |
+
if _, exists := seen[trimmedKey]; exists {
|
| 132 |
+
continue
|
| 133 |
+
}
|
| 134 |
+
seen[trimmedKey] = struct{}{}
|
| 135 |
+
normalized = append(normalized, trimmedKey)
|
| 136 |
+
}
|
| 137 |
+
if len(normalized) == 0 {
|
| 138 |
+
return nil
|
| 139 |
+
}
|
| 140 |
+
return normalized
|
| 141 |
+
}
|
internal/access/reconcile.go
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package access
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"fmt"
|
| 5 |
+
"reflect"
|
| 6 |
+
"sort"
|
| 7 |
+
"strings"
|
| 8 |
+
|
| 9 |
+
configaccess "github.com/router-for-me/CLIProxyAPI/v7/internal/access/config_access"
|
| 10 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 11 |
+
sdkaccess "github.com/router-for-me/CLIProxyAPI/v7/sdk/access"
|
| 12 |
+
log "github.com/sirupsen/logrus"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
// ReconcileProviders builds the desired provider list by reusing existing providers when possible
|
| 16 |
+
// and creating or removing providers only when their configuration changed. It returns the final
|
| 17 |
+
// ordered provider slice along with the identifiers of providers that were added, updated, or
|
| 18 |
+
// removed compared to the previous configuration.
|
| 19 |
+
func ReconcileProviders(oldCfg, newCfg *config.Config, existing []sdkaccess.Provider) (result []sdkaccess.Provider, added, updated, removed []string, err error) {
|
| 20 |
+
_ = oldCfg
|
| 21 |
+
if newCfg == nil {
|
| 22 |
+
return nil, nil, nil, nil, nil
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
result = sdkaccess.RegisteredProviders()
|
| 26 |
+
|
| 27 |
+
existingMap := make(map[string]sdkaccess.Provider, len(existing))
|
| 28 |
+
for _, provider := range existing {
|
| 29 |
+
providerID := identifierFromProvider(provider)
|
| 30 |
+
if providerID == "" {
|
| 31 |
+
continue
|
| 32 |
+
}
|
| 33 |
+
existingMap[providerID] = provider
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
finalIDs := make(map[string]struct{}, len(result))
|
| 37 |
+
|
| 38 |
+
isInlineProvider := func(id string) bool {
|
| 39 |
+
return strings.EqualFold(id, sdkaccess.DefaultAccessProviderName)
|
| 40 |
+
}
|
| 41 |
+
appendChange := func(list *[]string, id string) {
|
| 42 |
+
if isInlineProvider(id) {
|
| 43 |
+
return
|
| 44 |
+
}
|
| 45 |
+
*list = append(*list, id)
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
for _, provider := range result {
|
| 49 |
+
providerID := identifierFromProvider(provider)
|
| 50 |
+
if providerID == "" {
|
| 51 |
+
continue
|
| 52 |
+
}
|
| 53 |
+
finalIDs[providerID] = struct{}{}
|
| 54 |
+
|
| 55 |
+
existingProvider, exists := existingMap[providerID]
|
| 56 |
+
if !exists {
|
| 57 |
+
appendChange(&added, providerID)
|
| 58 |
+
continue
|
| 59 |
+
}
|
| 60 |
+
if !providerInstanceEqual(existingProvider, provider) {
|
| 61 |
+
appendChange(&updated, providerID)
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
for providerID := range existingMap {
|
| 66 |
+
if _, exists := finalIDs[providerID]; exists {
|
| 67 |
+
continue
|
| 68 |
+
}
|
| 69 |
+
appendChange(&removed, providerID)
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
sort.Strings(added)
|
| 73 |
+
sort.Strings(updated)
|
| 74 |
+
sort.Strings(removed)
|
| 75 |
+
|
| 76 |
+
return result, added, updated, removed, nil
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
// ApplyAccessProviders reconciles the configured access providers against the
|
| 80 |
+
// currently registered providers and updates the manager. It logs a concise
|
| 81 |
+
// summary of the detected changes and returns whether any provider changed.
|
| 82 |
+
func ApplyAccessProviders(manager *sdkaccess.Manager, oldCfg, newCfg *config.Config) (bool, error) {
|
| 83 |
+
if manager == nil || newCfg == nil {
|
| 84 |
+
return false, nil
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
existing := manager.Providers()
|
| 88 |
+
configaccess.Register(&newCfg.SDKConfig)
|
| 89 |
+
providers, added, updated, removed, err := ReconcileProviders(oldCfg, newCfg, existing)
|
| 90 |
+
if err != nil {
|
| 91 |
+
log.Errorf("failed to reconcile request auth providers: %v", err)
|
| 92 |
+
return false, fmt.Errorf("reconciling access providers: %w", err)
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
manager.SetProviders(providers)
|
| 96 |
+
|
| 97 |
+
if len(added)+len(updated)+len(removed) > 0 {
|
| 98 |
+
log.Debugf("auth providers reconciled (added=%d updated=%d removed=%d)", len(added), len(updated), len(removed))
|
| 99 |
+
log.Debugf("auth providers changes details - added=%v updated=%v removed=%v", added, updated, removed)
|
| 100 |
+
return true, nil
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
log.Debug("auth providers unchanged after config update")
|
| 104 |
+
return false, nil
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
func identifierFromProvider(provider sdkaccess.Provider) string {
|
| 108 |
+
if provider == nil {
|
| 109 |
+
return ""
|
| 110 |
+
}
|
| 111 |
+
return strings.TrimSpace(provider.Identifier())
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
func providerInstanceEqual(a, b sdkaccess.Provider) bool {
|
| 115 |
+
if a == nil || b == nil {
|
| 116 |
+
return a == nil && b == nil
|
| 117 |
+
}
|
| 118 |
+
if reflect.TypeOf(a) != reflect.TypeOf(b) {
|
| 119 |
+
return false
|
| 120 |
+
}
|
| 121 |
+
valueA := reflect.ValueOf(a)
|
| 122 |
+
valueB := reflect.ValueOf(b)
|
| 123 |
+
if valueA.Kind() == reflect.Pointer && valueB.Kind() == reflect.Pointer {
|
| 124 |
+
return valueA.Pointer() == valueB.Pointer()
|
| 125 |
+
}
|
| 126 |
+
return reflect.DeepEqual(a, b)
|
| 127 |
+
}
|
internal/api/buffered_conn.go
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package api
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"bufio"
|
| 5 |
+
"crypto/tls"
|
| 6 |
+
"net"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
type bufferedConn struct {
|
| 10 |
+
net.Conn
|
| 11 |
+
reader *bufio.Reader
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
func (c *bufferedConn) Read(p []byte) (int, error) {
|
| 15 |
+
if c == nil {
|
| 16 |
+
return 0, net.ErrClosed
|
| 17 |
+
}
|
| 18 |
+
if c.reader == nil {
|
| 19 |
+
return c.Conn.Read(p)
|
| 20 |
+
}
|
| 21 |
+
return c.reader.Read(p)
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
func (c *bufferedConn) ConnectionState() tls.ConnectionState {
|
| 25 |
+
if c == nil || c.Conn == nil {
|
| 26 |
+
return tls.ConnectionState{}
|
| 27 |
+
}
|
| 28 |
+
if stater, ok := c.Conn.(interface{ ConnectionState() tls.ConnectionState }); ok {
|
| 29 |
+
return stater.ConnectionState()
|
| 30 |
+
}
|
| 31 |
+
return tls.ConnectionState{}
|
| 32 |
+
}
|
internal/api/handlers/management/api_key_usage.go
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
"strings"
|
| 6 |
+
"time"
|
| 7 |
+
|
| 8 |
+
"github.com/gin-gonic/gin"
|
| 9 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
type apiKeyUsageEntry struct {
|
| 13 |
+
Success int64 `json:"success"`
|
| 14 |
+
Failed int64 `json:"failed"`
|
| 15 |
+
RecentRequests []coreauth.RecentRequestBucket `json:"recent_requests"`
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
func mergeRecentRequestBuckets(dst, src []coreauth.RecentRequestBucket) []coreauth.RecentRequestBucket {
|
| 19 |
+
if len(dst) == 0 {
|
| 20 |
+
return src
|
| 21 |
+
}
|
| 22 |
+
if len(src) == 0 {
|
| 23 |
+
return dst
|
| 24 |
+
}
|
| 25 |
+
if len(dst) != len(src) {
|
| 26 |
+
n := len(dst)
|
| 27 |
+
if len(src) < n {
|
| 28 |
+
n = len(src)
|
| 29 |
+
}
|
| 30 |
+
for i := 0; i < n; i++ {
|
| 31 |
+
dst[i].Success += src[i].Success
|
| 32 |
+
dst[i].Failed += src[i].Failed
|
| 33 |
+
}
|
| 34 |
+
return dst
|
| 35 |
+
}
|
| 36 |
+
for i := range dst {
|
| 37 |
+
dst[i].Success += src[i].Success
|
| 38 |
+
dst[i].Failed += src[i].Failed
|
| 39 |
+
}
|
| 40 |
+
return dst
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
func apiKeyUsageProviderKey(auth *coreauth.Auth) string {
|
| 44 |
+
provider := strings.ToLower(strings.TrimSpace(auth.Provider))
|
| 45 |
+
if auth.Attributes != nil {
|
| 46 |
+
if compatName := strings.TrimSpace(auth.Attributes["compat_name"]); compatName != "" {
|
| 47 |
+
provider = strings.ToLower(compatName)
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
if provider == "" {
|
| 51 |
+
return "unknown"
|
| 52 |
+
}
|
| 53 |
+
return provider
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
// GetAPIKeyUsage returns recent request buckets for all in-memory api_key auths,
|
| 57 |
+
// grouped by provider and keyed by "base_url|api_key".
|
| 58 |
+
func (h *Handler) GetAPIKeyUsage(c *gin.Context) {
|
| 59 |
+
if h == nil {
|
| 60 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler not initialized"})
|
| 61 |
+
return
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
h.mu.Lock()
|
| 65 |
+
manager := h.authManager
|
| 66 |
+
h.mu.Unlock()
|
| 67 |
+
if manager == nil {
|
| 68 |
+
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "core auth manager unavailable"})
|
| 69 |
+
return
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
now := time.Now()
|
| 73 |
+
out := make(map[string]map[string]apiKeyUsageEntry)
|
| 74 |
+
for _, auth := range manager.List() {
|
| 75 |
+
if auth == nil {
|
| 76 |
+
continue
|
| 77 |
+
}
|
| 78 |
+
kind, apiKey := auth.AccountInfo()
|
| 79 |
+
if !strings.EqualFold(strings.TrimSpace(kind), "api_key") {
|
| 80 |
+
continue
|
| 81 |
+
}
|
| 82 |
+
apiKey = strings.TrimSpace(apiKey)
|
| 83 |
+
if apiKey == "" {
|
| 84 |
+
continue
|
| 85 |
+
}
|
| 86 |
+
baseURL := ""
|
| 87 |
+
if auth.Attributes != nil {
|
| 88 |
+
baseURL = strings.TrimSpace(auth.Attributes["base_url"])
|
| 89 |
+
if baseURL == "" {
|
| 90 |
+
baseURL = strings.TrimSpace(auth.Attributes["base-url"])
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
compositeKey := baseURL + "|" + apiKey
|
| 94 |
+
provider := apiKeyUsageProviderKey(auth)
|
| 95 |
+
|
| 96 |
+
recent := auth.RecentRequestsSnapshot(now)
|
| 97 |
+
providerBucket, ok := out[provider]
|
| 98 |
+
if !ok {
|
| 99 |
+
providerBucket = make(map[string]apiKeyUsageEntry)
|
| 100 |
+
out[provider] = providerBucket
|
| 101 |
+
}
|
| 102 |
+
if existing, exists := providerBucket[compositeKey]; exists {
|
| 103 |
+
existing.Success += auth.Success
|
| 104 |
+
existing.Failed += auth.Failed
|
| 105 |
+
existing.RecentRequests = mergeRecentRequestBuckets(existing.RecentRequests, recent)
|
| 106 |
+
providerBucket[compositeKey] = existing
|
| 107 |
+
continue
|
| 108 |
+
}
|
| 109 |
+
providerBucket[compositeKey] = apiKeyUsageEntry{
|
| 110 |
+
Success: auth.Success,
|
| 111 |
+
Failed: auth.Failed,
|
| 112 |
+
RecentRequests: recent,
|
| 113 |
+
}
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
c.JSON(http.StatusOK, out)
|
| 117 |
+
}
|
internal/api/handlers/management/api_key_usage_test.go
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/http/httptest"
|
| 8 |
+
"testing"
|
| 9 |
+
|
| 10 |
+
"github.com/gin-gonic/gin"
|
| 11 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 12 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
func sumRecentRequestBuckets(buckets []coreauth.RecentRequestBucket) (int64, int64) {
|
| 16 |
+
var success int64
|
| 17 |
+
var failed int64
|
| 18 |
+
for _, bucket := range buckets {
|
| 19 |
+
success += bucket.Success
|
| 20 |
+
failed += bucket.Failed
|
| 21 |
+
}
|
| 22 |
+
return success, failed
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
func TestGetAPIKeyUsage_GroupsByProviderAndAPIKey(t *testing.T) {
|
| 26 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 27 |
+
|
| 28 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 29 |
+
if _, err := manager.Register(context.Background(), &coreauth.Auth{
|
| 30 |
+
ID: "codex-auth",
|
| 31 |
+
Provider: "codex",
|
| 32 |
+
Attributes: map[string]string{
|
| 33 |
+
"api_key": "codex-key",
|
| 34 |
+
"base_url": "https://codex.example.com",
|
| 35 |
+
},
|
| 36 |
+
}); err != nil {
|
| 37 |
+
t.Fatalf("register codex auth: %v", err)
|
| 38 |
+
}
|
| 39 |
+
if _, err := manager.Register(context.Background(), &coreauth.Auth{
|
| 40 |
+
ID: "claude-auth",
|
| 41 |
+
Provider: "claude",
|
| 42 |
+
Attributes: map[string]string{
|
| 43 |
+
"api_key": "claude-key",
|
| 44 |
+
"base_url": "https://claude.example.com",
|
| 45 |
+
},
|
| 46 |
+
}); err != nil {
|
| 47 |
+
t.Fatalf("register claude auth: %v", err)
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
manager.MarkResult(context.Background(), coreauth.Result{AuthID: "codex-auth", Provider: "codex", Model: "gpt-5", Success: true})
|
| 51 |
+
manager.MarkResult(context.Background(), coreauth.Result{AuthID: "codex-auth", Provider: "codex", Model: "gpt-5", Success: false})
|
| 52 |
+
manager.MarkResult(context.Background(), coreauth.Result{AuthID: "claude-auth", Provider: "claude", Model: "claude-4", Success: true})
|
| 53 |
+
|
| 54 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
| 55 |
+
|
| 56 |
+
rec := httptest.NewRecorder()
|
| 57 |
+
ginCtx, _ := gin.CreateTestContext(rec)
|
| 58 |
+
req := httptest.NewRequest(http.MethodGet, "/v0/management/api-key-usage", nil)
|
| 59 |
+
ginCtx.Request = req
|
| 60 |
+
h.GetAPIKeyUsage(ginCtx)
|
| 61 |
+
|
| 62 |
+
if rec.Code != http.StatusOK {
|
| 63 |
+
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
var payload map[string]map[string]apiKeyUsageEntry
|
| 67 |
+
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
|
| 68 |
+
t.Fatalf("decode payload: %v", err)
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
codexEntry := payload["codex"]["https://codex.example.com|codex-key"]
|
| 72 |
+
if codexEntry.Success != 1 || codexEntry.Failed != 1 {
|
| 73 |
+
t.Fatalf("codex totals = %d/%d, want 1/1", codexEntry.Success, codexEntry.Failed)
|
| 74 |
+
}
|
| 75 |
+
if len(codexEntry.RecentRequests) != 20 {
|
| 76 |
+
t.Fatalf("codex buckets len = %d, want 20", len(codexEntry.RecentRequests))
|
| 77 |
+
}
|
| 78 |
+
codexSuccess, codexFailed := sumRecentRequestBuckets(codexEntry.RecentRequests)
|
| 79 |
+
if codexSuccess != 1 || codexFailed != 1 {
|
| 80 |
+
t.Fatalf("codex totals = %d/%d, want 1/1", codexSuccess, codexFailed)
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
claudeEntry := payload["claude"]["https://claude.example.com|claude-key"]
|
| 84 |
+
if claudeEntry.Success != 1 || claudeEntry.Failed != 0 {
|
| 85 |
+
t.Fatalf("claude totals = %d/%d, want 1/0", claudeEntry.Success, claudeEntry.Failed)
|
| 86 |
+
}
|
| 87 |
+
if len(claudeEntry.RecentRequests) != 20 {
|
| 88 |
+
t.Fatalf("claude buckets len = %d, want 20", len(claudeEntry.RecentRequests))
|
| 89 |
+
}
|
| 90 |
+
claudeSuccess, claudeFailed := sumRecentRequestBuckets(claudeEntry.RecentRequests)
|
| 91 |
+
if claudeSuccess != 1 || claudeFailed != 0 {
|
| 92 |
+
t.Fatalf("claude totals = %d/%d, want 1/0", claudeSuccess, claudeFailed)
|
| 93 |
+
}
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
func TestGetAPIKeyUsage_GroupsOpenAICompatibleByCompatName(t *testing.T) {
|
| 97 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 98 |
+
|
| 99 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 100 |
+
if _, err := manager.Register(context.Background(), &coreauth.Auth{
|
| 101 |
+
ID: "vast-auth",
|
| 102 |
+
Provider: "openai-compatible-vast",
|
| 103 |
+
Attributes: map[string]string{
|
| 104 |
+
"api_key": "vast-key",
|
| 105 |
+
"base_url": "https://www.vastnum.com/v1",
|
| 106 |
+
"compat_name": "VAST",
|
| 107 |
+
},
|
| 108 |
+
}); err != nil {
|
| 109 |
+
t.Fatalf("register vast auth: %v", err)
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
manager.MarkResult(context.Background(), coreauth.Result{AuthID: "vast-auth", Provider: "openai-compatible-vast", Model: "gpt-5", Success: true})
|
| 113 |
+
|
| 114 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
| 115 |
+
|
| 116 |
+
rec := httptest.NewRecorder()
|
| 117 |
+
ginCtx, _ := gin.CreateTestContext(rec)
|
| 118 |
+
req := httptest.NewRequest(http.MethodGet, "/v0/management/api-key-usage", nil)
|
| 119 |
+
ginCtx.Request = req
|
| 120 |
+
h.GetAPIKeyUsage(ginCtx)
|
| 121 |
+
|
| 122 |
+
if rec.Code != http.StatusOK {
|
| 123 |
+
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
var payload map[string]map[string]apiKeyUsageEntry
|
| 127 |
+
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
|
| 128 |
+
t.Fatalf("decode payload: %v", err)
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
if _, exists := payload["openai-compatible-vast"]; exists {
|
| 132 |
+
t.Fatalf("unexpected namespaced provider bucket in payload: %#v", payload)
|
| 133 |
+
}
|
| 134 |
+
vastBucket, exists := payload["vast"]
|
| 135 |
+
if !exists {
|
| 136 |
+
t.Fatalf("missing compat provider bucket in payload: %#v", payload)
|
| 137 |
+
}
|
| 138 |
+
vastEntry := vastBucket["https://www.vastnum.com/v1|vast-key"]
|
| 139 |
+
if vastEntry.Success != 1 || vastEntry.Failed != 0 {
|
| 140 |
+
t.Fatalf("vast totals = %d/%d, want 1/0", vastEntry.Success, vastEntry.Failed)
|
| 141 |
+
}
|
| 142 |
+
}
|
internal/api/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me/CLIProxyAPI/v7/internal/config"
|
| 15 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 16 |
+
"github.com/router-for-me/CLIProxyAPI/v7/sdk/proxyutil"
|
| 17 |
+
log "github.com/sirupsen/logrus"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
const defaultAPICallTimeout = 60 * time.Second
|
| 21 |
+
|
| 22 |
+
const (
|
| 23 |
+
antigravityOAuthClientID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com"
|
| 24 |
+
antigravityOAuthClientSecret = "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"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
var antigravityOAuthTokenURL = "https://oauth2.googleapis.com/token"
|
| 28 |
+
|
| 29 |
+
type apiCallRequest struct {
|
| 30 |
+
AuthIndexSnake *string `json:"auth_index"`
|
| 31 |
+
AuthIndexCamel *string `json:"authIndex"`
|
| 32 |
+
AuthIndexPascal *string `json:"AuthIndex"`
|
| 33 |
+
Method string `json:"method"`
|
| 34 |
+
URL string `json:"url"`
|
| 35 |
+
Header map[string]string `json:"header"`
|
| 36 |
+
Data string `json:"data"`
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
type apiCallResponse struct {
|
| 40 |
+
StatusCode int `json:"status_code"`
|
| 41 |
+
Header map[string][]string `json:"header"`
|
| 42 |
+
Body string `json:"body"`
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
// APICall makes a generic HTTP request on behalf of the management API caller.
|
| 46 |
+
// It is protected by the management middleware.
|
| 47 |
+
//
|
| 48 |
+
// Endpoint:
|
| 49 |
+
//
|
| 50 |
+
// POST /v0/management/api-call
|
| 51 |
+
//
|
| 52 |
+
// Authentication:
|
| 53 |
+
//
|
| 54 |
+
// Same as other management APIs (requires a management key and remote-management rules).
|
| 55 |
+
// You can provide the key via:
|
| 56 |
+
// - Authorization: Bearer <key>
|
| 57 |
+
// - X-Management-Key: <key>
|
| 58 |
+
//
|
| 59 |
+
// Request JSON:
|
| 60 |
+
// - auth_index / authIndex / AuthIndex (optional):
|
| 61 |
+
// The credential "auth_index" from GET /v0/management/auth-files (or other endpoints returning it).
|
| 62 |
+
// If omitted or not found, credential-specific proxy/token substitution is skipped.
|
| 63 |
+
// - method (required): HTTP method, e.g. GET, POST, PUT, PATCH, DELETE.
|
| 64 |
+
// - url (required): Absolute URL including scheme and host, e.g. "https://api.example.com/v1/ping".
|
| 65 |
+
// - header (optional): Request headers map.
|
| 66 |
+
// Supports magic variable "$TOKEN$" which is replaced using the selected credential:
|
| 67 |
+
// 1) metadata.access_token
|
| 68 |
+
// 2) attributes.api_key
|
| 69 |
+
// 3) metadata.token / metadata.id_token / metadata.cookie
|
| 70 |
+
// Example: {"Authorization":"Bearer $TOKEN$"}.
|
| 71 |
+
// Note: if you need to override the HTTP Host header, set header["Host"].
|
| 72 |
+
// - data (optional): Raw request body as string (useful for POST/PUT/PATCH).
|
| 73 |
+
//
|
| 74 |
+
// Proxy selection (highest priority first):
|
| 75 |
+
// 1. Selected credential proxy_url
|
| 76 |
+
// 2. Global config proxy-url
|
| 77 |
+
// 3. Direct connect (environment proxies are not used)
|
| 78 |
+
//
|
| 79 |
+
// Response JSON (returned with HTTP 200 when the APICall itself succeeds):
|
| 80 |
+
// - status_code: Upstream HTTP status code.
|
| 81 |
+
// - header: Upstream response headers.
|
| 82 |
+
// - body: Upstream response body as string.
|
| 83 |
+
//
|
| 84 |
+
// Example:
|
| 85 |
+
//
|
| 86 |
+
// curl -sS -X POST "http://127.0.0.1:8317/v0/management/api-call" \
|
| 87 |
+
// -H "Authorization: Bearer <MANAGEMENT_KEY>" \
|
| 88 |
+
// -H "Content-Type: application/json" \
|
| 89 |
+
// -d '{"auth_index":"<AUTH_INDEX>","method":"GET","url":"https://api.example.com/v1/ping","header":{"Authorization":"Bearer $TOKEN$"}}'
|
| 90 |
+
//
|
| 91 |
+
// curl -sS -X POST "http://127.0.0.1:8317/v0/management/api-call" \
|
| 92 |
+
// -H "Authorization: Bearer 831227" \
|
| 93 |
+
// -H "Content-Type: application/json" \
|
| 94 |
+
// -d '{"auth_index":"<AUTH_INDEX>","method":"POST","url":"https://api.example.com/v1/fetchAvailableModels","header":{"Authorization":"Bearer $TOKEN$","Content-Type":"application/json","User-Agent":"cliproxyapi"},"data":"{}"}'
|
| 95 |
+
func (h *Handler) APICall(c *gin.Context) {
|
| 96 |
+
var body apiCallRequest
|
| 97 |
+
if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil {
|
| 98 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
|
| 99 |
+
return
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
method := strings.ToUpper(strings.TrimSpace(body.Method))
|
| 103 |
+
if method == "" {
|
| 104 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "missing method"})
|
| 105 |
+
return
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
urlStr := strings.TrimSpace(body.URL)
|
| 109 |
+
if urlStr == "" {
|
| 110 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "missing url"})
|
| 111 |
+
return
|
| 112 |
+
}
|
| 113 |
+
parsedURL, errParseURL := url.Parse(urlStr)
|
| 114 |
+
if errParseURL != nil || parsedURL.Scheme == "" || parsedURL.Host == "" {
|
| 115 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid url"})
|
| 116 |
+
return
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
authIndex := firstNonEmptyString(body.AuthIndexSnake, body.AuthIndexCamel, body.AuthIndexPascal)
|
| 120 |
+
auth := h.authByIndex(authIndex)
|
| 121 |
+
|
| 122 |
+
reqHeaders := body.Header
|
| 123 |
+
if reqHeaders == nil {
|
| 124 |
+
reqHeaders = map[string]string{}
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
var hostOverride string
|
| 128 |
+
var token string
|
| 129 |
+
var tokenResolved bool
|
| 130 |
+
var tokenErr error
|
| 131 |
+
for key, value := range reqHeaders {
|
| 132 |
+
if !strings.Contains(value, "$TOKEN$") {
|
| 133 |
+
continue
|
| 134 |
+
}
|
| 135 |
+
if !tokenResolved {
|
| 136 |
+
token, tokenErr = h.resolveTokenForAuth(c.Request.Context(), auth)
|
| 137 |
+
tokenResolved = true
|
| 138 |
+
}
|
| 139 |
+
if auth != nil && token == "" {
|
| 140 |
+
if tokenErr != nil {
|
| 141 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "auth token refresh failed"})
|
| 142 |
+
return
|
| 143 |
+
}
|
| 144 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "auth token not found"})
|
| 145 |
+
return
|
| 146 |
+
}
|
| 147 |
+
if token == "" {
|
| 148 |
+
continue
|
| 149 |
+
}
|
| 150 |
+
reqHeaders[key] = strings.ReplaceAll(value, "$TOKEN$", token)
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
var requestBody io.Reader
|
| 154 |
+
if body.Data != "" {
|
| 155 |
+
requestBody = strings.NewReader(body.Data)
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
req, errNewRequest := http.NewRequestWithContext(c.Request.Context(), method, urlStr, requestBody)
|
| 159 |
+
if errNewRequest != nil {
|
| 160 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to build request"})
|
| 161 |
+
return
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
for key, value := range reqHeaders {
|
| 165 |
+
if strings.EqualFold(key, "host") {
|
| 166 |
+
hostOverride = strings.TrimSpace(value)
|
| 167 |
+
continue
|
| 168 |
+
}
|
| 169 |
+
req.Header.Set(key, value)
|
| 170 |
+
}
|
| 171 |
+
if hostOverride != "" {
|
| 172 |
+
req.Host = hostOverride
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
httpClient := &http.Client{
|
| 176 |
+
Timeout: defaultAPICallTimeout,
|
| 177 |
+
}
|
| 178 |
+
httpClient.Transport = h.apiCallTransport(auth)
|
| 179 |
+
|
| 180 |
+
resp, errDo := httpClient.Do(req)
|
| 181 |
+
if errDo != nil {
|
| 182 |
+
log.WithError(errDo).Debug("management APICall request failed")
|
| 183 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "request failed"})
|
| 184 |
+
return
|
| 185 |
+
}
|
| 186 |
+
defer func() {
|
| 187 |
+
if errClose := resp.Body.Close(); errClose != nil {
|
| 188 |
+
log.Errorf("response body close error: %v", errClose)
|
| 189 |
+
}
|
| 190 |
+
}()
|
| 191 |
+
|
| 192 |
+
respBody, errReadAll := io.ReadAll(resp.Body)
|
| 193 |
+
if errReadAll != nil {
|
| 194 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "failed to read response"})
|
| 195 |
+
return
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
c.JSON(http.StatusOK, apiCallResponse{
|
| 199 |
+
StatusCode: resp.StatusCode,
|
| 200 |
+
Header: resp.Header,
|
| 201 |
+
Body: string(respBody),
|
| 202 |
+
})
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
func firstNonEmptyString(values ...*string) string {
|
| 206 |
+
for _, v := range values {
|
| 207 |
+
if v == nil {
|
| 208 |
+
continue
|
| 209 |
+
}
|
| 210 |
+
if out := strings.TrimSpace(*v); out != "" {
|
| 211 |
+
return out
|
| 212 |
+
}
|
| 213 |
+
}
|
| 214 |
+
return ""
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
func tokenValueForAuth(auth *coreauth.Auth) string {
|
| 218 |
+
if auth == nil {
|
| 219 |
+
return ""
|
| 220 |
+
}
|
| 221 |
+
if v := tokenValueFromMetadata(auth.Metadata); v != "" {
|
| 222 |
+
return v
|
| 223 |
+
}
|
| 224 |
+
if auth.Attributes != nil {
|
| 225 |
+
if v := strings.TrimSpace(auth.Attributes["api_key"]); v != "" {
|
| 226 |
+
return v
|
| 227 |
+
}
|
| 228 |
+
}
|
| 229 |
+
return ""
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
func (h *Handler) resolveTokenForAuth(ctx context.Context, auth *coreauth.Auth) (string, error) {
|
| 233 |
+
if auth == nil {
|
| 234 |
+
return "", nil
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
if strings.EqualFold(strings.TrimSpace(auth.Provider), "antigravity") {
|
| 238 |
+
token, errToken := h.refreshAntigravityOAuthAccessToken(ctx, auth)
|
| 239 |
+
return token, errToken
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
return tokenValueForAuth(auth), nil
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
func (h *Handler) refreshAntigravityOAuthAccessToken(ctx context.Context, auth *coreauth.Auth) (string, error) {
|
| 246 |
+
if ctx == nil {
|
| 247 |
+
ctx = context.Background()
|
| 248 |
+
}
|
| 249 |
+
if auth == nil {
|
| 250 |
+
return "", nil
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
metadata := auth.Metadata
|
| 254 |
+
if len(metadata) == 0 {
|
| 255 |
+
return "", fmt.Errorf("antigravity oauth metadata missing")
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
current := strings.TrimSpace(tokenValueFromMetadata(metadata))
|
| 259 |
+
if current != "" && !antigravityTokenNeedsRefresh(metadata) {
|
| 260 |
+
return current, nil
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
refreshToken := stringValue(metadata, "refresh_token")
|
| 264 |
+
if refreshToken == "" {
|
| 265 |
+
return "", fmt.Errorf("antigravity refresh token missing")
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
tokenURL := strings.TrimSpace(antigravityOAuthTokenURL)
|
| 269 |
+
if tokenURL == "" {
|
| 270 |
+
tokenURL = "https://oauth2.googleapis.com/token"
|
| 271 |
+
}
|
| 272 |
+
form := url.Values{}
|
| 273 |
+
form.Set("client_id", antigravityOAuthClientID)
|
| 274 |
+
form.Set("client_secret", antigravityOAuthClientSecret)
|
| 275 |
+
form.Set("grant_type", "refresh_token")
|
| 276 |
+
form.Set("refresh_token", refreshToken)
|
| 277 |
+
|
| 278 |
+
req, errReq := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(form.Encode()))
|
| 279 |
+
if errReq != nil {
|
| 280 |
+
return "", errReq
|
| 281 |
+
}
|
| 282 |
+
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
| 283 |
+
|
| 284 |
+
httpClient := &http.Client{
|
| 285 |
+
Timeout: defaultAPICallTimeout,
|
| 286 |
+
Transport: h.apiCallTransport(auth),
|
| 287 |
+
}
|
| 288 |
+
resp, errDo := httpClient.Do(req)
|
| 289 |
+
if errDo != nil {
|
| 290 |
+
return "", errDo
|
| 291 |
+
}
|
| 292 |
+
defer func() {
|
| 293 |
+
if errClose := resp.Body.Close(); errClose != nil {
|
| 294 |
+
log.Errorf("response body close error: %v", errClose)
|
| 295 |
+
}
|
| 296 |
+
}()
|
| 297 |
+
|
| 298 |
+
bodyBytes, errRead := io.ReadAll(resp.Body)
|
| 299 |
+
if errRead != nil {
|
| 300 |
+
return "", errRead
|
| 301 |
+
}
|
| 302 |
+
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
| 303 |
+
return "", fmt.Errorf("antigravity oauth token refresh failed: status %d: %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
var tokenResp struct {
|
| 307 |
+
AccessToken string `json:"access_token"`
|
| 308 |
+
RefreshToken string `json:"refresh_token"`
|
| 309 |
+
ExpiresIn int64 `json:"expires_in"`
|
| 310 |
+
TokenType string `json:"token_type"`
|
| 311 |
+
}
|
| 312 |
+
if errUnmarshal := json.Unmarshal(bodyBytes, &tokenResp); errUnmarshal != nil {
|
| 313 |
+
return "", errUnmarshal
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
if strings.TrimSpace(tokenResp.AccessToken) == "" {
|
| 317 |
+
return "", fmt.Errorf("antigravity oauth token refresh returned empty access_token")
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
if auth.Metadata == nil {
|
| 321 |
+
auth.Metadata = make(map[string]any)
|
| 322 |
+
}
|
| 323 |
+
now := time.Now()
|
| 324 |
+
auth.Metadata["access_token"] = strings.TrimSpace(tokenResp.AccessToken)
|
| 325 |
+
if strings.TrimSpace(tokenResp.RefreshToken) != "" {
|
| 326 |
+
auth.Metadata["refresh_token"] = strings.TrimSpace(tokenResp.RefreshToken)
|
| 327 |
+
}
|
| 328 |
+
if tokenResp.ExpiresIn > 0 {
|
| 329 |
+
auth.Metadata["expires_in"] = tokenResp.ExpiresIn
|
| 330 |
+
auth.Metadata["timestamp"] = now.UnixMilli()
|
| 331 |
+
auth.Metadata["expired"] = now.Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Format(time.RFC3339)
|
| 332 |
+
}
|
| 333 |
+
auth.Metadata["type"] = "antigravity"
|
| 334 |
+
|
| 335 |
+
if h != nil && h.authManager != nil {
|
| 336 |
+
auth.LastRefreshedAt = now
|
| 337 |
+
auth.UpdatedAt = now
|
| 338 |
+
_, _ = h.authManager.Update(ctx, auth)
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
return strings.TrimSpace(tokenResp.AccessToken), nil
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
func antigravityTokenNeedsRefresh(metadata map[string]any) bool {
|
| 345 |
+
// Refresh a bit early to avoid requests racing token expiry.
|
| 346 |
+
const skew = 30 * time.Second
|
| 347 |
+
|
| 348 |
+
if metadata == nil {
|
| 349 |
+
return true
|
| 350 |
+
}
|
| 351 |
+
if expStr, ok := metadata["expired"].(string); ok {
|
| 352 |
+
if ts, errParse := time.Parse(time.RFC3339, strings.TrimSpace(expStr)); errParse == nil {
|
| 353 |
+
return !ts.After(time.Now().Add(skew))
|
| 354 |
+
}
|
| 355 |
+
}
|
| 356 |
+
expiresIn := int64Value(metadata["expires_in"])
|
| 357 |
+
timestampMs := int64Value(metadata["timestamp"])
|
| 358 |
+
if expiresIn > 0 && timestampMs > 0 {
|
| 359 |
+
exp := time.UnixMilli(timestampMs).Add(time.Duration(expiresIn) * time.Second)
|
| 360 |
+
return !exp.After(time.Now().Add(skew))
|
| 361 |
+
}
|
| 362 |
+
return true
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
func int64Value(raw any) int64 {
|
| 366 |
+
switch typed := raw.(type) {
|
| 367 |
+
case int:
|
| 368 |
+
return int64(typed)
|
| 369 |
+
case int32:
|
| 370 |
+
return int64(typed)
|
| 371 |
+
case int64:
|
| 372 |
+
return typed
|
| 373 |
+
case uint:
|
| 374 |
+
return int64(typed)
|
| 375 |
+
case uint32:
|
| 376 |
+
return int64(typed)
|
| 377 |
+
case uint64:
|
| 378 |
+
if typed > uint64(^uint64(0)>>1) {
|
| 379 |
+
return 0
|
| 380 |
+
}
|
| 381 |
+
return int64(typed)
|
| 382 |
+
case float32:
|
| 383 |
+
return int64(typed)
|
| 384 |
+
case float64:
|
| 385 |
+
return int64(typed)
|
| 386 |
+
case json.Number:
|
| 387 |
+
if i, errParse := typed.Int64(); errParse == nil {
|
| 388 |
+
return i
|
| 389 |
+
}
|
| 390 |
+
case string:
|
| 391 |
+
if s := strings.TrimSpace(typed); s != "" {
|
| 392 |
+
if i, errParse := json.Number(s).Int64(); errParse == nil {
|
| 393 |
+
return i
|
| 394 |
+
}
|
| 395 |
+
}
|
| 396 |
+
}
|
| 397 |
+
return 0
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
func stringValue(metadata map[string]any, key string) string {
|
| 401 |
+
if len(metadata) == 0 || key == "" {
|
| 402 |
+
return ""
|
| 403 |
+
}
|
| 404 |
+
if v, ok := metadata[key].(string); ok {
|
| 405 |
+
return strings.TrimSpace(v)
|
| 406 |
+
}
|
| 407 |
+
return ""
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
func tokenValueFromMetadata(metadata map[string]any) string {
|
| 411 |
+
if len(metadata) == 0 {
|
| 412 |
+
return ""
|
| 413 |
+
}
|
| 414 |
+
if v, ok := metadata["accessToken"].(string); ok && strings.TrimSpace(v) != "" {
|
| 415 |
+
return strings.TrimSpace(v)
|
| 416 |
+
}
|
| 417 |
+
if v, ok := metadata["access_token"].(string); ok && strings.TrimSpace(v) != "" {
|
| 418 |
+
return strings.TrimSpace(v)
|
| 419 |
+
}
|
| 420 |
+
if tokenRaw, ok := metadata["token"]; ok && tokenRaw != nil {
|
| 421 |
+
switch typed := tokenRaw.(type) {
|
| 422 |
+
case string:
|
| 423 |
+
if v := strings.TrimSpace(typed); v != "" {
|
| 424 |
+
return v
|
| 425 |
+
}
|
| 426 |
+
case map[string]any:
|
| 427 |
+
if v, ok := typed["access_token"].(string); ok && strings.TrimSpace(v) != "" {
|
| 428 |
+
return strings.TrimSpace(v)
|
| 429 |
+
}
|
| 430 |
+
if v, ok := typed["accessToken"].(string); ok && strings.TrimSpace(v) != "" {
|
| 431 |
+
return strings.TrimSpace(v)
|
| 432 |
+
}
|
| 433 |
+
case map[string]string:
|
| 434 |
+
if v := strings.TrimSpace(typed["access_token"]); v != "" {
|
| 435 |
+
return v
|
| 436 |
+
}
|
| 437 |
+
if v := strings.TrimSpace(typed["accessToken"]); v != "" {
|
| 438 |
+
return v
|
| 439 |
+
}
|
| 440 |
+
}
|
| 441 |
+
}
|
| 442 |
+
if v, ok := metadata["token"].(string); ok && strings.TrimSpace(v) != "" {
|
| 443 |
+
return strings.TrimSpace(v)
|
| 444 |
+
}
|
| 445 |
+
if v, ok := metadata["id_token"].(string); ok && strings.TrimSpace(v) != "" {
|
| 446 |
+
return strings.TrimSpace(v)
|
| 447 |
+
}
|
| 448 |
+
if v, ok := metadata["cookie"].(string); ok && strings.TrimSpace(v) != "" {
|
| 449 |
+
return strings.TrimSpace(v)
|
| 450 |
+
}
|
| 451 |
+
return ""
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
func (h *Handler) authByIndex(authIndex string) *coreauth.Auth {
|
| 455 |
+
authIndex = strings.TrimSpace(authIndex)
|
| 456 |
+
if authIndex == "" || h == nil || h.authManager == nil {
|
| 457 |
+
return nil
|
| 458 |
+
}
|
| 459 |
+
auths := h.authManager.List()
|
| 460 |
+
for _, auth := range auths {
|
| 461 |
+
if auth == nil {
|
| 462 |
+
continue
|
| 463 |
+
}
|
| 464 |
+
auth.EnsureIndex()
|
| 465 |
+
if auth.Index == authIndex {
|
| 466 |
+
return auth
|
| 467 |
+
}
|
| 468 |
+
}
|
| 469 |
+
return nil
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
func (h *Handler) apiCallTransport(auth *coreauth.Auth) http.RoundTripper {
|
| 473 |
+
var proxyCandidates []string
|
| 474 |
+
if auth != nil {
|
| 475 |
+
if proxyStr := strings.TrimSpace(auth.ProxyURL); proxyStr != "" {
|
| 476 |
+
proxyCandidates = append(proxyCandidates, proxyStr)
|
| 477 |
+
}
|
| 478 |
+
if h != nil && h.cfg != nil {
|
| 479 |
+
if proxyStr := strings.TrimSpace(proxyURLFromAPIKeyConfig(h.cfg, auth)); proxyStr != "" {
|
| 480 |
+
proxyCandidates = append(proxyCandidates, proxyStr)
|
| 481 |
+
}
|
| 482 |
+
}
|
| 483 |
+
}
|
| 484 |
+
if h != nil && h.cfg != nil {
|
| 485 |
+
if proxyStr := strings.TrimSpace(h.cfg.ProxyURL); proxyStr != "" {
|
| 486 |
+
proxyCandidates = append(proxyCandidates, proxyStr)
|
| 487 |
+
}
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
for _, proxyStr := range proxyCandidates {
|
| 491 |
+
if transport := buildProxyTransport(proxyStr); transport != nil {
|
| 492 |
+
return transport
|
| 493 |
+
}
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
transport, ok := http.DefaultTransport.(*http.Transport)
|
| 497 |
+
if !ok || transport == nil {
|
| 498 |
+
return &http.Transport{Proxy: nil}
|
| 499 |
+
}
|
| 500 |
+
clone := transport.Clone()
|
| 501 |
+
clone.Proxy = nil
|
| 502 |
+
return clone
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
type apiKeyConfigEntry interface {
|
| 506 |
+
GetAPIKey() string
|
| 507 |
+
GetBaseURL() string
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
func resolveAPIKeyConfig[T apiKeyConfigEntry](entries []T, auth *coreauth.Auth) *T {
|
| 511 |
+
if auth == nil || len(entries) == 0 {
|
| 512 |
+
return nil
|
| 513 |
+
}
|
| 514 |
+
attrKey, attrBase := "", ""
|
| 515 |
+
if auth.Attributes != nil {
|
| 516 |
+
attrKey = strings.TrimSpace(auth.Attributes["api_key"])
|
| 517 |
+
attrBase = strings.TrimSpace(auth.Attributes["base_url"])
|
| 518 |
+
}
|
| 519 |
+
for i := range entries {
|
| 520 |
+
entry := &entries[i]
|
| 521 |
+
cfgKey := strings.TrimSpace((*entry).GetAPIKey())
|
| 522 |
+
cfgBase := strings.TrimSpace((*entry).GetBaseURL())
|
| 523 |
+
if attrKey != "" && attrBase != "" {
|
| 524 |
+
if strings.EqualFold(cfgKey, attrKey) && strings.EqualFold(cfgBase, attrBase) {
|
| 525 |
+
return entry
|
| 526 |
+
}
|
| 527 |
+
continue
|
| 528 |
+
}
|
| 529 |
+
if attrKey != "" && strings.EqualFold(cfgKey, attrKey) {
|
| 530 |
+
if cfgBase == "" || strings.EqualFold(cfgBase, attrBase) {
|
| 531 |
+
return entry
|
| 532 |
+
}
|
| 533 |
+
}
|
| 534 |
+
if attrKey == "" && attrBase != "" && strings.EqualFold(cfgBase, attrBase) {
|
| 535 |
+
return entry
|
| 536 |
+
}
|
| 537 |
+
}
|
| 538 |
+
if attrKey != "" {
|
| 539 |
+
for i := range entries {
|
| 540 |
+
entry := &entries[i]
|
| 541 |
+
if strings.EqualFold(strings.TrimSpace((*entry).GetAPIKey()), attrKey) {
|
| 542 |
+
return entry
|
| 543 |
+
}
|
| 544 |
+
}
|
| 545 |
+
}
|
| 546 |
+
return nil
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
func proxyURLFromAPIKeyConfig(cfg *config.Config, auth *coreauth.Auth) string {
|
| 550 |
+
if cfg == nil || auth == nil {
|
| 551 |
+
return ""
|
| 552 |
+
}
|
| 553 |
+
authKind, authAccount := auth.AccountInfo()
|
| 554 |
+
if !strings.EqualFold(strings.TrimSpace(authKind), "api_key") {
|
| 555 |
+
return ""
|
| 556 |
+
}
|
| 557 |
+
|
| 558 |
+
attrs := auth.Attributes
|
| 559 |
+
compatName := ""
|
| 560 |
+
providerKey := ""
|
| 561 |
+
if len(attrs) > 0 {
|
| 562 |
+
compatName = strings.TrimSpace(attrs["compat_name"])
|
| 563 |
+
providerKey = strings.TrimSpace(attrs["provider_key"])
|
| 564 |
+
}
|
| 565 |
+
if compatName != "" || strings.EqualFold(strings.TrimSpace(auth.Provider), "openai-compatibility") {
|
| 566 |
+
return resolveOpenAICompatAPIKeyProxyURL(cfg, auth, strings.TrimSpace(authAccount), providerKey, compatName)
|
| 567 |
+
}
|
| 568 |
+
|
| 569 |
+
switch strings.ToLower(strings.TrimSpace(auth.Provider)) {
|
| 570 |
+
case "gemini":
|
| 571 |
+
if entry := resolveAPIKeyConfig(cfg.GeminiKey, auth); entry != nil {
|
| 572 |
+
return strings.TrimSpace(entry.ProxyURL)
|
| 573 |
+
}
|
| 574 |
+
case "gemini-interactions":
|
| 575 |
+
if entry := resolveAPIKeyConfig(cfg.InteractionsKey, auth); entry != nil {
|
| 576 |
+
return strings.TrimSpace(entry.ProxyURL)
|
| 577 |
+
}
|
| 578 |
+
case "claude":
|
| 579 |
+
if entry := resolveAPIKeyConfig(cfg.ClaudeKey, auth); entry != nil {
|
| 580 |
+
return strings.TrimSpace(entry.ProxyURL)
|
| 581 |
+
}
|
| 582 |
+
case "codex":
|
| 583 |
+
if entry := resolveAPIKeyConfig(cfg.CodexKey, auth); entry != nil {
|
| 584 |
+
return strings.TrimSpace(entry.ProxyURL)
|
| 585 |
+
}
|
| 586 |
+
case "xai":
|
| 587 |
+
if entry := resolveAPIKeyConfig(cfg.XAIKey, auth); entry != nil {
|
| 588 |
+
return strings.TrimSpace(entry.ProxyURL)
|
| 589 |
+
}
|
| 590 |
+
}
|
| 591 |
+
return ""
|
| 592 |
+
}
|
| 593 |
+
|
| 594 |
+
func resolveOpenAICompatAPIKeyProxyURL(cfg *config.Config, auth *coreauth.Auth, apiKey, providerKey, compatName string) string {
|
| 595 |
+
if cfg == nil || auth == nil {
|
| 596 |
+
return ""
|
| 597 |
+
}
|
| 598 |
+
apiKey = strings.TrimSpace(apiKey)
|
| 599 |
+
if apiKey == "" {
|
| 600 |
+
return ""
|
| 601 |
+
}
|
| 602 |
+
candidates := make([]string, 0, 3)
|
| 603 |
+
if v := strings.TrimSpace(compatName); v != "" {
|
| 604 |
+
candidates = append(candidates, v)
|
| 605 |
+
}
|
| 606 |
+
if v := strings.TrimSpace(providerKey); v != "" {
|
| 607 |
+
candidates = append(candidates, v)
|
| 608 |
+
}
|
| 609 |
+
if v := strings.TrimSpace(auth.Provider); v != "" {
|
| 610 |
+
candidates = append(candidates, v)
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
+
for i := range cfg.OpenAICompatibility {
|
| 614 |
+
compat := &cfg.OpenAICompatibility[i]
|
| 615 |
+
if compat.Disabled {
|
| 616 |
+
continue
|
| 617 |
+
}
|
| 618 |
+
for _, candidate := range candidates {
|
| 619 |
+
if candidate != "" && strings.EqualFold(strings.TrimSpace(candidate), compat.Name) {
|
| 620 |
+
for j := range compat.APIKeyEntries {
|
| 621 |
+
entry := &compat.APIKeyEntries[j]
|
| 622 |
+
if strings.EqualFold(strings.TrimSpace(entry.APIKey), apiKey) {
|
| 623 |
+
return strings.TrimSpace(entry.ProxyURL)
|
| 624 |
+
}
|
| 625 |
+
}
|
| 626 |
+
return ""
|
| 627 |
+
}
|
| 628 |
+
}
|
| 629 |
+
}
|
| 630 |
+
return ""
|
| 631 |
+
}
|
| 632 |
+
|
| 633 |
+
func buildProxyTransport(proxyStr string) *http.Transport {
|
| 634 |
+
transport, _, errBuild := proxyutil.BuildHTTPTransport(proxyStr)
|
| 635 |
+
if errBuild != nil {
|
| 636 |
+
log.WithError(errBuild).Debug("build proxy transport failed")
|
| 637 |
+
return nil
|
| 638 |
+
}
|
| 639 |
+
return transport
|
| 640 |
+
}
|
internal/api/handlers/management/api_tools_test.go
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"net/http"
|
| 6 |
+
"testing"
|
| 7 |
+
|
| 8 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 9 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 10 |
+
sdkconfig "github.com/router-for-me/CLIProxyAPI/v7/sdk/config"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
func TestAPICallTransportDirectBypassesGlobalProxy(t *testing.T) {
|
| 14 |
+
t.Parallel()
|
| 15 |
+
|
| 16 |
+
h := &Handler{
|
| 17 |
+
cfg: &config.Config{
|
| 18 |
+
SDKConfig: sdkconfig.SDKConfig{ProxyURL: "http://global-proxy.example.com:8080"},
|
| 19 |
+
},
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
transport := h.apiCallTransport(&coreauth.Auth{ProxyURL: "direct"})
|
| 23 |
+
httpTransport, ok := transport.(*http.Transport)
|
| 24 |
+
if !ok {
|
| 25 |
+
t.Fatalf("transport type = %T, want *http.Transport", transport)
|
| 26 |
+
}
|
| 27 |
+
if httpTransport.Proxy != nil {
|
| 28 |
+
t.Fatal("expected direct transport to disable proxy function")
|
| 29 |
+
}
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
func TestAPICallTransportInvalidAuthFallsBackToGlobalProxy(t *testing.T) {
|
| 33 |
+
t.Parallel()
|
| 34 |
+
|
| 35 |
+
h := &Handler{
|
| 36 |
+
cfg: &config.Config{
|
| 37 |
+
SDKConfig: sdkconfig.SDKConfig{ProxyURL: "http://global-proxy.example.com:8080"},
|
| 38 |
+
},
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
transport := h.apiCallTransport(&coreauth.Auth{ProxyURL: "bad-value"})
|
| 42 |
+
httpTransport, ok := transport.(*http.Transport)
|
| 43 |
+
if !ok {
|
| 44 |
+
t.Fatalf("transport type = %T, want *http.Transport", transport)
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
req, errRequest := http.NewRequest(http.MethodGet, "https://example.com", nil)
|
| 48 |
+
if errRequest != nil {
|
| 49 |
+
t.Fatalf("http.NewRequest returned error: %v", errRequest)
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
proxyURL, errProxy := httpTransport.Proxy(req)
|
| 53 |
+
if errProxy != nil {
|
| 54 |
+
t.Fatalf("httpTransport.Proxy returned error: %v", errProxy)
|
| 55 |
+
}
|
| 56 |
+
if proxyURL == nil || proxyURL.String() != "http://global-proxy.example.com:8080" {
|
| 57 |
+
t.Fatalf("proxy URL = %v, want http://global-proxy.example.com:8080", proxyURL)
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
func TestAPICallTransportAPIKeyAuthFallsBackToConfigProxyURL(t *testing.T) {
|
| 62 |
+
t.Parallel()
|
| 63 |
+
|
| 64 |
+
h := &Handler{
|
| 65 |
+
cfg: &config.Config{
|
| 66 |
+
SDKConfig: sdkconfig.SDKConfig{ProxyURL: "http://global-proxy.example.com:8080"},
|
| 67 |
+
GeminiKey: []config.GeminiKey{{
|
| 68 |
+
APIKey: "gemini-key",
|
| 69 |
+
ProxyURL: "http://gemini-proxy.example.com:8080",
|
| 70 |
+
}},
|
| 71 |
+
ClaudeKey: []config.ClaudeKey{{
|
| 72 |
+
APIKey: "claude-key",
|
| 73 |
+
ProxyURL: "http://claude-proxy.example.com:8080",
|
| 74 |
+
}},
|
| 75 |
+
CodexKey: []config.CodexKey{{
|
| 76 |
+
APIKey: "codex-key",
|
| 77 |
+
ProxyURL: "http://codex-proxy.example.com:8080",
|
| 78 |
+
}},
|
| 79 |
+
XAIKey: []config.XAIKey{{
|
| 80 |
+
APIKey: "xai-key",
|
| 81 |
+
ProxyURL: "http://xai-proxy.example.com:8080",
|
| 82 |
+
}},
|
| 83 |
+
OpenAICompatibility: []config.OpenAICompatibility{{
|
| 84 |
+
Name: "bohe",
|
| 85 |
+
BaseURL: "https://bohe.example.com",
|
| 86 |
+
APIKeyEntries: []config.OpenAICompatibilityAPIKey{{
|
| 87 |
+
APIKey: "compat-key",
|
| 88 |
+
ProxyURL: "http://compat-proxy.example.com:8080",
|
| 89 |
+
}},
|
| 90 |
+
}},
|
| 91 |
+
},
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
cases := []struct {
|
| 95 |
+
name string
|
| 96 |
+
auth *coreauth.Auth
|
| 97 |
+
wantProxy string
|
| 98 |
+
}{
|
| 99 |
+
{
|
| 100 |
+
name: "gemini",
|
| 101 |
+
auth: &coreauth.Auth{
|
| 102 |
+
Provider: "gemini",
|
| 103 |
+
Attributes: map[string]string{"api_key": "gemini-key"},
|
| 104 |
+
},
|
| 105 |
+
wantProxy: "http://gemini-proxy.example.com:8080",
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
name: "claude",
|
| 109 |
+
auth: &coreauth.Auth{
|
| 110 |
+
Provider: "claude",
|
| 111 |
+
Attributes: map[string]string{"api_key": "claude-key"},
|
| 112 |
+
},
|
| 113 |
+
wantProxy: "http://claude-proxy.example.com:8080",
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
name: "codex",
|
| 117 |
+
auth: &coreauth.Auth{
|
| 118 |
+
Provider: "codex",
|
| 119 |
+
Attributes: map[string]string{"api_key": "codex-key"},
|
| 120 |
+
},
|
| 121 |
+
wantProxy: "http://codex-proxy.example.com:8080",
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
name: "xai",
|
| 125 |
+
auth: &coreauth.Auth{
|
| 126 |
+
Provider: "xai",
|
| 127 |
+
Attributes: map[string]string{"api_key": "xai-key"},
|
| 128 |
+
},
|
| 129 |
+
wantProxy: "http://xai-proxy.example.com:8080",
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
name: "openai-compatibility",
|
| 133 |
+
auth: &coreauth.Auth{
|
| 134 |
+
Provider: "bohe",
|
| 135 |
+
Attributes: map[string]string{
|
| 136 |
+
"api_key": "compat-key",
|
| 137 |
+
"compat_name": "bohe",
|
| 138 |
+
"provider_key": "bohe",
|
| 139 |
+
},
|
| 140 |
+
},
|
| 141 |
+
wantProxy: "http://compat-proxy.example.com:8080",
|
| 142 |
+
},
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
for _, tc := range cases {
|
| 146 |
+
tc := tc
|
| 147 |
+
t.Run(tc.name, func(t *testing.T) {
|
| 148 |
+
t.Parallel()
|
| 149 |
+
|
| 150 |
+
transport := h.apiCallTransport(tc.auth)
|
| 151 |
+
httpTransport, ok := transport.(*http.Transport)
|
| 152 |
+
if !ok {
|
| 153 |
+
t.Fatalf("transport type = %T, want *http.Transport", transport)
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
req, errRequest := http.NewRequest(http.MethodGet, "https://example.com", nil)
|
| 157 |
+
if errRequest != nil {
|
| 158 |
+
t.Fatalf("http.NewRequest returned error: %v", errRequest)
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
proxyURL, errProxy := httpTransport.Proxy(req)
|
| 162 |
+
if errProxy != nil {
|
| 163 |
+
t.Fatalf("httpTransport.Proxy returned error: %v", errProxy)
|
| 164 |
+
}
|
| 165 |
+
if proxyURL == nil || proxyURL.String() != tc.wantProxy {
|
| 166 |
+
t.Fatalf("proxy URL = %v, want %s", proxyURL, tc.wantProxy)
|
| 167 |
+
}
|
| 168 |
+
})
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
func TestAuthByIndexDistinguishesSharedAPIKeysAcrossProviders(t *testing.T) {
|
| 173 |
+
t.Parallel()
|
| 174 |
+
|
| 175 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 176 |
+
geminiAuth := &coreauth.Auth{
|
| 177 |
+
ID: "gemini:apikey:123",
|
| 178 |
+
Provider: "gemini",
|
| 179 |
+
Attributes: map[string]string{
|
| 180 |
+
"api_key": "shared-key",
|
| 181 |
+
},
|
| 182 |
+
}
|
| 183 |
+
compatAuth := &coreauth.Auth{
|
| 184 |
+
ID: "openai-compatibility:bohe:456",
|
| 185 |
+
Provider: "bohe",
|
| 186 |
+
Label: "bohe",
|
| 187 |
+
Attributes: map[string]string{
|
| 188 |
+
"api_key": "shared-key",
|
| 189 |
+
"compat_name": "bohe",
|
| 190 |
+
"provider_key": "bohe",
|
| 191 |
+
},
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
if _, errRegister := manager.Register(context.Background(), geminiAuth); errRegister != nil {
|
| 195 |
+
t.Fatalf("register gemini auth: %v", errRegister)
|
| 196 |
+
}
|
| 197 |
+
if _, errRegister := manager.Register(context.Background(), compatAuth); errRegister != nil {
|
| 198 |
+
t.Fatalf("register compat auth: %v", errRegister)
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
geminiIndex := geminiAuth.EnsureIndex()
|
| 202 |
+
compatIndex := compatAuth.EnsureIndex()
|
| 203 |
+
if geminiIndex == compatIndex {
|
| 204 |
+
t.Fatalf("shared api key produced duplicate auth_index %q", geminiIndex)
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
h := &Handler{authManager: manager}
|
| 208 |
+
|
| 209 |
+
gotGemini := h.authByIndex(geminiIndex)
|
| 210 |
+
if gotGemini == nil {
|
| 211 |
+
t.Fatal("expected gemini auth by index")
|
| 212 |
+
}
|
| 213 |
+
if gotGemini.ID != geminiAuth.ID {
|
| 214 |
+
t.Fatalf("authByIndex(gemini) returned %q, want %q", gotGemini.ID, geminiAuth.ID)
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
gotCompat := h.authByIndex(compatIndex)
|
| 218 |
+
if gotCompat == nil {
|
| 219 |
+
t.Fatal("expected compat auth by index")
|
| 220 |
+
}
|
| 221 |
+
if gotCompat.ID != compatAuth.ID {
|
| 222 |
+
t.Fatalf("authByIndex(compat) returned %q, want %q", gotCompat.ID, compatAuth.ID)
|
| 223 |
+
}
|
| 224 |
+
}
|
internal/api/handlers/management/auth_files.go
ADDED
|
@@ -0,0 +1,2810 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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"bytes"
|
| 5 |
+
"context"
|
| 6 |
+
"crypto/sha256"
|
| 7 |
+
"encoding/hex"
|
| 8 |
+
"encoding/json"
|
| 9 |
+
"errors"
|
| 10 |
+
"fmt"
|
| 11 |
+
"io"
|
| 12 |
+
"mime/multipart"
|
| 13 |
+
"net"
|
| 14 |
+
"net/http"
|
| 15 |
+
"os"
|
| 16 |
+
"path/filepath"
|
| 17 |
+
"runtime"
|
| 18 |
+
"sort"
|
| 19 |
+
"strconv"
|
| 20 |
+
"strings"
|
| 21 |
+
"sync"
|
| 22 |
+
"time"
|
| 23 |
+
|
| 24 |
+
"github.com/gin-gonic/gin"
|
| 25 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/auth/antigravity"
|
| 26 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/auth/claude"
|
| 27 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/auth/codex"
|
| 28 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/auth/kimi"
|
| 29 |
+
xaiauth "github.com/router-for-me/CLIProxyAPI/v7/internal/auth/xai"
|
| 30 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 31 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/misc"
|
| 32 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
|
| 33 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
|
| 34 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
| 35 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/watcher/synthesizer"
|
| 36 |
+
sdkAuth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
| 37 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 38 |
+
"github.com/router-for-me/CLIProxyAPI/v7/sdk/pluginapi"
|
| 39 |
+
log "github.com/sirupsen/logrus"
|
| 40 |
+
"github.com/tidwall/gjson"
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
var lastRefreshKeys = []string{"last_refresh", "lastRefresh", "last_refreshed_at", "lastRefreshedAt"}
|
| 44 |
+
|
| 45 |
+
const (
|
| 46 |
+
anthropicCallbackPort = 54545
|
| 47 |
+
codexCallbackPort = 1455
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
type callbackForwarder struct {
|
| 51 |
+
provider string
|
| 52 |
+
server *http.Server
|
| 53 |
+
done chan struct{}
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
type codexOAuthService interface {
|
| 57 |
+
GenerateAuthURL(state string, pkceCodes *codex.PKCECodes) (string, error)
|
| 58 |
+
ExchangeCodeForTokens(ctx context.Context, code string, pkceCodes *codex.PKCECodes) (*codex.CodexAuthBundle, error)
|
| 59 |
+
CreateTokenStorage(bundle *codex.CodexAuthBundle) *codex.CodexTokenStorage
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
var (
|
| 63 |
+
callbackForwardersMu sync.Mutex
|
| 64 |
+
callbackForwarders = make(map[int]*callbackForwarder)
|
| 65 |
+
authFileEntryMu sync.Mutex
|
| 66 |
+
errAuthFileMustBeJSON = errors.New("auth file must be .json")
|
| 67 |
+
errAuthFileNotFound = errors.New("auth file not found")
|
| 68 |
+
errPluginVirtualAuth = errors.New("plugin virtual auth cannot be modified directly; edit or delete the source auth file")
|
| 69 |
+
newCodexOAuthService = func(cfg *config.Config) codexOAuthService { return codex.NewCodexAuth(cfg) }
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
func extractLastRefreshTimestamp(meta map[string]any) (time.Time, bool) {
|
| 73 |
+
if len(meta) == 0 {
|
| 74 |
+
return time.Time{}, false
|
| 75 |
+
}
|
| 76 |
+
for _, key := range lastRefreshKeys {
|
| 77 |
+
if val, ok := meta[key]; ok {
|
| 78 |
+
if ts, ok1 := parseLastRefreshValue(val); ok1 {
|
| 79 |
+
return ts, true
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
}
|
| 83 |
+
return time.Time{}, false
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
func parseLastRefreshValue(v any) (time.Time, bool) {
|
| 87 |
+
switch val := v.(type) {
|
| 88 |
+
case string:
|
| 89 |
+
s := strings.TrimSpace(val)
|
| 90 |
+
if s == "" {
|
| 91 |
+
return time.Time{}, false
|
| 92 |
+
}
|
| 93 |
+
layouts := []string{time.RFC3339, time.RFC3339Nano, "2006-01-02 15:04:05", "2006-01-02T15:04:05Z07:00"}
|
| 94 |
+
for _, layout := range layouts {
|
| 95 |
+
if ts, err := time.Parse(layout, s); err == nil {
|
| 96 |
+
return ts.UTC(), true
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
if unix, err := strconv.ParseInt(s, 10, 64); err == nil && unix > 0 {
|
| 100 |
+
return time.Unix(unix, 0).UTC(), true
|
| 101 |
+
}
|
| 102 |
+
case float64:
|
| 103 |
+
if val <= 0 {
|
| 104 |
+
return time.Time{}, false
|
| 105 |
+
}
|
| 106 |
+
return time.Unix(int64(val), 0).UTC(), true
|
| 107 |
+
case int64:
|
| 108 |
+
if val <= 0 {
|
| 109 |
+
return time.Time{}, false
|
| 110 |
+
}
|
| 111 |
+
return time.Unix(val, 0).UTC(), true
|
| 112 |
+
case int:
|
| 113 |
+
if val <= 0 {
|
| 114 |
+
return time.Time{}, false
|
| 115 |
+
}
|
| 116 |
+
return time.Unix(int64(val), 0).UTC(), true
|
| 117 |
+
case json.Number:
|
| 118 |
+
if i, err := val.Int64(); err == nil && i > 0 {
|
| 119 |
+
return time.Unix(i, 0).UTC(), true
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
return time.Time{}, false
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
func isWebUIRequest(c *gin.Context) bool {
|
| 126 |
+
raw := strings.TrimSpace(c.Query("is_webui"))
|
| 127 |
+
if raw == "" {
|
| 128 |
+
return false
|
| 129 |
+
}
|
| 130 |
+
switch strings.ToLower(raw) {
|
| 131 |
+
case "1", "true", "yes", "on":
|
| 132 |
+
return true
|
| 133 |
+
default:
|
| 134 |
+
return false
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
func startCallbackForwarder(port int, provider, targetBase string) (*callbackForwarder, error) {
|
| 139 |
+
callbackForwardersMu.Lock()
|
| 140 |
+
prev := callbackForwarders[port]
|
| 141 |
+
if prev != nil {
|
| 142 |
+
delete(callbackForwarders, port)
|
| 143 |
+
}
|
| 144 |
+
callbackForwardersMu.Unlock()
|
| 145 |
+
|
| 146 |
+
if prev != nil {
|
| 147 |
+
stopForwarderInstance(port, prev)
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
addr := fmt.Sprintf("0.0.0.0:%d", port)
|
| 151 |
+
ln, err := net.Listen("tcp", addr)
|
| 152 |
+
if err != nil {
|
| 153 |
+
return nil, fmt.Errorf("failed to listen on %s: %w", addr, err)
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 157 |
+
target := targetBase
|
| 158 |
+
if raw := r.URL.RawQuery; raw != "" {
|
| 159 |
+
if strings.Contains(target, "?") {
|
| 160 |
+
target = target + "&" + raw
|
| 161 |
+
} else {
|
| 162 |
+
target = target + "?" + raw
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
w.Header().Set("Cache-Control", "no-store")
|
| 166 |
+
http.Redirect(w, r, target, http.StatusFound)
|
| 167 |
+
})
|
| 168 |
+
|
| 169 |
+
srv := &http.Server{
|
| 170 |
+
Handler: handler,
|
| 171 |
+
ReadHeaderTimeout: 5 * time.Second,
|
| 172 |
+
WriteTimeout: 5 * time.Second,
|
| 173 |
+
}
|
| 174 |
+
done := make(chan struct{})
|
| 175 |
+
|
| 176 |
+
go func() {
|
| 177 |
+
if errServe := srv.Serve(ln); errServe != nil && !errors.Is(errServe, http.ErrServerClosed) {
|
| 178 |
+
log.WithError(errServe).Warnf("callback forwarder for %s stopped unexpectedly", provider)
|
| 179 |
+
}
|
| 180 |
+
close(done)
|
| 181 |
+
}()
|
| 182 |
+
|
| 183 |
+
forwarder := &callbackForwarder{
|
| 184 |
+
provider: provider,
|
| 185 |
+
server: srv,
|
| 186 |
+
done: done,
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
callbackForwardersMu.Lock()
|
| 190 |
+
callbackForwarders[port] = forwarder
|
| 191 |
+
callbackForwardersMu.Unlock()
|
| 192 |
+
|
| 193 |
+
log.Infof("callback forwarder for %s listening on %s", provider, addr)
|
| 194 |
+
|
| 195 |
+
return forwarder, nil
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
func stopCallbackForwarderInstance(port int, forwarder *callbackForwarder) {
|
| 199 |
+
if forwarder == nil {
|
| 200 |
+
return
|
| 201 |
+
}
|
| 202 |
+
callbackForwardersMu.Lock()
|
| 203 |
+
if current := callbackForwarders[port]; current == forwarder {
|
| 204 |
+
delete(callbackForwarders, port)
|
| 205 |
+
}
|
| 206 |
+
callbackForwardersMu.Unlock()
|
| 207 |
+
|
| 208 |
+
stopForwarderInstance(port, forwarder)
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
func stopForwarderInstance(port int, forwarder *callbackForwarder) {
|
| 212 |
+
if forwarder == nil || forwarder.server == nil {
|
| 213 |
+
return
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
| 217 |
+
defer cancel()
|
| 218 |
+
|
| 219 |
+
if err := forwarder.server.Shutdown(ctx); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
| 220 |
+
log.WithError(err).Warnf("failed to shut down callback forwarder on port %d", port)
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
select {
|
| 224 |
+
case <-forwarder.done:
|
| 225 |
+
case <-time.After(2 * time.Second):
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
log.Infof("callback forwarder on port %d stopped", port)
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
func (h *Handler) managementCallbackURL(path string) (string, error) {
|
| 232 |
+
if h == nil || h.cfg == nil || h.cfg.Port <= 0 {
|
| 233 |
+
return "", fmt.Errorf("server port is not configured")
|
| 234 |
+
}
|
| 235 |
+
if !strings.HasPrefix(path, "/") {
|
| 236 |
+
path = "/" + path
|
| 237 |
+
}
|
| 238 |
+
scheme := "http"
|
| 239 |
+
if h.cfg.TLS.Enable {
|
| 240 |
+
scheme = "https"
|
| 241 |
+
}
|
| 242 |
+
return fmt.Sprintf("%s://127.0.0.1:%d%s", scheme, h.cfg.Port, path), nil
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
func pluginAuthProviderFromPath(path string) (string, bool) {
|
| 246 |
+
path = strings.TrimSpace(path)
|
| 247 |
+
const prefix = "/v0/management/"
|
| 248 |
+
const suffix = "-auth-url"
|
| 249 |
+
if !strings.HasPrefix(path, prefix) || !strings.HasSuffix(path, suffix) {
|
| 250 |
+
return "", false
|
| 251 |
+
}
|
| 252 |
+
provider := strings.TrimSuffix(strings.TrimPrefix(path, prefix), suffix)
|
| 253 |
+
provider = strings.ToLower(strings.TrimSpace(provider))
|
| 254 |
+
if provider == "" {
|
| 255 |
+
return "", false
|
| 256 |
+
}
|
| 257 |
+
for _, r := range provider {
|
| 258 |
+
switch {
|
| 259 |
+
case r >= 'a' && r <= 'z':
|
| 260 |
+
case r >= '0' && r <= '9':
|
| 261 |
+
case r == '-':
|
| 262 |
+
default:
|
| 263 |
+
return "", false
|
| 264 |
+
}
|
| 265 |
+
}
|
| 266 |
+
return provider, true
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
func (h *Handler) ServePluginAuthURL(c *gin.Context) bool {
|
| 270 |
+
if h == nil || c == nil || c.Request == nil || c.Request.URL == nil {
|
| 271 |
+
return false
|
| 272 |
+
}
|
| 273 |
+
h.mu.Lock()
|
| 274 |
+
host := h.pluginHost
|
| 275 |
+
h.mu.Unlock()
|
| 276 |
+
if host == nil {
|
| 277 |
+
return false
|
| 278 |
+
}
|
| 279 |
+
provider, ok := pluginAuthProviderFromPath(c.Request.URL.Path)
|
| 280 |
+
if !ok || !host.HasAuthProvider(provider) {
|
| 281 |
+
return false
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
ctx := PopulateAuthContext(context.Background(), c)
|
| 285 |
+
baseURL, errBaseURL := h.managementCallbackURL("/v0/management/oauth-callback")
|
| 286 |
+
if errBaseURL != nil {
|
| 287 |
+
log.WithError(errBaseURL).Error("failed to compute plugin auth callback URL")
|
| 288 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate authorization url"})
|
| 289 |
+
return true
|
| 290 |
+
}
|
| 291 |
+
resp, handled, errStart := host.StartLogin(ctx, provider, baseURL)
|
| 292 |
+
if !handled {
|
| 293 |
+
return false
|
| 294 |
+
}
|
| 295 |
+
if errStart != nil {
|
| 296 |
+
log.WithError(errStart).Error("failed to start plugin auth login")
|
| 297 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate authorization url"})
|
| 298 |
+
return true
|
| 299 |
+
}
|
| 300 |
+
state := strings.TrimSpace(resp.State)
|
| 301 |
+
if state == "" {
|
| 302 |
+
log.WithField("provider", provider).Error("plugin auth provider returned empty state")
|
| 303 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "invalid oauth state"})
|
| 304 |
+
return true
|
| 305 |
+
}
|
| 306 |
+
if errState := ValidateOAuthState(state); errState != nil {
|
| 307 |
+
log.WithError(errState).WithField("provider", provider).Error("plugin auth provider returned invalid state")
|
| 308 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "invalid oauth state"})
|
| 309 |
+
return true
|
| 310 |
+
}
|
| 311 |
+
if errRegister := RegisterPluginOAuthSession(state, provider, resp.Metadata); errRegister != nil {
|
| 312 |
+
log.WithError(errRegister).WithField("provider", provider).Error("failed to register plugin oauth session")
|
| 313 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "failed to generate authorization url"})
|
| 314 |
+
return true
|
| 315 |
+
}
|
| 316 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok", "url": resp.URL, "state": state})
|
| 317 |
+
return true
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
func (h *Handler) ListAuthFiles(c *gin.Context) {
|
| 321 |
+
if h == nil {
|
| 322 |
+
c.JSON(500, gin.H{"error": "handler not initialized"})
|
| 323 |
+
return
|
| 324 |
+
}
|
| 325 |
+
if h.authManager == nil {
|
| 326 |
+
h.listAuthFilesFromDisk(c)
|
| 327 |
+
return
|
| 328 |
+
}
|
| 329 |
+
nameFilter := strings.TrimSpace(c.Query("name"))
|
| 330 |
+
authIndexFilter := strings.TrimSpace(c.Query("auth_index"))
|
| 331 |
+
auths := h.authManager.List()
|
| 332 |
+
files := make([]gin.H, 0, len(auths))
|
| 333 |
+
for _, auth := range auths {
|
| 334 |
+
if !matchesAuthFileLookup(auth, nameFilter, authIndexFilter) {
|
| 335 |
+
continue
|
| 336 |
+
}
|
| 337 |
+
if entry := h.buildAuthFileEntry(auth); entry != nil {
|
| 338 |
+
files = append(files, entry)
|
| 339 |
+
}
|
| 340 |
+
}
|
| 341 |
+
sort.Slice(files, func(i, j int) bool {
|
| 342 |
+
nameI, _ := files[i]["name"].(string)
|
| 343 |
+
nameJ, _ := files[j]["name"].(string)
|
| 344 |
+
return strings.ToLower(nameI) < strings.ToLower(nameJ)
|
| 345 |
+
})
|
| 346 |
+
c.JSON(200, gin.H{"files": files})
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
func lockedAuthIndex(auth *coreauth.Auth) string {
|
| 350 |
+
if auth == nil {
|
| 351 |
+
return ""
|
| 352 |
+
}
|
| 353 |
+
authFileEntryMu.Lock()
|
| 354 |
+
defer authFileEntryMu.Unlock()
|
| 355 |
+
return strings.TrimSpace(auth.EnsureIndex())
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
func matchesAuthFileLookup(auth *coreauth.Auth, name string, authIndex string) bool {
|
| 359 |
+
if auth == nil {
|
| 360 |
+
return false
|
| 361 |
+
}
|
| 362 |
+
if name != "" && strings.TrimSpace(auth.ID) != name && strings.TrimSpace(auth.FileName) != name {
|
| 363 |
+
return false
|
| 364 |
+
}
|
| 365 |
+
if authIndex != "" && lockedAuthIndex(auth) != authIndex {
|
| 366 |
+
return false
|
| 367 |
+
}
|
| 368 |
+
return true
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
func (h *Handler) lookupAuthFile(name string, authIndex string) (*coreauth.Auth, bool) {
|
| 372 |
+
name = strings.TrimSpace(name)
|
| 373 |
+
authIndex = strings.TrimSpace(authIndex)
|
| 374 |
+
if h == nil || h.authManager == nil || name == "" {
|
| 375 |
+
return nil, false
|
| 376 |
+
}
|
| 377 |
+
if authIndex == "" {
|
| 378 |
+
if auth, ok := h.authManager.GetByID(name); ok {
|
| 379 |
+
return auth, true
|
| 380 |
+
}
|
| 381 |
+
auths := h.authManager.List()
|
| 382 |
+
for _, auth := range auths {
|
| 383 |
+
if auth != nil && strings.TrimSpace(auth.FileName) == name {
|
| 384 |
+
return auth, true
|
| 385 |
+
}
|
| 386 |
+
}
|
| 387 |
+
return nil, false
|
| 388 |
+
}
|
| 389 |
+
auths := h.authManager.List()
|
| 390 |
+
for _, auth := range auths {
|
| 391 |
+
if matchesAuthFileLookup(auth, name, authIndex) {
|
| 392 |
+
return auth, true
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
return nil, false
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
// GetAuthFileModels returns the models supported by a specific auth file
|
| 399 |
+
func (h *Handler) GetAuthFileModels(c *gin.Context) {
|
| 400 |
+
name := c.Query("name")
|
| 401 |
+
if name == "" {
|
| 402 |
+
c.JSON(400, gin.H{"error": "name is required"})
|
| 403 |
+
return
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
// Try to find auth ID via authManager
|
| 407 |
+
var authID string
|
| 408 |
+
if h.authManager != nil {
|
| 409 |
+
auths := h.authManager.List()
|
| 410 |
+
for _, auth := range auths {
|
| 411 |
+
if auth.FileName == name || auth.ID == name {
|
| 412 |
+
authID = auth.ID
|
| 413 |
+
break
|
| 414 |
+
}
|
| 415 |
+
}
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
if authID == "" {
|
| 419 |
+
authID = name // fallback to filename as ID
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
// Get models from registry
|
| 423 |
+
reg := registry.GetGlobalRegistry()
|
| 424 |
+
models := reg.GetModelsForClient(authID)
|
| 425 |
+
|
| 426 |
+
result := make([]gin.H, 0, len(models))
|
| 427 |
+
for _, m := range models {
|
| 428 |
+
entry := gin.H{
|
| 429 |
+
"id": m.ID,
|
| 430 |
+
}
|
| 431 |
+
if m.DisplayName != "" {
|
| 432 |
+
entry["display_name"] = m.DisplayName
|
| 433 |
+
}
|
| 434 |
+
if m.Type != "" {
|
| 435 |
+
entry["type"] = m.Type
|
| 436 |
+
}
|
| 437 |
+
if m.OwnedBy != "" {
|
| 438 |
+
entry["owned_by"] = m.OwnedBy
|
| 439 |
+
}
|
| 440 |
+
result = append(result, entry)
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
c.JSON(200, gin.H{"models": result})
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
// List auth files from disk when the auth manager is unavailable.
|
| 447 |
+
func (h *Handler) listAuthFilesFromDisk(c *gin.Context) {
|
| 448 |
+
nameFilter := strings.TrimSpace(c.Query("name"))
|
| 449 |
+
authIndexFilter := strings.TrimSpace(c.Query("auth_index"))
|
| 450 |
+
entries, err := os.ReadDir(h.cfg.AuthDir)
|
| 451 |
+
if err != nil {
|
| 452 |
+
c.JSON(500, gin.H{"error": fmt.Sprintf("failed to read auth dir: %v", err)})
|
| 453 |
+
return
|
| 454 |
+
}
|
| 455 |
+
files := make([]gin.H, 0)
|
| 456 |
+
if authIndexFilter != "" {
|
| 457 |
+
c.JSON(200, gin.H{"files": files})
|
| 458 |
+
return
|
| 459 |
+
}
|
| 460 |
+
for _, e := range entries {
|
| 461 |
+
if e.IsDir() {
|
| 462 |
+
continue
|
| 463 |
+
}
|
| 464 |
+
name := e.Name()
|
| 465 |
+
if nameFilter != "" && name != nameFilter {
|
| 466 |
+
continue
|
| 467 |
+
}
|
| 468 |
+
if !strings.HasSuffix(strings.ToLower(name), ".json") {
|
| 469 |
+
continue
|
| 470 |
+
}
|
| 471 |
+
if info, errInfo := e.Info(); errInfo == nil {
|
| 472 |
+
fileData := gin.H{"name": name, "size": info.Size(), "modtime": info.ModTime()}
|
| 473 |
+
|
| 474 |
+
// Read file to get type field
|
| 475 |
+
full := filepath.Join(h.cfg.AuthDir, name)
|
| 476 |
+
if data, errRead := os.ReadFile(full); errRead == nil {
|
| 477 |
+
typeValue := gjson.GetBytes(data, "type").String()
|
| 478 |
+
emailValue := gjson.GetBytes(data, "email").String()
|
| 479 |
+
fileData["type"] = typeValue
|
| 480 |
+
fileData["email"] = emailValue
|
| 481 |
+
if projectID := strings.TrimSpace(gjson.GetBytes(data, "project_id").String()); projectID != "" {
|
| 482 |
+
fileData["project_id"] = projectID
|
| 483 |
+
}
|
| 484 |
+
if pv := gjson.GetBytes(data, "priority"); pv.Exists() {
|
| 485 |
+
switch pv.Type {
|
| 486 |
+
case gjson.Number:
|
| 487 |
+
fileData["priority"] = int(pv.Int())
|
| 488 |
+
case gjson.String:
|
| 489 |
+
if parsed, errAtoi := strconv.Atoi(strings.TrimSpace(pv.String())); errAtoi == nil {
|
| 490 |
+
fileData["priority"] = parsed
|
| 491 |
+
}
|
| 492 |
+
}
|
| 493 |
+
}
|
| 494 |
+
if nv := gjson.GetBytes(data, "note"); nv.Exists() && nv.Type == gjson.String {
|
| 495 |
+
if trimmed := strings.TrimSpace(nv.String()); trimmed != "" {
|
| 496 |
+
fileData["note"] = trimmed
|
| 497 |
+
}
|
| 498 |
+
}
|
| 499 |
+
if wv := gjson.GetBytes(data, "websockets"); wv.Exists() {
|
| 500 |
+
switch wv.Type {
|
| 501 |
+
case gjson.True:
|
| 502 |
+
fileData["websockets"] = true
|
| 503 |
+
case gjson.False:
|
| 504 |
+
fileData["websockets"] = false
|
| 505 |
+
case gjson.String:
|
| 506 |
+
if parsed, errParse := strconv.ParseBool(strings.TrimSpace(wv.String())); errParse == nil {
|
| 507 |
+
fileData["websockets"] = parsed
|
| 508 |
+
}
|
| 509 |
+
}
|
| 510 |
+
}
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
files = append(files, fileData)
|
| 514 |
+
}
|
| 515 |
+
}
|
| 516 |
+
c.JSON(200, gin.H{"files": files})
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
func (h *Handler) buildAuthFileEntry(auth *coreauth.Auth) gin.H {
|
| 520 |
+
authFileEntryMu.Lock()
|
| 521 |
+
defer authFileEntryMu.Unlock()
|
| 522 |
+
return h.buildAuthFileEntryLocked(auth)
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
func (h *Handler) buildAuthFileEntryLocked(auth *coreauth.Auth) gin.H {
|
| 526 |
+
if auth == nil {
|
| 527 |
+
return nil
|
| 528 |
+
}
|
| 529 |
+
auth.EnsureIndex()
|
| 530 |
+
runtimeOnly := isRuntimeOnlyAuth(auth)
|
| 531 |
+
if runtimeOnly && (auth.Disabled || auth.Status == coreauth.StatusDisabled) {
|
| 532 |
+
return nil
|
| 533 |
+
}
|
| 534 |
+
path := strings.TrimSpace(authAttribute(auth, "path"))
|
| 535 |
+
if path == "" && !runtimeOnly {
|
| 536 |
+
return nil
|
| 537 |
+
}
|
| 538 |
+
name := strings.TrimSpace(auth.FileName)
|
| 539 |
+
if name == "" {
|
| 540 |
+
name = auth.ID
|
| 541 |
+
}
|
| 542 |
+
entry := gin.H{
|
| 543 |
+
"id": auth.ID,
|
| 544 |
+
"auth_index": auth.Index,
|
| 545 |
+
"name": name,
|
| 546 |
+
"type": strings.TrimSpace(auth.Provider),
|
| 547 |
+
"provider": strings.TrimSpace(auth.Provider),
|
| 548 |
+
"label": auth.Label,
|
| 549 |
+
"status": auth.Status,
|
| 550 |
+
"status_message": auth.StatusMessage,
|
| 551 |
+
"disabled": auth.Disabled,
|
| 552 |
+
"unavailable": auth.Unavailable,
|
| 553 |
+
"runtime_only": runtimeOnly,
|
| 554 |
+
"source": "memory",
|
| 555 |
+
"size": int64(0),
|
| 556 |
+
}
|
| 557 |
+
entry["success"] = auth.Success
|
| 558 |
+
entry["failed"] = auth.Failed
|
| 559 |
+
entry["recent_requests"] = auth.RecentRequestsSnapshot(time.Now())
|
| 560 |
+
if email := authEmail(auth); email != "" {
|
| 561 |
+
entry["email"] = email
|
| 562 |
+
}
|
| 563 |
+
if projectID := authProjectID(auth); projectID != "" {
|
| 564 |
+
entry["project_id"] = projectID
|
| 565 |
+
}
|
| 566 |
+
if accountType, account := auth.AccountInfo(); accountType != "" || account != "" {
|
| 567 |
+
if accountType != "" {
|
| 568 |
+
entry["account_type"] = accountType
|
| 569 |
+
}
|
| 570 |
+
if account != "" {
|
| 571 |
+
entry["account"] = account
|
| 572 |
+
}
|
| 573 |
+
}
|
| 574 |
+
if !auth.CreatedAt.IsZero() {
|
| 575 |
+
entry["created_at"] = auth.CreatedAt
|
| 576 |
+
}
|
| 577 |
+
if !auth.UpdatedAt.IsZero() {
|
| 578 |
+
entry["modtime"] = auth.UpdatedAt
|
| 579 |
+
entry["updated_at"] = auth.UpdatedAt
|
| 580 |
+
}
|
| 581 |
+
if !auth.LastRefreshedAt.IsZero() {
|
| 582 |
+
entry["last_refresh"] = auth.LastRefreshedAt
|
| 583 |
+
}
|
| 584 |
+
if !auth.NextRetryAfter.IsZero() {
|
| 585 |
+
entry["next_retry_after"] = auth.NextRetryAfter
|
| 586 |
+
}
|
| 587 |
+
if path != "" {
|
| 588 |
+
entry["path"] = path
|
| 589 |
+
entry["source"] = "file"
|
| 590 |
+
if info, err := os.Stat(path); err == nil {
|
| 591 |
+
entry["size"] = info.Size()
|
| 592 |
+
entry["modtime"] = info.ModTime()
|
| 593 |
+
} else if os.IsNotExist(err) {
|
| 594 |
+
// Hide credentials removed from disk but still lingering in memory.
|
| 595 |
+
if !runtimeOnly && (auth.Disabled || auth.Status == coreauth.StatusDisabled || strings.EqualFold(strings.TrimSpace(auth.StatusMessage), "removed via management api")) {
|
| 596 |
+
return nil
|
| 597 |
+
}
|
| 598 |
+
entry["source"] = "memory"
|
| 599 |
+
} else {
|
| 600 |
+
log.WithError(err).Warnf("failed to stat auth file %s", path)
|
| 601 |
+
}
|
| 602 |
+
}
|
| 603 |
+
if claims := extractCodexIDTokenClaims(auth); claims != nil {
|
| 604 |
+
entry["id_token"] = claims
|
| 605 |
+
}
|
| 606 |
+
// Expose priority from Attributes (set by synthesizer from JSON "priority" field).
|
| 607 |
+
// Fall back to Metadata for auths registered via UploadAuthFile (no synthesizer).
|
| 608 |
+
if p := strings.TrimSpace(authAttribute(auth, "priority")); p != "" {
|
| 609 |
+
if parsed, err := strconv.Atoi(p); err == nil {
|
| 610 |
+
entry["priority"] = parsed
|
| 611 |
+
}
|
| 612 |
+
} else if auth.Metadata != nil {
|
| 613 |
+
if rawPriority, ok := auth.Metadata["priority"]; ok {
|
| 614 |
+
switch v := rawPriority.(type) {
|
| 615 |
+
case float64:
|
| 616 |
+
entry["priority"] = int(v)
|
| 617 |
+
case int:
|
| 618 |
+
entry["priority"] = v
|
| 619 |
+
case string:
|
| 620 |
+
if parsed, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {
|
| 621 |
+
entry["priority"] = parsed
|
| 622 |
+
}
|
| 623 |
+
}
|
| 624 |
+
}
|
| 625 |
+
}
|
| 626 |
+
// Expose note from Attributes (set by synthesizer from JSON "note" field).
|
| 627 |
+
// Fall back to Metadata for auths registered via UploadAuthFile (no synthesizer).
|
| 628 |
+
if note := strings.TrimSpace(authAttribute(auth, "note")); note != "" {
|
| 629 |
+
entry["note"] = note
|
| 630 |
+
} else if auth.Metadata != nil {
|
| 631 |
+
if rawNote, ok := auth.Metadata["note"].(string); ok {
|
| 632 |
+
if trimmed := strings.TrimSpace(rawNote); trimmed != "" {
|
| 633 |
+
entry["note"] = trimmed
|
| 634 |
+
}
|
| 635 |
+
}
|
| 636 |
+
}
|
| 637 |
+
if websockets, ok := authWebsocketsValue(auth); ok {
|
| 638 |
+
entry["websockets"] = websockets
|
| 639 |
+
}
|
| 640 |
+
return entry
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
func authWebsocketsValue(auth *coreauth.Auth) (bool, bool) {
|
| 644 |
+
if auth == nil {
|
| 645 |
+
return false, false
|
| 646 |
+
}
|
| 647 |
+
if auth.Attributes != nil {
|
| 648 |
+
if raw := strings.TrimSpace(auth.Attributes["websockets"]); raw != "" {
|
| 649 |
+
parsed, errParse := strconv.ParseBool(raw)
|
| 650 |
+
if errParse == nil {
|
| 651 |
+
return parsed, true
|
| 652 |
+
}
|
| 653 |
+
}
|
| 654 |
+
}
|
| 655 |
+
if auth.Metadata == nil {
|
| 656 |
+
return false, false
|
| 657 |
+
}
|
| 658 |
+
raw, ok := auth.Metadata["websockets"]
|
| 659 |
+
if !ok || raw == nil {
|
| 660 |
+
return false, false
|
| 661 |
+
}
|
| 662 |
+
switch v := raw.(type) {
|
| 663 |
+
case bool:
|
| 664 |
+
return v, true
|
| 665 |
+
case string:
|
| 666 |
+
parsed, errParse := strconv.ParseBool(strings.TrimSpace(v))
|
| 667 |
+
if errParse == nil {
|
| 668 |
+
return parsed, true
|
| 669 |
+
}
|
| 670 |
+
}
|
| 671 |
+
return false, false
|
| 672 |
+
}
|
| 673 |
+
|
| 674 |
+
func authProjectID(auth *coreauth.Auth) string {
|
| 675 |
+
if auth == nil {
|
| 676 |
+
return ""
|
| 677 |
+
}
|
| 678 |
+
if auth.Metadata != nil {
|
| 679 |
+
if v, ok := auth.Metadata["project_id"].(string); ok {
|
| 680 |
+
if projectID := strings.TrimSpace(v); projectID != "" {
|
| 681 |
+
return projectID
|
| 682 |
+
}
|
| 683 |
+
}
|
| 684 |
+
}
|
| 685 |
+
if auth.Attributes != nil {
|
| 686 |
+
if projectID := strings.TrimSpace(auth.Attributes["project_id"]); projectID != "" {
|
| 687 |
+
return projectID
|
| 688 |
+
}
|
| 689 |
+
}
|
| 690 |
+
return ""
|
| 691 |
+
}
|
| 692 |
+
|
| 693 |
+
func extractCodexIDTokenClaims(auth *coreauth.Auth) gin.H {
|
| 694 |
+
if auth == nil || auth.Metadata == nil {
|
| 695 |
+
return nil
|
| 696 |
+
}
|
| 697 |
+
if !strings.EqualFold(strings.TrimSpace(auth.Provider), "codex") {
|
| 698 |
+
return nil
|
| 699 |
+
}
|
| 700 |
+
idTokenRaw, ok := auth.Metadata["id_token"].(string)
|
| 701 |
+
if !ok {
|
| 702 |
+
return nil
|
| 703 |
+
}
|
| 704 |
+
idToken := strings.TrimSpace(idTokenRaw)
|
| 705 |
+
if idToken == "" {
|
| 706 |
+
return nil
|
| 707 |
+
}
|
| 708 |
+
claims, err := codex.ParseJWTToken(idToken)
|
| 709 |
+
if err != nil || claims == nil {
|
| 710 |
+
return nil
|
| 711 |
+
}
|
| 712 |
+
|
| 713 |
+
result := gin.H{}
|
| 714 |
+
if v := strings.TrimSpace(claims.CodexAuthInfo.ChatgptAccountID); v != "" {
|
| 715 |
+
result["chatgpt_account_id"] = v
|
| 716 |
+
}
|
| 717 |
+
if v := strings.TrimSpace(claims.CodexAuthInfo.ChatgptPlanType); v != "" {
|
| 718 |
+
result["plan_type"] = v
|
| 719 |
+
}
|
| 720 |
+
if v := claims.CodexAuthInfo.ChatgptSubscriptionActiveStart; v != nil {
|
| 721 |
+
result["chatgpt_subscription_active_start"] = v
|
| 722 |
+
}
|
| 723 |
+
if v := claims.CodexAuthInfo.ChatgptSubscriptionActiveUntil; v != nil {
|
| 724 |
+
result["chatgpt_subscription_active_until"] = v
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
if len(result) == 0 {
|
| 728 |
+
return nil
|
| 729 |
+
}
|
| 730 |
+
return result
|
| 731 |
+
}
|
| 732 |
+
|
| 733 |
+
func authEmail(auth *coreauth.Auth) string {
|
| 734 |
+
if auth == nil {
|
| 735 |
+
return ""
|
| 736 |
+
}
|
| 737 |
+
if auth.Metadata != nil {
|
| 738 |
+
if v, ok := auth.Metadata["email"].(string); ok {
|
| 739 |
+
return strings.TrimSpace(v)
|
| 740 |
+
}
|
| 741 |
+
}
|
| 742 |
+
if auth.Attributes != nil {
|
| 743 |
+
if v := strings.TrimSpace(auth.Attributes["email"]); v != "" {
|
| 744 |
+
return v
|
| 745 |
+
}
|
| 746 |
+
if v := strings.TrimSpace(auth.Attributes["account_email"]); v != "" {
|
| 747 |
+
return v
|
| 748 |
+
}
|
| 749 |
+
}
|
| 750 |
+
return ""
|
| 751 |
+
}
|
| 752 |
+
|
| 753 |
+
func authAttribute(auth *coreauth.Auth, key string) string {
|
| 754 |
+
if auth == nil || len(auth.Attributes) == 0 {
|
| 755 |
+
return ""
|
| 756 |
+
}
|
| 757 |
+
return auth.Attributes[key]
|
| 758 |
+
}
|
| 759 |
+
|
| 760 |
+
func isRuntimeOnlyAuth(auth *coreauth.Auth) bool {
|
| 761 |
+
if auth == nil || len(auth.Attributes) == 0 {
|
| 762 |
+
return false
|
| 763 |
+
}
|
| 764 |
+
return strings.EqualFold(strings.TrimSpace(auth.Attributes["runtime_only"]), "true")
|
| 765 |
+
}
|
| 766 |
+
|
| 767 |
+
func isUnsafeAuthFileName(name string) bool {
|
| 768 |
+
if strings.TrimSpace(name) == "" {
|
| 769 |
+
return true
|
| 770 |
+
}
|
| 771 |
+
if strings.ContainsAny(name, "/\\") {
|
| 772 |
+
return true
|
| 773 |
+
}
|
| 774 |
+
if filepath.VolumeName(name) != "" {
|
| 775 |
+
return true
|
| 776 |
+
}
|
| 777 |
+
return false
|
| 778 |
+
}
|
| 779 |
+
|
| 780 |
+
// Download single auth file by name
|
| 781 |
+
func (h *Handler) DownloadAuthFile(c *gin.Context) {
|
| 782 |
+
name := strings.TrimSpace(c.Query("name"))
|
| 783 |
+
if isUnsafeAuthFileName(name) {
|
| 784 |
+
c.JSON(400, gin.H{"error": "invalid name"})
|
| 785 |
+
return
|
| 786 |
+
}
|
| 787 |
+
if !strings.HasSuffix(strings.ToLower(name), ".json") {
|
| 788 |
+
c.JSON(400, gin.H{"error": "name must end with .json"})
|
| 789 |
+
return
|
| 790 |
+
}
|
| 791 |
+
full := filepath.Join(h.cfg.AuthDir, name)
|
| 792 |
+
data, err := os.ReadFile(full)
|
| 793 |
+
if err != nil {
|
| 794 |
+
if os.IsNotExist(err) {
|
| 795 |
+
c.JSON(404, gin.H{"error": "file not found"})
|
| 796 |
+
} else {
|
| 797 |
+
c.JSON(500, gin.H{"error": fmt.Sprintf("failed to read file: %v", err)})
|
| 798 |
+
}
|
| 799 |
+
return
|
| 800 |
+
}
|
| 801 |
+
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", name))
|
| 802 |
+
c.Data(200, "application/json", data)
|
| 803 |
+
}
|
| 804 |
+
|
| 805 |
+
// Upload auth file: multipart or raw JSON with ?name=
|
| 806 |
+
func (h *Handler) UploadAuthFile(c *gin.Context) {
|
| 807 |
+
if h.authManager == nil {
|
| 808 |
+
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "core auth manager unavailable"})
|
| 809 |
+
return
|
| 810 |
+
}
|
| 811 |
+
ctx := c.Request.Context()
|
| 812 |
+
|
| 813 |
+
fileHeaders, errMultipart := h.multipartAuthFileHeaders(c)
|
| 814 |
+
if errMultipart != nil {
|
| 815 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid multipart form: %v", errMultipart)})
|
| 816 |
+
return
|
| 817 |
+
}
|
| 818 |
+
if len(fileHeaders) == 1 {
|
| 819 |
+
if _, errUpload := h.storeUploadedAuthFile(ctx, fileHeaders[0]); errUpload != nil {
|
| 820 |
+
if errors.Is(errUpload, errAuthFileMustBeJSON) {
|
| 821 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "file must be .json"})
|
| 822 |
+
return
|
| 823 |
+
}
|
| 824 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": errUpload.Error()})
|
| 825 |
+
return
|
| 826 |
+
}
|
| 827 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
| 828 |
+
return
|
| 829 |
+
}
|
| 830 |
+
if len(fileHeaders) > 1 {
|
| 831 |
+
uploaded := make([]string, 0, len(fileHeaders))
|
| 832 |
+
failed := make([]gin.H, 0)
|
| 833 |
+
for _, file := range fileHeaders {
|
| 834 |
+
name, errUpload := h.storeUploadedAuthFile(ctx, file)
|
| 835 |
+
if errUpload != nil {
|
| 836 |
+
failureName := ""
|
| 837 |
+
if file != nil {
|
| 838 |
+
failureName = filepath.Base(file.Filename)
|
| 839 |
+
}
|
| 840 |
+
msg := errUpload.Error()
|
| 841 |
+
if errors.Is(errUpload, errAuthFileMustBeJSON) {
|
| 842 |
+
msg = "file must be .json"
|
| 843 |
+
}
|
| 844 |
+
failed = append(failed, gin.H{"name": failureName, "error": msg})
|
| 845 |
+
continue
|
| 846 |
+
}
|
| 847 |
+
uploaded = append(uploaded, name)
|
| 848 |
+
}
|
| 849 |
+
if len(failed) > 0 {
|
| 850 |
+
c.JSON(http.StatusMultiStatus, gin.H{
|
| 851 |
+
"status": "partial",
|
| 852 |
+
"uploaded": len(uploaded),
|
| 853 |
+
"files": uploaded,
|
| 854 |
+
"failed": failed,
|
| 855 |
+
})
|
| 856 |
+
return
|
| 857 |
+
}
|
| 858 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok", "uploaded": len(uploaded), "files": uploaded})
|
| 859 |
+
return
|
| 860 |
+
}
|
| 861 |
+
if c.ContentType() == "multipart/form-data" {
|
| 862 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "no files uploaded"})
|
| 863 |
+
return
|
| 864 |
+
}
|
| 865 |
+
name := strings.TrimSpace(c.Query("name"))
|
| 866 |
+
if isUnsafeAuthFileName(name) {
|
| 867 |
+
c.JSON(400, gin.H{"error": "invalid name"})
|
| 868 |
+
return
|
| 869 |
+
}
|
| 870 |
+
if !strings.HasSuffix(strings.ToLower(name), ".json") {
|
| 871 |
+
c.JSON(400, gin.H{"error": "name must end with .json"})
|
| 872 |
+
return
|
| 873 |
+
}
|
| 874 |
+
data, err := io.ReadAll(c.Request.Body)
|
| 875 |
+
if err != nil {
|
| 876 |
+
c.JSON(400, gin.H{"error": "failed to read body"})
|
| 877 |
+
return
|
| 878 |
+
}
|
| 879 |
+
if err = h.writeAuthFile(ctx, filepath.Base(name), data); err != nil {
|
| 880 |
+
c.JSON(500, gin.H{"error": err.Error()})
|
| 881 |
+
return
|
| 882 |
+
}
|
| 883 |
+
c.JSON(200, gin.H{"status": "ok"})
|
| 884 |
+
}
|
| 885 |
+
|
| 886 |
+
// Delete auth files: single by name or all
|
| 887 |
+
func (h *Handler) DeleteAuthFile(c *gin.Context) {
|
| 888 |
+
if h.authManager == nil {
|
| 889 |
+
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "core auth manager unavailable"})
|
| 890 |
+
return
|
| 891 |
+
}
|
| 892 |
+
ctx := c.Request.Context()
|
| 893 |
+
if all := c.Query("all"); all == "true" || all == "1" || all == "*" {
|
| 894 |
+
entries, err := os.ReadDir(h.cfg.AuthDir)
|
| 895 |
+
if err != nil {
|
| 896 |
+
c.JSON(500, gin.H{"error": fmt.Sprintf("failed to read auth dir: %v", err)})
|
| 897 |
+
return
|
| 898 |
+
}
|
| 899 |
+
deleted := 0
|
| 900 |
+
for _, e := range entries {
|
| 901 |
+
if e.IsDir() {
|
| 902 |
+
continue
|
| 903 |
+
}
|
| 904 |
+
name := e.Name()
|
| 905 |
+
if !strings.HasSuffix(strings.ToLower(name), ".json") {
|
| 906 |
+
continue
|
| 907 |
+
}
|
| 908 |
+
full := filepath.Join(h.cfg.AuthDir, name)
|
| 909 |
+
if !filepath.IsAbs(full) {
|
| 910 |
+
if abs, errAbs := filepath.Abs(full); errAbs == nil {
|
| 911 |
+
full = abs
|
| 912 |
+
}
|
| 913 |
+
}
|
| 914 |
+
if err = os.Remove(full); err == nil {
|
| 915 |
+
if errDel := h.deleteTokenRecord(ctx, full); errDel != nil {
|
| 916 |
+
c.JSON(500, gin.H{"error": errDel.Error()})
|
| 917 |
+
return
|
| 918 |
+
}
|
| 919 |
+
deleted++
|
| 920 |
+
h.removeAuth(ctx, full)
|
| 921 |
+
}
|
| 922 |
+
}
|
| 923 |
+
c.JSON(200, gin.H{"status": "ok", "deleted": deleted})
|
| 924 |
+
return
|
| 925 |
+
}
|
| 926 |
+
|
| 927 |
+
names, errNames := requestedAuthFileNamesForDelete(c)
|
| 928 |
+
if errNames != nil {
|
| 929 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": errNames.Error()})
|
| 930 |
+
return
|
| 931 |
+
}
|
| 932 |
+
if len(names) == 0 {
|
| 933 |
+
c.JSON(400, gin.H{"error": "invalid name"})
|
| 934 |
+
return
|
| 935 |
+
}
|
| 936 |
+
if len(names) == 1 {
|
| 937 |
+
if _, status, errDelete := h.deleteAuthFileByName(ctx, names[0]); errDelete != nil {
|
| 938 |
+
c.JSON(status, gin.H{"error": errDelete.Error()})
|
| 939 |
+
return
|
| 940 |
+
}
|
| 941 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
| 942 |
+
return
|
| 943 |
+
}
|
| 944 |
+
|
| 945 |
+
deletedFiles := make([]string, 0, len(names))
|
| 946 |
+
failed := make([]gin.H, 0)
|
| 947 |
+
for _, name := range names {
|
| 948 |
+
deletedName, _, errDelete := h.deleteAuthFileByName(ctx, name)
|
| 949 |
+
if errDelete != nil {
|
| 950 |
+
failed = append(failed, gin.H{"name": name, "error": errDelete.Error()})
|
| 951 |
+
continue
|
| 952 |
+
}
|
| 953 |
+
deletedFiles = append(deletedFiles, deletedName)
|
| 954 |
+
}
|
| 955 |
+
if len(failed) > 0 {
|
| 956 |
+
c.JSON(http.StatusMultiStatus, gin.H{
|
| 957 |
+
"status": "partial",
|
| 958 |
+
"deleted": len(deletedFiles),
|
| 959 |
+
"files": deletedFiles,
|
| 960 |
+
"failed": failed,
|
| 961 |
+
})
|
| 962 |
+
return
|
| 963 |
+
}
|
| 964 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok", "deleted": len(deletedFiles), "files": deletedFiles})
|
| 965 |
+
}
|
| 966 |
+
|
| 967 |
+
func (h *Handler) multipartAuthFileHeaders(c *gin.Context) ([]*multipart.FileHeader, error) {
|
| 968 |
+
if h == nil || c == nil || c.ContentType() != "multipart/form-data" {
|
| 969 |
+
return nil, nil
|
| 970 |
+
}
|
| 971 |
+
form, err := c.MultipartForm()
|
| 972 |
+
if err != nil {
|
| 973 |
+
return nil, err
|
| 974 |
+
}
|
| 975 |
+
if form == nil || len(form.File) == 0 {
|
| 976 |
+
return nil, nil
|
| 977 |
+
}
|
| 978 |
+
|
| 979 |
+
keys := make([]string, 0, len(form.File))
|
| 980 |
+
for key := range form.File {
|
| 981 |
+
keys = append(keys, key)
|
| 982 |
+
}
|
| 983 |
+
sort.Strings(keys)
|
| 984 |
+
|
| 985 |
+
headers := make([]*multipart.FileHeader, 0)
|
| 986 |
+
for _, key := range keys {
|
| 987 |
+
headers = append(headers, form.File[key]...)
|
| 988 |
+
}
|
| 989 |
+
return headers, nil
|
| 990 |
+
}
|
| 991 |
+
|
| 992 |
+
func (h *Handler) storeUploadedAuthFile(ctx context.Context, file *multipart.FileHeader) (string, error) {
|
| 993 |
+
if file == nil {
|
| 994 |
+
return "", fmt.Errorf("no file uploaded")
|
| 995 |
+
}
|
| 996 |
+
name := filepath.Base(strings.TrimSpace(file.Filename))
|
| 997 |
+
if !strings.HasSuffix(strings.ToLower(name), ".json") {
|
| 998 |
+
return "", errAuthFileMustBeJSON
|
| 999 |
+
}
|
| 1000 |
+
src, err := file.Open()
|
| 1001 |
+
if err != nil {
|
| 1002 |
+
return "", fmt.Errorf("failed to open uploaded file: %w", err)
|
| 1003 |
+
}
|
| 1004 |
+
defer src.Close()
|
| 1005 |
+
|
| 1006 |
+
data, err := io.ReadAll(src)
|
| 1007 |
+
if err != nil {
|
| 1008 |
+
return "", fmt.Errorf("failed to read uploaded file: %w", err)
|
| 1009 |
+
}
|
| 1010 |
+
if err := h.writeAuthFile(ctx, name, data); err != nil {
|
| 1011 |
+
return "", err
|
| 1012 |
+
}
|
| 1013 |
+
return name, nil
|
| 1014 |
+
}
|
| 1015 |
+
|
| 1016 |
+
func (h *Handler) writeAuthFile(ctx context.Context, name string, data []byte) error {
|
| 1017 |
+
dst := filepath.Join(h.cfg.AuthDir, filepath.Base(name))
|
| 1018 |
+
if !filepath.IsAbs(dst) {
|
| 1019 |
+
if abs, errAbs := filepath.Abs(dst); errAbs == nil {
|
| 1020 |
+
dst = abs
|
| 1021 |
+
}
|
| 1022 |
+
}
|
| 1023 |
+
auth, err := h.buildAuthFromFileData(dst, data)
|
| 1024 |
+
if err != nil {
|
| 1025 |
+
return err
|
| 1026 |
+
}
|
| 1027 |
+
if errWrite := os.WriteFile(dst, data, 0o600); errWrite != nil {
|
| 1028 |
+
return fmt.Errorf("failed to write file: %w", errWrite)
|
| 1029 |
+
}
|
| 1030 |
+
if err := h.upsertAuthRecord(ctx, auth); err != nil {
|
| 1031 |
+
return err
|
| 1032 |
+
}
|
| 1033 |
+
return nil
|
| 1034 |
+
}
|
| 1035 |
+
|
| 1036 |
+
func requestedAuthFileNamesForDelete(c *gin.Context) ([]string, error) {
|
| 1037 |
+
if c == nil {
|
| 1038 |
+
return nil, nil
|
| 1039 |
+
}
|
| 1040 |
+
names := uniqueAuthFileNames(c.QueryArray("name"))
|
| 1041 |
+
if len(names) > 0 {
|
| 1042 |
+
return names, nil
|
| 1043 |
+
}
|
| 1044 |
+
|
| 1045 |
+
body, err := io.ReadAll(c.Request.Body)
|
| 1046 |
+
if err != nil {
|
| 1047 |
+
return nil, fmt.Errorf("failed to read body")
|
| 1048 |
+
}
|
| 1049 |
+
body = bytes.TrimSpace(body)
|
| 1050 |
+
if len(body) == 0 {
|
| 1051 |
+
return nil, nil
|
| 1052 |
+
}
|
| 1053 |
+
|
| 1054 |
+
var objectBody struct {
|
| 1055 |
+
Name string `json:"name"`
|
| 1056 |
+
Names []string `json:"names"`
|
| 1057 |
+
}
|
| 1058 |
+
if body[0] == '[' {
|
| 1059 |
+
var arrayBody []string
|
| 1060 |
+
if err := json.Unmarshal(body, &arrayBody); err != nil {
|
| 1061 |
+
return nil, fmt.Errorf("invalid request body")
|
| 1062 |
+
}
|
| 1063 |
+
return uniqueAuthFileNames(arrayBody), nil
|
| 1064 |
+
}
|
| 1065 |
+
if err := json.Unmarshal(body, &objectBody); err != nil {
|
| 1066 |
+
return nil, fmt.Errorf("invalid request body")
|
| 1067 |
+
}
|
| 1068 |
+
|
| 1069 |
+
out := make([]string, 0, len(objectBody.Names)+1)
|
| 1070 |
+
if strings.TrimSpace(objectBody.Name) != "" {
|
| 1071 |
+
out = append(out, objectBody.Name)
|
| 1072 |
+
}
|
| 1073 |
+
out = append(out, objectBody.Names...)
|
| 1074 |
+
return uniqueAuthFileNames(out), nil
|
| 1075 |
+
}
|
| 1076 |
+
|
| 1077 |
+
func uniqueAuthFileNames(names []string) []string {
|
| 1078 |
+
if len(names) == 0 {
|
| 1079 |
+
return nil
|
| 1080 |
+
}
|
| 1081 |
+
seen := make(map[string]struct{}, len(names))
|
| 1082 |
+
out := make([]string, 0, len(names))
|
| 1083 |
+
for _, name := range names {
|
| 1084 |
+
name = strings.TrimSpace(name)
|
| 1085 |
+
if name == "" {
|
| 1086 |
+
continue
|
| 1087 |
+
}
|
| 1088 |
+
if _, ok := seen[name]; ok {
|
| 1089 |
+
continue
|
| 1090 |
+
}
|
| 1091 |
+
seen[name] = struct{}{}
|
| 1092 |
+
out = append(out, name)
|
| 1093 |
+
}
|
| 1094 |
+
return out
|
| 1095 |
+
}
|
| 1096 |
+
|
| 1097 |
+
func (h *Handler) deleteAuthFileByName(ctx context.Context, name string) (string, int, error) {
|
| 1098 |
+
name = strings.TrimSpace(name)
|
| 1099 |
+
if isUnsafeAuthFileName(name) {
|
| 1100 |
+
return "", http.StatusBadRequest, fmt.Errorf("invalid name")
|
| 1101 |
+
}
|
| 1102 |
+
|
| 1103 |
+
targetPath := filepath.Join(h.cfg.AuthDir, filepath.Base(name))
|
| 1104 |
+
targetID := ""
|
| 1105 |
+
if targetAuth := h.findAuthForDelete(name); targetAuth != nil {
|
| 1106 |
+
if !isPluginVirtualSourceDelete(name, targetAuth) {
|
| 1107 |
+
return filepath.Base(name), http.StatusConflict, errPluginVirtualAuth
|
| 1108 |
+
}
|
| 1109 |
+
targetID = strings.TrimSpace(targetAuth.ID)
|
| 1110 |
+
if path := strings.TrimSpace(authAttribute(targetAuth, "path")); path != "" {
|
| 1111 |
+
targetPath = path
|
| 1112 |
+
}
|
| 1113 |
+
}
|
| 1114 |
+
if !filepath.IsAbs(targetPath) {
|
| 1115 |
+
if abs, errAbs := filepath.Abs(targetPath); errAbs == nil {
|
| 1116 |
+
targetPath = abs
|
| 1117 |
+
}
|
| 1118 |
+
}
|
| 1119 |
+
if errRemove := os.Remove(targetPath); errRemove != nil {
|
| 1120 |
+
if os.IsNotExist(errRemove) {
|
| 1121 |
+
return filepath.Base(name), http.StatusNotFound, errAuthFileNotFound
|
| 1122 |
+
}
|
| 1123 |
+
return filepath.Base(name), http.StatusInternalServerError, fmt.Errorf("failed to remove file: %w", errRemove)
|
| 1124 |
+
}
|
| 1125 |
+
if errDeleteRecord := h.deleteTokenRecord(ctx, targetPath); errDeleteRecord != nil {
|
| 1126 |
+
return filepath.Base(name), http.StatusInternalServerError, errDeleteRecord
|
| 1127 |
+
}
|
| 1128 |
+
h.removeAuthsForPath(ctx, targetPath, targetID)
|
| 1129 |
+
return filepath.Base(name), http.StatusOK, nil
|
| 1130 |
+
}
|
| 1131 |
+
|
| 1132 |
+
func isPluginVirtualSourceDelete(name string, auth *coreauth.Auth) bool {
|
| 1133 |
+
if !coreauth.IsPluginVirtualAuth(auth) {
|
| 1134 |
+
return true
|
| 1135 |
+
}
|
| 1136 |
+
sourcePath := strings.TrimSpace(authAttribute(auth, coreauth.AttributeVirtualSource))
|
| 1137 |
+
if sourcePath == "" {
|
| 1138 |
+
sourcePath = strings.TrimSpace(authAttribute(auth, "path"))
|
| 1139 |
+
}
|
| 1140 |
+
if sourcePath == "" {
|
| 1141 |
+
return false
|
| 1142 |
+
}
|
| 1143 |
+
return strings.EqualFold(filepath.Base(strings.TrimSpace(name)), filepath.Base(sourcePath))
|
| 1144 |
+
}
|
| 1145 |
+
|
| 1146 |
+
func (h *Handler) findAuthForDelete(name string) *coreauth.Auth {
|
| 1147 |
+
if h == nil || h.authManager == nil {
|
| 1148 |
+
return nil
|
| 1149 |
+
}
|
| 1150 |
+
name = strings.TrimSpace(name)
|
| 1151 |
+
if name == "" {
|
| 1152 |
+
return nil
|
| 1153 |
+
}
|
| 1154 |
+
if auth, ok := h.authManager.GetByID(name); ok {
|
| 1155 |
+
return auth
|
| 1156 |
+
}
|
| 1157 |
+
auths := h.authManager.List()
|
| 1158 |
+
for _, auth := range auths {
|
| 1159 |
+
if auth == nil {
|
| 1160 |
+
continue
|
| 1161 |
+
}
|
| 1162 |
+
if strings.TrimSpace(auth.FileName) == name {
|
| 1163 |
+
return auth
|
| 1164 |
+
}
|
| 1165 |
+
if filepath.Base(strings.TrimSpace(authAttribute(auth, "path"))) == name {
|
| 1166 |
+
return auth
|
| 1167 |
+
}
|
| 1168 |
+
}
|
| 1169 |
+
return nil
|
| 1170 |
+
}
|
| 1171 |
+
|
| 1172 |
+
func (h *Handler) authIDForPath(path string) string {
|
| 1173 |
+
path = strings.TrimSpace(path)
|
| 1174 |
+
if path == "" {
|
| 1175 |
+
return ""
|
| 1176 |
+
}
|
| 1177 |
+
path = filepath.Clean(path)
|
| 1178 |
+
if !filepath.IsAbs(path) {
|
| 1179 |
+
if abs, errAbs := filepath.Abs(path); errAbs == nil {
|
| 1180 |
+
path = abs
|
| 1181 |
+
}
|
| 1182 |
+
}
|
| 1183 |
+
id := path
|
| 1184 |
+
if h != nil && h.cfg != nil {
|
| 1185 |
+
authDir := strings.TrimSpace(h.cfg.AuthDir)
|
| 1186 |
+
if resolvedAuthDir, errResolve := util.ResolveAuthDir(authDir); errResolve == nil && resolvedAuthDir != "" {
|
| 1187 |
+
authDir = resolvedAuthDir
|
| 1188 |
+
}
|
| 1189 |
+
if authDir != "" {
|
| 1190 |
+
authDir = filepath.Clean(authDir)
|
| 1191 |
+
if !filepath.IsAbs(authDir) {
|
| 1192 |
+
if abs, errAbs := filepath.Abs(authDir); errAbs == nil {
|
| 1193 |
+
authDir = abs
|
| 1194 |
+
}
|
| 1195 |
+
}
|
| 1196 |
+
if rel, errRel := filepath.Rel(authDir, path); errRel == nil && rel != "" {
|
| 1197 |
+
id = rel
|
| 1198 |
+
}
|
| 1199 |
+
}
|
| 1200 |
+
}
|
| 1201 |
+
// On Windows, normalize ID casing to avoid duplicate auth entries caused by case-insensitive paths.
|
| 1202 |
+
if runtime.GOOS == "windows" {
|
| 1203 |
+
id = strings.ToLower(id)
|
| 1204 |
+
}
|
| 1205 |
+
return id
|
| 1206 |
+
}
|
| 1207 |
+
|
| 1208 |
+
func (h *Handler) registerAuthFromFile(ctx context.Context, path string, data []byte) error {
|
| 1209 |
+
if h.authManager == nil {
|
| 1210 |
+
return nil
|
| 1211 |
+
}
|
| 1212 |
+
auth, err := h.buildAuthFromFileData(path, data)
|
| 1213 |
+
if err != nil {
|
| 1214 |
+
return err
|
| 1215 |
+
}
|
| 1216 |
+
return h.upsertAuthRecord(ctx, auth)
|
| 1217 |
+
}
|
| 1218 |
+
|
| 1219 |
+
func (h *Handler) buildAuthFromFileData(path string, data []byte) (*coreauth.Auth, error) {
|
| 1220 |
+
if path == "" {
|
| 1221 |
+
return nil, fmt.Errorf("auth path is empty")
|
| 1222 |
+
}
|
| 1223 |
+
if data == nil {
|
| 1224 |
+
var err error
|
| 1225 |
+
data, err = os.ReadFile(path)
|
| 1226 |
+
if err != nil {
|
| 1227 |
+
return nil, fmt.Errorf("failed to read auth file: %w", err)
|
| 1228 |
+
}
|
| 1229 |
+
}
|
| 1230 |
+
metadata := make(map[string]any)
|
| 1231 |
+
if err := json.Unmarshal(data, &metadata); err != nil {
|
| 1232 |
+
return nil, fmt.Errorf("invalid auth file: %w", err)
|
| 1233 |
+
}
|
| 1234 |
+
provider, _ := metadata["type"].(string)
|
| 1235 |
+
if provider == "" {
|
| 1236 |
+
provider = "unknown"
|
| 1237 |
+
}
|
| 1238 |
+
label := provider
|
| 1239 |
+
if email, ok := metadata["email"].(string); ok && email != "" {
|
| 1240 |
+
label = email
|
| 1241 |
+
}
|
| 1242 |
+
lastRefresh, hasLastRefresh := extractLastRefreshTimestamp(metadata)
|
| 1243 |
+
|
| 1244 |
+
authID := h.authIDForPath(path)
|
| 1245 |
+
if authID == "" {
|
| 1246 |
+
authID = path
|
| 1247 |
+
}
|
| 1248 |
+
auth := (*coreauth.Auth)(nil)
|
| 1249 |
+
if h != nil && h.cfg != nil {
|
| 1250 |
+
sctx := &synthesizer.SynthesisContext{
|
| 1251 |
+
Config: h.cfg,
|
| 1252 |
+
AuthDir: h.cfg.AuthDir,
|
| 1253 |
+
Now: time.Now(),
|
| 1254 |
+
IDGenerator: synthesizer.NewStableIDGenerator(),
|
| 1255 |
+
}
|
| 1256 |
+
if generated := synthesizer.SynthesizeAuthFile(sctx, path, data); len(generated) > 0 && generated[0] != nil {
|
| 1257 |
+
auth = generated[0].Clone()
|
| 1258 |
+
}
|
| 1259 |
+
}
|
| 1260 |
+
if auth == nil {
|
| 1261 |
+
auth = &coreauth.Auth{
|
| 1262 |
+
ID: authID,
|
| 1263 |
+
Provider: provider,
|
| 1264 |
+
Label: label,
|
| 1265 |
+
Status: coreauth.StatusActive,
|
| 1266 |
+
Attributes: map[string]string{
|
| 1267 |
+
"path": path,
|
| 1268 |
+
"source": path,
|
| 1269 |
+
},
|
| 1270 |
+
Metadata: metadata,
|
| 1271 |
+
CreatedAt: time.Now(),
|
| 1272 |
+
UpdatedAt: time.Now(),
|
| 1273 |
+
}
|
| 1274 |
+
}
|
| 1275 |
+
auth.ID = authID
|
| 1276 |
+
auth.FileName = filepath.Base(path)
|
| 1277 |
+
if hasLastRefresh {
|
| 1278 |
+
auth.LastRefreshedAt = lastRefresh
|
| 1279 |
+
}
|
| 1280 |
+
if h != nil && h.authManager != nil {
|
| 1281 |
+
if existing, ok := h.authManager.GetByID(authID); ok {
|
| 1282 |
+
auth.CreatedAt = existing.CreatedAt
|
| 1283 |
+
if !hasLastRefresh {
|
| 1284 |
+
auth.LastRefreshedAt = existing.LastRefreshedAt
|
| 1285 |
+
}
|
| 1286 |
+
auth.NextRefreshAfter = existing.NextRefreshAfter
|
| 1287 |
+
auth.Runtime = existing.Runtime
|
| 1288 |
+
}
|
| 1289 |
+
}
|
| 1290 |
+
coreauth.ApplyCustomHeadersFromMetadata(auth)
|
| 1291 |
+
return auth, nil
|
| 1292 |
+
}
|
| 1293 |
+
|
| 1294 |
+
func (h *Handler) upsertAuthRecord(ctx context.Context, auth *coreauth.Auth) error {
|
| 1295 |
+
if h == nil || h.authManager == nil || auth == nil {
|
| 1296 |
+
return nil
|
| 1297 |
+
}
|
| 1298 |
+
if existing, ok := h.authManager.GetByID(auth.ID); ok {
|
| 1299 |
+
auth.CreatedAt = existing.CreatedAt
|
| 1300 |
+
_, err := h.authManager.Update(ctx, auth)
|
| 1301 |
+
return err
|
| 1302 |
+
}
|
| 1303 |
+
_, err := h.authManager.Register(ctx, auth)
|
| 1304 |
+
return err
|
| 1305 |
+
}
|
| 1306 |
+
|
| 1307 |
+
// PatchAuthFileStatus toggles the disabled state of an auth file
|
| 1308 |
+
func (h *Handler) PatchAuthFileStatus(c *gin.Context) {
|
| 1309 |
+
if h.authManager == nil {
|
| 1310 |
+
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "core auth manager unavailable"})
|
| 1311 |
+
return
|
| 1312 |
+
}
|
| 1313 |
+
|
| 1314 |
+
var req struct {
|
| 1315 |
+
Name string `json:"name"`
|
| 1316 |
+
AuthIndex string `json:"auth_index"`
|
| 1317 |
+
Disabled *bool `json:"disabled"`
|
| 1318 |
+
}
|
| 1319 |
+
if err := c.ShouldBindJSON(&req); err != nil {
|
| 1320 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
| 1321 |
+
return
|
| 1322 |
+
}
|
| 1323 |
+
|
| 1324 |
+
name := strings.TrimSpace(req.Name)
|
| 1325 |
+
authIndex := strings.TrimSpace(req.AuthIndex)
|
| 1326 |
+
if name == "" {
|
| 1327 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
| 1328 |
+
return
|
| 1329 |
+
}
|
| 1330 |
+
if req.Disabled == nil {
|
| 1331 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "disabled is required"})
|
| 1332 |
+
return
|
| 1333 |
+
}
|
| 1334 |
+
|
| 1335 |
+
ctx := c.Request.Context()
|
| 1336 |
+
|
| 1337 |
+
targetAuth, _ := h.lookupAuthFile(name, authIndex)
|
| 1338 |
+
if targetAuth == nil {
|
| 1339 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "auth file not found"})
|
| 1340 |
+
return
|
| 1341 |
+
}
|
| 1342 |
+
if coreauth.IsPluginVirtualAuth(targetAuth) {
|
| 1343 |
+
// Allow status changes only when targeting the source auth file name, matching delete semantics.
|
| 1344 |
+
// Expanded virtual project auths still cannot be modified independently.
|
| 1345 |
+
if !isPluginVirtualSourceDelete(name, targetAuth) {
|
| 1346 |
+
c.JSON(http.StatusConflict, gin.H{"error": errPluginVirtualAuth.Error()})
|
| 1347 |
+
return
|
| 1348 |
+
}
|
| 1349 |
+
if errPatch := h.patchPluginVirtualSourceStatus(ctx, targetAuth, *req.Disabled); errPatch != nil {
|
| 1350 |
+
status := http.StatusInternalServerError
|
| 1351 |
+
if errors.Is(errPatch, errAuthFileNotFound) || os.IsNotExist(errPatch) {
|
| 1352 |
+
status = http.StatusNotFound
|
| 1353 |
+
}
|
| 1354 |
+
c.JSON(status, gin.H{"error": errPatch.Error()})
|
| 1355 |
+
return
|
| 1356 |
+
}
|
| 1357 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok", "disabled": *req.Disabled})
|
| 1358 |
+
return
|
| 1359 |
+
}
|
| 1360 |
+
|
| 1361 |
+
if coreauth.IsConfigAPIKeyAuth(targetAuth) {
|
| 1362 |
+
h.mu.Lock()
|
| 1363 |
+
handled, errToggle := toggleConfigAPIKeyExcludedAll(h.cfg, targetAuth, *req.Disabled)
|
| 1364 |
+
if errToggle != nil {
|
| 1365 |
+
h.mu.Unlock()
|
| 1366 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to update config api key: %v", errToggle)})
|
| 1367 |
+
return
|
| 1368 |
+
}
|
| 1369 |
+
if !handled {
|
| 1370 |
+
h.mu.Unlock()
|
| 1371 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "config api key entry not found"})
|
| 1372 |
+
return
|
| 1373 |
+
}
|
| 1374 |
+
cfgSnapshot, okSnapshot := h.saveConfigAndSnapshotLocked(c)
|
| 1375 |
+
h.mu.Unlock()
|
| 1376 |
+
if !okSnapshot {
|
| 1377 |
+
return
|
| 1378 |
+
}
|
| 1379 |
+
h.reloadConfigAfterManagementSave(ctx, cfgSnapshot)
|
| 1380 |
+
if h.tokenStore != nil {
|
| 1381 |
+
_ = h.tokenStore.Delete(ctx, targetAuth.ID)
|
| 1382 |
+
}
|
| 1383 |
+
c.JSON(http.StatusOK, gin.H{
|
| 1384 |
+
"status": "ok",
|
| 1385 |
+
"disabled": *req.Disabled,
|
| 1386 |
+
"via": "config:excluded-models",
|
| 1387 |
+
"excluded_pattern": configAPIKeyDisablePattern,
|
| 1388 |
+
})
|
| 1389 |
+
return
|
| 1390 |
+
}
|
| 1391 |
+
|
| 1392 |
+
applyAuthDisabledState(targetAuth, *req.Disabled)
|
| 1393 |
+
if _, err := h.authManager.Update(ctx, targetAuth); err != nil {
|
| 1394 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to update auth: %v", err)})
|
| 1395 |
+
return
|
| 1396 |
+
}
|
| 1397 |
+
|
| 1398 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok", "disabled": *req.Disabled})
|
| 1399 |
+
}
|
| 1400 |
+
|
| 1401 |
+
// patchPluginVirtualSourceStatus toggles disabled on a plugin multi-auth source file and all
|
| 1402 |
+
// runtime auths expanded from it. Virtual project children cannot be toggled independently.
|
| 1403 |
+
func (h *Handler) patchPluginVirtualSourceStatus(ctx context.Context, targetAuth *coreauth.Auth, disabled bool) error {
|
| 1404 |
+
if h == nil || h.authManager == nil || targetAuth == nil {
|
| 1405 |
+
return fmt.Errorf("core auth manager unavailable")
|
| 1406 |
+
}
|
| 1407 |
+
sourcePath := strings.TrimSpace(authAttribute(targetAuth, coreauth.AttributeVirtualSource))
|
| 1408 |
+
if sourcePath == "" {
|
| 1409 |
+
sourcePath = strings.TrimSpace(authAttribute(targetAuth, "path"))
|
| 1410 |
+
}
|
| 1411 |
+
if sourcePath == "" {
|
| 1412 |
+
return errPluginVirtualAuth
|
| 1413 |
+
}
|
| 1414 |
+
if errWrite := setSourceAuthFileDisabled(sourcePath, disabled); errWrite != nil {
|
| 1415 |
+
if os.IsNotExist(errWrite) {
|
| 1416 |
+
return errAuthFileNotFound
|
| 1417 |
+
}
|
| 1418 |
+
return fmt.Errorf("failed to update source auth file: %w", errWrite)
|
| 1419 |
+
}
|
| 1420 |
+
now := time.Now()
|
| 1421 |
+
for _, auth := range h.authManager.List() {
|
| 1422 |
+
if auth == nil {
|
| 1423 |
+
continue
|
| 1424 |
+
}
|
| 1425 |
+
if !sameAuthFilePath(authAttribute(auth, "path"), sourcePath) &&
|
| 1426 |
+
!sameAuthFilePath(authAttribute(auth, coreauth.AttributeVirtualSource), sourcePath) {
|
| 1427 |
+
continue
|
| 1428 |
+
}
|
| 1429 |
+
applyAuthDisabledState(auth, disabled)
|
| 1430 |
+
auth.UpdatedAt = now
|
| 1431 |
+
if _, errUpdate := h.authManager.Update(ctx, auth); errUpdate != nil {
|
| 1432 |
+
return fmt.Errorf("failed to update auth %s: %w", auth.ID, errUpdate)
|
| 1433 |
+
}
|
| 1434 |
+
}
|
| 1435 |
+
return nil
|
| 1436 |
+
}
|
| 1437 |
+
|
| 1438 |
+
func setSourceAuthFileDisabled(path string, disabled bool) error {
|
| 1439 |
+
path = strings.TrimSpace(path)
|
| 1440 |
+
if path == "" {
|
| 1441 |
+
return fmt.Errorf("source auth path is empty")
|
| 1442 |
+
}
|
| 1443 |
+
data, errRead := os.ReadFile(path)
|
| 1444 |
+
if errRead != nil {
|
| 1445 |
+
return errRead
|
| 1446 |
+
}
|
| 1447 |
+
metadata := make(map[string]any)
|
| 1448 |
+
if len(bytes.TrimSpace(data)) > 0 {
|
| 1449 |
+
if errUnmarshal := json.Unmarshal(data, &metadata); errUnmarshal != nil {
|
| 1450 |
+
return fmt.Errorf("invalid auth file: %w", errUnmarshal)
|
| 1451 |
+
}
|
| 1452 |
+
}
|
| 1453 |
+
if metadata == nil {
|
| 1454 |
+
metadata = make(map[string]any)
|
| 1455 |
+
}
|
| 1456 |
+
metadata["disabled"] = disabled
|
| 1457 |
+
raw, errMarshal := json.Marshal(metadata)
|
| 1458 |
+
if errMarshal != nil {
|
| 1459 |
+
return fmt.Errorf("marshal auth file: %w", errMarshal)
|
| 1460 |
+
}
|
| 1461 |
+
if errWrite := os.WriteFile(path, raw, 0o600); errWrite != nil {
|
| 1462 |
+
return errWrite
|
| 1463 |
+
}
|
| 1464 |
+
return nil
|
| 1465 |
+
}
|
| 1466 |
+
|
| 1467 |
+
func applyAuthDisabledState(auth *coreauth.Auth, disabled bool) {
|
| 1468 |
+
if auth == nil {
|
| 1469 |
+
return
|
| 1470 |
+
}
|
| 1471 |
+
auth.Disabled = disabled
|
| 1472 |
+
if disabled {
|
| 1473 |
+
auth.Status = coreauth.StatusDisabled
|
| 1474 |
+
auth.StatusMessage = "disabled via management API"
|
| 1475 |
+
} else {
|
| 1476 |
+
auth.Status = coreauth.StatusActive
|
| 1477 |
+
auth.StatusMessage = ""
|
| 1478 |
+
}
|
| 1479 |
+
auth.UpdatedAt = time.Now()
|
| 1480 |
+
if auth.Metadata == nil {
|
| 1481 |
+
auth.Metadata = make(map[string]any)
|
| 1482 |
+
}
|
| 1483 |
+
auth.Metadata["disabled"] = disabled
|
| 1484 |
+
}
|
| 1485 |
+
|
| 1486 |
+
// PatchAuthFileFields updates arbitrary metadata fields of an auth file.
|
| 1487 |
+
func (h *Handler) PatchAuthFileFields(c *gin.Context) {
|
| 1488 |
+
if h.authManager == nil {
|
| 1489 |
+
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "core auth manager unavailable"})
|
| 1490 |
+
return
|
| 1491 |
+
}
|
| 1492 |
+
|
| 1493 |
+
var req map[string]json.RawMessage
|
| 1494 |
+
decoder := json.NewDecoder(c.Request.Body)
|
| 1495 |
+
decoder.UseNumber()
|
| 1496 |
+
if err := decoder.Decode(&req); err != nil {
|
| 1497 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
| 1498 |
+
return
|
| 1499 |
+
}
|
| 1500 |
+
|
| 1501 |
+
nameRaw, ok := req["name"]
|
| 1502 |
+
if !ok {
|
| 1503 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
| 1504 |
+
return
|
| 1505 |
+
}
|
| 1506 |
+
var nameValue string
|
| 1507 |
+
if err := json.Unmarshal(nameRaw, &nameValue); err != nil {
|
| 1508 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
| 1509 |
+
return
|
| 1510 |
+
}
|
| 1511 |
+
name := strings.TrimSpace(nameValue)
|
| 1512 |
+
if name == "" {
|
| 1513 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
|
| 1514 |
+
return
|
| 1515 |
+
}
|
| 1516 |
+
delete(req, "name")
|
| 1517 |
+
|
| 1518 |
+
ctx := c.Request.Context()
|
| 1519 |
+
|
| 1520 |
+
// Find auth by name or ID
|
| 1521 |
+
var targetAuth *coreauth.Auth
|
| 1522 |
+
if auth, ok := h.authManager.GetByID(name); ok {
|
| 1523 |
+
targetAuth = auth
|
| 1524 |
+
} else {
|
| 1525 |
+
auths := h.authManager.List()
|
| 1526 |
+
for _, auth := range auths {
|
| 1527 |
+
if auth.FileName == name {
|
| 1528 |
+
targetAuth = auth
|
| 1529 |
+
break
|
| 1530 |
+
}
|
| 1531 |
+
}
|
| 1532 |
+
}
|
| 1533 |
+
|
| 1534 |
+
if targetAuth == nil {
|
| 1535 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "auth file not found"})
|
| 1536 |
+
return
|
| 1537 |
+
}
|
| 1538 |
+
if coreauth.IsPluginVirtualAuth(targetAuth) {
|
| 1539 |
+
c.JSON(http.StatusConflict, gin.H{"error": errPluginVirtualAuth.Error()})
|
| 1540 |
+
return
|
| 1541 |
+
}
|
| 1542 |
+
|
| 1543 |
+
changed := false
|
| 1544 |
+
touchedRoots := make(map[string]struct{}, len(req))
|
| 1545 |
+
for key, rawValue := range req {
|
| 1546 |
+
fieldPath := strings.TrimSpace(key)
|
| 1547 |
+
if fieldPath == "" {
|
| 1548 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "field name is required"})
|
| 1549 |
+
return
|
| 1550 |
+
}
|
| 1551 |
+
value, errDecode := decodeAuthFileFieldValue(rawValue)
|
| 1552 |
+
if errDecode != nil {
|
| 1553 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid field %s", fieldPath)})
|
| 1554 |
+
return
|
| 1555 |
+
}
|
| 1556 |
+
if targetAuth.Metadata == nil {
|
| 1557 |
+
targetAuth.Metadata = make(map[string]any)
|
| 1558 |
+
}
|
| 1559 |
+
|
| 1560 |
+
if fieldPath == "headers" {
|
| 1561 |
+
applyAuthFileHeadersPatch(targetAuth, value)
|
| 1562 |
+
} else if errSet := setAuthFileMetadataValue(targetAuth.Metadata, fieldPath, value); errSet != nil {
|
| 1563 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": errSet.Error()})
|
| 1564 |
+
return
|
| 1565 |
+
}
|
| 1566 |
+
if root := rootAuthFileField(fieldPath); root != "" {
|
| 1567 |
+
touchedRoots[root] = struct{}{}
|
| 1568 |
+
}
|
| 1569 |
+
changed = true
|
| 1570 |
+
}
|
| 1571 |
+
if changed {
|
| 1572 |
+
syncAuthFileMetadataFields(targetAuth, touchedRoots)
|
| 1573 |
+
}
|
| 1574 |
+
|
| 1575 |
+
if !changed {
|
| 1576 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "no fields to update"})
|
| 1577 |
+
return
|
| 1578 |
+
}
|
| 1579 |
+
|
| 1580 |
+
targetAuth.UpdatedAt = time.Now()
|
| 1581 |
+
|
| 1582 |
+
if _, err := h.authManager.Update(ctx, targetAuth); err != nil {
|
| 1583 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to update auth: %v", err)})
|
| 1584 |
+
return
|
| 1585 |
+
}
|
| 1586 |
+
|
| 1587 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
| 1588 |
+
}
|
| 1589 |
+
|
| 1590 |
+
func decodeAuthFileFieldValue(raw json.RawMessage) (any, error) {
|
| 1591 |
+
decoder := json.NewDecoder(bytes.NewReader(raw))
|
| 1592 |
+
decoder.UseNumber()
|
| 1593 |
+
var value any
|
| 1594 |
+
if err := decoder.Decode(&value); err != nil {
|
| 1595 |
+
return nil, err
|
| 1596 |
+
}
|
| 1597 |
+
return value, nil
|
| 1598 |
+
}
|
| 1599 |
+
|
| 1600 |
+
func rootAuthFileField(path string) string {
|
| 1601 |
+
path = strings.TrimSpace(path)
|
| 1602 |
+
if path == "" {
|
| 1603 |
+
return ""
|
| 1604 |
+
}
|
| 1605 |
+
if idx := strings.Index(path, "."); idx >= 0 {
|
| 1606 |
+
return strings.TrimSpace(path[:idx])
|
| 1607 |
+
}
|
| 1608 |
+
return path
|
| 1609 |
+
}
|
| 1610 |
+
|
| 1611 |
+
func setAuthFileMetadataValue(metadata map[string]any, path string, value any) error {
|
| 1612 |
+
if metadata == nil {
|
| 1613 |
+
return fmt.Errorf("metadata is nil")
|
| 1614 |
+
}
|
| 1615 |
+
parts := strings.Split(path, ".")
|
| 1616 |
+
current := metadata
|
| 1617 |
+
for i, rawPart := range parts {
|
| 1618 |
+
part := strings.TrimSpace(rawPart)
|
| 1619 |
+
if part == "" {
|
| 1620 |
+
return fmt.Errorf("invalid field path: %s", path)
|
| 1621 |
+
}
|
| 1622 |
+
if i == len(parts)-1 {
|
| 1623 |
+
current[part] = value
|
| 1624 |
+
return nil
|
| 1625 |
+
}
|
| 1626 |
+
next, ok := current[part].(map[string]any)
|
| 1627 |
+
if !ok {
|
| 1628 |
+
next = make(map[string]any)
|
| 1629 |
+
current[part] = next
|
| 1630 |
+
}
|
| 1631 |
+
current = next
|
| 1632 |
+
}
|
| 1633 |
+
return nil
|
| 1634 |
+
}
|
| 1635 |
+
|
| 1636 |
+
func applyAuthFileHeadersPatch(auth *coreauth.Auth, value any) {
|
| 1637 |
+
if auth == nil {
|
| 1638 |
+
return
|
| 1639 |
+
}
|
| 1640 |
+
if auth.Metadata == nil {
|
| 1641 |
+
auth.Metadata = make(map[string]any)
|
| 1642 |
+
}
|
| 1643 |
+
headersPatch, ok := authFileHeadersStringMap(value)
|
| 1644 |
+
if !ok {
|
| 1645 |
+
auth.Metadata["headers"] = value
|
| 1646 |
+
return
|
| 1647 |
+
}
|
| 1648 |
+
|
| 1649 |
+
existingHeaders := coreauth.ExtractCustomHeadersFromMetadata(auth.Metadata)
|
| 1650 |
+
nextHeaders := make(map[string]string, len(existingHeaders))
|
| 1651 |
+
for key, val := range existingHeaders {
|
| 1652 |
+
nextHeaders[key] = val
|
| 1653 |
+
}
|
| 1654 |
+
for key, value := range headersPatch {
|
| 1655 |
+
name := strings.TrimSpace(key)
|
| 1656 |
+
if name == "" {
|
| 1657 |
+
continue
|
| 1658 |
+
}
|
| 1659 |
+
val := strings.TrimSpace(value)
|
| 1660 |
+
if val == "" {
|
| 1661 |
+
delete(nextHeaders, name)
|
| 1662 |
+
continue
|
| 1663 |
+
}
|
| 1664 |
+
nextHeaders[name] = val
|
| 1665 |
+
}
|
| 1666 |
+
|
| 1667 |
+
if len(nextHeaders) == 0 {
|
| 1668 |
+
delete(auth.Metadata, "headers")
|
| 1669 |
+
return
|
| 1670 |
+
}
|
| 1671 |
+
metaHeaders := make(map[string]any, len(nextHeaders))
|
| 1672 |
+
for key, value := range nextHeaders {
|
| 1673 |
+
metaHeaders[key] = value
|
| 1674 |
+
}
|
| 1675 |
+
auth.Metadata["headers"] = metaHeaders
|
| 1676 |
+
}
|
| 1677 |
+
|
| 1678 |
+
func authFileHeadersStringMap(value any) (map[string]string, bool) {
|
| 1679 |
+
switch typed := value.(type) {
|
| 1680 |
+
case map[string]string:
|
| 1681 |
+
return typed, true
|
| 1682 |
+
case map[string]any:
|
| 1683 |
+
out := make(map[string]string, len(typed))
|
| 1684 |
+
for key, rawValue := range typed {
|
| 1685 |
+
value, ok := rawValue.(string)
|
| 1686 |
+
if !ok {
|
| 1687 |
+
return nil, false
|
| 1688 |
+
}
|
| 1689 |
+
out[key] = value
|
| 1690 |
+
}
|
| 1691 |
+
return out, true
|
| 1692 |
+
default:
|
| 1693 |
+
return nil, false
|
| 1694 |
+
}
|
| 1695 |
+
}
|
| 1696 |
+
|
| 1697 |
+
func syncAuthFileMetadataFields(auth *coreauth.Auth, touchedRoots map[string]struct{}) {
|
| 1698 |
+
if auth == nil || len(touchedRoots) == 0 {
|
| 1699 |
+
return
|
| 1700 |
+
}
|
| 1701 |
+
if _, ok := touchedRoots["prefix"]; ok {
|
| 1702 |
+
if prefix, okString := auth.Metadata["prefix"].(string); okString {
|
| 1703 |
+
auth.Prefix = strings.TrimSpace(prefix)
|
| 1704 |
+
}
|
| 1705 |
+
}
|
| 1706 |
+
if _, ok := touchedRoots["proxy_url"]; ok {
|
| 1707 |
+
if proxyURL, okString := auth.Metadata["proxy_url"].(string); okString {
|
| 1708 |
+
auth.ProxyURL = strings.TrimSpace(proxyURL)
|
| 1709 |
+
}
|
| 1710 |
+
}
|
| 1711 |
+
if _, ok := touchedRoots["headers"]; ok {
|
| 1712 |
+
syncAuthFileHeaderAttributes(auth)
|
| 1713 |
+
}
|
| 1714 |
+
if _, ok := touchedRoots["priority"]; ok {
|
| 1715 |
+
syncAuthFilePriorityAttribute(auth)
|
| 1716 |
+
}
|
| 1717 |
+
if _, ok := touchedRoots["note"]; ok {
|
| 1718 |
+
syncAuthFileNoteAttribute(auth)
|
| 1719 |
+
}
|
| 1720 |
+
if _, ok := touchedRoots["websockets"]; ok {
|
| 1721 |
+
syncAuthFileWebsocketsAttribute(auth)
|
| 1722 |
+
}
|
| 1723 |
+
if _, ok := touchedRoots["disabled"]; ok {
|
| 1724 |
+
syncAuthFileDisabledState(auth)
|
| 1725 |
+
}
|
| 1726 |
+
}
|
| 1727 |
+
|
| 1728 |
+
func syncAuthFileHeaderAttributes(auth *coreauth.Auth) {
|
| 1729 |
+
if auth == nil {
|
| 1730 |
+
return
|
| 1731 |
+
}
|
| 1732 |
+
if auth.Attributes == nil {
|
| 1733 |
+
auth.Attributes = make(map[string]string)
|
| 1734 |
+
}
|
| 1735 |
+
for key := range auth.Attributes {
|
| 1736 |
+
if strings.HasPrefix(key, "header:") {
|
| 1737 |
+
delete(auth.Attributes, key)
|
| 1738 |
+
}
|
| 1739 |
+
}
|
| 1740 |
+
for name, value := range coreauth.ExtractCustomHeadersFromMetadata(auth.Metadata) {
|
| 1741 |
+
auth.Attributes["header:"+name] = value
|
| 1742 |
+
}
|
| 1743 |
+
}
|
| 1744 |
+
|
| 1745 |
+
func syncAuthFilePriorityAttribute(auth *coreauth.Auth) {
|
| 1746 |
+
if auth == nil {
|
| 1747 |
+
return
|
| 1748 |
+
}
|
| 1749 |
+
if auth.Attributes == nil {
|
| 1750 |
+
auth.Attributes = make(map[string]string)
|
| 1751 |
+
}
|
| 1752 |
+
priority, ok := authFileIntValue(auth.Metadata["priority"])
|
| 1753 |
+
if !ok {
|
| 1754 |
+
delete(auth.Attributes, "priority")
|
| 1755 |
+
return
|
| 1756 |
+
}
|
| 1757 |
+
if priority == 0 {
|
| 1758 |
+
delete(auth.Attributes, "priority")
|
| 1759 |
+
return
|
| 1760 |
+
}
|
| 1761 |
+
auth.Attributes["priority"] = strconv.Itoa(priority)
|
| 1762 |
+
}
|
| 1763 |
+
|
| 1764 |
+
func authFileIntValue(value any) (int, bool) {
|
| 1765 |
+
switch typed := value.(type) {
|
| 1766 |
+
case int:
|
| 1767 |
+
return typed, true
|
| 1768 |
+
case int64:
|
| 1769 |
+
return int(typed), true
|
| 1770 |
+
case float64:
|
| 1771 |
+
return int(typed), true
|
| 1772 |
+
case json.Number:
|
| 1773 |
+
if i, err := typed.Int64(); err == nil {
|
| 1774 |
+
return int(i), true
|
| 1775 |
+
}
|
| 1776 |
+
case string:
|
| 1777 |
+
if i, err := strconv.Atoi(strings.TrimSpace(typed)); err == nil {
|
| 1778 |
+
return i, true
|
| 1779 |
+
}
|
| 1780 |
+
}
|
| 1781 |
+
return 0, false
|
| 1782 |
+
}
|
| 1783 |
+
|
| 1784 |
+
func syncAuthFileNoteAttribute(auth *coreauth.Auth) {
|
| 1785 |
+
if auth == nil {
|
| 1786 |
+
return
|
| 1787 |
+
}
|
| 1788 |
+
if auth.Attributes == nil {
|
| 1789 |
+
auth.Attributes = make(map[string]string)
|
| 1790 |
+
}
|
| 1791 |
+
note, ok := auth.Metadata["note"].(string)
|
| 1792 |
+
if !ok {
|
| 1793 |
+
delete(auth.Attributes, "note")
|
| 1794 |
+
return
|
| 1795 |
+
}
|
| 1796 |
+
note = strings.TrimSpace(note)
|
| 1797 |
+
if note == "" {
|
| 1798 |
+
delete(auth.Attributes, "note")
|
| 1799 |
+
return
|
| 1800 |
+
}
|
| 1801 |
+
auth.Attributes["note"] = note
|
| 1802 |
+
}
|
| 1803 |
+
|
| 1804 |
+
func syncAuthFileWebsocketsAttribute(auth *coreauth.Auth) {
|
| 1805 |
+
if auth == nil {
|
| 1806 |
+
return
|
| 1807 |
+
}
|
| 1808 |
+
if auth.Attributes == nil {
|
| 1809 |
+
auth.Attributes = make(map[string]string)
|
| 1810 |
+
}
|
| 1811 |
+
websockets, ok := authFileBoolValue(auth.Metadata["websockets"])
|
| 1812 |
+
if !ok {
|
| 1813 |
+
delete(auth.Attributes, "websockets")
|
| 1814 |
+
return
|
| 1815 |
+
}
|
| 1816 |
+
auth.Attributes["websockets"] = strconv.FormatBool(websockets)
|
| 1817 |
+
}
|
| 1818 |
+
|
| 1819 |
+
func authFileBoolValue(value any) (bool, bool) {
|
| 1820 |
+
switch typed := value.(type) {
|
| 1821 |
+
case bool:
|
| 1822 |
+
return typed, true
|
| 1823 |
+
case string:
|
| 1824 |
+
parsed, errParse := strconv.ParseBool(strings.TrimSpace(typed))
|
| 1825 |
+
if errParse == nil {
|
| 1826 |
+
return parsed, true
|
| 1827 |
+
}
|
| 1828 |
+
}
|
| 1829 |
+
return false, false
|
| 1830 |
+
}
|
| 1831 |
+
|
| 1832 |
+
func syncAuthFileDisabledState(auth *coreauth.Auth) {
|
| 1833 |
+
if auth == nil {
|
| 1834 |
+
return
|
| 1835 |
+
}
|
| 1836 |
+
disabled, ok := authFileBoolValue(auth.Metadata["disabled"])
|
| 1837 |
+
if !ok {
|
| 1838 |
+
return
|
| 1839 |
+
}
|
| 1840 |
+
auth.Disabled = disabled
|
| 1841 |
+
if disabled {
|
| 1842 |
+
auth.Status = coreauth.StatusDisabled
|
| 1843 |
+
if strings.TrimSpace(auth.StatusMessage) == "" {
|
| 1844 |
+
auth.StatusMessage = "disabled via management API"
|
| 1845 |
+
}
|
| 1846 |
+
return
|
| 1847 |
+
}
|
| 1848 |
+
auth.Status = coreauth.StatusActive
|
| 1849 |
+
auth.StatusMessage = ""
|
| 1850 |
+
}
|
| 1851 |
+
|
| 1852 |
+
func (h *Handler) removeAuth(ctx context.Context, id string) {
|
| 1853 |
+
if h == nil || h.authManager == nil {
|
| 1854 |
+
return
|
| 1855 |
+
}
|
| 1856 |
+
id = strings.TrimSpace(id)
|
| 1857 |
+
if id == "" {
|
| 1858 |
+
return
|
| 1859 |
+
}
|
| 1860 |
+
if _, ok := h.authManager.GetByID(id); ok {
|
| 1861 |
+
h.authManager.Remove(ctx, id)
|
| 1862 |
+
return
|
| 1863 |
+
}
|
| 1864 |
+
authID := h.authIDForPath(id)
|
| 1865 |
+
if authID == "" {
|
| 1866 |
+
return
|
| 1867 |
+
}
|
| 1868 |
+
h.authManager.Remove(ctx, authID)
|
| 1869 |
+
}
|
| 1870 |
+
|
| 1871 |
+
func (h *Handler) removeAuthsForPath(ctx context.Context, path string, fallbackID string) {
|
| 1872 |
+
if h == nil || h.authManager == nil {
|
| 1873 |
+
return
|
| 1874 |
+
}
|
| 1875 |
+
removed := false
|
| 1876 |
+
for _, auth := range h.authManager.List() {
|
| 1877 |
+
if auth == nil {
|
| 1878 |
+
continue
|
| 1879 |
+
}
|
| 1880 |
+
if sameAuthFilePath(authAttribute(auth, "path"), path) || sameAuthFilePath(authAttribute(auth, coreauth.AttributeVirtualSource), path) {
|
| 1881 |
+
h.removeAuth(ctx, auth.ID)
|
| 1882 |
+
removed = true
|
| 1883 |
+
}
|
| 1884 |
+
}
|
| 1885 |
+
if removed {
|
| 1886 |
+
return
|
| 1887 |
+
}
|
| 1888 |
+
if strings.TrimSpace(fallbackID) != "" {
|
| 1889 |
+
h.removeAuth(ctx, fallbackID)
|
| 1890 |
+
return
|
| 1891 |
+
}
|
| 1892 |
+
h.removeAuth(ctx, path)
|
| 1893 |
+
}
|
| 1894 |
+
|
| 1895 |
+
func sameAuthFilePath(left, right string) bool {
|
| 1896 |
+
left = cleanAuthFilePath(left)
|
| 1897 |
+
right = cleanAuthFilePath(right)
|
| 1898 |
+
if left == "" || right == "" {
|
| 1899 |
+
return false
|
| 1900 |
+
}
|
| 1901 |
+
if runtime.GOOS == "windows" {
|
| 1902 |
+
return strings.EqualFold(left, right)
|
| 1903 |
+
}
|
| 1904 |
+
return left == right
|
| 1905 |
+
}
|
| 1906 |
+
|
| 1907 |
+
func cleanAuthFilePath(path string) string {
|
| 1908 |
+
path = strings.TrimSpace(path)
|
| 1909 |
+
if path == "" {
|
| 1910 |
+
return ""
|
| 1911 |
+
}
|
| 1912 |
+
if abs, errAbs := filepath.Abs(path); errAbs == nil && strings.TrimSpace(abs) != "" {
|
| 1913 |
+
path = abs
|
| 1914 |
+
}
|
| 1915 |
+
return filepath.Clean(path)
|
| 1916 |
+
}
|
| 1917 |
+
|
| 1918 |
+
func (h *Handler) deleteTokenRecord(ctx context.Context, path string) error {
|
| 1919 |
+
if strings.TrimSpace(path) == "" {
|
| 1920 |
+
return fmt.Errorf("auth path is empty")
|
| 1921 |
+
}
|
| 1922 |
+
store := h.tokenStoreWithBaseDir()
|
| 1923 |
+
if store == nil {
|
| 1924 |
+
return fmt.Errorf("token store unavailable")
|
| 1925 |
+
}
|
| 1926 |
+
return store.Delete(ctx, path)
|
| 1927 |
+
}
|
| 1928 |
+
|
| 1929 |
+
func (h *Handler) tokenStoreWithBaseDir() coreauth.Store {
|
| 1930 |
+
if h == nil {
|
| 1931 |
+
return nil
|
| 1932 |
+
}
|
| 1933 |
+
store := h.tokenStore
|
| 1934 |
+
if store == nil {
|
| 1935 |
+
store = sdkAuth.GetTokenStore()
|
| 1936 |
+
h.tokenStore = store
|
| 1937 |
+
}
|
| 1938 |
+
if h.cfg != nil {
|
| 1939 |
+
if dirSetter, ok := store.(interface{ SetBaseDir(string) }); ok {
|
| 1940 |
+
dirSetter.SetBaseDir(h.cfg.AuthDir)
|
| 1941 |
+
}
|
| 1942 |
+
}
|
| 1943 |
+
return store
|
| 1944 |
+
}
|
| 1945 |
+
|
| 1946 |
+
func (h *Handler) saveTokenRecord(ctx context.Context, record *coreauth.Auth) (string, error) {
|
| 1947 |
+
if record == nil {
|
| 1948 |
+
return "", fmt.Errorf("token record is nil")
|
| 1949 |
+
}
|
| 1950 |
+
store := h.tokenStoreWithBaseDir()
|
| 1951 |
+
if store == nil {
|
| 1952 |
+
return "", fmt.Errorf("token store unavailable")
|
| 1953 |
+
}
|
| 1954 |
+
if h.postAuthHook != nil {
|
| 1955 |
+
if err := h.postAuthHook(ctx, record); err != nil {
|
| 1956 |
+
return "", fmt.Errorf("post-auth hook failed: %w", err)
|
| 1957 |
+
}
|
| 1958 |
+
}
|
| 1959 |
+
savedPath, errSave := store.Save(ctx, record)
|
| 1960 |
+
if errSave != nil {
|
| 1961 |
+
return savedPath, errSave
|
| 1962 |
+
}
|
| 1963 |
+
if h.postAuthPersistHook != nil {
|
| 1964 |
+
if errHook := h.postAuthPersistHook(ctx, record); errHook != nil {
|
| 1965 |
+
return savedPath, fmt.Errorf("post-auth persist hook failed: %w", errHook)
|
| 1966 |
+
}
|
| 1967 |
+
}
|
| 1968 |
+
return savedPath, nil
|
| 1969 |
+
}
|
| 1970 |
+
|
| 1971 |
+
func (h *Handler) RequestAnthropicToken(c *gin.Context) {
|
| 1972 |
+
ctx := context.Background()
|
| 1973 |
+
ctx = PopulateAuthContext(ctx, c)
|
| 1974 |
+
|
| 1975 |
+
fmt.Println("Initializing Claude authentication...")
|
| 1976 |
+
|
| 1977 |
+
// Generate PKCE codes
|
| 1978 |
+
pkceCodes, err := claude.GeneratePKCECodes()
|
| 1979 |
+
if err != nil {
|
| 1980 |
+
log.Errorf("Failed to generate PKCE codes: %v", err)
|
| 1981 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate PKCE codes"})
|
| 1982 |
+
return
|
| 1983 |
+
}
|
| 1984 |
+
|
| 1985 |
+
// Generate random state parameter
|
| 1986 |
+
state, err := misc.GenerateRandomState()
|
| 1987 |
+
if err != nil {
|
| 1988 |
+
log.Errorf("Failed to generate state parameter: %v", err)
|
| 1989 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate state parameter"})
|
| 1990 |
+
return
|
| 1991 |
+
}
|
| 1992 |
+
|
| 1993 |
+
// Initialize Claude auth service
|
| 1994 |
+
anthropicAuth := claude.NewClaudeAuth(h.cfg)
|
| 1995 |
+
|
| 1996 |
+
// Generate authorization URL (then override redirect_uri to reuse server port)
|
| 1997 |
+
authURL, state, err := anthropicAuth.GenerateAuthURL(state, pkceCodes)
|
| 1998 |
+
if err != nil {
|
| 1999 |
+
log.Errorf("Failed to generate authorization URL: %v", err)
|
| 2000 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate authorization url"})
|
| 2001 |
+
return
|
| 2002 |
+
}
|
| 2003 |
+
|
| 2004 |
+
RegisterOAuthSession(state, "anthropic")
|
| 2005 |
+
|
| 2006 |
+
isWebUI := isWebUIRequest(c)
|
| 2007 |
+
var forwarder *callbackForwarder
|
| 2008 |
+
if isWebUI {
|
| 2009 |
+
targetURL, errTarget := h.managementCallbackURL("/anthropic/callback")
|
| 2010 |
+
if errTarget != nil {
|
| 2011 |
+
log.WithError(errTarget).Error("failed to compute anthropic callback target")
|
| 2012 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "callback server unavailable"})
|
| 2013 |
+
return
|
| 2014 |
+
}
|
| 2015 |
+
var errStart error
|
| 2016 |
+
if forwarder, errStart = startCallbackForwarder(anthropicCallbackPort, "anthropic", targetURL); errStart != nil {
|
| 2017 |
+
log.WithError(errStart).Error("failed to start anthropic callback forwarder")
|
| 2018 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start callback server"})
|
| 2019 |
+
return
|
| 2020 |
+
}
|
| 2021 |
+
}
|
| 2022 |
+
|
| 2023 |
+
go func() {
|
| 2024 |
+
if isWebUI {
|
| 2025 |
+
defer stopCallbackForwarderInstance(anthropicCallbackPort, forwarder)
|
| 2026 |
+
}
|
| 2027 |
+
|
| 2028 |
+
// Helper: wait for callback file
|
| 2029 |
+
waitFile := filepath.Join(h.cfg.AuthDir, fmt.Sprintf(".oauth-anthropic-%s.oauth", state))
|
| 2030 |
+
waitForFile := func(path string, timeout time.Duration) (map[string]string, error) {
|
| 2031 |
+
deadline := time.Now().Add(timeout)
|
| 2032 |
+
for {
|
| 2033 |
+
if !IsOAuthSessionPending(state, "anthropic") {
|
| 2034 |
+
return nil, errOAuthSessionNotPending
|
| 2035 |
+
}
|
| 2036 |
+
if time.Now().After(deadline) {
|
| 2037 |
+
SetOAuthSessionError(state, "Timeout waiting for OAuth callback")
|
| 2038 |
+
return nil, fmt.Errorf("timeout waiting for OAuth callback")
|
| 2039 |
+
}
|
| 2040 |
+
data, errRead := os.ReadFile(path)
|
| 2041 |
+
if errRead == nil {
|
| 2042 |
+
var m map[string]string
|
| 2043 |
+
_ = json.Unmarshal(data, &m)
|
| 2044 |
+
_ = os.Remove(path)
|
| 2045 |
+
return m, nil
|
| 2046 |
+
}
|
| 2047 |
+
time.Sleep(500 * time.Millisecond)
|
| 2048 |
+
}
|
| 2049 |
+
}
|
| 2050 |
+
|
| 2051 |
+
fmt.Println("Waiting for authentication callback...")
|
| 2052 |
+
// Wait up to 5 minutes
|
| 2053 |
+
resultMap, errWait := waitForFile(waitFile, 5*time.Minute)
|
| 2054 |
+
if errWait != nil {
|
| 2055 |
+
if errors.Is(errWait, errOAuthSessionNotPending) {
|
| 2056 |
+
return
|
| 2057 |
+
}
|
| 2058 |
+
authErr := claude.NewAuthenticationError(claude.ErrCallbackTimeout, errWait)
|
| 2059 |
+
log.Error(claude.GetUserFriendlyMessage(authErr))
|
| 2060 |
+
return
|
| 2061 |
+
}
|
| 2062 |
+
if errStr := resultMap["error"]; errStr != "" {
|
| 2063 |
+
oauthErr := claude.NewOAuthError(errStr, "", http.StatusBadRequest)
|
| 2064 |
+
log.Error(claude.GetUserFriendlyMessage(oauthErr))
|
| 2065 |
+
SetOAuthSessionError(state, "Bad request")
|
| 2066 |
+
return
|
| 2067 |
+
}
|
| 2068 |
+
if resultMap["state"] != state {
|
| 2069 |
+
authErr := claude.NewAuthenticationError(claude.ErrInvalidState, fmt.Errorf("expected %s, got %s", state, resultMap["state"]))
|
| 2070 |
+
log.Error(claude.GetUserFriendlyMessage(authErr))
|
| 2071 |
+
SetOAuthSessionError(state, "State code error")
|
| 2072 |
+
return
|
| 2073 |
+
}
|
| 2074 |
+
|
| 2075 |
+
// Parse code (Claude may append state after '#')
|
| 2076 |
+
rawCode := resultMap["code"]
|
| 2077 |
+
code := strings.Split(rawCode, "#")[0]
|
| 2078 |
+
|
| 2079 |
+
// Exchange code for tokens using internal auth service
|
| 2080 |
+
bundle, errExchange := anthropicAuth.ExchangeCodeForTokens(ctx, code, state, pkceCodes)
|
| 2081 |
+
if errExchange != nil {
|
| 2082 |
+
authErr := claude.NewAuthenticationError(claude.ErrCodeExchangeFailed, errExchange)
|
| 2083 |
+
log.Errorf("Failed to exchange authorization code for tokens: %v", authErr)
|
| 2084 |
+
SetOAuthSessionError(state, "Failed to exchange authorization code for tokens")
|
| 2085 |
+
return
|
| 2086 |
+
}
|
| 2087 |
+
|
| 2088 |
+
// Create token storage
|
| 2089 |
+
tokenStorage := anthropicAuth.CreateTokenStorage(bundle)
|
| 2090 |
+
record := &coreauth.Auth{
|
| 2091 |
+
ID: fmt.Sprintf("claude-%s.json", tokenStorage.Email),
|
| 2092 |
+
Provider: "claude",
|
| 2093 |
+
FileName: fmt.Sprintf("claude-%s.json", tokenStorage.Email),
|
| 2094 |
+
Storage: tokenStorage,
|
| 2095 |
+
Metadata: map[string]any{"email": tokenStorage.Email},
|
| 2096 |
+
}
|
| 2097 |
+
if errGuard := guardOAuthSessionPendingForSave(state, "anthropic"); errGuard != nil {
|
| 2098 |
+
return
|
| 2099 |
+
}
|
| 2100 |
+
savedPath, errSave := h.saveTokenRecord(ctx, record)
|
| 2101 |
+
if errSave != nil {
|
| 2102 |
+
log.Errorf("Failed to save authentication tokens: %v", errSave)
|
| 2103 |
+
SetOAuthSessionError(state, "Failed to save authentication tokens")
|
| 2104 |
+
return
|
| 2105 |
+
}
|
| 2106 |
+
|
| 2107 |
+
fmt.Printf("Authentication successful! Token saved to %s\n", savedPath)
|
| 2108 |
+
if bundle.APIKey != "" {
|
| 2109 |
+
fmt.Println("API key obtained and saved")
|
| 2110 |
+
}
|
| 2111 |
+
fmt.Println("You can now use Claude services through this CLI")
|
| 2112 |
+
CompleteOAuthSession(state)
|
| 2113 |
+
}()
|
| 2114 |
+
|
| 2115 |
+
c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state})
|
| 2116 |
+
}
|
| 2117 |
+
|
| 2118 |
+
func (h *Handler) RequestCodexToken(c *gin.Context) {
|
| 2119 |
+
ctx := context.Background()
|
| 2120 |
+
ctx = PopulateAuthContext(ctx, c)
|
| 2121 |
+
|
| 2122 |
+
fmt.Println("Initializing Codex authentication...")
|
| 2123 |
+
|
| 2124 |
+
// Generate PKCE codes
|
| 2125 |
+
pkceCodes, err := codex.GeneratePKCECodes()
|
| 2126 |
+
if err != nil {
|
| 2127 |
+
log.Errorf("Failed to generate PKCE codes: %v", err)
|
| 2128 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate PKCE codes"})
|
| 2129 |
+
return
|
| 2130 |
+
}
|
| 2131 |
+
|
| 2132 |
+
// Generate random state parameter
|
| 2133 |
+
state, err := misc.GenerateRandomState()
|
| 2134 |
+
if err != nil {
|
| 2135 |
+
log.Errorf("Failed to generate state parameter: %v", err)
|
| 2136 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate state parameter"})
|
| 2137 |
+
return
|
| 2138 |
+
}
|
| 2139 |
+
|
| 2140 |
+
// Initialize Codex auth service
|
| 2141 |
+
openaiAuth := newCodexOAuthService(h.cfg)
|
| 2142 |
+
|
| 2143 |
+
// Generate authorization URL
|
| 2144 |
+
authURL, err := openaiAuth.GenerateAuthURL(state, pkceCodes)
|
| 2145 |
+
if err != nil {
|
| 2146 |
+
log.Errorf("Failed to generate authorization URL: %v", err)
|
| 2147 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate authorization url"})
|
| 2148 |
+
return
|
| 2149 |
+
}
|
| 2150 |
+
|
| 2151 |
+
RegisterOAuthSession(state, "codex")
|
| 2152 |
+
|
| 2153 |
+
isWebUI := isWebUIRequest(c)
|
| 2154 |
+
var forwarder *callbackForwarder
|
| 2155 |
+
if isWebUI {
|
| 2156 |
+
targetURL, errTarget := h.managementCallbackURL("/codex/callback")
|
| 2157 |
+
if errTarget != nil {
|
| 2158 |
+
log.WithError(errTarget).Error("failed to compute codex callback target")
|
| 2159 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "callback server unavailable"})
|
| 2160 |
+
return
|
| 2161 |
+
}
|
| 2162 |
+
var errStart error
|
| 2163 |
+
if forwarder, errStart = startCallbackForwarder(codexCallbackPort, "codex", targetURL); errStart != nil {
|
| 2164 |
+
log.WithError(errStart).Error("failed to start codex callback forwarder")
|
| 2165 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start callback server"})
|
| 2166 |
+
return
|
| 2167 |
+
}
|
| 2168 |
+
}
|
| 2169 |
+
|
| 2170 |
+
go func() {
|
| 2171 |
+
if isWebUI {
|
| 2172 |
+
defer stopCallbackForwarderInstance(codexCallbackPort, forwarder)
|
| 2173 |
+
}
|
| 2174 |
+
|
| 2175 |
+
// Wait for callback file
|
| 2176 |
+
waitFile := filepath.Join(h.cfg.AuthDir, fmt.Sprintf(".oauth-codex-%s.oauth", state))
|
| 2177 |
+
deadline := time.Now().Add(5 * time.Minute)
|
| 2178 |
+
var code string
|
| 2179 |
+
for {
|
| 2180 |
+
if !IsOAuthSessionPending(state, "codex") {
|
| 2181 |
+
return
|
| 2182 |
+
}
|
| 2183 |
+
if time.Now().After(deadline) {
|
| 2184 |
+
authErr := codex.NewAuthenticationError(codex.ErrCallbackTimeout, fmt.Errorf("timeout waiting for OAuth callback"))
|
| 2185 |
+
log.Error(codex.GetUserFriendlyMessage(authErr))
|
| 2186 |
+
SetOAuthSessionError(state, "Timeout waiting for OAuth callback")
|
| 2187 |
+
return
|
| 2188 |
+
}
|
| 2189 |
+
if data, errR := os.ReadFile(waitFile); errR == nil {
|
| 2190 |
+
var m map[string]string
|
| 2191 |
+
_ = json.Unmarshal(data, &m)
|
| 2192 |
+
_ = os.Remove(waitFile)
|
| 2193 |
+
if errStr := m["error"]; errStr != "" {
|
| 2194 |
+
oauthErr := codex.NewOAuthError(errStr, "", http.StatusBadRequest)
|
| 2195 |
+
log.Error(codex.GetUserFriendlyMessage(oauthErr))
|
| 2196 |
+
SetOAuthSessionError(state, "Bad Request")
|
| 2197 |
+
return
|
| 2198 |
+
}
|
| 2199 |
+
if m["state"] != state {
|
| 2200 |
+
authErr := codex.NewAuthenticationError(codex.ErrInvalidState, fmt.Errorf("expected %s, got %s", state, m["state"]))
|
| 2201 |
+
SetOAuthSessionError(state, "State code error")
|
| 2202 |
+
log.Error(codex.GetUserFriendlyMessage(authErr))
|
| 2203 |
+
return
|
| 2204 |
+
}
|
| 2205 |
+
code = m["code"]
|
| 2206 |
+
break
|
| 2207 |
+
}
|
| 2208 |
+
time.Sleep(500 * time.Millisecond)
|
| 2209 |
+
}
|
| 2210 |
+
|
| 2211 |
+
log.Debug("Authorization code received, exchanging for tokens...")
|
| 2212 |
+
// Exchange code for tokens using internal auth service
|
| 2213 |
+
bundle, errExchange := openaiAuth.ExchangeCodeForTokens(ctx, code, pkceCodes)
|
| 2214 |
+
if errExchange != nil {
|
| 2215 |
+
authErr := codex.NewAuthenticationError(codex.ErrCodeExchangeFailed, errExchange)
|
| 2216 |
+
SetOAuthSessionError(state, oauthSessionErrorWithCause("Failed to exchange authorization code for tokens", errExchange))
|
| 2217 |
+
log.Errorf("Failed to exchange authorization code for tokens: %v", authErr)
|
| 2218 |
+
return
|
| 2219 |
+
}
|
| 2220 |
+
|
| 2221 |
+
// Extract additional info for filename generation
|
| 2222 |
+
claims, _ := codex.ParseJWTToken(bundle.TokenData.IDToken)
|
| 2223 |
+
planType := ""
|
| 2224 |
+
hashAccountID := ""
|
| 2225 |
+
if claims != nil {
|
| 2226 |
+
planType = strings.TrimSpace(claims.CodexAuthInfo.ChatgptPlanType)
|
| 2227 |
+
if accountID := claims.GetAccountID(); accountID != "" {
|
| 2228 |
+
digest := sha256.Sum256([]byte(accountID))
|
| 2229 |
+
hashAccountID = hex.EncodeToString(digest[:])[:8]
|
| 2230 |
+
}
|
| 2231 |
+
}
|
| 2232 |
+
|
| 2233 |
+
// Create token storage and persist
|
| 2234 |
+
tokenStorage := openaiAuth.CreateTokenStorage(bundle)
|
| 2235 |
+
fileName := codex.CredentialFileName(tokenStorage.Email, planType, hashAccountID, true)
|
| 2236 |
+
record := &coreauth.Auth{
|
| 2237 |
+
ID: fileName,
|
| 2238 |
+
Provider: "codex",
|
| 2239 |
+
FileName: fileName,
|
| 2240 |
+
Storage: tokenStorage,
|
| 2241 |
+
Metadata: map[string]any{
|
| 2242 |
+
"email": tokenStorage.Email,
|
| 2243 |
+
"account_id": tokenStorage.AccountID,
|
| 2244 |
+
},
|
| 2245 |
+
}
|
| 2246 |
+
if errGuard := guardOAuthSessionPendingForSave(state, "codex"); errGuard != nil {
|
| 2247 |
+
return
|
| 2248 |
+
}
|
| 2249 |
+
savedPath, errSave := h.saveTokenRecord(ctx, record)
|
| 2250 |
+
if errSave != nil {
|
| 2251 |
+
SetOAuthSessionError(state, "Failed to save authentication tokens")
|
| 2252 |
+
log.Errorf("Failed to save authentication tokens: %v", errSave)
|
| 2253 |
+
return
|
| 2254 |
+
}
|
| 2255 |
+
fmt.Printf("Authentication successful! Token saved to %s\n", savedPath)
|
| 2256 |
+
if bundle.APIKey != "" {
|
| 2257 |
+
fmt.Println("API key obtained and saved")
|
| 2258 |
+
}
|
| 2259 |
+
fmt.Println("You can now use Codex services through this CLI")
|
| 2260 |
+
CompleteOAuthSession(state)
|
| 2261 |
+
}()
|
| 2262 |
+
|
| 2263 |
+
c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state})
|
| 2264 |
+
}
|
| 2265 |
+
|
| 2266 |
+
func (h *Handler) RequestAntigravityToken(c *gin.Context) {
|
| 2267 |
+
ctx := context.Background()
|
| 2268 |
+
ctx = PopulateAuthContext(ctx, c)
|
| 2269 |
+
|
| 2270 |
+
fmt.Println("Initializing Antigravity authentication...")
|
| 2271 |
+
|
| 2272 |
+
authSvc := antigravity.NewAntigravityAuth(h.cfg, nil)
|
| 2273 |
+
|
| 2274 |
+
state, errState := misc.GenerateRandomState()
|
| 2275 |
+
if errState != nil {
|
| 2276 |
+
log.Errorf("Failed to generate state parameter: %v", errState)
|
| 2277 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate state parameter"})
|
| 2278 |
+
return
|
| 2279 |
+
}
|
| 2280 |
+
|
| 2281 |
+
redirectURI := fmt.Sprintf("http://localhost:%d/oauth-callback", antigravity.CallbackPort)
|
| 2282 |
+
authURL := authSvc.BuildAuthURL(state, redirectURI)
|
| 2283 |
+
|
| 2284 |
+
RegisterOAuthSession(state, "antigravity")
|
| 2285 |
+
|
| 2286 |
+
isWebUI := isWebUIRequest(c)
|
| 2287 |
+
var forwarder *callbackForwarder
|
| 2288 |
+
if isWebUI {
|
| 2289 |
+
targetURL, errTarget := h.managementCallbackURL("/antigravity/callback")
|
| 2290 |
+
if errTarget != nil {
|
| 2291 |
+
log.WithError(errTarget).Error("failed to compute antigravity callback target")
|
| 2292 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "callback server unavailable"})
|
| 2293 |
+
return
|
| 2294 |
+
}
|
| 2295 |
+
var errStart error
|
| 2296 |
+
if forwarder, errStart = startCallbackForwarder(antigravity.CallbackPort, "antigravity", targetURL); errStart != nil {
|
| 2297 |
+
log.WithError(errStart).Error("failed to start antigravity callback forwarder")
|
| 2298 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start callback server"})
|
| 2299 |
+
return
|
| 2300 |
+
}
|
| 2301 |
+
}
|
| 2302 |
+
|
| 2303 |
+
go func() {
|
| 2304 |
+
if isWebUI {
|
| 2305 |
+
defer stopCallbackForwarderInstance(antigravity.CallbackPort, forwarder)
|
| 2306 |
+
}
|
| 2307 |
+
|
| 2308 |
+
waitFile := filepath.Join(h.cfg.AuthDir, fmt.Sprintf(".oauth-antigravity-%s.oauth", state))
|
| 2309 |
+
deadline := time.Now().Add(5 * time.Minute)
|
| 2310 |
+
var authCode string
|
| 2311 |
+
for {
|
| 2312 |
+
if !IsOAuthSessionPending(state, "antigravity") {
|
| 2313 |
+
return
|
| 2314 |
+
}
|
| 2315 |
+
if time.Now().After(deadline) {
|
| 2316 |
+
log.Error("oauth flow timed out")
|
| 2317 |
+
SetOAuthSessionError(state, "OAuth flow timed out")
|
| 2318 |
+
return
|
| 2319 |
+
}
|
| 2320 |
+
if data, errReadFile := os.ReadFile(waitFile); errReadFile == nil {
|
| 2321 |
+
var payload map[string]string
|
| 2322 |
+
_ = json.Unmarshal(data, &payload)
|
| 2323 |
+
_ = os.Remove(waitFile)
|
| 2324 |
+
if errStr := strings.TrimSpace(payload["error"]); errStr != "" {
|
| 2325 |
+
log.Errorf("Authentication failed: %s", errStr)
|
| 2326 |
+
SetOAuthSessionError(state, "Authentication failed")
|
| 2327 |
+
return
|
| 2328 |
+
}
|
| 2329 |
+
if payloadState := strings.TrimSpace(payload["state"]); payloadState != "" && payloadState != state {
|
| 2330 |
+
log.Errorf("Authentication failed: state mismatch")
|
| 2331 |
+
SetOAuthSessionError(state, "Authentication failed: state mismatch")
|
| 2332 |
+
return
|
| 2333 |
+
}
|
| 2334 |
+
authCode = strings.TrimSpace(payload["code"])
|
| 2335 |
+
if authCode == "" {
|
| 2336 |
+
log.Error("Authentication failed: code not found")
|
| 2337 |
+
SetOAuthSessionError(state, "Authentication failed: code not found")
|
| 2338 |
+
return
|
| 2339 |
+
}
|
| 2340 |
+
break
|
| 2341 |
+
}
|
| 2342 |
+
time.Sleep(500 * time.Millisecond)
|
| 2343 |
+
}
|
| 2344 |
+
|
| 2345 |
+
tokenResp, errToken := authSvc.ExchangeCodeForTokens(ctx, authCode, redirectURI)
|
| 2346 |
+
if errToken != nil {
|
| 2347 |
+
log.Errorf("Failed to exchange token: %v", errToken)
|
| 2348 |
+
SetOAuthSessionError(state, "Failed to exchange token")
|
| 2349 |
+
return
|
| 2350 |
+
}
|
| 2351 |
+
|
| 2352 |
+
accessToken := strings.TrimSpace(tokenResp.AccessToken)
|
| 2353 |
+
if accessToken == "" {
|
| 2354 |
+
log.Error("antigravity: token exchange returned empty access token")
|
| 2355 |
+
SetOAuthSessionError(state, "Failed to exchange token")
|
| 2356 |
+
return
|
| 2357 |
+
}
|
| 2358 |
+
|
| 2359 |
+
email, errInfo := authSvc.FetchUserInfo(ctx, accessToken)
|
| 2360 |
+
if errInfo != nil {
|
| 2361 |
+
log.Errorf("Failed to fetch user info: %v", errInfo)
|
| 2362 |
+
SetOAuthSessionError(state, "Failed to fetch user info")
|
| 2363 |
+
return
|
| 2364 |
+
}
|
| 2365 |
+
email = strings.TrimSpace(email)
|
| 2366 |
+
if email == "" {
|
| 2367 |
+
log.Error("antigravity: user info returned empty email")
|
| 2368 |
+
SetOAuthSessionError(state, "Failed to fetch user info")
|
| 2369 |
+
return
|
| 2370 |
+
}
|
| 2371 |
+
|
| 2372 |
+
projectID := ""
|
| 2373 |
+
if accessToken != "" {
|
| 2374 |
+
fetchedProjectID, errProject := authSvc.FetchProjectID(ctx, accessToken)
|
| 2375 |
+
if errProject != nil {
|
| 2376 |
+
log.Warnf("antigravity: failed to fetch project ID: %v", errProject)
|
| 2377 |
+
} else {
|
| 2378 |
+
projectID = fetchedProjectID
|
| 2379 |
+
log.Infof("antigravity: obtained project ID %s", util.HideAPIKey(projectID))
|
| 2380 |
+
}
|
| 2381 |
+
}
|
| 2382 |
+
|
| 2383 |
+
now := time.Now()
|
| 2384 |
+
metadata := map[string]any{
|
| 2385 |
+
"type": "antigravity",
|
| 2386 |
+
"access_token": tokenResp.AccessToken,
|
| 2387 |
+
"refresh_token": tokenResp.RefreshToken,
|
| 2388 |
+
"expires_in": tokenResp.ExpiresIn,
|
| 2389 |
+
"timestamp": now.UnixMilli(),
|
| 2390 |
+
"expired": now.Add(time.Duration(tokenResp.ExpiresIn) * time.Second).Format(time.RFC3339),
|
| 2391 |
+
}
|
| 2392 |
+
if email != "" {
|
| 2393 |
+
metadata["email"] = email
|
| 2394 |
+
}
|
| 2395 |
+
if projectID != "" {
|
| 2396 |
+
metadata["project_id"] = projectID
|
| 2397 |
+
}
|
| 2398 |
+
|
| 2399 |
+
fileName := antigravity.CredentialFileName(email)
|
| 2400 |
+
label := strings.TrimSpace(email)
|
| 2401 |
+
if label == "" {
|
| 2402 |
+
label = "antigravity"
|
| 2403 |
+
}
|
| 2404 |
+
|
| 2405 |
+
record := &coreauth.Auth{
|
| 2406 |
+
ID: fileName,
|
| 2407 |
+
Provider: "antigravity",
|
| 2408 |
+
FileName: fileName,
|
| 2409 |
+
Label: label,
|
| 2410 |
+
Metadata: metadata,
|
| 2411 |
+
}
|
| 2412 |
+
if errGuard := guardOAuthSessionPendingForSave(state, "antigravity"); errGuard != nil {
|
| 2413 |
+
return
|
| 2414 |
+
}
|
| 2415 |
+
savedPath, errSave := h.saveTokenRecord(ctx, record)
|
| 2416 |
+
if errSave != nil {
|
| 2417 |
+
log.Errorf("Failed to save token to file: %v", errSave)
|
| 2418 |
+
SetOAuthSessionError(state, "Failed to save token to file")
|
| 2419 |
+
return
|
| 2420 |
+
}
|
| 2421 |
+
|
| 2422 |
+
CompleteOAuthSession(state)
|
| 2423 |
+
fmt.Printf("Authentication successful! Token saved to %s\n", savedPath)
|
| 2424 |
+
if projectID != "" {
|
| 2425 |
+
fmt.Printf("Using GCP project: %s\n", util.HideAPIKey(projectID))
|
| 2426 |
+
}
|
| 2427 |
+
fmt.Println("You can now use Antigravity services through this CLI")
|
| 2428 |
+
}()
|
| 2429 |
+
|
| 2430 |
+
c.JSON(200, gin.H{"status": "ok", "url": authURL, "state": state})
|
| 2431 |
+
}
|
| 2432 |
+
|
| 2433 |
+
func (h *Handler) RequestXAIToken(c *gin.Context) {
|
| 2434 |
+
ctx := context.Background()
|
| 2435 |
+
ctx = PopulateAuthContext(ctx, c)
|
| 2436 |
+
|
| 2437 |
+
fmt.Println("Initializing xAI authentication...")
|
| 2438 |
+
|
| 2439 |
+
state := fmt.Sprintf("xai-%d", time.Now().UnixNano())
|
| 2440 |
+
authSvc := xaiauth.NewXAIAuth(h.cfg)
|
| 2441 |
+
|
| 2442 |
+
deviceFlow, errStartDeviceFlow := authSvc.StartDeviceFlow(ctx)
|
| 2443 |
+
if errStartDeviceFlow != nil {
|
| 2444 |
+
log.Errorf("Failed to start xAI device flow: %v", errStartDeviceFlow)
|
| 2445 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start device authorization flow"})
|
| 2446 |
+
return
|
| 2447 |
+
}
|
| 2448 |
+
authURL := strings.TrimSpace(deviceFlow.VerificationURIComplete)
|
| 2449 |
+
if authURL == "" {
|
| 2450 |
+
authURL = strings.TrimSpace(deviceFlow.VerificationURI)
|
| 2451 |
+
}
|
| 2452 |
+
|
| 2453 |
+
RegisterOAuthSession(state, "xai")
|
| 2454 |
+
|
| 2455 |
+
go func() {
|
| 2456 |
+
pollCtx, cancelPoll := context.WithCancel(ctx)
|
| 2457 |
+
defer cancelPoll()
|
| 2458 |
+
go watchOAuthSessionCancel(pollCtx, cancelPoll, state, "xai")
|
| 2459 |
+
|
| 2460 |
+
fmt.Println("Waiting for xAI authentication...")
|
| 2461 |
+
bundle, errWaitForAuthorization := authSvc.WaitForAuthorization(pollCtx, deviceFlow)
|
| 2462 |
+
if errWaitForAuthorization != nil {
|
| 2463 |
+
if !IsOAuthSessionPending(state, "xai") {
|
| 2464 |
+
return
|
| 2465 |
+
}
|
| 2466 |
+
log.Errorf("xAI authentication failed: %v", errWaitForAuthorization)
|
| 2467 |
+
SetOAuthSessionError(state, oauthSessionErrorWithCause("Authentication failed", errWaitForAuthorization))
|
| 2468 |
+
return
|
| 2469 |
+
}
|
| 2470 |
+
if !IsOAuthSessionPending(state, "xai") {
|
| 2471 |
+
return
|
| 2472 |
+
}
|
| 2473 |
+
|
| 2474 |
+
tokenStorage := authSvc.CreateTokenStorage(bundle)
|
| 2475 |
+
if tokenStorage == nil || strings.TrimSpace(tokenStorage.AccessToken) == "" {
|
| 2476 |
+
log.Error("xAI token exchange returned empty access token")
|
| 2477 |
+
SetOAuthSessionError(state, "Failed to exchange token")
|
| 2478 |
+
return
|
| 2479 |
+
}
|
| 2480 |
+
|
| 2481 |
+
fileName := xaiauth.CredentialFileName(tokenStorage.Email, tokenStorage.Subject)
|
| 2482 |
+
label := strings.TrimSpace(tokenStorage.Email)
|
| 2483 |
+
if label == "" {
|
| 2484 |
+
label = "xAI"
|
| 2485 |
+
}
|
| 2486 |
+
|
| 2487 |
+
metadata := map[string]any{
|
| 2488 |
+
"type": "xai",
|
| 2489 |
+
"access_token": tokenStorage.AccessToken,
|
| 2490 |
+
"refresh_token": tokenStorage.RefreshToken,
|
| 2491 |
+
"id_token": tokenStorage.IDToken,
|
| 2492 |
+
"token_type": tokenStorage.TokenType,
|
| 2493 |
+
"expires_in": tokenStorage.ExpiresIn,
|
| 2494 |
+
"expired": tokenStorage.Expire,
|
| 2495 |
+
"last_refresh": tokenStorage.LastRefresh,
|
| 2496 |
+
"base_url": tokenStorage.BaseURL,
|
| 2497 |
+
"token_endpoint": tokenStorage.TokenEndpoint,
|
| 2498 |
+
"auth_kind": "oauth",
|
| 2499 |
+
}
|
| 2500 |
+
if tokenStorage.Email != "" {
|
| 2501 |
+
metadata["email"] = tokenStorage.Email
|
| 2502 |
+
}
|
| 2503 |
+
if tokenStorage.Subject != "" {
|
| 2504 |
+
metadata["sub"] = tokenStorage.Subject
|
| 2505 |
+
}
|
| 2506 |
+
|
| 2507 |
+
record := &coreauth.Auth{
|
| 2508 |
+
ID: fileName,
|
| 2509 |
+
Provider: "xai",
|
| 2510 |
+
FileName: fileName,
|
| 2511 |
+
Label: label,
|
| 2512 |
+
Storage: tokenStorage,
|
| 2513 |
+
Metadata: metadata,
|
| 2514 |
+
Attributes: map[string]string{
|
| 2515 |
+
"auth_kind": "oauth",
|
| 2516 |
+
"base_url": tokenStorage.BaseURL,
|
| 2517 |
+
},
|
| 2518 |
+
}
|
| 2519 |
+
if errGuard := guardOAuthSessionPendingForSave(state, "xai"); errGuard != nil {
|
| 2520 |
+
return
|
| 2521 |
+
}
|
| 2522 |
+
savedPath, errSave := h.saveTokenRecord(ctx, record)
|
| 2523 |
+
if errSave != nil {
|
| 2524 |
+
log.Errorf("Failed to save xAI token to file: %v", errSave)
|
| 2525 |
+
SetOAuthSessionError(state, "Failed to save token to file")
|
| 2526 |
+
return
|
| 2527 |
+
}
|
| 2528 |
+
|
| 2529 |
+
CompleteOAuthSession(state)
|
| 2530 |
+
fmt.Printf("Authentication successful! Token saved to %s\n", savedPath)
|
| 2531 |
+
fmt.Println("You can now use xAI services through this CLI")
|
| 2532 |
+
}()
|
| 2533 |
+
|
| 2534 |
+
response := gin.H{"status": "ok", "url": authURL, "state": state, "flow": "device"}
|
| 2535 |
+
if userCode := strings.TrimSpace(deviceFlow.UserCode); userCode != "" {
|
| 2536 |
+
response["user_code"] = userCode
|
| 2537 |
+
}
|
| 2538 |
+
if deviceFlow.ExpiresIn > 0 {
|
| 2539 |
+
response["expires_in"] = deviceFlow.ExpiresIn
|
| 2540 |
+
} else {
|
| 2541 |
+
response["expires_in"] = int(xaiauth.MaxPollDuration / time.Second)
|
| 2542 |
+
}
|
| 2543 |
+
c.JSON(200, response)
|
| 2544 |
+
}
|
| 2545 |
+
|
| 2546 |
+
func (h *Handler) RequestKimiToken(c *gin.Context) {
|
| 2547 |
+
ctx := context.Background()
|
| 2548 |
+
ctx = PopulateAuthContext(ctx, c)
|
| 2549 |
+
|
| 2550 |
+
fmt.Println("Initializing Kimi authentication...")
|
| 2551 |
+
|
| 2552 |
+
state := fmt.Sprintf("kmi-%d", time.Now().UnixNano())
|
| 2553 |
+
// Initialize Kimi auth service
|
| 2554 |
+
kimiAuth := kimi.NewKimiAuth(h.cfg)
|
| 2555 |
+
|
| 2556 |
+
// Generate authorization URL
|
| 2557 |
+
deviceFlow, errStartDeviceFlow := kimiAuth.StartDeviceFlow(ctx)
|
| 2558 |
+
if errStartDeviceFlow != nil {
|
| 2559 |
+
log.Errorf("Failed to generate authorization URL: %v", errStartDeviceFlow)
|
| 2560 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate authorization url"})
|
| 2561 |
+
return
|
| 2562 |
+
}
|
| 2563 |
+
authURL := deviceFlow.VerificationURIComplete
|
| 2564 |
+
if authURL == "" {
|
| 2565 |
+
authURL = deviceFlow.VerificationURI
|
| 2566 |
+
}
|
| 2567 |
+
|
| 2568 |
+
RegisterOAuthSession(state, "kimi")
|
| 2569 |
+
|
| 2570 |
+
go func() {
|
| 2571 |
+
pollCtx, cancelPoll := context.WithCancel(ctx)
|
| 2572 |
+
defer cancelPoll()
|
| 2573 |
+
go watchOAuthSessionCancel(pollCtx, cancelPoll, state, "kimi")
|
| 2574 |
+
|
| 2575 |
+
fmt.Println("Waiting for authentication...")
|
| 2576 |
+
authBundle, errWaitForAuthorization := kimiAuth.WaitForAuthorization(pollCtx, deviceFlow)
|
| 2577 |
+
if errWaitForAuthorization != nil {
|
| 2578 |
+
if !IsOAuthSessionPending(state, "kimi") {
|
| 2579 |
+
return
|
| 2580 |
+
}
|
| 2581 |
+
SetOAuthSessionError(state, oauthSessionErrorWithCause("Authentication failed", errWaitForAuthorization))
|
| 2582 |
+
fmt.Printf("Authentication failed: %v\n", errWaitForAuthorization)
|
| 2583 |
+
return
|
| 2584 |
+
}
|
| 2585 |
+
if !IsOAuthSessionPending(state, "kimi") {
|
| 2586 |
+
return
|
| 2587 |
+
}
|
| 2588 |
+
|
| 2589 |
+
// Create token storage
|
| 2590 |
+
tokenStorage := kimiAuth.CreateTokenStorage(authBundle)
|
| 2591 |
+
|
| 2592 |
+
metadata := map[string]any{
|
| 2593 |
+
"type": "kimi",
|
| 2594 |
+
"access_token": authBundle.TokenData.AccessToken,
|
| 2595 |
+
"refresh_token": authBundle.TokenData.RefreshToken,
|
| 2596 |
+
"token_type": authBundle.TokenData.TokenType,
|
| 2597 |
+
"scope": authBundle.TokenData.Scope,
|
| 2598 |
+
"timestamp": time.Now().UnixMilli(),
|
| 2599 |
+
}
|
| 2600 |
+
if authBundle.TokenData.ExpiresAt > 0 {
|
| 2601 |
+
expired := time.Unix(authBundle.TokenData.ExpiresAt, 0).UTC().Format(time.RFC3339)
|
| 2602 |
+
metadata["expired"] = expired
|
| 2603 |
+
}
|
| 2604 |
+
if strings.TrimSpace(authBundle.DeviceID) != "" {
|
| 2605 |
+
metadata["device_id"] = strings.TrimSpace(authBundle.DeviceID)
|
| 2606 |
+
}
|
| 2607 |
+
|
| 2608 |
+
fileName := fmt.Sprintf("kimi-%d.json", time.Now().UnixMilli())
|
| 2609 |
+
record := &coreauth.Auth{
|
| 2610 |
+
ID: fileName,
|
| 2611 |
+
Provider: "kimi",
|
| 2612 |
+
FileName: fileName,
|
| 2613 |
+
Label: "Kimi User",
|
| 2614 |
+
Storage: tokenStorage,
|
| 2615 |
+
Metadata: metadata,
|
| 2616 |
+
}
|
| 2617 |
+
if errGuard := guardOAuthSessionPendingForSave(state, "kimi"); errGuard != nil {
|
| 2618 |
+
return
|
| 2619 |
+
}
|
| 2620 |
+
savedPath, errSave := h.saveTokenRecord(ctx, record)
|
| 2621 |
+
if errSave != nil {
|
| 2622 |
+
log.Errorf("Failed to save authentication tokens: %v", errSave)
|
| 2623 |
+
SetOAuthSessionError(state, "Failed to save authentication tokens")
|
| 2624 |
+
return
|
| 2625 |
+
}
|
| 2626 |
+
|
| 2627 |
+
fmt.Printf("Authentication successful! Token saved to %s\n", savedPath)
|
| 2628 |
+
fmt.Println("You can now use Kimi services through this CLI")
|
| 2629 |
+
CompleteOAuthSession(state)
|
| 2630 |
+
}()
|
| 2631 |
+
|
| 2632 |
+
response := gin.H{"status": "ok", "url": authURL, "state": state, "flow": "device"}
|
| 2633 |
+
if userCode := strings.TrimSpace(deviceFlow.UserCode); userCode != "" {
|
| 2634 |
+
response["user_code"] = userCode
|
| 2635 |
+
}
|
| 2636 |
+
if deviceFlow.ExpiresIn > 0 {
|
| 2637 |
+
response["expires_in"] = deviceFlow.ExpiresIn
|
| 2638 |
+
}
|
| 2639 |
+
c.JSON(200, response)
|
| 2640 |
+
}
|
| 2641 |
+
|
| 2642 |
+
// watchOAuthSessionCancel cancels pollCtx once the OAuth session is no longer pending.
|
| 2643 |
+
func watchOAuthSessionCancel(pollCtx context.Context, cancel context.CancelFunc, state, provider string) {
|
| 2644 |
+
if cancel == nil {
|
| 2645 |
+
return
|
| 2646 |
+
}
|
| 2647 |
+
ticker := time.NewTicker(2 * time.Second)
|
| 2648 |
+
defer ticker.Stop()
|
| 2649 |
+
for {
|
| 2650 |
+
select {
|
| 2651 |
+
case <-pollCtx.Done():
|
| 2652 |
+
return
|
| 2653 |
+
case <-ticker.C:
|
| 2654 |
+
if !IsOAuthSessionPending(state, provider) {
|
| 2655 |
+
cancel()
|
| 2656 |
+
return
|
| 2657 |
+
}
|
| 2658 |
+
}
|
| 2659 |
+
}
|
| 2660 |
+
}
|
| 2661 |
+
|
| 2662 |
+
// CancelAuthSession cancels a pending OAuth session identified by state.
|
| 2663 |
+
// Protected by management auth. Safe for both callback and device-code flows:
|
| 2664 |
+
// waiters check IsOAuthSessionPending and exit without saving credentials.
|
| 2665 |
+
func (h *Handler) CancelAuthSession(c *gin.Context) {
|
| 2666 |
+
state := strings.TrimSpace(c.Query("state"))
|
| 2667 |
+
if state == "" {
|
| 2668 |
+
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "missing state"})
|
| 2669 |
+
return
|
| 2670 |
+
}
|
| 2671 |
+
if err := ValidateOAuthState(state); err != nil {
|
| 2672 |
+
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "invalid state"})
|
| 2673 |
+
return
|
| 2674 |
+
}
|
| 2675 |
+
cancelled := CancelOAuthSession(state)
|
| 2676 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok", "cancelled": cancelled})
|
| 2677 |
+
}
|
| 2678 |
+
|
| 2679 |
+
func (h *Handler) GetAuthStatus(c *gin.Context) {
|
| 2680 |
+
state := strings.TrimSpace(c.Query("state"))
|
| 2681 |
+
if state == "" {
|
| 2682 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
| 2683 |
+
return
|
| 2684 |
+
}
|
| 2685 |
+
if err := ValidateOAuthState(state); err != nil {
|
| 2686 |
+
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "invalid state"})
|
| 2687 |
+
return
|
| 2688 |
+
}
|
| 2689 |
+
|
| 2690 |
+
provider, status, isPlugin, metadata, completed, ok := GetOAuthSessionDetails(state)
|
| 2691 |
+
if !ok {
|
| 2692 |
+
c.JSON(http.StatusOK, gin.H{"status": "error", "error": "unknown or expired state"})
|
| 2693 |
+
return
|
| 2694 |
+
}
|
| 2695 |
+
if completed {
|
| 2696 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
| 2697 |
+
return
|
| 2698 |
+
}
|
| 2699 |
+
if status != "" {
|
| 2700 |
+
c.JSON(http.StatusOK, gin.H{"status": "error", "error": status})
|
| 2701 |
+
return
|
| 2702 |
+
}
|
| 2703 |
+
h.mu.Lock()
|
| 2704 |
+
host := h.pluginHost
|
| 2705 |
+
h.mu.Unlock()
|
| 2706 |
+
if isPlugin && host != nil && host.HasAuthProvider(provider) {
|
| 2707 |
+
ctx := PopulateAuthContext(context.Background(), c)
|
| 2708 |
+
resp, handled, errPoll := host.PollLogin(ctx, provider, state, metadata)
|
| 2709 |
+
if handled {
|
| 2710 |
+
if errPoll != nil {
|
| 2711 |
+
message := strings.TrimSpace(errPoll.Error())
|
| 2712 |
+
if message == "" {
|
| 2713 |
+
message = "Authentication failed"
|
| 2714 |
+
}
|
| 2715 |
+
SetOAuthSessionError(state, message)
|
| 2716 |
+
c.JSON(http.StatusOK, gin.H{"status": "error", "error": message})
|
| 2717 |
+
return
|
| 2718 |
+
}
|
| 2719 |
+
switch resp.Status {
|
| 2720 |
+
case "", pluginapi.AuthLoginStatusPending:
|
| 2721 |
+
c.JSON(http.StatusOK, gin.H{"status": "wait"})
|
| 2722 |
+
return
|
| 2723 |
+
case pluginapi.AuthLoginStatusError:
|
| 2724 |
+
message := strings.TrimSpace(resp.Message)
|
| 2725 |
+
if message == "" {
|
| 2726 |
+
message = "Authentication failed"
|
| 2727 |
+
}
|
| 2728 |
+
SetOAuthSessionError(state, message)
|
| 2729 |
+
c.JSON(http.StatusOK, gin.H{"status": "error", "error": message})
|
| 2730 |
+
return
|
| 2731 |
+
case pluginapi.AuthLoginStatusSuccess:
|
| 2732 |
+
records := pluginLoginPollAuths(host, resp)
|
| 2733 |
+
if len(records) == 0 {
|
| 2734 |
+
SetOAuthSessionError(state, "Authentication failed")
|
| 2735 |
+
c.JSON(http.StatusOK, gin.H{"status": "error", "error": "Authentication failed"})
|
| 2736 |
+
return
|
| 2737 |
+
}
|
| 2738 |
+
if errSave := h.savePluginLoginRecords(ctx, records); errSave != nil {
|
| 2739 |
+
log.WithError(errSave).WithField("provider", provider).Error("failed to save plugin auth tokens")
|
| 2740 |
+
SetOAuthSessionError(state, "Failed to save authentication tokens")
|
| 2741 |
+
c.JSON(http.StatusOK, gin.H{"status": "error", "error": "Failed to save authentication tokens"})
|
| 2742 |
+
return
|
| 2743 |
+
}
|
| 2744 |
+
CompleteOAuthSession(state)
|
| 2745 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
| 2746 |
+
return
|
| 2747 |
+
default:
|
| 2748 |
+
c.JSON(http.StatusOK, gin.H{"status": "wait"})
|
| 2749 |
+
return
|
| 2750 |
+
}
|
| 2751 |
+
}
|
| 2752 |
+
}
|
| 2753 |
+
c.JSON(http.StatusOK, gin.H{"status": "wait"})
|
| 2754 |
+
}
|
| 2755 |
+
|
| 2756 |
+
func pluginLoginPollAuths(host *pluginhost.Host, resp pluginapi.AuthLoginPollResponse) []*coreauth.Auth {
|
| 2757 |
+
if host == nil {
|
| 2758 |
+
return nil
|
| 2759 |
+
}
|
| 2760 |
+
authDatas := resp.Auths
|
| 2761 |
+
if len(authDatas) == 0 {
|
| 2762 |
+
authDatas = []pluginapi.AuthData{resp.Auth}
|
| 2763 |
+
}
|
| 2764 |
+
records := make([]*coreauth.Auth, 0, len(authDatas))
|
| 2765 |
+
for _, authData := range authDatas {
|
| 2766 |
+
record := host.AuthDataToCoreAuth(authData, "", "")
|
| 2767 |
+
if record == nil {
|
| 2768 |
+
return nil
|
| 2769 |
+
}
|
| 2770 |
+
records = append(records, record)
|
| 2771 |
+
}
|
| 2772 |
+
return records
|
| 2773 |
+
}
|
| 2774 |
+
|
| 2775 |
+
func (h *Handler) savePluginLoginRecords(ctx context.Context, records []*coreauth.Auth) error {
|
| 2776 |
+
savedPaths := make([]string, 0, len(records))
|
| 2777 |
+
for _, record := range records {
|
| 2778 |
+
savedPath, errSave := h.saveTokenRecord(ctx, record)
|
| 2779 |
+
if strings.TrimSpace(savedPath) != "" {
|
| 2780 |
+
savedPaths = append(savedPaths, savedPath)
|
| 2781 |
+
}
|
| 2782 |
+
if errSave != nil {
|
| 2783 |
+
h.rollbackSavedTokenRecords(ctx, savedPaths)
|
| 2784 |
+
return errSave
|
| 2785 |
+
}
|
| 2786 |
+
}
|
| 2787 |
+
return nil
|
| 2788 |
+
}
|
| 2789 |
+
|
| 2790 |
+
func (h *Handler) rollbackSavedTokenRecords(ctx context.Context, savedPaths []string) {
|
| 2791 |
+
for i := len(savedPaths) - 1; i >= 0; i-- {
|
| 2792 |
+
path := strings.TrimSpace(savedPaths[i])
|
| 2793 |
+
if path == "" {
|
| 2794 |
+
continue
|
| 2795 |
+
}
|
| 2796 |
+
if errDelete := h.deleteTokenRecord(ctx, path); errDelete != nil {
|
| 2797 |
+
log.WithError(errDelete).WithField("path", path).Warn("failed to roll back plugin auth token")
|
| 2798 |
+
}
|
| 2799 |
+
h.removeAuthsForPath(ctx, path, path)
|
| 2800 |
+
}
|
| 2801 |
+
}
|
| 2802 |
+
|
| 2803 |
+
// PopulateAuthContext extracts request info and adds it to the context
|
| 2804 |
+
func PopulateAuthContext(ctx context.Context, c *gin.Context) context.Context {
|
| 2805 |
+
info := &coreauth.RequestInfo{
|
| 2806 |
+
Query: c.Request.URL.Query(),
|
| 2807 |
+
Headers: c.Request.Header,
|
| 2808 |
+
}
|
| 2809 |
+
return coreauth.WithRequestInfo(ctx, info)
|
| 2810 |
+
}
|
internal/api/handlers/management/auth_files_batch_test.go
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"bytes"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"mime/multipart"
|
| 7 |
+
"net/http"
|
| 8 |
+
"net/http/httptest"
|
| 9 |
+
"net/url"
|
| 10 |
+
"os"
|
| 11 |
+
"path/filepath"
|
| 12 |
+
"testing"
|
| 13 |
+
|
| 14 |
+
"github.com/gin-gonic/gin"
|
| 15 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 16 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
func TestUploadAuthFile_BatchMultipart(t *testing.T) {
|
| 20 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 21 |
+
|
| 22 |
+
authDir := t.TempDir()
|
| 23 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 24 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 25 |
+
|
| 26 |
+
files := []struct {
|
| 27 |
+
name string
|
| 28 |
+
content string
|
| 29 |
+
}{
|
| 30 |
+
{name: "alpha.json", content: `{"type":"codex","email":"alpha@example.com"}`},
|
| 31 |
+
{name: "beta.json", content: `{"type":"claude","email":"beta@example.com"}`},
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
var body bytes.Buffer
|
| 35 |
+
writer := multipart.NewWriter(&body)
|
| 36 |
+
for _, file := range files {
|
| 37 |
+
part, err := writer.CreateFormFile("file", file.name)
|
| 38 |
+
if err != nil {
|
| 39 |
+
t.Fatalf("failed to create multipart file: %v", err)
|
| 40 |
+
}
|
| 41 |
+
if _, err = part.Write([]byte(file.content)); err != nil {
|
| 42 |
+
t.Fatalf("failed to write multipart content: %v", err)
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
if err := writer.Close(); err != nil {
|
| 46 |
+
t.Fatalf("failed to close multipart writer: %v", err)
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
rec := httptest.NewRecorder()
|
| 50 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 51 |
+
req := httptest.NewRequest(http.MethodPost, "/v0/management/auth-files", &body)
|
| 52 |
+
req.Header.Set("Content-Type", writer.FormDataContentType())
|
| 53 |
+
ctx.Request = req
|
| 54 |
+
|
| 55 |
+
h.UploadAuthFile(ctx)
|
| 56 |
+
|
| 57 |
+
if rec.Code != http.StatusOK {
|
| 58 |
+
t.Fatalf("expected upload status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
var payload map[string]any
|
| 62 |
+
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
|
| 63 |
+
t.Fatalf("failed to decode response: %v", err)
|
| 64 |
+
}
|
| 65 |
+
if got, ok := payload["uploaded"].(float64); !ok || int(got) != len(files) {
|
| 66 |
+
t.Fatalf("expected uploaded=%d, got %#v", len(files), payload["uploaded"])
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
for _, file := range files {
|
| 70 |
+
fullPath := filepath.Join(authDir, file.name)
|
| 71 |
+
data, err := os.ReadFile(fullPath)
|
| 72 |
+
if err != nil {
|
| 73 |
+
t.Fatalf("expected uploaded file %s to exist: %v", file.name, err)
|
| 74 |
+
}
|
| 75 |
+
if string(data) != file.content {
|
| 76 |
+
t.Fatalf("expected file %s content %q, got %q", file.name, file.content, string(data))
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
auths := manager.List()
|
| 81 |
+
if len(auths) != len(files) {
|
| 82 |
+
t.Fatalf("expected %d auth entries, got %d", len(files), len(auths))
|
| 83 |
+
}
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
func TestUploadAuthFile_BatchMultipart_InvalidJSONDoesNotOverwriteExistingFile(t *testing.T) {
|
| 87 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 88 |
+
|
| 89 |
+
authDir := t.TempDir()
|
| 90 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 91 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 92 |
+
|
| 93 |
+
existingName := "alpha.json"
|
| 94 |
+
existingContent := `{"type":"codex","email":"alpha@example.com"}`
|
| 95 |
+
if err := os.WriteFile(filepath.Join(authDir, existingName), []byte(existingContent), 0o600); err != nil {
|
| 96 |
+
t.Fatalf("failed to seed existing auth file: %v", err)
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
files := []struct {
|
| 100 |
+
name string
|
| 101 |
+
content string
|
| 102 |
+
}{
|
| 103 |
+
{name: existingName, content: `{"type":"codex"`},
|
| 104 |
+
{name: "beta.json", content: `{"type":"claude","email":"beta@example.com"}`},
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
var body bytes.Buffer
|
| 108 |
+
writer := multipart.NewWriter(&body)
|
| 109 |
+
for _, file := range files {
|
| 110 |
+
part, err := writer.CreateFormFile("file", file.name)
|
| 111 |
+
if err != nil {
|
| 112 |
+
t.Fatalf("failed to create multipart file: %v", err)
|
| 113 |
+
}
|
| 114 |
+
if _, err = part.Write([]byte(file.content)); err != nil {
|
| 115 |
+
t.Fatalf("failed to write multipart content: %v", err)
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
if err := writer.Close(); err != nil {
|
| 119 |
+
t.Fatalf("failed to close multipart writer: %v", err)
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
rec := httptest.NewRecorder()
|
| 123 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 124 |
+
req := httptest.NewRequest(http.MethodPost, "/v0/management/auth-files", &body)
|
| 125 |
+
req.Header.Set("Content-Type", writer.FormDataContentType())
|
| 126 |
+
ctx.Request = req
|
| 127 |
+
|
| 128 |
+
h.UploadAuthFile(ctx)
|
| 129 |
+
|
| 130 |
+
if rec.Code != http.StatusMultiStatus {
|
| 131 |
+
t.Fatalf("expected upload status %d, got %d with body %s", http.StatusMultiStatus, rec.Code, rec.Body.String())
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
data, err := os.ReadFile(filepath.Join(authDir, existingName))
|
| 135 |
+
if err != nil {
|
| 136 |
+
t.Fatalf("expected existing auth file to remain readable: %v", err)
|
| 137 |
+
}
|
| 138 |
+
if string(data) != existingContent {
|
| 139 |
+
t.Fatalf("expected existing auth file to remain %q, got %q", existingContent, string(data))
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
betaData, err := os.ReadFile(filepath.Join(authDir, "beta.json"))
|
| 143 |
+
if err != nil {
|
| 144 |
+
t.Fatalf("expected valid auth file to be created: %v", err)
|
| 145 |
+
}
|
| 146 |
+
if string(betaData) != files[1].content {
|
| 147 |
+
t.Fatalf("expected beta auth file content %q, got %q", files[1].content, string(betaData))
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
func TestDeleteAuthFile_BatchQuery(t *testing.T) {
|
| 152 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 153 |
+
|
| 154 |
+
authDir := t.TempDir()
|
| 155 |
+
files := []string{"alpha.json", "beta.json"}
|
| 156 |
+
for _, name := range files {
|
| 157 |
+
if err := os.WriteFile(filepath.Join(authDir, name), []byte(`{"type":"codex"}`), 0o600); err != nil {
|
| 158 |
+
t.Fatalf("failed to write auth file %s: %v", name, err)
|
| 159 |
+
}
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 163 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 164 |
+
h.tokenStore = &memoryAuthStore{}
|
| 165 |
+
|
| 166 |
+
rec := httptest.NewRecorder()
|
| 167 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 168 |
+
req := httptest.NewRequest(
|
| 169 |
+
http.MethodDelete,
|
| 170 |
+
"/v0/management/auth-files?name="+url.QueryEscape(files[0])+"&name="+url.QueryEscape(files[1]),
|
| 171 |
+
nil,
|
| 172 |
+
)
|
| 173 |
+
ctx.Request = req
|
| 174 |
+
|
| 175 |
+
h.DeleteAuthFile(ctx)
|
| 176 |
+
|
| 177 |
+
if rec.Code != http.StatusOK {
|
| 178 |
+
t.Fatalf("expected delete status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
var payload map[string]any
|
| 182 |
+
if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
|
| 183 |
+
t.Fatalf("failed to decode response: %v", err)
|
| 184 |
+
}
|
| 185 |
+
if got, ok := payload["deleted"].(float64); !ok || int(got) != len(files) {
|
| 186 |
+
t.Fatalf("expected deleted=%d, got %#v", len(files), payload["deleted"])
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
for _, name := range files {
|
| 190 |
+
if _, err := os.Stat(filepath.Join(authDir, name)); !os.IsNotExist(err) {
|
| 191 |
+
t.Fatalf("expected auth file %s to be removed, stat err: %v", name, err)
|
| 192 |
+
}
|
| 193 |
+
}
|
| 194 |
+
}
|
internal/api/handlers/management/auth_files_delete_test.go
ADDED
|
@@ -0,0 +1,172 @@
|
|
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|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/http/httptest"
|
| 8 |
+
"net/url"
|
| 9 |
+
"os"
|
| 10 |
+
"path/filepath"
|
| 11 |
+
"testing"
|
| 12 |
+
|
| 13 |
+
"github.com/gin-gonic/gin"
|
| 14 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 15 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
func TestDeleteAuthFile_UsesAuthPathFromManager(t *testing.T) {
|
| 19 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 20 |
+
|
| 21 |
+
tempDir := t.TempDir()
|
| 22 |
+
authDir := filepath.Join(tempDir, "auth")
|
| 23 |
+
externalDir := filepath.Join(tempDir, "external")
|
| 24 |
+
if errMkdirAuth := os.MkdirAll(authDir, 0o700); errMkdirAuth != nil {
|
| 25 |
+
t.Fatalf("failed to create auth dir: %v", errMkdirAuth)
|
| 26 |
+
}
|
| 27 |
+
if errMkdirExternal := os.MkdirAll(externalDir, 0o700); errMkdirExternal != nil {
|
| 28 |
+
t.Fatalf("failed to create external dir: %v", errMkdirExternal)
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
fileName := "codex-user@example.com-plus.json"
|
| 32 |
+
shadowPath := filepath.Join(authDir, fileName)
|
| 33 |
+
realPath := filepath.Join(externalDir, fileName)
|
| 34 |
+
if errWriteShadow := os.WriteFile(shadowPath, []byte(`{"type":"codex","email":"shadow@example.com"}`), 0o600); errWriteShadow != nil {
|
| 35 |
+
t.Fatalf("failed to write shadow file: %v", errWriteShadow)
|
| 36 |
+
}
|
| 37 |
+
if errWriteReal := os.WriteFile(realPath, []byte(`{"type":"codex","email":"real@example.com"}`), 0o600); errWriteReal != nil {
|
| 38 |
+
t.Fatalf("failed to write real file: %v", errWriteReal)
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 42 |
+
record := &coreauth.Auth{
|
| 43 |
+
ID: "legacy/" + fileName,
|
| 44 |
+
FileName: fileName,
|
| 45 |
+
Provider: "codex",
|
| 46 |
+
Status: coreauth.StatusError,
|
| 47 |
+
Unavailable: true,
|
| 48 |
+
Attributes: map[string]string{
|
| 49 |
+
"path": realPath,
|
| 50 |
+
},
|
| 51 |
+
Metadata: map[string]any{
|
| 52 |
+
"type": "codex",
|
| 53 |
+
"email": "real@example.com",
|
| 54 |
+
},
|
| 55 |
+
}
|
| 56 |
+
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
|
| 57 |
+
t.Fatalf("failed to register auth record: %v", errRegister)
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 61 |
+
h.tokenStore = &memoryAuthStore{}
|
| 62 |
+
|
| 63 |
+
deleteRec := httptest.NewRecorder()
|
| 64 |
+
deleteCtx, _ := gin.CreateTestContext(deleteRec)
|
| 65 |
+
deleteReq := httptest.NewRequest(http.MethodDelete, "/v0/management/auth-files?name="+url.QueryEscape(fileName), nil)
|
| 66 |
+
deleteCtx.Request = deleteReq
|
| 67 |
+
h.DeleteAuthFile(deleteCtx)
|
| 68 |
+
|
| 69 |
+
if deleteRec.Code != http.StatusOK {
|
| 70 |
+
t.Fatalf("expected delete status %d, got %d with body %s", http.StatusOK, deleteRec.Code, deleteRec.Body.String())
|
| 71 |
+
}
|
| 72 |
+
if _, errStatReal := os.Stat(realPath); !os.IsNotExist(errStatReal) {
|
| 73 |
+
t.Fatalf("expected managed auth file to be removed, stat err: %v", errStatReal)
|
| 74 |
+
}
|
| 75 |
+
if _, errStatShadow := os.Stat(shadowPath); errStatShadow != nil {
|
| 76 |
+
t.Fatalf("expected shadow auth file to remain, stat err: %v", errStatShadow)
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
listRec := httptest.NewRecorder()
|
| 80 |
+
listCtx, _ := gin.CreateTestContext(listRec)
|
| 81 |
+
listReq := httptest.NewRequest(http.MethodGet, "/v0/management/auth-files", nil)
|
| 82 |
+
listCtx.Request = listReq
|
| 83 |
+
h.ListAuthFiles(listCtx)
|
| 84 |
+
|
| 85 |
+
if listRec.Code != http.StatusOK {
|
| 86 |
+
t.Fatalf("expected list status %d, got %d with body %s", http.StatusOK, listRec.Code, listRec.Body.String())
|
| 87 |
+
}
|
| 88 |
+
var listPayload map[string]any
|
| 89 |
+
if errUnmarshal := json.Unmarshal(listRec.Body.Bytes(), &listPayload); errUnmarshal != nil {
|
| 90 |
+
t.Fatalf("failed to decode list payload: %v", errUnmarshal)
|
| 91 |
+
}
|
| 92 |
+
filesRaw, ok := listPayload["files"].([]any)
|
| 93 |
+
if !ok {
|
| 94 |
+
t.Fatalf("expected files array, payload: %#v", listPayload)
|
| 95 |
+
}
|
| 96 |
+
if len(filesRaw) != 0 {
|
| 97 |
+
t.Fatalf("expected removed auth to be hidden from list, got %d entries", len(filesRaw))
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
func TestDeleteAuthFile_FallbackToAuthDirPath(t *testing.T) {
|
| 102 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 103 |
+
|
| 104 |
+
authDir := t.TempDir()
|
| 105 |
+
fileName := "fallback-user.json"
|
| 106 |
+
filePath := filepath.Join(authDir, fileName)
|
| 107 |
+
if errWrite := os.WriteFile(filePath, []byte(`{"type":"codex"}`), 0o600); errWrite != nil {
|
| 108 |
+
t.Fatalf("failed to write auth file: %v", errWrite)
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 112 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 113 |
+
h.tokenStore = &memoryAuthStore{}
|
| 114 |
+
|
| 115 |
+
deleteRec := httptest.NewRecorder()
|
| 116 |
+
deleteCtx, _ := gin.CreateTestContext(deleteRec)
|
| 117 |
+
deleteReq := httptest.NewRequest(http.MethodDelete, "/v0/management/auth-files?name="+url.QueryEscape(fileName), nil)
|
| 118 |
+
deleteCtx.Request = deleteReq
|
| 119 |
+
h.DeleteAuthFile(deleteCtx)
|
| 120 |
+
|
| 121 |
+
if deleteRec.Code != http.StatusOK {
|
| 122 |
+
t.Fatalf("expected delete status %d, got %d with body %s", http.StatusOK, deleteRec.Code, deleteRec.Body.String())
|
| 123 |
+
}
|
| 124 |
+
if _, errStat := os.Stat(filePath); !os.IsNotExist(errStat) {
|
| 125 |
+
t.Fatalf("expected auth file to be removed from auth dir, stat err: %v", errStat)
|
| 126 |
+
}
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
func TestDeleteAuthFile_RemovesRuntimeAuth(t *testing.T) {
|
| 130 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 131 |
+
|
| 132 |
+
authDir := t.TempDir()
|
| 133 |
+
fileName := "runtime-remove-user.json"
|
| 134 |
+
filePath := filepath.Join(authDir, fileName)
|
| 135 |
+
if errWrite := os.WriteFile(filePath, []byte(`{"type":"codex","email":"runtime@example.com"}`), 0o600); errWrite != nil {
|
| 136 |
+
t.Fatalf("failed to write auth file: %v", errWrite)
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 140 |
+
record := &coreauth.Auth{
|
| 141 |
+
ID: "runtime-remove-auth",
|
| 142 |
+
FileName: fileName,
|
| 143 |
+
Provider: "codex",
|
| 144 |
+
Status: coreauth.StatusActive,
|
| 145 |
+
Attributes: map[string]string{
|
| 146 |
+
"path": filePath,
|
| 147 |
+
},
|
| 148 |
+
Metadata: map[string]any{
|
| 149 |
+
"type": "codex",
|
| 150 |
+
"email": "runtime@example.com",
|
| 151 |
+
},
|
| 152 |
+
}
|
| 153 |
+
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
|
| 154 |
+
t.Fatalf("failed to register auth record: %v", errRegister)
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 158 |
+
h.tokenStore = &memoryAuthStore{}
|
| 159 |
+
|
| 160 |
+
deleteRec := httptest.NewRecorder()
|
| 161 |
+
deleteCtx, _ := gin.CreateTestContext(deleteRec)
|
| 162 |
+
deleteReq := httptest.NewRequest(http.MethodDelete, "/v0/management/auth-files?name="+url.QueryEscape(fileName), nil)
|
| 163 |
+
deleteCtx.Request = deleteReq
|
| 164 |
+
h.DeleteAuthFile(deleteCtx)
|
| 165 |
+
|
| 166 |
+
if deleteRec.Code != http.StatusOK {
|
| 167 |
+
t.Fatalf("expected delete status %d, got %d with body %s", http.StatusOK, deleteRec.Code, deleteRec.Body.String())
|
| 168 |
+
}
|
| 169 |
+
if _, ok := manager.GetByID(record.ID); ok {
|
| 170 |
+
t.Fatalf("expected runtime auth %q to be removed", record.ID)
|
| 171 |
+
}
|
| 172 |
+
}
|
internal/api/handlers/management/auth_files_download_test.go
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
"net/http/httptest"
|
| 6 |
+
"net/url"
|
| 7 |
+
"os"
|
| 8 |
+
"path/filepath"
|
| 9 |
+
"testing"
|
| 10 |
+
|
| 11 |
+
"github.com/gin-gonic/gin"
|
| 12 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
func TestDownloadAuthFile_ReturnsFile(t *testing.T) {
|
| 16 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 17 |
+
|
| 18 |
+
authDir := t.TempDir()
|
| 19 |
+
fileName := "download-user.json"
|
| 20 |
+
expected := []byte(`{"type":"codex"}`)
|
| 21 |
+
if err := os.WriteFile(filepath.Join(authDir, fileName), expected, 0o600); err != nil {
|
| 22 |
+
t.Fatalf("failed to write auth file: %v", err)
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
| 26 |
+
|
| 27 |
+
rec := httptest.NewRecorder()
|
| 28 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 29 |
+
ctx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/auth-files/download?name="+url.QueryEscape(fileName), nil)
|
| 30 |
+
h.DownloadAuthFile(ctx)
|
| 31 |
+
|
| 32 |
+
if rec.Code != http.StatusOK {
|
| 33 |
+
t.Fatalf("expected download status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
| 34 |
+
}
|
| 35 |
+
if got := rec.Body.Bytes(); string(got) != string(expected) {
|
| 36 |
+
t.Fatalf("unexpected download content: %q", string(got))
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
func TestDownloadAuthFile_RejectsPathSeparators(t *testing.T) {
|
| 41 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 42 |
+
|
| 43 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, nil)
|
| 44 |
+
|
| 45 |
+
for _, name := range []string{
|
| 46 |
+
"../external/secret.json",
|
| 47 |
+
`..\\external\\secret.json`,
|
| 48 |
+
"nested/secret.json",
|
| 49 |
+
`nested\\secret.json`,
|
| 50 |
+
} {
|
| 51 |
+
rec := httptest.NewRecorder()
|
| 52 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 53 |
+
ctx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/auth-files/download?name="+url.QueryEscape(name), nil)
|
| 54 |
+
h.DownloadAuthFile(ctx)
|
| 55 |
+
|
| 56 |
+
if rec.Code != http.StatusBadRequest {
|
| 57 |
+
t.Fatalf("expected %d for name %q, got %d with body %s", http.StatusBadRequest, name, rec.Code, rec.Body.String())
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
}
|
internal/api/handlers/management/auth_files_download_windows_test.go
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//go:build windows
|
| 2 |
+
|
| 3 |
+
package management
|
| 4 |
+
|
| 5 |
+
import (
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/http/httptest"
|
| 8 |
+
"net/url"
|
| 9 |
+
"os"
|
| 10 |
+
"path/filepath"
|
| 11 |
+
"testing"
|
| 12 |
+
|
| 13 |
+
"github.com/gin-gonic/gin"
|
| 14 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
func TestDownloadAuthFile_PreventsWindowsSlashTraversal(t *testing.T) {
|
| 18 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 19 |
+
|
| 20 |
+
tempDir := t.TempDir()
|
| 21 |
+
authDir := filepath.Join(tempDir, "auth")
|
| 22 |
+
externalDir := filepath.Join(tempDir, "external")
|
| 23 |
+
if err := os.MkdirAll(authDir, 0o700); err != nil {
|
| 24 |
+
t.Fatalf("failed to create auth dir: %v", err)
|
| 25 |
+
}
|
| 26 |
+
if err := os.MkdirAll(externalDir, 0o700); err != nil {
|
| 27 |
+
t.Fatalf("failed to create external dir: %v", err)
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
secretName := "secret.json"
|
| 31 |
+
secretPath := filepath.Join(externalDir, secretName)
|
| 32 |
+
if err := os.WriteFile(secretPath, []byte(`{"secret":true}`), 0o600); err != nil {
|
| 33 |
+
t.Fatalf("failed to write external file: %v", err)
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
| 37 |
+
|
| 38 |
+
rec := httptest.NewRecorder()
|
| 39 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 40 |
+
ctx.Request = httptest.NewRequest(
|
| 41 |
+
http.MethodGet,
|
| 42 |
+
"/v0/management/auth-files/download?name="+url.QueryEscape("../external/"+secretName),
|
| 43 |
+
nil,
|
| 44 |
+
)
|
| 45 |
+
h.DownloadAuthFile(ctx)
|
| 46 |
+
|
| 47 |
+
if rec.Code != http.StatusBadRequest {
|
| 48 |
+
t.Fatalf("expected status %d, got %d with body %s", http.StatusBadRequest, rec.Code, rec.Body.String())
|
| 49 |
+
}
|
| 50 |
+
}
|
internal/api/handlers/management/auth_files_filter_test.go
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/http/httptest"
|
| 8 |
+
"os"
|
| 9 |
+
"path/filepath"
|
| 10 |
+
"strings"
|
| 11 |
+
"sync"
|
| 12 |
+
"testing"
|
| 13 |
+
|
| 14 |
+
"github.com/gin-gonic/gin"
|
| 15 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 16 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
func TestListAuthFilesFiltersByNameAndAuthIndex(t *testing.T) {
|
| 20 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 21 |
+
|
| 22 |
+
authDir := t.TempDir()
|
| 23 |
+
fileName := "shared-codex.json"
|
| 24 |
+
filePath := filepath.Join(authDir, fileName)
|
| 25 |
+
if errWrite := os.WriteFile(filePath, []byte(`{"type":"codex"}`), 0o600); errWrite != nil {
|
| 26 |
+
t.Fatalf("failed to write auth file: %v", errWrite)
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 30 |
+
registerAuthForLookupTest(t, manager, &coreauth.Auth{
|
| 31 |
+
ID: "auth-a",
|
| 32 |
+
Index: "idx-a",
|
| 33 |
+
FileName: fileName,
|
| 34 |
+
Provider: "codex",
|
| 35 |
+
Status: coreauth.StatusActive,
|
| 36 |
+
Attributes: map[string]string{
|
| 37 |
+
"path": filePath,
|
| 38 |
+
},
|
| 39 |
+
})
|
| 40 |
+
registerAuthForLookupTest(t, manager, &coreauth.Auth{
|
| 41 |
+
ID: "auth-b",
|
| 42 |
+
Index: "idx-b",
|
| 43 |
+
FileName: fileName,
|
| 44 |
+
Provider: "codex",
|
| 45 |
+
Status: coreauth.StatusActive,
|
| 46 |
+
Attributes: map[string]string{
|
| 47 |
+
"path": filePath,
|
| 48 |
+
},
|
| 49 |
+
})
|
| 50 |
+
|
| 51 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 52 |
+
rec := httptest.NewRecorder()
|
| 53 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 54 |
+
req := httptest.NewRequest(http.MethodGet, "/v0/management/auth-files?name=shared-codex.json&auth_index=idx-b", nil)
|
| 55 |
+
ctx.Request = req
|
| 56 |
+
|
| 57 |
+
h.ListAuthFiles(ctx)
|
| 58 |
+
|
| 59 |
+
if rec.Code != http.StatusOK {
|
| 60 |
+
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 61 |
+
}
|
| 62 |
+
var payload struct {
|
| 63 |
+
Files []map[string]any `json:"files"`
|
| 64 |
+
}
|
| 65 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &payload); errDecode != nil {
|
| 66 |
+
t.Fatalf("decode response: %v", errDecode)
|
| 67 |
+
}
|
| 68 |
+
if len(payload.Files) != 1 {
|
| 69 |
+
t.Fatalf("files len = %d, want 1 payload=%s", len(payload.Files), rec.Body.String())
|
| 70 |
+
}
|
| 71 |
+
if got := payload.Files[0]["id"]; got != "auth-b" {
|
| 72 |
+
t.Fatalf("id = %#v, want auth-b", got)
|
| 73 |
+
}
|
| 74 |
+
if got := payload.Files[0]["auth_index"]; got != "idx-b" {
|
| 75 |
+
t.Fatalf("auth_index = %#v, want idx-b", got)
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
func TestListAuthFilesFromDiskFiltersByNameAndRejectsAuthIndex(t *testing.T) {
|
| 80 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 81 |
+
|
| 82 |
+
authDir := t.TempDir()
|
| 83 |
+
for _, file := range []struct {
|
| 84 |
+
name string
|
| 85 |
+
body string
|
| 86 |
+
}{
|
| 87 |
+
{name: "alpha.json", body: `{"type":"codex","email":"alpha@example.com"}`},
|
| 88 |
+
{name: "beta.json", body: `{"type":"codex","email":"beta@example.com"}`},
|
| 89 |
+
} {
|
| 90 |
+
if errWrite := os.WriteFile(filepath.Join(authDir, file.name), []byte(file.body), 0o600); errWrite != nil {
|
| 91 |
+
t.Fatalf("failed to write auth file %s: %v", file.name, errWrite)
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
| 96 |
+
rec := httptest.NewRecorder()
|
| 97 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 98 |
+
ctx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/auth-files?name=beta.json", nil)
|
| 99 |
+
|
| 100 |
+
h.ListAuthFiles(ctx)
|
| 101 |
+
|
| 102 |
+
if rec.Code != http.StatusOK {
|
| 103 |
+
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 104 |
+
}
|
| 105 |
+
var payload struct {
|
| 106 |
+
Files []map[string]any `json:"files"`
|
| 107 |
+
}
|
| 108 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &payload); errDecode != nil {
|
| 109 |
+
t.Fatalf("decode response: %v", errDecode)
|
| 110 |
+
}
|
| 111 |
+
if len(payload.Files) != 1 || payload.Files[0]["name"] != "beta.json" {
|
| 112 |
+
t.Fatalf("files = %#v, want only beta.json", payload.Files)
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
rec = httptest.NewRecorder()
|
| 116 |
+
ctx, _ = gin.CreateTestContext(rec)
|
| 117 |
+
ctx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/auth-files?name=beta.json&auth_index=idx-b", nil)
|
| 118 |
+
|
| 119 |
+
h.ListAuthFiles(ctx)
|
| 120 |
+
|
| 121 |
+
if rec.Code != http.StatusOK {
|
| 122 |
+
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 123 |
+
}
|
| 124 |
+
payload.Files = nil
|
| 125 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &payload); errDecode != nil {
|
| 126 |
+
t.Fatalf("decode auth_index response: %v", errDecode)
|
| 127 |
+
}
|
| 128 |
+
if len(payload.Files) != 0 {
|
| 129 |
+
t.Fatalf("files = %#v, want no disk fallback matches for auth_index", payload.Files)
|
| 130 |
+
}
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
func TestPatchAuthFileStatusVerifiesAuthIndex(t *testing.T) {
|
| 134 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 135 |
+
|
| 136 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 137 |
+
registerAuthForLookupTest(t, manager, &coreauth.Auth{
|
| 138 |
+
ID: "auth-a",
|
| 139 |
+
Index: "idx-a",
|
| 140 |
+
FileName: "shared-codex.json",
|
| 141 |
+
Provider: "codex",
|
| 142 |
+
Status: coreauth.StatusActive,
|
| 143 |
+
})
|
| 144 |
+
registerAuthForLookupTest(t, manager, &coreauth.Auth{
|
| 145 |
+
ID: "auth-b",
|
| 146 |
+
Index: "idx-b",
|
| 147 |
+
FileName: "shared-codex.json",
|
| 148 |
+
Provider: "codex",
|
| 149 |
+
Status: coreauth.StatusActive,
|
| 150 |
+
})
|
| 151 |
+
|
| 152 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
| 153 |
+
rec := httptest.NewRecorder()
|
| 154 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 155 |
+
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/status", strings.NewReader(`{"name":"shared-codex.json","auth_index":"idx-b","disabled":true}`))
|
| 156 |
+
req.Header.Set("Content-Type", "application/json")
|
| 157 |
+
ctx.Request = req
|
| 158 |
+
|
| 159 |
+
h.PatchAuthFileStatus(ctx)
|
| 160 |
+
|
| 161 |
+
if rec.Code != http.StatusOK {
|
| 162 |
+
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 163 |
+
}
|
| 164 |
+
authA, okA := manager.GetByID("auth-a")
|
| 165 |
+
authB, okB := manager.GetByID("auth-b")
|
| 166 |
+
if !okA || !okB {
|
| 167 |
+
t.Fatalf("expected both auth records to exist")
|
| 168 |
+
}
|
| 169 |
+
if authA.Disabled || authA.Status == coreauth.StatusDisabled {
|
| 170 |
+
t.Fatalf("auth-a was modified: %+v", authA)
|
| 171 |
+
}
|
| 172 |
+
if !authB.Disabled || authB.Status != coreauth.StatusDisabled {
|
| 173 |
+
t.Fatalf("auth-b was not disabled: %+v", authB)
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
func TestPatchAuthFileStatusRejectsMismatchedAuthIndex(t *testing.T) {
|
| 178 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 179 |
+
|
| 180 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 181 |
+
registerAuthForLookupTest(t, manager, &coreauth.Auth{
|
| 182 |
+
ID: "auth-a",
|
| 183 |
+
Index: "idx-a",
|
| 184 |
+
FileName: "shared-codex.json",
|
| 185 |
+
Provider: "codex",
|
| 186 |
+
Status: coreauth.StatusActive,
|
| 187 |
+
})
|
| 188 |
+
|
| 189 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
| 190 |
+
rec := httptest.NewRecorder()
|
| 191 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 192 |
+
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/status", strings.NewReader(`{"name":"shared-codex.json","auth_index":"idx-missing","disabled":true}`))
|
| 193 |
+
req.Header.Set("Content-Type", "application/json")
|
| 194 |
+
ctx.Request = req
|
| 195 |
+
|
| 196 |
+
h.PatchAuthFileStatus(ctx)
|
| 197 |
+
|
| 198 |
+
if rec.Code != http.StatusNotFound {
|
| 199 |
+
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusNotFound, rec.Body.String())
|
| 200 |
+
}
|
| 201 |
+
authA, ok := manager.GetByID("auth-a")
|
| 202 |
+
if !ok {
|
| 203 |
+
t.Fatalf("expected auth-a to exist")
|
| 204 |
+
}
|
| 205 |
+
if authA.Disabled || authA.Status == coreauth.StatusDisabled {
|
| 206 |
+
t.Fatalf("auth-a was modified: %+v", authA)
|
| 207 |
+
}
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
func TestAuthFileLookupAndEntryBuildConcurrentEnsureIndex(t *testing.T) {
|
| 211 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 212 |
+
|
| 213 |
+
authDir := t.TempDir()
|
| 214 |
+
fileName := "concurrent-codex.json"
|
| 215 |
+
filePath := filepath.Join(authDir, fileName)
|
| 216 |
+
if errWrite := os.WriteFile(filePath, []byte(`{"type":"codex"}`), 0o600); errWrite != nil {
|
| 217 |
+
t.Fatalf("failed to write auth file: %v", errWrite)
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
| 221 |
+
auth := &coreauth.Auth{
|
| 222 |
+
ID: "auth-concurrent",
|
| 223 |
+
Index: "idx-concurrent",
|
| 224 |
+
FileName: fileName,
|
| 225 |
+
Provider: "codex",
|
| 226 |
+
Status: coreauth.StatusActive,
|
| 227 |
+
Attributes: map[string]string{
|
| 228 |
+
"path": filePath,
|
| 229 |
+
},
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
var wg sync.WaitGroup
|
| 233 |
+
for i := 0; i < 32; i++ {
|
| 234 |
+
wg.Add(1)
|
| 235 |
+
go func() {
|
| 236 |
+
defer wg.Done()
|
| 237 |
+
for j := 0; j < 100; j++ {
|
| 238 |
+
if !matchesAuthFileLookup(auth, fileName, "idx-concurrent") {
|
| 239 |
+
t.Errorf("auth lookup did not match")
|
| 240 |
+
}
|
| 241 |
+
entry := h.buildAuthFileEntry(auth)
|
| 242 |
+
if entry == nil {
|
| 243 |
+
t.Errorf("entry is nil")
|
| 244 |
+
continue
|
| 245 |
+
}
|
| 246 |
+
if got := entry["auth_index"]; got != "idx-concurrent" {
|
| 247 |
+
t.Errorf("auth_index = %#v, want idx-concurrent", got)
|
| 248 |
+
}
|
| 249 |
+
}
|
| 250 |
+
}()
|
| 251 |
+
}
|
| 252 |
+
wg.Wait()
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
func registerAuthForLookupTest(t *testing.T, manager *coreauth.Manager, auth *coreauth.Auth) {
|
| 256 |
+
t.Helper()
|
| 257 |
+
if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil {
|
| 258 |
+
t.Fatalf("register auth %q: %v", auth.ID, errRegister)
|
| 259 |
+
}
|
| 260 |
+
}
|
internal/api/handlers/management/auth_files_patch_fields_test.go
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/http/httptest"
|
| 8 |
+
"os"
|
| 9 |
+
"path/filepath"
|
| 10 |
+
"strings"
|
| 11 |
+
"testing"
|
| 12 |
+
|
| 13 |
+
"github.com/gin-gonic/gin"
|
| 14 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 15 |
+
fileauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
| 16 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
func TestPatchAuthFileFields_MergeHeadersAndDeleteEmptyValues(t *testing.T) {
|
| 20 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 21 |
+
|
| 22 |
+
store := &memoryAuthStore{}
|
| 23 |
+
manager := coreauth.NewManager(store, nil, nil)
|
| 24 |
+
record := &coreauth.Auth{
|
| 25 |
+
ID: "test.json",
|
| 26 |
+
FileName: "test.json",
|
| 27 |
+
Provider: "claude",
|
| 28 |
+
Attributes: map[string]string{
|
| 29 |
+
"path": "/tmp/test.json",
|
| 30 |
+
"header:X-Old": "old",
|
| 31 |
+
"header:X-Remove": "gone",
|
| 32 |
+
},
|
| 33 |
+
Metadata: map[string]any{
|
| 34 |
+
"type": "claude",
|
| 35 |
+
"headers": map[string]any{
|
| 36 |
+
"X-Old": "old",
|
| 37 |
+
"X-Remove": "gone",
|
| 38 |
+
},
|
| 39 |
+
},
|
| 40 |
+
}
|
| 41 |
+
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
|
| 42 |
+
t.Fatalf("failed to register auth record: %v", errRegister)
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
| 46 |
+
|
| 47 |
+
body := `{"name":"test.json","prefix":"p1","proxy_url":"http://proxy.local","headers":{"X-Old":"new","X-New":"v","X-Remove":" ","X-Nope":""}}`
|
| 48 |
+
rec := httptest.NewRecorder()
|
| 49 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 50 |
+
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/fields", strings.NewReader(body))
|
| 51 |
+
req.Header.Set("Content-Type", "application/json")
|
| 52 |
+
ctx.Request = req
|
| 53 |
+
h.PatchAuthFileFields(ctx)
|
| 54 |
+
|
| 55 |
+
if rec.Code != http.StatusOK {
|
| 56 |
+
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
updated, ok := manager.GetByID("test.json")
|
| 60 |
+
if !ok || updated == nil {
|
| 61 |
+
t.Fatalf("expected auth record to exist after patch")
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
if updated.Prefix != "p1" {
|
| 65 |
+
t.Fatalf("prefix = %q, want %q", updated.Prefix, "p1")
|
| 66 |
+
}
|
| 67 |
+
if updated.ProxyURL != "http://proxy.local" {
|
| 68 |
+
t.Fatalf("proxy_url = %q, want %q", updated.ProxyURL, "http://proxy.local")
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
if updated.Metadata == nil {
|
| 72 |
+
t.Fatalf("expected metadata to be non-nil")
|
| 73 |
+
}
|
| 74 |
+
if got, _ := updated.Metadata["prefix"].(string); got != "p1" {
|
| 75 |
+
t.Fatalf("metadata.prefix = %q, want %q", got, "p1")
|
| 76 |
+
}
|
| 77 |
+
if got, _ := updated.Metadata["proxy_url"].(string); got != "http://proxy.local" {
|
| 78 |
+
t.Fatalf("metadata.proxy_url = %q, want %q", got, "http://proxy.local")
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
headersMeta, ok := updated.Metadata["headers"].(map[string]any)
|
| 82 |
+
if !ok {
|
| 83 |
+
raw, _ := json.Marshal(updated.Metadata["headers"])
|
| 84 |
+
t.Fatalf("metadata.headers = %T (%s), want map[string]any", updated.Metadata["headers"], string(raw))
|
| 85 |
+
}
|
| 86 |
+
if got := headersMeta["X-Old"]; got != "new" {
|
| 87 |
+
t.Fatalf("metadata.headers.X-Old = %#v, want %q", got, "new")
|
| 88 |
+
}
|
| 89 |
+
if got := headersMeta["X-New"]; got != "v" {
|
| 90 |
+
t.Fatalf("metadata.headers.X-New = %#v, want %q", got, "v")
|
| 91 |
+
}
|
| 92 |
+
if _, ok := headersMeta["X-Remove"]; ok {
|
| 93 |
+
t.Fatalf("expected metadata.headers.X-Remove to be deleted")
|
| 94 |
+
}
|
| 95 |
+
if _, ok := headersMeta["X-Nope"]; ok {
|
| 96 |
+
t.Fatalf("expected metadata.headers.X-Nope to be absent")
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
if got := updated.Attributes["header:X-Old"]; got != "new" {
|
| 100 |
+
t.Fatalf("attrs header:X-Old = %q, want %q", got, "new")
|
| 101 |
+
}
|
| 102 |
+
if got := updated.Attributes["header:X-New"]; got != "v" {
|
| 103 |
+
t.Fatalf("attrs header:X-New = %q, want %q", got, "v")
|
| 104 |
+
}
|
| 105 |
+
if _, ok := updated.Attributes["header:X-Remove"]; ok {
|
| 106 |
+
t.Fatalf("expected attrs header:X-Remove to be deleted")
|
| 107 |
+
}
|
| 108 |
+
if _, ok := updated.Attributes["header:X-Nope"]; ok {
|
| 109 |
+
t.Fatalf("expected attrs header:X-Nope to be absent")
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
func TestPatchAuthFileFields_HeadersEmptyMapIsNoop(t *testing.T) {
|
| 114 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 115 |
+
|
| 116 |
+
store := &memoryAuthStore{}
|
| 117 |
+
manager := coreauth.NewManager(store, nil, nil)
|
| 118 |
+
record := &coreauth.Auth{
|
| 119 |
+
ID: "noop.json",
|
| 120 |
+
FileName: "noop.json",
|
| 121 |
+
Provider: "claude",
|
| 122 |
+
Attributes: map[string]string{
|
| 123 |
+
"path": "/tmp/noop.json",
|
| 124 |
+
"header:X-Kee": "1",
|
| 125 |
+
},
|
| 126 |
+
Metadata: map[string]any{
|
| 127 |
+
"type": "claude",
|
| 128 |
+
"headers": map[string]any{
|
| 129 |
+
"X-Kee": "1",
|
| 130 |
+
},
|
| 131 |
+
},
|
| 132 |
+
}
|
| 133 |
+
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
|
| 134 |
+
t.Fatalf("failed to register auth record: %v", errRegister)
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
| 138 |
+
|
| 139 |
+
body := `{"name":"noop.json","note":"hello","headers":{}}`
|
| 140 |
+
rec := httptest.NewRecorder()
|
| 141 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 142 |
+
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/fields", strings.NewReader(body))
|
| 143 |
+
req.Header.Set("Content-Type", "application/json")
|
| 144 |
+
ctx.Request = req
|
| 145 |
+
h.PatchAuthFileFields(ctx)
|
| 146 |
+
|
| 147 |
+
if rec.Code != http.StatusOK {
|
| 148 |
+
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
updated, ok := manager.GetByID("noop.json")
|
| 152 |
+
if !ok || updated == nil {
|
| 153 |
+
t.Fatalf("expected auth record to exist after patch")
|
| 154 |
+
}
|
| 155 |
+
if got := updated.Attributes["header:X-Kee"]; got != "1" {
|
| 156 |
+
t.Fatalf("attrs header:X-Kee = %q, want %q", got, "1")
|
| 157 |
+
}
|
| 158 |
+
headersMeta, ok := updated.Metadata["headers"].(map[string]any)
|
| 159 |
+
if !ok {
|
| 160 |
+
t.Fatalf("expected metadata.headers to remain a map, got %T", updated.Metadata["headers"])
|
| 161 |
+
}
|
| 162 |
+
if got := headersMeta["X-Kee"]; got != "1" {
|
| 163 |
+
t.Fatalf("metadata.headers.X-Kee = %#v, want %q", got, "1")
|
| 164 |
+
}
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
func TestPatchAuthFileFields_WebsocketsFalseIsUpdate(t *testing.T) {
|
| 168 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 169 |
+
|
| 170 |
+
store := &memoryAuthStore{}
|
| 171 |
+
manager := coreauth.NewManager(store, nil, nil)
|
| 172 |
+
record := &coreauth.Auth{
|
| 173 |
+
ID: "codex.json",
|
| 174 |
+
FileName: "codex.json",
|
| 175 |
+
Provider: "codex",
|
| 176 |
+
Attributes: map[string]string{
|
| 177 |
+
"path": "/tmp/codex.json",
|
| 178 |
+
"websockets": "true",
|
| 179 |
+
},
|
| 180 |
+
Metadata: map[string]any{
|
| 181 |
+
"type": "codex",
|
| 182 |
+
"websockets": true,
|
| 183 |
+
},
|
| 184 |
+
}
|
| 185 |
+
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
|
| 186 |
+
t.Fatalf("failed to register auth record: %v", errRegister)
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
| 190 |
+
|
| 191 |
+
body := `{"name":"codex.json","websockets":false}`
|
| 192 |
+
rec := httptest.NewRecorder()
|
| 193 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 194 |
+
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/fields", strings.NewReader(body))
|
| 195 |
+
req.Header.Set("Content-Type", "application/json")
|
| 196 |
+
ctx.Request = req
|
| 197 |
+
h.PatchAuthFileFields(ctx)
|
| 198 |
+
|
| 199 |
+
if rec.Code != http.StatusOK {
|
| 200 |
+
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
updated, ok := manager.GetByID("codex.json")
|
| 204 |
+
if !ok || updated == nil {
|
| 205 |
+
t.Fatalf("expected auth record to exist after patch")
|
| 206 |
+
}
|
| 207 |
+
if got := updated.Attributes["websockets"]; got != "false" {
|
| 208 |
+
t.Fatalf("attrs websockets = %q, want %q", got, "false")
|
| 209 |
+
}
|
| 210 |
+
if got, ok := updated.Metadata["websockets"].(bool); !ok || got {
|
| 211 |
+
t.Fatalf("metadata.websockets = %#v, want false", updated.Metadata["websockets"])
|
| 212 |
+
}
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
func TestPatchAuthFileFields_ArbitraryFieldsPersistToFile(t *testing.T) {
|
| 216 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 217 |
+
|
| 218 |
+
authDir := t.TempDir()
|
| 219 |
+
fileName := "generic.json"
|
| 220 |
+
filePath := filepath.Join(authDir, fileName)
|
| 221 |
+
store := fileauth.NewFileTokenStore()
|
| 222 |
+
store.SetBaseDir(authDir)
|
| 223 |
+
manager := coreauth.NewManager(store, nil, nil)
|
| 224 |
+
record := &coreauth.Auth{
|
| 225 |
+
ID: fileName,
|
| 226 |
+
FileName: fileName,
|
| 227 |
+
Provider: "codex",
|
| 228 |
+
Attributes: map[string]string{
|
| 229 |
+
"path": filePath,
|
| 230 |
+
},
|
| 231 |
+
Metadata: map[string]any{
|
| 232 |
+
"type": "codex",
|
| 233 |
+
},
|
| 234 |
+
}
|
| 235 |
+
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
|
| 236 |
+
t.Fatalf("failed to register auth record: %v", errRegister)
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 240 |
+
|
| 241 |
+
body := `{"name":"generic.json","abc":true,"nested.cde":true,"fgh":{"ijk":true}}`
|
| 242 |
+
rec := httptest.NewRecorder()
|
| 243 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 244 |
+
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/fields", strings.NewReader(body))
|
| 245 |
+
req.Header.Set("Content-Type", "application/json")
|
| 246 |
+
ctx.Request = req
|
| 247 |
+
h.PatchAuthFileFields(ctx)
|
| 248 |
+
|
| 249 |
+
if rec.Code != http.StatusOK {
|
| 250 |
+
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
raw, errRead := os.ReadFile(filePath)
|
| 254 |
+
if errRead != nil {
|
| 255 |
+
t.Fatalf("failed to read updated auth file: %v", errRead)
|
| 256 |
+
}
|
| 257 |
+
var data map[string]any
|
| 258 |
+
if errUnmarshal := json.Unmarshal(raw, &data); errUnmarshal != nil {
|
| 259 |
+
t.Fatalf("failed to unmarshal updated auth file: %v", errUnmarshal)
|
| 260 |
+
}
|
| 261 |
+
if got := data["abc"]; got != true {
|
| 262 |
+
t.Fatalf("abc = %#v, want true", got)
|
| 263 |
+
}
|
| 264 |
+
nested, ok := data["nested"].(map[string]any)
|
| 265 |
+
if !ok {
|
| 266 |
+
t.Fatalf("nested = %#v, want object", data["nested"])
|
| 267 |
+
}
|
| 268 |
+
if got := nested["cde"]; got != true {
|
| 269 |
+
t.Fatalf("nested.cde = %#v, want true", got)
|
| 270 |
+
}
|
| 271 |
+
fgh, ok := data["fgh"].(map[string]any)
|
| 272 |
+
if !ok {
|
| 273 |
+
t.Fatalf("fgh = %#v, want object", data["fgh"])
|
| 274 |
+
}
|
| 275 |
+
if got := fgh["ijk"]; got != true {
|
| 276 |
+
t.Fatalf("fgh.ijk = %#v, want true", got)
|
| 277 |
+
}
|
| 278 |
+
}
|
internal/api/handlers/management/auth_files_plugin_oauth_test.go
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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/http/httptest"
|
| 8 |
+
"net/url"
|
| 9 |
+
"os"
|
| 10 |
+
"path/filepath"
|
| 11 |
+
"strings"
|
| 12 |
+
"testing"
|
| 13 |
+
|
| 14 |
+
"github.com/gin-gonic/gin"
|
| 15 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 16 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
|
| 17 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 18 |
+
"github.com/router-for-me/CLIProxyAPI/v7/sdk/pluginapi"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
func TestPluginLoginPollAuthsExpandsMultipleAuths(t *testing.T) {
|
| 22 |
+
host := pluginhost.New()
|
| 23 |
+
resp := pluginapi.AuthLoginPollResponse{
|
| 24 |
+
Status: pluginapi.AuthLoginStatusSuccess,
|
| 25 |
+
Auths: []pluginapi.AuthData{
|
| 26 |
+
{
|
| 27 |
+
Provider: "gemini-cli",
|
| 28 |
+
ID: "geminicli.json",
|
| 29 |
+
FileName: "geminicli.json",
|
| 30 |
+
StorageJSON: []byte(`{"type":"gemini-cli"}`),
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
Provider: "gemini-cli",
|
| 34 |
+
ID: "geminicli-project-a.json",
|
| 35 |
+
FileName: "geminicli-project-a.json",
|
| 36 |
+
StorageJSON: []byte(`{"type":"gemini-cli","project_id":"project-a"}`),
|
| 37 |
+
Metadata: map[string]any{"project_id": "project-a"},
|
| 38 |
+
},
|
| 39 |
+
},
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
records := pluginLoginPollAuths(host, resp)
|
| 43 |
+
if len(records) != 2 {
|
| 44 |
+
t.Fatalf("pluginLoginPollAuths() len = %d, want two records", len(records))
|
| 45 |
+
}
|
| 46 |
+
if records[0].ID != "geminicli.json" || records[1].ID != "geminicli-project-a.json" {
|
| 47 |
+
t.Fatalf("records = %#v, want both plugin auths", records)
|
| 48 |
+
}
|
| 49 |
+
if gotProject := records[1].Metadata["project_id"]; gotProject != "project-a" {
|
| 50 |
+
t.Fatalf("project_id = %#v, want project-a", gotProject)
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
func TestSavePluginLoginRecordsRollsBackSavedAuthsOnFailure(t *testing.T) {
|
| 55 |
+
store := &pluginLoginRollbackStore{failAt: 2}
|
| 56 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, nil)
|
| 57 |
+
h.tokenStore = store
|
| 58 |
+
|
| 59 |
+
records := []*coreauth.Auth{
|
| 60 |
+
{
|
| 61 |
+
ID: "geminicli.json",
|
| 62 |
+
FileName: "geminicli.json",
|
| 63 |
+
Provider: "gemini-cli",
|
| 64 |
+
Metadata: map[string]any{"type": "gemini-cli"},
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
ID: "geminicli-project-a.json",
|
| 68 |
+
FileName: "geminicli-project-a.json",
|
| 69 |
+
Provider: "gemini-cli",
|
| 70 |
+
Metadata: map[string]any{"type": "gemini-cli", "project_id": "project-a"},
|
| 71 |
+
},
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
errSave := h.savePluginLoginRecords(context.Background(), records)
|
| 75 |
+
if errSave == nil {
|
| 76 |
+
t.Fatal("savePluginLoginRecords() error = nil, want rollback-triggering error")
|
| 77 |
+
}
|
| 78 |
+
if len(store.saved) != 2 {
|
| 79 |
+
t.Fatalf("saved len = %d, want two attempted saves", len(store.saved))
|
| 80 |
+
}
|
| 81 |
+
if !store.deleted["geminicli.json"] || !store.deleted["geminicli-project-a.json"] {
|
| 82 |
+
t.Fatalf("deleted = %#v, want both saved auths rolled back", store.deleted)
|
| 83 |
+
}
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
func TestPatchPluginVirtualAuthStatusReturnsConflictForVirtualChild(t *testing.T) {
|
| 87 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 88 |
+
auth := pluginVirtualAuthForTest(t.TempDir(), "source.json", "auth-1")
|
| 89 |
+
if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil {
|
| 90 |
+
t.Fatalf("register virtual auth: %v", errRegister)
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
| 94 |
+
rec := httptest.NewRecorder()
|
| 95 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 96 |
+
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/status", strings.NewReader(`{"name":"auth-1","disabled":true}`))
|
| 97 |
+
req.Header.Set("Content-Type", "application/json")
|
| 98 |
+
ctx.Request = req
|
| 99 |
+
|
| 100 |
+
h.PatchAuthFileStatus(ctx)
|
| 101 |
+
|
| 102 |
+
if rec.Code != http.StatusConflict {
|
| 103 |
+
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusConflict, rec.Body.String())
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
func TestPatchPluginVirtualSourceStatusDisablesAllExpandedAuths(t *testing.T) {
|
| 108 |
+
authDir := t.TempDir()
|
| 109 |
+
fileName := "source.json"
|
| 110 |
+
filePath := filepath.Join(authDir, fileName)
|
| 111 |
+
if errWrite := os.WriteFile(filePath, []byte(`{"type":"gemini-cli","disabled":false}`), 0o600); errWrite != nil {
|
| 112 |
+
t.Fatalf("write source auth file: %v", errWrite)
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 116 |
+
for _, id := range []string{"source.json", "virtual-project-a"} {
|
| 117 |
+
auth := pluginVirtualAuthForTest(authDir, fileName, id)
|
| 118 |
+
if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil {
|
| 119 |
+
t.Fatalf("register virtual auth %s: %v", id, errRegister)
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 124 |
+
rec := httptest.NewRecorder()
|
| 125 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 126 |
+
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/status", strings.NewReader(`{"name":"source.json","disabled":true}`))
|
| 127 |
+
req.Header.Set("Content-Type", "application/json")
|
| 128 |
+
ctx.Request = req
|
| 129 |
+
|
| 130 |
+
h.PatchAuthFileStatus(ctx)
|
| 131 |
+
|
| 132 |
+
if rec.Code != http.StatusOK {
|
| 133 |
+
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 134 |
+
}
|
| 135 |
+
raw, errRead := os.ReadFile(filePath)
|
| 136 |
+
if errRead != nil {
|
| 137 |
+
t.Fatalf("read source auth file: %v", errRead)
|
| 138 |
+
}
|
| 139 |
+
if !strings.Contains(string(raw), `"disabled":true`) {
|
| 140 |
+
t.Fatalf("source auth file = %s, want disabled:true", string(raw))
|
| 141 |
+
}
|
| 142 |
+
for _, id := range []string{"source.json", "virtual-project-a"} {
|
| 143 |
+
auth, ok := manager.GetByID(id)
|
| 144 |
+
if !ok || auth == nil {
|
| 145 |
+
t.Fatalf("expected auth %s to remain registered", id)
|
| 146 |
+
}
|
| 147 |
+
if !auth.Disabled || auth.Status != coreauth.StatusDisabled {
|
| 148 |
+
t.Fatalf("auth %s disabled/status = %v/%s, want disabled", id, auth.Disabled, auth.Status)
|
| 149 |
+
}
|
| 150 |
+
}
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
func TestPatchPluginVirtualAuthFieldsReturnsConflict(t *testing.T) {
|
| 154 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 155 |
+
auth := pluginVirtualAuthForTest(t.TempDir(), "source.json", "auth-1")
|
| 156 |
+
if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil {
|
| 157 |
+
t.Fatalf("register virtual auth: %v", errRegister)
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
| 161 |
+
rec := httptest.NewRecorder()
|
| 162 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 163 |
+
req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/fields", strings.NewReader(`{"name":"auth-1","note":"hello"}`))
|
| 164 |
+
req.Header.Set("Content-Type", "application/json")
|
| 165 |
+
ctx.Request = req
|
| 166 |
+
|
| 167 |
+
h.PatchAuthFileFields(ctx)
|
| 168 |
+
|
| 169 |
+
if rec.Code != http.StatusConflict {
|
| 170 |
+
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusConflict, rec.Body.String())
|
| 171 |
+
}
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
func TestDeletePluginVirtualSourceRemovesExpandedRuntimeAuths(t *testing.T) {
|
| 175 |
+
authDir := t.TempDir()
|
| 176 |
+
fileName := "source.json"
|
| 177 |
+
filePath := filepath.Join(authDir, fileName)
|
| 178 |
+
if errWrite := os.WriteFile(filePath, []byte(`{"type":"gemini-cli"}`), 0o600); errWrite != nil {
|
| 179 |
+
t.Fatalf("write source auth file: %v", errWrite)
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 183 |
+
for _, id := range []string{"auth-1", "auth-2"} {
|
| 184 |
+
auth := pluginVirtualAuthForTest(authDir, fileName, id)
|
| 185 |
+
if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil {
|
| 186 |
+
t.Fatalf("register virtual auth %s: %v", id, errRegister)
|
| 187 |
+
}
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 191 |
+
h.tokenStore = &memoryAuthStore{}
|
| 192 |
+
rec := httptest.NewRecorder()
|
| 193 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 194 |
+
req := httptest.NewRequest(http.MethodDelete, "/v0/management/auth-files?name="+url.QueryEscape(fileName), nil)
|
| 195 |
+
ctx.Request = req
|
| 196 |
+
|
| 197 |
+
h.DeleteAuthFile(ctx)
|
| 198 |
+
|
| 199 |
+
if rec.Code != http.StatusOK {
|
| 200 |
+
t.Fatalf("status = %d, want %d body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 201 |
+
}
|
| 202 |
+
if _, errStat := os.Stat(filePath); !os.IsNotExist(errStat) {
|
| 203 |
+
t.Fatalf("expected source auth file to be removed, stat err: %v", errStat)
|
| 204 |
+
}
|
| 205 |
+
for _, id := range []string{"auth-1", "auth-2"} {
|
| 206 |
+
if _, ok := manager.GetByID(id); ok {
|
| 207 |
+
t.Fatalf("expected virtual auth %s to be removed", id)
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
func pluginVirtualAuthForTest(authDir, fileName, id string) *coreauth.Auth {
|
| 213 |
+
filePath := filepath.Join(authDir, fileName)
|
| 214 |
+
auth := &coreauth.Auth{
|
| 215 |
+
ID: id,
|
| 216 |
+
FileName: fileName,
|
| 217 |
+
Provider: "gemini-cli",
|
| 218 |
+
Attributes: map[string]string{
|
| 219 |
+
"path": filePath,
|
| 220 |
+
},
|
| 221 |
+
Metadata: map[string]any{
|
| 222 |
+
"type": "gemini-cli",
|
| 223 |
+
},
|
| 224 |
+
}
|
| 225 |
+
coreauth.MarkPluginVirtualAuth(auth, filePath, 0)
|
| 226 |
+
return auth
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
type pluginLoginRollbackStore struct {
|
| 230 |
+
failAt int
|
| 231 |
+
saved []string
|
| 232 |
+
deleted map[string]bool
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
func (s *pluginLoginRollbackStore) List(context.Context) ([]*coreauth.Auth, error) {
|
| 236 |
+
return nil, nil
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
func (s *pluginLoginRollbackStore) Save(_ context.Context, auth *coreauth.Auth) (string, error) {
|
| 240 |
+
path := strings.TrimSpace(auth.FileName)
|
| 241 |
+
if path == "" {
|
| 242 |
+
path = strings.TrimSpace(auth.ID)
|
| 243 |
+
}
|
| 244 |
+
s.saved = append(s.saved, path)
|
| 245 |
+
if len(s.saved) == s.failAt {
|
| 246 |
+
return path, errors.New("save failed after write")
|
| 247 |
+
}
|
| 248 |
+
return path, nil
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
func (s *pluginLoginRollbackStore) Delete(_ context.Context, id string) error {
|
| 252 |
+
if s.deleted == nil {
|
| 253 |
+
s.deleted = make(map[string]bool)
|
| 254 |
+
}
|
| 255 |
+
s.deleted[id] = true
|
| 256 |
+
return nil
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
func (s *pluginLoginRollbackStore) SetBaseDir(string) {}
|
internal/api/handlers/management/auth_files_project_id_test.go
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/http/httptest"
|
| 8 |
+
"os"
|
| 9 |
+
"path/filepath"
|
| 10 |
+
"testing"
|
| 11 |
+
|
| 12 |
+
"github.com/gin-gonic/gin"
|
| 13 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 14 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
func TestListAuthFiles_IncludesProjectIDFromManager(t *testing.T) {
|
| 18 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 19 |
+
|
| 20 |
+
authDir := t.TempDir()
|
| 21 |
+
fileName := "antigravity-user@example.com-project-a.json"
|
| 22 |
+
filePath := filepath.Join(authDir, fileName)
|
| 23 |
+
if errWrite := os.WriteFile(filePath, []byte(`{"type":"antigravity","email":"user@example.com","project_id":"project-a"}`), 0o600); errWrite != nil {
|
| 24 |
+
t.Fatalf("failed to write auth file: %v", errWrite)
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 28 |
+
record := &coreauth.Auth{
|
| 29 |
+
ID: fileName,
|
| 30 |
+
FileName: fileName,
|
| 31 |
+
Provider: "antigravity",
|
| 32 |
+
Status: coreauth.StatusActive,
|
| 33 |
+
Attributes: map[string]string{
|
| 34 |
+
"path": filePath,
|
| 35 |
+
},
|
| 36 |
+
Metadata: map[string]any{
|
| 37 |
+
"type": "antigravity",
|
| 38 |
+
"email": "user@example.com",
|
| 39 |
+
"project_id": "project-a",
|
| 40 |
+
},
|
| 41 |
+
}
|
| 42 |
+
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
|
| 43 |
+
t.Fatalf("failed to register auth record: %v", errRegister)
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 47 |
+
h.tokenStore = &memoryAuthStore{}
|
| 48 |
+
|
| 49 |
+
entry := firstAuthFileEntry(t, h)
|
| 50 |
+
if got := entry["project_id"]; got != "project-a" {
|
| 51 |
+
t.Fatalf("expected project_id %q, got %#v", "project-a", got)
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
func TestListAuthFilesFromDisk_IncludesProjectID(t *testing.T) {
|
| 56 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 57 |
+
|
| 58 |
+
authDir := t.TempDir()
|
| 59 |
+
filePath := filepath.Join(authDir, "antigravity-user@example.com-project-a.json")
|
| 60 |
+
if errWrite := os.WriteFile(filePath, []byte(`{"type":"antigravity","email":"user@example.com","project_id":"project-a"}`), 0o600); errWrite != nil {
|
| 61 |
+
t.Fatalf("failed to write auth file: %v", errWrite)
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
| 65 |
+
|
| 66 |
+
entry := firstAuthFileEntry(t, h)
|
| 67 |
+
if got := entry["project_id"]; got != "project-a" {
|
| 68 |
+
t.Fatalf("expected project_id %q, got %#v", "project-a", got)
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
func TestListAuthFiles_IncludesWebsocketsFromManager(t *testing.T) {
|
| 73 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 74 |
+
|
| 75 |
+
authDir := t.TempDir()
|
| 76 |
+
fileName := "codex-user@example.com-pro.json"
|
| 77 |
+
filePath := filepath.Join(authDir, fileName)
|
| 78 |
+
if errWrite := os.WriteFile(filePath, []byte(`{"type":"codex","email":"user@example.com"}`), 0o600); errWrite != nil {
|
| 79 |
+
t.Fatalf("failed to write auth file: %v", errWrite)
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 83 |
+
record := &coreauth.Auth{
|
| 84 |
+
ID: fileName,
|
| 85 |
+
FileName: fileName,
|
| 86 |
+
Provider: "codex",
|
| 87 |
+
Status: coreauth.StatusActive,
|
| 88 |
+
Attributes: map[string]string{
|
| 89 |
+
"path": filePath,
|
| 90 |
+
"websockets": "true",
|
| 91 |
+
},
|
| 92 |
+
Metadata: map[string]any{
|
| 93 |
+
"type": "codex",
|
| 94 |
+
},
|
| 95 |
+
}
|
| 96 |
+
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
|
| 97 |
+
t.Fatalf("failed to register auth record: %v", errRegister)
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 101 |
+
h.tokenStore = &memoryAuthStore{}
|
| 102 |
+
|
| 103 |
+
entry := firstAuthFileEntry(t, h)
|
| 104 |
+
if got := entry["websockets"]; got != true {
|
| 105 |
+
t.Fatalf("expected websockets true, got %#v", got)
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
func TestListAuthFilesFromDisk_IncludesWebsockets(t *testing.T) {
|
| 110 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 111 |
+
|
| 112 |
+
authDir := t.TempDir()
|
| 113 |
+
filePath := filepath.Join(authDir, "codex-user@example.com-pro.json")
|
| 114 |
+
if errWrite := os.WriteFile(filePath, []byte(`{"type":"codex","email":"user@example.com","websockets":false}`), 0o600); errWrite != nil {
|
| 115 |
+
t.Fatalf("failed to write auth file: %v", errWrite)
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
| 119 |
+
|
| 120 |
+
entry := firstAuthFileEntry(t, h)
|
| 121 |
+
if got := entry["websockets"]; got != false {
|
| 122 |
+
t.Fatalf("expected websockets false, got %#v", got)
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
func firstAuthFileEntry(t *testing.T, h *Handler) map[string]any {
|
| 127 |
+
t.Helper()
|
| 128 |
+
|
| 129 |
+
rec := httptest.NewRecorder()
|
| 130 |
+
ginCtx, _ := gin.CreateTestContext(rec)
|
| 131 |
+
ginCtx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/auth-files", nil)
|
| 132 |
+
|
| 133 |
+
h.ListAuthFiles(ginCtx)
|
| 134 |
+
|
| 135 |
+
if rec.Code != http.StatusOK {
|
| 136 |
+
t.Fatalf("expected list status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
var payload map[string]any
|
| 140 |
+
if errUnmarshal := json.Unmarshal(rec.Body.Bytes(), &payload); errUnmarshal != nil {
|
| 141 |
+
t.Fatalf("failed to decode list payload: %v", errUnmarshal)
|
| 142 |
+
}
|
| 143 |
+
filesRaw, ok := payload["files"].([]any)
|
| 144 |
+
if !ok {
|
| 145 |
+
t.Fatalf("expected files array, payload: %#v", payload)
|
| 146 |
+
}
|
| 147 |
+
if len(filesRaw) != 1 {
|
| 148 |
+
t.Fatalf("expected 1 auth entry, got %d", len(filesRaw))
|
| 149 |
+
}
|
| 150 |
+
fileEntry, ok := filesRaw[0].(map[string]any)
|
| 151 |
+
if !ok {
|
| 152 |
+
t.Fatalf("expected file entry object, got %#v", filesRaw[0])
|
| 153 |
+
}
|
| 154 |
+
return fileEntry
|
| 155 |
+
}
|
internal/api/handlers/management/auth_files_recent_requests_test.go
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/http/httptest"
|
| 8 |
+
"testing"
|
| 9 |
+
|
| 10 |
+
"github.com/gin-gonic/gin"
|
| 11 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 12 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
func TestListAuthFiles_IncludesRecentRequestsBuckets(t *testing.T) {
|
| 16 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 17 |
+
|
| 18 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 19 |
+
record := &coreauth.Auth{
|
| 20 |
+
ID: "runtime-only-auth-1",
|
| 21 |
+
Provider: "codex",
|
| 22 |
+
Attributes: map[string]string{
|
| 23 |
+
"runtime_only": "true",
|
| 24 |
+
},
|
| 25 |
+
Metadata: map[string]any{
|
| 26 |
+
"type": "codex",
|
| 27 |
+
},
|
| 28 |
+
}
|
| 29 |
+
if _, errRegister := manager.Register(context.Background(), record); errRegister != nil {
|
| 30 |
+
t.Fatalf("failed to register auth record: %v", errRegister)
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
| 34 |
+
h.tokenStore = &memoryAuthStore{}
|
| 35 |
+
|
| 36 |
+
rec := httptest.NewRecorder()
|
| 37 |
+
ginCtx, _ := gin.CreateTestContext(rec)
|
| 38 |
+
req := httptest.NewRequest(http.MethodGet, "/v0/management/auth-files", nil)
|
| 39 |
+
ginCtx.Request = req
|
| 40 |
+
|
| 41 |
+
h.ListAuthFiles(ginCtx)
|
| 42 |
+
|
| 43 |
+
if rec.Code != http.StatusOK {
|
| 44 |
+
t.Fatalf("expected list status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
var payload map[string]any
|
| 48 |
+
if errUnmarshal := json.Unmarshal(rec.Body.Bytes(), &payload); errUnmarshal != nil {
|
| 49 |
+
t.Fatalf("failed to decode list payload: %v", errUnmarshal)
|
| 50 |
+
}
|
| 51 |
+
filesRaw, ok := payload["files"].([]any)
|
| 52 |
+
if !ok {
|
| 53 |
+
t.Fatalf("expected files array, payload: %#v", payload)
|
| 54 |
+
}
|
| 55 |
+
if len(filesRaw) != 1 {
|
| 56 |
+
t.Fatalf("expected 1 auth entry, got %d", len(filesRaw))
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
fileEntry, ok := filesRaw[0].(map[string]any)
|
| 60 |
+
if !ok {
|
| 61 |
+
t.Fatalf("expected file entry object, got %#v", filesRaw[0])
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
if _, ok := fileEntry["success"].(float64); !ok {
|
| 65 |
+
t.Fatalf("expected success number, got %#v", fileEntry["success"])
|
| 66 |
+
}
|
| 67 |
+
if _, ok := fileEntry["failed"].(float64); !ok {
|
| 68 |
+
t.Fatalf("expected failed number, got %#v", fileEntry["failed"])
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
recentRaw, ok := fileEntry["recent_requests"].([]any)
|
| 72 |
+
if !ok {
|
| 73 |
+
t.Fatalf("expected recent_requests array, got %#v", fileEntry["recent_requests"])
|
| 74 |
+
}
|
| 75 |
+
if len(recentRaw) != 20 {
|
| 76 |
+
t.Fatalf("expected 20 recent_requests buckets, got %d", len(recentRaw))
|
| 77 |
+
}
|
| 78 |
+
for idx, item := range recentRaw {
|
| 79 |
+
bucket, ok := item.(map[string]any)
|
| 80 |
+
if !ok {
|
| 81 |
+
t.Fatalf("expected bucket object at %d, got %#v", idx, item)
|
| 82 |
+
}
|
| 83 |
+
if _, ok := bucket["time"].(string); !ok {
|
| 84 |
+
t.Fatalf("expected bucket time string at %d, got %#v", idx, bucket["time"])
|
| 85 |
+
}
|
| 86 |
+
if _, ok := bucket["success"].(float64); !ok {
|
| 87 |
+
t.Fatalf("expected bucket success number at %d, got %#v", idx, bucket["success"])
|
| 88 |
+
}
|
| 89 |
+
if _, ok := bucket["failed"].(float64); !ok {
|
| 90 |
+
t.Fatalf("expected bucket failed number at %d, got %#v", idx, bucket["failed"])
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
}
|
internal/api/handlers/management/auth_files_upload_test.go
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"bytes"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"mime/multipart"
|
| 7 |
+
"net/http"
|
| 8 |
+
"net/http/httptest"
|
| 9 |
+
"testing"
|
| 10 |
+
|
| 11 |
+
"github.com/gin-gonic/gin"
|
| 12 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 13 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
func TestUploadAuthFile_PreservesPriorityAttributes(t *testing.T) {
|
| 17 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 18 |
+
gin.SetMode(gin.TestMode)
|
| 19 |
+
|
| 20 |
+
authDir := t.TempDir()
|
| 21 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 22 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
| 23 |
+
|
| 24 |
+
content := `{"type":"codex","email":"midai0530@gmail.com","priority":98}`
|
| 25 |
+
|
| 26 |
+
var body bytes.Buffer
|
| 27 |
+
writer := multipart.NewWriter(&body)
|
| 28 |
+
part, err := writer.CreateFormFile("file", "codex-midai0530@gmail.com-plus.json")
|
| 29 |
+
if err != nil {
|
| 30 |
+
t.Fatalf("failed to create multipart file: %v", err)
|
| 31 |
+
}
|
| 32 |
+
if _, err = part.Write([]byte(content)); err != nil {
|
| 33 |
+
t.Fatalf("failed to write multipart content: %v", err)
|
| 34 |
+
}
|
| 35 |
+
if err = writer.Close(); err != nil {
|
| 36 |
+
t.Fatalf("failed to close multipart writer: %v", err)
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
rec := httptest.NewRecorder()
|
| 40 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 41 |
+
req := httptest.NewRequest(http.MethodPost, "/v0/management/auth-files", &body)
|
| 42 |
+
req.Header.Set("Content-Type", writer.FormDataContentType())
|
| 43 |
+
ctx.Request = req
|
| 44 |
+
|
| 45 |
+
h.UploadAuthFile(ctx)
|
| 46 |
+
|
| 47 |
+
if rec.Code != http.StatusOK {
|
| 48 |
+
t.Fatalf("expected upload status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
var payload map[string]any
|
| 52 |
+
if err = json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
|
| 53 |
+
t.Fatalf("failed to decode response: %v", err)
|
| 54 |
+
}
|
| 55 |
+
if status, _ := payload["status"].(string); status != "ok" {
|
| 56 |
+
t.Fatalf("expected status ok, got %#v", payload["status"])
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
auth, ok := manager.GetByID("codex-midai0530@gmail.com-plus.json")
|
| 60 |
+
if !ok || auth == nil {
|
| 61 |
+
t.Fatalf("expected uploaded auth record to exist")
|
| 62 |
+
}
|
| 63 |
+
if got := auth.Attributes["priority"]; got != "98" {
|
| 64 |
+
t.Fatalf("priority attribute = %q, want %q", got, "98")
|
| 65 |
+
}
|
| 66 |
+
if got := auth.Metadata["priority"]; got != float64(98) {
|
| 67 |
+
t.Fatalf("priority metadata = %#v, want 98", got)
|
| 68 |
+
}
|
| 69 |
+
}
|
internal/api/handlers/management/config_apikey_disable.go
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"fmt"
|
| 5 |
+
"strings"
|
| 6 |
+
|
| 7 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 8 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/watcher/synthesizer"
|
| 9 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
const configAPIKeyDisablePattern = "*"
|
| 13 |
+
|
| 14 |
+
func setConfigAPIKeyExcludedAll(models []string, disable bool) []string {
|
| 15 |
+
if disable {
|
| 16 |
+
for _, item := range models {
|
| 17 |
+
if strings.TrimSpace(item) == configAPIKeyDisablePattern {
|
| 18 |
+
return config.NormalizeExcludedModels(models)
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
return config.NormalizeExcludedModels(append(append([]string(nil), models...), configAPIKeyDisablePattern))
|
| 22 |
+
}
|
| 23 |
+
filtered := make([]string, 0, len(models))
|
| 24 |
+
for _, item := range models {
|
| 25 |
+
if strings.TrimSpace(item) == configAPIKeyDisablePattern {
|
| 26 |
+
continue
|
| 27 |
+
}
|
| 28 |
+
filtered = append(filtered, item)
|
| 29 |
+
}
|
| 30 |
+
return config.NormalizeExcludedModels(filtered)
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
func toggleConfigAPIKeyExcludedAll(cfg *config.Config, auth *coreauth.Auth, disable bool) (bool, error) {
|
| 34 |
+
if cfg == nil || auth == nil || !coreauth.IsConfigAPIKeyAuth(auth) {
|
| 35 |
+
return false, nil
|
| 36 |
+
}
|
| 37 |
+
authID := strings.TrimSpace(auth.ID)
|
| 38 |
+
if authID == "" {
|
| 39 |
+
return false, fmt.Errorf("auth id is empty")
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
idGen := synthesizer.NewStableIDGenerator()
|
| 43 |
+
|
| 44 |
+
for i := range cfg.GeminiKey {
|
| 45 |
+
entry := &cfg.GeminiKey[i]
|
| 46 |
+
id, _ := idGen.Next("gemini:apikey", entry.APIKey, entry.BaseURL)
|
| 47 |
+
if id == authID {
|
| 48 |
+
entry.ExcludedModels = setConfigAPIKeyExcludedAll(entry.ExcludedModels, disable)
|
| 49 |
+
return true, nil
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
for i := range cfg.InteractionsKey {
|
| 53 |
+
entry := &cfg.InteractionsKey[i]
|
| 54 |
+
id, _ := idGen.Next("gemini-interactions:apikey", entry.APIKey, entry.BaseURL)
|
| 55 |
+
if id == authID {
|
| 56 |
+
entry.ExcludedModels = setConfigAPIKeyExcludedAll(entry.ExcludedModels, disable)
|
| 57 |
+
return true, nil
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
for i := range cfg.ClaudeKey {
|
| 61 |
+
entry := &cfg.ClaudeKey[i]
|
| 62 |
+
id, _ := idGen.Next("claude:apikey", entry.APIKey, entry.BaseURL)
|
| 63 |
+
if id == authID {
|
| 64 |
+
entry.ExcludedModels = setConfigAPIKeyExcludedAll(entry.ExcludedModels, disable)
|
| 65 |
+
return true, nil
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
for i := range cfg.CodexKey {
|
| 69 |
+
entry := &cfg.CodexKey[i]
|
| 70 |
+
id, _ := idGen.Next("codex:apikey", entry.APIKey, entry.BaseURL)
|
| 71 |
+
if id == authID {
|
| 72 |
+
entry.ExcludedModels = setConfigAPIKeyExcludedAll(entry.ExcludedModels, disable)
|
| 73 |
+
return true, nil
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
for i := range cfg.XAIKey {
|
| 77 |
+
entry := &cfg.XAIKey[i]
|
| 78 |
+
id, _ := idGen.Next("xai:apikey", entry.APIKey, entry.BaseURL)
|
| 79 |
+
if id == authID {
|
| 80 |
+
entry.ExcludedModels = setConfigAPIKeyExcludedAll(entry.ExcludedModels, disable)
|
| 81 |
+
return true, nil
|
| 82 |
+
}
|
| 83 |
+
}
|
| 84 |
+
for i := range cfg.VertexCompatAPIKey {
|
| 85 |
+
entry := &cfg.VertexCompatAPIKey[i]
|
| 86 |
+
id, _ := idGen.Next("vertex:apikey", entry.APIKey, entry.BaseURL, entry.ProxyURL)
|
| 87 |
+
if id == authID {
|
| 88 |
+
entry.ExcludedModels = setConfigAPIKeyExcludedAll(entry.ExcludedModels, disable)
|
| 89 |
+
return true, nil
|
| 90 |
+
}
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
return false, nil
|
| 94 |
+
}
|
internal/api/handlers/management/config_apikey_disable_test.go
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"testing"
|
| 5 |
+
|
| 6 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 7 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/watcher/synthesizer"
|
| 8 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
func TestSetConfigAPIKeyExcludedAll(t *testing.T) {
|
| 12 |
+
gotDisable := setConfigAPIKeyExcludedAll([]string{"gpt-5"}, true)
|
| 13 |
+
if len(gotDisable) != 2 || gotDisable[0] != "gpt-5" || gotDisable[1] != "*" {
|
| 14 |
+
t.Fatalf("unexpected disable list: %#v", gotDisable)
|
| 15 |
+
}
|
| 16 |
+
gotEnable := setConfigAPIKeyExcludedAll([]string{"gpt-5", "*"}, false)
|
| 17 |
+
if len(gotEnable) != 1 || gotEnable[0] != "gpt-5" {
|
| 18 |
+
t.Fatalf("unexpected enable list: %#v", gotEnable)
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
func TestToggleConfigAPIKeyExcludedAll_XAI(t *testing.T) {
|
| 23 |
+
cfg := &config.Config{
|
| 24 |
+
XAIKey: []config.XAIKey{{
|
| 25 |
+
APIKey: "xai-test",
|
| 26 |
+
BaseURL: "https://api.x.ai/v1",
|
| 27 |
+
}},
|
| 28 |
+
}
|
| 29 |
+
idGen := synthesizer.NewStableIDGenerator()
|
| 30 |
+
authID, _ := idGen.Next("xai:apikey", "xai-test", "https://api.x.ai/v1")
|
| 31 |
+
auth := &coreauth.Auth{
|
| 32 |
+
ID: authID,
|
| 33 |
+
Provider: "xai",
|
| 34 |
+
Attributes: map[string]string{
|
| 35 |
+
"api_key": "xai-test",
|
| 36 |
+
"base_url": "https://api.x.ai/v1",
|
| 37 |
+
"source": "config:xai[abc]",
|
| 38 |
+
},
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
handled, errToggle := toggleConfigAPIKeyExcludedAll(cfg, auth, true)
|
| 42 |
+
if errToggle != nil || !handled {
|
| 43 |
+
t.Fatalf("toggle disable: handled=%v err=%v", handled, errToggle)
|
| 44 |
+
}
|
| 45 |
+
if len(cfg.XAIKey[0].ExcludedModels) != 1 || cfg.XAIKey[0].ExcludedModels[0] != "*" {
|
| 46 |
+
t.Fatalf("excluded-models = %#v, want [*]", cfg.XAIKey[0].ExcludedModels)
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
func TestToggleConfigAPIKeyExcludedAll_Codex(t *testing.T) {
|
| 51 |
+
cfg := &config.Config{
|
| 52 |
+
CodexKey: []config.CodexKey{{
|
| 53 |
+
APIKey: "sk-test",
|
| 54 |
+
BaseURL: "https://example.com/v1",
|
| 55 |
+
}},
|
| 56 |
+
}
|
| 57 |
+
idGen := synthesizer.NewStableIDGenerator()
|
| 58 |
+
authID, _ := idGen.Next("codex:apikey", "sk-test", "https://example.com/v1")
|
| 59 |
+
auth := &coreauth.Auth{
|
| 60 |
+
ID: authID,
|
| 61 |
+
Provider: "codex",
|
| 62 |
+
Attributes: map[string]string{
|
| 63 |
+
"api_key": "sk-test",
|
| 64 |
+
"base_url": "https://example.com/v1",
|
| 65 |
+
"source": "config:codex[abc]",
|
| 66 |
+
},
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
handled, err := toggleConfigAPIKeyExcludedAll(cfg, auth, true)
|
| 70 |
+
if err != nil || !handled {
|
| 71 |
+
t.Fatalf("toggle disable: handled=%v err=%v", handled, err)
|
| 72 |
+
}
|
| 73 |
+
if len(cfg.CodexKey[0].ExcludedModels) != 1 || cfg.CodexKey[0].ExcludedModels[0] != "*" {
|
| 74 |
+
t.Fatalf("expected excluded-models [*], got %#v", cfg.CodexKey[0].ExcludedModels)
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
handled, err = toggleConfigAPIKeyExcludedAll(cfg, auth, false)
|
| 78 |
+
if err != nil || !handled {
|
| 79 |
+
t.Fatalf("toggle enable: handled=%v err=%v", handled, err)
|
| 80 |
+
}
|
| 81 |
+
if len(cfg.CodexKey[0].ExcludedModels) != 0 {
|
| 82 |
+
t.Fatalf("expected excluded-models cleared, got %#v", cfg.CodexKey[0].ExcludedModels)
|
| 83 |
+
}
|
| 84 |
+
}
|
internal/api/handlers/management/config_auth_index.go
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"fmt"
|
| 5 |
+
"strings"
|
| 6 |
+
|
| 7 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 8 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/watcher/synthesizer"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
type geminiKeyWithAuthIndex struct {
|
| 12 |
+
config.GeminiKey
|
| 13 |
+
AuthIndex string `json:"auth-index,omitempty"`
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
type claudeKeyWithAuthIndex struct {
|
| 17 |
+
config.ClaudeKey
|
| 18 |
+
AuthIndex string `json:"auth-index,omitempty"`
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
type codexKeyWithAuthIndex struct {
|
| 22 |
+
config.CodexKey
|
| 23 |
+
AuthIndex string `json:"auth-index,omitempty"`
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
type xaiKeyWithAuthIndex struct {
|
| 27 |
+
config.XAIKey
|
| 28 |
+
AuthIndex string `json:"auth-index,omitempty"`
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
type vertexCompatKeyWithAuthIndex struct {
|
| 32 |
+
config.VertexCompatKey
|
| 33 |
+
AuthIndex string `json:"auth-index,omitempty"`
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
type openAICompatibilityAPIKeyWithAuthIndex struct {
|
| 37 |
+
config.OpenAICompatibilityAPIKey
|
| 38 |
+
AuthIndex string `json:"auth-index,omitempty"`
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
type openAICompatibilityWithAuthIndex struct {
|
| 42 |
+
Name string `json:"name"`
|
| 43 |
+
Priority int `json:"priority,omitempty"`
|
| 44 |
+
Disabled bool `json:"disabled"`
|
| 45 |
+
Prefix string `json:"prefix,omitempty"`
|
| 46 |
+
BaseURL string `json:"base-url"`
|
| 47 |
+
APIKeyEntries []openAICompatibilityAPIKeyWithAuthIndex `json:"api-key-entries,omitempty"`
|
| 48 |
+
Models []config.OpenAICompatibilityModel `json:"models,omitempty"`
|
| 49 |
+
Headers map[string]string `json:"headers,omitempty"`
|
| 50 |
+
DisableCooling bool `json:"disable-cooling,omitempty"`
|
| 51 |
+
AuthIndex string `json:"auth-index,omitempty"`
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
func (h *Handler) liveAuthIndexByID() map[string]string {
|
| 55 |
+
out := map[string]string{}
|
| 56 |
+
if h == nil {
|
| 57 |
+
return out
|
| 58 |
+
}
|
| 59 |
+
h.mu.Lock()
|
| 60 |
+
manager := h.authManager
|
| 61 |
+
h.mu.Unlock()
|
| 62 |
+
if manager == nil {
|
| 63 |
+
return out
|
| 64 |
+
}
|
| 65 |
+
// authManager.List() returns clones, so EnsureIndex only affects these copies.
|
| 66 |
+
for _, auth := range manager.List() {
|
| 67 |
+
if auth == nil {
|
| 68 |
+
continue
|
| 69 |
+
}
|
| 70 |
+
id := strings.TrimSpace(auth.ID)
|
| 71 |
+
if id == "" {
|
| 72 |
+
continue
|
| 73 |
+
}
|
| 74 |
+
idx := strings.TrimSpace(auth.Index)
|
| 75 |
+
if idx == "" {
|
| 76 |
+
idx = auth.EnsureIndex()
|
| 77 |
+
}
|
| 78 |
+
if idx == "" {
|
| 79 |
+
continue
|
| 80 |
+
}
|
| 81 |
+
out[id] = idx
|
| 82 |
+
}
|
| 83 |
+
return out
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
func (h *Handler) geminiKeysWithAuthIndex() []geminiKeyWithAuthIndex {
|
| 87 |
+
if h == nil {
|
| 88 |
+
return nil
|
| 89 |
+
}
|
| 90 |
+
liveIndexByID := h.liveAuthIndexByID()
|
| 91 |
+
|
| 92 |
+
h.mu.Lock()
|
| 93 |
+
defer h.mu.Unlock()
|
| 94 |
+
if h.cfg == nil {
|
| 95 |
+
return nil
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
idGen := synthesizer.NewStableIDGenerator()
|
| 99 |
+
out := make([]geminiKeyWithAuthIndex, len(h.cfg.GeminiKey))
|
| 100 |
+
for i := range h.cfg.GeminiKey {
|
| 101 |
+
entry := h.cfg.GeminiKey[i]
|
| 102 |
+
authIndex := ""
|
| 103 |
+
if key := strings.TrimSpace(entry.APIKey); key != "" {
|
| 104 |
+
id, _ := idGen.Next("gemini:apikey", key, entry.BaseURL)
|
| 105 |
+
authIndex = liveIndexByID[id]
|
| 106 |
+
}
|
| 107 |
+
out[i] = geminiKeyWithAuthIndex{
|
| 108 |
+
GeminiKey: entry,
|
| 109 |
+
AuthIndex: authIndex,
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
return out
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
func (h *Handler) interactionsKeysWithAuthIndex() []geminiKeyWithAuthIndex {
|
| 116 |
+
if h == nil {
|
| 117 |
+
return nil
|
| 118 |
+
}
|
| 119 |
+
liveIndexByID := h.liveAuthIndexByID()
|
| 120 |
+
|
| 121 |
+
h.mu.Lock()
|
| 122 |
+
defer h.mu.Unlock()
|
| 123 |
+
if h.cfg == nil {
|
| 124 |
+
return nil
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
idGen := synthesizer.NewStableIDGenerator()
|
| 128 |
+
out := make([]geminiKeyWithAuthIndex, len(h.cfg.InteractionsKey))
|
| 129 |
+
for i := range h.cfg.InteractionsKey {
|
| 130 |
+
entry := h.cfg.InteractionsKey[i]
|
| 131 |
+
authIndex := ""
|
| 132 |
+
if key := strings.TrimSpace(entry.APIKey); key != "" {
|
| 133 |
+
id, _ := idGen.Next("gemini-interactions:apikey", key, entry.BaseURL)
|
| 134 |
+
authIndex = liveIndexByID[id]
|
| 135 |
+
}
|
| 136 |
+
out[i] = geminiKeyWithAuthIndex{
|
| 137 |
+
GeminiKey: entry,
|
| 138 |
+
AuthIndex: authIndex,
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
return out
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
func (h *Handler) claudeKeysWithAuthIndex() []claudeKeyWithAuthIndex {
|
| 145 |
+
if h == nil {
|
| 146 |
+
return nil
|
| 147 |
+
}
|
| 148 |
+
liveIndexByID := h.liveAuthIndexByID()
|
| 149 |
+
|
| 150 |
+
h.mu.Lock()
|
| 151 |
+
defer h.mu.Unlock()
|
| 152 |
+
if h.cfg == nil {
|
| 153 |
+
return nil
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
idGen := synthesizer.NewStableIDGenerator()
|
| 157 |
+
out := make([]claudeKeyWithAuthIndex, len(h.cfg.ClaudeKey))
|
| 158 |
+
for i := range h.cfg.ClaudeKey {
|
| 159 |
+
entry := h.cfg.ClaudeKey[i]
|
| 160 |
+
authIndex := ""
|
| 161 |
+
if key := strings.TrimSpace(entry.APIKey); key != "" {
|
| 162 |
+
id, _ := idGen.Next("claude:apikey", key, entry.BaseURL)
|
| 163 |
+
authIndex = liveIndexByID[id]
|
| 164 |
+
}
|
| 165 |
+
out[i] = claudeKeyWithAuthIndex{
|
| 166 |
+
ClaudeKey: entry,
|
| 167 |
+
AuthIndex: authIndex,
|
| 168 |
+
}
|
| 169 |
+
}
|
| 170 |
+
return out
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
func (h *Handler) codexKeysWithAuthIndex() []codexKeyWithAuthIndex {
|
| 174 |
+
if h == nil {
|
| 175 |
+
return nil
|
| 176 |
+
}
|
| 177 |
+
liveIndexByID := h.liveAuthIndexByID()
|
| 178 |
+
|
| 179 |
+
h.mu.Lock()
|
| 180 |
+
defer h.mu.Unlock()
|
| 181 |
+
if h.cfg == nil {
|
| 182 |
+
return nil
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
idGen := synthesizer.NewStableIDGenerator()
|
| 186 |
+
out := make([]codexKeyWithAuthIndex, len(h.cfg.CodexKey))
|
| 187 |
+
for i := range h.cfg.CodexKey {
|
| 188 |
+
entry := h.cfg.CodexKey[i]
|
| 189 |
+
authIndex := ""
|
| 190 |
+
if key := strings.TrimSpace(entry.APIKey); key != "" {
|
| 191 |
+
id, _ := idGen.Next("codex:apikey", key, entry.BaseURL)
|
| 192 |
+
authIndex = liveIndexByID[id]
|
| 193 |
+
}
|
| 194 |
+
out[i] = codexKeyWithAuthIndex{
|
| 195 |
+
CodexKey: entry,
|
| 196 |
+
AuthIndex: authIndex,
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
return out
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
func (h *Handler) xaiKeysWithAuthIndex() []xaiKeyWithAuthIndex {
|
| 203 |
+
if h == nil {
|
| 204 |
+
return nil
|
| 205 |
+
}
|
| 206 |
+
liveIndexByID := h.liveAuthIndexByID()
|
| 207 |
+
|
| 208 |
+
h.mu.Lock()
|
| 209 |
+
defer h.mu.Unlock()
|
| 210 |
+
if h.cfg == nil {
|
| 211 |
+
return nil
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
idGen := synthesizer.NewStableIDGenerator()
|
| 215 |
+
out := make([]xaiKeyWithAuthIndex, len(h.cfg.XAIKey))
|
| 216 |
+
for i := range h.cfg.XAIKey {
|
| 217 |
+
entry := h.cfg.XAIKey[i]
|
| 218 |
+
authIndex := ""
|
| 219 |
+
if key := strings.TrimSpace(entry.APIKey); key != "" {
|
| 220 |
+
id, _ := idGen.Next("xai:apikey", key, entry.BaseURL)
|
| 221 |
+
authIndex = liveIndexByID[id]
|
| 222 |
+
}
|
| 223 |
+
out[i] = xaiKeyWithAuthIndex{
|
| 224 |
+
XAIKey: entry,
|
| 225 |
+
AuthIndex: authIndex,
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
return out
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
func (h *Handler) vertexCompatKeysWithAuthIndex() []vertexCompatKeyWithAuthIndex {
|
| 232 |
+
if h == nil {
|
| 233 |
+
return nil
|
| 234 |
+
}
|
| 235 |
+
liveIndexByID := h.liveAuthIndexByID()
|
| 236 |
+
|
| 237 |
+
h.mu.Lock()
|
| 238 |
+
defer h.mu.Unlock()
|
| 239 |
+
if h.cfg == nil {
|
| 240 |
+
return nil
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
idGen := synthesizer.NewStableIDGenerator()
|
| 244 |
+
out := make([]vertexCompatKeyWithAuthIndex, len(h.cfg.VertexCompatAPIKey))
|
| 245 |
+
for i := range h.cfg.VertexCompatAPIKey {
|
| 246 |
+
entry := h.cfg.VertexCompatAPIKey[i]
|
| 247 |
+
id, _ := idGen.Next("vertex:apikey", entry.APIKey, entry.BaseURL, entry.ProxyURL)
|
| 248 |
+
authIndex := liveIndexByID[id]
|
| 249 |
+
out[i] = vertexCompatKeyWithAuthIndex{
|
| 250 |
+
VertexCompatKey: entry,
|
| 251 |
+
AuthIndex: authIndex,
|
| 252 |
+
}
|
| 253 |
+
}
|
| 254 |
+
return out
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
func (h *Handler) openAICompatibilityWithAuthIndex() []openAICompatibilityWithAuthIndex {
|
| 258 |
+
if h == nil {
|
| 259 |
+
return nil
|
| 260 |
+
}
|
| 261 |
+
liveIndexByID := h.liveAuthIndexByID()
|
| 262 |
+
|
| 263 |
+
h.mu.Lock()
|
| 264 |
+
defer h.mu.Unlock()
|
| 265 |
+
if h.cfg == nil {
|
| 266 |
+
return nil
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
normalized := normalizedOpenAICompatibilityEntries(h.cfg.OpenAICompatibility)
|
| 270 |
+
out := make([]openAICompatibilityWithAuthIndex, len(normalized))
|
| 271 |
+
idGen := synthesizer.NewStableIDGenerator()
|
| 272 |
+
for i := range normalized {
|
| 273 |
+
entry := normalized[i]
|
| 274 |
+
providerName := strings.ToLower(strings.TrimSpace(entry.Name))
|
| 275 |
+
if providerName == "" {
|
| 276 |
+
providerName = "openai-compatibility"
|
| 277 |
+
}
|
| 278 |
+
idKind := fmt.Sprintf("openai-compatibility:%s", providerName)
|
| 279 |
+
|
| 280 |
+
response := openAICompatibilityWithAuthIndex{
|
| 281 |
+
Name: entry.Name,
|
| 282 |
+
Priority: entry.Priority,
|
| 283 |
+
Disabled: entry.Disabled,
|
| 284 |
+
Prefix: entry.Prefix,
|
| 285 |
+
BaseURL: entry.BaseURL,
|
| 286 |
+
Models: entry.Models,
|
| 287 |
+
Headers: entry.Headers,
|
| 288 |
+
DisableCooling: entry.DisableCooling,
|
| 289 |
+
AuthIndex: "",
|
| 290 |
+
}
|
| 291 |
+
if len(entry.APIKeyEntries) == 0 {
|
| 292 |
+
id, _ := idGen.Next(idKind, entry.BaseURL)
|
| 293 |
+
response.AuthIndex = liveIndexByID[id]
|
| 294 |
+
} else {
|
| 295 |
+
response.APIKeyEntries = make([]openAICompatibilityAPIKeyWithAuthIndex, len(entry.APIKeyEntries))
|
| 296 |
+
for j := range entry.APIKeyEntries {
|
| 297 |
+
apiKeyEntry := entry.APIKeyEntries[j]
|
| 298 |
+
id, _ := idGen.Next(idKind, apiKeyEntry.APIKey, entry.BaseURL, apiKeyEntry.ProxyURL)
|
| 299 |
+
response.APIKeyEntries[j] = openAICompatibilityAPIKeyWithAuthIndex{
|
| 300 |
+
OpenAICompatibilityAPIKey: apiKeyEntry,
|
| 301 |
+
AuthIndex: liveIndexByID[id],
|
| 302 |
+
}
|
| 303 |
+
}
|
| 304 |
+
}
|
| 305 |
+
out[i] = response
|
| 306 |
+
}
|
| 307 |
+
return out
|
| 308 |
+
}
|
internal/api/handlers/management/config_basic.go
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"fmt"
|
| 6 |
+
"io"
|
| 7 |
+
"net/http"
|
| 8 |
+
"os"
|
| 9 |
+
"path/filepath"
|
| 10 |
+
"strings"
|
| 11 |
+
"time"
|
| 12 |
+
|
| 13 |
+
"github.com/gin-gonic/gin"
|
| 14 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 15 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
| 16 |
+
sdkconfig "github.com/router-for-me/CLIProxyAPI/v7/sdk/config"
|
| 17 |
+
log "github.com/sirupsen/logrus"
|
| 18 |
+
"gopkg.in/yaml.v3"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
const (
|
| 22 |
+
latestReleaseURL = "https://api.github.com/repos/router-for-me/CLIProxyAPI/releases/latest"
|
| 23 |
+
latestReleaseUserAgent = "CLIProxyAPI"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
func (h *Handler) GetConfig(c *gin.Context) {
|
| 27 |
+
if h == nil || h.cfg == nil {
|
| 28 |
+
c.JSON(200, gin.H{})
|
| 29 |
+
return
|
| 30 |
+
}
|
| 31 |
+
c.JSON(200, new(*h.cfg))
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
type releaseInfo struct {
|
| 35 |
+
TagName string `json:"tag_name"`
|
| 36 |
+
Name string `json:"name"`
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
// GetLatestVersion returns the latest release version from GitHub without downloading assets.
|
| 40 |
+
func (h *Handler) GetLatestVersion(c *gin.Context) {
|
| 41 |
+
client := &http.Client{Timeout: 10 * time.Second}
|
| 42 |
+
proxyURL := ""
|
| 43 |
+
if h != nil && h.cfg != nil {
|
| 44 |
+
proxyURL = strings.TrimSpace(h.cfg.ProxyURL)
|
| 45 |
+
}
|
| 46 |
+
if proxyURL != "" {
|
| 47 |
+
sdkCfg := &sdkconfig.SDKConfig{ProxyURL: proxyURL}
|
| 48 |
+
util.SetProxy(sdkCfg, client)
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
req, err := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, latestReleaseURL, nil)
|
| 52 |
+
if err != nil {
|
| 53 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "request_create_failed", "message": err.Error()})
|
| 54 |
+
return
|
| 55 |
+
}
|
| 56 |
+
req.Header.Set("Accept", "application/vnd.github+json")
|
| 57 |
+
req.Header.Set("User-Agent", latestReleaseUserAgent)
|
| 58 |
+
|
| 59 |
+
resp, err := client.Do(req)
|
| 60 |
+
if err != nil {
|
| 61 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "request_failed", "message": err.Error()})
|
| 62 |
+
return
|
| 63 |
+
}
|
| 64 |
+
defer func() {
|
| 65 |
+
if errClose := resp.Body.Close(); errClose != nil {
|
| 66 |
+
log.WithError(errClose).Debug("failed to close latest version response body")
|
| 67 |
+
}
|
| 68 |
+
}()
|
| 69 |
+
|
| 70 |
+
if resp.StatusCode != http.StatusOK {
|
| 71 |
+
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
|
| 72 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "unexpected_status", "message": fmt.Sprintf("status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))})
|
| 73 |
+
return
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
var info releaseInfo
|
| 77 |
+
if errDecode := json.NewDecoder(resp.Body).Decode(&info); errDecode != nil {
|
| 78 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "decode_failed", "message": errDecode.Error()})
|
| 79 |
+
return
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
version := strings.TrimSpace(info.TagName)
|
| 83 |
+
if version == "" {
|
| 84 |
+
version = strings.TrimSpace(info.Name)
|
| 85 |
+
}
|
| 86 |
+
if version == "" {
|
| 87 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "invalid_response", "message": "missing release version"})
|
| 88 |
+
return
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
c.JSON(http.StatusOK, gin.H{"latest-version": version})
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
func WriteConfig(path string, data []byte) error {
|
| 95 |
+
data = config.NormalizeCommentIndentation(data)
|
| 96 |
+
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
| 97 |
+
if err != nil {
|
| 98 |
+
return err
|
| 99 |
+
}
|
| 100 |
+
if _, errWrite := f.Write(data); errWrite != nil {
|
| 101 |
+
_ = f.Close()
|
| 102 |
+
return errWrite
|
| 103 |
+
}
|
| 104 |
+
if errSync := f.Sync(); errSync != nil {
|
| 105 |
+
_ = f.Close()
|
| 106 |
+
return errSync
|
| 107 |
+
}
|
| 108 |
+
return f.Close()
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
func (h *Handler) PutConfigYAML(c *gin.Context) {
|
| 112 |
+
body, err := io.ReadAll(c.Request.Body)
|
| 113 |
+
if err != nil {
|
| 114 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_yaml", "message": "cannot read request body"})
|
| 115 |
+
return
|
| 116 |
+
}
|
| 117 |
+
var cfg config.Config
|
| 118 |
+
if err = yaml.Unmarshal(body, &cfg); err != nil {
|
| 119 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_yaml", "message": err.Error()})
|
| 120 |
+
return
|
| 121 |
+
}
|
| 122 |
+
// Validate config using LoadConfigOptional with optional=false to enforce parsing
|
| 123 |
+
tmpDir := filepath.Dir(h.configFilePath)
|
| 124 |
+
tmpFile, err := os.CreateTemp(tmpDir, "config-validate-*.yaml")
|
| 125 |
+
if err != nil {
|
| 126 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": err.Error()})
|
| 127 |
+
return
|
| 128 |
+
}
|
| 129 |
+
tempFile := tmpFile.Name()
|
| 130 |
+
if _, errWrite := tmpFile.Write(body); errWrite != nil {
|
| 131 |
+
_ = tmpFile.Close()
|
| 132 |
+
_ = os.Remove(tempFile)
|
| 133 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": errWrite.Error()})
|
| 134 |
+
return
|
| 135 |
+
}
|
| 136 |
+
if errClose := tmpFile.Close(); errClose != nil {
|
| 137 |
+
_ = os.Remove(tempFile)
|
| 138 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": errClose.Error()})
|
| 139 |
+
return
|
| 140 |
+
}
|
| 141 |
+
defer func() {
|
| 142 |
+
_ = os.Remove(tempFile)
|
| 143 |
+
}()
|
| 144 |
+
_, err = config.LoadConfigOptional(tempFile, false)
|
| 145 |
+
if err != nil {
|
| 146 |
+
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "invalid_config", "message": err.Error()})
|
| 147 |
+
return
|
| 148 |
+
}
|
| 149 |
+
h.mu.Lock()
|
| 150 |
+
defer h.mu.Unlock()
|
| 151 |
+
if WriteConfig(h.configFilePath, body) != nil {
|
| 152 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": "failed to write config"})
|
| 153 |
+
return
|
| 154 |
+
}
|
| 155 |
+
// Reload into handler to keep memory in sync
|
| 156 |
+
newCfg, err := config.LoadConfig(h.configFilePath)
|
| 157 |
+
if err != nil {
|
| 158 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "reload_failed", "message": err.Error()})
|
| 159 |
+
return
|
| 160 |
+
}
|
| 161 |
+
h.cfg = newCfg
|
| 162 |
+
c.JSON(http.StatusOK, gin.H{"ok": true, "changed": []string{"config"}})
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
// GetConfigYAML returns the raw config.yaml file bytes without re-encoding.
|
| 166 |
+
// It preserves comments and original formatting/styles.
|
| 167 |
+
func (h *Handler) GetConfigYAML(c *gin.Context) {
|
| 168 |
+
data, err := os.ReadFile(h.configFilePath)
|
| 169 |
+
if err != nil {
|
| 170 |
+
if os.IsNotExist(err) {
|
| 171 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "not_found", "message": "config file not found"})
|
| 172 |
+
return
|
| 173 |
+
}
|
| 174 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "read_failed", "message": err.Error()})
|
| 175 |
+
return
|
| 176 |
+
}
|
| 177 |
+
c.Header("Content-Type", "application/yaml; charset=utf-8")
|
| 178 |
+
c.Header("Cache-Control", "no-store")
|
| 179 |
+
c.Header("X-Content-Type-Options", "nosniff")
|
| 180 |
+
// Write raw bytes as-is
|
| 181 |
+
_, _ = c.Writer.Write(data)
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
// Debug
|
| 185 |
+
func (h *Handler) GetDebug(c *gin.Context) { c.JSON(200, gin.H{"debug": h.cfg.Debug}) }
|
| 186 |
+
func (h *Handler) PutDebug(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.Debug = v }) }
|
| 187 |
+
|
| 188 |
+
// UsageStatisticsEnabled
|
| 189 |
+
func (h *Handler) GetUsageStatisticsEnabled(c *gin.Context) {
|
| 190 |
+
c.JSON(200, gin.H{"usage-statistics-enabled": h.cfg.UsageStatisticsEnabled})
|
| 191 |
+
}
|
| 192 |
+
func (h *Handler) PutUsageStatisticsEnabled(c *gin.Context) {
|
| 193 |
+
h.updateBoolField(c, func(v bool) { h.cfg.UsageStatisticsEnabled = v })
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
// UsageStatisticsEnabled
|
| 197 |
+
func (h *Handler) GetLoggingToFile(c *gin.Context) {
|
| 198 |
+
c.JSON(200, gin.H{"logging-to-file": h.cfg.LoggingToFile})
|
| 199 |
+
}
|
| 200 |
+
func (h *Handler) PutLoggingToFile(c *gin.Context) {
|
| 201 |
+
h.updateBoolField(c, func(v bool) { h.cfg.LoggingToFile = v })
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
// LogsMaxTotalSizeMB
|
| 205 |
+
func (h *Handler) GetLogsMaxTotalSizeMB(c *gin.Context) {
|
| 206 |
+
c.JSON(200, gin.H{"logs-max-total-size-mb": h.cfg.LogsMaxTotalSizeMB})
|
| 207 |
+
}
|
| 208 |
+
func (h *Handler) PutLogsMaxTotalSizeMB(c *gin.Context) {
|
| 209 |
+
var body struct {
|
| 210 |
+
Value *int `json:"value"`
|
| 211 |
+
}
|
| 212 |
+
if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil || body.Value == nil {
|
| 213 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
|
| 214 |
+
return
|
| 215 |
+
}
|
| 216 |
+
value := *body.Value
|
| 217 |
+
if value < 0 {
|
| 218 |
+
value = 0
|
| 219 |
+
}
|
| 220 |
+
h.cfg.LogsMaxTotalSizeMB = value
|
| 221 |
+
h.persist(c)
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
// ErrorLogsMaxFiles
|
| 225 |
+
func (h *Handler) GetErrorLogsMaxFiles(c *gin.Context) {
|
| 226 |
+
c.JSON(200, gin.H{"error-logs-max-files": h.cfg.ErrorLogsMaxFiles})
|
| 227 |
+
}
|
| 228 |
+
func (h *Handler) PutErrorLogsMaxFiles(c *gin.Context) {
|
| 229 |
+
var body struct {
|
| 230 |
+
Value *int `json:"value"`
|
| 231 |
+
}
|
| 232 |
+
if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil || body.Value == nil {
|
| 233 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
|
| 234 |
+
return
|
| 235 |
+
}
|
| 236 |
+
value := *body.Value
|
| 237 |
+
if value < 0 {
|
| 238 |
+
value = 10
|
| 239 |
+
}
|
| 240 |
+
h.cfg.ErrorLogsMaxFiles = value
|
| 241 |
+
h.persist(c)
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
// Request log
|
| 245 |
+
func (h *Handler) GetRequestLog(c *gin.Context) { c.JSON(200, gin.H{"request-log": h.cfg.RequestLog}) }
|
| 246 |
+
func (h *Handler) PutRequestLog(c *gin.Context) {
|
| 247 |
+
h.updateBoolField(c, func(v bool) { h.cfg.RequestLog = v })
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
// Websocket auth
|
| 251 |
+
func (h *Handler) GetWebsocketAuth(c *gin.Context) {
|
| 252 |
+
c.JSON(200, gin.H{"ws-auth": h.cfg.WebsocketAuth})
|
| 253 |
+
}
|
| 254 |
+
func (h *Handler) PutWebsocketAuth(c *gin.Context) {
|
| 255 |
+
h.updateBoolField(c, func(v bool) { h.cfg.WebsocketAuth = v })
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
// Request retry
|
| 259 |
+
func (h *Handler) GetRequestRetry(c *gin.Context) {
|
| 260 |
+
c.JSON(200, gin.H{"request-retry": h.cfg.RequestRetry})
|
| 261 |
+
}
|
| 262 |
+
func (h *Handler) PutRequestRetry(c *gin.Context) {
|
| 263 |
+
h.updateIntField(c, func(v int) { h.cfg.RequestRetry = v })
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
// Max retry interval
|
| 267 |
+
func (h *Handler) GetMaxRetryInterval(c *gin.Context) {
|
| 268 |
+
c.JSON(200, gin.H{"max-retry-interval": h.cfg.MaxRetryInterval})
|
| 269 |
+
}
|
| 270 |
+
func (h *Handler) PutMaxRetryInterval(c *gin.Context) {
|
| 271 |
+
h.updateIntField(c, func(v int) { h.cfg.MaxRetryInterval = v })
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
// ForceModelPrefix
|
| 275 |
+
func (h *Handler) GetForceModelPrefix(c *gin.Context) {
|
| 276 |
+
c.JSON(200, gin.H{"force-model-prefix": h.cfg.ForceModelPrefix})
|
| 277 |
+
}
|
| 278 |
+
func (h *Handler) PutForceModelPrefix(c *gin.Context) {
|
| 279 |
+
h.updateBoolField(c, func(v bool) { h.cfg.ForceModelPrefix = v })
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
func normalizeRoutingStrategy(strategy string) (string, bool) {
|
| 283 |
+
normalized := strings.ToLower(strings.TrimSpace(strategy))
|
| 284 |
+
switch normalized {
|
| 285 |
+
case "", "round-robin", "roundrobin", "rr":
|
| 286 |
+
return "round-robin", true
|
| 287 |
+
case "fill-first", "fillfirst", "ff":
|
| 288 |
+
return "fill-first", true
|
| 289 |
+
default:
|
| 290 |
+
return "", false
|
| 291 |
+
}
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
// RoutingStrategy
|
| 295 |
+
func (h *Handler) GetRoutingStrategy(c *gin.Context) {
|
| 296 |
+
strategy, ok := normalizeRoutingStrategy(h.cfg.Routing.Strategy)
|
| 297 |
+
if !ok {
|
| 298 |
+
c.JSON(200, gin.H{"strategy": strings.TrimSpace(h.cfg.Routing.Strategy)})
|
| 299 |
+
return
|
| 300 |
+
}
|
| 301 |
+
c.JSON(200, gin.H{"strategy": strategy})
|
| 302 |
+
}
|
| 303 |
+
func (h *Handler) PutRoutingStrategy(c *gin.Context) {
|
| 304 |
+
var body struct {
|
| 305 |
+
Value *string `json:"value"`
|
| 306 |
+
}
|
| 307 |
+
if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil || body.Value == nil {
|
| 308 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
|
| 309 |
+
return
|
| 310 |
+
}
|
| 311 |
+
normalized, ok := normalizeRoutingStrategy(*body.Value)
|
| 312 |
+
if !ok {
|
| 313 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid strategy"})
|
| 314 |
+
return
|
| 315 |
+
}
|
| 316 |
+
h.cfg.Routing.Strategy = normalized
|
| 317 |
+
h.persist(c)
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
// Proxy URL
|
| 321 |
+
func (h *Handler) GetProxyURL(c *gin.Context) { c.JSON(200, gin.H{"proxy-url": h.cfg.ProxyURL}) }
|
| 322 |
+
func (h *Handler) PutProxyURL(c *gin.Context) {
|
| 323 |
+
h.updateStringField(c, func(v string) { h.cfg.ProxyURL = v })
|
| 324 |
+
}
|
| 325 |
+
func (h *Handler) DeleteProxyURL(c *gin.Context) {
|
| 326 |
+
h.cfg.ProxyURL = ""
|
| 327 |
+
h.persist(c)
|
| 328 |
+
}
|
internal/api/handlers/management/config_lists.go
ADDED
|
@@ -0,0 +1,1561 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"fmt"
|
| 6 |
+
"strings"
|
| 7 |
+
|
| 8 |
+
"github.com/gin-gonic/gin"
|
| 9 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
// Generic helpers for list[string]
|
| 13 |
+
func (h *Handler) putStringList(c *gin.Context, set func([]string), after func()) {
|
| 14 |
+
data, err := c.GetRawData()
|
| 15 |
+
if err != nil {
|
| 16 |
+
c.JSON(400, gin.H{"error": "failed to read body"})
|
| 17 |
+
return
|
| 18 |
+
}
|
| 19 |
+
var arr []string
|
| 20 |
+
if err = json.Unmarshal(data, &arr); err != nil {
|
| 21 |
+
var obj struct {
|
| 22 |
+
Items []string `json:"items"`
|
| 23 |
+
}
|
| 24 |
+
if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 {
|
| 25 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 26 |
+
return
|
| 27 |
+
}
|
| 28 |
+
arr = obj.Items
|
| 29 |
+
}
|
| 30 |
+
set(arr)
|
| 31 |
+
if after != nil {
|
| 32 |
+
after()
|
| 33 |
+
}
|
| 34 |
+
h.persist(c)
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
func (h *Handler) patchStringList(c *gin.Context, target *[]string, after func()) {
|
| 38 |
+
var body struct {
|
| 39 |
+
Old *string `json:"old"`
|
| 40 |
+
New *string `json:"new"`
|
| 41 |
+
Index *int `json:"index"`
|
| 42 |
+
Value *string `json:"value"`
|
| 43 |
+
}
|
| 44 |
+
if err := c.ShouldBindJSON(&body); err != nil {
|
| 45 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 46 |
+
return
|
| 47 |
+
}
|
| 48 |
+
if body.Index != nil && body.Value != nil && *body.Index >= 0 && *body.Index < len(*target) {
|
| 49 |
+
(*target)[*body.Index] = *body.Value
|
| 50 |
+
if after != nil {
|
| 51 |
+
after()
|
| 52 |
+
}
|
| 53 |
+
h.persist(c)
|
| 54 |
+
return
|
| 55 |
+
}
|
| 56 |
+
if body.Old != nil && body.New != nil {
|
| 57 |
+
for i := range *target {
|
| 58 |
+
if (*target)[i] == *body.Old {
|
| 59 |
+
(*target)[i] = *body.New
|
| 60 |
+
if after != nil {
|
| 61 |
+
after()
|
| 62 |
+
}
|
| 63 |
+
h.persist(c)
|
| 64 |
+
return
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
*target = append(*target, *body.New)
|
| 68 |
+
if after != nil {
|
| 69 |
+
after()
|
| 70 |
+
}
|
| 71 |
+
h.persist(c)
|
| 72 |
+
return
|
| 73 |
+
}
|
| 74 |
+
c.JSON(400, gin.H{"error": "missing fields"})
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
func (h *Handler) deleteFromStringList(c *gin.Context, target *[]string, after func()) {
|
| 78 |
+
if idxStr := c.Query("index"); idxStr != "" {
|
| 79 |
+
var idx int
|
| 80 |
+
_, err := fmt.Sscanf(idxStr, "%d", &idx)
|
| 81 |
+
if err == nil && idx >= 0 && idx < len(*target) {
|
| 82 |
+
*target = append((*target)[:idx], (*target)[idx+1:]...)
|
| 83 |
+
if after != nil {
|
| 84 |
+
after()
|
| 85 |
+
}
|
| 86 |
+
h.persist(c)
|
| 87 |
+
return
|
| 88 |
+
}
|
| 89 |
+
}
|
| 90 |
+
if val := strings.TrimSpace(c.Query("value")); val != "" {
|
| 91 |
+
out := make([]string, 0, len(*target))
|
| 92 |
+
for _, v := range *target {
|
| 93 |
+
if strings.TrimSpace(v) != val {
|
| 94 |
+
out = append(out, v)
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
*target = out
|
| 98 |
+
if after != nil {
|
| 99 |
+
after()
|
| 100 |
+
}
|
| 101 |
+
h.persist(c)
|
| 102 |
+
return
|
| 103 |
+
}
|
| 104 |
+
c.JSON(400, gin.H{"error": "missing index or value"})
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// api-keys
|
| 108 |
+
func (h *Handler) GetAPIKeys(c *gin.Context) { c.JSON(200, gin.H{"api-keys": h.cfg.APIKeys}) }
|
| 109 |
+
func (h *Handler) PutAPIKeys(c *gin.Context) {
|
| 110 |
+
h.putStringList(c, func(v []string) {
|
| 111 |
+
h.cfg.APIKeys = append([]string(nil), v...)
|
| 112 |
+
}, nil)
|
| 113 |
+
}
|
| 114 |
+
func (h *Handler) PatchAPIKeys(c *gin.Context) {
|
| 115 |
+
h.patchStringList(c, &h.cfg.APIKeys, func() {})
|
| 116 |
+
}
|
| 117 |
+
func (h *Handler) DeleteAPIKeys(c *gin.Context) {
|
| 118 |
+
h.deleteFromStringList(c, &h.cfg.APIKeys, func() {})
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
// gemini-api-key: []GeminiKey
|
| 122 |
+
func (h *Handler) GetGeminiKeys(c *gin.Context) {
|
| 123 |
+
c.JSON(200, gin.H{"gemini-api-key": h.geminiKeysWithAuthIndex()})
|
| 124 |
+
}
|
| 125 |
+
func (h *Handler) PutGeminiKeys(c *gin.Context) {
|
| 126 |
+
data, err := c.GetRawData()
|
| 127 |
+
if err != nil {
|
| 128 |
+
c.JSON(400, gin.H{"error": "failed to read body"})
|
| 129 |
+
return
|
| 130 |
+
}
|
| 131 |
+
var arr []config.GeminiKey
|
| 132 |
+
if err = json.Unmarshal(data, &arr); err != nil {
|
| 133 |
+
var obj struct {
|
| 134 |
+
Items []config.GeminiKey `json:"items"`
|
| 135 |
+
}
|
| 136 |
+
if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 {
|
| 137 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 138 |
+
return
|
| 139 |
+
}
|
| 140 |
+
arr = obj.Items
|
| 141 |
+
}
|
| 142 |
+
h.mu.Lock()
|
| 143 |
+
defer h.mu.Unlock()
|
| 144 |
+
h.cfg.GeminiKey = append([]config.GeminiKey(nil), arr...)
|
| 145 |
+
h.cfg.SanitizeGeminiKeys()
|
| 146 |
+
h.persistLocked(c)
|
| 147 |
+
}
|
| 148 |
+
func (h *Handler) PatchGeminiKey(c *gin.Context) {
|
| 149 |
+
type geminiKeyPatch struct {
|
| 150 |
+
APIKey *string `json:"api-key"`
|
| 151 |
+
Prefix *string `json:"prefix"`
|
| 152 |
+
BaseURL *string `json:"base-url"`
|
| 153 |
+
ProxyURL *string `json:"proxy-url"`
|
| 154 |
+
Headers *map[string]string `json:"headers"`
|
| 155 |
+
ExcludedModels *[]string `json:"excluded-models"`
|
| 156 |
+
}
|
| 157 |
+
var body struct {
|
| 158 |
+
Index *int `json:"index"`
|
| 159 |
+
Match *string `json:"match"`
|
| 160 |
+
Value *geminiKeyPatch `json:"value"`
|
| 161 |
+
}
|
| 162 |
+
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
|
| 163 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 164 |
+
return
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
h.mu.Lock()
|
| 168 |
+
defer h.mu.Unlock()
|
| 169 |
+
targetIndex := -1
|
| 170 |
+
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.GeminiKey) {
|
| 171 |
+
targetIndex = *body.Index
|
| 172 |
+
}
|
| 173 |
+
if targetIndex == -1 && body.Match != nil {
|
| 174 |
+
match := strings.TrimSpace(*body.Match)
|
| 175 |
+
if match != "" {
|
| 176 |
+
for i := range h.cfg.GeminiKey {
|
| 177 |
+
if h.cfg.GeminiKey[i].APIKey == match {
|
| 178 |
+
targetIndex = i
|
| 179 |
+
break
|
| 180 |
+
}
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
}
|
| 184 |
+
if targetIndex == -1 {
|
| 185 |
+
c.JSON(404, gin.H{"error": "item not found"})
|
| 186 |
+
return
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
entry := h.cfg.GeminiKey[targetIndex]
|
| 190 |
+
if body.Value.APIKey != nil {
|
| 191 |
+
trimmed := strings.TrimSpace(*body.Value.APIKey)
|
| 192 |
+
if trimmed == "" {
|
| 193 |
+
h.cfg.GeminiKey = append(h.cfg.GeminiKey[:targetIndex], h.cfg.GeminiKey[targetIndex+1:]...)
|
| 194 |
+
h.cfg.SanitizeGeminiKeys()
|
| 195 |
+
h.persistLocked(c)
|
| 196 |
+
return
|
| 197 |
+
}
|
| 198 |
+
entry.APIKey = trimmed
|
| 199 |
+
}
|
| 200 |
+
if body.Value.Prefix != nil {
|
| 201 |
+
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
|
| 202 |
+
}
|
| 203 |
+
if body.Value.BaseURL != nil {
|
| 204 |
+
entry.BaseURL = strings.TrimSpace(*body.Value.BaseURL)
|
| 205 |
+
}
|
| 206 |
+
if body.Value.ProxyURL != nil {
|
| 207 |
+
entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL)
|
| 208 |
+
}
|
| 209 |
+
if body.Value.Headers != nil {
|
| 210 |
+
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
|
| 211 |
+
}
|
| 212 |
+
if body.Value.ExcludedModels != nil {
|
| 213 |
+
entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels)
|
| 214 |
+
}
|
| 215 |
+
h.cfg.GeminiKey[targetIndex] = entry
|
| 216 |
+
h.cfg.SanitizeGeminiKeys()
|
| 217 |
+
h.persistLocked(c)
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
func (h *Handler) DeleteGeminiKey(c *gin.Context) {
|
| 221 |
+
h.mu.Lock()
|
| 222 |
+
defer h.mu.Unlock()
|
| 223 |
+
if val := strings.TrimSpace(c.Query("api-key")); val != "" {
|
| 224 |
+
if baseRaw, okBase := c.GetQuery("base-url"); okBase {
|
| 225 |
+
base := strings.TrimSpace(baseRaw)
|
| 226 |
+
out := make([]config.GeminiKey, 0, len(h.cfg.GeminiKey))
|
| 227 |
+
for _, v := range h.cfg.GeminiKey {
|
| 228 |
+
if strings.TrimSpace(v.APIKey) == val && strings.TrimSpace(v.BaseURL) == base {
|
| 229 |
+
continue
|
| 230 |
+
}
|
| 231 |
+
out = append(out, v)
|
| 232 |
+
}
|
| 233 |
+
if len(out) != len(h.cfg.GeminiKey) {
|
| 234 |
+
h.cfg.GeminiKey = out
|
| 235 |
+
h.cfg.SanitizeGeminiKeys()
|
| 236 |
+
h.persistLocked(c)
|
| 237 |
+
} else {
|
| 238 |
+
c.JSON(404, gin.H{"error": "item not found"})
|
| 239 |
+
}
|
| 240 |
+
return
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
matchIndex := -1
|
| 244 |
+
matchCount := 0
|
| 245 |
+
for i := range h.cfg.GeminiKey {
|
| 246 |
+
if strings.TrimSpace(h.cfg.GeminiKey[i].APIKey) == val {
|
| 247 |
+
matchCount++
|
| 248 |
+
if matchIndex == -1 {
|
| 249 |
+
matchIndex = i
|
| 250 |
+
}
|
| 251 |
+
}
|
| 252 |
+
}
|
| 253 |
+
if matchCount == 0 {
|
| 254 |
+
c.JSON(404, gin.H{"error": "item not found"})
|
| 255 |
+
return
|
| 256 |
+
}
|
| 257 |
+
if matchCount > 1 {
|
| 258 |
+
c.JSON(400, gin.H{"error": "multiple items match api-key; base-url is required"})
|
| 259 |
+
return
|
| 260 |
+
}
|
| 261 |
+
h.cfg.GeminiKey = append(h.cfg.GeminiKey[:matchIndex], h.cfg.GeminiKey[matchIndex+1:]...)
|
| 262 |
+
h.cfg.SanitizeGeminiKeys()
|
| 263 |
+
h.persistLocked(c)
|
| 264 |
+
return
|
| 265 |
+
}
|
| 266 |
+
if idxStr := c.Query("index"); idxStr != "" {
|
| 267 |
+
var idx int
|
| 268 |
+
if _, err := fmt.Sscanf(idxStr, "%d", &idx); err == nil && idx >= 0 && idx < len(h.cfg.GeminiKey) {
|
| 269 |
+
h.cfg.GeminiKey = append(h.cfg.GeminiKey[:idx], h.cfg.GeminiKey[idx+1:]...)
|
| 270 |
+
h.cfg.SanitizeGeminiKeys()
|
| 271 |
+
h.persistLocked(c)
|
| 272 |
+
return
|
| 273 |
+
}
|
| 274 |
+
}
|
| 275 |
+
c.JSON(400, gin.H{"error": "missing api-key or index"})
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
// interactions-api-key: []GeminiKey
|
| 279 |
+
func (h *Handler) GetInteractionsKeys(c *gin.Context) {
|
| 280 |
+
c.JSON(200, gin.H{"interactions-api-key": h.interactionsKeysWithAuthIndex()})
|
| 281 |
+
}
|
| 282 |
+
func (h *Handler) PutInteractionsKeys(c *gin.Context) {
|
| 283 |
+
data, errRead := c.GetRawData()
|
| 284 |
+
if errRead != nil {
|
| 285 |
+
c.JSON(400, gin.H{"error": "failed to read body"})
|
| 286 |
+
return
|
| 287 |
+
}
|
| 288 |
+
var arr []config.GeminiKey
|
| 289 |
+
errUnmarshal := json.Unmarshal(data, &arr)
|
| 290 |
+
if errUnmarshal != nil {
|
| 291 |
+
var obj struct {
|
| 292 |
+
Items []config.GeminiKey `json:"items"`
|
| 293 |
+
}
|
| 294 |
+
errObjUnmarshal := json.Unmarshal(data, &obj)
|
| 295 |
+
if errObjUnmarshal != nil || len(obj.Items) == 0 {
|
| 296 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 297 |
+
return
|
| 298 |
+
}
|
| 299 |
+
arr = obj.Items
|
| 300 |
+
}
|
| 301 |
+
h.mu.Lock()
|
| 302 |
+
defer h.mu.Unlock()
|
| 303 |
+
h.cfg.InteractionsKey = append([]config.GeminiKey(nil), arr...)
|
| 304 |
+
h.cfg.SanitizeInteractionsKeys()
|
| 305 |
+
h.persistLocked(c)
|
| 306 |
+
}
|
| 307 |
+
func (h *Handler) PatchInteractionsKey(c *gin.Context) {
|
| 308 |
+
type geminiKeyPatch struct {
|
| 309 |
+
APIKey *string `json:"api-key"`
|
| 310 |
+
Prefix *string `json:"prefix"`
|
| 311 |
+
BaseURL *string `json:"base-url"`
|
| 312 |
+
ProxyURL *string `json:"proxy-url"`
|
| 313 |
+
Headers *map[string]string `json:"headers"`
|
| 314 |
+
ExcludedModels *[]string `json:"excluded-models"`
|
| 315 |
+
}
|
| 316 |
+
var body struct {
|
| 317 |
+
Index *int `json:"index"`
|
| 318 |
+
Match *string `json:"match"`
|
| 319 |
+
Value *geminiKeyPatch `json:"value"`
|
| 320 |
+
}
|
| 321 |
+
errBind := c.ShouldBindJSON(&body)
|
| 322 |
+
if errBind != nil || body.Value == nil {
|
| 323 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 324 |
+
return
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
h.mu.Lock()
|
| 328 |
+
defer h.mu.Unlock()
|
| 329 |
+
targetIndex := -1
|
| 330 |
+
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.InteractionsKey) {
|
| 331 |
+
targetIndex = *body.Index
|
| 332 |
+
}
|
| 333 |
+
if targetIndex == -1 && body.Match != nil {
|
| 334 |
+
match := strings.TrimSpace(*body.Match)
|
| 335 |
+
if match != "" {
|
| 336 |
+
for i := range h.cfg.InteractionsKey {
|
| 337 |
+
if h.cfg.InteractionsKey[i].APIKey == match {
|
| 338 |
+
targetIndex = i
|
| 339 |
+
break
|
| 340 |
+
}
|
| 341 |
+
}
|
| 342 |
+
}
|
| 343 |
+
}
|
| 344 |
+
if targetIndex == -1 {
|
| 345 |
+
c.JSON(404, gin.H{"error": "item not found"})
|
| 346 |
+
return
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
entry := h.cfg.InteractionsKey[targetIndex]
|
| 350 |
+
if body.Value.APIKey != nil {
|
| 351 |
+
trimmed := strings.TrimSpace(*body.Value.APIKey)
|
| 352 |
+
if trimmed == "" {
|
| 353 |
+
h.cfg.InteractionsKey = append(h.cfg.InteractionsKey[:targetIndex], h.cfg.InteractionsKey[targetIndex+1:]...)
|
| 354 |
+
h.cfg.SanitizeInteractionsKeys()
|
| 355 |
+
h.persistLocked(c)
|
| 356 |
+
return
|
| 357 |
+
}
|
| 358 |
+
entry.APIKey = trimmed
|
| 359 |
+
}
|
| 360 |
+
if body.Value.Prefix != nil {
|
| 361 |
+
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
|
| 362 |
+
}
|
| 363 |
+
if body.Value.BaseURL != nil {
|
| 364 |
+
entry.BaseURL = strings.TrimSpace(*body.Value.BaseURL)
|
| 365 |
+
}
|
| 366 |
+
if body.Value.ProxyURL != nil {
|
| 367 |
+
entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL)
|
| 368 |
+
}
|
| 369 |
+
if body.Value.Headers != nil {
|
| 370 |
+
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
|
| 371 |
+
}
|
| 372 |
+
if body.Value.ExcludedModels != nil {
|
| 373 |
+
entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels)
|
| 374 |
+
}
|
| 375 |
+
h.cfg.InteractionsKey[targetIndex] = entry
|
| 376 |
+
h.cfg.SanitizeInteractionsKeys()
|
| 377 |
+
h.persistLocked(c)
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
func (h *Handler) DeleteInteractionsKey(c *gin.Context) {
|
| 381 |
+
h.mu.Lock()
|
| 382 |
+
defer h.mu.Unlock()
|
| 383 |
+
if val := strings.TrimSpace(c.Query("api-key")); val != "" {
|
| 384 |
+
if baseRaw, okBase := c.GetQuery("base-url"); okBase {
|
| 385 |
+
base := strings.TrimSpace(baseRaw)
|
| 386 |
+
out := make([]config.GeminiKey, 0, len(h.cfg.InteractionsKey))
|
| 387 |
+
for _, v := range h.cfg.InteractionsKey {
|
| 388 |
+
if strings.TrimSpace(v.APIKey) == val && strings.TrimSpace(v.BaseURL) == base {
|
| 389 |
+
continue
|
| 390 |
+
}
|
| 391 |
+
out = append(out, v)
|
| 392 |
+
}
|
| 393 |
+
if len(out) != len(h.cfg.InteractionsKey) {
|
| 394 |
+
h.cfg.InteractionsKey = out
|
| 395 |
+
h.cfg.SanitizeInteractionsKeys()
|
| 396 |
+
h.persistLocked(c)
|
| 397 |
+
} else {
|
| 398 |
+
c.JSON(404, gin.H{"error": "item not found"})
|
| 399 |
+
}
|
| 400 |
+
return
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
matchIndex := -1
|
| 404 |
+
matchCount := 0
|
| 405 |
+
for i := range h.cfg.InteractionsKey {
|
| 406 |
+
if strings.TrimSpace(h.cfg.InteractionsKey[i].APIKey) == val {
|
| 407 |
+
matchCount++
|
| 408 |
+
if matchIndex == -1 {
|
| 409 |
+
matchIndex = i
|
| 410 |
+
}
|
| 411 |
+
}
|
| 412 |
+
}
|
| 413 |
+
if matchCount == 0 {
|
| 414 |
+
c.JSON(404, gin.H{"error": "item not found"})
|
| 415 |
+
return
|
| 416 |
+
}
|
| 417 |
+
if matchCount > 1 {
|
| 418 |
+
c.JSON(400, gin.H{"error": "multiple items match api-key; base-url is required"})
|
| 419 |
+
return
|
| 420 |
+
}
|
| 421 |
+
h.cfg.InteractionsKey = append(h.cfg.InteractionsKey[:matchIndex], h.cfg.InteractionsKey[matchIndex+1:]...)
|
| 422 |
+
h.cfg.SanitizeInteractionsKeys()
|
| 423 |
+
h.persistLocked(c)
|
| 424 |
+
return
|
| 425 |
+
}
|
| 426 |
+
if idxStr := c.Query("index"); idxStr != "" {
|
| 427 |
+
var idx int
|
| 428 |
+
_, errScan := fmt.Sscanf(idxStr, "%d", &idx)
|
| 429 |
+
if errScan == nil && idx >= 0 && idx < len(h.cfg.InteractionsKey) {
|
| 430 |
+
h.cfg.InteractionsKey = append(h.cfg.InteractionsKey[:idx], h.cfg.InteractionsKey[idx+1:]...)
|
| 431 |
+
h.cfg.SanitizeInteractionsKeys()
|
| 432 |
+
h.persistLocked(c)
|
| 433 |
+
return
|
| 434 |
+
}
|
| 435 |
+
}
|
| 436 |
+
c.JSON(400, gin.H{"error": "missing api-key or index"})
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
// claude-api-key: []ClaudeKey
|
| 440 |
+
func (h *Handler) GetClaudeKeys(c *gin.Context) {
|
| 441 |
+
c.JSON(200, gin.H{"claude-api-key": h.claudeKeysWithAuthIndex()})
|
| 442 |
+
}
|
| 443 |
+
func (h *Handler) PutClaudeKeys(c *gin.Context) {
|
| 444 |
+
data, err := c.GetRawData()
|
| 445 |
+
if err != nil {
|
| 446 |
+
c.JSON(400, gin.H{"error": "failed to read body"})
|
| 447 |
+
return
|
| 448 |
+
}
|
| 449 |
+
var arr []config.ClaudeKey
|
| 450 |
+
if err = json.Unmarshal(data, &arr); err != nil {
|
| 451 |
+
var obj struct {
|
| 452 |
+
Items []config.ClaudeKey `json:"items"`
|
| 453 |
+
}
|
| 454 |
+
if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 {
|
| 455 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 456 |
+
return
|
| 457 |
+
}
|
| 458 |
+
arr = obj.Items
|
| 459 |
+
}
|
| 460 |
+
for i := range arr {
|
| 461 |
+
normalizeClaudeKey(&arr[i])
|
| 462 |
+
}
|
| 463 |
+
h.mu.Lock()
|
| 464 |
+
defer h.mu.Unlock()
|
| 465 |
+
h.cfg.ClaudeKey = arr
|
| 466 |
+
h.cfg.SanitizeClaudeKeys()
|
| 467 |
+
h.persistLocked(c)
|
| 468 |
+
}
|
| 469 |
+
func (h *Handler) PatchClaudeKey(c *gin.Context) {
|
| 470 |
+
type claudeKeyPatch struct {
|
| 471 |
+
APIKey *string `json:"api-key"`
|
| 472 |
+
Prefix *string `json:"prefix"`
|
| 473 |
+
BaseURL *string `json:"base-url"`
|
| 474 |
+
ProxyURL *string `json:"proxy-url"`
|
| 475 |
+
Models *[]config.ClaudeModel `json:"models"`
|
| 476 |
+
Headers *map[string]string `json:"headers"`
|
| 477 |
+
ExcludedModels *[]string `json:"excluded-models"`
|
| 478 |
+
RebuildMidSystemMessage *bool `json:"rebuild-mid-system-message"`
|
| 479 |
+
}
|
| 480 |
+
var body struct {
|
| 481 |
+
Index *int `json:"index"`
|
| 482 |
+
Match *string `json:"match"`
|
| 483 |
+
Value *claudeKeyPatch `json:"value"`
|
| 484 |
+
}
|
| 485 |
+
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
|
| 486 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 487 |
+
return
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
h.mu.Lock()
|
| 491 |
+
defer h.mu.Unlock()
|
| 492 |
+
targetIndex := -1
|
| 493 |
+
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.ClaudeKey) {
|
| 494 |
+
targetIndex = *body.Index
|
| 495 |
+
}
|
| 496 |
+
if targetIndex == -1 && body.Match != nil {
|
| 497 |
+
match := strings.TrimSpace(*body.Match)
|
| 498 |
+
for i := range h.cfg.ClaudeKey {
|
| 499 |
+
if h.cfg.ClaudeKey[i].APIKey == match {
|
| 500 |
+
targetIndex = i
|
| 501 |
+
break
|
| 502 |
+
}
|
| 503 |
+
}
|
| 504 |
+
}
|
| 505 |
+
if targetIndex == -1 {
|
| 506 |
+
c.JSON(404, gin.H{"error": "item not found"})
|
| 507 |
+
return
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
entry := h.cfg.ClaudeKey[targetIndex]
|
| 511 |
+
if body.Value.APIKey != nil {
|
| 512 |
+
entry.APIKey = strings.TrimSpace(*body.Value.APIKey)
|
| 513 |
+
}
|
| 514 |
+
if body.Value.Prefix != nil {
|
| 515 |
+
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
|
| 516 |
+
}
|
| 517 |
+
if body.Value.BaseURL != nil {
|
| 518 |
+
entry.BaseURL = strings.TrimSpace(*body.Value.BaseURL)
|
| 519 |
+
}
|
| 520 |
+
if body.Value.ProxyURL != nil {
|
| 521 |
+
entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL)
|
| 522 |
+
}
|
| 523 |
+
if body.Value.Models != nil {
|
| 524 |
+
entry.Models = append([]config.ClaudeModel(nil), (*body.Value.Models)...)
|
| 525 |
+
}
|
| 526 |
+
if body.Value.Headers != nil {
|
| 527 |
+
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
|
| 528 |
+
}
|
| 529 |
+
if body.Value.ExcludedModels != nil {
|
| 530 |
+
entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels)
|
| 531 |
+
}
|
| 532 |
+
if body.Value.RebuildMidSystemMessage != nil {
|
| 533 |
+
entry.RebuildMidSystemMessage = *body.Value.RebuildMidSystemMessage
|
| 534 |
+
}
|
| 535 |
+
normalizeClaudeKey(&entry)
|
| 536 |
+
h.cfg.ClaudeKey[targetIndex] = entry
|
| 537 |
+
h.cfg.SanitizeClaudeKeys()
|
| 538 |
+
h.persistLocked(c)
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
func (h *Handler) DeleteClaudeKey(c *gin.Context) {
|
| 542 |
+
h.mu.Lock()
|
| 543 |
+
defer h.mu.Unlock()
|
| 544 |
+
if val := strings.TrimSpace(c.Query("api-key")); val != "" {
|
| 545 |
+
if baseRaw, okBase := c.GetQuery("base-url"); okBase {
|
| 546 |
+
base := strings.TrimSpace(baseRaw)
|
| 547 |
+
out := make([]config.ClaudeKey, 0, len(h.cfg.ClaudeKey))
|
| 548 |
+
for _, v := range h.cfg.ClaudeKey {
|
| 549 |
+
if strings.TrimSpace(v.APIKey) == val && strings.TrimSpace(v.BaseURL) == base {
|
| 550 |
+
continue
|
| 551 |
+
}
|
| 552 |
+
out = append(out, v)
|
| 553 |
+
}
|
| 554 |
+
h.cfg.ClaudeKey = out
|
| 555 |
+
h.cfg.SanitizeClaudeKeys()
|
| 556 |
+
h.persistLocked(c)
|
| 557 |
+
return
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
matchIndex := -1
|
| 561 |
+
matchCount := 0
|
| 562 |
+
for i := range h.cfg.ClaudeKey {
|
| 563 |
+
if strings.TrimSpace(h.cfg.ClaudeKey[i].APIKey) == val {
|
| 564 |
+
matchCount++
|
| 565 |
+
if matchIndex == -1 {
|
| 566 |
+
matchIndex = i
|
| 567 |
+
}
|
| 568 |
+
}
|
| 569 |
+
}
|
| 570 |
+
if matchCount > 1 {
|
| 571 |
+
c.JSON(400, gin.H{"error": "multiple items match api-key; base-url is required"})
|
| 572 |
+
return
|
| 573 |
+
}
|
| 574 |
+
if matchIndex != -1 {
|
| 575 |
+
h.cfg.ClaudeKey = append(h.cfg.ClaudeKey[:matchIndex], h.cfg.ClaudeKey[matchIndex+1:]...)
|
| 576 |
+
}
|
| 577 |
+
h.cfg.SanitizeClaudeKeys()
|
| 578 |
+
h.persistLocked(c)
|
| 579 |
+
return
|
| 580 |
+
}
|
| 581 |
+
if idxStr := c.Query("index"); idxStr != "" {
|
| 582 |
+
var idx int
|
| 583 |
+
_, err := fmt.Sscanf(idxStr, "%d", &idx)
|
| 584 |
+
if err == nil && idx >= 0 && idx < len(h.cfg.ClaudeKey) {
|
| 585 |
+
h.cfg.ClaudeKey = append(h.cfg.ClaudeKey[:idx], h.cfg.ClaudeKey[idx+1:]...)
|
| 586 |
+
h.cfg.SanitizeClaudeKeys()
|
| 587 |
+
h.persistLocked(c)
|
| 588 |
+
return
|
| 589 |
+
}
|
| 590 |
+
}
|
| 591 |
+
c.JSON(400, gin.H{"error": "missing api-key or index"})
|
| 592 |
+
}
|
| 593 |
+
|
| 594 |
+
// openai-compatibility: []OpenAICompatibility
|
| 595 |
+
func (h *Handler) GetOpenAICompat(c *gin.Context) {
|
| 596 |
+
c.JSON(200, gin.H{"openai-compatibility": h.openAICompatibilityWithAuthIndex()})
|
| 597 |
+
}
|
| 598 |
+
func (h *Handler) PutOpenAICompat(c *gin.Context) {
|
| 599 |
+
data, err := c.GetRawData()
|
| 600 |
+
if err != nil {
|
| 601 |
+
c.JSON(400, gin.H{"error": "failed to read body"})
|
| 602 |
+
return
|
| 603 |
+
}
|
| 604 |
+
var arr []config.OpenAICompatibility
|
| 605 |
+
if err = json.Unmarshal(data, &arr); err != nil {
|
| 606 |
+
var obj struct {
|
| 607 |
+
Items []config.OpenAICompatibility `json:"items"`
|
| 608 |
+
}
|
| 609 |
+
if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 {
|
| 610 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 611 |
+
return
|
| 612 |
+
}
|
| 613 |
+
arr = obj.Items
|
| 614 |
+
}
|
| 615 |
+
filtered := make([]config.OpenAICompatibility, 0, len(arr))
|
| 616 |
+
for i := range arr {
|
| 617 |
+
normalizeOpenAICompatibilityEntry(&arr[i])
|
| 618 |
+
if strings.TrimSpace(arr[i].BaseURL) != "" {
|
| 619 |
+
filtered = append(filtered, arr[i])
|
| 620 |
+
}
|
| 621 |
+
}
|
| 622 |
+
h.mu.Lock()
|
| 623 |
+
defer h.mu.Unlock()
|
| 624 |
+
h.cfg.OpenAICompatibility = filtered
|
| 625 |
+
h.cfg.SanitizeOpenAICompatibility()
|
| 626 |
+
h.persistLocked(c)
|
| 627 |
+
}
|
| 628 |
+
func (h *Handler) PatchOpenAICompat(c *gin.Context) {
|
| 629 |
+
type openAICompatPatch struct {
|
| 630 |
+
Name *string `json:"name"`
|
| 631 |
+
Prefix *string `json:"prefix"`
|
| 632 |
+
Disabled *bool `json:"disabled"`
|
| 633 |
+
DisableCooling *bool `json:"disable-cooling"`
|
| 634 |
+
BaseURL *string `json:"base-url"`
|
| 635 |
+
APIKeyEntries *[]config.OpenAICompatibilityAPIKey `json:"api-key-entries"`
|
| 636 |
+
Models *[]config.OpenAICompatibilityModel `json:"models"`
|
| 637 |
+
Headers *map[string]string `json:"headers"`
|
| 638 |
+
}
|
| 639 |
+
var body struct {
|
| 640 |
+
Name *string `json:"name"`
|
| 641 |
+
Index *int `json:"index"`
|
| 642 |
+
Value *openAICompatPatch `json:"value"`
|
| 643 |
+
}
|
| 644 |
+
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
|
| 645 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 646 |
+
return
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
h.mu.Lock()
|
| 650 |
+
defer h.mu.Unlock()
|
| 651 |
+
targetIndex := -1
|
| 652 |
+
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.OpenAICompatibility) {
|
| 653 |
+
targetIndex = *body.Index
|
| 654 |
+
}
|
| 655 |
+
if targetIndex == -1 && body.Name != nil {
|
| 656 |
+
match := strings.TrimSpace(*body.Name)
|
| 657 |
+
for i := range h.cfg.OpenAICompatibility {
|
| 658 |
+
if h.cfg.OpenAICompatibility[i].Name == match {
|
| 659 |
+
targetIndex = i
|
| 660 |
+
break
|
| 661 |
+
}
|
| 662 |
+
}
|
| 663 |
+
}
|
| 664 |
+
if targetIndex == -1 {
|
| 665 |
+
c.JSON(404, gin.H{"error": "item not found"})
|
| 666 |
+
return
|
| 667 |
+
}
|
| 668 |
+
|
| 669 |
+
entry := h.cfg.OpenAICompatibility[targetIndex]
|
| 670 |
+
if body.Value.Name != nil {
|
| 671 |
+
entry.Name = strings.TrimSpace(*body.Value.Name)
|
| 672 |
+
}
|
| 673 |
+
if body.Value.Prefix != nil {
|
| 674 |
+
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
|
| 675 |
+
}
|
| 676 |
+
if body.Value.Disabled != nil {
|
| 677 |
+
entry.Disabled = *body.Value.Disabled
|
| 678 |
+
}
|
| 679 |
+
if body.Value.DisableCooling != nil {
|
| 680 |
+
entry.DisableCooling = *body.Value.DisableCooling
|
| 681 |
+
}
|
| 682 |
+
if body.Value.BaseURL != nil {
|
| 683 |
+
trimmed := strings.TrimSpace(*body.Value.BaseURL)
|
| 684 |
+
if trimmed == "" {
|
| 685 |
+
h.cfg.OpenAICompatibility = append(h.cfg.OpenAICompatibility[:targetIndex], h.cfg.OpenAICompatibility[targetIndex+1:]...)
|
| 686 |
+
h.cfg.SanitizeOpenAICompatibility()
|
| 687 |
+
h.persistLocked(c)
|
| 688 |
+
return
|
| 689 |
+
}
|
| 690 |
+
entry.BaseURL = trimmed
|
| 691 |
+
}
|
| 692 |
+
if body.Value.APIKeyEntries != nil {
|
| 693 |
+
entry.APIKeyEntries = append([]config.OpenAICompatibilityAPIKey(nil), (*body.Value.APIKeyEntries)...)
|
| 694 |
+
}
|
| 695 |
+
if body.Value.Models != nil {
|
| 696 |
+
entry.Models = append([]config.OpenAICompatibilityModel(nil), (*body.Value.Models)...)
|
| 697 |
+
}
|
| 698 |
+
if body.Value.Headers != nil {
|
| 699 |
+
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
|
| 700 |
+
}
|
| 701 |
+
normalizeOpenAICompatibilityEntry(&entry)
|
| 702 |
+
h.cfg.OpenAICompatibility[targetIndex] = entry
|
| 703 |
+
h.cfg.SanitizeOpenAICompatibility()
|
| 704 |
+
h.persistLocked(c)
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
func (h *Handler) DeleteOpenAICompat(c *gin.Context) {
|
| 708 |
+
h.mu.Lock()
|
| 709 |
+
defer h.mu.Unlock()
|
| 710 |
+
if name := c.Query("name"); name != "" {
|
| 711 |
+
out := make([]config.OpenAICompatibility, 0, len(h.cfg.OpenAICompatibility))
|
| 712 |
+
for _, v := range h.cfg.OpenAICompatibility {
|
| 713 |
+
if v.Name != name {
|
| 714 |
+
out = append(out, v)
|
| 715 |
+
}
|
| 716 |
+
}
|
| 717 |
+
h.cfg.OpenAICompatibility = out
|
| 718 |
+
h.cfg.SanitizeOpenAICompatibility()
|
| 719 |
+
h.persistLocked(c)
|
| 720 |
+
return
|
| 721 |
+
}
|
| 722 |
+
if idxStr := c.Query("index"); idxStr != "" {
|
| 723 |
+
var idx int
|
| 724 |
+
_, err := fmt.Sscanf(idxStr, "%d", &idx)
|
| 725 |
+
if err == nil && idx >= 0 && idx < len(h.cfg.OpenAICompatibility) {
|
| 726 |
+
h.cfg.OpenAICompatibility = append(h.cfg.OpenAICompatibility[:idx], h.cfg.OpenAICompatibility[idx+1:]...)
|
| 727 |
+
h.cfg.SanitizeOpenAICompatibility()
|
| 728 |
+
h.persistLocked(c)
|
| 729 |
+
return
|
| 730 |
+
}
|
| 731 |
+
}
|
| 732 |
+
c.JSON(400, gin.H{"error": "missing name or index"})
|
| 733 |
+
}
|
| 734 |
+
|
| 735 |
+
// vertex-api-key: []VertexCompatKey
|
| 736 |
+
func (h *Handler) GetVertexCompatKeys(c *gin.Context) {
|
| 737 |
+
c.JSON(200, gin.H{"vertex-api-key": h.vertexCompatKeysWithAuthIndex()})
|
| 738 |
+
}
|
| 739 |
+
func (h *Handler) PutVertexCompatKeys(c *gin.Context) {
|
| 740 |
+
data, err := c.GetRawData()
|
| 741 |
+
if err != nil {
|
| 742 |
+
c.JSON(400, gin.H{"error": "failed to read body"})
|
| 743 |
+
return
|
| 744 |
+
}
|
| 745 |
+
var arr []config.VertexCompatKey
|
| 746 |
+
if err = json.Unmarshal(data, &arr); err != nil {
|
| 747 |
+
var obj struct {
|
| 748 |
+
Items []config.VertexCompatKey `json:"items"`
|
| 749 |
+
}
|
| 750 |
+
if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 {
|
| 751 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 752 |
+
return
|
| 753 |
+
}
|
| 754 |
+
arr = obj.Items
|
| 755 |
+
}
|
| 756 |
+
for i := range arr {
|
| 757 |
+
normalizeVertexCompatKey(&arr[i])
|
| 758 |
+
if arr[i].APIKey == "" {
|
| 759 |
+
c.JSON(400, gin.H{"error": fmt.Sprintf("vertex-api-key[%d].api-key is required", i)})
|
| 760 |
+
return
|
| 761 |
+
}
|
| 762 |
+
}
|
| 763 |
+
h.mu.Lock()
|
| 764 |
+
defer h.mu.Unlock()
|
| 765 |
+
h.cfg.VertexCompatAPIKey = append([]config.VertexCompatKey(nil), arr...)
|
| 766 |
+
h.cfg.SanitizeVertexCompatKeys()
|
| 767 |
+
h.persistLocked(c)
|
| 768 |
+
}
|
| 769 |
+
func (h *Handler) PatchVertexCompatKey(c *gin.Context) {
|
| 770 |
+
type vertexCompatPatch struct {
|
| 771 |
+
APIKey *string `json:"api-key"`
|
| 772 |
+
Prefix *string `json:"prefix"`
|
| 773 |
+
BaseURL *string `json:"base-url"`
|
| 774 |
+
ProxyURL *string `json:"proxy-url"`
|
| 775 |
+
Headers *map[string]string `json:"headers"`
|
| 776 |
+
Models *[]config.VertexCompatModel `json:"models"`
|
| 777 |
+
ExcludedModels *[]string `json:"excluded-models"`
|
| 778 |
+
}
|
| 779 |
+
var body struct {
|
| 780 |
+
Index *int `json:"index"`
|
| 781 |
+
Match *string `json:"match"`
|
| 782 |
+
Value *vertexCompatPatch `json:"value"`
|
| 783 |
+
}
|
| 784 |
+
if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil || body.Value == nil {
|
| 785 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 786 |
+
return
|
| 787 |
+
}
|
| 788 |
+
|
| 789 |
+
h.mu.Lock()
|
| 790 |
+
defer h.mu.Unlock()
|
| 791 |
+
targetIndex := -1
|
| 792 |
+
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.VertexCompatAPIKey) {
|
| 793 |
+
targetIndex = *body.Index
|
| 794 |
+
}
|
| 795 |
+
if targetIndex == -1 && body.Match != nil {
|
| 796 |
+
match := strings.TrimSpace(*body.Match)
|
| 797 |
+
if match != "" {
|
| 798 |
+
for i := range h.cfg.VertexCompatAPIKey {
|
| 799 |
+
if h.cfg.VertexCompatAPIKey[i].APIKey == match {
|
| 800 |
+
targetIndex = i
|
| 801 |
+
break
|
| 802 |
+
}
|
| 803 |
+
}
|
| 804 |
+
}
|
| 805 |
+
}
|
| 806 |
+
if targetIndex == -1 {
|
| 807 |
+
c.JSON(404, gin.H{"error": "item not found"})
|
| 808 |
+
return
|
| 809 |
+
}
|
| 810 |
+
|
| 811 |
+
entry := h.cfg.VertexCompatAPIKey[targetIndex]
|
| 812 |
+
if body.Value.APIKey != nil {
|
| 813 |
+
trimmed := strings.TrimSpace(*body.Value.APIKey)
|
| 814 |
+
if trimmed == "" {
|
| 815 |
+
h.cfg.VertexCompatAPIKey = append(h.cfg.VertexCompatAPIKey[:targetIndex], h.cfg.VertexCompatAPIKey[targetIndex+1:]...)
|
| 816 |
+
h.cfg.SanitizeVertexCompatKeys()
|
| 817 |
+
h.persistLocked(c)
|
| 818 |
+
return
|
| 819 |
+
}
|
| 820 |
+
entry.APIKey = trimmed
|
| 821 |
+
}
|
| 822 |
+
if body.Value.Prefix != nil {
|
| 823 |
+
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
|
| 824 |
+
}
|
| 825 |
+
if body.Value.BaseURL != nil {
|
| 826 |
+
trimmed := strings.TrimSpace(*body.Value.BaseURL)
|
| 827 |
+
if trimmed == "" {
|
| 828 |
+
h.cfg.VertexCompatAPIKey = append(h.cfg.VertexCompatAPIKey[:targetIndex], h.cfg.VertexCompatAPIKey[targetIndex+1:]...)
|
| 829 |
+
h.cfg.SanitizeVertexCompatKeys()
|
| 830 |
+
h.persistLocked(c)
|
| 831 |
+
return
|
| 832 |
+
}
|
| 833 |
+
entry.BaseURL = trimmed
|
| 834 |
+
}
|
| 835 |
+
if body.Value.ProxyURL != nil {
|
| 836 |
+
entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL)
|
| 837 |
+
}
|
| 838 |
+
if body.Value.Headers != nil {
|
| 839 |
+
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
|
| 840 |
+
}
|
| 841 |
+
if body.Value.Models != nil {
|
| 842 |
+
entry.Models = append([]config.VertexCompatModel(nil), (*body.Value.Models)...)
|
| 843 |
+
}
|
| 844 |
+
if body.Value.ExcludedModels != nil {
|
| 845 |
+
entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels)
|
| 846 |
+
}
|
| 847 |
+
normalizeVertexCompatKey(&entry)
|
| 848 |
+
h.cfg.VertexCompatAPIKey[targetIndex] = entry
|
| 849 |
+
h.cfg.SanitizeVertexCompatKeys()
|
| 850 |
+
h.persistLocked(c)
|
| 851 |
+
}
|
| 852 |
+
|
| 853 |
+
func (h *Handler) DeleteVertexCompatKey(c *gin.Context) {
|
| 854 |
+
h.mu.Lock()
|
| 855 |
+
defer h.mu.Unlock()
|
| 856 |
+
if val := strings.TrimSpace(c.Query("api-key")); val != "" {
|
| 857 |
+
if baseRaw, okBase := c.GetQuery("base-url"); okBase {
|
| 858 |
+
base := strings.TrimSpace(baseRaw)
|
| 859 |
+
out := make([]config.VertexCompatKey, 0, len(h.cfg.VertexCompatAPIKey))
|
| 860 |
+
for _, v := range h.cfg.VertexCompatAPIKey {
|
| 861 |
+
if strings.TrimSpace(v.APIKey) == val && strings.TrimSpace(v.BaseURL) == base {
|
| 862 |
+
continue
|
| 863 |
+
}
|
| 864 |
+
out = append(out, v)
|
| 865 |
+
}
|
| 866 |
+
h.cfg.VertexCompatAPIKey = out
|
| 867 |
+
h.cfg.SanitizeVertexCompatKeys()
|
| 868 |
+
h.persistLocked(c)
|
| 869 |
+
return
|
| 870 |
+
}
|
| 871 |
+
|
| 872 |
+
matchIndex := -1
|
| 873 |
+
matchCount := 0
|
| 874 |
+
for i := range h.cfg.VertexCompatAPIKey {
|
| 875 |
+
if strings.TrimSpace(h.cfg.VertexCompatAPIKey[i].APIKey) == val {
|
| 876 |
+
matchCount++
|
| 877 |
+
if matchIndex == -1 {
|
| 878 |
+
matchIndex = i
|
| 879 |
+
}
|
| 880 |
+
}
|
| 881 |
+
}
|
| 882 |
+
if matchCount > 1 {
|
| 883 |
+
c.JSON(400, gin.H{"error": "multiple items match api-key; base-url is required"})
|
| 884 |
+
return
|
| 885 |
+
}
|
| 886 |
+
if matchIndex != -1 {
|
| 887 |
+
h.cfg.VertexCompatAPIKey = append(h.cfg.VertexCompatAPIKey[:matchIndex], h.cfg.VertexCompatAPIKey[matchIndex+1:]...)
|
| 888 |
+
}
|
| 889 |
+
h.cfg.SanitizeVertexCompatKeys()
|
| 890 |
+
h.persistLocked(c)
|
| 891 |
+
return
|
| 892 |
+
}
|
| 893 |
+
if idxStr := c.Query("index"); idxStr != "" {
|
| 894 |
+
var idx int
|
| 895 |
+
_, errScan := fmt.Sscanf(idxStr, "%d", &idx)
|
| 896 |
+
if errScan == nil && idx >= 0 && idx < len(h.cfg.VertexCompatAPIKey) {
|
| 897 |
+
h.cfg.VertexCompatAPIKey = append(h.cfg.VertexCompatAPIKey[:idx], h.cfg.VertexCompatAPIKey[idx+1:]...)
|
| 898 |
+
h.cfg.SanitizeVertexCompatKeys()
|
| 899 |
+
h.persistLocked(c)
|
| 900 |
+
return
|
| 901 |
+
}
|
| 902 |
+
}
|
| 903 |
+
c.JSON(400, gin.H{"error": "missing api-key or index"})
|
| 904 |
+
}
|
| 905 |
+
|
| 906 |
+
// oauth-excluded-models: map[string][]string
|
| 907 |
+
func (h *Handler) GetOAuthExcludedModels(c *gin.Context) {
|
| 908 |
+
c.JSON(200, gin.H{"oauth-excluded-models": config.NormalizeOAuthExcludedModels(h.cfg.OAuthExcludedModels)})
|
| 909 |
+
}
|
| 910 |
+
|
| 911 |
+
func (h *Handler) PutOAuthExcludedModels(c *gin.Context) {
|
| 912 |
+
data, err := c.GetRawData()
|
| 913 |
+
if err != nil {
|
| 914 |
+
c.JSON(400, gin.H{"error": "failed to read body"})
|
| 915 |
+
return
|
| 916 |
+
}
|
| 917 |
+
var entries map[string][]string
|
| 918 |
+
if err = json.Unmarshal(data, &entries); err != nil {
|
| 919 |
+
var wrapper struct {
|
| 920 |
+
Items map[string][]string `json:"items"`
|
| 921 |
+
}
|
| 922 |
+
if err2 := json.Unmarshal(data, &wrapper); err2 != nil {
|
| 923 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 924 |
+
return
|
| 925 |
+
}
|
| 926 |
+
entries = wrapper.Items
|
| 927 |
+
}
|
| 928 |
+
h.cfg.OAuthExcludedModels = config.NormalizeOAuthExcludedModels(entries)
|
| 929 |
+
h.persist(c)
|
| 930 |
+
}
|
| 931 |
+
|
| 932 |
+
func (h *Handler) PatchOAuthExcludedModels(c *gin.Context) {
|
| 933 |
+
var body struct {
|
| 934 |
+
Provider *string `json:"provider"`
|
| 935 |
+
Models []string `json:"models"`
|
| 936 |
+
}
|
| 937 |
+
if err := c.ShouldBindJSON(&body); err != nil || body.Provider == nil {
|
| 938 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 939 |
+
return
|
| 940 |
+
}
|
| 941 |
+
provider := strings.ToLower(strings.TrimSpace(*body.Provider))
|
| 942 |
+
if provider == "" {
|
| 943 |
+
c.JSON(400, gin.H{"error": "invalid provider"})
|
| 944 |
+
return
|
| 945 |
+
}
|
| 946 |
+
normalized := config.NormalizeExcludedModels(body.Models)
|
| 947 |
+
if len(normalized) == 0 {
|
| 948 |
+
if h.cfg.OAuthExcludedModels == nil {
|
| 949 |
+
c.JSON(404, gin.H{"error": "provider not found"})
|
| 950 |
+
return
|
| 951 |
+
}
|
| 952 |
+
if _, ok := h.cfg.OAuthExcludedModels[provider]; !ok {
|
| 953 |
+
c.JSON(404, gin.H{"error": "provider not found"})
|
| 954 |
+
return
|
| 955 |
+
}
|
| 956 |
+
delete(h.cfg.OAuthExcludedModels, provider)
|
| 957 |
+
if len(h.cfg.OAuthExcludedModels) == 0 {
|
| 958 |
+
h.cfg.OAuthExcludedModels = nil
|
| 959 |
+
}
|
| 960 |
+
h.persist(c)
|
| 961 |
+
return
|
| 962 |
+
}
|
| 963 |
+
if h.cfg.OAuthExcludedModels == nil {
|
| 964 |
+
h.cfg.OAuthExcludedModels = make(map[string][]string)
|
| 965 |
+
}
|
| 966 |
+
h.cfg.OAuthExcludedModels[provider] = normalized
|
| 967 |
+
h.persist(c)
|
| 968 |
+
}
|
| 969 |
+
|
| 970 |
+
func (h *Handler) DeleteOAuthExcludedModels(c *gin.Context) {
|
| 971 |
+
provider := strings.ToLower(strings.TrimSpace(c.Query("provider")))
|
| 972 |
+
if provider == "" {
|
| 973 |
+
c.JSON(400, gin.H{"error": "missing provider"})
|
| 974 |
+
return
|
| 975 |
+
}
|
| 976 |
+
if h.cfg.OAuthExcludedModels == nil {
|
| 977 |
+
c.JSON(404, gin.H{"error": "provider not found"})
|
| 978 |
+
return
|
| 979 |
+
}
|
| 980 |
+
if _, ok := h.cfg.OAuthExcludedModels[provider]; !ok {
|
| 981 |
+
c.JSON(404, gin.H{"error": "provider not found"})
|
| 982 |
+
return
|
| 983 |
+
}
|
| 984 |
+
delete(h.cfg.OAuthExcludedModels, provider)
|
| 985 |
+
if len(h.cfg.OAuthExcludedModels) == 0 {
|
| 986 |
+
h.cfg.OAuthExcludedModels = nil
|
| 987 |
+
}
|
| 988 |
+
h.persist(c)
|
| 989 |
+
}
|
| 990 |
+
|
| 991 |
+
// oauth-model-alias: map[string][]OAuthModelAlias
|
| 992 |
+
func (h *Handler) GetOAuthModelAlias(c *gin.Context) {
|
| 993 |
+
c.JSON(200, gin.H{"oauth-model-alias": sanitizedOAuthModelAlias(h.cfg.OAuthModelAlias)})
|
| 994 |
+
}
|
| 995 |
+
|
| 996 |
+
func (h *Handler) PutOAuthModelAlias(c *gin.Context) {
|
| 997 |
+
data, err := c.GetRawData()
|
| 998 |
+
if err != nil {
|
| 999 |
+
c.JSON(400, gin.H{"error": "failed to read body"})
|
| 1000 |
+
return
|
| 1001 |
+
}
|
| 1002 |
+
var entries map[string][]config.OAuthModelAlias
|
| 1003 |
+
if err = json.Unmarshal(data, &entries); err != nil {
|
| 1004 |
+
var wrapper struct {
|
| 1005 |
+
Items map[string][]config.OAuthModelAlias `json:"items"`
|
| 1006 |
+
}
|
| 1007 |
+
if err2 := json.Unmarshal(data, &wrapper); err2 != nil {
|
| 1008 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 1009 |
+
return
|
| 1010 |
+
}
|
| 1011 |
+
entries = wrapper.Items
|
| 1012 |
+
}
|
| 1013 |
+
h.cfg.OAuthModelAlias = sanitizedOAuthModelAlias(entries)
|
| 1014 |
+
h.persist(c)
|
| 1015 |
+
}
|
| 1016 |
+
|
| 1017 |
+
func (h *Handler) PatchOAuthModelAlias(c *gin.Context) {
|
| 1018 |
+
var body struct {
|
| 1019 |
+
Provider *string `json:"provider"`
|
| 1020 |
+
Channel *string `json:"channel"`
|
| 1021 |
+
Aliases []config.OAuthModelAlias `json:"aliases"`
|
| 1022 |
+
}
|
| 1023 |
+
if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil {
|
| 1024 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 1025 |
+
return
|
| 1026 |
+
}
|
| 1027 |
+
channelRaw := ""
|
| 1028 |
+
if body.Channel != nil {
|
| 1029 |
+
channelRaw = *body.Channel
|
| 1030 |
+
} else if body.Provider != nil {
|
| 1031 |
+
channelRaw = *body.Provider
|
| 1032 |
+
}
|
| 1033 |
+
channel := strings.ToLower(strings.TrimSpace(channelRaw))
|
| 1034 |
+
if channel == "" {
|
| 1035 |
+
c.JSON(400, gin.H{"error": "invalid channel"})
|
| 1036 |
+
return
|
| 1037 |
+
}
|
| 1038 |
+
|
| 1039 |
+
normalizedMap := sanitizedOAuthModelAlias(map[string][]config.OAuthModelAlias{channel: body.Aliases})
|
| 1040 |
+
normalized := normalizedMap[channel]
|
| 1041 |
+
if len(normalized) == 0 {
|
| 1042 |
+
if h.cfg.OAuthModelAlias == nil {
|
| 1043 |
+
c.JSON(404, gin.H{"error": "channel not found"})
|
| 1044 |
+
return
|
| 1045 |
+
}
|
| 1046 |
+
if _, ok := h.cfg.OAuthModelAlias[channel]; !ok {
|
| 1047 |
+
c.JSON(404, gin.H{"error": "channel not found"})
|
| 1048 |
+
return
|
| 1049 |
+
}
|
| 1050 |
+
delete(h.cfg.OAuthModelAlias, channel)
|
| 1051 |
+
if len(h.cfg.OAuthModelAlias) == 0 {
|
| 1052 |
+
h.cfg.OAuthModelAlias = nil
|
| 1053 |
+
}
|
| 1054 |
+
h.persist(c)
|
| 1055 |
+
return
|
| 1056 |
+
}
|
| 1057 |
+
if h.cfg.OAuthModelAlias == nil {
|
| 1058 |
+
h.cfg.OAuthModelAlias = make(map[string][]config.OAuthModelAlias)
|
| 1059 |
+
}
|
| 1060 |
+
h.cfg.OAuthModelAlias[channel] = normalized
|
| 1061 |
+
h.persist(c)
|
| 1062 |
+
}
|
| 1063 |
+
|
| 1064 |
+
func (h *Handler) DeleteOAuthModelAlias(c *gin.Context) {
|
| 1065 |
+
channel := strings.ToLower(strings.TrimSpace(c.Query("channel")))
|
| 1066 |
+
if channel == "" {
|
| 1067 |
+
channel = strings.ToLower(strings.TrimSpace(c.Query("provider")))
|
| 1068 |
+
}
|
| 1069 |
+
if channel == "" {
|
| 1070 |
+
c.JSON(400, gin.H{"error": "missing channel"})
|
| 1071 |
+
return
|
| 1072 |
+
}
|
| 1073 |
+
if h.cfg.OAuthModelAlias == nil {
|
| 1074 |
+
c.JSON(404, gin.H{"error": "channel not found"})
|
| 1075 |
+
return
|
| 1076 |
+
}
|
| 1077 |
+
if _, ok := h.cfg.OAuthModelAlias[channel]; !ok {
|
| 1078 |
+
c.JSON(404, gin.H{"error": "channel not found"})
|
| 1079 |
+
return
|
| 1080 |
+
}
|
| 1081 |
+
delete(h.cfg.OAuthModelAlias, channel)
|
| 1082 |
+
if len(h.cfg.OAuthModelAlias) == 0 {
|
| 1083 |
+
h.cfg.OAuthModelAlias = nil
|
| 1084 |
+
}
|
| 1085 |
+
h.persist(c)
|
| 1086 |
+
}
|
| 1087 |
+
|
| 1088 |
+
// codex-api-key: []CodexKey
|
| 1089 |
+
func (h *Handler) GetCodexKeys(c *gin.Context) {
|
| 1090 |
+
c.JSON(200, gin.H{"codex-api-key": h.codexKeysWithAuthIndex()})
|
| 1091 |
+
}
|
| 1092 |
+
func (h *Handler) PutCodexKeys(c *gin.Context) {
|
| 1093 |
+
data, err := c.GetRawData()
|
| 1094 |
+
if err != nil {
|
| 1095 |
+
c.JSON(400, gin.H{"error": "failed to read body"})
|
| 1096 |
+
return
|
| 1097 |
+
}
|
| 1098 |
+
var arr []config.CodexKey
|
| 1099 |
+
if err = json.Unmarshal(data, &arr); err != nil {
|
| 1100 |
+
var obj struct {
|
| 1101 |
+
Items []config.CodexKey `json:"items"`
|
| 1102 |
+
}
|
| 1103 |
+
if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 {
|
| 1104 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 1105 |
+
return
|
| 1106 |
+
}
|
| 1107 |
+
arr = obj.Items
|
| 1108 |
+
}
|
| 1109 |
+
// Filter out codex entries with empty base-url (treat as removed)
|
| 1110 |
+
filtered := make([]config.CodexKey, 0, len(arr))
|
| 1111 |
+
for i := range arr {
|
| 1112 |
+
entry := arr[i]
|
| 1113 |
+
normalizeCodexKey(&entry)
|
| 1114 |
+
if entry.BaseURL == "" {
|
| 1115 |
+
continue
|
| 1116 |
+
}
|
| 1117 |
+
filtered = append(filtered, entry)
|
| 1118 |
+
}
|
| 1119 |
+
h.mu.Lock()
|
| 1120 |
+
defer h.mu.Unlock()
|
| 1121 |
+
h.cfg.CodexKey = filtered
|
| 1122 |
+
h.cfg.SanitizeCodexKeys()
|
| 1123 |
+
h.persistLocked(c)
|
| 1124 |
+
}
|
| 1125 |
+
func (h *Handler) PatchCodexKey(c *gin.Context) {
|
| 1126 |
+
type codexKeyPatch struct {
|
| 1127 |
+
APIKey *string `json:"api-key"`
|
| 1128 |
+
Prefix *string `json:"prefix"`
|
| 1129 |
+
BaseURL *string `json:"base-url"`
|
| 1130 |
+
ProxyURL *string `json:"proxy-url"`
|
| 1131 |
+
Models *[]config.CodexModel `json:"models"`
|
| 1132 |
+
Headers *map[string]string `json:"headers"`
|
| 1133 |
+
ExcludedModels *[]string `json:"excluded-models"`
|
| 1134 |
+
}
|
| 1135 |
+
var body struct {
|
| 1136 |
+
Index *int `json:"index"`
|
| 1137 |
+
Match *string `json:"match"`
|
| 1138 |
+
Value *codexKeyPatch `json:"value"`
|
| 1139 |
+
}
|
| 1140 |
+
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
|
| 1141 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 1142 |
+
return
|
| 1143 |
+
}
|
| 1144 |
+
|
| 1145 |
+
h.mu.Lock()
|
| 1146 |
+
defer h.mu.Unlock()
|
| 1147 |
+
targetIndex := -1
|
| 1148 |
+
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.CodexKey) {
|
| 1149 |
+
targetIndex = *body.Index
|
| 1150 |
+
}
|
| 1151 |
+
if targetIndex == -1 && body.Match != nil {
|
| 1152 |
+
match := strings.TrimSpace(*body.Match)
|
| 1153 |
+
for i := range h.cfg.CodexKey {
|
| 1154 |
+
if h.cfg.CodexKey[i].APIKey == match {
|
| 1155 |
+
targetIndex = i
|
| 1156 |
+
break
|
| 1157 |
+
}
|
| 1158 |
+
}
|
| 1159 |
+
}
|
| 1160 |
+
if targetIndex == -1 {
|
| 1161 |
+
c.JSON(404, gin.H{"error": "item not found"})
|
| 1162 |
+
return
|
| 1163 |
+
}
|
| 1164 |
+
|
| 1165 |
+
entry := h.cfg.CodexKey[targetIndex]
|
| 1166 |
+
if body.Value.APIKey != nil {
|
| 1167 |
+
entry.APIKey = strings.TrimSpace(*body.Value.APIKey)
|
| 1168 |
+
}
|
| 1169 |
+
if body.Value.Prefix != nil {
|
| 1170 |
+
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
|
| 1171 |
+
}
|
| 1172 |
+
if body.Value.BaseURL != nil {
|
| 1173 |
+
trimmed := strings.TrimSpace(*body.Value.BaseURL)
|
| 1174 |
+
if trimmed == "" {
|
| 1175 |
+
h.cfg.CodexKey = append(h.cfg.CodexKey[:targetIndex], h.cfg.CodexKey[targetIndex+1:]...)
|
| 1176 |
+
h.cfg.SanitizeCodexKeys()
|
| 1177 |
+
h.persistLocked(c)
|
| 1178 |
+
return
|
| 1179 |
+
}
|
| 1180 |
+
entry.BaseURL = trimmed
|
| 1181 |
+
}
|
| 1182 |
+
if body.Value.ProxyURL != nil {
|
| 1183 |
+
entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL)
|
| 1184 |
+
}
|
| 1185 |
+
if body.Value.Models != nil {
|
| 1186 |
+
entry.Models = append([]config.CodexModel(nil), (*body.Value.Models)...)
|
| 1187 |
+
}
|
| 1188 |
+
if body.Value.Headers != nil {
|
| 1189 |
+
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
|
| 1190 |
+
}
|
| 1191 |
+
if body.Value.ExcludedModels != nil {
|
| 1192 |
+
entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels)
|
| 1193 |
+
}
|
| 1194 |
+
normalizeCodexKey(&entry)
|
| 1195 |
+
h.cfg.CodexKey[targetIndex] = entry
|
| 1196 |
+
h.cfg.SanitizeCodexKeys()
|
| 1197 |
+
h.persistLocked(c)
|
| 1198 |
+
}
|
| 1199 |
+
|
| 1200 |
+
func (h *Handler) DeleteCodexKey(c *gin.Context) {
|
| 1201 |
+
h.mu.Lock()
|
| 1202 |
+
defer h.mu.Unlock()
|
| 1203 |
+
if val := strings.TrimSpace(c.Query("api-key")); val != "" {
|
| 1204 |
+
if baseRaw, okBase := c.GetQuery("base-url"); okBase {
|
| 1205 |
+
base := strings.TrimSpace(baseRaw)
|
| 1206 |
+
out := make([]config.CodexKey, 0, len(h.cfg.CodexKey))
|
| 1207 |
+
for _, v := range h.cfg.CodexKey {
|
| 1208 |
+
if strings.TrimSpace(v.APIKey) == val && strings.TrimSpace(v.BaseURL) == base {
|
| 1209 |
+
continue
|
| 1210 |
+
}
|
| 1211 |
+
out = append(out, v)
|
| 1212 |
+
}
|
| 1213 |
+
h.cfg.CodexKey = out
|
| 1214 |
+
h.cfg.SanitizeCodexKeys()
|
| 1215 |
+
h.persistLocked(c)
|
| 1216 |
+
return
|
| 1217 |
+
}
|
| 1218 |
+
|
| 1219 |
+
matchIndex := -1
|
| 1220 |
+
matchCount := 0
|
| 1221 |
+
for i := range h.cfg.CodexKey {
|
| 1222 |
+
if strings.TrimSpace(h.cfg.CodexKey[i].APIKey) == val {
|
| 1223 |
+
matchCount++
|
| 1224 |
+
if matchIndex == -1 {
|
| 1225 |
+
matchIndex = i
|
| 1226 |
+
}
|
| 1227 |
+
}
|
| 1228 |
+
}
|
| 1229 |
+
if matchCount > 1 {
|
| 1230 |
+
c.JSON(400, gin.H{"error": "multiple items match api-key; base-url is required"})
|
| 1231 |
+
return
|
| 1232 |
+
}
|
| 1233 |
+
if matchIndex != -1 {
|
| 1234 |
+
h.cfg.CodexKey = append(h.cfg.CodexKey[:matchIndex], h.cfg.CodexKey[matchIndex+1:]...)
|
| 1235 |
+
}
|
| 1236 |
+
h.cfg.SanitizeCodexKeys()
|
| 1237 |
+
h.persistLocked(c)
|
| 1238 |
+
return
|
| 1239 |
+
}
|
| 1240 |
+
if idxStr := c.Query("index"); idxStr != "" {
|
| 1241 |
+
var idx int
|
| 1242 |
+
_, err := fmt.Sscanf(idxStr, "%d", &idx)
|
| 1243 |
+
if err == nil && idx >= 0 && idx < len(h.cfg.CodexKey) {
|
| 1244 |
+
h.cfg.CodexKey = append(h.cfg.CodexKey[:idx], h.cfg.CodexKey[idx+1:]...)
|
| 1245 |
+
h.cfg.SanitizeCodexKeys()
|
| 1246 |
+
h.persistLocked(c)
|
| 1247 |
+
return
|
| 1248 |
+
}
|
| 1249 |
+
}
|
| 1250 |
+
c.JSON(400, gin.H{"error": "missing api-key or index"})
|
| 1251 |
+
}
|
| 1252 |
+
|
| 1253 |
+
// xai-api-key: []XAIKey
|
| 1254 |
+
func (h *Handler) GetXAIKeys(c *gin.Context) {
|
| 1255 |
+
c.JSON(200, gin.H{"xai-api-key": h.xaiKeysWithAuthIndex()})
|
| 1256 |
+
}
|
| 1257 |
+
|
| 1258 |
+
func (h *Handler) PutXAIKeys(c *gin.Context) {
|
| 1259 |
+
data, errRead := c.GetRawData()
|
| 1260 |
+
if errRead != nil {
|
| 1261 |
+
c.JSON(400, gin.H{"error": "failed to read body"})
|
| 1262 |
+
return
|
| 1263 |
+
}
|
| 1264 |
+
var arr []config.XAIKey
|
| 1265 |
+
if errUnmarshal := json.Unmarshal(data, &arr); errUnmarshal != nil {
|
| 1266 |
+
var obj struct {
|
| 1267 |
+
Items []config.XAIKey `json:"items"`
|
| 1268 |
+
}
|
| 1269 |
+
if errObject := json.Unmarshal(data, &obj); errObject != nil || len(obj.Items) == 0 {
|
| 1270 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 1271 |
+
return
|
| 1272 |
+
}
|
| 1273 |
+
arr = obj.Items
|
| 1274 |
+
}
|
| 1275 |
+
filtered := make([]config.XAIKey, 0, len(arr))
|
| 1276 |
+
for i := range arr {
|
| 1277 |
+
entry := arr[i]
|
| 1278 |
+
normalizeCodexKey(&entry)
|
| 1279 |
+
if entry.BaseURL == "" {
|
| 1280 |
+
continue
|
| 1281 |
+
}
|
| 1282 |
+
filtered = append(filtered, entry)
|
| 1283 |
+
}
|
| 1284 |
+
h.mu.Lock()
|
| 1285 |
+
defer h.mu.Unlock()
|
| 1286 |
+
h.cfg.XAIKey = filtered
|
| 1287 |
+
h.cfg.SanitizeXAIKeys()
|
| 1288 |
+
h.persistLocked(c)
|
| 1289 |
+
}
|
| 1290 |
+
|
| 1291 |
+
func (h *Handler) PatchXAIKey(c *gin.Context) {
|
| 1292 |
+
type xaiKeyPatch struct {
|
| 1293 |
+
APIKey *string `json:"api-key"`
|
| 1294 |
+
Priority *int `json:"priority"`
|
| 1295 |
+
Prefix *string `json:"prefix"`
|
| 1296 |
+
BaseURL *string `json:"base-url"`
|
| 1297 |
+
Websockets *bool `json:"websockets"`
|
| 1298 |
+
ProxyURL *string `json:"proxy-url"`
|
| 1299 |
+
Models *[]config.XAIModel `json:"models"`
|
| 1300 |
+
Headers *map[string]string `json:"headers"`
|
| 1301 |
+
ExcludedModels *[]string `json:"excluded-models"`
|
| 1302 |
+
DisableCooling *bool `json:"disable-cooling"`
|
| 1303 |
+
}
|
| 1304 |
+
var body struct {
|
| 1305 |
+
Index *int `json:"index"`
|
| 1306 |
+
Match *string `json:"match"`
|
| 1307 |
+
Value *xaiKeyPatch `json:"value"`
|
| 1308 |
+
}
|
| 1309 |
+
if errBind := c.ShouldBindJSON(&body); errBind != nil || body.Value == nil {
|
| 1310 |
+
c.JSON(400, gin.H{"error": "invalid body"})
|
| 1311 |
+
return
|
| 1312 |
+
}
|
| 1313 |
+
|
| 1314 |
+
h.mu.Lock()
|
| 1315 |
+
defer h.mu.Unlock()
|
| 1316 |
+
targetIndex := -1
|
| 1317 |
+
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.XAIKey) {
|
| 1318 |
+
targetIndex = *body.Index
|
| 1319 |
+
}
|
| 1320 |
+
if targetIndex == -1 && body.Match != nil {
|
| 1321 |
+
match := strings.TrimSpace(*body.Match)
|
| 1322 |
+
for i := range h.cfg.XAIKey {
|
| 1323 |
+
if h.cfg.XAIKey[i].APIKey == match {
|
| 1324 |
+
targetIndex = i
|
| 1325 |
+
break
|
| 1326 |
+
}
|
| 1327 |
+
}
|
| 1328 |
+
}
|
| 1329 |
+
if targetIndex == -1 {
|
| 1330 |
+
c.JSON(404, gin.H{"error": "item not found"})
|
| 1331 |
+
return
|
| 1332 |
+
}
|
| 1333 |
+
|
| 1334 |
+
entry := h.cfg.XAIKey[targetIndex]
|
| 1335 |
+
if body.Value.APIKey != nil {
|
| 1336 |
+
entry.APIKey = strings.TrimSpace(*body.Value.APIKey)
|
| 1337 |
+
}
|
| 1338 |
+
if body.Value.Priority != nil {
|
| 1339 |
+
entry.Priority = *body.Value.Priority
|
| 1340 |
+
}
|
| 1341 |
+
if body.Value.Prefix != nil {
|
| 1342 |
+
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
|
| 1343 |
+
}
|
| 1344 |
+
if body.Value.BaseURL != nil {
|
| 1345 |
+
trimmed := strings.TrimSpace(*body.Value.BaseURL)
|
| 1346 |
+
if trimmed == "" {
|
| 1347 |
+
h.cfg.XAIKey = append(h.cfg.XAIKey[:targetIndex], h.cfg.XAIKey[targetIndex+1:]...)
|
| 1348 |
+
h.cfg.SanitizeXAIKeys()
|
| 1349 |
+
h.persistLocked(c)
|
| 1350 |
+
return
|
| 1351 |
+
}
|
| 1352 |
+
entry.BaseURL = trimmed
|
| 1353 |
+
}
|
| 1354 |
+
if body.Value.Websockets != nil {
|
| 1355 |
+
entry.Websockets = *body.Value.Websockets
|
| 1356 |
+
}
|
| 1357 |
+
if body.Value.ProxyURL != nil {
|
| 1358 |
+
entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL)
|
| 1359 |
+
}
|
| 1360 |
+
if body.Value.Models != nil {
|
| 1361 |
+
entry.Models = append([]config.XAIModel(nil), (*body.Value.Models)...)
|
| 1362 |
+
}
|
| 1363 |
+
if body.Value.Headers != nil {
|
| 1364 |
+
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
|
| 1365 |
+
}
|
| 1366 |
+
if body.Value.ExcludedModels != nil {
|
| 1367 |
+
entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels)
|
| 1368 |
+
}
|
| 1369 |
+
if body.Value.DisableCooling != nil {
|
| 1370 |
+
entry.DisableCooling = *body.Value.DisableCooling
|
| 1371 |
+
}
|
| 1372 |
+
normalizeCodexKey(&entry)
|
| 1373 |
+
h.cfg.XAIKey[targetIndex] = entry
|
| 1374 |
+
h.cfg.SanitizeXAIKeys()
|
| 1375 |
+
h.persistLocked(c)
|
| 1376 |
+
}
|
| 1377 |
+
|
| 1378 |
+
func (h *Handler) DeleteXAIKey(c *gin.Context) {
|
| 1379 |
+
h.mu.Lock()
|
| 1380 |
+
defer h.mu.Unlock()
|
| 1381 |
+
if val := strings.TrimSpace(c.Query("api-key")); val != "" {
|
| 1382 |
+
if baseRaw, okBase := c.GetQuery("base-url"); okBase {
|
| 1383 |
+
base := strings.TrimSpace(baseRaw)
|
| 1384 |
+
out := make([]config.XAIKey, 0, len(h.cfg.XAIKey))
|
| 1385 |
+
for _, entry := range h.cfg.XAIKey {
|
| 1386 |
+
if strings.TrimSpace(entry.APIKey) == val && strings.TrimSpace(entry.BaseURL) == base {
|
| 1387 |
+
continue
|
| 1388 |
+
}
|
| 1389 |
+
out = append(out, entry)
|
| 1390 |
+
}
|
| 1391 |
+
h.cfg.XAIKey = out
|
| 1392 |
+
h.cfg.SanitizeXAIKeys()
|
| 1393 |
+
h.persistLocked(c)
|
| 1394 |
+
return
|
| 1395 |
+
}
|
| 1396 |
+
|
| 1397 |
+
matchIndex := -1
|
| 1398 |
+
matchCount := 0
|
| 1399 |
+
for i := range h.cfg.XAIKey {
|
| 1400 |
+
if strings.TrimSpace(h.cfg.XAIKey[i].APIKey) == val {
|
| 1401 |
+
matchCount++
|
| 1402 |
+
if matchIndex == -1 {
|
| 1403 |
+
matchIndex = i
|
| 1404 |
+
}
|
| 1405 |
+
}
|
| 1406 |
+
}
|
| 1407 |
+
if matchCount > 1 {
|
| 1408 |
+
c.JSON(400, gin.H{"error": "multiple items match api-key; base-url is required"})
|
| 1409 |
+
return
|
| 1410 |
+
}
|
| 1411 |
+
if matchIndex != -1 {
|
| 1412 |
+
h.cfg.XAIKey = append(h.cfg.XAIKey[:matchIndex], h.cfg.XAIKey[matchIndex+1:]...)
|
| 1413 |
+
}
|
| 1414 |
+
h.cfg.SanitizeXAIKeys()
|
| 1415 |
+
h.persistLocked(c)
|
| 1416 |
+
return
|
| 1417 |
+
}
|
| 1418 |
+
if idxStr := c.Query("index"); idxStr != "" {
|
| 1419 |
+
var idx int
|
| 1420 |
+
_, errScan := fmt.Sscanf(idxStr, "%d", &idx)
|
| 1421 |
+
if errScan == nil && idx >= 0 && idx < len(h.cfg.XAIKey) {
|
| 1422 |
+
h.cfg.XAIKey = append(h.cfg.XAIKey[:idx], h.cfg.XAIKey[idx+1:]...)
|
| 1423 |
+
h.cfg.SanitizeXAIKeys()
|
| 1424 |
+
h.persistLocked(c)
|
| 1425 |
+
return
|
| 1426 |
+
}
|
| 1427 |
+
}
|
| 1428 |
+
c.JSON(400, gin.H{"error": "missing api-key or index"})
|
| 1429 |
+
}
|
| 1430 |
+
|
| 1431 |
+
func normalizeOpenAICompatibilityEntry(entry *config.OpenAICompatibility) {
|
| 1432 |
+
if entry == nil {
|
| 1433 |
+
return
|
| 1434 |
+
}
|
| 1435 |
+
// Trim base-url; empty base-url indicates provider should be removed by sanitization
|
| 1436 |
+
entry.BaseURL = strings.TrimSpace(entry.BaseURL)
|
| 1437 |
+
entry.Headers = config.NormalizeHeaders(entry.Headers)
|
| 1438 |
+
existing := make(map[string]struct{}, len(entry.APIKeyEntries))
|
| 1439 |
+
for i := range entry.APIKeyEntries {
|
| 1440 |
+
trimmed := strings.TrimSpace(entry.APIKeyEntries[i].APIKey)
|
| 1441 |
+
entry.APIKeyEntries[i].APIKey = trimmed
|
| 1442 |
+
if trimmed != "" {
|
| 1443 |
+
existing[trimmed] = struct{}{}
|
| 1444 |
+
}
|
| 1445 |
+
}
|
| 1446 |
+
}
|
| 1447 |
+
|
| 1448 |
+
func normalizedOpenAICompatibilityEntries(entries []config.OpenAICompatibility) []config.OpenAICompatibility {
|
| 1449 |
+
if len(entries) == 0 {
|
| 1450 |
+
return nil
|
| 1451 |
+
}
|
| 1452 |
+
out := make([]config.OpenAICompatibility, len(entries))
|
| 1453 |
+
for i := range entries {
|
| 1454 |
+
copyEntry := entries[i]
|
| 1455 |
+
if len(copyEntry.APIKeyEntries) > 0 {
|
| 1456 |
+
copyEntry.APIKeyEntries = append([]config.OpenAICompatibilityAPIKey(nil), copyEntry.APIKeyEntries...)
|
| 1457 |
+
}
|
| 1458 |
+
normalizeOpenAICompatibilityEntry(©Entry)
|
| 1459 |
+
out[i] = copyEntry
|
| 1460 |
+
}
|
| 1461 |
+
return out
|
| 1462 |
+
}
|
| 1463 |
+
|
| 1464 |
+
func normalizeClaudeKey(entry *config.ClaudeKey) {
|
| 1465 |
+
if entry == nil {
|
| 1466 |
+
return
|
| 1467 |
+
}
|
| 1468 |
+
entry.APIKey = strings.TrimSpace(entry.APIKey)
|
| 1469 |
+
entry.BaseURL = strings.TrimSpace(entry.BaseURL)
|
| 1470 |
+
entry.ProxyURL = strings.TrimSpace(entry.ProxyURL)
|
| 1471 |
+
entry.Headers = config.NormalizeHeaders(entry.Headers)
|
| 1472 |
+
entry.ExcludedModels = config.NormalizeExcludedModels(entry.ExcludedModels)
|
| 1473 |
+
if len(entry.Models) == 0 {
|
| 1474 |
+
return
|
| 1475 |
+
}
|
| 1476 |
+
normalized := make([]config.ClaudeModel, 0, len(entry.Models))
|
| 1477 |
+
for i := range entry.Models {
|
| 1478 |
+
model := entry.Models[i]
|
| 1479 |
+
model.Name = strings.TrimSpace(model.Name)
|
| 1480 |
+
model.Alias = strings.TrimSpace(model.Alias)
|
| 1481 |
+
if model.Name == "" && model.Alias == "" {
|
| 1482 |
+
continue
|
| 1483 |
+
}
|
| 1484 |
+
normalized = append(normalized, model)
|
| 1485 |
+
}
|
| 1486 |
+
entry.Models = normalized
|
| 1487 |
+
}
|
| 1488 |
+
|
| 1489 |
+
func normalizeCodexKey(entry *config.CodexKey) {
|
| 1490 |
+
if entry == nil {
|
| 1491 |
+
return
|
| 1492 |
+
}
|
| 1493 |
+
entry.APIKey = strings.TrimSpace(entry.APIKey)
|
| 1494 |
+
entry.Prefix = strings.TrimSpace(entry.Prefix)
|
| 1495 |
+
entry.BaseURL = strings.TrimSpace(entry.BaseURL)
|
| 1496 |
+
entry.ProxyURL = strings.TrimSpace(entry.ProxyURL)
|
| 1497 |
+
entry.Headers = config.NormalizeHeaders(entry.Headers)
|
| 1498 |
+
entry.ExcludedModels = config.NormalizeExcludedModels(entry.ExcludedModels)
|
| 1499 |
+
if len(entry.Models) == 0 {
|
| 1500 |
+
return
|
| 1501 |
+
}
|
| 1502 |
+
normalized := make([]config.CodexModel, 0, len(entry.Models))
|
| 1503 |
+
for i := range entry.Models {
|
| 1504 |
+
model := entry.Models[i]
|
| 1505 |
+
model.Name = strings.TrimSpace(model.Name)
|
| 1506 |
+
model.Alias = strings.TrimSpace(model.Alias)
|
| 1507 |
+
if model.Name == "" && model.Alias == "" {
|
| 1508 |
+
continue
|
| 1509 |
+
}
|
| 1510 |
+
normalized = append(normalized, model)
|
| 1511 |
+
}
|
| 1512 |
+
entry.Models = normalized
|
| 1513 |
+
}
|
| 1514 |
+
|
| 1515 |
+
func normalizeVertexCompatKey(entry *config.VertexCompatKey) {
|
| 1516 |
+
if entry == nil {
|
| 1517 |
+
return
|
| 1518 |
+
}
|
| 1519 |
+
entry.APIKey = strings.TrimSpace(entry.APIKey)
|
| 1520 |
+
entry.Prefix = strings.TrimSpace(entry.Prefix)
|
| 1521 |
+
entry.BaseURL = strings.TrimSpace(entry.BaseURL)
|
| 1522 |
+
entry.ProxyURL = strings.TrimSpace(entry.ProxyURL)
|
| 1523 |
+
entry.Headers = config.NormalizeHeaders(entry.Headers)
|
| 1524 |
+
entry.ExcludedModels = config.NormalizeExcludedModels(entry.ExcludedModels)
|
| 1525 |
+
if len(entry.Models) == 0 {
|
| 1526 |
+
return
|
| 1527 |
+
}
|
| 1528 |
+
normalized := make([]config.VertexCompatModel, 0, len(entry.Models))
|
| 1529 |
+
for i := range entry.Models {
|
| 1530 |
+
model := entry.Models[i]
|
| 1531 |
+
model.Name = strings.TrimSpace(model.Name)
|
| 1532 |
+
model.Alias = strings.TrimSpace(model.Alias)
|
| 1533 |
+
if model.Name == "" || model.Alias == "" {
|
| 1534 |
+
continue
|
| 1535 |
+
}
|
| 1536 |
+
normalized = append(normalized, model)
|
| 1537 |
+
}
|
| 1538 |
+
entry.Models = normalized
|
| 1539 |
+
}
|
| 1540 |
+
|
| 1541 |
+
func sanitizedOAuthModelAlias(entries map[string][]config.OAuthModelAlias) map[string][]config.OAuthModelAlias {
|
| 1542 |
+
if len(entries) == 0 {
|
| 1543 |
+
return nil
|
| 1544 |
+
}
|
| 1545 |
+
copied := make(map[string][]config.OAuthModelAlias, len(entries))
|
| 1546 |
+
for channel, aliases := range entries {
|
| 1547 |
+
if len(aliases) == 0 {
|
| 1548 |
+
continue
|
| 1549 |
+
}
|
| 1550 |
+
copied[channel] = append([]config.OAuthModelAlias(nil), aliases...)
|
| 1551 |
+
}
|
| 1552 |
+
if len(copied) == 0 {
|
| 1553 |
+
return nil
|
| 1554 |
+
}
|
| 1555 |
+
cfg := config.Config{OAuthModelAlias: copied}
|
| 1556 |
+
cfg.SanitizeOAuthModelAlias()
|
| 1557 |
+
if len(cfg.OAuthModelAlias) == 0 {
|
| 1558 |
+
return nil
|
| 1559 |
+
}
|
| 1560 |
+
return cfg.OAuthModelAlias
|
| 1561 |
+
}
|
internal/api/handlers/management/config_lists_delete_keys_test.go
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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/gin-gonic/gin"
|
| 11 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
func writeTestConfigFile(t *testing.T) string {
|
| 15 |
+
t.Helper()
|
| 16 |
+
|
| 17 |
+
dir := t.TempDir()
|
| 18 |
+
path := filepath.Join(dir, "config.yaml")
|
| 19 |
+
if errWrite := os.WriteFile(path, []byte("{}\n"), 0o600); errWrite != nil {
|
| 20 |
+
t.Fatalf("failed to write test config: %v", errWrite)
|
| 21 |
+
}
|
| 22 |
+
return path
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
func TestDeleteGeminiKey_RequiresBaseURLWhenAPIKeyDuplicated(t *testing.T) {
|
| 26 |
+
t.Parallel()
|
| 27 |
+
|
| 28 |
+
h := &Handler{
|
| 29 |
+
cfg: &config.Config{
|
| 30 |
+
GeminiKey: []config.GeminiKey{
|
| 31 |
+
{APIKey: "shared-key", BaseURL: "https://a.example.com"},
|
| 32 |
+
{APIKey: "shared-key", BaseURL: "https://b.example.com"},
|
| 33 |
+
},
|
| 34 |
+
},
|
| 35 |
+
configFilePath: writeTestConfigFile(t),
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
rec := httptest.NewRecorder()
|
| 39 |
+
c, _ := gin.CreateTestContext(rec)
|
| 40 |
+
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/gemini-api-key?api-key=shared-key", nil)
|
| 41 |
+
|
| 42 |
+
h.DeleteGeminiKey(c)
|
| 43 |
+
|
| 44 |
+
if rec.Code != http.StatusBadRequest {
|
| 45 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
|
| 46 |
+
}
|
| 47 |
+
if got := len(h.cfg.GeminiKey); got != 2 {
|
| 48 |
+
t.Fatalf("gemini keys len = %d, want 2", got)
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
func TestDeleteGeminiKey_DeletesOnlyMatchingBaseURL(t *testing.T) {
|
| 53 |
+
t.Parallel()
|
| 54 |
+
|
| 55 |
+
h := &Handler{
|
| 56 |
+
cfg: &config.Config{
|
| 57 |
+
GeminiKey: []config.GeminiKey{
|
| 58 |
+
{APIKey: "shared-key", BaseURL: "https://a.example.com"},
|
| 59 |
+
{APIKey: "shared-key", BaseURL: "https://b.example.com"},
|
| 60 |
+
},
|
| 61 |
+
},
|
| 62 |
+
configFilePath: writeTestConfigFile(t),
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
rec := httptest.NewRecorder()
|
| 66 |
+
c, _ := gin.CreateTestContext(rec)
|
| 67 |
+
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/gemini-api-key?api-key=shared-key&base-url=https://a.example.com", nil)
|
| 68 |
+
|
| 69 |
+
h.DeleteGeminiKey(c)
|
| 70 |
+
|
| 71 |
+
if rec.Code != http.StatusOK {
|
| 72 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 73 |
+
}
|
| 74 |
+
if got := len(h.cfg.GeminiKey); got != 1 {
|
| 75 |
+
t.Fatalf("gemini keys len = %d, want 1", got)
|
| 76 |
+
}
|
| 77 |
+
if got := h.cfg.GeminiKey[0].BaseURL; got != "https://b.example.com" {
|
| 78 |
+
t.Fatalf("remaining base-url = %q, want %q", got, "https://b.example.com")
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
func TestDeleteClaudeKey_DeletesEmptyBaseURLWhenExplicitlyProvided(t *testing.T) {
|
| 83 |
+
t.Parallel()
|
| 84 |
+
|
| 85 |
+
h := &Handler{
|
| 86 |
+
cfg: &config.Config{
|
| 87 |
+
ClaudeKey: []config.ClaudeKey{
|
| 88 |
+
{APIKey: "shared-key", BaseURL: ""},
|
| 89 |
+
{APIKey: "shared-key", BaseURL: "https://claude.example.com"},
|
| 90 |
+
},
|
| 91 |
+
},
|
| 92 |
+
configFilePath: writeTestConfigFile(t),
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
rec := httptest.NewRecorder()
|
| 96 |
+
c, _ := gin.CreateTestContext(rec)
|
| 97 |
+
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/claude-api-key?api-key=shared-key&base-url=", nil)
|
| 98 |
+
|
| 99 |
+
h.DeleteClaudeKey(c)
|
| 100 |
+
|
| 101 |
+
if rec.Code != http.StatusOK {
|
| 102 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 103 |
+
}
|
| 104 |
+
if got := len(h.cfg.ClaudeKey); got != 1 {
|
| 105 |
+
t.Fatalf("claude keys len = %d, want 1", got)
|
| 106 |
+
}
|
| 107 |
+
if got := h.cfg.ClaudeKey[0].BaseURL; got != "https://claude.example.com" {
|
| 108 |
+
t.Fatalf("remaining base-url = %q, want %q", got, "https://claude.example.com")
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
func TestDeleteVertexCompatKey_DeletesOnlyMatchingBaseURL(t *testing.T) {
|
| 113 |
+
t.Parallel()
|
| 114 |
+
|
| 115 |
+
h := &Handler{
|
| 116 |
+
cfg: &config.Config{
|
| 117 |
+
VertexCompatAPIKey: []config.VertexCompatKey{
|
| 118 |
+
{APIKey: "shared-key", BaseURL: "https://a.example.com"},
|
| 119 |
+
{APIKey: "shared-key", BaseURL: "https://b.example.com"},
|
| 120 |
+
},
|
| 121 |
+
},
|
| 122 |
+
configFilePath: writeTestConfigFile(t),
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
rec := httptest.NewRecorder()
|
| 126 |
+
c, _ := gin.CreateTestContext(rec)
|
| 127 |
+
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/vertex-api-key?api-key=shared-key&base-url=https://b.example.com", nil)
|
| 128 |
+
|
| 129 |
+
h.DeleteVertexCompatKey(c)
|
| 130 |
+
|
| 131 |
+
if rec.Code != http.StatusOK {
|
| 132 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 133 |
+
}
|
| 134 |
+
if got := len(h.cfg.VertexCompatAPIKey); got != 1 {
|
| 135 |
+
t.Fatalf("vertex keys len = %d, want 1", got)
|
| 136 |
+
}
|
| 137 |
+
if got := h.cfg.VertexCompatAPIKey[0].BaseURL; got != "https://a.example.com" {
|
| 138 |
+
t.Fatalf("remaining base-url = %q, want %q", got, "https://a.example.com")
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
func TestDeleteXAIKey_RequiresBaseURLWhenAPIKeyDuplicated(t *testing.T) {
|
| 143 |
+
t.Parallel()
|
| 144 |
+
|
| 145 |
+
h := &Handler{
|
| 146 |
+
cfg: &config.Config{
|
| 147 |
+
XAIKey: []config.XAIKey{
|
| 148 |
+
{APIKey: "shared-key", BaseURL: "https://a.example.com"},
|
| 149 |
+
{APIKey: "shared-key", BaseURL: "https://b.example.com"},
|
| 150 |
+
},
|
| 151 |
+
},
|
| 152 |
+
configFilePath: writeTestConfigFile(t),
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
rec := httptest.NewRecorder()
|
| 156 |
+
c, _ := gin.CreateTestContext(rec)
|
| 157 |
+
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/xai-api-key?api-key=shared-key", nil)
|
| 158 |
+
|
| 159 |
+
h.DeleteXAIKey(c)
|
| 160 |
+
|
| 161 |
+
if rec.Code != http.StatusBadRequest {
|
| 162 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
|
| 163 |
+
}
|
| 164 |
+
if got := len(h.cfg.XAIKey); got != 2 {
|
| 165 |
+
t.Fatalf("xAI keys len = %d, want 2", got)
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
func TestDeleteCodexKey_RequiresBaseURLWhenAPIKeyDuplicated(t *testing.T) {
|
| 170 |
+
t.Parallel()
|
| 171 |
+
|
| 172 |
+
h := &Handler{
|
| 173 |
+
cfg: &config.Config{
|
| 174 |
+
CodexKey: []config.CodexKey{
|
| 175 |
+
{APIKey: "shared-key", BaseURL: "https://a.example.com"},
|
| 176 |
+
{APIKey: "shared-key", BaseURL: "https://b.example.com"},
|
| 177 |
+
},
|
| 178 |
+
},
|
| 179 |
+
configFilePath: writeTestConfigFile(t),
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
rec := httptest.NewRecorder()
|
| 183 |
+
c, _ := gin.CreateTestContext(rec)
|
| 184 |
+
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/codex-api-key?api-key=shared-key", nil)
|
| 185 |
+
|
| 186 |
+
h.DeleteCodexKey(c)
|
| 187 |
+
|
| 188 |
+
if rec.Code != http.StatusBadRequest {
|
| 189 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusBadRequest, rec.Body.String())
|
| 190 |
+
}
|
| 191 |
+
if got := len(h.cfg.CodexKey); got != 2 {
|
| 192 |
+
t.Fatalf("codex keys len = %d, want 2", got)
|
| 193 |
+
}
|
| 194 |
+
}
|
internal/api/handlers/management/config_openai_compat_test.go
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"net/http"
|
| 6 |
+
"net/http/httptest"
|
| 7 |
+
"testing"
|
| 8 |
+
|
| 9 |
+
"github.com/gin-gonic/gin"
|
| 10 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
func TestGetOpenAICompatIncludesDisableCooling(t *testing.T) {
|
| 14 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 15 |
+
|
| 16 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{
|
| 17 |
+
OpenAICompatibility: []config.OpenAICompatibility{
|
| 18 |
+
{
|
| 19 |
+
Name: "Mimo CN",
|
| 20 |
+
BaseURL: "https://token-plan-cn.xiaomimimo.com/v1",
|
| 21 |
+
APIKeyEntries: []config.OpenAICompatibilityAPIKey{
|
| 22 |
+
{APIKey: "test-key"},
|
| 23 |
+
},
|
| 24 |
+
Models: []config.OpenAICompatibilityModel{
|
| 25 |
+
{Name: "mimo-v2.5", Alias: ""},
|
| 26 |
+
},
|
| 27 |
+
DisableCooling: true,
|
| 28 |
+
},
|
| 29 |
+
},
|
| 30 |
+
}, nil)
|
| 31 |
+
|
| 32 |
+
rec := httptest.NewRecorder()
|
| 33 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 34 |
+
ctx.Request = httptest.NewRequest(http.MethodGet, "/v0/management/openai-compatibility", nil)
|
| 35 |
+
h.GetOpenAICompat(ctx)
|
| 36 |
+
|
| 37 |
+
if rec.Code != http.StatusOK {
|
| 38 |
+
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
var body struct {
|
| 42 |
+
OpenAICompatibility []struct {
|
| 43 |
+
DisableCooling *bool `json:"disable-cooling"`
|
| 44 |
+
} `json:"openai-compatibility"`
|
| 45 |
+
}
|
| 46 |
+
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
| 47 |
+
t.Fatalf("failed to decode response: %v", err)
|
| 48 |
+
}
|
| 49 |
+
if len(body.OpenAICompatibility) != 1 {
|
| 50 |
+
t.Fatalf("expected 1 openai-compatibility entry, got %d", len(body.OpenAICompatibility))
|
| 51 |
+
}
|
| 52 |
+
if body.OpenAICompatibility[0].DisableCooling == nil || !*body.OpenAICompatibility[0].DisableCooling {
|
| 53 |
+
t.Fatalf("expected disable-cooling to be present and true, got %#v", body.OpenAICompatibility[0].DisableCooling)
|
| 54 |
+
}
|
| 55 |
+
}
|
internal/api/handlers/management/config_xai_key_test.go
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
"net/http/httptest"
|
| 6 |
+
"strings"
|
| 7 |
+
"testing"
|
| 8 |
+
|
| 9 |
+
"github.com/gin-gonic/gin"
|
| 10 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
func TestPatchXAIKeyUpdatesExecutionFields(t *testing.T) {
|
| 14 |
+
h := &Handler{
|
| 15 |
+
cfg: &config.Config{XAIKey: []config.XAIKey{{
|
| 16 |
+
APIKey: "xai-key",
|
| 17 |
+
Priority: 1,
|
| 18 |
+
BaseURL: "https://api.x.ai/v1",
|
| 19 |
+
Websockets: true,
|
| 20 |
+
DisableCooling: false,
|
| 21 |
+
}}},
|
| 22 |
+
configFilePath: writeTestConfigFile(t),
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
rec := httptest.NewRecorder()
|
| 26 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 27 |
+
ctx.Request = httptest.NewRequest(http.MethodPatch, "/v0/management/xai-api-key", strings.NewReader(`{
|
| 28 |
+
"index": 0,
|
| 29 |
+
"value": {
|
| 30 |
+
"priority": 7,
|
| 31 |
+
"websockets": false,
|
| 32 |
+
"disable-cooling": true
|
| 33 |
+
}
|
| 34 |
+
}`))
|
| 35 |
+
ctx.Request.Header.Set("Content-Type", "application/json")
|
| 36 |
+
|
| 37 |
+
h.PatchXAIKey(ctx)
|
| 38 |
+
|
| 39 |
+
if rec.Code != http.StatusOK {
|
| 40 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 41 |
+
}
|
| 42 |
+
entry := h.cfg.XAIKey[0]
|
| 43 |
+
if entry.Priority != 7 {
|
| 44 |
+
t.Fatalf("priority = %d, want 7", entry.Priority)
|
| 45 |
+
}
|
| 46 |
+
if entry.Websockets {
|
| 47 |
+
t.Fatal("websockets = true, want false")
|
| 48 |
+
}
|
| 49 |
+
if !entry.DisableCooling {
|
| 50 |
+
t.Fatal("disable-cooling = false, want true")
|
| 51 |
+
}
|
| 52 |
+
}
|
internal/api/handlers/management/handler.go
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Package management provides the management API handlers and middleware
|
| 2 |
+
// for configuring the server and managing auth files.
|
| 3 |
+
package management
|
| 4 |
+
|
| 5 |
+
import (
|
| 6 |
+
"context"
|
| 7 |
+
"crypto/subtle"
|
| 8 |
+
"fmt"
|
| 9 |
+
"net/http"
|
| 10 |
+
"os"
|
| 11 |
+
"path/filepath"
|
| 12 |
+
"strings"
|
| 13 |
+
"sync"
|
| 14 |
+
"time"
|
| 15 |
+
|
| 16 |
+
"github.com/gin-gonic/gin"
|
| 17 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/buildinfo"
|
| 18 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 19 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
|
| 20 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/pluginstore"
|
| 21 |
+
sdkAuth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
|
| 22 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 23 |
+
log "github.com/sirupsen/logrus"
|
| 24 |
+
"golang.org/x/crypto/bcrypt"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
type attemptInfo struct {
|
| 28 |
+
count int
|
| 29 |
+
blockedUntil time.Time
|
| 30 |
+
lastActivity time.Time // track last activity for cleanup
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
// attemptCleanupInterval controls how often stale IP entries are purged
|
| 34 |
+
const attemptCleanupInterval = 1 * time.Hour
|
| 35 |
+
|
| 36 |
+
// attemptMaxIdleTime controls how long an IP can be idle before cleanup
|
| 37 |
+
const attemptMaxIdleTime = 2 * time.Hour
|
| 38 |
+
|
| 39 |
+
// Handler aggregates config reference, persistence path and helpers.
|
| 40 |
+
type Handler struct {
|
| 41 |
+
cfg *config.Config
|
| 42 |
+
configFilePath string
|
| 43 |
+
mu sync.Mutex
|
| 44 |
+
reloadMu sync.Mutex
|
| 45 |
+
reloadGeneration uint64
|
| 46 |
+
appliedReloadGeneration uint64
|
| 47 |
+
attemptsMu sync.Mutex
|
| 48 |
+
failedAttempts map[string]*attemptInfo // keyed by client IP
|
| 49 |
+
authManager *coreauth.Manager
|
| 50 |
+
tokenStore coreauth.Store
|
| 51 |
+
localPassword string
|
| 52 |
+
allowRemoteOverride bool
|
| 53 |
+
envSecret string
|
| 54 |
+
logDir string
|
| 55 |
+
postAuthHook coreauth.PostAuthHook
|
| 56 |
+
postAuthPersistHook coreauth.PostAuthHook
|
| 57 |
+
pluginHost *pluginhost.Host
|
| 58 |
+
configReloadHook func(context.Context, *config.Config)
|
| 59 |
+
pluginStoreRegistryURL string
|
| 60 |
+
pluginStoreHTTPClient pluginstore.HTTPDoer
|
| 61 |
+
pluginReleaseCacheMu sync.Mutex
|
| 62 |
+
pluginReleaseCache map[string]pluginReleaseCacheEntry
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
type configReloadSnapshot struct {
|
| 66 |
+
cfg *config.Config
|
| 67 |
+
generation uint64
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
// NewHandler creates a new management handler instance.
|
| 71 |
+
func NewHandler(cfg *config.Config, configFilePath string, manager *coreauth.Manager) *Handler {
|
| 72 |
+
envSecret, _ := os.LookupEnv("MANAGEMENT_PASSWORD")
|
| 73 |
+
envSecret = strings.TrimSpace(envSecret)
|
| 74 |
+
|
| 75 |
+
h := &Handler{
|
| 76 |
+
cfg: cfg,
|
| 77 |
+
configFilePath: configFilePath,
|
| 78 |
+
failedAttempts: make(map[string]*attemptInfo),
|
| 79 |
+
authManager: manager,
|
| 80 |
+
tokenStore: sdkAuth.GetTokenStore(),
|
| 81 |
+
allowRemoteOverride: envSecret != "",
|
| 82 |
+
envSecret: envSecret,
|
| 83 |
+
}
|
| 84 |
+
h.startAttemptCleanup()
|
| 85 |
+
return h
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
// startAttemptCleanup launches a background goroutine that periodically
|
| 89 |
+
// removes stale IP entries from failedAttempts to prevent memory leaks.
|
| 90 |
+
func (h *Handler) startAttemptCleanup() {
|
| 91 |
+
go func() {
|
| 92 |
+
ticker := time.NewTicker(attemptCleanupInterval)
|
| 93 |
+
defer ticker.Stop()
|
| 94 |
+
for range ticker.C {
|
| 95 |
+
h.purgeStaleAttempts()
|
| 96 |
+
}
|
| 97 |
+
}()
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
// purgeStaleAttempts removes IP entries that have been idle beyond attemptMaxIdleTime
|
| 101 |
+
// and whose ban (if any) has expired.
|
| 102 |
+
func (h *Handler) purgeStaleAttempts() {
|
| 103 |
+
now := time.Now()
|
| 104 |
+
h.attemptsMu.Lock()
|
| 105 |
+
defer h.attemptsMu.Unlock()
|
| 106 |
+
for ip, ai := range h.failedAttempts {
|
| 107 |
+
// Skip if still banned
|
| 108 |
+
if !ai.blockedUntil.IsZero() && now.Before(ai.blockedUntil) {
|
| 109 |
+
continue
|
| 110 |
+
}
|
| 111 |
+
// Remove if idle too long
|
| 112 |
+
if now.Sub(ai.lastActivity) > attemptMaxIdleTime {
|
| 113 |
+
delete(h.failedAttempts, ip)
|
| 114 |
+
}
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
// NewHandler creates a new management handler instance.
|
| 119 |
+
func NewHandlerWithoutConfigFilePath(cfg *config.Config, manager *coreauth.Manager) *Handler {
|
| 120 |
+
return NewHandler(cfg, "", manager)
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
// SetConfig updates the in-memory config reference when the server hot-reloads.
|
| 124 |
+
func (h *Handler) SetConfig(cfg *config.Config) {
|
| 125 |
+
if h == nil {
|
| 126 |
+
return
|
| 127 |
+
}
|
| 128 |
+
h.mu.Lock()
|
| 129 |
+
h.cfg = cfg
|
| 130 |
+
h.mu.Unlock()
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
// SetAuthManager updates the auth manager reference used by management endpoints.
|
| 134 |
+
func (h *Handler) SetAuthManager(manager *coreauth.Manager) {
|
| 135 |
+
if h == nil {
|
| 136 |
+
return
|
| 137 |
+
}
|
| 138 |
+
h.mu.Lock()
|
| 139 |
+
h.authManager = manager
|
| 140 |
+
h.mu.Unlock()
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
// SetPluginHost updates the plugin host used by plugin-backed management endpoints.
|
| 144 |
+
func (h *Handler) SetPluginHost(host *pluginhost.Host) {
|
| 145 |
+
if h == nil {
|
| 146 |
+
return
|
| 147 |
+
}
|
| 148 |
+
h.mu.Lock()
|
| 149 |
+
h.pluginHost = host
|
| 150 |
+
h.mu.Unlock()
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
// SetConfigReloadHook updates the callback used after management saves config changes.
|
| 154 |
+
func (h *Handler) SetConfigReloadHook(hook func(context.Context, *config.Config)) {
|
| 155 |
+
if h == nil {
|
| 156 |
+
return
|
| 157 |
+
}
|
| 158 |
+
h.mu.Lock()
|
| 159 |
+
h.configReloadHook = hook
|
| 160 |
+
h.mu.Unlock()
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
// reloadSnapshotConfigLocked clones the runtime config and assigns a reload generation.
|
| 164 |
+
// Callers must hold h.mu.
|
| 165 |
+
func (h *Handler) reloadSnapshotConfigLocked() configReloadSnapshot {
|
| 166 |
+
if h == nil || h.cfg == nil {
|
| 167 |
+
return configReloadSnapshot{}
|
| 168 |
+
}
|
| 169 |
+
h.reloadGeneration++
|
| 170 |
+
return configReloadSnapshot{
|
| 171 |
+
cfg: h.cfg.CloneForRuntime(),
|
| 172 |
+
generation: h.reloadGeneration,
|
| 173 |
+
}
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
// saveConfigAndSnapshotLocked saves h.cfg and returns a full runtime config snapshot.
|
| 177 |
+
// Callers must hold h.mu.
|
| 178 |
+
func (h *Handler) saveConfigAndSnapshotLocked(c *gin.Context) (configReloadSnapshot, bool) {
|
| 179 |
+
if errSave := config.SaveConfigPreserveComments(h.configFilePath, h.cfg); errSave != nil {
|
| 180 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to save config: %v", errSave)})
|
| 181 |
+
return configReloadSnapshot{}, false
|
| 182 |
+
}
|
| 183 |
+
return h.reloadSnapshotConfigLocked(), true
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
// reloadConfigAfterManagementSave reloads from an independent config snapshot.
|
| 187 |
+
// Callers must pass a full Config clone captured immediately after a successful save.
|
| 188 |
+
func (h *Handler) reloadConfigAfterManagementSave(ctx context.Context, snapshot configReloadSnapshot) {
|
| 189 |
+
if h == nil || snapshot.cfg == nil || snapshot.generation == 0 {
|
| 190 |
+
return
|
| 191 |
+
}
|
| 192 |
+
h.reloadMu.Lock()
|
| 193 |
+
defer h.reloadMu.Unlock()
|
| 194 |
+
|
| 195 |
+
h.mu.Lock()
|
| 196 |
+
if snapshot.generation < h.appliedReloadGeneration {
|
| 197 |
+
h.mu.Unlock()
|
| 198 |
+
return
|
| 199 |
+
}
|
| 200 |
+
hook := h.configReloadHook
|
| 201 |
+
host := h.pluginHost
|
| 202 |
+
h.mu.Unlock()
|
| 203 |
+
if hook != nil {
|
| 204 |
+
hook(ctx, snapshot.cfg)
|
| 205 |
+
} else if host != nil {
|
| 206 |
+
host.ApplyConfig(ctx, snapshot.cfg)
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
h.mu.Lock()
|
| 210 |
+
if snapshot.generation > h.appliedReloadGeneration {
|
| 211 |
+
h.appliedReloadGeneration = snapshot.generation
|
| 212 |
+
}
|
| 213 |
+
h.mu.Unlock()
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
// reloadConfigAfterManagementSaveAsync reloads from an independent config snapshot.
|
| 217 |
+
// Callers must pass a full Config clone captured immediately after a successful save.
|
| 218 |
+
func (h *Handler) reloadConfigAfterManagementSaveAsync(ctx context.Context, snapshot configReloadSnapshot) {
|
| 219 |
+
if h == nil || snapshot.cfg == nil || snapshot.generation == 0 {
|
| 220 |
+
return
|
| 221 |
+
}
|
| 222 |
+
reloadCtx := context.Background()
|
| 223 |
+
if ctx != nil {
|
| 224 |
+
reloadCtx = context.WithoutCancel(ctx)
|
| 225 |
+
}
|
| 226 |
+
go func() {
|
| 227 |
+
defer func() {
|
| 228 |
+
if recovered := recover(); recovered != nil {
|
| 229 |
+
log.WithField("panic", recovered).Error("management: async config reload panicked")
|
| 230 |
+
}
|
| 231 |
+
}()
|
| 232 |
+
h.reloadConfigAfterManagementSave(reloadCtx, snapshot)
|
| 233 |
+
}()
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
// SetLocalPassword configures the runtime-local password accepted for localhost requests.
|
| 237 |
+
func (h *Handler) SetLocalPassword(password string) { h.localPassword = password }
|
| 238 |
+
|
| 239 |
+
// SetLogDirectory updates the directory where main.log should be looked up.
|
| 240 |
+
func (h *Handler) SetLogDirectory(dir string) {
|
| 241 |
+
if dir == "" {
|
| 242 |
+
return
|
| 243 |
+
}
|
| 244 |
+
if !filepath.IsAbs(dir) {
|
| 245 |
+
if abs, err := filepath.Abs(dir); err == nil {
|
| 246 |
+
dir = abs
|
| 247 |
+
}
|
| 248 |
+
}
|
| 249 |
+
h.logDir = dir
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
// SetPostAuthHook registers a hook to be called after auth record creation but before persistence.
|
| 253 |
+
func (h *Handler) SetPostAuthHook(hook coreauth.PostAuthHook) {
|
| 254 |
+
h.postAuthHook = hook
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
// SetPostAuthPersistHook registers a hook to be called after auth persistence.
|
| 258 |
+
func (h *Handler) SetPostAuthPersistHook(hook coreauth.PostAuthHook) {
|
| 259 |
+
h.postAuthPersistHook = hook
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
// Middleware enforces access control for management endpoints.
|
| 263 |
+
// All requests (local and remote) require a valid management key.
|
| 264 |
+
// Additionally, remote access requires allow-remote-management=true.
|
| 265 |
+
func (h *Handler) Middleware() gin.HandlerFunc {
|
| 266 |
+
return func(c *gin.Context) {
|
| 267 |
+
c.Header("X-CPA-VERSION", buildinfo.Version)
|
| 268 |
+
c.Header("X-CPA-COMMIT", buildinfo.Commit)
|
| 269 |
+
c.Header("X-CPA-BUILD-DATE", buildinfo.BuildDate)
|
| 270 |
+
c.Header("X-CPA-SUPPORT-PLUGIN", pluginhost.SupportPluginHeaderValue())
|
| 271 |
+
|
| 272 |
+
clientIP := c.ClientIP()
|
| 273 |
+
localClient := clientIP == "127.0.0.1" || clientIP == "::1"
|
| 274 |
+
|
| 275 |
+
// Accept either Authorization: Bearer <key> or X-Management-Key
|
| 276 |
+
var provided string
|
| 277 |
+
if ah := c.GetHeader("Authorization"); ah != "" {
|
| 278 |
+
parts := strings.SplitN(ah, " ", 2)
|
| 279 |
+
if len(parts) == 2 && strings.ToLower(parts[0]) == "bearer" {
|
| 280 |
+
provided = parts[1]
|
| 281 |
+
} else {
|
| 282 |
+
provided = ah
|
| 283 |
+
}
|
| 284 |
+
}
|
| 285 |
+
if provided == "" {
|
| 286 |
+
provided = c.GetHeader("X-Management-Key")
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
allowed, statusCode, errMsg := h.AuthenticateManagementKey(clientIP, localClient, provided)
|
| 290 |
+
if !allowed {
|
| 291 |
+
c.AbortWithStatusJSON(statusCode, gin.H{"error": errMsg})
|
| 292 |
+
return
|
| 293 |
+
}
|
| 294 |
+
c.Next()
|
| 295 |
+
}
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
// AuthenticateManagementKey verifies the provided management key for the given client.
|
| 299 |
+
// It mirrors the behaviour of Middleware() so non-HTTP callers can reuse the same logic.
|
| 300 |
+
func (h *Handler) AuthenticateManagementKey(clientIP string, localClient bool, provided string) (bool, int, string) {
|
| 301 |
+
const maxFailures = 5
|
| 302 |
+
const banDuration = 30 * time.Minute
|
| 303 |
+
|
| 304 |
+
if h == nil {
|
| 305 |
+
return false, http.StatusForbidden, "remote management disabled"
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
cfg := h.cfg
|
| 309 |
+
var (
|
| 310 |
+
allowRemote bool
|
| 311 |
+
secretHash string
|
| 312 |
+
)
|
| 313 |
+
if cfg != nil {
|
| 314 |
+
allowRemote = cfg.RemoteManagement.AllowRemote
|
| 315 |
+
secretHash = cfg.RemoteManagement.SecretKey
|
| 316 |
+
}
|
| 317 |
+
if h.allowRemoteOverride {
|
| 318 |
+
allowRemote = true
|
| 319 |
+
}
|
| 320 |
+
envSecret := h.envSecret
|
| 321 |
+
|
| 322 |
+
now := time.Now()
|
| 323 |
+
h.attemptsMu.Lock()
|
| 324 |
+
ai := h.failedAttempts[clientIP]
|
| 325 |
+
if ai != nil && !ai.blockedUntil.IsZero() {
|
| 326 |
+
if now.Before(ai.blockedUntil) {
|
| 327 |
+
remaining := ai.blockedUntil.Sub(now).Round(time.Second)
|
| 328 |
+
h.attemptsMu.Unlock()
|
| 329 |
+
return false, http.StatusForbidden, fmt.Sprintf("IP banned due to too many failed attempts. Try again in %s", remaining)
|
| 330 |
+
}
|
| 331 |
+
// Ban expired, reset state
|
| 332 |
+
ai.blockedUntil = time.Time{}
|
| 333 |
+
ai.count = 0
|
| 334 |
+
}
|
| 335 |
+
h.attemptsMu.Unlock()
|
| 336 |
+
|
| 337 |
+
if !localClient && !allowRemote {
|
| 338 |
+
return false, http.StatusForbidden, "remote management disabled"
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
fail := func() {
|
| 342 |
+
h.attemptsMu.Lock()
|
| 343 |
+
aip := h.failedAttempts[clientIP]
|
| 344 |
+
if aip == nil {
|
| 345 |
+
aip = &attemptInfo{}
|
| 346 |
+
h.failedAttempts[clientIP] = aip
|
| 347 |
+
}
|
| 348 |
+
aip.count++
|
| 349 |
+
aip.lastActivity = time.Now()
|
| 350 |
+
if aip.count >= maxFailures {
|
| 351 |
+
aip.blockedUntil = time.Now().Add(banDuration)
|
| 352 |
+
aip.count = 0
|
| 353 |
+
}
|
| 354 |
+
h.attemptsMu.Unlock()
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
reset := func() {
|
| 358 |
+
h.attemptsMu.Lock()
|
| 359 |
+
if ai := h.failedAttempts[clientIP]; ai != nil {
|
| 360 |
+
ai.count = 0
|
| 361 |
+
ai.blockedUntil = time.Time{}
|
| 362 |
+
}
|
| 363 |
+
h.attemptsMu.Unlock()
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
if secretHash == "" && envSecret == "" {
|
| 367 |
+
return false, http.StatusForbidden, "remote management key not set"
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
if provided == "" {
|
| 371 |
+
fail()
|
| 372 |
+
return false, http.StatusUnauthorized, "missing management key"
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
if localClient {
|
| 376 |
+
if lp := h.localPassword; lp != "" {
|
| 377 |
+
if subtle.ConstantTimeCompare([]byte(provided), []byte(lp)) == 1 {
|
| 378 |
+
reset()
|
| 379 |
+
return true, 0, ""
|
| 380 |
+
}
|
| 381 |
+
}
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
if envSecret != "" && subtle.ConstantTimeCompare([]byte(provided), []byte(envSecret)) == 1 {
|
| 385 |
+
reset()
|
| 386 |
+
return true, 0, ""
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
if secretHash == "" || bcrypt.CompareHashAndPassword([]byte(secretHash), []byte(provided)) != nil {
|
| 390 |
+
fail()
|
| 391 |
+
return false, http.StatusUnauthorized, "invalid management key"
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
reset()
|
| 395 |
+
|
| 396 |
+
return true, 0, ""
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
// persist saves the current in-memory config to disk.
|
| 400 |
+
func (h *Handler) persist(c *gin.Context) bool {
|
| 401 |
+
h.mu.Lock()
|
| 402 |
+
defer h.mu.Unlock()
|
| 403 |
+
return h.persistLocked(c)
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
// persistLocked saves the current in-memory config to disk.
|
| 407 |
+
// It expects the caller to hold h.mu.
|
| 408 |
+
func (h *Handler) persistLocked(c *gin.Context) bool {
|
| 409 |
+
// Preserve comments when writing
|
| 410 |
+
if err := config.SaveConfigPreserveComments(h.configFilePath, h.cfg); err != nil {
|
| 411 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to save config: %v", err)})
|
| 412 |
+
return false
|
| 413 |
+
}
|
| 414 |
+
snapshot := h.reloadSnapshotConfigLocked()
|
| 415 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
| 416 |
+
var reqCtx context.Context
|
| 417 |
+
if c != nil && c.Request != nil {
|
| 418 |
+
reqCtx = c.Request.Context()
|
| 419 |
+
}
|
| 420 |
+
h.reloadConfigAfterManagementSaveAsync(reqCtx, snapshot)
|
| 421 |
+
return true
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
// Helper methods for simple types
|
| 425 |
+
func (h *Handler) updateBoolField(c *gin.Context, set func(bool)) {
|
| 426 |
+
var body struct {
|
| 427 |
+
Value *bool `json:"value"`
|
| 428 |
+
}
|
| 429 |
+
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
|
| 430 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
|
| 431 |
+
return
|
| 432 |
+
}
|
| 433 |
+
set(*body.Value)
|
| 434 |
+
h.persist(c)
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
func (h *Handler) updateIntField(c *gin.Context, set func(int)) {
|
| 438 |
+
var body struct {
|
| 439 |
+
Value *int `json:"value"`
|
| 440 |
+
}
|
| 441 |
+
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
|
| 442 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
|
| 443 |
+
return
|
| 444 |
+
}
|
| 445 |
+
set(*body.Value)
|
| 446 |
+
h.persist(c)
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
func (h *Handler) updateStringField(c *gin.Context, set func(string)) {
|
| 450 |
+
var body struct {
|
| 451 |
+
Value *string `json:"value"`
|
| 452 |
+
}
|
| 453 |
+
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
|
| 454 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
|
| 455 |
+
return
|
| 456 |
+
}
|
| 457 |
+
set(*body.Value)
|
| 458 |
+
h.persist(c)
|
| 459 |
+
}
|
internal/api/handlers/management/handler_test.go
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
"net/http/httptest"
|
| 6 |
+
"strings"
|
| 7 |
+
"testing"
|
| 8 |
+
|
| 9 |
+
"github.com/gin-gonic/gin"
|
| 10 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 11 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
func TestAuthenticateManagementKey_LocalhostIPBan_BlocksCorrectKeyDuringBan(t *testing.T) {
|
| 15 |
+
h := &Handler{
|
| 16 |
+
cfg: &config.Config{},
|
| 17 |
+
failedAttempts: make(map[string]*attemptInfo),
|
| 18 |
+
envSecret: "test-secret",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
for i := 0; i < 5; i++ {
|
| 22 |
+
allowed, statusCode, errMsg := h.AuthenticateManagementKey("127.0.0.1", true, "wrong-secret")
|
| 23 |
+
if allowed {
|
| 24 |
+
t.Fatalf("expected auth to be denied at attempt %d", i+1)
|
| 25 |
+
}
|
| 26 |
+
if statusCode != http.StatusUnauthorized || errMsg != "invalid management key" {
|
| 27 |
+
t.Fatalf("unexpected auth failure at attempt %d: status=%d msg=%q", i+1, statusCode, errMsg)
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
allowed, statusCode, errMsg := h.AuthenticateManagementKey("127.0.0.1", true, "test-secret")
|
| 32 |
+
if allowed {
|
| 33 |
+
t.Fatalf("expected correct key to be denied while banned")
|
| 34 |
+
}
|
| 35 |
+
if statusCode != http.StatusForbidden {
|
| 36 |
+
t.Fatalf("expected forbidden status while banned, got %d", statusCode)
|
| 37 |
+
}
|
| 38 |
+
if !strings.HasPrefix(errMsg, "IP banned due to too many failed attempts. Try again in") {
|
| 39 |
+
t.Fatalf("unexpected banned message: %q", errMsg)
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
func TestMiddlewareSetsSupportPluginHeader(t *testing.T) {
|
| 44 |
+
|
| 45 |
+
h := &Handler{
|
| 46 |
+
cfg: &config.Config{},
|
| 47 |
+
failedAttempts: make(map[string]*attemptInfo),
|
| 48 |
+
envSecret: "test-secret",
|
| 49 |
+
}
|
| 50 |
+
middleware := h.Middleware()
|
| 51 |
+
|
| 52 |
+
t.Run("invalid key", func(t *testing.T) {
|
| 53 |
+
rec := httptest.NewRecorder()
|
| 54 |
+
c, _ := gin.CreateTestContext(rec)
|
| 55 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/config", nil)
|
| 56 |
+
c.Request.RemoteAddr = "127.0.0.1:12345"
|
| 57 |
+
c.Request.Header.Set("X-Management-Key", "wrong-secret")
|
| 58 |
+
|
| 59 |
+
middleware(c)
|
| 60 |
+
|
| 61 |
+
if rec.Code != http.StatusUnauthorized {
|
| 62 |
+
t.Fatalf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
|
| 63 |
+
}
|
| 64 |
+
if got := rec.Header().Get("X-CPA-SUPPORT-PLUGIN"); got != pluginhost.SupportPluginHeaderValue() {
|
| 65 |
+
t.Fatalf("X-CPA-SUPPORT-PLUGIN = %q, want %q", got, pluginhost.SupportPluginHeaderValue())
|
| 66 |
+
}
|
| 67 |
+
})
|
| 68 |
+
|
| 69 |
+
t.Run("valid key", func(t *testing.T) {
|
| 70 |
+
engine := gin.New()
|
| 71 |
+
engine.GET("/v0/management/config", middleware, func(c *gin.Context) {
|
| 72 |
+
c.Status(http.StatusOK)
|
| 73 |
+
})
|
| 74 |
+
|
| 75 |
+
rec := httptest.NewRecorder()
|
| 76 |
+
req := httptest.NewRequest(http.MethodGet, "/v0/management/config", nil)
|
| 77 |
+
req.RemoteAddr = "127.0.0.1:12345"
|
| 78 |
+
req.Header.Set("X-Management-Key", "test-secret")
|
| 79 |
+
engine.ServeHTTP(rec, req)
|
| 80 |
+
|
| 81 |
+
if rec.Code != http.StatusOK {
|
| 82 |
+
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
|
| 83 |
+
}
|
| 84 |
+
if got := rec.Header().Get("X-CPA-SUPPORT-PLUGIN"); got != pluginhost.SupportPluginHeaderValue() {
|
| 85 |
+
t.Fatalf("X-CPA-SUPPORT-PLUGIN = %q, want %q", got, pluginhost.SupportPluginHeaderValue())
|
| 86 |
+
}
|
| 87 |
+
})
|
| 88 |
+
}
|
internal/api/handlers/management/logs.go
ADDED
|
@@ -0,0 +1,1310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"bufio"
|
| 5 |
+
"bytes"
|
| 6 |
+
"crypto/sha256"
|
| 7 |
+
"encoding/base64"
|
| 8 |
+
"encoding/json"
|
| 9 |
+
"errors"
|
| 10 |
+
"fmt"
|
| 11 |
+
"io"
|
| 12 |
+
"math"
|
| 13 |
+
"net/http"
|
| 14 |
+
"os"
|
| 15 |
+
"path/filepath"
|
| 16 |
+
"sort"
|
| 17 |
+
"strconv"
|
| 18 |
+
"strings"
|
| 19 |
+
"time"
|
| 20 |
+
|
| 21 |
+
"github.com/gin-gonic/gin"
|
| 22 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
const (
|
| 26 |
+
defaultLogFileName = "main.log"
|
| 27 |
+
logScannerInitialBuffer = 64 * 1024
|
| 28 |
+
logScannerMaxBuffer = 8 * 1024 * 1024
|
| 29 |
+
logCursorVersion = 1
|
| 30 |
+
logCursorFingerprintMax = 4 * 1024
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
// GetLogs returns log lines with optional incremental loading.
|
| 34 |
+
//
|
| 35 |
+
// The legacy timestamp path keeps line-count as the total scanned line count for
|
| 36 |
+
// compatibility. Cursor and tail reads avoid scanning older files, so line-count
|
| 37 |
+
// is the number of returned lines there. A cursor emitted by the legacy path
|
| 38 |
+
// points at the latest complete log boundary; combining after with limit is
|
| 39 |
+
// therefore tail semantics and does not replay lines trimmed by limit.
|
| 40 |
+
func (h *Handler) GetLogs(c *gin.Context) {
|
| 41 |
+
if h == nil {
|
| 42 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
|
| 43 |
+
return
|
| 44 |
+
}
|
| 45 |
+
if h.cfg == nil {
|
| 46 |
+
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"})
|
| 47 |
+
return
|
| 48 |
+
}
|
| 49 |
+
if !h.cfg.LoggingToFile {
|
| 50 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "logging to file disabled"})
|
| 51 |
+
return
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
logDir := h.logDirectory()
|
| 55 |
+
if strings.TrimSpace(logDir) == "" {
|
| 56 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"})
|
| 57 |
+
return
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
rawCursor := strings.TrimSpace(c.Query("cursor"))
|
| 61 |
+
files, err := h.collectLogFiles(logDir)
|
| 62 |
+
if err != nil {
|
| 63 |
+
if os.IsNotExist(err) {
|
| 64 |
+
cutoff := parseCutoff(c.Query("after"))
|
| 65 |
+
latest := cutoff
|
| 66 |
+
if rawCursor != "" {
|
| 67 |
+
if cursor, errCursor := decodeLogCursor(rawCursor); errCursor == nil && cursor.LatestTimestamp > latest {
|
| 68 |
+
latest = cursor.LatestTimestamp
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
writeLogsResponse(c, []string{}, 0, latest, "", rawCursor != "")
|
| 72 |
+
return
|
| 73 |
+
}
|
| 74 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to list log files: %v", err)})
|
| 75 |
+
return
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
limit, errLimit := parseLimit(c.Query("limit"))
|
| 79 |
+
if errLimit != nil {
|
| 80 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid limit: %v", errLimit)})
|
| 81 |
+
return
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
cutoff := parseCutoff(c.Query("after"))
|
| 85 |
+
if rawCursor != "" {
|
| 86 |
+
result, reset, errCursor := readLogFilesFromCursor(logDir, files, rawCursor, limit)
|
| 87 |
+
if errCursor != nil {
|
| 88 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log files: %v", errCursor)})
|
| 89 |
+
return
|
| 90 |
+
}
|
| 91 |
+
if reset {
|
| 92 |
+
result, errCursor = tailLogFiles(files, limit, result.latest)
|
| 93 |
+
if errCursor != nil {
|
| 94 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log files: %v", errCursor)})
|
| 95 |
+
return
|
| 96 |
+
}
|
| 97 |
+
writeLogsResponse(c, result.lines, len(result.lines), result.latest, result.nextCursor, true)
|
| 98 |
+
return
|
| 99 |
+
}
|
| 100 |
+
writeLogsResponse(c, result.lines, len(result.lines), result.latest, result.nextCursor, false)
|
| 101 |
+
return
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
if cutoff == 0 && limit > 0 {
|
| 105 |
+
result, errTail := tailLogFiles(files, limit, 0)
|
| 106 |
+
if errTail != nil {
|
| 107 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log files: %v", errTail)})
|
| 108 |
+
return
|
| 109 |
+
}
|
| 110 |
+
writeLogsResponse(c, result.lines, len(result.lines), result.latest, result.nextCursor, false)
|
| 111 |
+
return
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
acc := newLogAccumulator(cutoff, limit)
|
| 115 |
+
for i := range files {
|
| 116 |
+
if errProcess := acc.consumeFile(files[i]); errProcess != nil {
|
| 117 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log file: %v", errProcess)})
|
| 118 |
+
return
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
lines, total, latest := acc.result()
|
| 123 |
+
if latest == 0 || latest < cutoff {
|
| 124 |
+
latest = cutoff
|
| 125 |
+
}
|
| 126 |
+
nextCursor, errCursor := cursorForLatestLogFile(files, latest)
|
| 127 |
+
if errCursor != nil {
|
| 128 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to prepare log cursor: %v", errCursor)})
|
| 129 |
+
return
|
| 130 |
+
}
|
| 131 |
+
writeLogsResponse(c, lines, total, latest, nextCursor, false)
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
// DeleteLogs removes all rotated log files and truncates the active log.
|
| 135 |
+
func (h *Handler) DeleteLogs(c *gin.Context) {
|
| 136 |
+
if h == nil {
|
| 137 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
|
| 138 |
+
return
|
| 139 |
+
}
|
| 140 |
+
if h.cfg == nil {
|
| 141 |
+
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"})
|
| 142 |
+
return
|
| 143 |
+
}
|
| 144 |
+
if !h.cfg.LoggingToFile {
|
| 145 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "logging to file disabled"})
|
| 146 |
+
return
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
dir := h.logDirectory()
|
| 150 |
+
if strings.TrimSpace(dir) == "" {
|
| 151 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"})
|
| 152 |
+
return
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
entries, err := os.ReadDir(dir)
|
| 156 |
+
if err != nil {
|
| 157 |
+
if os.IsNotExist(err) {
|
| 158 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "log directory not found"})
|
| 159 |
+
return
|
| 160 |
+
}
|
| 161 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to list log directory: %v", err)})
|
| 162 |
+
return
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
removed := 0
|
| 166 |
+
for _, entry := range entries {
|
| 167 |
+
if entry.IsDir() {
|
| 168 |
+
continue
|
| 169 |
+
}
|
| 170 |
+
name := entry.Name()
|
| 171 |
+
fullPath := filepath.Join(dir, name)
|
| 172 |
+
if name == defaultLogFileName {
|
| 173 |
+
if errTrunc := os.Truncate(fullPath, 0); errTrunc != nil && !os.IsNotExist(errTrunc) {
|
| 174 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to truncate log file: %v", errTrunc)})
|
| 175 |
+
return
|
| 176 |
+
}
|
| 177 |
+
continue
|
| 178 |
+
}
|
| 179 |
+
if isRotatedLogFile(name) {
|
| 180 |
+
if errRemove := os.Remove(fullPath); errRemove != nil && !os.IsNotExist(errRemove) {
|
| 181 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to remove %s: %v", name, errRemove)})
|
| 182 |
+
return
|
| 183 |
+
}
|
| 184 |
+
removed++
|
| 185 |
+
}
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
c.JSON(http.StatusOK, gin.H{
|
| 189 |
+
"success": true,
|
| 190 |
+
"message": "Logs cleared successfully",
|
| 191 |
+
"removed": removed,
|
| 192 |
+
})
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
// GetRequestErrorLogs lists error request log files when RequestLog is disabled.
|
| 196 |
+
// It returns an empty list when RequestLog is enabled.
|
| 197 |
+
func (h *Handler) GetRequestErrorLogs(c *gin.Context) {
|
| 198 |
+
if h == nil {
|
| 199 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
|
| 200 |
+
return
|
| 201 |
+
}
|
| 202 |
+
if h.cfg == nil {
|
| 203 |
+
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"})
|
| 204 |
+
return
|
| 205 |
+
}
|
| 206 |
+
if h.cfg.RequestLog {
|
| 207 |
+
c.JSON(http.StatusOK, gin.H{"files": []any{}})
|
| 208 |
+
return
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
dir := h.logDirectory()
|
| 212 |
+
if strings.TrimSpace(dir) == "" {
|
| 213 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"})
|
| 214 |
+
return
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
entries, err := os.ReadDir(dir)
|
| 218 |
+
if err != nil {
|
| 219 |
+
if os.IsNotExist(err) {
|
| 220 |
+
c.JSON(http.StatusOK, gin.H{"files": []any{}})
|
| 221 |
+
return
|
| 222 |
+
}
|
| 223 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to list request error logs: %v", err)})
|
| 224 |
+
return
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
type errorLog struct {
|
| 228 |
+
Name string `json:"name"`
|
| 229 |
+
Size int64 `json:"size"`
|
| 230 |
+
Modified int64 `json:"modified"`
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
files := make([]errorLog, 0, len(entries))
|
| 234 |
+
for _, entry := range entries {
|
| 235 |
+
if entry.IsDir() {
|
| 236 |
+
continue
|
| 237 |
+
}
|
| 238 |
+
name := entry.Name()
|
| 239 |
+
if !strings.HasPrefix(name, "error-") || !strings.HasSuffix(name, ".log") {
|
| 240 |
+
continue
|
| 241 |
+
}
|
| 242 |
+
info, errInfo := entry.Info()
|
| 243 |
+
if errInfo != nil {
|
| 244 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log info for %s: %v", name, errInfo)})
|
| 245 |
+
return
|
| 246 |
+
}
|
| 247 |
+
files = append(files, errorLog{
|
| 248 |
+
Name: name,
|
| 249 |
+
Size: info.Size(),
|
| 250 |
+
Modified: info.ModTime().Unix(),
|
| 251 |
+
})
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
sort.Slice(files, func(i, j int) bool { return files[i].Modified > files[j].Modified })
|
| 255 |
+
|
| 256 |
+
c.JSON(http.StatusOK, gin.H{"files": files})
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
// GetRequestLogByID finds and downloads a request log file by its request ID.
|
| 260 |
+
// The ID is matched against the suffix of log file names (format: *-{requestID}.log).
|
| 261 |
+
func (h *Handler) GetRequestLogByID(c *gin.Context) {
|
| 262 |
+
if h == nil {
|
| 263 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
|
| 264 |
+
return
|
| 265 |
+
}
|
| 266 |
+
if h.cfg == nil {
|
| 267 |
+
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"})
|
| 268 |
+
return
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
dir := h.logDirectory()
|
| 272 |
+
if strings.TrimSpace(dir) == "" {
|
| 273 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"})
|
| 274 |
+
return
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
requestID := strings.TrimSpace(c.Param("id"))
|
| 278 |
+
if requestID == "" {
|
| 279 |
+
requestID = strings.TrimSpace(c.Query("id"))
|
| 280 |
+
}
|
| 281 |
+
if requestID == "" {
|
| 282 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "missing request ID"})
|
| 283 |
+
return
|
| 284 |
+
}
|
| 285 |
+
if strings.ContainsAny(requestID, "/\\") {
|
| 286 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request ID"})
|
| 287 |
+
return
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
entries, err := os.ReadDir(dir)
|
| 291 |
+
if err != nil {
|
| 292 |
+
if os.IsNotExist(err) {
|
| 293 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "log directory not found"})
|
| 294 |
+
return
|
| 295 |
+
}
|
| 296 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to list log directory: %v", err)})
|
| 297 |
+
return
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
suffix := "-" + requestID + ".log"
|
| 301 |
+
var matchedFile string
|
| 302 |
+
for _, entry := range entries {
|
| 303 |
+
if entry.IsDir() {
|
| 304 |
+
continue
|
| 305 |
+
}
|
| 306 |
+
name := entry.Name()
|
| 307 |
+
if strings.HasSuffix(name, suffix) {
|
| 308 |
+
matchedFile = name
|
| 309 |
+
break
|
| 310 |
+
}
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
if matchedFile == "" {
|
| 314 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "log file not found for the given request ID"})
|
| 315 |
+
return
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
dirAbs, errAbs := filepath.Abs(dir)
|
| 319 |
+
if errAbs != nil {
|
| 320 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to resolve log directory: %v", errAbs)})
|
| 321 |
+
return
|
| 322 |
+
}
|
| 323 |
+
fullPath := filepath.Clean(filepath.Join(dirAbs, matchedFile))
|
| 324 |
+
prefix := dirAbs + string(os.PathSeparator)
|
| 325 |
+
if !strings.HasPrefix(fullPath, prefix) {
|
| 326 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file path"})
|
| 327 |
+
return
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
info, errStat := os.Stat(fullPath)
|
| 331 |
+
if errStat != nil {
|
| 332 |
+
if os.IsNotExist(errStat) {
|
| 333 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "log file not found"})
|
| 334 |
+
return
|
| 335 |
+
}
|
| 336 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log file: %v", errStat)})
|
| 337 |
+
return
|
| 338 |
+
}
|
| 339 |
+
if info.IsDir() {
|
| 340 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file"})
|
| 341 |
+
return
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
c.FileAttachment(fullPath, matchedFile)
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
// DownloadRequestErrorLog downloads a specific error request log file by name.
|
| 348 |
+
func (h *Handler) DownloadRequestErrorLog(c *gin.Context) {
|
| 349 |
+
if h == nil {
|
| 350 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
|
| 351 |
+
return
|
| 352 |
+
}
|
| 353 |
+
if h.cfg == nil {
|
| 354 |
+
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"})
|
| 355 |
+
return
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
dir := h.logDirectory()
|
| 359 |
+
if strings.TrimSpace(dir) == "" {
|
| 360 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"})
|
| 361 |
+
return
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
name := strings.TrimSpace(c.Param("name"))
|
| 365 |
+
if name == "" || strings.Contains(name, "/") || strings.Contains(name, "\\") {
|
| 366 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file name"})
|
| 367 |
+
return
|
| 368 |
+
}
|
| 369 |
+
if !strings.HasPrefix(name, "error-") || !strings.HasSuffix(name, ".log") {
|
| 370 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "log file not found"})
|
| 371 |
+
return
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
dirAbs, errAbs := filepath.Abs(dir)
|
| 375 |
+
if errAbs != nil {
|
| 376 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to resolve log directory: %v", errAbs)})
|
| 377 |
+
return
|
| 378 |
+
}
|
| 379 |
+
fullPath := filepath.Clean(filepath.Join(dirAbs, name))
|
| 380 |
+
prefix := dirAbs + string(os.PathSeparator)
|
| 381 |
+
if !strings.HasPrefix(fullPath, prefix) {
|
| 382 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file path"})
|
| 383 |
+
return
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
info, errStat := os.Stat(fullPath)
|
| 387 |
+
if errStat != nil {
|
| 388 |
+
if os.IsNotExist(errStat) {
|
| 389 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "log file not found"})
|
| 390 |
+
return
|
| 391 |
+
}
|
| 392 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log file: %v", errStat)})
|
| 393 |
+
return
|
| 394 |
+
}
|
| 395 |
+
if info.IsDir() {
|
| 396 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file"})
|
| 397 |
+
return
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
c.FileAttachment(fullPath, name)
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
func (h *Handler) logDirectory() string {
|
| 404 |
+
if h == nil {
|
| 405 |
+
return ""
|
| 406 |
+
}
|
| 407 |
+
if h.logDir != "" {
|
| 408 |
+
return h.logDir
|
| 409 |
+
}
|
| 410 |
+
return logging.ResolveLogDirectory(h.cfg)
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
func (h *Handler) collectLogFiles(dir string) ([]string, error) {
|
| 414 |
+
entries, err := os.ReadDir(dir)
|
| 415 |
+
if err != nil {
|
| 416 |
+
return nil, err
|
| 417 |
+
}
|
| 418 |
+
type candidate struct {
|
| 419 |
+
path string
|
| 420 |
+
order int64
|
| 421 |
+
}
|
| 422 |
+
cands := make([]candidate, 0, len(entries))
|
| 423 |
+
for _, entry := range entries {
|
| 424 |
+
if entry.IsDir() {
|
| 425 |
+
continue
|
| 426 |
+
}
|
| 427 |
+
name := entry.Name()
|
| 428 |
+
if name == defaultLogFileName {
|
| 429 |
+
cands = append(cands, candidate{path: filepath.Join(dir, name), order: 0})
|
| 430 |
+
continue
|
| 431 |
+
}
|
| 432 |
+
if order, ok := rotationOrder(name); ok {
|
| 433 |
+
cands = append(cands, candidate{path: filepath.Join(dir, name), order: order})
|
| 434 |
+
}
|
| 435 |
+
}
|
| 436 |
+
if len(cands) == 0 {
|
| 437 |
+
return []string{}, nil
|
| 438 |
+
}
|
| 439 |
+
sort.Slice(cands, func(i, j int) bool { return cands[i].order < cands[j].order })
|
| 440 |
+
paths := make([]string, 0, len(cands))
|
| 441 |
+
for i := len(cands) - 1; i >= 0; i-- {
|
| 442 |
+
paths = append(paths, cands[i].path)
|
| 443 |
+
}
|
| 444 |
+
return paths, nil
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
type logAccumulator struct {
|
| 448 |
+
cutoff int64
|
| 449 |
+
limit int
|
| 450 |
+
lines []string
|
| 451 |
+
total int
|
| 452 |
+
latest int64
|
| 453 |
+
include bool
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
func newLogAccumulator(cutoff int64, limit int) *logAccumulator {
|
| 457 |
+
capacity := 256
|
| 458 |
+
if limit > 0 && limit < capacity {
|
| 459 |
+
capacity = limit
|
| 460 |
+
}
|
| 461 |
+
return &logAccumulator{
|
| 462 |
+
cutoff: cutoff,
|
| 463 |
+
limit: limit,
|
| 464 |
+
lines: make([]string, 0, capacity),
|
| 465 |
+
}
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
func (acc *logAccumulator) consumeFile(path string) error {
|
| 469 |
+
file, err := os.Open(path)
|
| 470 |
+
if err != nil {
|
| 471 |
+
if os.IsNotExist(err) {
|
| 472 |
+
return nil
|
| 473 |
+
}
|
| 474 |
+
return err
|
| 475 |
+
}
|
| 476 |
+
defer func() {
|
| 477 |
+
_ = file.Close()
|
| 478 |
+
}()
|
| 479 |
+
|
| 480 |
+
scanner := bufio.NewScanner(file)
|
| 481 |
+
buf := make([]byte, 0, logScannerInitialBuffer)
|
| 482 |
+
scanner.Buffer(buf, logScannerMaxBuffer)
|
| 483 |
+
for scanner.Scan() {
|
| 484 |
+
acc.addLine(scanner.Text())
|
| 485 |
+
}
|
| 486 |
+
if errScan := scanner.Err(); errScan != nil {
|
| 487 |
+
return errScan
|
| 488 |
+
}
|
| 489 |
+
return nil
|
| 490 |
+
}
|
| 491 |
+
|
| 492 |
+
func (acc *logAccumulator) addLine(raw string) {
|
| 493 |
+
line := strings.TrimRight(raw, "\r")
|
| 494 |
+
acc.total++
|
| 495 |
+
ts := parseTimestamp(line)
|
| 496 |
+
if ts > acc.latest {
|
| 497 |
+
acc.latest = ts
|
| 498 |
+
}
|
| 499 |
+
if ts > 0 {
|
| 500 |
+
acc.include = acc.cutoff == 0 || ts > acc.cutoff
|
| 501 |
+
if acc.cutoff == 0 || acc.include {
|
| 502 |
+
acc.append(line)
|
| 503 |
+
}
|
| 504 |
+
return
|
| 505 |
+
}
|
| 506 |
+
if acc.cutoff == 0 || acc.include {
|
| 507 |
+
acc.append(line)
|
| 508 |
+
}
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
func (acc *logAccumulator) append(line string) {
|
| 512 |
+
acc.lines = append(acc.lines, line)
|
| 513 |
+
if acc.limit > 0 && len(acc.lines) > acc.limit {
|
| 514 |
+
acc.lines = acc.lines[len(acc.lines)-acc.limit:]
|
| 515 |
+
}
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
func (acc *logAccumulator) result() ([]string, int, int64) {
|
| 519 |
+
if acc.lines == nil {
|
| 520 |
+
acc.lines = []string{}
|
| 521 |
+
}
|
| 522 |
+
return acc.lines, acc.total, acc.latest
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
type logCursor struct {
|
| 526 |
+
Version int `json:"v"`
|
| 527 |
+
File string `json:"file"`
|
| 528 |
+
Offset int64 `json:"offset"`
|
| 529 |
+
Size int64 `json:"size"`
|
| 530 |
+
ModTime int64 `json:"modTime"`
|
| 531 |
+
ModTimeUnixNano int64 `json:"modTimeUnixNano,omitempty"`
|
| 532 |
+
LatestTimestamp int64 `json:"latestTimestamp"`
|
| 533 |
+
Fingerprint string `json:"fingerprint"`
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
type completeLogRead struct {
|
| 537 |
+
lines []string
|
| 538 |
+
endOffset int64
|
| 539 |
+
latest int64
|
| 540 |
+
hitLimit bool
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
type logReadResult struct {
|
| 544 |
+
lines []string
|
| 545 |
+
latest int64
|
| 546 |
+
nextCursor string
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
func writeLogsResponse(c *gin.Context, lines []string, lineCount int, latest int64, nextCursor string, cursorReset bool) {
|
| 550 |
+
if lines == nil {
|
| 551 |
+
lines = []string{}
|
| 552 |
+
}
|
| 553 |
+
payload := gin.H{
|
| 554 |
+
"lines": lines,
|
| 555 |
+
"line-count": lineCount,
|
| 556 |
+
"latest-timestamp": latest,
|
| 557 |
+
"next-cursor": nextCursor,
|
| 558 |
+
}
|
| 559 |
+
if cursorReset {
|
| 560 |
+
payload["cursor-reset"] = true
|
| 561 |
+
}
|
| 562 |
+
c.JSON(http.StatusOK, payload)
|
| 563 |
+
}
|
| 564 |
+
|
| 565 |
+
func tailLogFiles(files []string, limit int, fallbackLatest int64) (logReadResult, error) {
|
| 566 |
+
result := logReadResult{
|
| 567 |
+
lines: []string{},
|
| 568 |
+
latest: fallbackLatest,
|
| 569 |
+
}
|
| 570 |
+
for i := len(files) - 1; i >= 0; i-- {
|
| 571 |
+
remaining := 0
|
| 572 |
+
if limit > 0 {
|
| 573 |
+
remaining = limit - len(result.lines)
|
| 574 |
+
if remaining <= 0 {
|
| 575 |
+
break
|
| 576 |
+
}
|
| 577 |
+
}
|
| 578 |
+
read, errRead := readTailLogLines(files[i], remaining)
|
| 579 |
+
if errRead != nil {
|
| 580 |
+
if errors.Is(errRead, os.ErrNotExist) {
|
| 581 |
+
continue
|
| 582 |
+
}
|
| 583 |
+
return logReadResult{}, errRead
|
| 584 |
+
}
|
| 585 |
+
if len(read.lines) == 0 {
|
| 586 |
+
continue
|
| 587 |
+
}
|
| 588 |
+
result.lines = append(append([]string{}, read.lines...), result.lines...)
|
| 589 |
+
if read.latest > result.latest {
|
| 590 |
+
result.latest = read.latest
|
| 591 |
+
}
|
| 592 |
+
}
|
| 593 |
+
nextCursor, errCursor := cursorForLatestLogFile(files, result.latest)
|
| 594 |
+
if errCursor != nil {
|
| 595 |
+
return logReadResult{}, errCursor
|
| 596 |
+
}
|
| 597 |
+
result.nextCursor = nextCursor
|
| 598 |
+
return result, nil
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
func readTailLogLines(path string, limit int) (completeLogRead, error) {
|
| 602 |
+
boundary, errBoundary := completeLogBoundary(path)
|
| 603 |
+
if errBoundary != nil {
|
| 604 |
+
return completeLogRead{}, errBoundary
|
| 605 |
+
}
|
| 606 |
+
if boundary == 0 {
|
| 607 |
+
return completeLogRead{lines: []string{}}, nil
|
| 608 |
+
}
|
| 609 |
+
start, errStart := tailStartOffset(path, boundary, limit)
|
| 610 |
+
if errStart != nil {
|
| 611 |
+
return completeLogRead{}, errStart
|
| 612 |
+
}
|
| 613 |
+
return readCompleteLogLines(path, start, boundary, limit)
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
func tailStartOffset(path string, boundary int64, limit int) (int64, error) {
|
| 617 |
+
if limit <= 0 {
|
| 618 |
+
return 0, nil
|
| 619 |
+
}
|
| 620 |
+
file, errOpen := os.Open(path)
|
| 621 |
+
if errOpen != nil {
|
| 622 |
+
return 0, errOpen
|
| 623 |
+
}
|
| 624 |
+
defer func() {
|
| 625 |
+
_ = file.Close()
|
| 626 |
+
}()
|
| 627 |
+
buf := make([]byte, 32*1024)
|
| 628 |
+
pos := boundary
|
| 629 |
+
lineBreaks := 0
|
| 630 |
+
for pos > 0 {
|
| 631 |
+
chunk := minInt64(int64(len(buf)), pos)
|
| 632 |
+
pos -= chunk
|
| 633 |
+
n, errRead := file.ReadAt(buf[:chunk], pos)
|
| 634 |
+
if errRead != nil && errRead != io.EOF {
|
| 635 |
+
return 0, errRead
|
| 636 |
+
}
|
| 637 |
+
if n <= 0 {
|
| 638 |
+
continue
|
| 639 |
+
}
|
| 640 |
+
data := buf[:n]
|
| 641 |
+
for len(data) > 0 {
|
| 642 |
+
idx := bytes.LastIndexByte(data, '\n')
|
| 643 |
+
if idx < 0 {
|
| 644 |
+
break
|
| 645 |
+
}
|
| 646 |
+
lineBreaks++
|
| 647 |
+
if lineBreaks > limit {
|
| 648 |
+
return pos + int64(idx) + 1, nil
|
| 649 |
+
}
|
| 650 |
+
data = data[:idx]
|
| 651 |
+
}
|
| 652 |
+
}
|
| 653 |
+
return 0, nil
|
| 654 |
+
}
|
| 655 |
+
|
| 656 |
+
func cursorForLatestLogFile(files []string, latest int64) (string, error) {
|
| 657 |
+
for i := len(files) - 1; i >= 0; i-- {
|
| 658 |
+
boundary, errBoundary := completeLogBoundary(files[i])
|
| 659 |
+
if errBoundary != nil {
|
| 660 |
+
if errors.Is(errBoundary, os.ErrNotExist) {
|
| 661 |
+
continue
|
| 662 |
+
}
|
| 663 |
+
return "", errBoundary
|
| 664 |
+
}
|
| 665 |
+
cursor, errCursor := newLogCursor(files[i], boundary, latest)
|
| 666 |
+
if errCursor != nil {
|
| 667 |
+
if errors.Is(errCursor, os.ErrNotExist) {
|
| 668 |
+
continue
|
| 669 |
+
}
|
| 670 |
+
return "", errCursor
|
| 671 |
+
}
|
| 672 |
+
return cursor, nil
|
| 673 |
+
}
|
| 674 |
+
return "", nil
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
func readLogFilesFromCursor(logDir string, files []string, raw string, limit int) (logReadResult, bool, error) {
|
| 678 |
+
cursor, errDecode := decodeLogCursor(raw)
|
| 679 |
+
if errDecode != nil {
|
| 680 |
+
return logReadResult{lines: []string{}}, true, nil
|
| 681 |
+
}
|
| 682 |
+
result := logReadResult{
|
| 683 |
+
lines: []string{},
|
| 684 |
+
latest: cursor.LatestTimestamp,
|
| 685 |
+
nextCursor: raw,
|
| 686 |
+
}
|
| 687 |
+
if _, errPath := safeLogFilePath(logDir, cursor.File); errPath != nil {
|
| 688 |
+
return result, true, nil
|
| 689 |
+
}
|
| 690 |
+
startIndex, found, errLocate := locateLogCursorFile(files, cursor)
|
| 691 |
+
if errLocate != nil {
|
| 692 |
+
return result, false, errLocate
|
| 693 |
+
}
|
| 694 |
+
if !found {
|
| 695 |
+
return result, true, nil
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
currentCursorPath := files[startIndex]
|
| 699 |
+
currentCursorOffset := cursor.Offset
|
| 700 |
+
advanced := false
|
| 701 |
+
for i := startIndex; i < len(files); i++ {
|
| 702 |
+
remaining := 0
|
| 703 |
+
if limit > 0 {
|
| 704 |
+
remaining = limit - len(result.lines)
|
| 705 |
+
if remaining <= 0 {
|
| 706 |
+
break
|
| 707 |
+
}
|
| 708 |
+
}
|
| 709 |
+
offset := int64(0)
|
| 710 |
+
if i == startIndex {
|
| 711 |
+
offset = cursor.Offset
|
| 712 |
+
}
|
| 713 |
+
read, errRead := readCompleteLogLines(files[i], offset, -1, remaining)
|
| 714 |
+
if errRead != nil {
|
| 715 |
+
if errors.Is(errRead, os.ErrNotExist) {
|
| 716 |
+
return result, true, nil
|
| 717 |
+
}
|
| 718 |
+
return result, false, errRead
|
| 719 |
+
}
|
| 720 |
+
if len(read.lines) > 0 {
|
| 721 |
+
result.lines = append(result.lines, read.lines...)
|
| 722 |
+
if read.latest > result.latest {
|
| 723 |
+
result.latest = read.latest
|
| 724 |
+
}
|
| 725 |
+
currentCursorPath = files[i]
|
| 726 |
+
currentCursorOffset = read.endOffset
|
| 727 |
+
advanced = true
|
| 728 |
+
}
|
| 729 |
+
if read.hitLimit {
|
| 730 |
+
break
|
| 731 |
+
}
|
| 732 |
+
}
|
| 733 |
+
if !advanced {
|
| 734 |
+
return result, false, nil
|
| 735 |
+
}
|
| 736 |
+
|
| 737 |
+
nextCursor, errCursor := newLogCursor(currentCursorPath, currentCursorOffset, result.latest)
|
| 738 |
+
if errCursor != nil {
|
| 739 |
+
if errors.Is(errCursor, os.ErrNotExist) {
|
| 740 |
+
return result, true, nil
|
| 741 |
+
}
|
| 742 |
+
return result, false, errCursor
|
| 743 |
+
}
|
| 744 |
+
result.nextCursor = nextCursor
|
| 745 |
+
return result, false, nil
|
| 746 |
+
}
|
| 747 |
+
|
| 748 |
+
func locateLogCursorFile(files []string, cursor logCursor) (int, bool, error) {
|
| 749 |
+
nameToIndex := make(map[string]int, len(files))
|
| 750 |
+
for i := range files {
|
| 751 |
+
nameToIndex[filepath.Base(files[i])] = i
|
| 752 |
+
}
|
| 753 |
+
deferEmptyMainMatch := false
|
| 754 |
+
if index, ok := nameToIndex[cursor.File]; ok {
|
| 755 |
+
matches, truncated, errMatch := logFileMatchesCursor(files[index], cursor)
|
| 756 |
+
if errMatch != nil {
|
| 757 |
+
if errors.Is(errMatch, os.ErrNotExist) {
|
| 758 |
+
return 0, false, nil
|
| 759 |
+
}
|
| 760 |
+
return 0, false, errMatch
|
| 761 |
+
}
|
| 762 |
+
if matches && !truncated {
|
| 763 |
+
if shouldDeferEmptyMainCursorToRotated(files, cursor) {
|
| 764 |
+
deferEmptyMainMatch = true
|
| 765 |
+
} else if shouldResetAmbiguousEmptyMainCursor(files, index, cursor) {
|
| 766 |
+
return 0, false, nil
|
| 767 |
+
} else {
|
| 768 |
+
return index, true, nil
|
| 769 |
+
}
|
| 770 |
+
}
|
| 771 |
+
}
|
| 772 |
+
|
| 773 |
+
if cursor.File != defaultLogFileName || (cursor.Offset == 0 && cursor.Size == 0 && !deferEmptyMainMatch) {
|
| 774 |
+
return 0, false, nil
|
| 775 |
+
}
|
| 776 |
+
if cursor.Offset == 0 && cursor.Size == 0 {
|
| 777 |
+
for i := range files {
|
| 778 |
+
if filepath.Base(files[i]) == defaultLogFileName {
|
| 779 |
+
continue
|
| 780 |
+
}
|
| 781 |
+
if !logFileChangedAfterCursor(files[i], cursor) {
|
| 782 |
+
continue
|
| 783 |
+
}
|
| 784 |
+
matches, truncated, errMatch := logFileMatchesCursor(files[i], cursor)
|
| 785 |
+
if errMatch != nil {
|
| 786 |
+
if errors.Is(errMatch, os.ErrNotExist) {
|
| 787 |
+
continue
|
| 788 |
+
}
|
| 789 |
+
return 0, false, errMatch
|
| 790 |
+
}
|
| 791 |
+
if truncated {
|
| 792 |
+
continue
|
| 793 |
+
}
|
| 794 |
+
if matches {
|
| 795 |
+
return i, true, nil
|
| 796 |
+
}
|
| 797 |
+
}
|
| 798 |
+
return 0, false, nil
|
| 799 |
+
}
|
| 800 |
+
for i := len(files) - 1; i >= 0; i-- {
|
| 801 |
+
if filepath.Base(files[i]) == defaultLogFileName {
|
| 802 |
+
continue
|
| 803 |
+
}
|
| 804 |
+
matches, truncated, errMatch := logFileMatchesCursor(files[i], cursor)
|
| 805 |
+
if errMatch != nil {
|
| 806 |
+
if errors.Is(errMatch, os.ErrNotExist) {
|
| 807 |
+
continue
|
| 808 |
+
}
|
| 809 |
+
return 0, false, errMatch
|
| 810 |
+
}
|
| 811 |
+
if truncated {
|
| 812 |
+
continue
|
| 813 |
+
}
|
| 814 |
+
if matches {
|
| 815 |
+
return i, true, nil
|
| 816 |
+
}
|
| 817 |
+
}
|
| 818 |
+
return 0, false, nil
|
| 819 |
+
}
|
| 820 |
+
|
| 821 |
+
func shouldDeferEmptyMainCursorToRotated(files []string, cursor logCursor) bool {
|
| 822 |
+
if cursor.File != defaultLogFileName || cursor.Offset != 0 || cursor.Size != 0 {
|
| 823 |
+
return false
|
| 824 |
+
}
|
| 825 |
+
for i := range files {
|
| 826 |
+
if filepath.Base(files[i]) == defaultLogFileName {
|
| 827 |
+
continue
|
| 828 |
+
}
|
| 829 |
+
if logFileChangedAfterCursor(files[i], cursor) {
|
| 830 |
+
return true
|
| 831 |
+
}
|
| 832 |
+
}
|
| 833 |
+
return false
|
| 834 |
+
}
|
| 835 |
+
|
| 836 |
+
func shouldResetAmbiguousEmptyMainCursor(files []string, mainIndex int, cursor logCursor) bool {
|
| 837 |
+
if cursor.File != defaultLogFileName || cursor.Offset != 0 || cursor.Size != 0 {
|
| 838 |
+
return false
|
| 839 |
+
}
|
| 840 |
+
info, errStat := os.Stat(files[mainIndex])
|
| 841 |
+
if errStat != nil || info.IsDir() {
|
| 842 |
+
return false
|
| 843 |
+
}
|
| 844 |
+
if info.Size() == cursor.Size && info.ModTime().UnixNano() == cursorModTimeUnixNano(cursor) {
|
| 845 |
+
return false
|
| 846 |
+
}
|
| 847 |
+
for i := range files {
|
| 848 |
+
if i == mainIndex || filepath.Base(files[i]) == defaultLogFileName {
|
| 849 |
+
continue
|
| 850 |
+
}
|
| 851 |
+
rotatedInfo, errRotated := os.Stat(files[i])
|
| 852 |
+
if errRotated != nil || rotatedInfo.IsDir() || rotatedInfo.Size() == 0 {
|
| 853 |
+
continue
|
| 854 |
+
}
|
| 855 |
+
if !logFileChangedAfterCursor(files[i], cursor) {
|
| 856 |
+
return true
|
| 857 |
+
}
|
| 858 |
+
}
|
| 859 |
+
return false
|
| 860 |
+
}
|
| 861 |
+
|
| 862 |
+
func logFileChangedAfterCursor(path string, cursor logCursor) bool {
|
| 863 |
+
info, errStat := os.Stat(path)
|
| 864 |
+
if errStat != nil || info.IsDir() || info.Size() == 0 {
|
| 865 |
+
return false
|
| 866 |
+
}
|
| 867 |
+
return info.ModTime().UnixNano() > cursorModTimeUnixNano(cursor)
|
| 868 |
+
}
|
| 869 |
+
|
| 870 |
+
func logFileMatchesCursor(path string, cursor logCursor) (bool, bool, error) {
|
| 871 |
+
info, errStat := os.Stat(path)
|
| 872 |
+
if errStat != nil {
|
| 873 |
+
return false, false, errStat
|
| 874 |
+
}
|
| 875 |
+
if info.IsDir() {
|
| 876 |
+
return false, false, fmt.Errorf("invalid log file")
|
| 877 |
+
}
|
| 878 |
+
if info.Size() < cursor.Offset {
|
| 879 |
+
return false, true, nil
|
| 880 |
+
}
|
| 881 |
+
boundary := cursorFingerprintBoundary(cursor)
|
| 882 |
+
if info.Size() < boundary {
|
| 883 |
+
return false, true, nil
|
| 884 |
+
}
|
| 885 |
+
fingerprint, errFingerprint := logFileFingerprint(path, boundary)
|
| 886 |
+
if errFingerprint != nil {
|
| 887 |
+
return false, false, errFingerprint
|
| 888 |
+
}
|
| 889 |
+
return fingerprint == cursor.Fingerprint, false, nil
|
| 890 |
+
}
|
| 891 |
+
|
| 892 |
+
func encodeLogCursor(cursor logCursor) (string, error) {
|
| 893 |
+
raw, err := json.Marshal(cursor)
|
| 894 |
+
if err != nil {
|
| 895 |
+
return "", err
|
| 896 |
+
}
|
| 897 |
+
return base64.RawURLEncoding.EncodeToString(raw), nil
|
| 898 |
+
}
|
| 899 |
+
|
| 900 |
+
func decodeLogCursor(raw string) (logCursor, error) {
|
| 901 |
+
value := strings.TrimSpace(raw)
|
| 902 |
+
if value == "" {
|
| 903 |
+
return logCursor{}, fmt.Errorf("empty cursor")
|
| 904 |
+
}
|
| 905 |
+
data, err := base64.RawURLEncoding.DecodeString(value)
|
| 906 |
+
if err != nil {
|
| 907 |
+
data, err = base64.URLEncoding.DecodeString(value)
|
| 908 |
+
}
|
| 909 |
+
if err != nil {
|
| 910 |
+
return logCursor{}, fmt.Errorf("invalid cursor encoding")
|
| 911 |
+
}
|
| 912 |
+
var cursor logCursor
|
| 913 |
+
if errUnmarshal := json.Unmarshal(data, &cursor); errUnmarshal != nil {
|
| 914 |
+
return logCursor{}, fmt.Errorf("invalid cursor payload")
|
| 915 |
+
}
|
| 916 |
+
if errValidate := validateLogCursor(cursor); errValidate != nil {
|
| 917 |
+
return logCursor{}, errValidate
|
| 918 |
+
}
|
| 919 |
+
return cursor, nil
|
| 920 |
+
}
|
| 921 |
+
|
| 922 |
+
func validateLogCursor(cursor logCursor) error {
|
| 923 |
+
if cursor.Version != logCursorVersion {
|
| 924 |
+
return fmt.Errorf("unsupported cursor version")
|
| 925 |
+
}
|
| 926 |
+
if !isAllowedLogCursorFile(cursor.File) {
|
| 927 |
+
return fmt.Errorf("invalid cursor file")
|
| 928 |
+
}
|
| 929 |
+
if cursor.Offset < 0 || cursor.Size < 0 || cursor.ModTime < 0 || cursor.LatestTimestamp < 0 {
|
| 930 |
+
return fmt.Errorf("invalid cursor position")
|
| 931 |
+
}
|
| 932 |
+
if strings.TrimSpace(cursor.Fingerprint) == "" {
|
| 933 |
+
return fmt.Errorf("invalid cursor fingerprint")
|
| 934 |
+
}
|
| 935 |
+
return nil
|
| 936 |
+
}
|
| 937 |
+
|
| 938 |
+
func isAllowedLogCursorFile(name string) bool {
|
| 939 |
+
if name == "" || name == "." || name == ".." {
|
| 940 |
+
return false
|
| 941 |
+
}
|
| 942 |
+
if strings.ContainsAny(name, `/\`) {
|
| 943 |
+
return false
|
| 944 |
+
}
|
| 945 |
+
if filepath.Base(name) != name {
|
| 946 |
+
return false
|
| 947 |
+
}
|
| 948 |
+
return name == defaultLogFileName || isRotatedLogFile(name)
|
| 949 |
+
}
|
| 950 |
+
|
| 951 |
+
func safeLogFilePath(logDir, name string) (string, error) {
|
| 952 |
+
if !isAllowedLogCursorFile(name) {
|
| 953 |
+
return "", fmt.Errorf("invalid log file")
|
| 954 |
+
}
|
| 955 |
+
dirAbs, errAbs := filepath.Abs(logDir)
|
| 956 |
+
if errAbs != nil {
|
| 957 |
+
return "", fmt.Errorf("resolve log directory: %w", errAbs)
|
| 958 |
+
}
|
| 959 |
+
dirAbs = filepath.Clean(dirAbs)
|
| 960 |
+
fullPath := filepath.Clean(filepath.Join(dirAbs, name))
|
| 961 |
+
rel, errRel := filepath.Rel(dirAbs, fullPath)
|
| 962 |
+
if errRel != nil {
|
| 963 |
+
return "", fmt.Errorf("resolve log file: %w", errRel)
|
| 964 |
+
}
|
| 965 |
+
if rel == "." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) || rel == ".." || filepath.IsAbs(rel) {
|
| 966 |
+
return "", fmt.Errorf("invalid log file")
|
| 967 |
+
}
|
| 968 |
+
return fullPath, nil
|
| 969 |
+
}
|
| 970 |
+
|
| 971 |
+
func newLogCursor(path string, offset, latest int64) (string, error) {
|
| 972 |
+
info, errStat := os.Stat(path)
|
| 973 |
+
if errStat != nil {
|
| 974 |
+
return "", errStat
|
| 975 |
+
}
|
| 976 |
+
if info.IsDir() {
|
| 977 |
+
return "", fmt.Errorf("invalid log file")
|
| 978 |
+
}
|
| 979 |
+
if offset < 0 || offset > info.Size() {
|
| 980 |
+
return "", fmt.Errorf("invalid cursor offset")
|
| 981 |
+
}
|
| 982 |
+
fingerprintCursor := logCursor{
|
| 983 |
+
Offset: offset,
|
| 984 |
+
Size: info.Size(),
|
| 985 |
+
}
|
| 986 |
+
fingerprint, errFingerprint := logFileFingerprint(path, cursorFingerprintBoundary(fingerprintCursor))
|
| 987 |
+
if errFingerprint != nil {
|
| 988 |
+
return "", errFingerprint
|
| 989 |
+
}
|
| 990 |
+
return encodeLogCursor(logCursor{
|
| 991 |
+
Version: logCursorVersion,
|
| 992 |
+
File: filepath.Base(path),
|
| 993 |
+
Offset: offset,
|
| 994 |
+
Size: info.Size(),
|
| 995 |
+
ModTime: info.ModTime().Unix(),
|
| 996 |
+
ModTimeUnixNano: info.ModTime().UnixNano(),
|
| 997 |
+
LatestTimestamp: latest,
|
| 998 |
+
Fingerprint: fingerprint,
|
| 999 |
+
})
|
| 1000 |
+
}
|
| 1001 |
+
|
| 1002 |
+
func cursorFingerprintBoundary(cursor logCursor) int64 {
|
| 1003 |
+
if cursor.Offset == 0 && cursor.Size > 0 {
|
| 1004 |
+
return cursor.Size
|
| 1005 |
+
}
|
| 1006 |
+
return cursor.Offset
|
| 1007 |
+
}
|
| 1008 |
+
|
| 1009 |
+
func cursorModTimeUnixNano(cursor logCursor) int64 {
|
| 1010 |
+
if cursor.ModTimeUnixNano > 0 {
|
| 1011 |
+
return cursor.ModTimeUnixNano
|
| 1012 |
+
}
|
| 1013 |
+
return cursor.ModTime * int64(time.Second)
|
| 1014 |
+
}
|
| 1015 |
+
|
| 1016 |
+
func logFileFingerprint(path string, boundary int64) (string, error) {
|
| 1017 |
+
if boundary < 0 {
|
| 1018 |
+
return "", fmt.Errorf("invalid fingerprint boundary")
|
| 1019 |
+
}
|
| 1020 |
+
file, errOpen := os.Open(path)
|
| 1021 |
+
if errOpen != nil {
|
| 1022 |
+
return "", errOpen
|
| 1023 |
+
}
|
| 1024 |
+
defer func() {
|
| 1025 |
+
_ = file.Close()
|
| 1026 |
+
}()
|
| 1027 |
+
info, errStat := file.Stat()
|
| 1028 |
+
if errStat != nil {
|
| 1029 |
+
return "", errStat
|
| 1030 |
+
}
|
| 1031 |
+
if info.IsDir() {
|
| 1032 |
+
return "", fmt.Errorf("invalid log file")
|
| 1033 |
+
}
|
| 1034 |
+
if boundary > info.Size() {
|
| 1035 |
+
return "", fmt.Errorf("invalid fingerprint boundary")
|
| 1036 |
+
}
|
| 1037 |
+
|
| 1038 |
+
hash := sha256.New()
|
| 1039 |
+
_, _ = fmt.Fprintf(hash, "log-cursor-v1:%d:", boundary)
|
| 1040 |
+
firstLen := minInt64(boundary, logCursorFingerprintMax)
|
| 1041 |
+
if errRead := writeFileRange(hash, file, 0, firstLen); errRead != nil {
|
| 1042 |
+
return "", errRead
|
| 1043 |
+
}
|
| 1044 |
+
tailLen := minInt64(boundary, logCursorFingerprintMax)
|
| 1045 |
+
tailStart := boundary - tailLen
|
| 1046 |
+
_, _ = fmt.Fprintf(hash, ":%d:", tailStart)
|
| 1047 |
+
if errRead := writeFileRange(hash, file, tailStart, tailLen); errRead != nil {
|
| 1048 |
+
return "", errRead
|
| 1049 |
+
}
|
| 1050 |
+
sum := hash.Sum(nil)
|
| 1051 |
+
return base64.RawURLEncoding.EncodeToString(sum[:12]), nil
|
| 1052 |
+
}
|
| 1053 |
+
|
| 1054 |
+
func writeFileRange(dst io.Writer, file *os.File, start, length int64) error {
|
| 1055 |
+
if length <= 0 {
|
| 1056 |
+
return nil
|
| 1057 |
+
}
|
| 1058 |
+
buf := make([]byte, 32*1024)
|
| 1059 |
+
pos := start
|
| 1060 |
+
remaining := length
|
| 1061 |
+
for remaining > 0 {
|
| 1062 |
+
chunk := minInt64(int64(len(buf)), remaining)
|
| 1063 |
+
n, errRead := file.ReadAt(buf[:chunk], pos)
|
| 1064 |
+
if n > 0 {
|
| 1065 |
+
if _, errWrite := dst.Write(buf[:n]); errWrite != nil {
|
| 1066 |
+
return errWrite
|
| 1067 |
+
}
|
| 1068 |
+
pos += int64(n)
|
| 1069 |
+
remaining -= int64(n)
|
| 1070 |
+
}
|
| 1071 |
+
if errRead != nil {
|
| 1072 |
+
if errRead == io.EOF && remaining == 0 {
|
| 1073 |
+
return nil
|
| 1074 |
+
}
|
| 1075 |
+
return errRead
|
| 1076 |
+
}
|
| 1077 |
+
}
|
| 1078 |
+
return nil
|
| 1079 |
+
}
|
| 1080 |
+
|
| 1081 |
+
func readCompleteLogLines(path string, offset, maxOffset int64, limit int) (completeLogRead, error) {
|
| 1082 |
+
if offset < 0 {
|
| 1083 |
+
return completeLogRead{}, fmt.Errorf("invalid log offset")
|
| 1084 |
+
}
|
| 1085 |
+
file, errOpen := os.Open(path)
|
| 1086 |
+
if errOpen != nil {
|
| 1087 |
+
return completeLogRead{}, errOpen
|
| 1088 |
+
}
|
| 1089 |
+
defer func() {
|
| 1090 |
+
_ = file.Close()
|
| 1091 |
+
}()
|
| 1092 |
+
info, errStat := file.Stat()
|
| 1093 |
+
if errStat != nil {
|
| 1094 |
+
return completeLogRead{}, errStat
|
| 1095 |
+
}
|
| 1096 |
+
if info.IsDir() {
|
| 1097 |
+
return completeLogRead{}, fmt.Errorf("invalid log file")
|
| 1098 |
+
}
|
| 1099 |
+
size := info.Size()
|
| 1100 |
+
if maxOffset < 0 || maxOffset > size {
|
| 1101 |
+
maxOffset = size
|
| 1102 |
+
}
|
| 1103 |
+
if offset > maxOffset {
|
| 1104 |
+
return completeLogRead{}, fmt.Errorf("invalid log offset")
|
| 1105 |
+
}
|
| 1106 |
+
|
| 1107 |
+
reader := io.NewSectionReader(file, offset, maxOffset-offset)
|
| 1108 |
+
result := completeLogRead{
|
| 1109 |
+
lines: []string{},
|
| 1110 |
+
endOffset: offset,
|
| 1111 |
+
}
|
| 1112 |
+
currentOffset := offset
|
| 1113 |
+
buf := make([]byte, 32*1024)
|
| 1114 |
+
line := make([]byte, 0, logScannerInitialBuffer)
|
| 1115 |
+
for {
|
| 1116 |
+
n, errRead := reader.Read(buf)
|
| 1117 |
+
if n > 0 {
|
| 1118 |
+
data := buf[:n]
|
| 1119 |
+
for len(data) > 0 {
|
| 1120 |
+
idx := bytes.IndexByte(data, '\n')
|
| 1121 |
+
if idx < 0 {
|
| 1122 |
+
if len(line)+len(data) > logScannerMaxBuffer {
|
| 1123 |
+
return completeLogRead{}, fmt.Errorf("log line exceeds %d bytes", logScannerMaxBuffer)
|
| 1124 |
+
}
|
| 1125 |
+
line = append(line, data...)
|
| 1126 |
+
currentOffset += int64(len(data))
|
| 1127 |
+
break
|
| 1128 |
+
}
|
| 1129 |
+
|
| 1130 |
+
segment := data[:idx]
|
| 1131 |
+
if len(line)+len(segment) > logScannerMaxBuffer {
|
| 1132 |
+
return completeLogRead{}, fmt.Errorf("log line exceeds %d bytes", logScannerMaxBuffer)
|
| 1133 |
+
}
|
| 1134 |
+
line = append(line, segment...)
|
| 1135 |
+
currentOffset += int64(idx) + 1
|
| 1136 |
+
text := strings.TrimRight(string(line), "\r")
|
| 1137 |
+
result.lines = append(result.lines, text)
|
| 1138 |
+
result.endOffset = currentOffset
|
| 1139 |
+
if ts := parseTimestamp(text); ts > result.latest {
|
| 1140 |
+
result.latest = ts
|
| 1141 |
+
}
|
| 1142 |
+
line = line[:0]
|
| 1143 |
+
if limit > 0 && len(result.lines) >= limit {
|
| 1144 |
+
result.hitLimit = true
|
| 1145 |
+
return result, nil
|
| 1146 |
+
}
|
| 1147 |
+
data = data[idx+1:]
|
| 1148 |
+
}
|
| 1149 |
+
}
|
| 1150 |
+
if errRead == io.EOF {
|
| 1151 |
+
break
|
| 1152 |
+
}
|
| 1153 |
+
if errRead != nil {
|
| 1154 |
+
return completeLogRead{}, errRead
|
| 1155 |
+
}
|
| 1156 |
+
}
|
| 1157 |
+
return result, nil
|
| 1158 |
+
}
|
| 1159 |
+
|
| 1160 |
+
func completeLogBoundary(path string) (int64, error) {
|
| 1161 |
+
file, errOpen := os.Open(path)
|
| 1162 |
+
if errOpen != nil {
|
| 1163 |
+
return 0, errOpen
|
| 1164 |
+
}
|
| 1165 |
+
defer func() {
|
| 1166 |
+
_ = file.Close()
|
| 1167 |
+
}()
|
| 1168 |
+
info, errStat := file.Stat()
|
| 1169 |
+
if errStat != nil {
|
| 1170 |
+
return 0, errStat
|
| 1171 |
+
}
|
| 1172 |
+
if info.IsDir() {
|
| 1173 |
+
return 0, fmt.Errorf("invalid log file")
|
| 1174 |
+
}
|
| 1175 |
+
size := info.Size()
|
| 1176 |
+
if size == 0 {
|
| 1177 |
+
return 0, nil
|
| 1178 |
+
}
|
| 1179 |
+
buf := make([]byte, 32*1024)
|
| 1180 |
+
pos := size
|
| 1181 |
+
for pos > 0 {
|
| 1182 |
+
chunk := minInt64(int64(len(buf)), pos)
|
| 1183 |
+
pos -= chunk
|
| 1184 |
+
n, errRead := file.ReadAt(buf[:chunk], pos)
|
| 1185 |
+
if errRead != nil && errRead != io.EOF {
|
| 1186 |
+
return 0, errRead
|
| 1187 |
+
}
|
| 1188 |
+
if n <= 0 {
|
| 1189 |
+
continue
|
| 1190 |
+
}
|
| 1191 |
+
if idx := bytes.LastIndexByte(buf[:n], '\n'); idx >= 0 {
|
| 1192 |
+
return pos + int64(idx) + 1, nil
|
| 1193 |
+
}
|
| 1194 |
+
}
|
| 1195 |
+
return 0, nil
|
| 1196 |
+
}
|
| 1197 |
+
|
| 1198 |
+
func minInt64(a, b int64) int64 {
|
| 1199 |
+
if a < b {
|
| 1200 |
+
return a
|
| 1201 |
+
}
|
| 1202 |
+
return b
|
| 1203 |
+
}
|
| 1204 |
+
|
| 1205 |
+
func parseCutoff(raw string) int64 {
|
| 1206 |
+
value := strings.TrimSpace(raw)
|
| 1207 |
+
if value == "" {
|
| 1208 |
+
return 0
|
| 1209 |
+
}
|
| 1210 |
+
ts, err := strconv.ParseInt(value, 10, 64)
|
| 1211 |
+
if err != nil || ts <= 0 {
|
| 1212 |
+
return 0
|
| 1213 |
+
}
|
| 1214 |
+
return ts
|
| 1215 |
+
}
|
| 1216 |
+
|
| 1217 |
+
func parseLimit(raw string) (int, error) {
|
| 1218 |
+
value := strings.TrimSpace(raw)
|
| 1219 |
+
if value == "" {
|
| 1220 |
+
return 0, nil
|
| 1221 |
+
}
|
| 1222 |
+
limit, err := strconv.Atoi(value)
|
| 1223 |
+
if err != nil {
|
| 1224 |
+
return 0, fmt.Errorf("must be a positive integer")
|
| 1225 |
+
}
|
| 1226 |
+
if limit <= 0 {
|
| 1227 |
+
return 0, fmt.Errorf("must be greater than zero")
|
| 1228 |
+
}
|
| 1229 |
+
return limit, nil
|
| 1230 |
+
}
|
| 1231 |
+
|
| 1232 |
+
func parseTimestamp(line string) int64 {
|
| 1233 |
+
if strings.HasPrefix(line, "[") {
|
| 1234 |
+
line = line[1:]
|
| 1235 |
+
}
|
| 1236 |
+
if len(line) < 19 {
|
| 1237 |
+
return 0
|
| 1238 |
+
}
|
| 1239 |
+
candidate := line[:19]
|
| 1240 |
+
t, err := time.ParseInLocation("2006-01-02 15:04:05", candidate, time.Local)
|
| 1241 |
+
if err != nil {
|
| 1242 |
+
return 0
|
| 1243 |
+
}
|
| 1244 |
+
return t.Unix()
|
| 1245 |
+
}
|
| 1246 |
+
|
| 1247 |
+
func isRotatedLogFile(name string) bool {
|
| 1248 |
+
if _, ok := rotationOrder(name); ok {
|
| 1249 |
+
return true
|
| 1250 |
+
}
|
| 1251 |
+
return false
|
| 1252 |
+
}
|
| 1253 |
+
|
| 1254 |
+
func rotationOrder(name string) (int64, bool) {
|
| 1255 |
+
if order, ok := numericRotationOrder(name); ok {
|
| 1256 |
+
return order, true
|
| 1257 |
+
}
|
| 1258 |
+
if order, ok := timestampRotationOrder(name); ok {
|
| 1259 |
+
return order, true
|
| 1260 |
+
}
|
| 1261 |
+
return 0, false
|
| 1262 |
+
}
|
| 1263 |
+
|
| 1264 |
+
func numericRotationOrder(name string) (int64, bool) {
|
| 1265 |
+
if !strings.HasPrefix(name, defaultLogFileName+".") {
|
| 1266 |
+
return 0, false
|
| 1267 |
+
}
|
| 1268 |
+
suffix := strings.TrimPrefix(name, defaultLogFileName+".")
|
| 1269 |
+
if suffix == "" {
|
| 1270 |
+
return 0, false
|
| 1271 |
+
}
|
| 1272 |
+
n, err := strconv.Atoi(suffix)
|
| 1273 |
+
if err != nil {
|
| 1274 |
+
return 0, false
|
| 1275 |
+
}
|
| 1276 |
+
return int64(n), true
|
| 1277 |
+
}
|
| 1278 |
+
|
| 1279 |
+
func timestampRotationOrder(name string) (int64, bool) {
|
| 1280 |
+
ext := filepath.Ext(defaultLogFileName)
|
| 1281 |
+
base := strings.TrimSuffix(defaultLogFileName, ext)
|
| 1282 |
+
if base == "" {
|
| 1283 |
+
return 0, false
|
| 1284 |
+
}
|
| 1285 |
+
prefix := base + "-"
|
| 1286 |
+
if !strings.HasPrefix(name, prefix) {
|
| 1287 |
+
return 0, false
|
| 1288 |
+
}
|
| 1289 |
+
clean := strings.TrimPrefix(name, prefix)
|
| 1290 |
+
if strings.HasSuffix(clean, ".gz") {
|
| 1291 |
+
clean = strings.TrimSuffix(clean, ".gz")
|
| 1292 |
+
}
|
| 1293 |
+
if ext != "" {
|
| 1294 |
+
if !strings.HasSuffix(clean, ext) {
|
| 1295 |
+
return 0, false
|
| 1296 |
+
}
|
| 1297 |
+
clean = strings.TrimSuffix(clean, ext)
|
| 1298 |
+
}
|
| 1299 |
+
if clean == "" {
|
| 1300 |
+
return 0, false
|
| 1301 |
+
}
|
| 1302 |
+
if idx := strings.IndexByte(clean, '.'); idx != -1 {
|
| 1303 |
+
clean = clean[:idx]
|
| 1304 |
+
}
|
| 1305 |
+
parsed, err := time.ParseInLocation("2006-01-02T15-04-05", clean, time.Local)
|
| 1306 |
+
if err != nil {
|
| 1307 |
+
return 0, false
|
| 1308 |
+
}
|
| 1309 |
+
return math.MaxInt64 - parsed.Unix(), true
|
| 1310 |
+
}
|
internal/api/handlers/management/logs_test.go
ADDED
|
@@ -0,0 +1,736 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/base64"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/http/httptest"
|
| 8 |
+
"net/url"
|
| 9 |
+
"os"
|
| 10 |
+
"path/filepath"
|
| 11 |
+
"reflect"
|
| 12 |
+
"strconv"
|
| 13 |
+
"strings"
|
| 14 |
+
"testing"
|
| 15 |
+
"time"
|
| 16 |
+
|
| 17 |
+
"github.com/gin-gonic/gin"
|
| 18 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
func TestDecodeLogCursorRejectsUnsafeFiles(t *testing.T) {
|
| 22 |
+
unsafeNames := []string{
|
| 23 |
+
"",
|
| 24 |
+
".",
|
| 25 |
+
"..",
|
| 26 |
+
"../secret",
|
| 27 |
+
"nested/main.log",
|
| 28 |
+
`nested\main.log`,
|
| 29 |
+
"error.log",
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
for _, name := range unsafeNames {
|
| 33 |
+
t.Run(name, func(t *testing.T) {
|
| 34 |
+
raw := mustEncodeRawCursor(t, logCursor{
|
| 35 |
+
Version: logCursorVersion,
|
| 36 |
+
File: name,
|
| 37 |
+
Fingerprint: "fingerprint",
|
| 38 |
+
})
|
| 39 |
+
if _, err := decodeLogCursor(raw); err == nil {
|
| 40 |
+
t.Fatalf("decodeLogCursor(%q) succeeded, want error", name)
|
| 41 |
+
}
|
| 42 |
+
})
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
for _, name := range []string{defaultLogFileName, defaultLogFileName + ".1", "main-2026-06-15T10-00-00.log"} {
|
| 46 |
+
t.Run("allowed_"+name, func(t *testing.T) {
|
| 47 |
+
raw := mustEncodeRawCursor(t, logCursor{
|
| 48 |
+
Version: logCursorVersion,
|
| 49 |
+
File: name,
|
| 50 |
+
Fingerprint: "fingerprint",
|
| 51 |
+
})
|
| 52 |
+
if _, err := decodeLogCursor(raw); err != nil {
|
| 53 |
+
t.Fatalf("decodeLogCursor(%q) error = %v", name, err)
|
| 54 |
+
}
|
| 55 |
+
})
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
func TestLogCursorRoundTripOmitsAbsolutePath(t *testing.T) {
|
| 60 |
+
dir := t.TempDir()
|
| 61 |
+
path := filepath.Join(dir, defaultLogFileName)
|
| 62 |
+
if err := os.WriteFile(path, []byte("line one\nline two\n"), 0o644); err != nil {
|
| 63 |
+
t.Fatalf("write log file: %v", err)
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
boundary, errBoundary := completeLogBoundary(path)
|
| 67 |
+
if errBoundary != nil {
|
| 68 |
+
t.Fatalf("completeLogBoundary() error = %v", errBoundary)
|
| 69 |
+
}
|
| 70 |
+
raw, errCursor := newLogCursor(path, boundary, 123)
|
| 71 |
+
if errCursor != nil {
|
| 72 |
+
t.Fatalf("newLogCursor() error = %v", errCursor)
|
| 73 |
+
}
|
| 74 |
+
decoded, errDecode := decodeLogCursor(raw)
|
| 75 |
+
if errDecode != nil {
|
| 76 |
+
t.Fatalf("decodeLogCursor() error = %v", errDecode)
|
| 77 |
+
}
|
| 78 |
+
if decoded.File != defaultLogFileName {
|
| 79 |
+
t.Fatalf("cursor file = %q, want %q", decoded.File, defaultLogFileName)
|
| 80 |
+
}
|
| 81 |
+
if decoded.Offset != boundary {
|
| 82 |
+
t.Fatalf("cursor offset = %d, want %d", decoded.Offset, boundary)
|
| 83 |
+
}
|
| 84 |
+
if decoded.LatestTimestamp != 123 {
|
| 85 |
+
t.Fatalf("cursor latest timestamp = %d, want 123", decoded.LatestTimestamp)
|
| 86 |
+
}
|
| 87 |
+
if strings.Contains(raw, dir) {
|
| 88 |
+
t.Fatalf("encoded cursor contains log directory %q: %q", dir, raw)
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
func TestReadCompleteLogLinesSkipsTrailingPartial(t *testing.T) {
|
| 93 |
+
dir := t.TempDir()
|
| 94 |
+
path := filepath.Join(dir, defaultLogFileName)
|
| 95 |
+
initial := "first\nsecond\r\npartial"
|
| 96 |
+
if err := os.WriteFile(path, []byte(initial), 0o644); err != nil {
|
| 97 |
+
t.Fatalf("write log file: %v", err)
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
read, errRead := readCompleteLogLines(path, 0, -1, 0)
|
| 101 |
+
if errRead != nil {
|
| 102 |
+
t.Fatalf("readCompleteLogLines() error = %v", errRead)
|
| 103 |
+
}
|
| 104 |
+
wantLines := []string{"first", "second"}
|
| 105 |
+
if !reflect.DeepEqual(read.lines, wantLines) {
|
| 106 |
+
t.Fatalf("lines = %#v, want %#v", read.lines, wantLines)
|
| 107 |
+
}
|
| 108 |
+
wantOffset := int64(len("first\nsecond\r\n"))
|
| 109 |
+
if read.endOffset != wantOffset {
|
| 110 |
+
t.Fatalf("endOffset = %d, want %d", read.endOffset, wantOffset)
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
file, errOpen := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0)
|
| 114 |
+
if errOpen != nil {
|
| 115 |
+
t.Fatalf("open log file: %v", errOpen)
|
| 116 |
+
}
|
| 117 |
+
if _, errWrite := file.WriteString("\n"); errWrite != nil {
|
| 118 |
+
_ = file.Close()
|
| 119 |
+
t.Fatalf("append newline: %v", errWrite)
|
| 120 |
+
}
|
| 121 |
+
if errClose := file.Close(); errClose != nil {
|
| 122 |
+
t.Fatalf("close log file: %v", errClose)
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
next, errNext := readCompleteLogLines(path, read.endOffset, -1, 0)
|
| 126 |
+
if errNext != nil {
|
| 127 |
+
t.Fatalf("readCompleteLogLines() after append error = %v", errNext)
|
| 128 |
+
}
|
| 129 |
+
if !reflect.DeepEqual(next.lines, []string{"partial"}) {
|
| 130 |
+
t.Fatalf("next lines = %#v, want partial", next.lines)
|
| 131 |
+
}
|
| 132 |
+
if next.endOffset != int64(len(initial)+1) {
|
| 133 |
+
t.Fatalf("next endOffset = %d, want %d", next.endOffset, len(initial)+1)
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
func TestGetLogsTailLimitReturnsRecentLinesWithCursor(t *testing.T) {
|
| 138 |
+
dir := t.TempDir()
|
| 139 |
+
lines := []string{
|
| 140 |
+
"[2026-06-15 10:00:00] first",
|
| 141 |
+
"[2026-06-15 10:00:01] second",
|
| 142 |
+
"[2026-06-15 10:00:02] third",
|
| 143 |
+
"[2026-06-15 10:00:03] fourth",
|
| 144 |
+
}
|
| 145 |
+
writeMainLog(t, dir, strings.Join(lines, "\n")+"\n")
|
| 146 |
+
|
| 147 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=2")
|
| 148 |
+
wantLines := []string{lines[2], lines[3]}
|
| 149 |
+
if !reflect.DeepEqual(resp.Lines, wantLines) {
|
| 150 |
+
t.Fatalf("lines = %#v, want %#v", resp.Lines, wantLines)
|
| 151 |
+
}
|
| 152 |
+
if resp.LineCount != len(wantLines) {
|
| 153 |
+
t.Fatalf("line-count = %d, want returned line count %d", resp.LineCount, len(wantLines))
|
| 154 |
+
}
|
| 155 |
+
if resp.NextCursor == "" {
|
| 156 |
+
t.Fatal("next-cursor is empty")
|
| 157 |
+
}
|
| 158 |
+
wantLatest := time.Date(2026, 6, 15, 10, 0, 3, 0, time.Local).Unix()
|
| 159 |
+
if resp.LatestTimestamp != wantLatest {
|
| 160 |
+
t.Fatalf("latest-timestamp = %d, want %d", resp.LatestTimestamp, wantLatest)
|
| 161 |
+
}
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
func TestGetLogsTailLimitDoesNotScanOlderFilesForLineCount(t *testing.T) {
|
| 165 |
+
dir := t.TempDir()
|
| 166 |
+
rotatedPath := filepath.Join(dir, defaultLogFileName+".1")
|
| 167 |
+
if err := os.WriteFile(rotatedPath, []byte(strings.Repeat("x", logScannerMaxBuffer+1)+"\n"), 0o644); err != nil {
|
| 168 |
+
t.Fatalf("write rotated log: %v", err)
|
| 169 |
+
}
|
| 170 |
+
writeMainLog(t, dir, "[2026-06-15 10:00:00] current\n")
|
| 171 |
+
|
| 172 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=1")
|
| 173 |
+
wantLines := []string{"[2026-06-15 10:00:00] current"}
|
| 174 |
+
if !reflect.DeepEqual(resp.Lines, wantLines) {
|
| 175 |
+
t.Fatalf("lines = %#v, want %#v", resp.Lines, wantLines)
|
| 176 |
+
}
|
| 177 |
+
if resp.LineCount != len(wantLines) {
|
| 178 |
+
t.Fatalf("line-count = %d, want returned line count %d", resp.LineCount, len(wantLines))
|
| 179 |
+
}
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
func TestGetLogsNoLimitKeepsFullScanBehavior(t *testing.T) {
|
| 183 |
+
dir := t.TempDir()
|
| 184 |
+
writeMainLog(t, dir, "complete\npartial")
|
| 185 |
+
|
| 186 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs")
|
| 187 |
+
wantLines := []string{"complete", "partial"}
|
| 188 |
+
if !reflect.DeepEqual(resp.Lines, wantLines) {
|
| 189 |
+
t.Fatalf("lines = %#v, want %#v", resp.Lines, wantLines)
|
| 190 |
+
}
|
| 191 |
+
if resp.LineCount != 2 {
|
| 192 |
+
t.Fatalf("line-count = %d, want full scan count 2", resp.LineCount)
|
| 193 |
+
}
|
| 194 |
+
if resp.NextCursor == "" {
|
| 195 |
+
t.Fatal("next-cursor is empty")
|
| 196 |
+
}
|
| 197 |
+
cursor, errCursor := decodeLogCursor(resp.NextCursor)
|
| 198 |
+
if errCursor != nil {
|
| 199 |
+
t.Fatalf("decode next-cursor: %v", errCursor)
|
| 200 |
+
}
|
| 201 |
+
if cursor.Offset != int64(len("complete\n")) {
|
| 202 |
+
t.Fatalf("cursor offset = %d, want complete-line boundary", cursor.Offset)
|
| 203 |
+
}
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
func TestGetLogsAfterKeepsTimestampScanAndReturnsCursor(t *testing.T) {
|
| 207 |
+
dir := t.TempDir()
|
| 208 |
+
lines := []string{
|
| 209 |
+
"[2026-06-15 10:00:00] first",
|
| 210 |
+
"[2026-06-15 10:00:01] second",
|
| 211 |
+
"[2026-06-15 10:00:02] third",
|
| 212 |
+
}
|
| 213 |
+
writeMainLog(t, dir, strings.Join(lines, "\n")+"\n")
|
| 214 |
+
|
| 215 |
+
cutoff := time.Date(2026, 6, 15, 10, 0, 0, 0, time.Local).Unix()
|
| 216 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?after="+strconv.FormatInt(cutoff, 10))
|
| 217 |
+
wantLines := []string{lines[1], lines[2]}
|
| 218 |
+
if !reflect.DeepEqual(resp.Lines, wantLines) {
|
| 219 |
+
t.Fatalf("lines = %#v, want %#v", resp.Lines, wantLines)
|
| 220 |
+
}
|
| 221 |
+
if resp.LineCount != 3 {
|
| 222 |
+
t.Fatalf("line-count = %d, want full scan count 3", resp.LineCount)
|
| 223 |
+
}
|
| 224 |
+
if resp.NextCursor == "" {
|
| 225 |
+
t.Fatal("next-cursor is empty")
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
func TestGetLogsCursorReturnsOnlyNewCompleteLines(t *testing.T) {
|
| 230 |
+
dir := t.TempDir()
|
| 231 |
+
lines := []string{
|
| 232 |
+
"[2026-06-15 10:00:00] first",
|
| 233 |
+
"[2026-06-15 10:00:01] second",
|
| 234 |
+
"[2026-06-15 10:00:02] third",
|
| 235 |
+
}
|
| 236 |
+
writeMainLog(t, dir, strings.Join(lines, "\n")+"\n")
|
| 237 |
+
initial := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=2")
|
| 238 |
+
if initial.NextCursor == "" {
|
| 239 |
+
t.Fatal("initial next-cursor is empty")
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
appendMainLog(t, dir, "[2026-06-15 10:00:03] fourth\n")
|
| 243 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(initial.NextCursor)+"&limit=10")
|
| 244 |
+
wantLines := []string{"[2026-06-15 10:00:03] fourth"}
|
| 245 |
+
if !reflect.DeepEqual(resp.Lines, wantLines) {
|
| 246 |
+
t.Fatalf("lines = %#v, want %#v", resp.Lines, wantLines)
|
| 247 |
+
}
|
| 248 |
+
if resp.LineCount != 1 {
|
| 249 |
+
t.Fatalf("line-count = %d, want 1", resp.LineCount)
|
| 250 |
+
}
|
| 251 |
+
if resp.CursorReset {
|
| 252 |
+
t.Fatal("cursor-reset = true, want false")
|
| 253 |
+
}
|
| 254 |
+
wantLatest := time.Date(2026, 6, 15, 10, 0, 3, 0, time.Local).Unix()
|
| 255 |
+
if resp.LatestTimestamp != wantLatest {
|
| 256 |
+
t.Fatalf("latest-timestamp = %d, want %d", resp.LatestTimestamp, wantLatest)
|
| 257 |
+
}
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
func TestGetLogsCursorRejectsOversizedLine(t *testing.T) {
|
| 261 |
+
dir := t.TempDir()
|
| 262 |
+
writeMainLog(t, dir, "[2026-06-15 10:00:00] first\n")
|
| 263 |
+
initial := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=1")
|
| 264 |
+
if initial.NextCursor == "" {
|
| 265 |
+
t.Fatal("initial next-cursor is empty")
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
appendMainLog(t, dir, strings.Repeat("x", logScannerMaxBuffer+1)+"\n")
|
| 269 |
+
status, body := performGetLogsRaw(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(initial.NextCursor)+"&limit=1")
|
| 270 |
+
if status != http.StatusInternalServerError {
|
| 271 |
+
t.Fatalf("status = %d, want %d", status, http.StatusInternalServerError)
|
| 272 |
+
}
|
| 273 |
+
if !strings.Contains(body, "log line exceeds") {
|
| 274 |
+
t.Fatalf("body = %s, want oversized line error", body)
|
| 275 |
+
}
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
func TestGetLogsCursorNoNewLinesKeepsCursorStable(t *testing.T) {
|
| 279 |
+
dir := t.TempDir()
|
| 280 |
+
line := "[2026-06-15 10:00:00] first"
|
| 281 |
+
writeMainLog(t, dir, line+"\n")
|
| 282 |
+
initial := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=1")
|
| 283 |
+
|
| 284 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(initial.NextCursor)+"&limit=10")
|
| 285 |
+
if len(resp.Lines) != 0 {
|
| 286 |
+
t.Fatalf("lines = %#v, want empty", resp.Lines)
|
| 287 |
+
}
|
| 288 |
+
if resp.LineCount != 0 {
|
| 289 |
+
t.Fatalf("line-count = %d, want 0", resp.LineCount)
|
| 290 |
+
}
|
| 291 |
+
if resp.NextCursor != initial.NextCursor {
|
| 292 |
+
t.Fatalf("next-cursor changed with no complete lines")
|
| 293 |
+
}
|
| 294 |
+
if resp.LatestTimestamp != initial.LatestTimestamp {
|
| 295 |
+
t.Fatalf("latest-timestamp = %d, want %d", resp.LatestTimestamp, initial.LatestTimestamp)
|
| 296 |
+
}
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
func TestGetLogsCursorDoesNotAdvancePastTrailingPartial(t *testing.T) {
|
| 300 |
+
dir := t.TempDir()
|
| 301 |
+
line := "[2026-06-15 10:00:00] first"
|
| 302 |
+
writeMainLog(t, dir, line+"\n")
|
| 303 |
+
initial := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=1")
|
| 304 |
+
|
| 305 |
+
appendMainLog(t, dir, "partial")
|
| 306 |
+
partial := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(initial.NextCursor)+"&limit=10")
|
| 307 |
+
if len(partial.Lines) != 0 {
|
| 308 |
+
t.Fatalf("partial lines = %#v, want empty", partial.Lines)
|
| 309 |
+
}
|
| 310 |
+
if partial.NextCursor != initial.NextCursor {
|
| 311 |
+
t.Fatalf("cursor advanced past partial line")
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
appendMainLog(t, dir, "\n")
|
| 315 |
+
complete := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(initial.NextCursor)+"&limit=10")
|
| 316 |
+
if !reflect.DeepEqual(complete.Lines, []string{"partial"}) {
|
| 317 |
+
t.Fatalf("complete lines = %#v, want partial", complete.Lines)
|
| 318 |
+
}
|
| 319 |
+
if complete.LatestTimestamp != initial.LatestTimestamp {
|
| 320 |
+
t.Fatalf("latest-timestamp = %d, want %d", complete.LatestTimestamp, initial.LatestTimestamp)
|
| 321 |
+
}
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
func TestGetLogsCursorResetAfterTruncateTailsLimit(t *testing.T) {
|
| 325 |
+
dir := t.TempDir()
|
| 326 |
+
lines := []string{
|
| 327 |
+
"[2026-06-15 10:00:00] first",
|
| 328 |
+
"[2026-06-15 10:00:01] second",
|
| 329 |
+
"[2026-06-15 10:00:02] third",
|
| 330 |
+
}
|
| 331 |
+
writeMainLog(t, dir, strings.Join(lines, "\n")+"\n")
|
| 332 |
+
initial := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=3")
|
| 333 |
+
|
| 334 |
+
resetLine := "[2026-06-15 10:00:03] reset"
|
| 335 |
+
writeMainLog(t, dir, resetLine+"\n")
|
| 336 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(initial.NextCursor)+"&limit=1")
|
| 337 |
+
if !resp.CursorReset {
|
| 338 |
+
t.Fatal("cursor-reset = false, want true")
|
| 339 |
+
}
|
| 340 |
+
if !reflect.DeepEqual(resp.Lines, []string{resetLine}) {
|
| 341 |
+
t.Fatalf("lines = %#v, want reset tail", resp.Lines)
|
| 342 |
+
}
|
| 343 |
+
if resp.LineCount != 1 {
|
| 344 |
+
t.Fatalf("line-count = %d, want 1", resp.LineCount)
|
| 345 |
+
}
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
func TestGetLogsCursorReadsAcrossRotation(t *testing.T) {
|
| 349 |
+
dir := t.TempDir()
|
| 350 |
+
line1 := "[2026-06-15 10:00:00] first"
|
| 351 |
+
line2 := "[2026-06-15 10:00:01] second"
|
| 352 |
+
line3 := "[2026-06-15 10:00:02] third"
|
| 353 |
+
writeMainLog(t, dir, line1+"\n")
|
| 354 |
+
initial := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=1")
|
| 355 |
+
|
| 356 |
+
appendMainLog(t, dir, line2+"\n")
|
| 357 |
+
if err := os.Rename(filepath.Join(dir, defaultLogFileName), filepath.Join(dir, defaultLogFileName+".1")); err != nil {
|
| 358 |
+
t.Fatalf("rotate main log: %v", err)
|
| 359 |
+
}
|
| 360 |
+
writeMainLog(t, dir, line3+"\n")
|
| 361 |
+
|
| 362 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(initial.NextCursor)+"&limit=10")
|
| 363 |
+
wantLines := []string{line2, line3}
|
| 364 |
+
if !reflect.DeepEqual(resp.Lines, wantLines) {
|
| 365 |
+
t.Fatalf("lines = %#v, want %#v", resp.Lines, wantLines)
|
| 366 |
+
}
|
| 367 |
+
if resp.CursorReset {
|
| 368 |
+
t.Fatal("cursor-reset = true, want false")
|
| 369 |
+
}
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
func TestGetLogsCursorReadsRotatedFileWhenNewMainIsSmaller(t *testing.T) {
|
| 373 |
+
dir := t.TempDir()
|
| 374 |
+
line1 := "[2026-06-15 10:00:00] first line with enough bytes"
|
| 375 |
+
line2 := "[2026-06-15 10:00:01] second"
|
| 376 |
+
line3 := "new"
|
| 377 |
+
writeMainLog(t, dir, line1+"\n")
|
| 378 |
+
initial := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=1")
|
| 379 |
+
|
| 380 |
+
appendMainLog(t, dir, line2+"\n")
|
| 381 |
+
if err := os.Rename(filepath.Join(dir, defaultLogFileName), filepath.Join(dir, defaultLogFileName+".1")); err != nil {
|
| 382 |
+
t.Fatalf("rotate main log: %v", err)
|
| 383 |
+
}
|
| 384 |
+
writeMainLog(t, dir, line3+"\n")
|
| 385 |
+
|
| 386 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(initial.NextCursor)+"&limit=1")
|
| 387 |
+
if !reflect.DeepEqual(resp.Lines, []string{line2}) {
|
| 388 |
+
t.Fatalf("lines = %#v, want rotated unread line", resp.Lines)
|
| 389 |
+
}
|
| 390 |
+
if resp.CursorReset {
|
| 391 |
+
t.Fatal("cursor-reset = true, want false")
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
next := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(resp.NextCursor)+"&limit=1")
|
| 395 |
+
if !reflect.DeepEqual(next.Lines, []string{line3}) {
|
| 396 |
+
t.Fatalf("next lines = %#v, want new main line", next.Lines)
|
| 397 |
+
}
|
| 398 |
+
if next.CursorReset {
|
| 399 |
+
t.Fatal("next cursor-reset = true, want false")
|
| 400 |
+
}
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
func TestGetLogsZeroOffsetCursorWithPartialLineReadsAcrossRotation(t *testing.T) {
|
| 404 |
+
dir := t.TempDir()
|
| 405 |
+
writeMainLog(t, dir, "partial")
|
| 406 |
+
initial := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=1")
|
| 407 |
+
if initial.NextCursor == "" {
|
| 408 |
+
t.Fatal("initial next-cursor is empty")
|
| 409 |
+
}
|
| 410 |
+
cursor, errCursor := decodeLogCursor(initial.NextCursor)
|
| 411 |
+
if errCursor != nil {
|
| 412 |
+
t.Fatalf("decode initial cursor: %v", errCursor)
|
| 413 |
+
}
|
| 414 |
+
if cursor.Offset != 0 || cursor.Size == 0 {
|
| 415 |
+
t.Fatalf("cursor offset/size = %d/%d, want zero offset with partial size", cursor.Offset, cursor.Size)
|
| 416 |
+
}
|
| 417 |
+
|
| 418 |
+
appendMainLog(t, dir, " complete\n")
|
| 419 |
+
if err := os.Rename(filepath.Join(dir, defaultLogFileName), filepath.Join(dir, defaultLogFileName+".1")); err != nil {
|
| 420 |
+
t.Fatalf("rotate main log: %v", err)
|
| 421 |
+
}
|
| 422 |
+
writeMainLog(t, dir, "new\n")
|
| 423 |
+
|
| 424 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(initial.NextCursor)+"&limit=10")
|
| 425 |
+
wantLines := []string{"partial complete", "new"}
|
| 426 |
+
if !reflect.DeepEqual(resp.Lines, wantLines) {
|
| 427 |
+
t.Fatalf("lines = %#v, want %#v", resp.Lines, wantLines)
|
| 428 |
+
}
|
| 429 |
+
if resp.CursorReset {
|
| 430 |
+
t.Fatal("cursor-reset = true, want false")
|
| 431 |
+
}
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
func TestGetLogsZeroOffsetCursorWithEmptyFileReadsAcrossRotation(t *testing.T) {
|
| 435 |
+
dir := t.TempDir()
|
| 436 |
+
writeMainLog(t, dir, "")
|
| 437 |
+
initial := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=1")
|
| 438 |
+
if initial.NextCursor == "" {
|
| 439 |
+
t.Fatal("initial next-cursor is empty")
|
| 440 |
+
}
|
| 441 |
+
cursor, errCursor := decodeLogCursor(initial.NextCursor)
|
| 442 |
+
if errCursor != nil {
|
| 443 |
+
t.Fatalf("decode initial cursor: %v", errCursor)
|
| 444 |
+
}
|
| 445 |
+
if cursor.Offset != 0 || cursor.Size != 0 {
|
| 446 |
+
t.Fatalf("cursor offset/size = %d/%d, want empty zero offset", cursor.Offset, cursor.Size)
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
appendMainLog(t, dir, "first\n")
|
| 450 |
+
mainPath := filepath.Join(dir, defaultLogFileName)
|
| 451 |
+
nextModTime := time.Unix(0, cursorModTimeUnixNano(cursor)+int64(time.Second))
|
| 452 |
+
if err := os.Chtimes(mainPath, nextModTime, nextModTime); err != nil {
|
| 453 |
+
t.Fatalf("update main log mtime: %v", err)
|
| 454 |
+
}
|
| 455 |
+
if err := os.Rename(mainPath, filepath.Join(dir, defaultLogFileName+".1")); err != nil {
|
| 456 |
+
t.Fatalf("rotate main log: %v", err)
|
| 457 |
+
}
|
| 458 |
+
writeMainLog(t, dir, "second\n")
|
| 459 |
+
|
| 460 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(initial.NextCursor)+"&limit=1")
|
| 461 |
+
if !reflect.DeepEqual(resp.Lines, []string{"first"}) {
|
| 462 |
+
t.Fatalf("lines = %#v, want first rotated line", resp.Lines)
|
| 463 |
+
}
|
| 464 |
+
if resp.CursorReset {
|
| 465 |
+
t.Fatal("cursor-reset = true, want false")
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
next := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(resp.NextCursor)+"&limit=1")
|
| 469 |
+
if !reflect.DeepEqual(next.Lines, []string{"second"}) {
|
| 470 |
+
t.Fatalf("next lines = %#v, want second main line", next.Lines)
|
| 471 |
+
}
|
| 472 |
+
if next.CursorReset {
|
| 473 |
+
t.Fatal("next cursor-reset = true, want false")
|
| 474 |
+
}
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
func TestGetLogsZeroOffsetCursorWithEmptyFileReadsAcrossTwoRotations(t *testing.T) {
|
| 478 |
+
dir := t.TempDir()
|
| 479 |
+
writeMainLog(t, dir, "")
|
| 480 |
+
initial := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=1")
|
| 481 |
+
if initial.NextCursor == "" {
|
| 482 |
+
t.Fatal("initial next-cursor is empty")
|
| 483 |
+
}
|
| 484 |
+
cursor, errCursor := decodeLogCursor(initial.NextCursor)
|
| 485 |
+
if errCursor != nil {
|
| 486 |
+
t.Fatalf("decode initial cursor: %v", errCursor)
|
| 487 |
+
}
|
| 488 |
+
if cursor.Offset != 0 || cursor.Size != 0 {
|
| 489 |
+
t.Fatalf("cursor offset/size = %d/%d, want empty zero offset", cursor.Offset, cursor.Size)
|
| 490 |
+
}
|
| 491 |
+
|
| 492 |
+
mainPath := filepath.Join(dir, defaultLogFileName)
|
| 493 |
+
firstRotatedPath := filepath.Join(dir, defaultLogFileName+".1")
|
| 494 |
+
secondRotatedPath := filepath.Join(dir, defaultLogFileName+".2")
|
| 495 |
+
firstModTime := time.Unix(0, cursorModTimeUnixNano(cursor)+int64(time.Second))
|
| 496 |
+
secondModTime := time.Unix(0, cursorModTimeUnixNano(cursor)+2*int64(time.Second))
|
| 497 |
+
|
| 498 |
+
appendMainLog(t, dir, "first\n")
|
| 499 |
+
if err := os.Chtimes(mainPath, firstModTime, firstModTime); err != nil {
|
| 500 |
+
t.Fatalf("update first main log mtime: %v", err)
|
| 501 |
+
}
|
| 502 |
+
if err := os.Rename(mainPath, firstRotatedPath); err != nil {
|
| 503 |
+
t.Fatalf("rotate first main log: %v", err)
|
| 504 |
+
}
|
| 505 |
+
writeMainLog(t, dir, "second\n")
|
| 506 |
+
if err := os.Chtimes(mainPath, secondModTime, secondModTime); err != nil {
|
| 507 |
+
t.Fatalf("update second main log mtime: %v", err)
|
| 508 |
+
}
|
| 509 |
+
if err := os.Rename(firstRotatedPath, secondRotatedPath); err != nil {
|
| 510 |
+
t.Fatalf("advance first rotated log: %v", err)
|
| 511 |
+
}
|
| 512 |
+
if err := os.Rename(mainPath, firstRotatedPath); err != nil {
|
| 513 |
+
t.Fatalf("rotate second main log: %v", err)
|
| 514 |
+
}
|
| 515 |
+
writeMainLog(t, dir, "third\n")
|
| 516 |
+
|
| 517 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(initial.NextCursor)+"&limit=1")
|
| 518 |
+
if !reflect.DeepEqual(resp.Lines, []string{"first"}) {
|
| 519 |
+
t.Fatalf("lines = %#v, want oldest rotated line", resp.Lines)
|
| 520 |
+
}
|
| 521 |
+
if resp.CursorReset {
|
| 522 |
+
t.Fatal("cursor-reset = true, want false")
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
next := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(resp.NextCursor)+"&limit=1")
|
| 526 |
+
if !reflect.DeepEqual(next.Lines, []string{"second"}) {
|
| 527 |
+
t.Fatalf("next lines = %#v, want newer rotated line", next.Lines)
|
| 528 |
+
}
|
| 529 |
+
if next.CursorReset {
|
| 530 |
+
t.Fatal("next cursor-reset = true, want false")
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
latest := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(next.NextCursor)+"&limit=1")
|
| 534 |
+
if !reflect.DeepEqual(latest.Lines, []string{"third"}) {
|
| 535 |
+
t.Fatalf("latest lines = %#v, want main line", latest.Lines)
|
| 536 |
+
}
|
| 537 |
+
if latest.CursorReset {
|
| 538 |
+
t.Fatal("latest cursor-reset = true, want false")
|
| 539 |
+
}
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
func TestGetLogsZeroOffsetCursorWithEmptyFileResetsWhenRotationModTimeAmbiguous(t *testing.T) {
|
| 543 |
+
dir := t.TempDir()
|
| 544 |
+
mainPath := filepath.Join(dir, defaultLogFileName)
|
| 545 |
+
fixedModTime := time.Date(2026, 6, 15, 10, 0, 0, 0, time.Local)
|
| 546 |
+
writeMainLog(t, dir, "")
|
| 547 |
+
if err := os.Chtimes(mainPath, fixedModTime, fixedModTime); err != nil {
|
| 548 |
+
t.Fatalf("set initial main mtime: %v", err)
|
| 549 |
+
}
|
| 550 |
+
initial := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?limit=1")
|
| 551 |
+
if initial.NextCursor == "" {
|
| 552 |
+
t.Fatal("initial next-cursor is empty")
|
| 553 |
+
}
|
| 554 |
+
cursor, errCursor := decodeLogCursor(initial.NextCursor)
|
| 555 |
+
if errCursor != nil {
|
| 556 |
+
t.Fatalf("decode initial cursor: %v", errCursor)
|
| 557 |
+
}
|
| 558 |
+
if cursor.Offset != 0 || cursor.Size != 0 {
|
| 559 |
+
t.Fatalf("cursor offset/size = %d/%d, want empty zero offset", cursor.Offset, cursor.Size)
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
first := "[2026-06-15 10:00:01] first"
|
| 563 |
+
second := "[2026-06-15 10:00:02] second"
|
| 564 |
+
appendMainLog(t, dir, first+"\n")
|
| 565 |
+
if err := os.Chtimes(mainPath, fixedModTime, fixedModTime); err != nil {
|
| 566 |
+
t.Fatalf("set rotated mtime: %v", err)
|
| 567 |
+
}
|
| 568 |
+
if err := os.Rename(mainPath, filepath.Join(dir, defaultLogFileName+".1")); err != nil {
|
| 569 |
+
t.Fatalf("rotate main log: %v", err)
|
| 570 |
+
}
|
| 571 |
+
writeMainLog(t, dir, second+"\n")
|
| 572 |
+
if err := os.Chtimes(mainPath, fixedModTime, fixedModTime); err != nil {
|
| 573 |
+
t.Fatalf("set new main mtime: %v", err)
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(initial.NextCursor)+"&limit=2")
|
| 577 |
+
wantLines := []string{first, second}
|
| 578 |
+
if !reflect.DeepEqual(resp.Lines, wantLines) {
|
| 579 |
+
t.Fatalf("lines = %#v, want %#v", resp.Lines, wantLines)
|
| 580 |
+
}
|
| 581 |
+
if !resp.CursorReset {
|
| 582 |
+
t.Fatal("cursor-reset = false, want true for ambiguous empty cursor rotation")
|
| 583 |
+
}
|
| 584 |
+
if resp.LineCount != len(wantLines) {
|
| 585 |
+
t.Fatalf("line-count = %d, want returned line count %d", resp.LineCount, len(wantLines))
|
| 586 |
+
}
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
func TestGetLogsInvalidCursorResetsToTail(t *testing.T) {
|
| 590 |
+
dir := t.TempDir()
|
| 591 |
+
lines := []string{
|
| 592 |
+
"[2026-06-15 10:00:00] first",
|
| 593 |
+
"[2026-06-15 10:00:01] second",
|
| 594 |
+
}
|
| 595 |
+
writeMainLog(t, dir, strings.Join(lines, "\n")+"\n")
|
| 596 |
+
|
| 597 |
+
cases := []string{
|
| 598 |
+
"not-base64",
|
| 599 |
+
mustEncodeRawCursor(t, logCursor{
|
| 600 |
+
Version: logCursorVersion,
|
| 601 |
+
File: "../secret",
|
| 602 |
+
Fingerprint: "fingerprint",
|
| 603 |
+
}),
|
| 604 |
+
}
|
| 605 |
+
for _, raw := range cases {
|
| 606 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(raw)+"&limit=1")
|
| 607 |
+
if !resp.CursorReset {
|
| 608 |
+
t.Fatalf("cursor-reset = false for cursor %q", raw)
|
| 609 |
+
}
|
| 610 |
+
if !reflect.DeepEqual(resp.Lines, []string{lines[1]}) {
|
| 611 |
+
t.Fatalf("lines = %#v, want latest line", resp.Lines)
|
| 612 |
+
}
|
| 613 |
+
if resp.LineCount != 1 {
|
| 614 |
+
t.Fatalf("line-count = %d, want 1", resp.LineCount)
|
| 615 |
+
}
|
| 616 |
+
}
|
| 617 |
+
}
|
| 618 |
+
|
| 619 |
+
func TestGetLogsMissingRotatedCursorFileResetsToTail(t *testing.T) {
|
| 620 |
+
dir := t.TempDir()
|
| 621 |
+
current := "[2026-06-15 10:00:01] current"
|
| 622 |
+
writeMainLog(t, dir, current+"\n")
|
| 623 |
+
rotatedPath := filepath.Join(dir, defaultLogFileName+".1")
|
| 624 |
+
if err := os.WriteFile(rotatedPath, []byte("[2026-06-15 10:00:00] old\n"), 0o644); err != nil {
|
| 625 |
+
t.Fatalf("write rotated log: %v", err)
|
| 626 |
+
}
|
| 627 |
+
cursor, errCursor := newLogCursor(rotatedPath, int64(len("[2026-06-15 10:00:00] old\n")), 0)
|
| 628 |
+
if errCursor != nil {
|
| 629 |
+
t.Fatalf("newLogCursor() error = %v", errCursor)
|
| 630 |
+
}
|
| 631 |
+
if errRemove := os.Remove(rotatedPath); errRemove != nil {
|
| 632 |
+
t.Fatalf("remove rotated log: %v", errRemove)
|
| 633 |
+
}
|
| 634 |
+
|
| 635 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape(cursor)+"&limit=1")
|
| 636 |
+
if !resp.CursorReset {
|
| 637 |
+
t.Fatal("cursor-reset = false, want true")
|
| 638 |
+
}
|
| 639 |
+
if !reflect.DeepEqual(resp.Lines, []string{current}) {
|
| 640 |
+
t.Fatalf("lines = %#v, want current tail", resp.Lines)
|
| 641 |
+
}
|
| 642 |
+
}
|
| 643 |
+
|
| 644 |
+
func TestGetLogsMissingLogDirKeepsOKEmptyResponse(t *testing.T) {
|
| 645 |
+
dir := filepath.Join(t.TempDir(), "missing")
|
| 646 |
+
resp := performGetLogs(t, newLogsTestHandler(dir, true), "/v0/management/logs?cursor="+url.QueryEscape("not-base64")+"&limit=1")
|
| 647 |
+
if len(resp.Lines) != 0 {
|
| 648 |
+
t.Fatalf("lines = %#v, want empty", resp.Lines)
|
| 649 |
+
}
|
| 650 |
+
if resp.LineCount != 0 {
|
| 651 |
+
t.Fatalf("line-count = %d, want 0", resp.LineCount)
|
| 652 |
+
}
|
| 653 |
+
if !resp.CursorReset {
|
| 654 |
+
t.Fatal("cursor-reset = false, want true for cursor against missing log dir")
|
| 655 |
+
}
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
func TestGetLogsLoggingDisabledKeepsBadRequest(t *testing.T) {
|
| 659 |
+
status, body := performGetLogsRaw(t, newLogsTestHandler(t.TempDir(), false), "/v0/management/logs?cursor=not-base64&limit=1")
|
| 660 |
+
if status != http.StatusBadRequest {
|
| 661 |
+
t.Fatalf("status = %d, want %d", status, http.StatusBadRequest)
|
| 662 |
+
}
|
| 663 |
+
if !strings.Contains(body, "logging to file disabled") {
|
| 664 |
+
t.Fatalf("body = %s, want logging disabled error", body)
|
| 665 |
+
}
|
| 666 |
+
}
|
| 667 |
+
|
| 668 |
+
func mustEncodeRawCursor(t *testing.T, cursor logCursor) string {
|
| 669 |
+
t.Helper()
|
| 670 |
+
raw, err := json.Marshal(cursor)
|
| 671 |
+
if err != nil {
|
| 672 |
+
t.Fatalf("json.Marshal cursor: %v", err)
|
| 673 |
+
}
|
| 674 |
+
return base64.RawURLEncoding.EncodeToString(raw)
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
type logsAPIResponse struct {
|
| 678 |
+
Lines []string `json:"lines"`
|
| 679 |
+
LineCount int `json:"line-count"`
|
| 680 |
+
LatestTimestamp int64 `json:"latest-timestamp"`
|
| 681 |
+
NextCursor string `json:"next-cursor"`
|
| 682 |
+
CursorReset bool `json:"cursor-reset"`
|
| 683 |
+
}
|
| 684 |
+
|
| 685 |
+
func newLogsTestHandler(dir string, loggingToFile bool) *Handler {
|
| 686 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{LoggingToFile: loggingToFile}, nil)
|
| 687 |
+
h.SetLogDirectory(dir)
|
| 688 |
+
return h
|
| 689 |
+
}
|
| 690 |
+
|
| 691 |
+
func performGetLogs(t *testing.T, h *Handler, target string) logsAPIResponse {
|
| 692 |
+
t.Helper()
|
| 693 |
+
status, body := performGetLogsRaw(t, h, target)
|
| 694 |
+
if status != http.StatusOK {
|
| 695 |
+
t.Fatalf("GetLogs status = %d, body = %s", status, body)
|
| 696 |
+
}
|
| 697 |
+
var resp logsAPIResponse
|
| 698 |
+
if err := json.Unmarshal([]byte(body), &resp); err != nil {
|
| 699 |
+
t.Fatalf("decode response: %v", err)
|
| 700 |
+
}
|
| 701 |
+
if resp.Lines == nil {
|
| 702 |
+
resp.Lines = []string{}
|
| 703 |
+
}
|
| 704 |
+
return resp
|
| 705 |
+
}
|
| 706 |
+
|
| 707 |
+
func performGetLogsRaw(t *testing.T, h *Handler, target string) (int, string) {
|
| 708 |
+
t.Helper()
|
| 709 |
+
rec := httptest.NewRecorder()
|
| 710 |
+
c, _ := gin.CreateTestContext(rec)
|
| 711 |
+
c.Request = httptest.NewRequest(http.MethodGet, target, nil)
|
| 712 |
+
h.GetLogs(c)
|
| 713 |
+
return rec.Code, rec.Body.String()
|
| 714 |
+
}
|
| 715 |
+
|
| 716 |
+
func writeMainLog(t *testing.T, dir, content string) {
|
| 717 |
+
t.Helper()
|
| 718 |
+
if err := os.WriteFile(filepath.Join(dir, defaultLogFileName), []byte(content), 0o644); err != nil {
|
| 719 |
+
t.Fatalf("write main log: %v", err)
|
| 720 |
+
}
|
| 721 |
+
}
|
| 722 |
+
|
| 723 |
+
func appendMainLog(t *testing.T, dir, content string) {
|
| 724 |
+
t.Helper()
|
| 725 |
+
file, errOpen := os.OpenFile(filepath.Join(dir, defaultLogFileName), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
|
| 726 |
+
if errOpen != nil {
|
| 727 |
+
t.Fatalf("open main log: %v", errOpen)
|
| 728 |
+
}
|
| 729 |
+
if _, errWrite := file.WriteString(content); errWrite != nil {
|
| 730 |
+
_ = file.Close()
|
| 731 |
+
t.Fatalf("append main log: %v", errWrite)
|
| 732 |
+
}
|
| 733 |
+
if errClose := file.Close(); errClose != nil {
|
| 734 |
+
t.Fatalf("close main log: %v", errClose)
|
| 735 |
+
}
|
| 736 |
+
}
|
internal/api/handlers/management/model_definitions.go
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
"strings"
|
| 6 |
+
|
| 7 |
+
"github.com/gin-gonic/gin"
|
| 8 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
// GetStaticModelDefinitions returns static model metadata for a given channel.
|
| 12 |
+
// Channel is provided via path param (:channel) or query param (?channel=...).
|
| 13 |
+
func (h *Handler) GetStaticModelDefinitions(c *gin.Context) {
|
| 14 |
+
channel := strings.TrimSpace(c.Param("channel"))
|
| 15 |
+
if channel == "" {
|
| 16 |
+
channel = strings.TrimSpace(c.Query("channel"))
|
| 17 |
+
}
|
| 18 |
+
if channel == "" {
|
| 19 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "channel is required"})
|
| 20 |
+
return
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
models := registry.GetStaticModelDefinitionsByChannel(channel)
|
| 24 |
+
if models == nil {
|
| 25 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "unknown channel", "channel": channel})
|
| 26 |
+
return
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
c.JSON(http.StatusOK, gin.H{
|
| 30 |
+
"channel": strings.ToLower(strings.TrimSpace(channel)),
|
| 31 |
+
"models": models,
|
| 32 |
+
})
|
| 33 |
+
}
|
internal/api/handlers/management/oauth_callback.go
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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string `json:"provider"`
|
| 15 |
+
RedirectURL string `json:"redirect_url"`
|
| 16 |
+
Code string `json:"code"`
|
| 17 |
+
State string `json:"state"`
|
| 18 |
+
Error string `json:"error"`
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
func (h *Handler) PostOAuthCallback(c *gin.Context) {
|
| 22 |
+
if h == nil || h.cfg == nil {
|
| 23 |
+
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "handler not initialized"})
|
| 24 |
+
return
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
var req oauthCallbackRequest
|
| 28 |
+
if errBindJSON := c.ShouldBindJSON(&req); errBindJSON != nil {
|
| 29 |
+
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "invalid body"})
|
| 30 |
+
return
|
| 31 |
+
}
|
| 32 |
+
h.handleOAuthCallback(c, req)
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
func (h *Handler) GetOAuthCallback(c *gin.Context) {
|
| 36 |
+
req := oauthCallbackRequest{
|
| 37 |
+
Provider: strings.TrimSpace(c.Query("provider")),
|
| 38 |
+
Code: strings.TrimSpace(c.Query("code")),
|
| 39 |
+
State: strings.TrimSpace(c.Query("state")),
|
| 40 |
+
Error: firstNonEmpty(c.Query("error"), c.Query("error_description")),
|
| 41 |
+
}
|
| 42 |
+
h.handleOAuthCallback(c, req)
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
func (h *Handler) handleOAuthCallback(c *gin.Context, req oauthCallbackRequest) {
|
| 46 |
+
if h == nil || h.cfg == nil {
|
| 47 |
+
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "handler not initialized"})
|
| 48 |
+
return
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
state := strings.TrimSpace(req.State)
|
| 52 |
+
code := strings.TrimSpace(req.Code)
|
| 53 |
+
errMsg := strings.TrimSpace(req.Error)
|
| 54 |
+
|
| 55 |
+
if rawRedirect := strings.TrimSpace(req.RedirectURL); rawRedirect != "" {
|
| 56 |
+
u, errParse := url.Parse(rawRedirect)
|
| 57 |
+
if errParse != nil {
|
| 58 |
+
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "invalid redirect_url"})
|
| 59 |
+
return
|
| 60 |
+
}
|
| 61 |
+
q := u.Query()
|
| 62 |
+
if state == "" {
|
| 63 |
+
state = strings.TrimSpace(q.Get("state"))
|
| 64 |
+
}
|
| 65 |
+
if code == "" {
|
| 66 |
+
code = strings.TrimSpace(q.Get("code"))
|
| 67 |
+
}
|
| 68 |
+
if errMsg == "" {
|
| 69 |
+
errMsg = strings.TrimSpace(q.Get("error"))
|
| 70 |
+
if errMsg == "" {
|
| 71 |
+
errMsg = strings.TrimSpace(q.Get("error_description"))
|
| 72 |
+
}
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
if state == "" {
|
| 77 |
+
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "state is required"})
|
| 78 |
+
return
|
| 79 |
+
}
|
| 80 |
+
if err := ValidateOAuthState(state); err != nil {
|
| 81 |
+
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "invalid state"})
|
| 82 |
+
return
|
| 83 |
+
}
|
| 84 |
+
if code == "" && errMsg == "" {
|
| 85 |
+
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "code or error is required"})
|
| 86 |
+
return
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
sessionProvider, sessionStatus, isPlugin, _, completed, ok := GetOAuthSessionDetails(state)
|
| 90 |
+
if !ok {
|
| 91 |
+
c.JSON(http.StatusNotFound, gin.H{"status": "error", "error": "unknown or expired state"})
|
| 92 |
+
return
|
| 93 |
+
}
|
| 94 |
+
if completed {
|
| 95 |
+
c.JSON(http.StatusConflict, gin.H{"status": "error", "error": "oauth flow is already completed"})
|
| 96 |
+
return
|
| 97 |
+
}
|
| 98 |
+
provider := strings.TrimSpace(req.Provider)
|
| 99 |
+
if provider == "" {
|
| 100 |
+
provider = sessionProvider
|
| 101 |
+
}
|
| 102 |
+
var canonicalProvider string
|
| 103 |
+
var errNormalize error
|
| 104 |
+
if isPlugin {
|
| 105 |
+
canonicalProvider, errNormalize = NormalizePluginOAuthCallbackProvider(provider)
|
| 106 |
+
} else {
|
| 107 |
+
canonicalProvider, errNormalize = NormalizeOAuthCallbackProvider(provider)
|
| 108 |
+
}
|
| 109 |
+
if errNormalize != nil {
|
| 110 |
+
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "unsupported provider"})
|
| 111 |
+
return
|
| 112 |
+
}
|
| 113 |
+
if sessionStatus != "" {
|
| 114 |
+
c.JSON(http.StatusConflict, gin.H{"status": "error", "error": sessionStatus})
|
| 115 |
+
return
|
| 116 |
+
}
|
| 117 |
+
if !strings.EqualFold(sessionProvider, canonicalProvider) {
|
| 118 |
+
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "provider does not match state"})
|
| 119 |
+
return
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
if _, errWrite := WriteOAuthCallbackFileForPendingSession(h.cfg.AuthDir, canonicalProvider, state, code, errMsg); errWrite != nil {
|
| 123 |
+
if errors.Is(errWrite, errOAuthSessionNotPending) {
|
| 124 |
+
_, status, okSession := GetOAuthSession(state)
|
| 125 |
+
if okSession && status != "" {
|
| 126 |
+
c.JSON(http.StatusConflict, gin.H{"status": "error", "error": status})
|
| 127 |
+
return
|
| 128 |
+
}
|
| 129 |
+
c.JSON(http.StatusConflict, gin.H{"status": "error", "error": "oauth flow is not pending"})
|
| 130 |
+
return
|
| 131 |
+
}
|
| 132 |
+
log.WithError(errWrite).Error("failed to persist oauth callback")
|
| 133 |
+
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "failed to persist oauth callback"})
|
| 134 |
+
return
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
func firstNonEmpty(values ...string) string {
|
| 141 |
+
for _, value := range values {
|
| 142 |
+
trimmed := strings.TrimSpace(value)
|
| 143 |
+
if trimmed != "" {
|
| 144 |
+
return trimmed
|
| 145 |
+
}
|
| 146 |
+
}
|
| 147 |
+
return ""
|
| 148 |
+
}
|
internal/api/handlers/management/oauth_callback_test.go
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"net/http"
|
| 6 |
+
"net/http/httptest"
|
| 7 |
+
"os"
|
| 8 |
+
"path/filepath"
|
| 9 |
+
"strings"
|
| 10 |
+
"testing"
|
| 11 |
+
|
| 12 |
+
"github.com/gin-gonic/gin"
|
| 13 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
func TestPostOAuthCallbackCreatesMissingAuthDir(t *testing.T) {
|
| 17 |
+
|
| 18 |
+
authDir := filepath.Join(t.TempDir(), "missing-auth")
|
| 19 |
+
state := "test-antigravity-state"
|
| 20 |
+
RegisterOAuthSession(state, "antigravity")
|
| 21 |
+
defer CompleteOAuthSession(state)
|
| 22 |
+
|
| 23 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
| 24 |
+
router := gin.New()
|
| 25 |
+
router.POST("/v0/management/oauth-callback", h.PostOAuthCallback)
|
| 26 |
+
|
| 27 |
+
body := `{"provider":"antigravity","redirect_url":"http://localhost:59788/oauth-callback?state=test-antigravity-state&code=test-code"}`
|
| 28 |
+
req := httptest.NewRequest(http.MethodPost, "/v0/management/oauth-callback", strings.NewReader(body))
|
| 29 |
+
req.Header.Set("Content-Type", "application/json")
|
| 30 |
+
w := httptest.NewRecorder()
|
| 31 |
+
|
| 32 |
+
router.ServeHTTP(w, req)
|
| 33 |
+
|
| 34 |
+
if w.Code != http.StatusOK {
|
| 35 |
+
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, w.Code, w.Body.String())
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
callbackPath := filepath.Join(authDir, ".oauth-antigravity-"+state+".oauth")
|
| 39 |
+
data, errRead := os.ReadFile(callbackPath)
|
| 40 |
+
if errRead != nil {
|
| 41 |
+
t.Fatalf("expected callback file to be written: %v", errRead)
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
var payload oauthCallbackFilePayload
|
| 45 |
+
if errUnmarshal := json.Unmarshal(data, &payload); errUnmarshal != nil {
|
| 46 |
+
t.Fatalf("failed to decode callback payload: %v", errUnmarshal)
|
| 47 |
+
}
|
| 48 |
+
if payload.State != state || payload.Code != "test-code" || payload.Error != "" {
|
| 49 |
+
t.Fatalf("unexpected callback payload: %+v", payload)
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
func TestGetOAuthCallbackWritesPluginProviderCallback(t *testing.T) {
|
| 54 |
+
authDir := filepath.Join(t.TempDir(), "missing-auth")
|
| 55 |
+
state := "test-geminicli-state"
|
| 56 |
+
if errRegister := RegisterPluginOAuthSession(state, "gemini-cli", nil); errRegister != nil {
|
| 57 |
+
t.Fatalf("register plugin oauth session: %v", errRegister)
|
| 58 |
+
}
|
| 59 |
+
defer CompleteOAuthSession(state)
|
| 60 |
+
|
| 61 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
| 62 |
+
router := gin.New()
|
| 63 |
+
router.GET("/v0/management/oauth-callback", h.GetOAuthCallback)
|
| 64 |
+
|
| 65 |
+
req := httptest.NewRequest(http.MethodGet, "/v0/management/oauth-callback?state="+state+"&code=test-code", nil)
|
| 66 |
+
w := httptest.NewRecorder()
|
| 67 |
+
|
| 68 |
+
router.ServeHTTP(w, req)
|
| 69 |
+
|
| 70 |
+
if w.Code != http.StatusOK {
|
| 71 |
+
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, w.Code, w.Body.String())
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
callbackPath := filepath.Join(authDir, ".oauth-gemini-cli-"+state+".oauth")
|
| 75 |
+
data, errRead := os.ReadFile(callbackPath)
|
| 76 |
+
if errRead != nil {
|
| 77 |
+
t.Fatalf("expected callback file to be written: %v", errRead)
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
var payload oauthCallbackFilePayload
|
| 81 |
+
if errUnmarshal := json.Unmarshal(data, &payload); errUnmarshal != nil {
|
| 82 |
+
t.Fatalf("failed to decode callback payload: %v", errUnmarshal)
|
| 83 |
+
}
|
| 84 |
+
if payload.State != state || payload.Code != "test-code" || payload.Error != "" {
|
| 85 |
+
t.Fatalf("unexpected callback payload: %+v", payload)
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
func TestGetOAuthCallbackDoesNotAliasPluginProvider(t *testing.T) {
|
| 90 |
+
authDir := filepath.Join(t.TempDir(), "missing-auth")
|
| 91 |
+
state := "test-openai-plugin-state"
|
| 92 |
+
if errRegister := RegisterPluginOAuthSession(state, "openai", nil); errRegister != nil {
|
| 93 |
+
t.Fatalf("register plugin oauth session: %v", errRegister)
|
| 94 |
+
}
|
| 95 |
+
defer CompleteOAuthSession(state)
|
| 96 |
+
|
| 97 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
| 98 |
+
router := gin.New()
|
| 99 |
+
router.GET("/v0/management/oauth-callback", h.GetOAuthCallback)
|
| 100 |
+
|
| 101 |
+
req := httptest.NewRequest(http.MethodGet, "/v0/management/oauth-callback?state="+state+"&code=test-code", nil)
|
| 102 |
+
w := httptest.NewRecorder()
|
| 103 |
+
|
| 104 |
+
router.ServeHTTP(w, req)
|
| 105 |
+
|
| 106 |
+
if w.Code != http.StatusOK {
|
| 107 |
+
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, w.Code, w.Body.String())
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
callbackPath := filepath.Join(authDir, ".oauth-openai-"+state+".oauth")
|
| 111 |
+
if _, errRead := os.ReadFile(callbackPath); errRead != nil {
|
| 112 |
+
t.Fatalf("expected plugin callback provider to stay openai: %v", errRead)
|
| 113 |
+
}
|
| 114 |
+
if _, errRead := os.ReadFile(filepath.Join(authDir, ".oauth-codex-"+state+".oauth")); errRead == nil {
|
| 115 |
+
t.Fatal("unexpected codex callback file for openai plugin provider")
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
func TestWriteOAuthCallbackFileForPendingSessionCreatesMissingAuthDirForCallbackProviders(t *testing.T) {
|
| 120 |
+
// xAI uses device-code flow and no longer writes callback files.
|
| 121 |
+
providers := []string{"anthropic", "codex", "gemini", "antigravity"}
|
| 122 |
+
for _, provider := range providers {
|
| 123 |
+
t.Run(provider, func(t *testing.T) {
|
| 124 |
+
authDir := filepath.Join(t.TempDir(), "missing-auth")
|
| 125 |
+
state := provider + "-state"
|
| 126 |
+
RegisterOAuthSession(state, provider)
|
| 127 |
+
defer CompleteOAuthSession(state)
|
| 128 |
+
|
| 129 |
+
path, errWrite := WriteOAuthCallbackFileForPendingSession(authDir, provider, state, "code-"+provider, "")
|
| 130 |
+
if errWrite != nil {
|
| 131 |
+
t.Fatalf("expected callback file write to succeed: %v", errWrite)
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
data, errRead := os.ReadFile(path)
|
| 135 |
+
if errRead != nil {
|
| 136 |
+
t.Fatalf("expected callback file to be written: %v", errRead)
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
var payload oauthCallbackFilePayload
|
| 140 |
+
if errUnmarshal := json.Unmarshal(data, &payload); errUnmarshal != nil {
|
| 141 |
+
t.Fatalf("failed to decode callback payload: %v", errUnmarshal)
|
| 142 |
+
}
|
| 143 |
+
if payload.State != state || payload.Code != "code-"+provider || payload.Error != "" {
|
| 144 |
+
t.Fatalf("unexpected callback payload: %+v", payload)
|
| 145 |
+
}
|
| 146 |
+
})
|
| 147 |
+
}
|
| 148 |
+
}
|
internal/api/handlers/management/oauth_codex_concurrency_test.go
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/http/httptest"
|
| 8 |
+
"path/filepath"
|
| 9 |
+
"testing"
|
| 10 |
+
"time"
|
| 11 |
+
|
| 12 |
+
"github.com/gin-gonic/gin"
|
| 13 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/auth/codex"
|
| 14 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
type fakeCodexOAuthService struct{}
|
| 18 |
+
|
| 19 |
+
func (f *fakeCodexOAuthService) GenerateAuthURL(state string, pkceCodes *codex.PKCECodes) (string, error) {
|
| 20 |
+
return "https://auth.example.test/oauth?state=" + state, nil
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
func (f *fakeCodexOAuthService) ExchangeCodeForTokens(ctx context.Context, code string, pkceCodes *codex.PKCECodes) (*codex.CodexAuthBundle, error) {
|
| 24 |
+
now := time.Now()
|
| 25 |
+
return &codex.CodexAuthBundle{
|
| 26 |
+
TokenData: codex.CodexTokenData{
|
| 27 |
+
IDToken: "invalid-test-id-token",
|
| 28 |
+
AccessToken: "access-" + code,
|
| 29 |
+
RefreshToken: "refresh-" + code,
|
| 30 |
+
Email: "codex-" + code + "@example.test",
|
| 31 |
+
Expire: now.Add(time.Hour).Format(time.RFC3339),
|
| 32 |
+
},
|
| 33 |
+
LastRefresh: now.Format(time.RFC3339),
|
| 34 |
+
}, nil
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
func (f *fakeCodexOAuthService) CreateTokenStorage(bundle *codex.CodexAuthBundle) *codex.CodexTokenStorage {
|
| 38 |
+
return &codex.CodexTokenStorage{
|
| 39 |
+
IDToken: bundle.TokenData.IDToken,
|
| 40 |
+
AccessToken: bundle.TokenData.AccessToken,
|
| 41 |
+
RefreshToken: bundle.TokenData.RefreshToken,
|
| 42 |
+
AccountID: bundle.TokenData.AccountID,
|
| 43 |
+
LastRefresh: bundle.LastRefresh,
|
| 44 |
+
Email: bundle.TokenData.Email,
|
| 45 |
+
Expire: bundle.TokenData.Expire,
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
func TestRequestCodexTokenCompletionKeepsConcurrentSessionPending(t *testing.T) {
|
| 50 |
+
originalNewCodexOAuthService := newCodexOAuthService
|
| 51 |
+
newCodexOAuthService = func(cfg *config.Config) codexOAuthService {
|
| 52 |
+
return &fakeCodexOAuthService{}
|
| 53 |
+
}
|
| 54 |
+
defer func() {
|
| 55 |
+
newCodexOAuthService = originalNewCodexOAuthService
|
| 56 |
+
}()
|
| 57 |
+
|
| 58 |
+
authDir := filepath.Join(t.TempDir(), "auths")
|
| 59 |
+
handler := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, nil)
|
| 60 |
+
router := gin.New()
|
| 61 |
+
router.GET("/codex-auth-url", handler.RequestCodexToken)
|
| 62 |
+
|
| 63 |
+
firstState := requestCodexTokenState(t, router)
|
| 64 |
+
secondState := requestCodexTokenState(t, router)
|
| 65 |
+
defer CompleteOAuthSession(firstState)
|
| 66 |
+
defer CompleteOAuthSession(secondState)
|
| 67 |
+
|
| 68 |
+
if _, errWrite := WriteOAuthCallbackFileForPendingSession(authDir, "codex", firstState, "first-code", ""); errWrite != nil {
|
| 69 |
+
t.Fatalf("write first callback file: %v", errWrite)
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
waitForOAuthSessionDone(t, firstState)
|
| 73 |
+
if !IsOAuthSessionPending(secondState, "codex") {
|
| 74 |
+
t.Fatalf("expected concurrent codex session %s to remain pending after %s completed", secondState, firstState)
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
func requestCodexTokenState(t *testing.T, router http.Handler) string {
|
| 79 |
+
t.Helper()
|
| 80 |
+
|
| 81 |
+
req := httptest.NewRequest(http.MethodGet, "/codex-auth-url", nil)
|
| 82 |
+
w := httptest.NewRecorder()
|
| 83 |
+
router.ServeHTTP(w, req)
|
| 84 |
+
if w.Code != http.StatusOK {
|
| 85 |
+
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, w.Code, w.Body.String())
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
var payload struct {
|
| 89 |
+
State string `json:"state"`
|
| 90 |
+
}
|
| 91 |
+
if errDecode := json.Unmarshal(w.Body.Bytes(), &payload); errDecode != nil {
|
| 92 |
+
t.Fatalf("decode codex auth URL response: %v", errDecode)
|
| 93 |
+
}
|
| 94 |
+
if payload.State == "" {
|
| 95 |
+
t.Fatalf("expected codex auth URL response to include state")
|
| 96 |
+
}
|
| 97 |
+
return payload.State
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
func waitForOAuthSessionDone(t *testing.T, state string) {
|
| 101 |
+
t.Helper()
|
| 102 |
+
|
| 103 |
+
deadline := time.Now().Add(3 * time.Second)
|
| 104 |
+
for time.Now().Before(deadline) {
|
| 105 |
+
if !IsOAuthSessionPending(state, "codex") {
|
| 106 |
+
return
|
| 107 |
+
}
|
| 108 |
+
time.Sleep(20 * time.Millisecond)
|
| 109 |
+
}
|
| 110 |
+
t.Fatalf("timed out waiting for codex session %s to complete", state)
|
| 111 |
+
}
|
internal/api/handlers/management/oauth_sessions.go
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"errors"
|
| 6 |
+
"fmt"
|
| 7 |
+
"os"
|
| 8 |
+
"path/filepath"
|
| 9 |
+
"strings"
|
| 10 |
+
"sync"
|
| 11 |
+
"time"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
const (
|
| 15 |
+
// oauthSessionTTL must cover device-code flows (xAI ~30m, Kimi ~15m).
|
| 16 |
+
oauthSessionTTL = 30 * time.Minute
|
| 17 |
+
oauthCompletedSessionTTL = time.Minute
|
| 18 |
+
maxOAuthStateLength = 128
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
const (
|
| 22 |
+
oauthSessionSourceBuiltin = "builtin"
|
| 23 |
+
oauthSessionSourcePlugin = "plugin"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
var (
|
| 27 |
+
errInvalidOAuthState = errors.New("invalid oauth state")
|
| 28 |
+
errUnsupportedOAuthFlow = errors.New("unsupported oauth provider")
|
| 29 |
+
errOAuthSessionNotPending = errors.New("oauth session is not pending")
|
| 30 |
+
errOAuthSessionExists = errors.New("oauth session already exists")
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
type oauthSession struct {
|
| 34 |
+
Provider string
|
| 35 |
+
Status string
|
| 36 |
+
Source string
|
| 37 |
+
Metadata map[string]any
|
| 38 |
+
Completed bool
|
| 39 |
+
CreatedAt time.Time
|
| 40 |
+
ExpiresAt time.Time
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
type oauthSessionStore struct {
|
| 44 |
+
mu sync.RWMutex
|
| 45 |
+
ttl time.Duration
|
| 46 |
+
completedTTL time.Duration
|
| 47 |
+
sessions map[string]oauthSession
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
func newOAuthSessionStore(ttl time.Duration) *oauthSessionStore {
|
| 51 |
+
if ttl <= 0 {
|
| 52 |
+
ttl = oauthSessionTTL
|
| 53 |
+
}
|
| 54 |
+
completedTTL := oauthCompletedSessionTTL
|
| 55 |
+
if ttl < completedTTL {
|
| 56 |
+
completedTTL = ttl
|
| 57 |
+
}
|
| 58 |
+
return &oauthSessionStore{
|
| 59 |
+
ttl: ttl,
|
| 60 |
+
completedTTL: completedTTL,
|
| 61 |
+
sessions: make(map[string]oauthSession),
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
func (s *oauthSessionStore) purgeExpiredLocked(now time.Time) {
|
| 66 |
+
for state, session := range s.sessions {
|
| 67 |
+
if !session.ExpiresAt.IsZero() && now.After(session.ExpiresAt) {
|
| 68 |
+
delete(s.sessions, state)
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
func (s *oauthSessionStore) Register(state, provider string) {
|
| 74 |
+
state = strings.TrimSpace(state)
|
| 75 |
+
provider = strings.ToLower(strings.TrimSpace(provider))
|
| 76 |
+
if state == "" || provider == "" {
|
| 77 |
+
return
|
| 78 |
+
}
|
| 79 |
+
now := time.Now()
|
| 80 |
+
|
| 81 |
+
s.mu.Lock()
|
| 82 |
+
defer s.mu.Unlock()
|
| 83 |
+
|
| 84 |
+
s.purgeExpiredLocked(now)
|
| 85 |
+
s.sessions[state] = oauthSession{
|
| 86 |
+
Provider: provider,
|
| 87 |
+
Status: "",
|
| 88 |
+
Source: oauthSessionSourceBuiltin,
|
| 89 |
+
CreatedAt: now,
|
| 90 |
+
ExpiresAt: now.Add(s.ttl),
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
func (s *oauthSessionStore) RegisterPlugin(state, provider string, metadata map[string]any) error {
|
| 95 |
+
state = strings.TrimSpace(state)
|
| 96 |
+
provider = strings.ToLower(strings.TrimSpace(provider))
|
| 97 |
+
if state == "" || provider == "" {
|
| 98 |
+
return fmt.Errorf("%w: empty state or provider", errInvalidOAuthState)
|
| 99 |
+
}
|
| 100 |
+
if errState := ValidateOAuthState(state); errState != nil {
|
| 101 |
+
return errState
|
| 102 |
+
}
|
| 103 |
+
now := time.Now()
|
| 104 |
+
|
| 105 |
+
s.mu.Lock()
|
| 106 |
+
defer s.mu.Unlock()
|
| 107 |
+
|
| 108 |
+
s.purgeExpiredLocked(now)
|
| 109 |
+
if _, ok := s.sessions[state]; ok {
|
| 110 |
+
return errOAuthSessionExists
|
| 111 |
+
}
|
| 112 |
+
s.sessions[state] = oauthSession{
|
| 113 |
+
Provider: provider,
|
| 114 |
+
Status: "",
|
| 115 |
+
Source: oauthSessionSourcePlugin,
|
| 116 |
+
Metadata: cloneOAuthSessionMetadata(metadata),
|
| 117 |
+
CreatedAt: now,
|
| 118 |
+
ExpiresAt: now.Add(s.ttl),
|
| 119 |
+
}
|
| 120 |
+
return nil
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
func (s *oauthSessionStore) SetError(state, message string) {
|
| 124 |
+
state = strings.TrimSpace(state)
|
| 125 |
+
message = strings.TrimSpace(message)
|
| 126 |
+
if state == "" {
|
| 127 |
+
return
|
| 128 |
+
}
|
| 129 |
+
if message == "" {
|
| 130 |
+
message = "Authentication failed"
|
| 131 |
+
}
|
| 132 |
+
now := time.Now()
|
| 133 |
+
|
| 134 |
+
s.mu.Lock()
|
| 135 |
+
defer s.mu.Unlock()
|
| 136 |
+
|
| 137 |
+
s.purgeExpiredLocked(now)
|
| 138 |
+
session, ok := s.sessions[state]
|
| 139 |
+
if !ok || session.Completed {
|
| 140 |
+
return
|
| 141 |
+
}
|
| 142 |
+
session.Status = message
|
| 143 |
+
session.ExpiresAt = now.Add(s.ttl)
|
| 144 |
+
s.sessions[state] = session
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
func (s *oauthSessionStore) Complete(state string) {
|
| 148 |
+
state = strings.TrimSpace(state)
|
| 149 |
+
if state == "" {
|
| 150 |
+
return
|
| 151 |
+
}
|
| 152 |
+
now := time.Now()
|
| 153 |
+
|
| 154 |
+
s.mu.Lock()
|
| 155 |
+
defer s.mu.Unlock()
|
| 156 |
+
|
| 157 |
+
s.purgeExpiredLocked(now)
|
| 158 |
+
session, ok := s.sessions[state]
|
| 159 |
+
if !ok || session.Completed {
|
| 160 |
+
return
|
| 161 |
+
}
|
| 162 |
+
session.Status = ""
|
| 163 |
+
session.Metadata = nil
|
| 164 |
+
session.Completed = true
|
| 165 |
+
session.ExpiresAt = now.Add(s.completedTTL)
|
| 166 |
+
s.sessions[state] = session
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
func (s *oauthSessionStore) CompleteProvider(provider string, source string) int {
|
| 170 |
+
provider = strings.ToLower(strings.TrimSpace(provider))
|
| 171 |
+
if provider == "" {
|
| 172 |
+
return 0
|
| 173 |
+
}
|
| 174 |
+
source = strings.TrimSpace(source)
|
| 175 |
+
now := time.Now()
|
| 176 |
+
|
| 177 |
+
s.mu.Lock()
|
| 178 |
+
defer s.mu.Unlock()
|
| 179 |
+
|
| 180 |
+
s.purgeExpiredLocked(now)
|
| 181 |
+
removed := 0
|
| 182 |
+
for state, session := range s.sessions {
|
| 183 |
+
if !session.Completed && strings.EqualFold(session.Provider, provider) && (source == "" || session.Source == source) {
|
| 184 |
+
session.Status = ""
|
| 185 |
+
session.Metadata = nil
|
| 186 |
+
session.Completed = true
|
| 187 |
+
session.ExpiresAt = now.Add(s.completedTTL)
|
| 188 |
+
s.sessions[state] = session
|
| 189 |
+
removed++
|
| 190 |
+
}
|
| 191 |
+
}
|
| 192 |
+
return removed
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
func (s *oauthSessionStore) Get(state string) (oauthSession, bool) {
|
| 196 |
+
state = strings.TrimSpace(state)
|
| 197 |
+
now := time.Now()
|
| 198 |
+
|
| 199 |
+
s.mu.Lock()
|
| 200 |
+
defer s.mu.Unlock()
|
| 201 |
+
|
| 202 |
+
s.purgeExpiredLocked(now)
|
| 203 |
+
session, ok := s.sessions[state]
|
| 204 |
+
session.Metadata = cloneOAuthSessionMetadata(session.Metadata)
|
| 205 |
+
return session, ok
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
func (s *oauthSessionStore) IsPending(state, provider string) bool {
|
| 209 |
+
state = strings.TrimSpace(state)
|
| 210 |
+
provider = strings.ToLower(strings.TrimSpace(provider))
|
| 211 |
+
now := time.Now()
|
| 212 |
+
|
| 213 |
+
s.mu.Lock()
|
| 214 |
+
defer s.mu.Unlock()
|
| 215 |
+
|
| 216 |
+
s.purgeExpiredLocked(now)
|
| 217 |
+
session, ok := s.sessions[state]
|
| 218 |
+
if !ok {
|
| 219 |
+
return false
|
| 220 |
+
}
|
| 221 |
+
if session.Completed || session.Status != "" {
|
| 222 |
+
return false
|
| 223 |
+
}
|
| 224 |
+
if provider == "" {
|
| 225 |
+
return true
|
| 226 |
+
}
|
| 227 |
+
return strings.EqualFold(session.Provider, provider)
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
// Cancel removes a pending OAuth session so background waiters exit without saving credentials.
|
| 231 |
+
// Returns true when a pending session was cancelled.
|
| 232 |
+
func (s *oauthSessionStore) Cancel(state string) bool {
|
| 233 |
+
state = strings.TrimSpace(state)
|
| 234 |
+
if state == "" {
|
| 235 |
+
return false
|
| 236 |
+
}
|
| 237 |
+
now := time.Now()
|
| 238 |
+
|
| 239 |
+
s.mu.Lock()
|
| 240 |
+
defer s.mu.Unlock()
|
| 241 |
+
|
| 242 |
+
s.purgeExpiredLocked(now)
|
| 243 |
+
session, ok := s.sessions[state]
|
| 244 |
+
if !ok || session.Completed || session.Status != "" {
|
| 245 |
+
return false
|
| 246 |
+
}
|
| 247 |
+
delete(s.sessions, state)
|
| 248 |
+
return true
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
func cloneOAuthSessionMetadata(in map[string]any) map[string]any {
|
| 252 |
+
if len(in) == 0 {
|
| 253 |
+
return nil
|
| 254 |
+
}
|
| 255 |
+
out := make(map[string]any, len(in))
|
| 256 |
+
for key, value := range in {
|
| 257 |
+
out[key] = value
|
| 258 |
+
}
|
| 259 |
+
return out
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
var oauthSessions = newOAuthSessionStore(oauthSessionTTL)
|
| 263 |
+
|
| 264 |
+
func RegisterOAuthSession(state, provider string) { oauthSessions.Register(state, provider) }
|
| 265 |
+
|
| 266 |
+
func RegisterPluginOAuthSession(state, provider string, metadata map[string]any) error {
|
| 267 |
+
return oauthSessions.RegisterPlugin(state, provider, metadata)
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
func SetOAuthSessionError(state, message string) { oauthSessions.SetError(state, message) }
|
| 271 |
+
|
| 272 |
+
func CompleteOAuthSession(state string) { oauthSessions.Complete(state) }
|
| 273 |
+
|
| 274 |
+
func CompleteOAuthSessionsByProvider(provider string) int {
|
| 275 |
+
return oauthSessions.CompleteProvider(provider, oauthSessionSourceBuiltin)
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
func CompletePluginOAuthSessionsByProvider(provider string) int {
|
| 279 |
+
return oauthSessions.CompleteProvider(provider, oauthSessionSourcePlugin)
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
func GetOAuthSession(state string) (provider string, status string, ok bool) {
|
| 283 |
+
session, ok := oauthSessions.Get(state)
|
| 284 |
+
if !ok || session.Completed {
|
| 285 |
+
return "", "", false
|
| 286 |
+
}
|
| 287 |
+
return session.Provider, session.Status, true
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
func GetOAuthSessionDetails(state string) (provider string, status string, isPlugin bool, metadata map[string]any, completed bool, ok bool) {
|
| 291 |
+
session, ok := oauthSessions.Get(state)
|
| 292 |
+
if !ok {
|
| 293 |
+
return "", "", false, nil, false, false
|
| 294 |
+
}
|
| 295 |
+
return session.Provider, session.Status, session.Source == oauthSessionSourcePlugin, cloneOAuthSessionMetadata(session.Metadata), session.Completed, true
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
func IsOAuthSessionPending(state, provider string) bool {
|
| 299 |
+
return oauthSessions.IsPending(state, provider)
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
// guardOAuthSessionPendingForSave returns errOAuthSessionNotPending when the session
|
| 303 |
+
// is no longer pending (cancelled, completed, errored, or expired).
|
| 304 |
+
// Call immediately before persisting credentials so a cancel that races with token
|
| 305 |
+
// exchange or metadata fetch cannot save credentials for a cancelled flow.
|
| 306 |
+
func guardOAuthSessionPendingForSave(state, provider string) error {
|
| 307 |
+
if IsOAuthSessionPending(state, provider) {
|
| 308 |
+
return nil
|
| 309 |
+
}
|
| 310 |
+
return errOAuthSessionNotPending
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
// CancelOAuthSession cancels a pending OAuth session by state.
|
| 314 |
+
// Background callback and device-code waiters observe IsOAuthSessionPending as false and exit without saving credentials.
|
| 315 |
+
func CancelOAuthSession(state string) bool {
|
| 316 |
+
return oauthSessions.Cancel(state)
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
func oauthSessionErrorWithCause(message string, cause error) string {
|
| 320 |
+
message = strings.TrimSpace(message)
|
| 321 |
+
if message == "" {
|
| 322 |
+
message = "Authentication failed"
|
| 323 |
+
}
|
| 324 |
+
if cause == nil {
|
| 325 |
+
return message
|
| 326 |
+
}
|
| 327 |
+
detail := strings.TrimSpace(cause.Error())
|
| 328 |
+
if detail == "" {
|
| 329 |
+
return message
|
| 330 |
+
}
|
| 331 |
+
return message + ": " + detail
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
func ValidateOAuthState(state string) error {
|
| 335 |
+
trimmed := strings.TrimSpace(state)
|
| 336 |
+
if trimmed == "" {
|
| 337 |
+
return fmt.Errorf("%w: empty", errInvalidOAuthState)
|
| 338 |
+
}
|
| 339 |
+
if len(trimmed) > maxOAuthStateLength {
|
| 340 |
+
return fmt.Errorf("%w: too long", errInvalidOAuthState)
|
| 341 |
+
}
|
| 342 |
+
if strings.Contains(trimmed, "/") || strings.Contains(trimmed, "\\") {
|
| 343 |
+
return fmt.Errorf("%w: contains path separator", errInvalidOAuthState)
|
| 344 |
+
}
|
| 345 |
+
if strings.Contains(trimmed, "..") {
|
| 346 |
+
return fmt.Errorf("%w: contains '..'", errInvalidOAuthState)
|
| 347 |
+
}
|
| 348 |
+
for _, r := range trimmed {
|
| 349 |
+
switch {
|
| 350 |
+
case r >= 'a' && r <= 'z':
|
| 351 |
+
case r >= 'A' && r <= 'Z':
|
| 352 |
+
case r >= '0' && r <= '9':
|
| 353 |
+
case r == '-' || r == '_' || r == '.':
|
| 354 |
+
default:
|
| 355 |
+
return fmt.Errorf("%w: invalid character", errInvalidOAuthState)
|
| 356 |
+
}
|
| 357 |
+
}
|
| 358 |
+
return nil
|
| 359 |
+
}
|
| 360 |
+
|
| 361 |
+
func NormalizeOAuthProvider(provider string) (string, error) {
|
| 362 |
+
switch strings.ToLower(strings.TrimSpace(provider)) {
|
| 363 |
+
case "anthropic", "claude":
|
| 364 |
+
return "anthropic", nil
|
| 365 |
+
case "codex", "openai":
|
| 366 |
+
return "codex", nil
|
| 367 |
+
case "antigravity", "anti-gravity":
|
| 368 |
+
return "antigravity", nil
|
| 369 |
+
case "xai", "x-ai", "x.ai", "grok":
|
| 370 |
+
return "xai", nil
|
| 371 |
+
default:
|
| 372 |
+
return "", errUnsupportedOAuthFlow
|
| 373 |
+
}
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
func NormalizeOAuthCallbackProvider(provider string) (string, error) {
|
| 377 |
+
if normalized, errNormalize := NormalizeOAuthProvider(provider); errNormalize == nil {
|
| 378 |
+
return normalized, nil
|
| 379 |
+
}
|
| 380 |
+
return NormalizePluginOAuthCallbackProvider(provider)
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
func NormalizePluginOAuthCallbackProvider(provider string) (string, error) {
|
| 384 |
+
trimmed := strings.ToLower(strings.TrimSpace(provider))
|
| 385 |
+
if trimmed == "" {
|
| 386 |
+
return "", errUnsupportedOAuthFlow
|
| 387 |
+
}
|
| 388 |
+
for _, r := range trimmed {
|
| 389 |
+
switch {
|
| 390 |
+
case r >= 'a' && r <= 'z':
|
| 391 |
+
case r >= '0' && r <= '9':
|
| 392 |
+
case r == '-':
|
| 393 |
+
default:
|
| 394 |
+
return "", errUnsupportedOAuthFlow
|
| 395 |
+
}
|
| 396 |
+
}
|
| 397 |
+
return trimmed, nil
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
func normalizeOAuthCallbackProviderForPendingSession(provider, state string) (string, error) {
|
| 401 |
+
session, ok := oauthSessions.Get(state)
|
| 402 |
+
if ok && session.Source == oauthSessionSourcePlugin {
|
| 403 |
+
return NormalizePluginOAuthCallbackProvider(provider)
|
| 404 |
+
}
|
| 405 |
+
return NormalizeOAuthCallbackProvider(provider)
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
type oauthCallbackFilePayload struct {
|
| 409 |
+
Code string `json:"code"`
|
| 410 |
+
State string `json:"state"`
|
| 411 |
+
Error string `json:"error"`
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
func WriteOAuthCallbackFile(authDir, provider, state, code, errorMessage string) (string, error) {
|
| 415 |
+
canonicalProvider, err := NormalizeOAuthCallbackProvider(provider)
|
| 416 |
+
if err != nil {
|
| 417 |
+
return "", err
|
| 418 |
+
}
|
| 419 |
+
return writeOAuthCallbackFile(authDir, canonicalProvider, state, code, errorMessage)
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
func writeOAuthCallbackFile(authDir, canonicalProvider, state, code, errorMessage string) (string, error) {
|
| 423 |
+
if strings.TrimSpace(authDir) == "" {
|
| 424 |
+
return "", fmt.Errorf("auth dir is empty")
|
| 425 |
+
}
|
| 426 |
+
canonicalProvider = strings.TrimSpace(canonicalProvider)
|
| 427 |
+
if canonicalProvider == "" {
|
| 428 |
+
return "", errUnsupportedOAuthFlow
|
| 429 |
+
}
|
| 430 |
+
if err := ValidateOAuthState(state); err != nil {
|
| 431 |
+
return "", err
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
fileName := fmt.Sprintf(".oauth-%s-%s.oauth", canonicalProvider, state)
|
| 435 |
+
filePath := filepath.Join(authDir, fileName)
|
| 436 |
+
if err := os.MkdirAll(authDir, 0o700); err != nil {
|
| 437 |
+
return "", fmt.Errorf("create oauth callback dir: %w", err)
|
| 438 |
+
}
|
| 439 |
+
payload := oauthCallbackFilePayload{
|
| 440 |
+
Code: strings.TrimSpace(code),
|
| 441 |
+
State: strings.TrimSpace(state),
|
| 442 |
+
Error: strings.TrimSpace(errorMessage),
|
| 443 |
+
}
|
| 444 |
+
data, err := json.Marshal(payload)
|
| 445 |
+
if err != nil {
|
| 446 |
+
return "", fmt.Errorf("marshal oauth callback payload: %w", err)
|
| 447 |
+
}
|
| 448 |
+
if err := os.WriteFile(filePath, data, 0o600); err != nil {
|
| 449 |
+
return "", fmt.Errorf("write oauth callback file: %w", err)
|
| 450 |
+
}
|
| 451 |
+
return filePath, nil
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
func WriteOAuthCallbackFileForPendingSession(authDir, provider, state, code, errorMessage string) (string, error) {
|
| 455 |
+
canonicalProvider, err := normalizeOAuthCallbackProviderForPendingSession(provider, state)
|
| 456 |
+
if err != nil {
|
| 457 |
+
return "", err
|
| 458 |
+
}
|
| 459 |
+
if !IsOAuthSessionPending(state, canonicalProvider) {
|
| 460 |
+
return "", errOAuthSessionNotPending
|
| 461 |
+
}
|
| 462 |
+
return writeOAuthCallbackFile(authDir, canonicalProvider, state, code, errorMessage)
|
| 463 |
+
}
|
internal/api/handlers/management/oauth_sessions_test.go
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"errors"
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/http/httptest"
|
| 8 |
+
"strings"
|
| 9 |
+
"testing"
|
| 10 |
+
"time"
|
| 11 |
+
|
| 12 |
+
"github.com/gin-gonic/gin"
|
| 13 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
func TestOAuthSessionStoreCompleteKeepsShortLivedSession(t *testing.T) {
|
| 17 |
+
store := newOAuthSessionStore(time.Minute)
|
| 18 |
+
store.Register("completed-state", "codex")
|
| 19 |
+
|
| 20 |
+
store.Complete("completed-state")
|
| 21 |
+
|
| 22 |
+
if _, ok := store.Get("completed-state"); !ok {
|
| 23 |
+
t.Fatal("completed OAuth session was deleted instead of retained as a tombstone")
|
| 24 |
+
}
|
| 25 |
+
if store.IsPending("completed-state", "codex") {
|
| 26 |
+
t.Fatal("completed OAuth session remained pending")
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
func TestOAuthSessionStoreCompleteDoesNotExtendCompletedSession(t *testing.T) {
|
| 31 |
+
store := newOAuthSessionStore(time.Minute)
|
| 32 |
+
store.Register("completed-state", "codex")
|
| 33 |
+
store.Complete("completed-state")
|
| 34 |
+
before, ok := store.Get("completed-state")
|
| 35 |
+
if !ok {
|
| 36 |
+
t.Fatal("completed OAuth session tombstone is missing")
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
store.completedTTL = 2 * time.Minute
|
| 40 |
+
store.Complete("completed-state")
|
| 41 |
+
after, ok := store.Get("completed-state")
|
| 42 |
+
if !ok {
|
| 43 |
+
t.Fatal("completed OAuth session tombstone is missing after repeated completion")
|
| 44 |
+
}
|
| 45 |
+
if !after.ExpiresAt.Equal(before.ExpiresAt) {
|
| 46 |
+
t.Fatalf("repeated completion extended expiry from %s to %s", before.ExpiresAt, after.ExpiresAt)
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
func TestOAuthSessionStoreCompleteProviderSkipsCompletedSessions(t *testing.T) {
|
| 51 |
+
store := newOAuthSessionStore(time.Minute)
|
| 52 |
+
store.Register("completed-state", "codex")
|
| 53 |
+
store.Register("pending-state", "codex")
|
| 54 |
+
store.Complete("completed-state")
|
| 55 |
+
completedBefore, ok := store.Get("completed-state")
|
| 56 |
+
if !ok {
|
| 57 |
+
t.Fatal("completed OAuth session tombstone is missing")
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
store.completedTTL = 2 * time.Minute
|
| 61 |
+
if got := store.CompleteProvider("codex", oauthSessionSourceBuiltin); got != 1 {
|
| 62 |
+
t.Fatalf("CompleteProvider() = %d, want 1 newly completed session", got)
|
| 63 |
+
}
|
| 64 |
+
completedAfter, ok := store.Get("completed-state")
|
| 65 |
+
if !ok {
|
| 66 |
+
t.Fatal("completed OAuth session tombstone is missing after provider completion")
|
| 67 |
+
}
|
| 68 |
+
if !completedAfter.ExpiresAt.Equal(completedBefore.ExpiresAt) {
|
| 69 |
+
t.Fatalf("provider completion extended existing tombstone from %s to %s", completedBefore.ExpiresAt, completedAfter.ExpiresAt)
|
| 70 |
+
}
|
| 71 |
+
pendingAfter, ok := store.Get("pending-state")
|
| 72 |
+
if !ok || !pendingAfter.Completed {
|
| 73 |
+
t.Fatalf("pending session completed/ok = %t/%t, want true/true", pendingAfter.Completed, ok)
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
func TestGetOAuthSessionHidesCompletedSession(t *testing.T) {
|
| 78 |
+
store := newOAuthSessionStore(time.Minute)
|
| 79 |
+
replaceOAuthSessionStoreForTest(t, store)
|
| 80 |
+
store.Register("completed-state", "codex")
|
| 81 |
+
store.Complete("completed-state")
|
| 82 |
+
|
| 83 |
+
provider, status, ok := GetOAuthSession("completed-state")
|
| 84 |
+
if ok {
|
| 85 |
+
t.Fatalf("GetOAuthSession() = (%q, %q, true), want completed session hidden", provider, status)
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
_, _, _, _, completed, detailsOK := GetOAuthSessionDetails("completed-state")
|
| 89 |
+
if !detailsOK || !completed {
|
| 90 |
+
t.Fatalf("GetOAuthSessionDetails() completed/ok = %t/%t, want true/true", completed, detailsOK)
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
func TestGetAuthStatusRejectsUnknownStateAndAcceptsCompletedState(t *testing.T) {
|
| 95 |
+
store := newOAuthSessionStore(time.Minute)
|
| 96 |
+
replaceOAuthSessionStoreForTest(t, store)
|
| 97 |
+
|
| 98 |
+
handler := &Handler{}
|
| 99 |
+
router := gin.New()
|
| 100 |
+
router.GET("/status", handler.GetAuthStatus)
|
| 101 |
+
|
| 102 |
+
unknown := performOAuthStatusRequest(t, router, "unknown-state")
|
| 103 |
+
if unknown.Status != "error" || unknown.Error != "unknown or expired state" {
|
| 104 |
+
t.Fatalf("unknown state response = %#v, want unknown/expired error", unknown)
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
store.Register("completed-state", "codex")
|
| 108 |
+
store.Complete("completed-state")
|
| 109 |
+
completed := performOAuthStatusRequest(t, router, "completed-state")
|
| 110 |
+
if completed.Status != "ok" || completed.Error != "" {
|
| 111 |
+
t.Fatalf("completed state response = %#v, want success", completed)
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
func TestOAuthCallbackRejectsCompletedSession(t *testing.T) {
|
| 116 |
+
store := newOAuthSessionStore(time.Minute)
|
| 117 |
+
replaceOAuthSessionStoreForTest(t, store)
|
| 118 |
+
store.Register("completed-state", "codex")
|
| 119 |
+
store.Complete("completed-state")
|
| 120 |
+
|
| 121 |
+
handler := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, nil)
|
| 122 |
+
router := gin.New()
|
| 123 |
+
router.POST("/oauth-callback", handler.PostOAuthCallback)
|
| 124 |
+
|
| 125 |
+
req := httptest.NewRequest(
|
| 126 |
+
http.MethodPost,
|
| 127 |
+
"/oauth-callback",
|
| 128 |
+
strings.NewReader(`{"provider":"codex","state":"completed-state","code":"test-code"}`),
|
| 129 |
+
)
|
| 130 |
+
req.Header.Set("Content-Type", "application/json")
|
| 131 |
+
w := httptest.NewRecorder()
|
| 132 |
+
router.ServeHTTP(w, req)
|
| 133 |
+
|
| 134 |
+
if w.Code != http.StatusConflict {
|
| 135 |
+
t.Fatalf("completed callback status = %d, want %d; body=%s", w.Code, http.StatusConflict, w.Body.String())
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
type oauthStatusResponse struct {
|
| 140 |
+
Status string `json:"status"`
|
| 141 |
+
Error string `json:"error"`
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
func performOAuthStatusRequest(t *testing.T, router http.Handler, state string) oauthStatusResponse {
|
| 145 |
+
t.Helper()
|
| 146 |
+
req := httptest.NewRequest(http.MethodGet, "/status?state="+state, nil)
|
| 147 |
+
w := httptest.NewRecorder()
|
| 148 |
+
router.ServeHTTP(w, req)
|
| 149 |
+
|
| 150 |
+
if w.Code != http.StatusOK {
|
| 151 |
+
t.Fatalf("status request returned %d, want %d; body=%s", w.Code, http.StatusOK, w.Body.String())
|
| 152 |
+
}
|
| 153 |
+
var response oauthStatusResponse
|
| 154 |
+
if errDecode := json.Unmarshal(w.Body.Bytes(), &response); errDecode != nil {
|
| 155 |
+
t.Fatalf("decode status response: %v", errDecode)
|
| 156 |
+
}
|
| 157 |
+
return response
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
func TestOAuthSessionStoreCancelRemovesPendingSession(t *testing.T) {
|
| 161 |
+
store := newOAuthSessionStore(time.Minute)
|
| 162 |
+
store.Register("pending-state", "xai")
|
| 163 |
+
|
| 164 |
+
if !store.Cancel("pending-state") {
|
| 165 |
+
t.Fatal("Cancel() = false, want true for pending session")
|
| 166 |
+
}
|
| 167 |
+
if store.IsPending("pending-state", "xai") {
|
| 168 |
+
t.Fatal("cancelled session remained pending")
|
| 169 |
+
}
|
| 170 |
+
if _, ok := store.Get("pending-state"); ok {
|
| 171 |
+
t.Fatal("cancelled session still present in store")
|
| 172 |
+
}
|
| 173 |
+
if store.Cancel("pending-state") {
|
| 174 |
+
t.Fatal("second Cancel() = true, want false")
|
| 175 |
+
}
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
func TestOAuthSessionStoreCancelIgnoresCompletedAndUnknown(t *testing.T) {
|
| 179 |
+
store := newOAuthSessionStore(time.Minute)
|
| 180 |
+
store.Register("completed-state", "codex")
|
| 181 |
+
store.Complete("completed-state")
|
| 182 |
+
|
| 183 |
+
if store.Cancel("completed-state") {
|
| 184 |
+
t.Fatal("Cancel() completed session = true, want false")
|
| 185 |
+
}
|
| 186 |
+
if _, ok := store.Get("completed-state"); !ok {
|
| 187 |
+
t.Fatal("completed tombstone was removed by Cancel")
|
| 188 |
+
}
|
| 189 |
+
if store.Cancel("missing-state") {
|
| 190 |
+
t.Fatal("Cancel() unknown session = true, want false")
|
| 191 |
+
}
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
func TestOAuthSessionStoreCancelIgnoresErrorSession(t *testing.T) {
|
| 195 |
+
store := newOAuthSessionStore(time.Minute)
|
| 196 |
+
store.Register("error-state", "kimi")
|
| 197 |
+
store.SetError("error-state", "Authentication failed")
|
| 198 |
+
|
| 199 |
+
if store.IsPending("error-state", "kimi") {
|
| 200 |
+
t.Fatal("error session should not be pending")
|
| 201 |
+
}
|
| 202 |
+
if store.Cancel("error-state") {
|
| 203 |
+
t.Fatal("Cancel() error session = true, want false")
|
| 204 |
+
}
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
func TestCancelOAuthSessionAndCallbackRejectAfterCancel(t *testing.T) {
|
| 208 |
+
store := newOAuthSessionStore(time.Minute)
|
| 209 |
+
replaceOAuthSessionStoreForTest(t, store)
|
| 210 |
+
store.Register("callback-state", "anthropic")
|
| 211 |
+
|
| 212 |
+
if !CancelOAuthSession("callback-state") {
|
| 213 |
+
t.Fatal("CancelOAuthSession() = false, want true")
|
| 214 |
+
}
|
| 215 |
+
if IsOAuthSessionPending("callback-state", "anthropic") {
|
| 216 |
+
t.Fatal("session still pending after cancel")
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
_, errWrite := WriteOAuthCallbackFileForPendingSession(t.TempDir(), "anthropic", "callback-state", "code", "")
|
| 220 |
+
if errWrite == nil {
|
| 221 |
+
t.Fatal("expected callback write to fail after cancel")
|
| 222 |
+
}
|
| 223 |
+
if !errors.Is(errWrite, errOAuthSessionNotPending) {
|
| 224 |
+
t.Fatalf("callback write error = %v, want %v", errWrite, errOAuthSessionNotPending)
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
func TestGuardOAuthSessionPendingForSave(t *testing.T) {
|
| 229 |
+
store := newOAuthSessionStore(time.Minute)
|
| 230 |
+
replaceOAuthSessionStoreForTest(t, store)
|
| 231 |
+
|
| 232 |
+
providers := []string{"anthropic", "codex", "antigravity", "xai", "kimi"}
|
| 233 |
+
for _, provider := range providers {
|
| 234 |
+
state := provider + "-save-guard"
|
| 235 |
+
store.Register(state, provider)
|
| 236 |
+
|
| 237 |
+
if errGuard := guardOAuthSessionPendingForSave(state, provider); errGuard != nil {
|
| 238 |
+
t.Fatalf("%s pending guard error = %v, want nil", provider, errGuard)
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
if !CancelOAuthSession(state) {
|
| 242 |
+
t.Fatalf("%s CancelOAuthSession() = false, want true", provider)
|
| 243 |
+
}
|
| 244 |
+
if errGuard := guardOAuthSessionPendingForSave(state, provider); !errors.Is(errGuard, errOAuthSessionNotPending) {
|
| 245 |
+
t.Fatalf("%s after cancel guard error = %v, want %v", provider, errGuard, errOAuthSessionNotPending)
|
| 246 |
+
}
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
// Completed and errored sessions must also refuse save.
|
| 250 |
+
store.Register("completed-save", "codex")
|
| 251 |
+
store.Complete("completed-save")
|
| 252 |
+
if errGuard := guardOAuthSessionPendingForSave("completed-save", "codex"); !errors.Is(errGuard, errOAuthSessionNotPending) {
|
| 253 |
+
t.Fatalf("completed guard error = %v, want %v", errGuard, errOAuthSessionNotPending)
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
store.Register("error-save", "anthropic")
|
| 257 |
+
store.SetError("error-save", "Authentication failed")
|
| 258 |
+
if errGuard := guardOAuthSessionPendingForSave("error-save", "anthropic"); !errors.Is(errGuard, errOAuthSessionNotPending) {
|
| 259 |
+
t.Fatalf("error guard error = %v, want %v", errGuard, errOAuthSessionNotPending)
|
| 260 |
+
}
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
func TestCancelAuthSessionHandler(t *testing.T) {
|
| 264 |
+
store := newOAuthSessionStore(time.Minute)
|
| 265 |
+
replaceOAuthSessionStoreForTest(t, store)
|
| 266 |
+
store.Register("device-state", "xai")
|
| 267 |
+
|
| 268 |
+
handler := &Handler{}
|
| 269 |
+
router := gin.New()
|
| 270 |
+
router.DELETE("/oauth-session", handler.CancelAuthSession)
|
| 271 |
+
|
| 272 |
+
missing := performOAuthCancelRequest(t, router, "")
|
| 273 |
+
if missing.status != http.StatusBadRequest {
|
| 274 |
+
t.Fatalf("missing state status = %d, want %d", missing.status, http.StatusBadRequest)
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
invalid := performOAuthCancelRequest(t, router, "bad/state")
|
| 278 |
+
if invalid.status != http.StatusBadRequest {
|
| 279 |
+
t.Fatalf("invalid state status = %d, want %d", invalid.status, http.StatusBadRequest)
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
cancelled := performOAuthCancelRequest(t, router, "device-state")
|
| 283 |
+
if cancelled.status != http.StatusOK || !cancelled.cancelled || cancelled.bodyStatus != "ok" {
|
| 284 |
+
t.Fatalf("cancel pending response = %#v, want ok/cancelled", cancelled)
|
| 285 |
+
}
|
| 286 |
+
if IsOAuthSessionPending("device-state", "xai") {
|
| 287 |
+
t.Fatal("device session still pending after cancel API")
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
repeat := performOAuthCancelRequest(t, router, "device-state")
|
| 291 |
+
if repeat.status != http.StatusOK || repeat.cancelled {
|
| 292 |
+
t.Fatalf("repeat cancel response = %#v, want ok with cancelled=false", repeat)
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
// Status after cancel should not report success.
|
| 296 |
+
statusRouter := gin.New()
|
| 297 |
+
statusRouter.GET("/status", handler.GetAuthStatus)
|
| 298 |
+
unknown := performOAuthStatusRequest(t, statusRouter, "device-state")
|
| 299 |
+
if unknown.Status != "error" || unknown.Error != "unknown or expired state" {
|
| 300 |
+
t.Fatalf("status after cancel = %#v, want unknown/expired error", unknown)
|
| 301 |
+
}
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
type oauthCancelResponse struct {
|
| 305 |
+
status int
|
| 306 |
+
bodyStatus string
|
| 307 |
+
cancelled bool
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
func performOAuthCancelRequest(t *testing.T, router http.Handler, state string) oauthCancelResponse {
|
| 311 |
+
t.Helper()
|
| 312 |
+
path := "/oauth-session"
|
| 313 |
+
if state != "" {
|
| 314 |
+
path += "?state=" + state
|
| 315 |
+
}
|
| 316 |
+
req := httptest.NewRequest(http.MethodDelete, path, nil)
|
| 317 |
+
w := httptest.NewRecorder()
|
| 318 |
+
router.ServeHTTP(w, req)
|
| 319 |
+
|
| 320 |
+
var body struct {
|
| 321 |
+
Status string `json:"status"`
|
| 322 |
+
Cancelled bool `json:"cancelled"`
|
| 323 |
+
Error string `json:"error"`
|
| 324 |
+
}
|
| 325 |
+
if w.Body.Len() > 0 {
|
| 326 |
+
if errDecode := json.Unmarshal(w.Body.Bytes(), &body); errDecode != nil {
|
| 327 |
+
t.Fatalf("decode cancel response: %v body=%s", errDecode, w.Body.String())
|
| 328 |
+
}
|
| 329 |
+
}
|
| 330 |
+
return oauthCancelResponse{
|
| 331 |
+
status: w.Code,
|
| 332 |
+
bodyStatus: body.Status,
|
| 333 |
+
cancelled: body.Cancelled,
|
| 334 |
+
}
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
func replaceOAuthSessionStoreForTest(t *testing.T, store *oauthSessionStore) {
|
| 338 |
+
t.Helper()
|
| 339 |
+
original := oauthSessions
|
| 340 |
+
oauthSessions = store
|
| 341 |
+
t.Cleanup(func() {
|
| 342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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"errors"
|
| 7 |
+
"fmt"
|
| 8 |
+
"io"
|
| 9 |
+
"net/http"
|
| 10 |
+
"runtime"
|
| 11 |
+
"strings"
|
| 12 |
+
"sync"
|
| 13 |
+
"time"
|
| 14 |
+
|
| 15 |
+
"github.com/gin-gonic/gin"
|
| 16 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 17 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/htmlsanitize"
|
| 18 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
|
| 19 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/pluginstore"
|
| 20 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
|
| 21 |
+
sdkconfig "github.com/router-for-me/CLIProxyAPI/v7/sdk/config"
|
| 22 |
+
log "github.com/sirupsen/logrus"
|
| 23 |
+
"gopkg.in/yaml.v3"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
const (
|
| 27 |
+
// pluginReleaseCacheTTL bounds how long a resolved latest release version is
|
| 28 |
+
// reused before the GitHub API is queried again.
|
| 29 |
+
pluginReleaseCacheTTL = 10 * time.Minute
|
| 30 |
+
// pluginReleaseFailureCacheTTL throttles retries after a failed lookup so a
|
| 31 |
+
// rate-limited or unreachable API is not hammered on every listing.
|
| 32 |
+
pluginReleaseFailureCacheTTL = 30 * time.Second
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
type pluginReleaseCacheEntry struct {
|
| 36 |
+
version string
|
| 37 |
+
expiresAt time.Time
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
type pluginStoreListResponse struct {
|
| 41 |
+
PluginsEnabled bool `json:"plugins_enabled"`
|
| 42 |
+
PluginsDir string `json:"plugins_dir"`
|
| 43 |
+
Sources []pluginStoreSource `json:"sources"`
|
| 44 |
+
SourceErrors []pluginStoreSourceErr `json:"source_errors,omitempty"`
|
| 45 |
+
Plugins []pluginStoreListEntry `json:"plugins"`
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
type pluginStoreSource struct {
|
| 49 |
+
ID string `json:"id"`
|
| 50 |
+
Name string `json:"name"`
|
| 51 |
+
URL string `json:"url"`
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
type pluginStoreSourceErr struct {
|
| 55 |
+
SourceID string `json:"source_id"`
|
| 56 |
+
SourceName string `json:"source_name"`
|
| 57 |
+
SourceURL string `json:"source_url"`
|
| 58 |
+
Message string `json:"message"`
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
type pluginStoreListEntry struct {
|
| 62 |
+
StoreID string `json:"store_id"`
|
| 63 |
+
SourceID string `json:"source_id"`
|
| 64 |
+
SourceName string `json:"source_name"`
|
| 65 |
+
SourceURL string `json:"source_url"`
|
| 66 |
+
ID string `json:"id"`
|
| 67 |
+
Name string `json:"name"`
|
| 68 |
+
Description string `json:"description"`
|
| 69 |
+
Author string `json:"author"`
|
| 70 |
+
Version string `json:"version"`
|
| 71 |
+
Repository string `json:"repository"`
|
| 72 |
+
InstallType string `json:"install_type"`
|
| 73 |
+
AuthRequired bool `json:"auth_required"`
|
| 74 |
+
AuthConfigured bool `json:"auth_configured"`
|
| 75 |
+
Platforms []pluginStorePlatform `json:"platforms,omitempty"`
|
| 76 |
+
Logo string `json:"logo,omitempty"`
|
| 77 |
+
Homepage string `json:"homepage,omitempty"`
|
| 78 |
+
License string `json:"license,omitempty"`
|
| 79 |
+
Tags []string `json:"tags,omitempty"`
|
| 80 |
+
Installed bool `json:"installed"`
|
| 81 |
+
InstalledVersion string `json:"installed_version"`
|
| 82 |
+
InstalledSourceID string `json:"installed_source_id,omitempty"`
|
| 83 |
+
InstallSourceStatus string `json:"install_source_status,omitempty"`
|
| 84 |
+
Path string `json:"path"`
|
| 85 |
+
Configured bool `json:"configured"`
|
| 86 |
+
Registered bool `json:"registered"`
|
| 87 |
+
Enabled bool `json:"enabled"`
|
| 88 |
+
EffectiveEnabled bool `json:"effective_enabled"`
|
| 89 |
+
UpdateAvailable bool `json:"update_available"`
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
type pluginStorePlatform struct {
|
| 93 |
+
GOOS string `json:"goos"`
|
| 94 |
+
GOARCH string `json:"goarch"`
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
type pluginInstallResponse struct {
|
| 98 |
+
Status string `json:"status"`
|
| 99 |
+
SourceID string `json:"source_id"`
|
| 100 |
+
SourceName string `json:"source_name"`
|
| 101 |
+
SourceURL string `json:"source_url"`
|
| 102 |
+
ID string `json:"id"`
|
| 103 |
+
Version string `json:"version"`
|
| 104 |
+
InstallType string `json:"install_type"`
|
| 105 |
+
Path string `json:"path"`
|
| 106 |
+
PluginsEnabled bool `json:"plugins_enabled"`
|
| 107 |
+
RestartRequired bool `json:"restart_required"`
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
type pluginInstallRequest struct {
|
| 111 |
+
Version string `json:"version"`
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
type pluginLocalStatus struct {
|
| 115 |
+
Installed bool
|
| 116 |
+
InstalledVersion string
|
| 117 |
+
StoreManaged bool
|
| 118 |
+
InstalledSourceID string
|
| 119 |
+
InstalledSourceURL string
|
| 120 |
+
Path string
|
| 121 |
+
Configured bool
|
| 122 |
+
Registered bool
|
| 123 |
+
Enabled bool
|
| 124 |
+
EffectiveEnabled bool
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
type sourcedPlugin struct {
|
| 128 |
+
source pluginstore.Source
|
| 129 |
+
plugin pluginstore.Plugin
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
func (h *Handler) ListPluginStore(c *gin.Context) {
|
| 133 |
+
pluginsEnabled, pluginsDir, proxyURL, sourceConfigs, storeAuth, configs, host := h.pluginStoreSnapshot()
|
| 134 |
+
resolvedPluginsDir, errResolvePluginsDir := config.ResolvePluginsDir(pluginsDir)
|
| 135 |
+
if errResolvePluginsDir != nil {
|
| 136 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_directory_invalid", "message": errResolvePluginsDir.Error()})
|
| 137 |
+
return
|
| 138 |
+
}
|
| 139 |
+
pluginsDir = resolvedPluginsDir
|
| 140 |
+
sources, errSources := h.pluginStoreSources(sourceConfigs)
|
| 141 |
+
if errSources != nil {
|
| 142 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_store_source_invalid", "message": errSources.Error()})
|
| 143 |
+
return
|
| 144 |
+
}
|
| 145 |
+
plugins, sourceErrors := h.fetchSourcedPlugins(c.Request.Context(), proxyURL, storeAuth, sources)
|
| 146 |
+
if len(plugins) == 0 && len(sourceErrors) > 0 {
|
| 147 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "plugin_store_registry_failed", "message": sourceErrors[0].Message})
|
| 148 |
+
return
|
| 149 |
+
}
|
| 150 |
+
statuses, errStatus := pluginLocalStatuses(pluginsEnabled, pluginsDir, configs, host)
|
| 151 |
+
if errStatus != nil {
|
| 152 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_discovery_failed", "message": errStatus.Error()})
|
| 153 |
+
return
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
latestInput := make([]pluginstore.Plugin, 0, len(plugins))
|
| 157 |
+
for _, item := range plugins {
|
| 158 |
+
latestInput = append(latestInput, item.plugin)
|
| 159 |
+
}
|
| 160 |
+
client := h.newPluginStoreClient(proxyURL, "", storeAuth)
|
| 161 |
+
latestVersions := h.latestPluginVersions(c.Request.Context(), client, latestInput)
|
| 162 |
+
pluginSourceCounts := make(map[string]int, len(plugins))
|
| 163 |
+
for _, item := range plugins {
|
| 164 |
+
pluginSourceCounts[item.plugin.ID]++
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
entries := make([]pluginStoreListEntry, 0, len(plugins))
|
| 168 |
+
for index, item := range plugins {
|
| 169 |
+
plugin := item.plugin
|
| 170 |
+
status := statuses[plugin.ID]
|
| 171 |
+
installedSourceID, installSourceStatus, sourceAllowsUpdate := pluginStoreInstallSourceStatus(
|
| 172 |
+
status,
|
| 173 |
+
sources,
|
| 174 |
+
item.source.ID,
|
| 175 |
+
pluginSourceCounts[plugin.ID],
|
| 176 |
+
)
|
| 177 |
+
installedVersion := status.InstalledVersion
|
| 178 |
+
// Fall back to the registry version when the latest release is unknown.
|
| 179 |
+
storeVersion := plugin.Version
|
| 180 |
+
if latestVersions[index] != "" {
|
| 181 |
+
storeVersion = latestVersions[index]
|
| 182 |
+
}
|
| 183 |
+
entries = append(entries, pluginStoreListEntry{
|
| 184 |
+
StoreID: htmlsanitize.String(item.source.ID + "/" + plugin.ID),
|
| 185 |
+
SourceID: htmlsanitize.String(item.source.ID),
|
| 186 |
+
SourceName: htmlsanitize.String(item.source.Name),
|
| 187 |
+
SourceURL: htmlsanitize.String(item.source.URL),
|
| 188 |
+
ID: htmlsanitize.String(plugin.ID),
|
| 189 |
+
Name: htmlsanitize.String(plugin.Name),
|
| 190 |
+
Description: htmlsanitize.String(plugin.Description),
|
| 191 |
+
Author: htmlsanitize.String(plugin.Author),
|
| 192 |
+
Version: htmlsanitize.String(storeVersion),
|
| 193 |
+
Repository: htmlsanitize.String(plugin.Repository),
|
| 194 |
+
InstallType: htmlsanitize.String(pluginstore.PluginInstallType(plugin)),
|
| 195 |
+
AuthRequired: plugin.AuthRequired,
|
| 196 |
+
AuthConfigured: pluginAuthConfigured(item.source, plugin, storeAuth),
|
| 197 |
+
Platforms: sanitizePluginStorePlatforms(pluginstore.PluginPlatforms(plugin)),
|
| 198 |
+
Logo: htmlsanitize.String(plugin.Logo),
|
| 199 |
+
Homepage: htmlsanitize.String(plugin.Homepage),
|
| 200 |
+
License: htmlsanitize.String(plugin.License),
|
| 201 |
+
Tags: htmlsanitize.Strings(plugin.Tags),
|
| 202 |
+
Installed: status.Installed,
|
| 203 |
+
InstalledVersion: htmlsanitize.String(installedVersion),
|
| 204 |
+
InstalledSourceID: htmlsanitize.String(installedSourceID),
|
| 205 |
+
InstallSourceStatus: htmlsanitize.String(installSourceStatus),
|
| 206 |
+
Path: htmlsanitize.String(status.Path),
|
| 207 |
+
Configured: status.Configured,
|
| 208 |
+
Registered: status.Registered,
|
| 209 |
+
Enabled: status.Enabled,
|
| 210 |
+
EffectiveEnabled: status.EffectiveEnabled,
|
| 211 |
+
UpdateAvailable: sourceAllowsUpdate && pluginstore.UpdateAvailable(installedVersion, storeVersion),
|
| 212 |
+
})
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
c.JSON(http.StatusOK, pluginStoreListResponse{
|
| 216 |
+
PluginsEnabled: pluginsEnabled,
|
| 217 |
+
PluginsDir: htmlsanitize.String(pluginsDir),
|
| 218 |
+
Sources: sanitizePluginStoreSources(sources),
|
| 219 |
+
SourceErrors: sanitizePluginStoreSourceErrors(sourceErrors),
|
| 220 |
+
Plugins: entries,
|
| 221 |
+
})
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
func (h *Handler) InstallPluginFromStore(c *gin.Context) {
|
| 225 |
+
h.installPluginFromStore(c, runtime.GOOS, runtime.GOARCH)
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
func (h *Handler) installPluginFromStore(c *gin.Context, goos, goarch string) {
|
| 229 |
+
id, okID := pluginIDFromRequest(c)
|
| 230 |
+
if !okID {
|
| 231 |
+
return
|
| 232 |
+
}
|
| 233 |
+
requestedVersion, errVersionRequest := pluginInstallRequestedVersion(c)
|
| 234 |
+
if errVersionRequest != nil {
|
| 235 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_request", "message": errVersionRequest.Error()})
|
| 236 |
+
return
|
| 237 |
+
}
|
| 238 |
+
installCtx := c.Request.Context()
|
| 239 |
+
pluginsEnabled, pluginsDir, proxyURL, sourceConfigs, storeAuth, configs, host := h.pluginStoreSnapshot()
|
| 240 |
+
resolvedPluginsDir, errResolvePluginsDir := config.ResolvePluginsDir(pluginsDir)
|
| 241 |
+
if errResolvePluginsDir != nil {
|
| 242 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_directory_invalid", "message": errResolvePluginsDir.Error()})
|
| 243 |
+
return
|
| 244 |
+
}
|
| 245 |
+
pluginsDir = resolvedPluginsDir
|
| 246 |
+
sources, errSources := h.pluginStoreSources(sourceConfigs)
|
| 247 |
+
if errSources != nil {
|
| 248 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_store_source_invalid", "message": errSources.Error()})
|
| 249 |
+
return
|
| 250 |
+
}
|
| 251 |
+
source, plugin, client, okPlugin := h.findPluginStoreInstallTarget(installCtx, proxyURL, storeAuth, sources, id, c.Query("source"), c)
|
| 252 |
+
if !okPlugin {
|
| 253 |
+
return
|
| 254 |
+
}
|
| 255 |
+
if !validatePluginStoreInstallSource(c, configs, sources, id, source.ID) {
|
| 256 |
+
return
|
| 257 |
+
}
|
| 258 |
+
pluginIsBusy := func() bool { return pluginBusy(host, id) }
|
| 259 |
+
installOptions := pluginstore.InstallOptions{
|
| 260 |
+
PluginsDir: pluginsDir,
|
| 261 |
+
GOOS: goos,
|
| 262 |
+
GOARCH: goarch,
|
| 263 |
+
PluginLoaded: pluginIsBusy,
|
| 264 |
+
}
|
| 265 |
+
var manifest pluginstore.Manifest
|
| 266 |
+
var result pluginstore.InstallResult
|
| 267 |
+
var errInstall error
|
| 268 |
+
switch pluginstore.PluginInstallType(plugin) {
|
| 269 |
+
case pluginstore.InstallTypeDirect:
|
| 270 |
+
var errManifest error
|
| 271 |
+
manifest, errManifest = pluginStoreDirectManifest(source, plugin, requestedVersion)
|
| 272 |
+
if errManifest != nil {
|
| 273 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "plugin_manifest_invalid", "message": errManifest.Error()})
|
| 274 |
+
return
|
| 275 |
+
}
|
| 276 |
+
result, errInstall = client.InstallManifest(installCtx, manifest, installOptions)
|
| 277 |
+
case pluginstore.InstallTypeGitHubRelease:
|
| 278 |
+
result, errInstall = installPluginStoreGitHubRelease(installCtx, client, plugin, requestedVersion, installOptions)
|
| 279 |
+
default:
|
| 280 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "plugin_manifest_invalid", "message": fmt.Sprintf("unsupported install type %q", plugin.Install.Type)})
|
| 281 |
+
return
|
| 282 |
+
}
|
| 283 |
+
if errInstall != nil {
|
| 284 |
+
if errors.Is(errInstall, pluginstore.ErrLoadedPluginLocked) {
|
| 285 |
+
c.JSON(http.StatusConflict, gin.H{
|
| 286 |
+
"error": "plugin_update_requires_restart",
|
| 287 |
+
"message": "loaded plugin cannot be overwritten while the server is running",
|
| 288 |
+
"restart_required": true,
|
| 289 |
+
})
|
| 290 |
+
return
|
| 291 |
+
}
|
| 292 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "plugin_install_failed", "message": errInstall.Error()})
|
| 293 |
+
return
|
| 294 |
+
}
|
| 295 |
+
if manifest.ID == "" {
|
| 296 |
+
var errManifest error
|
| 297 |
+
manifest, errManifest = pluginStoreManifestForInstall(source, plugin, result)
|
| 298 |
+
if errManifest != nil {
|
| 299 |
+
c.JSON(http.StatusInternalServerError, gin.H{
|
| 300 |
+
"error": "plugin_manifest_failed",
|
| 301 |
+
"message": fmt.Sprintf("plugin file installed at %s but creating store manifest failed: %s", result.Path, errManifest.Error()),
|
| 302 |
+
"path": result.Path,
|
| 303 |
+
})
|
| 304 |
+
return
|
| 305 |
+
}
|
| 306 |
+
}
|
| 307 |
+
restartRequired := false
|
| 308 |
+
|
| 309 |
+
h.mu.Lock()
|
| 310 |
+
if h.cfg == nil {
|
| 311 |
+
h.mu.Unlock()
|
| 312 |
+
c.JSON(http.StatusInternalServerError, gin.H{
|
| 313 |
+
"error": "config_unavailable",
|
| 314 |
+
"message": fmt.Sprintf("plugin file installed at %s but config is unavailable to enable it", result.Path),
|
| 315 |
+
"path": result.Path,
|
| 316 |
+
})
|
| 317 |
+
return
|
| 318 |
+
}
|
| 319 |
+
if errEnable := h.enablePluginConfigLocked(id, manifest); errEnable != nil {
|
| 320 |
+
h.mu.Unlock()
|
| 321 |
+
c.JSON(http.StatusInternalServerError, gin.H{
|
| 322 |
+
"error": "config_update_failed",
|
| 323 |
+
"message": fmt.Sprintf("plugin file installed at %s but enabling it in config failed: %s", result.Path, errEnable.Error()),
|
| 324 |
+
"path": result.Path,
|
| 325 |
+
})
|
| 326 |
+
return
|
| 327 |
+
}
|
| 328 |
+
if errSave := config.SaveConfigPreserveComments(h.configFilePath, h.cfg); errSave != nil {
|
| 329 |
+
h.mu.Unlock()
|
| 330 |
+
c.JSON(http.StatusInternalServerError, gin.H{
|
| 331 |
+
"error": "config_save_failed",
|
| 332 |
+
"message": fmt.Sprintf("plugin file installed at %s but saving config failed: %s", result.Path, errSave.Error()),
|
| 333 |
+
"path": result.Path,
|
| 334 |
+
})
|
| 335 |
+
return
|
| 336 |
+
}
|
| 337 |
+
cfgSnapshot := h.reloadSnapshotConfigLocked()
|
| 338 |
+
h.mu.Unlock()
|
| 339 |
+
|
| 340 |
+
h.reloadConfigAfterManagementSaveAsync(c.Request.Context(), cfgSnapshot)
|
| 341 |
+
log.WithFields(log.Fields{
|
| 342 |
+
"plugin_id": result.ID,
|
| 343 |
+
"plugin_name": plugin.Name,
|
| 344 |
+
"source_id": source.ID,
|
| 345 |
+
"version": result.Version,
|
| 346 |
+
"install_type": result.InstallType,
|
| 347 |
+
"path": result.Path,
|
| 348 |
+
"overwritten": result.Overwritten,
|
| 349 |
+
}).Info("pluginstore: plugin installed")
|
| 350 |
+
|
| 351 |
+
c.JSON(http.StatusOK, pluginInstallResponse{
|
| 352 |
+
Status: "installed",
|
| 353 |
+
SourceID: htmlsanitize.String(source.ID),
|
| 354 |
+
SourceName: htmlsanitize.String(source.Name),
|
| 355 |
+
SourceURL: htmlsanitize.String(source.URL),
|
| 356 |
+
ID: htmlsanitize.String(result.ID),
|
| 357 |
+
Version: htmlsanitize.String(result.Version),
|
| 358 |
+
InstallType: htmlsanitize.String(result.InstallType),
|
| 359 |
+
Path: htmlsanitize.String(result.Path),
|
| 360 |
+
PluginsEnabled: pluginsEnabled,
|
| 361 |
+
RestartRequired: restartRequired,
|
| 362 |
+
})
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
func pluginStoreDirectManifest(source pluginstore.Source, plugin pluginstore.Plugin, requestedVersion string) (pluginstore.Manifest, error) {
|
| 366 |
+
version := normalizePluginStoreRequestedVersion(requestedVersion)
|
| 367 |
+
if version == "" {
|
| 368 |
+
version = normalizePluginStoreRequestedVersion(plugin.Version)
|
| 369 |
+
}
|
| 370 |
+
if normalizePluginStoreRequestedVersion(plugin.Version) == version {
|
| 371 |
+
plugin.Version = version
|
| 372 |
+
return pluginstore.ManifestFromPlugin(source, plugin)
|
| 373 |
+
}
|
| 374 |
+
for _, candidate := range plugin.Versions {
|
| 375 |
+
if normalizePluginStoreRequestedVersion(candidate.Version) != version {
|
| 376 |
+
continue
|
| 377 |
+
}
|
| 378 |
+
plugin.Version = version
|
| 379 |
+
plugin.Install = candidate.Install
|
| 380 |
+
if strings.TrimSpace(plugin.Install.Type) == "" {
|
| 381 |
+
plugin.Install.Type = pluginstore.InstallTypeDirect
|
| 382 |
+
}
|
| 383 |
+
return pluginstore.ManifestFromPlugin(source, plugin)
|
| 384 |
+
}
|
| 385 |
+
return pluginstore.Manifest{}, fmt.Errorf("direct plugin version %q not found", version)
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
func installPluginStoreGitHubRelease(ctx context.Context, client pluginstore.Client, plugin pluginstore.Plugin, requestedVersion string, options pluginstore.InstallOptions) (pluginstore.InstallResult, error) {
|
| 389 |
+
version := normalizePluginStoreRequestedVersion(requestedVersion)
|
| 390 |
+
if version == "" {
|
| 391 |
+
return client.Install(ctx, plugin, options)
|
| 392 |
+
}
|
| 393 |
+
tags := pluginStoreReleaseTagCandidates(requestedVersion)
|
| 394 |
+
errs := make([]error, 0, len(tags))
|
| 395 |
+
for _, tag := range tags {
|
| 396 |
+
result, errInstall := client.InstallVersion(ctx, plugin, tag, version, options)
|
| 397 |
+
if errInstall == nil {
|
| 398 |
+
return result, nil
|
| 399 |
+
}
|
| 400 |
+
errs = append(errs, fmt.Errorf("%s: %w", tag, errInstall))
|
| 401 |
+
}
|
| 402 |
+
return pluginstore.InstallResult{}, fmt.Errorf("install release by tag: %w", errors.Join(errs...))
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
func pluginStoreManifestForInstall(source pluginstore.Source, plugin pluginstore.Plugin, result pluginstore.InstallResult) (pluginstore.Manifest, error) {
|
| 406 |
+
installType := strings.TrimSpace(result.InstallType)
|
| 407 |
+
if installType == "" {
|
| 408 |
+
installType = pluginstore.PluginInstallType(plugin)
|
| 409 |
+
}
|
| 410 |
+
switch installType {
|
| 411 |
+
case pluginstore.InstallTypeDirect:
|
| 412 |
+
plugin.Version = strings.TrimSpace(result.Version)
|
| 413 |
+
plugin.Install = pluginstore.NormalizeInstallPlan(plugin.Install)
|
| 414 |
+
return pluginstore.ManifestFromPlugin(source, plugin)
|
| 415 |
+
case pluginstore.InstallTypeGitHubRelease:
|
| 416 |
+
releaseTag := strings.TrimSpace(result.ReleaseTag)
|
| 417 |
+
if releaseTag == "" {
|
| 418 |
+
return pluginstore.Manifest{}, fmt.Errorf("release tag is required")
|
| 419 |
+
}
|
| 420 |
+
return pluginstore.ManifestFromRelease(source, plugin, pluginstore.Release{TagName: releaseTag})
|
| 421 |
+
default:
|
| 422 |
+
return pluginstore.Manifest{}, fmt.Errorf("unsupported install type %q", result.InstallType)
|
| 423 |
+
}
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
func pluginInstallRequestedVersion(c *gin.Context) (string, error) {
|
| 427 |
+
requestedVersion := strings.TrimSpace(c.Query("version"))
|
| 428 |
+
if c == nil || c.Request == nil || c.Request.Body == nil || c.Request.Body == http.NoBody {
|
| 429 |
+
return requestedVersion, nil
|
| 430 |
+
}
|
| 431 |
+
body, errRead := io.ReadAll(c.Request.Body)
|
| 432 |
+
if errRead != nil {
|
| 433 |
+
return "", fmt.Errorf("read install request: %w", errRead)
|
| 434 |
+
}
|
| 435 |
+
if strings.TrimSpace(string(body)) == "" {
|
| 436 |
+
return requestedVersion, nil
|
| 437 |
+
}
|
| 438 |
+
var req pluginInstallRequest
|
| 439 |
+
if errDecode := json.Unmarshal(body, &req); errDecode != nil {
|
| 440 |
+
return "", fmt.Errorf("decode install request: %w", errDecode)
|
| 441 |
+
}
|
| 442 |
+
bodyVersion := strings.TrimSpace(req.Version)
|
| 443 |
+
if requestedVersion == "" {
|
| 444 |
+
return bodyVersion, nil
|
| 445 |
+
}
|
| 446 |
+
if bodyVersion == "" || normalizePluginStoreRequestedVersion(bodyVersion) == normalizePluginStoreRequestedVersion(requestedVersion) {
|
| 447 |
+
return requestedVersion, nil
|
| 448 |
+
}
|
| 449 |
+
return "", fmt.Errorf("version query %q does not match request body version %q", requestedVersion, bodyVersion)
|
| 450 |
+
}
|
| 451 |
+
|
| 452 |
+
func pluginStoreReleaseTagCandidates(version string) []string {
|
| 453 |
+
version = strings.TrimSpace(version)
|
| 454 |
+
if version == "" {
|
| 455 |
+
return nil
|
| 456 |
+
}
|
| 457 |
+
if strings.HasPrefix(strings.ToLower(version), "v") {
|
| 458 |
+
return []string{version, strings.TrimSpace(version[1:])}
|
| 459 |
+
}
|
| 460 |
+
return []string{version, "v" + version}
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
func normalizePluginStoreRequestedVersion(version string) string {
|
| 464 |
+
version = strings.TrimSpace(version)
|
| 465 |
+
if strings.HasPrefix(strings.ToLower(version), "v") {
|
| 466 |
+
return strings.TrimSpace(version[1:])
|
| 467 |
+
}
|
| 468 |
+
return version
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
// enablePluginConfigLocked sets plugins.configs.<id>.enabled and store while
|
| 472 |
+
// preserving the rest of the plugin's raw configuration. Callers must hold h.mu.
|
| 473 |
+
func (h *Handler) enablePluginConfigLocked(id string, storeManifest pluginstore.Manifest) error {
|
| 474 |
+
ensurePluginConfigMap(h.cfg)
|
| 475 |
+
node := pluginConfigNode(h.cfg.Plugins.Configs[id])
|
| 476 |
+
storeNode, errStoreNode := pluginStoreManifestYAMLNode(storeManifest)
|
| 477 |
+
if errStoreNode != nil {
|
| 478 |
+
return errStoreNode
|
| 479 |
+
}
|
| 480 |
+
setYAMLMappingValue(node, "enabled", boolYAMLNode(true))
|
| 481 |
+
setYAMLMappingValue(node, "store", storeNode)
|
| 482 |
+
updated, errConfig := pluginInstanceConfigFromNode(node)
|
| 483 |
+
if errConfig != nil {
|
| 484 |
+
return fmt.Errorf("decode plugin config: %w", errConfig)
|
| 485 |
+
}
|
| 486 |
+
h.cfg.Plugins.Configs[id] = updated
|
| 487 |
+
return nil
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
func pluginStoreManifestYAMLNode(manifest pluginstore.Manifest) (*yaml.Node, error) {
|
| 491 |
+
var node yaml.Node
|
| 492 |
+
if errEncode := node.Encode(manifest); errEncode != nil {
|
| 493 |
+
return nil, fmt.Errorf("encode store manifest: %w", errEncode)
|
| 494 |
+
}
|
| 495 |
+
return &node, nil
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
func (h *Handler) pluginStoreSnapshot() (bool, string, string, []string, []pluginstore.AuthConfig, map[string]config.PluginInstanceConfig, *pluginhost.Host) {
|
| 499 |
+
if h == nil {
|
| 500 |
+
return false, "plugins", "", nil, nil, map[string]config.PluginInstanceConfig{}, nil
|
| 501 |
+
}
|
| 502 |
+
h.mu.Lock()
|
| 503 |
+
defer h.mu.Unlock()
|
| 504 |
+
if h.cfg == nil {
|
| 505 |
+
return false, "plugins", "", nil, nil, map[string]config.PluginInstanceConfig{}, nil
|
| 506 |
+
}
|
| 507 |
+
pluginsEnabled := h.cfg.Plugins.Enabled
|
| 508 |
+
pluginsDir := normalizedPluginsDir(h.cfg.Plugins.Dir)
|
| 509 |
+
proxyURL := strings.TrimSpace(h.cfg.ProxyURL)
|
| 510 |
+
sourceConfigs := append([]string(nil), h.cfg.Plugins.StoreSources...)
|
| 511 |
+
storeAuth := append([]pluginstore.AuthConfig(nil), h.cfg.Plugins.StoreAuth...)
|
| 512 |
+
configs := make(map[string]config.PluginInstanceConfig, len(h.cfg.Plugins.Configs))
|
| 513 |
+
for id, item := range h.cfg.Plugins.Configs {
|
| 514 |
+
configs[id] = item
|
| 515 |
+
}
|
| 516 |
+
return pluginsEnabled, pluginsDir, proxyURL, sourceConfigs, storeAuth, configs, h.pluginHost
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
func (h *Handler) pluginStoreSources(sourceConfigs []string) ([]pluginstore.Source, error) {
|
| 520 |
+
if h != nil && strings.TrimSpace(h.pluginStoreRegistryURL) != "" {
|
| 521 |
+
source := pluginstore.DefaultSource()
|
| 522 |
+
source.URL = strings.TrimSpace(h.pluginStoreRegistryURL)
|
| 523 |
+
return []pluginstore.Source{source}, nil
|
| 524 |
+
}
|
| 525 |
+
return pluginstore.NormalizeSources(sourceConfigs)
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
func (h *Handler) newPluginStoreClient(proxyURL string, registryURL string, storeAuth []pluginstore.AuthConfig) pluginstore.Client {
|
| 529 |
+
registryURL = strings.TrimSpace(registryURL)
|
| 530 |
+
var httpClient pluginstore.HTTPDoer
|
| 531 |
+
if h != nil {
|
| 532 |
+
httpClient = h.pluginStoreHTTPClient
|
| 533 |
+
}
|
| 534 |
+
if registryURL == "" {
|
| 535 |
+
registryURL = pluginstore.DefaultRegistryURL
|
| 536 |
+
}
|
| 537 |
+
if httpClient != nil {
|
| 538 |
+
return pluginstore.Client{HTTPClient: httpClient, RegistryURL: registryURL, Auth: storeAuth}
|
| 539 |
+
}
|
| 540 |
+
client := &http.Client{}
|
| 541 |
+
if strings.TrimSpace(proxyURL) != "" {
|
| 542 |
+
util.SetProxy(&sdkconfig.SDKConfig{ProxyURL: strings.TrimSpace(proxyURL)}, client)
|
| 543 |
+
}
|
| 544 |
+
return pluginstore.Client{HTTPClient: client, RegistryURL: registryURL, Auth: storeAuth}
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
func (h *Handler) fetchSourcedPlugins(ctx context.Context, proxyURL string, storeAuth []pluginstore.AuthConfig, sources []pluginstore.Source) ([]sourcedPlugin, []pluginStoreSourceErr) {
|
| 548 |
+
plugins := make([]sourcedPlugin, 0)
|
| 549 |
+
sourceErrors := make([]pluginStoreSourceErr, 0)
|
| 550 |
+
for _, source := range sources {
|
| 551 |
+
client := h.newPluginStoreClient(proxyURL, source.URL, storeAuth)
|
| 552 |
+
registry, errRegistry := client.FetchRegistry(ctx)
|
| 553 |
+
if errRegistry != nil {
|
| 554 |
+
sourceErrors = append(sourceErrors, pluginStoreSourceErr{
|
| 555 |
+
SourceID: source.ID,
|
| 556 |
+
SourceName: source.Name,
|
| 557 |
+
SourceURL: source.URL,
|
| 558 |
+
Message: errRegistry.Error(),
|
| 559 |
+
})
|
| 560 |
+
continue
|
| 561 |
+
}
|
| 562 |
+
for _, plugin := range registry.Plugins {
|
| 563 |
+
plugins = append(plugins, sourcedPlugin{source: source, plugin: plugin})
|
| 564 |
+
}
|
| 565 |
+
}
|
| 566 |
+
return plugins, sourceErrors
|
| 567 |
+
}
|
| 568 |
+
|
| 569 |
+
func (h *Handler) findPluginStoreInstallTarget(ctx context.Context, proxyURL string, storeAuth []pluginstore.AuthConfig, sources []pluginstore.Source, id string, requestedSourceID string, c *gin.Context) (pluginstore.Source, pluginstore.Plugin, pluginstore.Client, bool) {
|
| 570 |
+
requestedSourceID = strings.TrimSpace(requestedSourceID)
|
| 571 |
+
if requestedSourceID != "" {
|
| 572 |
+
for _, source := range sources {
|
| 573 |
+
if source.ID != requestedSourceID {
|
| 574 |
+
continue
|
| 575 |
+
}
|
| 576 |
+
client := h.newPluginStoreClient(proxyURL, source.URL, storeAuth)
|
| 577 |
+
registry, errRegistry := client.FetchRegistry(ctx)
|
| 578 |
+
if errRegistry != nil {
|
| 579 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "plugin_store_registry_failed", "message": errRegistry.Error()})
|
| 580 |
+
return pluginstore.Source{}, pluginstore.Plugin{}, pluginstore.Client{}, false
|
| 581 |
+
}
|
| 582 |
+
plugin, okPlugin := registry.PluginByID(id)
|
| 583 |
+
if !okPlugin {
|
| 584 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "plugin_not_found", "message": "plugin not found in registry source"})
|
| 585 |
+
return pluginstore.Source{}, pluginstore.Plugin{}, pluginstore.Client{}, false
|
| 586 |
+
}
|
| 587 |
+
return source, plugin, client, true
|
| 588 |
+
}
|
| 589 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "plugin_store_source_not_found", "message": "plugin store source not found"})
|
| 590 |
+
return pluginstore.Source{}, pluginstore.Plugin{}, pluginstore.Client{}, false
|
| 591 |
+
}
|
| 592 |
+
|
| 593 |
+
plugins, sourceErrors := h.fetchSourcedPlugins(ctx, proxyURL, storeAuth, sources)
|
| 594 |
+
matches := make([]sourcedPlugin, 0)
|
| 595 |
+
for _, item := range plugins {
|
| 596 |
+
if item.plugin.ID == id {
|
| 597 |
+
matches = append(matches, item)
|
| 598 |
+
}
|
| 599 |
+
}
|
| 600 |
+
if len(matches) == 0 {
|
| 601 |
+
if len(plugins) == 0 && len(sourceErrors) > 0 {
|
| 602 |
+
c.JSON(http.StatusBadGateway, gin.H{"error": "plugin_store_registry_failed", "message": sourceErrors[0].Message})
|
| 603 |
+
return pluginstore.Source{}, pluginstore.Plugin{}, pluginstore.Client{}, false
|
| 604 |
+
}
|
| 605 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "plugin_not_found", "message": "plugin not found in registry"})
|
| 606 |
+
return pluginstore.Source{}, pluginstore.Plugin{}, pluginstore.Client{}, false
|
| 607 |
+
}
|
| 608 |
+
if len(matches) > 1 {
|
| 609 |
+
c.JSON(http.StatusConflict, gin.H{
|
| 610 |
+
"error": "plugin_store_source_required",
|
| 611 |
+
"message": "multiple plugin store sources contain this plugin id; specify source",
|
| 612 |
+
"sources": sanitizePluginStoreSources(sourcedPluginSources(matches)),
|
| 613 |
+
})
|
| 614 |
+
return pluginstore.Source{}, pluginstore.Plugin{}, pluginstore.Client{}, false
|
| 615 |
+
}
|
| 616 |
+
match := matches[0]
|
| 617 |
+
return match.source, match.plugin, h.newPluginStoreClient(proxyURL, match.source.URL, storeAuth), true
|
| 618 |
+
}
|
| 619 |
+
|
| 620 |
+
func sourcedPluginSources(plugins []sourcedPlugin) []pluginstore.Source {
|
| 621 |
+
sources := make([]pluginstore.Source, 0, len(plugins))
|
| 622 |
+
for _, item := range plugins {
|
| 623 |
+
sources = append(sources, item.source)
|
| 624 |
+
}
|
| 625 |
+
return sources
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
func sanitizePluginStoreSources(sources []pluginstore.Source) []pluginStoreSource {
|
| 629 |
+
out := make([]pluginStoreSource, 0, len(sources))
|
| 630 |
+
for _, source := range sources {
|
| 631 |
+
out = append(out, pluginStoreSource{
|
| 632 |
+
ID: htmlsanitize.String(source.ID),
|
| 633 |
+
Name: htmlsanitize.String(source.Name),
|
| 634 |
+
URL: htmlsanitize.String(source.URL),
|
| 635 |
+
})
|
| 636 |
+
}
|
| 637 |
+
return out
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
func sanitizePluginStoreSourceErrors(sourceErrors []pluginStoreSourceErr) []pluginStoreSourceErr {
|
| 641 |
+
if len(sourceErrors) == 0 {
|
| 642 |
+
return nil
|
| 643 |
+
}
|
| 644 |
+
out := make([]pluginStoreSourceErr, 0, len(sourceErrors))
|
| 645 |
+
for _, sourceError := range sourceErrors {
|
| 646 |
+
out = append(out, pluginStoreSourceErr{
|
| 647 |
+
SourceID: htmlsanitize.String(sourceError.SourceID),
|
| 648 |
+
SourceName: htmlsanitize.String(sourceError.SourceName),
|
| 649 |
+
SourceURL: htmlsanitize.String(sourceError.SourceURL),
|
| 650 |
+
Message: htmlsanitize.String(sourceError.Message),
|
| 651 |
+
})
|
| 652 |
+
}
|
| 653 |
+
return out
|
| 654 |
+
}
|
| 655 |
+
|
| 656 |
+
func sanitizePluginStorePlatforms(platforms []pluginstore.Platform) []pluginStorePlatform {
|
| 657 |
+
if len(platforms) == 0 {
|
| 658 |
+
return nil
|
| 659 |
+
}
|
| 660 |
+
out := make([]pluginStorePlatform, 0, len(platforms))
|
| 661 |
+
for _, platform := range platforms {
|
| 662 |
+
out = append(out, pluginStorePlatform{
|
| 663 |
+
GOOS: htmlsanitize.String(platform.GOOS),
|
| 664 |
+
GOARCH: htmlsanitize.String(platform.GOARCH),
|
| 665 |
+
})
|
| 666 |
+
}
|
| 667 |
+
return out
|
| 668 |
+
}
|
| 669 |
+
|
| 670 |
+
func pluginAuthConfigured(source pluginstore.Source, plugin pluginstore.Plugin, storeAuth []pluginstore.AuthConfig) bool {
|
| 671 |
+
return pluginstore.PluginAuthConfigured(source, plugin, storeAuth)
|
| 672 |
+
}
|
| 673 |
+
|
| 674 |
+
// latestPluginVersions resolves the latest release version of each registry
|
| 675 |
+
// plugin concurrently, returning results positionally aligned with plugins.
|
| 676 |
+
// Unresolved entries are left empty so callers can fall back gracefully.
|
| 677 |
+
func (h *Handler) latestPluginVersions(ctx context.Context, client pluginstore.Client, plugins []pluginstore.Plugin) []string {
|
| 678 |
+
versions := make([]string, len(plugins))
|
| 679 |
+
var wg sync.WaitGroup
|
| 680 |
+
for index := range plugins {
|
| 681 |
+
wg.Add(1)
|
| 682 |
+
go func(index int) {
|
| 683 |
+
defer wg.Done()
|
| 684 |
+
versions[index] = h.latestPluginVersion(ctx, client, plugins[index])
|
| 685 |
+
}(index)
|
| 686 |
+
}
|
| 687 |
+
wg.Wait()
|
| 688 |
+
return versions
|
| 689 |
+
}
|
| 690 |
+
|
| 691 |
+
// latestPluginVersion returns the plugin's latest release version, caching
|
| 692 |
+
// lookups per repository so repeated listings do not exhaust the GitHub API
|
| 693 |
+
// rate limit. Failed lookups are cached for a shorter interval and reported
|
| 694 |
+
// as an empty version.
|
| 695 |
+
func (h *Handler) latestPluginVersion(ctx context.Context, client pluginstore.Client, plugin pluginstore.Plugin) string {
|
| 696 |
+
if pluginstore.PluginInstallType(plugin) != pluginstore.InstallTypeGitHubRelease {
|
| 697 |
+
return ""
|
| 698 |
+
}
|
| 699 |
+
repository := strings.TrimSpace(plugin.Repository)
|
| 700 |
+
if repository == "" {
|
| 701 |
+
return ""
|
| 702 |
+
}
|
| 703 |
+
now := time.Now()
|
| 704 |
+
h.pluginReleaseCacheMu.Lock()
|
| 705 |
+
entry, found := h.pluginReleaseCache[repository]
|
| 706 |
+
h.pluginReleaseCacheMu.Unlock()
|
| 707 |
+
if found && now.Before(entry.expiresAt) {
|
| 708 |
+
return entry.version
|
| 709 |
+
}
|
| 710 |
+
|
| 711 |
+
version := ""
|
| 712 |
+
ttl := pluginReleaseFailureCacheTTL
|
| 713 |
+
release, errRelease := client.FetchLatestRelease(ctx, plugin)
|
| 714 |
+
if errRelease != nil {
|
| 715 |
+
log.WithError(errRelease).WithField("plugin_id", plugin.ID).Warn("pluginstore: failed to fetch latest release")
|
| 716 |
+
} else if latestVersion, errVersion := pluginstore.ReleaseVersion(release); errVersion != nil {
|
| 717 |
+
log.WithError(errVersion).WithField("plugin_id", plugin.ID).Warn("pluginstore: invalid latest release tag")
|
| 718 |
+
} else {
|
| 719 |
+
version = latestVersion
|
| 720 |
+
ttl = pluginReleaseCacheTTL
|
| 721 |
+
}
|
| 722 |
+
|
| 723 |
+
h.pluginReleaseCacheMu.Lock()
|
| 724 |
+
if h.pluginReleaseCache == nil {
|
| 725 |
+
h.pluginReleaseCache = make(map[string]pluginReleaseCacheEntry)
|
| 726 |
+
}
|
| 727 |
+
h.pluginReleaseCache[repository] = pluginReleaseCacheEntry{version: version, expiresAt: now.Add(ttl)}
|
| 728 |
+
h.pluginReleaseCacheMu.Unlock()
|
| 729 |
+
return version
|
| 730 |
+
}
|
| 731 |
+
|
| 732 |
+
func pluginLocalStatuses(pluginsEnabled bool, pluginsDir string, configs map[string]config.PluginInstanceConfig, host *pluginhost.Host) (map[string]pluginLocalStatus, error) {
|
| 733 |
+
statuses := map[string]pluginLocalStatus{}
|
| 734 |
+
files, errDiscover := pluginhost.DiscoverPluginFiles(pluginsDir, pluginStoreDesiredVersions(configs))
|
| 735 |
+
if errDiscover != nil {
|
| 736 |
+
return nil, errDiscover
|
| 737 |
+
}
|
| 738 |
+
for _, file := range files {
|
| 739 |
+
status := statuses[file.ID]
|
| 740 |
+
status.Installed = true
|
| 741 |
+
status.Path = file.Path
|
| 742 |
+
if strings.TrimSpace(file.Version) != "" {
|
| 743 |
+
status.InstalledVersion = strings.TrimSpace(file.Version)
|
| 744 |
+
}
|
| 745 |
+
status.Enabled = true
|
| 746 |
+
statuses[file.ID] = status
|
| 747 |
+
}
|
| 748 |
+
for id, item := range configs {
|
| 749 |
+
status := statuses[id]
|
| 750 |
+
status.Configured = true
|
| 751 |
+
status.Enabled = pluginInstanceEnabled(item)
|
| 752 |
+
status.InstalledSourceID, status.InstalledSourceURL, status.StoreManaged = pluginStoreConfiguredSource(item)
|
| 753 |
+
statuses[id] = status
|
| 754 |
+
}
|
| 755 |
+
if host != nil {
|
| 756 |
+
for _, info := range host.RegisteredPlugins() {
|
| 757 |
+
status := statuses[info.ID]
|
| 758 |
+
status.Installed = true
|
| 759 |
+
status.Registered = true
|
| 760 |
+
status.InstalledVersion = strings.TrimSpace(info.Metadata.Version)
|
| 761 |
+
if _, configured := configs[info.ID]; !configured && !status.Enabled {
|
| 762 |
+
status.Enabled = false
|
| 763 |
+
}
|
| 764 |
+
statuses[info.ID] = status
|
| 765 |
+
}
|
| 766 |
+
}
|
| 767 |
+
for id, status := range statuses {
|
| 768 |
+
status.EffectiveEnabled = pluginsEnabled && status.Enabled && status.Registered
|
| 769 |
+
statuses[id] = status
|
| 770 |
+
}
|
| 771 |
+
return statuses, nil
|
| 772 |
+
}
|
| 773 |
+
|
| 774 |
+
func pluginStoreConfiguredSource(item config.PluginInstanceConfig) (sourceID string, sourceURL string, managed bool) {
|
| 775 |
+
storeNode := pluginStoreConfigNode(item)
|
| 776 |
+
if storeNode == nil {
|
| 777 |
+
return "", "", false
|
| 778 |
+
}
|
| 779 |
+
var manifest pluginstore.Manifest
|
| 780 |
+
if errDecode := storeNode.Decode(&manifest); errDecode != nil {
|
| 781 |
+
return "", "", true
|
| 782 |
+
}
|
| 783 |
+
return strings.TrimSpace(manifest.SourceID), strings.TrimSpace(manifest.SourceURL), true
|
| 784 |
+
}
|
| 785 |
+
|
| 786 |
+
func pluginStoreResolveInstalledSource(status pluginLocalStatus, sources []pluginstore.Source) (string, bool) {
|
| 787 |
+
sourceID := strings.TrimSpace(status.InstalledSourceID)
|
| 788 |
+
sourceURL := strings.TrimSpace(status.InstalledSourceURL)
|
| 789 |
+
if sourceID != "" {
|
| 790 |
+
for _, source := range sources {
|
| 791 |
+
if strings.TrimSpace(source.ID) != sourceID {
|
| 792 |
+
continue
|
| 793 |
+
}
|
| 794 |
+
if sourceURL != "" && strings.TrimSpace(source.URL) != sourceURL {
|
| 795 |
+
return "", false
|
| 796 |
+
}
|
| 797 |
+
return sourceID, true
|
| 798 |
+
}
|
| 799 |
+
return sourceID, true
|
| 800 |
+
}
|
| 801 |
+
if sourceURL == "" {
|
| 802 |
+
return "", false
|
| 803 |
+
}
|
| 804 |
+
for _, source := range sources {
|
| 805 |
+
if strings.TrimSpace(source.URL) == sourceURL {
|
| 806 |
+
return strings.TrimSpace(source.ID), true
|
| 807 |
+
}
|
| 808 |
+
}
|
| 809 |
+
return "", false
|
| 810 |
+
}
|
| 811 |
+
|
| 812 |
+
func pluginStoreInstallSourceStatus(status pluginLocalStatus, sources []pluginstore.Source, entrySourceID string, sourceCount int) (installedSourceID string, sourceStatus string, allowUpdate bool) {
|
| 813 |
+
if !status.Installed && !status.Configured && !status.Registered {
|
| 814 |
+
return "", "", true
|
| 815 |
+
}
|
| 816 |
+
if sourceID, known := pluginStoreResolveInstalledSource(status, sources); known {
|
| 817 |
+
if sourceID == strings.TrimSpace(entrySourceID) {
|
| 818 |
+
return sourceID, "matched", true
|
| 819 |
+
}
|
| 820 |
+
return sourceID, "different", false
|
| 821 |
+
}
|
| 822 |
+
if status.StoreManaged || sourceCount > 1 {
|
| 823 |
+
return "", "unknown", false
|
| 824 |
+
}
|
| 825 |
+
return "", "assumed", true
|
| 826 |
+
}
|
| 827 |
+
|
| 828 |
+
func validatePluginStoreInstallSource(c *gin.Context, configs map[string]config.PluginInstanceConfig, sources []pluginstore.Source, id string, requestedSourceID string) bool {
|
| 829 |
+
item, configured := configs[id]
|
| 830 |
+
if !configured {
|
| 831 |
+
return true
|
| 832 |
+
}
|
| 833 |
+
installedSourceID, installedSourceURL, managed := pluginStoreConfiguredSource(item)
|
| 834 |
+
if !managed {
|
| 835 |
+
return true
|
| 836 |
+
}
|
| 837 |
+
status := pluginLocalStatus{
|
| 838 |
+
StoreManaged: true,
|
| 839 |
+
InstalledSourceID: installedSourceID,
|
| 840 |
+
InstalledSourceURL: installedSourceURL,
|
| 841 |
+
}
|
| 842 |
+
resolvedSourceID, known := pluginStoreResolveInstalledSource(status, sources)
|
| 843 |
+
if !known {
|
| 844 |
+
c.JSON(http.StatusConflict, gin.H{
|
| 845 |
+
"error": "plugin_store_installed_source_unknown",
|
| 846 |
+
"message": "installed plugin source cannot be verified; uninstall it before reinstalling from the store",
|
| 847 |
+
"requested_source_id": strings.TrimSpace(requestedSourceID),
|
| 848 |
+
})
|
| 849 |
+
return false
|
| 850 |
+
}
|
| 851 |
+
if resolvedSourceID != strings.TrimSpace(requestedSourceID) {
|
| 852 |
+
c.JSON(http.StatusConflict, gin.H{
|
| 853 |
+
"error": "plugin_store_source_conflict",
|
| 854 |
+
"message": "installed plugin belongs to a different store source; uninstall it before switching sources",
|
| 855 |
+
"installed_source_id": resolvedSourceID,
|
| 856 |
+
"requested_source_id": strings.TrimSpace(requestedSourceID),
|
| 857 |
+
})
|
| 858 |
+
return false
|
| 859 |
+
}
|
| 860 |
+
return true
|
| 861 |
+
}
|
| 862 |
+
|
| 863 |
+
func pluginStoreDesiredVersions(configs map[string]config.PluginInstanceConfig) map[string]string {
|
| 864 |
+
if len(configs) == 0 {
|
| 865 |
+
return nil
|
| 866 |
+
}
|
| 867 |
+
out := make(map[string]string, len(configs))
|
| 868 |
+
for id, item := range configs {
|
| 869 |
+
id = strings.TrimSpace(id)
|
| 870 |
+
version := pluginStoreDesiredVersion(item)
|
| 871 |
+
if id == "" || version == "" {
|
| 872 |
+
continue
|
| 873 |
+
}
|
| 874 |
+
out[id] = version
|
| 875 |
+
}
|
| 876 |
+
if len(out) == 0 {
|
| 877 |
+
return nil
|
| 878 |
+
}
|
| 879 |
+
return out
|
| 880 |
+
}
|
| 881 |
+
|
| 882 |
+
func pluginStoreDesiredVersion(item config.PluginInstanceConfig) string {
|
| 883 |
+
storeNode := pluginStoreConfigNode(item)
|
| 884 |
+
if storeNode == nil {
|
| 885 |
+
return ""
|
| 886 |
+
}
|
| 887 |
+
if version := pluginStoreNormalizeDesiredVersion(pluginStoreYAMLScalar(yamlMappingValue(storeNode, "version"))); version != "" {
|
| 888 |
+
return version
|
| 889 |
+
}
|
| 890 |
+
return pluginStoreNormalizeDesiredVersion(pluginStoreYAMLScalar(yamlMappingValue(storeNode, "release-tag")))
|
| 891 |
+
}
|
| 892 |
+
|
| 893 |
+
func pluginStoreConfigNode(item config.PluginInstanceConfig) *yaml.Node {
|
| 894 |
+
if item.Raw.Kind != yaml.MappingNode {
|
| 895 |
+
return nil
|
| 896 |
+
}
|
| 897 |
+
return yamlMappingValue(&item.Raw, "store")
|
| 898 |
+
}
|
| 899 |
+
|
| 900 |
+
func yamlMappingValue(node *yaml.Node, key string) *yaml.Node {
|
| 901 |
+
if node == nil || node.Kind != yaml.MappingNode {
|
| 902 |
+
return nil
|
| 903 |
+
}
|
| 904 |
+
for i := 0; i+1 < len(node.Content); i += 2 {
|
| 905 |
+
keyNode := node.Content[i]
|
| 906 |
+
if keyNode == nil || keyNode.Value != key {
|
| 907 |
+
continue
|
| 908 |
+
}
|
| 909 |
+
return node.Content[i+1]
|
| 910 |
+
}
|
| 911 |
+
return nil
|
| 912 |
+
}
|
| 913 |
+
|
| 914 |
+
func pluginStoreYAMLScalar(node *yaml.Node) string {
|
| 915 |
+
if node == nil || node.Kind != yaml.ScalarNode {
|
| 916 |
+
return ""
|
| 917 |
+
}
|
| 918 |
+
return strings.TrimSpace(node.Value)
|
| 919 |
+
}
|
| 920 |
+
|
| 921 |
+
func pluginStoreNormalizeDesiredVersion(version string) string {
|
| 922 |
+
version = strings.TrimSpace(version)
|
| 923 |
+
if len(version) > 1 && (version[0] == 'v' || version[0] == 'V') {
|
| 924 |
+
version = version[1:]
|
| 925 |
+
}
|
| 926 |
+
if version == "" || version[0] < '0' || version[0] > '9' {
|
| 927 |
+
return ""
|
| 928 |
+
}
|
| 929 |
+
return version
|
| 930 |
+
}
|
| 931 |
+
|
| 932 |
+
func pluginBusy(host *pluginhost.Host, id string) bool {
|
| 933 |
+
if host == nil {
|
| 934 |
+
return false
|
| 935 |
+
}
|
| 936 |
+
return host.PluginBusy(id)
|
| 937 |
+
}
|
internal/api/handlers/management/plugin_store_test.go
ADDED
|
@@ -0,0 +1,1436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"archive/zip"
|
| 5 |
+
"bytes"
|
| 6 |
+
"crypto/sha256"
|
| 7 |
+
"encoding/hex"
|
| 8 |
+
"encoding/json"
|
| 9 |
+
"html"
|
| 10 |
+
"io"
|
| 11 |
+
"net/http"
|
| 12 |
+
"net/http/httptest"
|
| 13 |
+
"os"
|
| 14 |
+
"path/filepath"
|
| 15 |
+
"runtime"
|
| 16 |
+
"strings"
|
| 17 |
+
"sync"
|
| 18 |
+
"testing"
|
| 19 |
+
|
| 20 |
+
"github.com/gin-gonic/gin"
|
| 21 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 22 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/pluginstore"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
func TestListPluginStoreMergesInstalledStatus(t *testing.T) {
|
| 26 |
+
t.Parallel()
|
| 27 |
+
|
| 28 |
+
pluginsDir := writeManagementPluginFile(t, "sample-provider")
|
| 29 |
+
h := &Handler{
|
| 30 |
+
cfg: &config.Config{
|
| 31 |
+
Plugins: config.PluginsConfig{
|
| 32 |
+
Enabled: true,
|
| 33 |
+
Dir: pluginsDir,
|
| 34 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 35 |
+
"sample-provider": pluginConfigFromYAML(t, "enabled: true\nmode: fast\n"),
|
| 36 |
+
},
|
| 37 |
+
},
|
| 38 |
+
},
|
| 39 |
+
configFilePath: writeTestConfigFile(t),
|
| 40 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 41 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 42 |
+
"https://registry.example/registry.json": registryJSON(t),
|
| 43 |
+
},
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
rec := httptest.NewRecorder()
|
| 47 |
+
c, _ := gin.CreateTestContext(rec)
|
| 48 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugin-store", nil)
|
| 49 |
+
|
| 50 |
+
h.ListPluginStore(c)
|
| 51 |
+
|
| 52 |
+
if rec.Code != http.StatusOK {
|
| 53 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 54 |
+
}
|
| 55 |
+
var body pluginStoreListResponse
|
| 56 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 57 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 58 |
+
}
|
| 59 |
+
if !body.PluginsEnabled {
|
| 60 |
+
t.Fatal("plugins_enabled = false, want true")
|
| 61 |
+
}
|
| 62 |
+
if len(body.Plugins) != 1 {
|
| 63 |
+
t.Fatalf("plugins len = %d, want 1", len(body.Plugins))
|
| 64 |
+
}
|
| 65 |
+
entry := body.Plugins[0]
|
| 66 |
+
if !entry.Installed || !entry.Configured || !entry.Enabled {
|
| 67 |
+
t.Fatalf("store entry status = %#v, want installed configured enabled", entry)
|
| 68 |
+
}
|
| 69 |
+
if entry.Registered || entry.EffectiveEnabled {
|
| 70 |
+
t.Fatalf("runtime status = registered %v effective %v, want false false", entry.Registered, entry.EffectiveEnabled)
|
| 71 |
+
}
|
| 72 |
+
if entry.InstalledVersion != "" {
|
| 73 |
+
t.Fatalf("installed_version = %q, want empty for unregistered plugin", entry.InstalledVersion)
|
| 74 |
+
}
|
| 75 |
+
if entry.UpdateAvailable {
|
| 76 |
+
t.Fatal("update_available = true, want false when installed version is unknown")
|
| 77 |
+
}
|
| 78 |
+
if entry.Path == "" {
|
| 79 |
+
t.Fatal("path is empty")
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
func TestPluginStoreDirectManifestPinsRequestedVersionArtifacts(t *testing.T) {
|
| 84 |
+
plugin := pluginstore.Plugin{
|
| 85 |
+
ID: "sample", Name: "Sample", Description: "Sample plugin", Author: "tester", Version: "1.0.0",
|
| 86 |
+
Install: pluginstore.InstallPlan{Type: pluginstore.InstallTypeDirect, Artifacts: []pluginstore.Artifact{{
|
| 87 |
+
GOOS: "linux", GOARCH: "amd64", URL: "https://downloads.example/sample-1.0.0.zip",
|
| 88 |
+
SHA256: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", Size: 100,
|
| 89 |
+
}}},
|
| 90 |
+
Versions: []pluginstore.Version{{
|
| 91 |
+
Version: "0.9.0",
|
| 92 |
+
Install: pluginstore.InstallPlan{Type: pluginstore.InstallTypeDirect, Artifacts: []pluginstore.Artifact{{
|
| 93 |
+
GOOS: "linux", GOARCH: "amd64", URL: "https://downloads.example/sample-0.9.0.zip",
|
| 94 |
+
SHA256: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789", Size: 90,
|
| 95 |
+
}}},
|
| 96 |
+
}},
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
manifest, errManifest := pluginStoreDirectManifest(pluginstore.DefaultSource(), plugin, "0.9.0")
|
| 100 |
+
if errManifest != nil {
|
| 101 |
+
t.Fatalf("pluginStoreDirectManifest() error = %v", errManifest)
|
| 102 |
+
}
|
| 103 |
+
if manifest.Version != "0.9.0" || len(manifest.Install.Artifacts) != 1 {
|
| 104 |
+
t.Fatalf("manifest = %#v, want pinned historical version artifact", manifest)
|
| 105 |
+
}
|
| 106 |
+
artifact := manifest.Install.Artifacts[0]
|
| 107 |
+
if artifact.URL != "https://downloads.example/sample-0.9.0.zip" || artifact.Size != 90 {
|
| 108 |
+
t.Fatalf("artifact = %#v, want historical 0.9.0 artifact", artifact)
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
func TestListPluginStoreUsesVersionFromInstalledFilename(t *testing.T) {
|
| 113 |
+
t.Parallel()
|
| 114 |
+
|
| 115 |
+
pluginsDir := t.TempDir()
|
| 116 |
+
archDir := filepath.Join(pluginsDir, runtime.GOOS, runtime.GOARCH)
|
| 117 |
+
if errMkdirAll := os.MkdirAll(archDir, 0o755); errMkdirAll != nil {
|
| 118 |
+
t.Fatalf("MkdirAll(%s) error = %v", archDir, errMkdirAll)
|
| 119 |
+
}
|
| 120 |
+
pluginPath := filepath.Join(archDir, "sample-provider-v0.0.1"+managementPluginExtension(runtime.GOOS))
|
| 121 |
+
if errWriteFile := os.WriteFile(pluginPath, []byte("x"), 0o644); errWriteFile != nil {
|
| 122 |
+
t.Fatalf("WriteFile(%s) error = %v", pluginPath, errWriteFile)
|
| 123 |
+
}
|
| 124 |
+
h := &Handler{
|
| 125 |
+
cfg: &config.Config{
|
| 126 |
+
Plugins: config.PluginsConfig{
|
| 127 |
+
Enabled: true,
|
| 128 |
+
Dir: pluginsDir,
|
| 129 |
+
},
|
| 130 |
+
},
|
| 131 |
+
configFilePath: writeTestConfigFile(t),
|
| 132 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 133 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 134 |
+
"https://registry.example/registry.json": registryJSON(t),
|
| 135 |
+
},
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
rec := httptest.NewRecorder()
|
| 139 |
+
c, _ := gin.CreateTestContext(rec)
|
| 140 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugin-store", nil)
|
| 141 |
+
|
| 142 |
+
h.ListPluginStore(c)
|
| 143 |
+
|
| 144 |
+
if rec.Code != http.StatusOK {
|
| 145 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 146 |
+
}
|
| 147 |
+
var body pluginStoreListResponse
|
| 148 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 149 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 150 |
+
}
|
| 151 |
+
if len(body.Plugins) != 1 {
|
| 152 |
+
t.Fatalf("plugins len = %d, want 1", len(body.Plugins))
|
| 153 |
+
}
|
| 154 |
+
entry := body.Plugins[0]
|
| 155 |
+
if !entry.Installed || entry.InstalledVersion != "0.0.1" {
|
| 156 |
+
t.Fatalf("store entry status = %#v, want installed version 0.0.1", entry)
|
| 157 |
+
}
|
| 158 |
+
if !entry.UpdateAvailable {
|
| 159 |
+
t.Fatalf("update_available = false, want true for installed 0.0.1 and registry 0.1.0")
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
func TestListPluginStoreUsesConfiguredStoreVersionWhenFilesCoexist(t *testing.T) {
|
| 164 |
+
t.Parallel()
|
| 165 |
+
|
| 166 |
+
pluginsDir := t.TempDir()
|
| 167 |
+
archDir := filepath.Join(pluginsDir, runtime.GOOS, runtime.GOARCH)
|
| 168 |
+
if errMkdirAll := os.MkdirAll(archDir, 0o755); errMkdirAll != nil {
|
| 169 |
+
t.Fatalf("MkdirAll(%s) error = %v", archDir, errMkdirAll)
|
| 170 |
+
}
|
| 171 |
+
extension := managementPluginExtension(runtime.GOOS)
|
| 172 |
+
pinnedPath := filepath.Join(archDir, "sample-provider-v0.1.0"+extension)
|
| 173 |
+
newerPath := filepath.Join(archDir, "sample-provider-v0.2.0"+extension)
|
| 174 |
+
for _, path := range []string{pinnedPath, newerPath} {
|
| 175 |
+
if errWriteFile := os.WriteFile(path, []byte("x"), 0o644); errWriteFile != nil {
|
| 176 |
+
t.Fatalf("WriteFile(%s) error = %v", path, errWriteFile)
|
| 177 |
+
}
|
| 178 |
+
}
|
| 179 |
+
h := &Handler{
|
| 180 |
+
cfg: &config.Config{
|
| 181 |
+
Plugins: config.PluginsConfig{
|
| 182 |
+
Enabled: true,
|
| 183 |
+
Dir: pluginsDir,
|
| 184 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 185 |
+
"sample-provider": pluginConfigFromYAML(t, "enabled: true\nstore:\n version: 0.1.0\n release-tag: v0.1.0\n"),
|
| 186 |
+
},
|
| 187 |
+
},
|
| 188 |
+
},
|
| 189 |
+
configFilePath: writeTestConfigFile(t),
|
| 190 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 191 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 192 |
+
"https://registry.example/registry.json": registryJSON(t),
|
| 193 |
+
},
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
rec := httptest.NewRecorder()
|
| 197 |
+
c, _ := gin.CreateTestContext(rec)
|
| 198 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugin-store", nil)
|
| 199 |
+
|
| 200 |
+
h.ListPluginStore(c)
|
| 201 |
+
|
| 202 |
+
if rec.Code != http.StatusOK {
|
| 203 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 204 |
+
}
|
| 205 |
+
var body pluginStoreListResponse
|
| 206 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 207 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 208 |
+
}
|
| 209 |
+
if len(body.Plugins) != 1 {
|
| 210 |
+
t.Fatalf("plugins len = %d, want 1", len(body.Plugins))
|
| 211 |
+
}
|
| 212 |
+
entry := body.Plugins[0]
|
| 213 |
+
if !entry.Installed || entry.InstalledVersion != "0.1.0" || entry.Path != pinnedPath {
|
| 214 |
+
t.Fatalf("store entry status = %#v, want pinned version/path %s", entry, pinnedPath)
|
| 215 |
+
}
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
func TestListPluginStoreEscapesRegistryStrings(t *testing.T) {
|
| 219 |
+
t.Parallel()
|
| 220 |
+
|
| 221 |
+
h := &Handler{
|
| 222 |
+
cfg: &config.Config{
|
| 223 |
+
Plugins: config.PluginsConfig{
|
| 224 |
+
Enabled: true,
|
| 225 |
+
Dir: t.TempDir(),
|
| 226 |
+
},
|
| 227 |
+
},
|
| 228 |
+
configFilePath: writeTestConfigFile(t),
|
| 229 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 230 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 231 |
+
"https://registry.example/registry.json": []byte(`{
|
| 232 |
+
"schema_version": 1,
|
| 233 |
+
"plugins": [{
|
| 234 |
+
"id": "sample-provider",
|
| 235 |
+
"name": "<script>alert(1)</script>",
|
| 236 |
+
"description": "<img src=x onerror=alert(1)>",
|
| 237 |
+
"author": "\"attacker\"",
|
| 238 |
+
"version": "0.1.0",
|
| 239 |
+
"repository": "https://github.com/author-name/cliproxy-sample-provider-plugin",
|
| 240 |
+
"logo": "<svg onload=alert(1)>",
|
| 241 |
+
"homepage": "https://example.com/?q=<x>",
|
| 242 |
+
"license": "<b>MIT</b>",
|
| 243 |
+
"tags": ["<provider>", "safe & sound"]
|
| 244 |
+
}]
|
| 245 |
+
}`),
|
| 246 |
+
},
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
rec := httptest.NewRecorder()
|
| 250 |
+
c, _ := gin.CreateTestContext(rec)
|
| 251 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugin-store", nil)
|
| 252 |
+
|
| 253 |
+
h.ListPluginStore(c)
|
| 254 |
+
|
| 255 |
+
if rec.Code != http.StatusOK {
|
| 256 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 257 |
+
}
|
| 258 |
+
var body pluginStoreListResponse
|
| 259 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 260 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 261 |
+
}
|
| 262 |
+
if len(body.Plugins) != 1 {
|
| 263 |
+
t.Fatalf("plugins len = %d, want 1", len(body.Plugins))
|
| 264 |
+
}
|
| 265 |
+
entry := body.Plugins[0]
|
| 266 |
+
if entry.Name != html.EscapeString("<script>alert(1)</script>") ||
|
| 267 |
+
entry.Description != html.EscapeString("<img src=x onerror=alert(1)>") ||
|
| 268 |
+
entry.Author != html.EscapeString(`"attacker"`) ||
|
| 269 |
+
entry.Version != "0.1.0" ||
|
| 270 |
+
entry.Repository != "https://github.com/author-name/cliproxy-sample-provider-plugin" ||
|
| 271 |
+
entry.Logo != html.EscapeString("<svg onload=alert(1)>") ||
|
| 272 |
+
entry.Homepage != html.EscapeString("https://example.com/?q=<x>") ||
|
| 273 |
+
entry.License != html.EscapeString("<b>MIT</b>") {
|
| 274 |
+
t.Fatalf("store entry = %#v, want escaped strings", entry)
|
| 275 |
+
}
|
| 276 |
+
if len(entry.Tags) != 2 ||
|
| 277 |
+
entry.Tags[0] != html.EscapeString("<provider>") ||
|
| 278 |
+
entry.Tags[1] != html.EscapeString("safe & sound") {
|
| 279 |
+
t.Fatalf("tags = %#v, want escaped strings", entry.Tags)
|
| 280 |
+
}
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
func TestListPluginStoreShowsLatestReleaseVersionAndCaches(t *testing.T) {
|
| 284 |
+
t.Parallel()
|
| 285 |
+
|
| 286 |
+
httpClient := &countingPluginStoreHTTPClient{responses: fakePluginStoreHTTPClient{
|
| 287 |
+
"https://registry.example/registry.json": registryJSON(t),
|
| 288 |
+
"https://api.github.com/repos/author-name/cliproxy-sample-provider-plugin/releases/latest": []byte(`{
|
| 289 |
+
"tag_name": "v0.2.0",
|
| 290 |
+
"assets": []
|
| 291 |
+
}`),
|
| 292 |
+
}}
|
| 293 |
+
h := &Handler{
|
| 294 |
+
cfg: &config.Config{
|
| 295 |
+
Plugins: config.PluginsConfig{
|
| 296 |
+
Enabled: true,
|
| 297 |
+
Dir: t.TempDir(),
|
| 298 |
+
},
|
| 299 |
+
},
|
| 300 |
+
configFilePath: writeTestConfigFile(t),
|
| 301 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 302 |
+
pluginStoreHTTPClient: httpClient,
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
listOnce := func() pluginStoreListResponse {
|
| 306 |
+
rec := httptest.NewRecorder()
|
| 307 |
+
c, _ := gin.CreateTestContext(rec)
|
| 308 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugin-store", nil)
|
| 309 |
+
h.ListPluginStore(c)
|
| 310 |
+
if rec.Code != http.StatusOK {
|
| 311 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 312 |
+
}
|
| 313 |
+
var body pluginStoreListResponse
|
| 314 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 315 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 316 |
+
}
|
| 317 |
+
return body
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
for call := 0; call < 2; call++ {
|
| 321 |
+
body := listOnce()
|
| 322 |
+
if len(body.Plugins) != 1 {
|
| 323 |
+
t.Fatalf("plugins len = %d, want 1", len(body.Plugins))
|
| 324 |
+
}
|
| 325 |
+
if body.Plugins[0].Version != "0.2.0" {
|
| 326 |
+
t.Fatalf("version = %q, want 0.2.0 from latest release tag", body.Plugins[0].Version)
|
| 327 |
+
}
|
| 328 |
+
}
|
| 329 |
+
releaseCalls := httpClient.count("https://api.github.com/repos/author-name/cliproxy-sample-provider-plugin/releases/latest")
|
| 330 |
+
if releaseCalls != 1 {
|
| 331 |
+
t.Fatalf("latest release fetched %d times, want 1 (cached)", releaseCalls)
|
| 332 |
+
}
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
func TestListPluginStoreFallsBackToRegistryVersion(t *testing.T) {
|
| 336 |
+
t.Parallel()
|
| 337 |
+
|
| 338 |
+
h := &Handler{
|
| 339 |
+
cfg: &config.Config{
|
| 340 |
+
Plugins: config.PluginsConfig{
|
| 341 |
+
Enabled: true,
|
| 342 |
+
Dir: t.TempDir(),
|
| 343 |
+
},
|
| 344 |
+
},
|
| 345 |
+
configFilePath: writeTestConfigFile(t),
|
| 346 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 347 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 348 |
+
"https://registry.example/registry.json": registryJSON(t),
|
| 349 |
+
},
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
rec := httptest.NewRecorder()
|
| 353 |
+
c, _ := gin.CreateTestContext(rec)
|
| 354 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugin-store", nil)
|
| 355 |
+
|
| 356 |
+
h.ListPluginStore(c)
|
| 357 |
+
|
| 358 |
+
if rec.Code != http.StatusOK {
|
| 359 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 360 |
+
}
|
| 361 |
+
var body pluginStoreListResponse
|
| 362 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 363 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 364 |
+
}
|
| 365 |
+
if len(body.Plugins) != 1 {
|
| 366 |
+
t.Fatalf("plugins len = %d, want 1", len(body.Plugins))
|
| 367 |
+
}
|
| 368 |
+
if body.Plugins[0].Version != "0.1.0" {
|
| 369 |
+
t.Fatalf("version = %q, want registry fallback 0.1.0", body.Plugins[0].Version)
|
| 370 |
+
}
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
func TestListPluginStoreIncludesThirdPartySources(t *testing.T) {
|
| 374 |
+
t.Parallel()
|
| 375 |
+
|
| 376 |
+
h := &Handler{
|
| 377 |
+
cfg: &config.Config{
|
| 378 |
+
Plugins: config.PluginsConfig{
|
| 379 |
+
Enabled: true,
|
| 380 |
+
Dir: t.TempDir(),
|
| 381 |
+
StoreSources: []string{"https://community.example/registry.json"},
|
| 382 |
+
},
|
| 383 |
+
},
|
| 384 |
+
configFilePath: writeTestConfigFile(t),
|
| 385 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 386 |
+
pluginstore.DefaultRegistryURL: registryJSON(t),
|
| 387 |
+
"https://community.example/registry.json": []byte(`{
|
| 388 |
+
"schema_version": 1,
|
| 389 |
+
"plugins": [{
|
| 390 |
+
"id": "third-provider",
|
| 391 |
+
"name": "Third Provider",
|
| 392 |
+
"description": "Adds third-party provider support.",
|
| 393 |
+
"author": "community",
|
| 394 |
+
"version": "0.3.0",
|
| 395 |
+
"repository": "https://github.com/community/cliproxy-third-provider-plugin"
|
| 396 |
+
}]
|
| 397 |
+
}`),
|
| 398 |
+
},
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
rec := httptest.NewRecorder()
|
| 402 |
+
c, _ := gin.CreateTestContext(rec)
|
| 403 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugin-store", nil)
|
| 404 |
+
|
| 405 |
+
h.ListPluginStore(c)
|
| 406 |
+
|
| 407 |
+
if rec.Code != http.StatusOK {
|
| 408 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 409 |
+
}
|
| 410 |
+
var body pluginStoreListResponse
|
| 411 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 412 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 413 |
+
}
|
| 414 |
+
if len(body.Sources) != 2 {
|
| 415 |
+
t.Fatalf("sources len = %d, want 2: %#v", len(body.Sources), body.Sources)
|
| 416 |
+
}
|
| 417 |
+
if len(body.Plugins) != 2 {
|
| 418 |
+
t.Fatalf("plugins len = %d, want 2: %#v", len(body.Plugins), body.Plugins)
|
| 419 |
+
}
|
| 420 |
+
byID := map[string]pluginStoreListEntry{}
|
| 421 |
+
for _, entry := range body.Plugins {
|
| 422 |
+
byID[entry.ID] = entry
|
| 423 |
+
}
|
| 424 |
+
if byID["sample-provider"].SourceID != pluginstore.DefaultSourceID {
|
| 425 |
+
t.Fatalf("official source id = %q, want %q", byID["sample-provider"].SourceID, pluginstore.DefaultSourceID)
|
| 426 |
+
}
|
| 427 |
+
third := byID["third-provider"]
|
| 428 |
+
communitySourceID := pluginstore.SourceID("https://community.example/registry.json")
|
| 429 |
+
if third.StoreID != communitySourceID+"/third-provider" || third.SourceID != communitySourceID || third.SourceName != "community.example" || third.SourceURL != "https://community.example/registry.json" {
|
| 430 |
+
t.Fatalf("third-party source fields = %#v", third)
|
| 431 |
+
}
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
func TestListPluginStoreMatchesInstalledStatusToManifestSource(t *testing.T) {
|
| 435 |
+
t.Parallel()
|
| 436 |
+
|
| 437 |
+
pluginsDir := t.TempDir()
|
| 438 |
+
archDir := filepath.Join(pluginsDir, runtime.GOOS, runtime.GOARCH)
|
| 439 |
+
if errMkdirAll := os.MkdirAll(archDir, 0o755); errMkdirAll != nil {
|
| 440 |
+
t.Fatalf("MkdirAll(%s) error = %v", archDir, errMkdirAll)
|
| 441 |
+
}
|
| 442 |
+
pluginPath := filepath.Join(archDir, "sample-provider-v0.0.1"+managementPluginExtension(runtime.GOOS))
|
| 443 |
+
if errWriteFile := os.WriteFile(pluginPath, []byte("x"), 0o644); errWriteFile != nil {
|
| 444 |
+
t.Fatalf("WriteFile(%s) error = %v", pluginPath, errWriteFile)
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
communityURL := "https://community.example/registry.json"
|
| 448 |
+
h := &Handler{
|
| 449 |
+
cfg: &config.Config{
|
| 450 |
+
Plugins: config.PluginsConfig{
|
| 451 |
+
Enabled: true,
|
| 452 |
+
Dir: pluginsDir,
|
| 453 |
+
StoreSources: []string{communityURL},
|
| 454 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 455 |
+
"sample-provider": pluginConfigWithStoreSource(t, pluginstore.DefaultSourceID, pluginstore.DefaultRegistryURL),
|
| 456 |
+
},
|
| 457 |
+
},
|
| 458 |
+
},
|
| 459 |
+
configFilePath: writeTestConfigFile(t),
|
| 460 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 461 |
+
pluginstore.DefaultRegistryURL: registryJSON(t),
|
| 462 |
+
communityURL: thirdPartySampleRegistryJSON(t),
|
| 463 |
+
},
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
rec := httptest.NewRecorder()
|
| 467 |
+
c, _ := gin.CreateTestContext(rec)
|
| 468 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugin-store", nil)
|
| 469 |
+
h.ListPluginStore(c)
|
| 470 |
+
|
| 471 |
+
if rec.Code != http.StatusOK {
|
| 472 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 473 |
+
}
|
| 474 |
+
var body struct {
|
| 475 |
+
Plugins []struct {
|
| 476 |
+
SourceID string `json:"source_id"`
|
| 477 |
+
InstalledSourceID string `json:"installed_source_id"`
|
| 478 |
+
InstallSourceStatus string `json:"install_source_status"`
|
| 479 |
+
UpdateAvailable bool `json:"update_available"`
|
| 480 |
+
} `json:"plugins"`
|
| 481 |
+
}
|
| 482 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 483 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 484 |
+
}
|
| 485 |
+
if len(body.Plugins) != 2 {
|
| 486 |
+
t.Fatalf("plugins len = %d, want 2", len(body.Plugins))
|
| 487 |
+
}
|
| 488 |
+
entries := make(map[string]struct {
|
| 489 |
+
InstalledSourceID string
|
| 490 |
+
InstallSourceStatus string
|
| 491 |
+
UpdateAvailable bool
|
| 492 |
+
}, len(body.Plugins))
|
| 493 |
+
for _, entry := range body.Plugins {
|
| 494 |
+
entries[entry.SourceID] = struct {
|
| 495 |
+
InstalledSourceID string
|
| 496 |
+
InstallSourceStatus string
|
| 497 |
+
UpdateAvailable bool
|
| 498 |
+
}{entry.InstalledSourceID, entry.InstallSourceStatus, entry.UpdateAvailable}
|
| 499 |
+
}
|
| 500 |
+
official := entries[pluginstore.DefaultSourceID]
|
| 501 |
+
if official.InstalledSourceID != pluginstore.DefaultSourceID || official.InstallSourceStatus != "matched" || !official.UpdateAvailable {
|
| 502 |
+
t.Fatalf("official entry = %#v, want matched update", official)
|
| 503 |
+
}
|
| 504 |
+
communitySourceID := pluginstore.SourceID(communityURL)
|
| 505 |
+
community := entries[communitySourceID]
|
| 506 |
+
if community.InstalledSourceID != pluginstore.DefaultSourceID || community.InstallSourceStatus != "different" || community.UpdateAvailable {
|
| 507 |
+
t.Fatalf("community entry = %#v, want different source without update", community)
|
| 508 |
+
}
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
func TestInstallPluginFromStoreRejectsImplicitSourceSwitch(t *testing.T) {
|
| 512 |
+
t.Parallel()
|
| 513 |
+
|
| 514 |
+
communityURL := "https://community.example/registry.json"
|
| 515 |
+
h := &Handler{
|
| 516 |
+
cfg: &config.Config{
|
| 517 |
+
Plugins: config.PluginsConfig{
|
| 518 |
+
Enabled: true,
|
| 519 |
+
Dir: writeManagementPluginFile(t, "sample-provider"),
|
| 520 |
+
StoreSources: []string{communityURL},
|
| 521 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 522 |
+
"sample-provider": pluginConfigWithStoreSource(t, pluginstore.DefaultSourceID, pluginstore.DefaultRegistryURL),
|
| 523 |
+
},
|
| 524 |
+
},
|
| 525 |
+
},
|
| 526 |
+
configFilePath: writeTestConfigFile(t),
|
| 527 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 528 |
+
pluginstore.DefaultRegistryURL: registryJSON(t),
|
| 529 |
+
communityURL: thirdPartySampleRegistryJSON(t),
|
| 530 |
+
},
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
rec := httptest.NewRecorder()
|
| 534 |
+
c, _ := gin.CreateTestContext(rec)
|
| 535 |
+
c.Params = gin.Params{{Key: "id", Value: "sample-provider"}}
|
| 536 |
+
communitySourceID := pluginstore.SourceID(communityURL)
|
| 537 |
+
c.Request = httptest.NewRequest(http.MethodPost, "/v0/management/plugin-store/sample-provider/install?source="+communitySourceID, nil)
|
| 538 |
+
h.InstallPluginFromStore(c)
|
| 539 |
+
|
| 540 |
+
if rec.Code != http.StatusConflict {
|
| 541 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusConflict, rec.Body.String())
|
| 542 |
+
}
|
| 543 |
+
if !strings.Contains(rec.Body.String(), "plugin_store_source_conflict") || !strings.Contains(rec.Body.String(), pluginstore.DefaultSourceID) {
|
| 544 |
+
t.Fatalf("body = %s, want source conflict with installed source", rec.Body.String())
|
| 545 |
+
}
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
+
func TestInstallPluginFromStoreRejectsUnknownManagedSource(t *testing.T) {
|
| 549 |
+
t.Parallel()
|
| 550 |
+
|
| 551 |
+
h := &Handler{
|
| 552 |
+
cfg: &config.Config{
|
| 553 |
+
Plugins: config.PluginsConfig{
|
| 554 |
+
Enabled: true,
|
| 555 |
+
Dir: writeManagementPluginFile(t, "sample-provider"),
|
| 556 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 557 |
+
"sample-provider": pluginConfigWithStoreSource(t, "", ""),
|
| 558 |
+
},
|
| 559 |
+
},
|
| 560 |
+
},
|
| 561 |
+
configFilePath: writeTestConfigFile(t),
|
| 562 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 563 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 564 |
+
"https://registry.example/registry.json": registryJSON(t),
|
| 565 |
+
},
|
| 566 |
+
}
|
| 567 |
+
|
| 568 |
+
rec := httptest.NewRecorder()
|
| 569 |
+
c, _ := gin.CreateTestContext(rec)
|
| 570 |
+
c.Params = gin.Params{{Key: "id", Value: "sample-provider"}}
|
| 571 |
+
c.Request = httptest.NewRequest(http.MethodPost, "/v0/management/plugin-store/sample-provider/install", nil)
|
| 572 |
+
h.InstallPluginFromStore(c)
|
| 573 |
+
|
| 574 |
+
if rec.Code != http.StatusConflict {
|
| 575 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusConflict, rec.Body.String())
|
| 576 |
+
}
|
| 577 |
+
if !strings.Contains(rec.Body.String(), "plugin_store_installed_source_unknown") {
|
| 578 |
+
t.Fatalf("body = %s, want unknown installed source error", rec.Body.String())
|
| 579 |
+
}
|
| 580 |
+
}
|
| 581 |
+
|
| 582 |
+
func TestListPluginStoreIncludesDirectMetadataAndAuth(t *testing.T) {
|
| 583 |
+
t.Setenv("PLUGIN_STORE_TOKEN", "secret-token")
|
| 584 |
+
|
| 585 |
+
h := &Handler{
|
| 586 |
+
cfg: &config.Config{
|
| 587 |
+
Plugins: config.PluginsConfig{
|
| 588 |
+
Enabled: true,
|
| 589 |
+
Dir: t.TempDir(),
|
| 590 |
+
StoreAuth: []pluginstore.AuthConfig{{
|
| 591 |
+
Match: "https://registry.example/",
|
| 592 |
+
ApplyTo: []string{pluginstore.RequestKindRegistry},
|
| 593 |
+
Type: pluginstore.AuthTypeBearer,
|
| 594 |
+
TokenEnv: "PLUGIN_STORE_TOKEN",
|
| 595 |
+
}},
|
| 596 |
+
},
|
| 597 |
+
},
|
| 598 |
+
configFilePath: writeTestConfigFile(t),
|
| 599 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 600 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 601 |
+
"https://registry.example/registry.json": directRegistryJSON("https://downloads.example/sample-provider.zip", "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"),
|
| 602 |
+
},
|
| 603 |
+
}
|
| 604 |
+
|
| 605 |
+
rec := httptest.NewRecorder()
|
| 606 |
+
c, _ := gin.CreateTestContext(rec)
|
| 607 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugin-store", nil)
|
| 608 |
+
|
| 609 |
+
h.ListPluginStore(c)
|
| 610 |
+
|
| 611 |
+
if rec.Code != http.StatusOK {
|
| 612 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 613 |
+
}
|
| 614 |
+
var body pluginStoreListResponse
|
| 615 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 616 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 617 |
+
}
|
| 618 |
+
if len(body.Plugins) != 1 {
|
| 619 |
+
t.Fatalf("plugins len = %d, want 1", len(body.Plugins))
|
| 620 |
+
}
|
| 621 |
+
entry := body.Plugins[0]
|
| 622 |
+
if entry.InstallType != pluginstore.InstallTypeDirect || !entry.AuthRequired || !entry.AuthConfigured {
|
| 623 |
+
t.Fatalf("direct metadata = %#v, want direct auth metadata", entry)
|
| 624 |
+
}
|
| 625 |
+
if !pluginStorePlatformsContain(entry.Platforms, "linux", "amd64") {
|
| 626 |
+
t.Fatalf("platforms = %#v, want linux/amd64", entry.Platforms)
|
| 627 |
+
}
|
| 628 |
+
}
|
| 629 |
+
|
| 630 |
+
func TestListPluginStoreReportsVersionArtifactAuth(t *testing.T) {
|
| 631 |
+
t.Setenv("PLUGIN_STORE_TOKEN", "secret-token")
|
| 632 |
+
|
| 633 |
+
h := &Handler{
|
| 634 |
+
cfg: &config.Config{
|
| 635 |
+
Plugins: config.PluginsConfig{
|
| 636 |
+
Enabled: true,
|
| 637 |
+
Dir: t.TempDir(),
|
| 638 |
+
StoreAuth: []pluginstore.AuthConfig{{
|
| 639 |
+
Match: "https://versioned.example/",
|
| 640 |
+
ApplyTo: []string{pluginstore.RequestKindArtifact},
|
| 641 |
+
Type: pluginstore.AuthTypeBearer,
|
| 642 |
+
TokenEnv: "PLUGIN_STORE_TOKEN",
|
| 643 |
+
}},
|
| 644 |
+
},
|
| 645 |
+
},
|
| 646 |
+
configFilePath: writeTestConfigFile(t),
|
| 647 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 648 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 649 |
+
"https://registry.example/registry.json": directRegistryJSONWithVersionArtifact(
|
| 650 |
+
"https://downloads.example/sample-provider.zip",
|
| 651 |
+
"https://versioned.example/sample-provider-0.3.0.zip",
|
| 652 |
+
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
| 653 |
+
),
|
| 654 |
+
},
|
| 655 |
+
}
|
| 656 |
+
|
| 657 |
+
rec := httptest.NewRecorder()
|
| 658 |
+
c, _ := gin.CreateTestContext(rec)
|
| 659 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugin-store", nil)
|
| 660 |
+
|
| 661 |
+
h.ListPluginStore(c)
|
| 662 |
+
|
| 663 |
+
if rec.Code != http.StatusOK {
|
| 664 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 665 |
+
}
|
| 666 |
+
var body pluginStoreListResponse
|
| 667 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 668 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 669 |
+
}
|
| 670 |
+
if len(body.Plugins) != 1 {
|
| 671 |
+
t.Fatalf("plugins len = %d, want 1", len(body.Plugins))
|
| 672 |
+
}
|
| 673 |
+
if !body.Plugins[0].AuthConfigured {
|
| 674 |
+
t.Fatalf("auth_configured = false, want true for version artifact auth")
|
| 675 |
+
}
|
| 676 |
+
}
|
| 677 |
+
|
| 678 |
+
func TestListPluginStoreReportsGitHubMetadataAuth(t *testing.T) {
|
| 679 |
+
t.Setenv("PLUGIN_STORE_TOKEN", "secret-token")
|
| 680 |
+
|
| 681 |
+
h := &Handler{
|
| 682 |
+
cfg: &config.Config{
|
| 683 |
+
Plugins: config.PluginsConfig{
|
| 684 |
+
Enabled: true,
|
| 685 |
+
Dir: t.TempDir(),
|
| 686 |
+
StoreAuth: []pluginstore.AuthConfig{{
|
| 687 |
+
Match: "https://api.github.com/repos/author-name/cliproxy-sample-provider-plugin/releases/",
|
| 688 |
+
ApplyTo: []string{pluginstore.RequestKindMetadata},
|
| 689 |
+
Type: pluginstore.AuthTypeBearer,
|
| 690 |
+
TokenEnv: "PLUGIN_STORE_TOKEN",
|
| 691 |
+
}},
|
| 692 |
+
},
|
| 693 |
+
},
|
| 694 |
+
configFilePath: writeTestConfigFile(t),
|
| 695 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 696 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 697 |
+
"https://registry.example/registry.json": registryJSON(t),
|
| 698 |
+
},
|
| 699 |
+
}
|
| 700 |
+
|
| 701 |
+
rec := httptest.NewRecorder()
|
| 702 |
+
c, _ := gin.CreateTestContext(rec)
|
| 703 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugin-store", nil)
|
| 704 |
+
|
| 705 |
+
h.ListPluginStore(c)
|
| 706 |
+
|
| 707 |
+
if rec.Code != http.StatusOK {
|
| 708 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 709 |
+
}
|
| 710 |
+
var body pluginStoreListResponse
|
| 711 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 712 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 713 |
+
}
|
| 714 |
+
if len(body.Plugins) != 1 {
|
| 715 |
+
t.Fatalf("plugins len = %d, want 1", len(body.Plugins))
|
| 716 |
+
}
|
| 717 |
+
if !body.Plugins[0].AuthConfigured {
|
| 718 |
+
t.Fatalf("auth_configured = false, want true for GitHub metadata auth")
|
| 719 |
+
}
|
| 720 |
+
}
|
| 721 |
+
|
| 722 |
+
func TestInstallPluginFromStoreRejectsUnresolvedPluginsDir(t *testing.T) {
|
| 723 |
+
workspace := t.TempDir()
|
| 724 |
+
t.Setenv("HOME", "")
|
| 725 |
+
t.Setenv("USERPROFILE", "")
|
| 726 |
+
t.Chdir(workspace)
|
| 727 |
+
|
| 728 |
+
h := &Handler{
|
| 729 |
+
cfg: &config.Config{
|
| 730 |
+
Plugins: config.PluginsConfig{
|
| 731 |
+
Dir: "~/.cli-proxy-api/plugins",
|
| 732 |
+
Configs: map[string]config.PluginInstanceConfig{},
|
| 733 |
+
},
|
| 734 |
+
},
|
| 735 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 736 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{},
|
| 737 |
+
}
|
| 738 |
+
rec := httptest.NewRecorder()
|
| 739 |
+
c, _ := gin.CreateTestContext(rec)
|
| 740 |
+
c.Params = gin.Params{{Key: "id", Value: "sample-provider"}}
|
| 741 |
+
c.Request = httptest.NewRequest(http.MethodPost, "/v0/management/plugin-store/sample-provider/install", nil)
|
| 742 |
+
|
| 743 |
+
h.InstallPluginFromStore(c)
|
| 744 |
+
|
| 745 |
+
if rec.Code != http.StatusInternalServerError {
|
| 746 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusInternalServerError, rec.Body.String())
|
| 747 |
+
}
|
| 748 |
+
var body map[string]any
|
| 749 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 750 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 751 |
+
}
|
| 752 |
+
if body["error"] != "plugin_directory_invalid" {
|
| 753 |
+
t.Fatalf("error = %#v, want plugin_directory_invalid", body["error"])
|
| 754 |
+
}
|
| 755 |
+
if _, errStat := os.Stat(filepath.Join(workspace, "~")); !os.IsNotExist(errStat) {
|
| 756 |
+
t.Fatalf("literal tilde directory stat error = %v, want not exist", errStat)
|
| 757 |
+
}
|
| 758 |
+
}
|
| 759 |
+
|
| 760 |
+
func TestInstallPluginFromStoreWritesFileAndEnablesConfig(t *testing.T) {
|
| 761 |
+
workspace := t.TempDir()
|
| 762 |
+
homeDir := filepath.Join(workspace, "home")
|
| 763 |
+
if errMkdir := os.MkdirAll(homeDir, 0o755); errMkdir != nil {
|
| 764 |
+
t.Fatalf("MkdirAll(%s) error = %v", homeDir, errMkdir)
|
| 765 |
+
}
|
| 766 |
+
t.Setenv("HOME", homeDir)
|
| 767 |
+
t.Setenv("USERPROFILE", homeDir)
|
| 768 |
+
t.Chdir(workspace)
|
| 769 |
+
|
| 770 |
+
cfg, errParse := config.ParseConfigBytes([]byte(`
|
| 771 |
+
plugins:
|
| 772 |
+
enabled: false
|
| 773 |
+
dir: "~/.cli-proxy-api/plugins"
|
| 774 |
+
`))
|
| 775 |
+
if errParse != nil {
|
| 776 |
+
t.Fatalf("ParseConfigBytes() error = %v", errParse)
|
| 777 |
+
}
|
| 778 |
+
cfg.Plugins.Configs["sample-provider"] = pluginConfigFromYAML(t, "enabled: false\nmode: fast\n")
|
| 779 |
+
pluginsDir := filepath.Join(homeDir, ".cli-proxy-api", "plugins")
|
| 780 |
+
archiveData := makeManagementPluginStoreZip(t, "sample-provider"+managementPluginExtension(runtime.GOOS), "library-data")
|
| 781 |
+
archiveName := "sample-provider_0.1.0_" + runtime.GOOS + "_" + runtime.GOARCH + ".zip"
|
| 782 |
+
checksum := sha256.Sum256(archiveData)
|
| 783 |
+
h := &Handler{
|
| 784 |
+
cfg: cfg,
|
| 785 |
+
configFilePath: writeTestConfigFile(t),
|
| 786 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 787 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 788 |
+
"https://registry.example/registry.json": registryJSON(t),
|
| 789 |
+
"https://api.github.com/repos/author-name/cliproxy-sample-provider-plugin/releases/latest": []byte(`{
|
| 790 |
+
"tag_name": "v0.1.0",
|
| 791 |
+
"assets": [
|
| 792 |
+
{"name": "` + archiveName + `", "browser_download_url": "https://downloads.example/` + archiveName + `"},
|
| 793 |
+
{"name": "checksums.txt", "browser_download_url": "https://downloads.example/checksums.txt"}
|
| 794 |
+
]
|
| 795 |
+
}`),
|
| 796 |
+
"https://downloads.example/" + archiveName: archiveData,
|
| 797 |
+
"https://downloads.example/checksums.txt": []byte(hex.EncodeToString(checksum[:]) + " " + archiveName + "\n"),
|
| 798 |
+
},
|
| 799 |
+
}
|
| 800 |
+
reloads, reloadDone := captureConfigReload(h)
|
| 801 |
+
|
| 802 |
+
rec := httptest.NewRecorder()
|
| 803 |
+
c, _ := gin.CreateTestContext(rec)
|
| 804 |
+
c.Params = gin.Params{{Key: "id", Value: "sample-provider"}}
|
| 805 |
+
c.Request = httptest.NewRequest(http.MethodPost, "/v0/management/plugin-store/sample-provider/install", nil)
|
| 806 |
+
|
| 807 |
+
h.InstallPluginFromStore(c)
|
| 808 |
+
|
| 809 |
+
if rec.Code != http.StatusOK {
|
| 810 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 811 |
+
}
|
| 812 |
+
cfgSnapshot := waitForAsyncReload(t, reloads)
|
| 813 |
+
waitForReloadDone(t, reloadDone)
|
| 814 |
+
if cfgSnapshot == h.cfg {
|
| 815 |
+
t.Fatalf("reload config = handler config %p, want independent snapshot", h.cfg)
|
| 816 |
+
}
|
| 817 |
+
var body pluginInstallResponse
|
| 818 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 819 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 820 |
+
}
|
| 821 |
+
if body.Status != "installed" || body.ID != "sample-provider" || body.Version != "0.1.0" {
|
| 822 |
+
t.Fatalf("install response = %#v", body)
|
| 823 |
+
}
|
| 824 |
+
if body.PluginsEnabled {
|
| 825 |
+
t.Fatal("plugins_enabled = true, want false")
|
| 826 |
+
}
|
| 827 |
+
if body.RestartRequired {
|
| 828 |
+
t.Fatal("restart_required = true, want false")
|
| 829 |
+
}
|
| 830 |
+
targetPath := filepath.Join(pluginsDir, runtime.GOOS, runtime.GOARCH, "sample-provider-v0.1.0"+managementPluginExtension(runtime.GOOS))
|
| 831 |
+
data, errRead := os.ReadFile(targetPath)
|
| 832 |
+
if errRead != nil {
|
| 833 |
+
t.Fatalf("ReadFile(%s) error = %v", targetPath, errRead)
|
| 834 |
+
}
|
| 835 |
+
if string(data) != "library-data" {
|
| 836 |
+
t.Fatalf("installed file = %q, want library-data", data)
|
| 837 |
+
}
|
| 838 |
+
item := h.cfg.Plugins.Configs["sample-provider"]
|
| 839 |
+
if item.Enabled == nil || !*item.Enabled {
|
| 840 |
+
t.Fatalf("plugin enabled = %#v, want true", item.Enabled)
|
| 841 |
+
}
|
| 842 |
+
snapshotItem := cfgSnapshot.Plugins.Configs["sample-provider"]
|
| 843 |
+
if snapshotItem.Enabled == nil || !*snapshotItem.Enabled {
|
| 844 |
+
t.Fatalf("snapshot plugin enabled = %#v, want true", snapshotItem.Enabled)
|
| 845 |
+
}
|
| 846 |
+
if h.cfg.Plugins.Enabled {
|
| 847 |
+
t.Fatal("global plugins.enabled changed to true")
|
| 848 |
+
}
|
| 849 |
+
if cfgSnapshot.Plugins.Enabled {
|
| 850 |
+
t.Fatal("snapshot global plugins.enabled changed to true")
|
| 851 |
+
}
|
| 852 |
+
raw := marshalPluginRaw(t, item)
|
| 853 |
+
if !strings.Contains(raw, "mode: fast") {
|
| 854 |
+
t.Fatalf("plugin raw config lost custom field:\n%s", raw)
|
| 855 |
+
}
|
| 856 |
+
manifest := pluginStoreManifestFromConfig(t, item)
|
| 857 |
+
if manifest.InstallType() != pluginstore.InstallTypeGitHubRelease || manifest.ReleaseTag != "v0.1.0" || manifest.Version != "0.1.0" {
|
| 858 |
+
t.Fatalf("store manifest = %#v, want github-release v0.1.0", manifest)
|
| 859 |
+
}
|
| 860 |
+
if raw := marshalPluginRaw(t, snapshotItem); !strings.Contains(raw, "mode: fast") {
|
| 861 |
+
t.Fatalf("snapshot plugin raw config lost custom field:\n%s", raw)
|
| 862 |
+
}
|
| 863 |
+
}
|
| 864 |
+
|
| 865 |
+
func TestInstallPluginFromStoreInstallsDirectArtifact(t *testing.T) {
|
| 866 |
+
t.Parallel()
|
| 867 |
+
|
| 868 |
+
pluginsDir := t.TempDir()
|
| 869 |
+
archiveData := makeManagementPluginStoreZip(t, "sample-provider"+managementPluginExtension(runtime.GOOS), "direct-library-data")
|
| 870 |
+
checksum := sha256.Sum256(archiveData)
|
| 871 |
+
artifactURL := "https://downloads.example/sample-provider.zip"
|
| 872 |
+
h := &Handler{
|
| 873 |
+
cfg: &config.Config{
|
| 874 |
+
Plugins: config.PluginsConfig{
|
| 875 |
+
Enabled: false,
|
| 876 |
+
Dir: pluginsDir,
|
| 877 |
+
},
|
| 878 |
+
},
|
| 879 |
+
configFilePath: writeTestConfigFile(t),
|
| 880 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 881 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 882 |
+
"https://registry.example/registry.json": directRegistryJSON(artifactURL, hex.EncodeToString(checksum[:])),
|
| 883 |
+
artifactURL: archiveData,
|
| 884 |
+
},
|
| 885 |
+
}
|
| 886 |
+
reloads, reloadDone := captureConfigReload(h)
|
| 887 |
+
|
| 888 |
+
rec := httptest.NewRecorder()
|
| 889 |
+
c, _ := gin.CreateTestContext(rec)
|
| 890 |
+
c.Params = gin.Params{{Key: "id", Value: "sample-provider"}}
|
| 891 |
+
c.Request = httptest.NewRequest(http.MethodPost, "/v0/management/plugin-store/sample-provider/install", nil)
|
| 892 |
+
|
| 893 |
+
h.InstallPluginFromStore(c)
|
| 894 |
+
|
| 895 |
+
if rec.Code != http.StatusOK {
|
| 896 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 897 |
+
}
|
| 898 |
+
waitForAsyncReload(t, reloads)
|
| 899 |
+
waitForReloadDone(t, reloadDone)
|
| 900 |
+
var body pluginInstallResponse
|
| 901 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 902 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 903 |
+
}
|
| 904 |
+
if body.InstallType != pluginstore.InstallTypeDirect || body.Version != "0.4.0" {
|
| 905 |
+
t.Fatalf("install response = %#v, want direct 0.4.0", body)
|
| 906 |
+
}
|
| 907 |
+
targetPath := filepath.Join(pluginsDir, runtime.GOOS, runtime.GOARCH, "sample-provider-v0.4.0"+managementPluginExtension(runtime.GOOS))
|
| 908 |
+
data, errRead := os.ReadFile(targetPath)
|
| 909 |
+
if errRead != nil {
|
| 910 |
+
t.Fatalf("ReadFile(%s) error = %v", targetPath, errRead)
|
| 911 |
+
}
|
| 912 |
+
if string(data) != "direct-library-data" {
|
| 913 |
+
t.Fatalf("installed file = %q, want direct-library-data", data)
|
| 914 |
+
}
|
| 915 |
+
manifest := pluginStoreManifestFromConfig(t, h.cfg.Plugins.Configs["sample-provider"])
|
| 916 |
+
if manifest.SchemaVersion != pluginstore.SchemaVersionV2 || manifest.InstallType() != pluginstore.InstallTypeDirect || manifest.Version != "0.4.0" {
|
| 917 |
+
t.Fatalf("store manifest = %#v, want direct schema v2 0.4.0", manifest)
|
| 918 |
+
}
|
| 919 |
+
if manifest.SourceURL != "https://registry.example/registry.json" || len(manifest.Install.Artifacts) == 0 {
|
| 920 |
+
t.Fatalf("store manifest source/artifacts = %q/%d, want source URL with pinned artifacts", manifest.SourceURL, len(manifest.Install.Artifacts))
|
| 921 |
+
}
|
| 922 |
+
if raw := marshalPluginRaw(t, h.cfg.Plugins.Configs["sample-provider"]); !strings.Contains(raw, "artifacts:") {
|
| 923 |
+
t.Fatalf("direct store manifest should persist pinned artifacts:\n%s", raw)
|
| 924 |
+
}
|
| 925 |
+
}
|
| 926 |
+
|
| 927 |
+
func TestInstallPluginFromStoreHonorsDirectQueryVersion(t *testing.T) {
|
| 928 |
+
t.Parallel()
|
| 929 |
+
|
| 930 |
+
pluginsDir := t.TempDir()
|
| 931 |
+
archiveData := makeManagementPluginStoreZip(t, "sample-provider"+managementPluginExtension(runtime.GOOS), "direct-history-data")
|
| 932 |
+
checksum := sha256.Sum256(archiveData)
|
| 933 |
+
topArtifactURL := "https://downloads.example/sample-provider-0.4.0.zip"
|
| 934 |
+
versionArtifactURL := "https://downloads.example/sample-provider-0.3.0.zip"
|
| 935 |
+
h := &Handler{
|
| 936 |
+
cfg: &config.Config{
|
| 937 |
+
Plugins: config.PluginsConfig{
|
| 938 |
+
Enabled: false,
|
| 939 |
+
Dir: pluginsDir,
|
| 940 |
+
},
|
| 941 |
+
},
|
| 942 |
+
configFilePath: writeTestConfigFile(t),
|
| 943 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 944 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 945 |
+
"https://registry.example/registry.json": directRegistryJSONWithVersionArtifact(topArtifactURL, versionArtifactURL, hex.EncodeToString(checksum[:])),
|
| 946 |
+
versionArtifactURL: archiveData,
|
| 947 |
+
},
|
| 948 |
+
}
|
| 949 |
+
reloads, reloadDone := captureConfigReload(h)
|
| 950 |
+
|
| 951 |
+
rec := httptest.NewRecorder()
|
| 952 |
+
c, _ := gin.CreateTestContext(rec)
|
| 953 |
+
c.Params = gin.Params{{Key: "id", Value: "sample-provider"}}
|
| 954 |
+
c.Request = httptest.NewRequest(http.MethodPost, "/v0/management/plugin-store/sample-provider/install?version=0.3.0", nil)
|
| 955 |
+
|
| 956 |
+
h.InstallPluginFromStore(c)
|
| 957 |
+
|
| 958 |
+
if rec.Code != http.StatusOK {
|
| 959 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 960 |
+
}
|
| 961 |
+
waitForAsyncReload(t, reloads)
|
| 962 |
+
waitForReloadDone(t, reloadDone)
|
| 963 |
+
var body pluginInstallResponse
|
| 964 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 965 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 966 |
+
}
|
| 967 |
+
if body.InstallType != pluginstore.InstallTypeDirect || body.Version != "0.3.0" {
|
| 968 |
+
t.Fatalf("install response = %#v, want direct 0.3.0", body)
|
| 969 |
+
}
|
| 970 |
+
targetPath := filepath.Join(pluginsDir, runtime.GOOS, runtime.GOARCH, "sample-provider-v0.3.0"+managementPluginExtension(runtime.GOOS))
|
| 971 |
+
data, errRead := os.ReadFile(targetPath)
|
| 972 |
+
if errRead != nil {
|
| 973 |
+
t.Fatalf("ReadFile(%s) error = %v", targetPath, errRead)
|
| 974 |
+
}
|
| 975 |
+
if string(data) != "direct-history-data" {
|
| 976 |
+
t.Fatalf("installed file = %q, want direct-history-data", data)
|
| 977 |
+
}
|
| 978 |
+
manifest := pluginStoreManifestFromConfig(t, h.cfg.Plugins.Configs["sample-provider"])
|
| 979 |
+
if manifest.Version != "0.3.0" || manifest.InstallType() != pluginstore.InstallTypeDirect || len(manifest.Install.Artifacts) != 1 {
|
| 980 |
+
t.Fatalf("store manifest = %#v, want pinned direct 0.3.0", manifest)
|
| 981 |
+
}
|
| 982 |
+
if manifest.Install.Artifacts[0].URL != versionArtifactURL {
|
| 983 |
+
t.Fatalf("store manifest artifact = %#v, want requested version URL", manifest.Install.Artifacts[0])
|
| 984 |
+
}
|
| 985 |
+
}
|
| 986 |
+
|
| 987 |
+
func TestInstallPluginFromStoreUsesRequestedThirdPartySource(t *testing.T) {
|
| 988 |
+
t.Parallel()
|
| 989 |
+
|
| 990 |
+
pluginsDir := t.TempDir()
|
| 991 |
+
archiveData := makeManagementPluginStoreZip(t, "sample-provider"+managementPluginExtension(runtime.GOOS), "third-party-library-data")
|
| 992 |
+
archiveName := "sample-provider_0.3.0_" + runtime.GOOS + "_" + runtime.GOARCH + ".zip"
|
| 993 |
+
checksum := sha256.Sum256(archiveData)
|
| 994 |
+
h := &Handler{
|
| 995 |
+
cfg: &config.Config{
|
| 996 |
+
Plugins: config.PluginsConfig{
|
| 997 |
+
Enabled: false,
|
| 998 |
+
Dir: pluginsDir,
|
| 999 |
+
StoreSources: []string{"https://community.example/registry.json"},
|
| 1000 |
+
},
|
| 1001 |
+
},
|
| 1002 |
+
configFilePath: writeTestConfigFile(t),
|
| 1003 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 1004 |
+
pluginstore.DefaultRegistryURL: registryJSON(t),
|
| 1005 |
+
"https://community.example/registry.json": thirdPartySampleRegistryJSON(t),
|
| 1006 |
+
"https://api.github.com/repos/community/cliproxy-sample-provider-plugin/releases/latest": []byte(`{
|
| 1007 |
+
"tag_name": "v0.3.0",
|
| 1008 |
+
"assets": [
|
| 1009 |
+
{"name": "` + archiveName + `", "browser_download_url": "https://downloads.example/` + archiveName + `"},
|
| 1010 |
+
{"name": "checksums.txt", "browser_download_url": "https://downloads.example/checksums.txt"}
|
| 1011 |
+
]
|
| 1012 |
+
}`),
|
| 1013 |
+
"https://downloads.example/" + archiveName: archiveData,
|
| 1014 |
+
"https://downloads.example/checksums.txt": []byte(hex.EncodeToString(checksum[:]) + " " + archiveName + "\n"),
|
| 1015 |
+
},
|
| 1016 |
+
}
|
| 1017 |
+
reloads, reloadDone := captureConfigReload(h)
|
| 1018 |
+
|
| 1019 |
+
rec := httptest.NewRecorder()
|
| 1020 |
+
c, _ := gin.CreateTestContext(rec)
|
| 1021 |
+
c.Params = gin.Params{{Key: "id", Value: "sample-provider"}}
|
| 1022 |
+
communitySourceID := pluginstore.SourceID("https://community.example/registry.json")
|
| 1023 |
+
c.Request = httptest.NewRequest(http.MethodPost, "/v0/management/plugin-store/sample-provider/install?source="+communitySourceID, nil)
|
| 1024 |
+
|
| 1025 |
+
h.InstallPluginFromStore(c)
|
| 1026 |
+
|
| 1027 |
+
if rec.Code != http.StatusOK {
|
| 1028 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 1029 |
+
}
|
| 1030 |
+
cfgSnapshot := waitForAsyncReload(t, reloads)
|
| 1031 |
+
waitForReloadDone(t, reloadDone)
|
| 1032 |
+
if cfgSnapshot == h.cfg {
|
| 1033 |
+
t.Fatalf("reload config = handler config %p, want independent snapshot", h.cfg)
|
| 1034 |
+
}
|
| 1035 |
+
var body pluginInstallResponse
|
| 1036 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 1037 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 1038 |
+
}
|
| 1039 |
+
if body.SourceID != communitySourceID || body.Version != "0.3.0" {
|
| 1040 |
+
t.Fatalf("install response = %#v, want community source version 0.3.0", body)
|
| 1041 |
+
}
|
| 1042 |
+
targetPath := filepath.Join(pluginsDir, runtime.GOOS, runtime.GOARCH, "sample-provider-v0.3.0"+managementPluginExtension(runtime.GOOS))
|
| 1043 |
+
data, errRead := os.ReadFile(targetPath)
|
| 1044 |
+
if errRead != nil {
|
| 1045 |
+
t.Fatalf("ReadFile(%s) error = %v", targetPath, errRead)
|
| 1046 |
+
}
|
| 1047 |
+
if string(data) != "third-party-library-data" {
|
| 1048 |
+
t.Fatalf("installed file = %q, want third-party-library-data", data)
|
| 1049 |
+
}
|
| 1050 |
+
snapshotItem := cfgSnapshot.Plugins.Configs["sample-provider"]
|
| 1051 |
+
if snapshotItem.Enabled == nil || !*snapshotItem.Enabled {
|
| 1052 |
+
t.Fatalf("snapshot plugin enabled = %#v, want true", snapshotItem.Enabled)
|
| 1053 |
+
}
|
| 1054 |
+
}
|
| 1055 |
+
|
| 1056 |
+
func TestInstallPluginFromStoreRequiresSourceForDuplicateIDs(t *testing.T) {
|
| 1057 |
+
t.Parallel()
|
| 1058 |
+
|
| 1059 |
+
h := &Handler{
|
| 1060 |
+
cfg: &config.Config{
|
| 1061 |
+
Plugins: config.PluginsConfig{
|
| 1062 |
+
Enabled: false,
|
| 1063 |
+
Dir: t.TempDir(),
|
| 1064 |
+
StoreSources: []string{"https://community.example/registry.json"},
|
| 1065 |
+
},
|
| 1066 |
+
},
|
| 1067 |
+
configFilePath: writeTestConfigFile(t),
|
| 1068 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 1069 |
+
pluginstore.DefaultRegistryURL: registryJSON(t),
|
| 1070 |
+
"https://community.example/registry.json": thirdPartySampleRegistryJSON(t),
|
| 1071 |
+
},
|
| 1072 |
+
}
|
| 1073 |
+
|
| 1074 |
+
rec := httptest.NewRecorder()
|
| 1075 |
+
c, _ := gin.CreateTestContext(rec)
|
| 1076 |
+
c.Params = gin.Params{{Key: "id", Value: "sample-provider"}}
|
| 1077 |
+
c.Request = httptest.NewRequest(http.MethodPost, "/v0/management/plugin-store/sample-provider/install", nil)
|
| 1078 |
+
|
| 1079 |
+
h.InstallPluginFromStore(c)
|
| 1080 |
+
|
| 1081 |
+
if rec.Code != http.StatusConflict {
|
| 1082 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusConflict, rec.Body.String())
|
| 1083 |
+
}
|
| 1084 |
+
if !strings.Contains(rec.Body.String(), "plugin_store_source_required") {
|
| 1085 |
+
t.Fatalf("body = %s, want source required error", rec.Body.String())
|
| 1086 |
+
}
|
| 1087 |
+
}
|
| 1088 |
+
|
| 1089 |
+
func TestInstallPluginFromStoreOverwritesFilePreservesConfigAndReloads(t *testing.T) {
|
| 1090 |
+
t.Parallel()
|
| 1091 |
+
|
| 1092 |
+
pluginsDir := t.TempDir()
|
| 1093 |
+
existingPath := filepath.Join(pluginsDir, runtime.GOOS, runtime.GOARCH, "sample-provider-v0.1.0"+managementPluginExtension(runtime.GOOS))
|
| 1094 |
+
if errMkdir := os.MkdirAll(filepath.Dir(existingPath), 0o755); errMkdir != nil {
|
| 1095 |
+
t.Fatalf("MkdirAll(%s) error = %v", filepath.Dir(existingPath), errMkdir)
|
| 1096 |
+
}
|
| 1097 |
+
if errWrite := os.WriteFile(existingPath, []byte("old-library-data"), 0o644); errWrite != nil {
|
| 1098 |
+
t.Fatalf("WriteFile(%s) error = %v", existingPath, errWrite)
|
| 1099 |
+
}
|
| 1100 |
+
archiveData := makeManagementPluginStoreZip(t, "sample-provider"+managementPluginExtension(runtime.GOOS), "new-library-data")
|
| 1101 |
+
archiveName := "sample-provider_0.1.0_" + runtime.GOOS + "_" + runtime.GOARCH + ".zip"
|
| 1102 |
+
checksum := sha256.Sum256(archiveData)
|
| 1103 |
+
h := &Handler{
|
| 1104 |
+
cfg: &config.Config{
|
| 1105 |
+
Plugins: config.PluginsConfig{
|
| 1106 |
+
Enabled: true,
|
| 1107 |
+
Dir: pluginsDir,
|
| 1108 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 1109 |
+
"sample-provider": pluginConfigFromYAML(t, "enabled: false\npriority: 5\nmode: fast\nextra: keep\n"),
|
| 1110 |
+
},
|
| 1111 |
+
},
|
| 1112 |
+
},
|
| 1113 |
+
configFilePath: writeTestConfigFile(t),
|
| 1114 |
+
pluginStoreRegistryURL: "https://registry.example/registry.json",
|
| 1115 |
+
pluginStoreHTTPClient: fakePluginStoreHTTPClient{
|
| 1116 |
+
"https://registry.example/registry.json": registryJSON(t),
|
| 1117 |
+
"https://api.github.com/repos/author-name/cliproxy-sample-provider-plugin/releases/latest": []byte(`{
|
| 1118 |
+
"tag_name": "v0.1.0",
|
| 1119 |
+
"assets": [
|
| 1120 |
+
{"name": "` + archiveName + `", "browser_download_url": "https://downloads.example/` + archiveName + `"},
|
| 1121 |
+
{"name": "checksums.txt", "browser_download_url": "https://downloads.example/checksums.txt"}
|
| 1122 |
+
]
|
| 1123 |
+
}`),
|
| 1124 |
+
"https://downloads.example/" + archiveName: archiveData,
|
| 1125 |
+
"https://downloads.example/checksums.txt": []byte(hex.EncodeToString(checksum[:]) + " " + archiveName + "\n"),
|
| 1126 |
+
},
|
| 1127 |
+
}
|
| 1128 |
+
reloads, reloadDone := captureConfigReload(h)
|
| 1129 |
+
|
| 1130 |
+
rec := httptest.NewRecorder()
|
| 1131 |
+
c, _ := gin.CreateTestContext(rec)
|
| 1132 |
+
c.Params = gin.Params{{Key: "id", Value: "sample-provider"}}
|
| 1133 |
+
c.Request = httptest.NewRequest(http.MethodPost, "/v0/management/plugin-store/sample-provider/install", nil)
|
| 1134 |
+
|
| 1135 |
+
h.InstallPluginFromStore(c)
|
| 1136 |
+
|
| 1137 |
+
if rec.Code != http.StatusOK {
|
| 1138 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 1139 |
+
}
|
| 1140 |
+
cfgSnapshot := waitForAsyncReload(t, reloads)
|
| 1141 |
+
waitForReloadDone(t, reloadDone)
|
| 1142 |
+
if cfgSnapshot == h.cfg {
|
| 1143 |
+
t.Fatalf("reload config = handler config %p, want independent snapshot", h.cfg)
|
| 1144 |
+
}
|
| 1145 |
+
data, errRead := os.ReadFile(existingPath)
|
| 1146 |
+
if errRead != nil {
|
| 1147 |
+
t.Fatalf("ReadFile(%s) error = %v", existingPath, errRead)
|
| 1148 |
+
}
|
| 1149 |
+
if string(data) != "new-library-data" {
|
| 1150 |
+
t.Fatalf("installed file = %q, want new-library-data", data)
|
| 1151 |
+
}
|
| 1152 |
+
item := h.cfg.Plugins.Configs["sample-provider"]
|
| 1153 |
+
if item.Enabled == nil || !*item.Enabled {
|
| 1154 |
+
t.Fatalf("plugin enabled = %#v, want true", item.Enabled)
|
| 1155 |
+
}
|
| 1156 |
+
snapshotItem := cfgSnapshot.Plugins.Configs["sample-provider"]
|
| 1157 |
+
if snapshotItem.Enabled == nil || !*snapshotItem.Enabled {
|
| 1158 |
+
t.Fatalf("snapshot plugin enabled = %#v, want true", snapshotItem.Enabled)
|
| 1159 |
+
}
|
| 1160 |
+
if item.Priority != 5 {
|
| 1161 |
+
t.Fatalf("plugin priority = %d, want 5", item.Priority)
|
| 1162 |
+
}
|
| 1163 |
+
if snapshotItem.Priority != 5 {
|
| 1164 |
+
t.Fatalf("snapshot plugin priority = %d, want 5", snapshotItem.Priority)
|
| 1165 |
+
}
|
| 1166 |
+
raw := marshalPluginRaw(t, item)
|
| 1167 |
+
if !strings.Contains(raw, "mode: fast") || !strings.Contains(raw, "extra: keep") {
|
| 1168 |
+
t.Fatalf("plugin raw config lost custom fields:\n%s", raw)
|
| 1169 |
+
}
|
| 1170 |
+
if raw := marshalPluginRaw(t, snapshotItem); !strings.Contains(raw, "mode: fast") || !strings.Contains(raw, "extra: keep") {
|
| 1171 |
+
t.Fatalf("snapshot plugin raw config lost custom fields:\n%s", raw)
|
| 1172 |
+
}
|
| 1173 |
+
}
|
| 1174 |
+
|
| 1175 |
+
func TestEnablePluginConfigLockedPreservesExistingFields(t *testing.T) {
|
| 1176 |
+
t.Parallel()
|
| 1177 |
+
|
| 1178 |
+
h := &Handler{
|
| 1179 |
+
cfg: &config.Config{
|
| 1180 |
+
Plugins: config.PluginsConfig{
|
| 1181 |
+
Enabled: false,
|
| 1182 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 1183 |
+
"sample-provider": pluginConfigFromYAML(t, "enabled: false\npriority: 5\nmode: fast\n"),
|
| 1184 |
+
},
|
| 1185 |
+
},
|
| 1186 |
+
},
|
| 1187 |
+
}
|
| 1188 |
+
|
| 1189 |
+
if errEnable := h.enablePluginConfigLocked("sample-provider", testStoreManifest()); errEnable != nil {
|
| 1190 |
+
t.Fatalf("enablePluginConfigLocked() error = %v", errEnable)
|
| 1191 |
+
}
|
| 1192 |
+
if h.cfg.Plugins.Enabled {
|
| 1193 |
+
t.Fatal("global Plugins.Enabled changed to true")
|
| 1194 |
+
}
|
| 1195 |
+
item := h.cfg.Plugins.Configs["sample-provider"]
|
| 1196 |
+
if item.Enabled == nil || !*item.Enabled {
|
| 1197 |
+
t.Fatalf("plugin enabled = %#v, want true", item.Enabled)
|
| 1198 |
+
}
|
| 1199 |
+
if item.Priority != 5 {
|
| 1200 |
+
t.Fatalf("plugin priority = %d, want 5", item.Priority)
|
| 1201 |
+
}
|
| 1202 |
+
raw := marshalPluginRaw(t, item)
|
| 1203 |
+
if !strings.Contains(raw, "mode: fast") || !strings.Contains(raw, "store:") {
|
| 1204 |
+
t.Fatalf("plugin raw config lost custom field:\n%s", raw)
|
| 1205 |
+
}
|
| 1206 |
+
}
|
| 1207 |
+
|
| 1208 |
+
func TestEnablePluginConfigLockedCreatesMissingConfig(t *testing.T) {
|
| 1209 |
+
t.Parallel()
|
| 1210 |
+
|
| 1211 |
+
h := &Handler{cfg: &config.Config{}}
|
| 1212 |
+
if errEnable := h.enablePluginConfigLocked("sample-provider", testStoreManifest()); errEnable != nil {
|
| 1213 |
+
t.Fatalf("enablePluginConfigLocked() error = %v", errEnable)
|
| 1214 |
+
}
|
| 1215 |
+
item := h.cfg.Plugins.Configs["sample-provider"]
|
| 1216 |
+
if item.Enabled == nil || !*item.Enabled {
|
| 1217 |
+
t.Fatalf("plugin enabled = %#v, want true", item.Enabled)
|
| 1218 |
+
}
|
| 1219 |
+
manifest := pluginStoreManifestFromConfig(t, item)
|
| 1220 |
+
if manifest.ID != "sample-provider" || manifest.ReleaseTag != "v0.1.0" {
|
| 1221 |
+
t.Fatalf("store manifest = %#v, want sample-provider v0.1.0", manifest)
|
| 1222 |
+
}
|
| 1223 |
+
}
|
| 1224 |
+
|
| 1225 |
+
type fakePluginStoreHTTPClient map[string][]byte
|
| 1226 |
+
|
| 1227 |
+
func (c fakePluginStoreHTTPClient) Do(req *http.Request) (*http.Response, error) {
|
| 1228 |
+
body, ok := c[req.URL.String()]
|
| 1229 |
+
if !ok {
|
| 1230 |
+
return &http.Response{
|
| 1231 |
+
StatusCode: http.StatusNotFound,
|
| 1232 |
+
Body: io.NopCloser(strings.NewReader("not found")),
|
| 1233 |
+
Header: make(http.Header),
|
| 1234 |
+
Request: req,
|
| 1235 |
+
}, nil
|
| 1236 |
+
}
|
| 1237 |
+
return &http.Response{
|
| 1238 |
+
StatusCode: http.StatusOK,
|
| 1239 |
+
Body: io.NopCloser(bytes.NewReader(body)),
|
| 1240 |
+
Header: make(http.Header),
|
| 1241 |
+
Request: req,
|
| 1242 |
+
}, nil
|
| 1243 |
+
}
|
| 1244 |
+
|
| 1245 |
+
type countingPluginStoreHTTPClient struct {
|
| 1246 |
+
responses fakePluginStoreHTTPClient
|
| 1247 |
+
mu sync.Mutex
|
| 1248 |
+
counts map[string]int
|
| 1249 |
+
}
|
| 1250 |
+
|
| 1251 |
+
func (c *countingPluginStoreHTTPClient) Do(req *http.Request) (*http.Response, error) {
|
| 1252 |
+
c.mu.Lock()
|
| 1253 |
+
if c.counts == nil {
|
| 1254 |
+
c.counts = make(map[string]int)
|
| 1255 |
+
}
|
| 1256 |
+
c.counts[req.URL.String()]++
|
| 1257 |
+
c.mu.Unlock()
|
| 1258 |
+
return c.responses.Do(req)
|
| 1259 |
+
}
|
| 1260 |
+
|
| 1261 |
+
func (c *countingPluginStoreHTTPClient) count(url string) int {
|
| 1262 |
+
c.mu.Lock()
|
| 1263 |
+
defer c.mu.Unlock()
|
| 1264 |
+
return c.counts[url]
|
| 1265 |
+
}
|
| 1266 |
+
|
| 1267 |
+
func registryJSON(t *testing.T) []byte {
|
| 1268 |
+
t.Helper()
|
| 1269 |
+
|
| 1270 |
+
return []byte(`{
|
| 1271 |
+
"schema_version": 1,
|
| 1272 |
+
"plugins": [{
|
| 1273 |
+
"id": "sample-provider",
|
| 1274 |
+
"name": "Sample Provider",
|
| 1275 |
+
"description": "Adds sample provider support.",
|
| 1276 |
+
"author": "author-name",
|
| 1277 |
+
"version": "0.1.0",
|
| 1278 |
+
"repository": "https://github.com/author-name/cliproxy-sample-provider-plugin",
|
| 1279 |
+
"tags": ["provider"]
|
| 1280 |
+
}]
|
| 1281 |
+
}`)
|
| 1282 |
+
}
|
| 1283 |
+
|
| 1284 |
+
func thirdPartySampleRegistryJSON(t *testing.T) []byte {
|
| 1285 |
+
t.Helper()
|
| 1286 |
+
|
| 1287 |
+
return []byte(`{
|
| 1288 |
+
"schema_version": 1,
|
| 1289 |
+
"plugins": [{
|
| 1290 |
+
"id": "sample-provider",
|
| 1291 |
+
"name": "Sample Provider Community Build",
|
| 1292 |
+
"description": "Adds sample provider support from a third-party source.",
|
| 1293 |
+
"author": "community",
|
| 1294 |
+
"version": "0.3.0",
|
| 1295 |
+
"repository": "https://github.com/community/cliproxy-sample-provider-plugin"
|
| 1296 |
+
}]
|
| 1297 |
+
}`)
|
| 1298 |
+
}
|
| 1299 |
+
|
| 1300 |
+
func directRegistryJSON(artifactURL string, checksum string) []byte {
|
| 1301 |
+
return []byte(`{
|
| 1302 |
+
"schema_version": 2,
|
| 1303 |
+
"plugins": [{
|
| 1304 |
+
"id": "sample-provider",
|
| 1305 |
+
"name": "Sample Provider",
|
| 1306 |
+
"description": "Adds sample provider support.",
|
| 1307 |
+
"author": "author-name",
|
| 1308 |
+
"version": "0.4.0",
|
| 1309 |
+
"auth_required": true,
|
| 1310 |
+
"install": {
|
| 1311 |
+
"type": "direct",
|
| 1312 |
+
"artifacts": [{
|
| 1313 |
+
"goos": "` + runtime.GOOS + `",
|
| 1314 |
+
"goarch": "` + runtime.GOARCH + `",
|
| 1315 |
+
"url": "` + artifactURL + `",
|
| 1316 |
+
"sha256": "` + checksum + `"
|
| 1317 |
+
}, {
|
| 1318 |
+
"goos": "linux",
|
| 1319 |
+
"goarch": "amd64",
|
| 1320 |
+
"url": "` + artifactURL + `",
|
| 1321 |
+
"sha256": "` + checksum + `"
|
| 1322 |
+
}]
|
| 1323 |
+
}
|
| 1324 |
+
}]
|
| 1325 |
+
}`)
|
| 1326 |
+
}
|
| 1327 |
+
|
| 1328 |
+
func directRegistryJSONWithVersionArtifact(artifactURL string, versionArtifactURL string, checksum string) []byte {
|
| 1329 |
+
return []byte(`{
|
| 1330 |
+
"schema_version": 2,
|
| 1331 |
+
"plugins": [{
|
| 1332 |
+
"id": "sample-provider",
|
| 1333 |
+
"name": "Sample Provider",
|
| 1334 |
+
"description": "Adds sample provider support.",
|
| 1335 |
+
"author": "author-name",
|
| 1336 |
+
"version": "0.4.0",
|
| 1337 |
+
"auth_required": true,
|
| 1338 |
+
"install": {
|
| 1339 |
+
"type": "direct",
|
| 1340 |
+
"artifacts": [{
|
| 1341 |
+
"goos": "` + runtime.GOOS + `",
|
| 1342 |
+
"goarch": "` + runtime.GOARCH + `",
|
| 1343 |
+
"url": "` + artifactURL + `",
|
| 1344 |
+
"sha256": "` + checksum + `"
|
| 1345 |
+
}]
|
| 1346 |
+
},
|
| 1347 |
+
"versions": [{
|
| 1348 |
+
"version": "0.3.0",
|
| 1349 |
+
"install": {
|
| 1350 |
+
"type": "direct",
|
| 1351 |
+
"artifacts": [{
|
| 1352 |
+
"goos": "` + runtime.GOOS + `",
|
| 1353 |
+
"goarch": "` + runtime.GOARCH + `",
|
| 1354 |
+
"url": "` + versionArtifactURL + `",
|
| 1355 |
+
"sha256": "` + checksum + `"
|
| 1356 |
+
}]
|
| 1357 |
+
}
|
| 1358 |
+
}]
|
| 1359 |
+
}]
|
| 1360 |
+
}`)
|
| 1361 |
+
}
|
| 1362 |
+
|
| 1363 |
+
func testStoreManifest() pluginstore.Manifest {
|
| 1364 |
+
return pluginstore.Manifest{
|
| 1365 |
+
ID: "sample-provider",
|
| 1366 |
+
Name: "Sample Provider",
|
| 1367 |
+
Description: "Adds sample provider support.",
|
| 1368 |
+
Author: "author-name",
|
| 1369 |
+
Version: "0.1.0",
|
| 1370 |
+
ReleaseTag: "v0.1.0",
|
| 1371 |
+
Repository: "https://github.com/author-name/cliproxy-sample-provider-plugin",
|
| 1372 |
+
Install: pluginstore.InstallPlan{Type: pluginstore.InstallTypeGitHubRelease},
|
| 1373 |
+
}
|
| 1374 |
+
}
|
| 1375 |
+
|
| 1376 |
+
func pluginConfigWithStoreSource(t *testing.T, sourceID string, sourceURL string) config.PluginInstanceConfig {
|
| 1377 |
+
t.Helper()
|
| 1378 |
+
sourceFields := ""
|
| 1379 |
+
if sourceID != "" {
|
| 1380 |
+
sourceFields += " source-id: " + sourceID + "\n"
|
| 1381 |
+
}
|
| 1382 |
+
if sourceURL != "" {
|
| 1383 |
+
sourceFields += " source-url: " + sourceURL + "\n"
|
| 1384 |
+
}
|
| 1385 |
+
return pluginConfigFromYAML(t, "enabled: true\nstore:\n schema-version: 1\n id: sample-provider\n version: 0.0.1\n release-tag: v0.0.1\n repository: https://github.com/author-name/cliproxy-sample-provider-plugin\n"+sourceFields+" install:\n type: github-release\n")
|
| 1386 |
+
}
|
| 1387 |
+
|
| 1388 |
+
func pluginStoreManifestFromConfig(t *testing.T, item config.PluginInstanceConfig) pluginstore.Manifest {
|
| 1389 |
+
t.Helper()
|
| 1390 |
+
|
| 1391 |
+
node := pluginConfigNode(item)
|
| 1392 |
+
for index := 0; index+1 < len(node.Content); index += 2 {
|
| 1393 |
+
key := node.Content[index]
|
| 1394 |
+
value := node.Content[index+1]
|
| 1395 |
+
if key == nil || key.Value != "store" {
|
| 1396 |
+
continue
|
| 1397 |
+
}
|
| 1398 |
+
var manifest pluginstore.Manifest
|
| 1399 |
+
if errDecode := value.Decode(&manifest); errDecode != nil {
|
| 1400 |
+
t.Fatalf("decode store manifest: %v", errDecode)
|
| 1401 |
+
}
|
| 1402 |
+
if errValidate := manifest.Validate(); errValidate != nil {
|
| 1403 |
+
t.Fatalf("store manifest Validate() error = %v; manifest=%#v", errValidate, manifest)
|
| 1404 |
+
}
|
| 1405 |
+
return manifest
|
| 1406 |
+
}
|
| 1407 |
+
t.Fatalf("plugin config missing store manifest:\n%s", marshalPluginRaw(t, item))
|
| 1408 |
+
return pluginstore.Manifest{}
|
| 1409 |
+
}
|
| 1410 |
+
|
| 1411 |
+
func pluginStorePlatformsContain(platforms []pluginStorePlatform, goos string, goarch string) bool {
|
| 1412 |
+
for _, platform := range platforms {
|
| 1413 |
+
if platform.GOOS == goos && platform.GOARCH == goarch {
|
| 1414 |
+
return true
|
| 1415 |
+
}
|
| 1416 |
+
}
|
| 1417 |
+
return false
|
| 1418 |
+
}
|
| 1419 |
+
|
| 1420 |
+
func makeManagementPluginStoreZip(t *testing.T, name string, content string) []byte {
|
| 1421 |
+
t.Helper()
|
| 1422 |
+
|
| 1423 |
+
var buffer bytes.Buffer
|
| 1424 |
+
writer := zip.NewWriter(&buffer)
|
| 1425 |
+
file, errCreate := writer.Create(name)
|
| 1426 |
+
if errCreate != nil {
|
| 1427 |
+
t.Fatalf("Create(%s) error = %v", name, errCreate)
|
| 1428 |
+
}
|
| 1429 |
+
if _, errWrite := file.Write([]byte(content)); errWrite != nil {
|
| 1430 |
+
t.Fatalf("Write(%s) error = %v", name, errWrite)
|
| 1431 |
+
}
|
| 1432 |
+
if errClose := writer.Close(); errClose != nil {
|
| 1433 |
+
t.Fatalf("Close() error = %v", errClose)
|
| 1434 |
+
}
|
| 1435 |
+
return buffer.Bytes()
|
| 1436 |
+
}
|
internal/api/handlers/management/plugins.go
ADDED
|
@@ -0,0 +1,713 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"errors"
|
| 6 |
+
"fmt"
|
| 7 |
+
"net/http"
|
| 8 |
+
"os"
|
| 9 |
+
"sort"
|
| 10 |
+
"strconv"
|
| 11 |
+
"strings"
|
| 12 |
+
|
| 13 |
+
"github.com/gin-gonic/gin"
|
| 14 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 15 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/htmlsanitize"
|
| 16 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
|
| 17 |
+
"github.com/router-for-me/CLIProxyAPI/v7/sdk/pluginapi"
|
| 18 |
+
"gopkg.in/yaml.v3"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
type pluginListResponse struct {
|
| 22 |
+
PluginsEnabled bool `json:"plugins_enabled"`
|
| 23 |
+
PluginsDir string `json:"plugins_dir"`
|
| 24 |
+
Plugins []pluginListEntry `json:"plugins"`
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
type pluginListEntry struct {
|
| 28 |
+
ID string `json:"id"`
|
| 29 |
+
Path string `json:"path"`
|
| 30 |
+
Configured bool `json:"configured"`
|
| 31 |
+
Registered bool `json:"registered"`
|
| 32 |
+
Enabled bool `json:"enabled"`
|
| 33 |
+
EffectiveEnabled bool `json:"effective_enabled"`
|
| 34 |
+
SupportsOAuth bool `json:"supports_oauth"`
|
| 35 |
+
OAuthProvider string `json:"oauth_provider"`
|
| 36 |
+
Logo string `json:"logo"`
|
| 37 |
+
ConfigFields []pluginConfigFieldInfo `json:"config_fields"`
|
| 38 |
+
Menus []pluginMenuInfo `json:"menus"`
|
| 39 |
+
Metadata *pluginMetadataInfo `json:"metadata"`
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
type pluginMetadataInfo struct {
|
| 43 |
+
Name string `json:"name"`
|
| 44 |
+
Version string `json:"version"`
|
| 45 |
+
Author string `json:"author"`
|
| 46 |
+
GitHubRepository string `json:"github_repository"`
|
| 47 |
+
Logo string `json:"logo"`
|
| 48 |
+
ConfigFields []pluginConfigFieldInfo `json:"config_fields"`
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
type pluginConfigFieldInfo struct {
|
| 52 |
+
Name string `json:"name"`
|
| 53 |
+
Type string `json:"type"`
|
| 54 |
+
EnumValues []string `json:"enum_values"`
|
| 55 |
+
Description string `json:"description"`
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
type pluginMenuInfo struct {
|
| 59 |
+
Path string `json:"path"`
|
| 60 |
+
Menu string `json:"menu"`
|
| 61 |
+
Description string `json:"description"`
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
// ListPlugins returns discovered, configured, and registered plugin entries.
|
| 65 |
+
func (h *Handler) ListPlugins(c *gin.Context) {
|
| 66 |
+
if h == nil || h.cfg == nil {
|
| 67 |
+
c.JSON(http.StatusOK, pluginListResponse{
|
| 68 |
+
PluginsDir: "plugins",
|
| 69 |
+
Plugins: []pluginListEntry{},
|
| 70 |
+
})
|
| 71 |
+
return
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
h.mu.Lock()
|
| 75 |
+
pluginsEnabled := h.cfg.Plugins.Enabled
|
| 76 |
+
pluginsDir := normalizedPluginsDir(h.cfg.Plugins.Dir)
|
| 77 |
+
configs := make(map[string]config.PluginInstanceConfig, len(h.cfg.Plugins.Configs))
|
| 78 |
+
for id, item := range h.cfg.Plugins.Configs {
|
| 79 |
+
configs[id] = item
|
| 80 |
+
}
|
| 81 |
+
host := h.pluginHost
|
| 82 |
+
h.mu.Unlock()
|
| 83 |
+
|
| 84 |
+
resolvedPluginsDir, errResolvePluginsDir := config.ResolvePluginsDir(pluginsDir)
|
| 85 |
+
if errResolvePluginsDir != nil {
|
| 86 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_directory_invalid", "message": errResolvePluginsDir.Error()})
|
| 87 |
+
return
|
| 88 |
+
}
|
| 89 |
+
pluginsDir = resolvedPluginsDir
|
| 90 |
+
entries := make(map[string]pluginListEntry)
|
| 91 |
+
files, errDiscover := pluginhost.DiscoverPluginFiles(pluginsDir, pluginStoreDesiredVersions(configs))
|
| 92 |
+
if errDiscover != nil {
|
| 93 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_discovery_failed", "message": errDiscover.Error()})
|
| 94 |
+
return
|
| 95 |
+
}
|
| 96 |
+
for _, file := range files {
|
| 97 |
+
entries[file.ID] = pluginListEntry{
|
| 98 |
+
ID: htmlsanitize.String(file.ID),
|
| 99 |
+
Path: htmlsanitize.String(file.Path),
|
| 100 |
+
Enabled: false,
|
| 101 |
+
ConfigFields: []pluginConfigFieldInfo{},
|
| 102 |
+
Menus: []pluginMenuInfo{},
|
| 103 |
+
}
|
| 104 |
+
}
|
| 105 |
+
for id, item := range configs {
|
| 106 |
+
entry := entries[id]
|
| 107 |
+
entry.ID = htmlsanitize.String(id)
|
| 108 |
+
entry.Configured = true
|
| 109 |
+
entry.Enabled = pluginInstanceEnabled(item)
|
| 110 |
+
if entry.ConfigFields == nil {
|
| 111 |
+
entry.ConfigFields = []pluginConfigFieldInfo{}
|
| 112 |
+
}
|
| 113 |
+
if entry.Menus == nil {
|
| 114 |
+
entry.Menus = []pluginMenuInfo{}
|
| 115 |
+
}
|
| 116 |
+
entries[id] = entry
|
| 117 |
+
}
|
| 118 |
+
if host != nil {
|
| 119 |
+
for _, info := range host.RegisteredPlugins() {
|
| 120 |
+
entry := entries[info.ID]
|
| 121 |
+
entry.ID = htmlsanitize.String(info.ID)
|
| 122 |
+
entry.Registered = true
|
| 123 |
+
entry.SupportsOAuth = info.SupportsOAuth
|
| 124 |
+
entry.OAuthProvider = htmlsanitize.String(info.OAuthProvider)
|
| 125 |
+
entry.Logo = htmlsanitize.String(info.Metadata.Logo)
|
| 126 |
+
entry.ConfigFields = pluginConfigFields(info.Metadata.ConfigFields)
|
| 127 |
+
entry.Menus = pluginMenus(info.Menus)
|
| 128 |
+
entry.Metadata = pluginMetadata(info.Metadata)
|
| 129 |
+
entries[info.ID] = entry
|
| 130 |
+
}
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
ids := make([]string, 0, len(entries))
|
| 134 |
+
for id := range entries {
|
| 135 |
+
ids = append(ids, id)
|
| 136 |
+
}
|
| 137 |
+
sort.Strings(ids)
|
| 138 |
+
out := make([]pluginListEntry, 0, len(ids))
|
| 139 |
+
for _, id := range ids {
|
| 140 |
+
entry := entries[id]
|
| 141 |
+
entry.EffectiveEnabled = pluginsEnabled && entry.Enabled && entry.Registered
|
| 142 |
+
if entry.ConfigFields == nil {
|
| 143 |
+
entry.ConfigFields = []pluginConfigFieldInfo{}
|
| 144 |
+
}
|
| 145 |
+
if entry.Menus == nil {
|
| 146 |
+
entry.Menus = []pluginMenuInfo{}
|
| 147 |
+
}
|
| 148 |
+
out = append(out, entry)
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
c.JSON(http.StatusOK, pluginListResponse{
|
| 152 |
+
PluginsEnabled: pluginsEnabled,
|
| 153 |
+
PluginsDir: htmlsanitize.String(pluginsDir),
|
| 154 |
+
Plugins: out,
|
| 155 |
+
})
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
// GetPluginConfig returns the preserved plugins.configs.<id> object as JSON.
|
| 159 |
+
func (h *Handler) GetPluginConfig(c *gin.Context) {
|
| 160 |
+
id, okID := pluginIDFromRequest(c)
|
| 161 |
+
if !okID {
|
| 162 |
+
return
|
| 163 |
+
}
|
| 164 |
+
if h == nil {
|
| 165 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "plugin_not_found", "message": "plugin not found"})
|
| 166 |
+
return
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
h.mu.Lock()
|
| 170 |
+
if h.cfg == nil {
|
| 171 |
+
h.mu.Unlock()
|
| 172 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "plugin_not_found", "message": "plugin not found"})
|
| 173 |
+
return
|
| 174 |
+
}
|
| 175 |
+
item, configured := h.cfg.Plugins.Configs[id]
|
| 176 |
+
pluginsDir := normalizedPluginsDir(h.cfg.Plugins.Dir)
|
| 177 |
+
host := h.pluginHost
|
| 178 |
+
h.mu.Unlock()
|
| 179 |
+
|
| 180 |
+
if configured {
|
| 181 |
+
body, errBody := pluginConfigJSONObject(item)
|
| 182 |
+
if errBody != nil {
|
| 183 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_config_encode_failed", "message": errBody.Error()})
|
| 184 |
+
return
|
| 185 |
+
}
|
| 186 |
+
c.JSON(http.StatusOK, body)
|
| 187 |
+
return
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
if pluginRegistered(host, id) {
|
| 191 |
+
c.JSON(http.StatusOK, gin.H{})
|
| 192 |
+
return
|
| 193 |
+
}
|
| 194 |
+
resolvedPluginsDir, errResolvePluginsDir := config.ResolvePluginsDir(pluginsDir)
|
| 195 |
+
if errResolvePluginsDir != nil {
|
| 196 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_directory_invalid", "message": errResolvePluginsDir.Error()})
|
| 197 |
+
return
|
| 198 |
+
}
|
| 199 |
+
discovered, errDiscover := pluginDiscovered(resolvedPluginsDir, id)
|
| 200 |
+
if errDiscover != nil {
|
| 201 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_discovery_failed", "message": errDiscover.Error()})
|
| 202 |
+
return
|
| 203 |
+
}
|
| 204 |
+
if discovered {
|
| 205 |
+
c.JSON(http.StatusOK, gin.H{})
|
| 206 |
+
return
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "plugin_not_found", "message": "plugin not found"})
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
// PatchPluginEnabled updates plugins.configs.<id>.enabled without touching plugins.enabled.
|
| 213 |
+
func (h *Handler) PatchPluginEnabled(c *gin.Context) {
|
| 214 |
+
id, okID := pluginIDFromRequest(c)
|
| 215 |
+
if !okID {
|
| 216 |
+
return
|
| 217 |
+
}
|
| 218 |
+
var body struct {
|
| 219 |
+
Enabled *bool `json:"enabled"`
|
| 220 |
+
}
|
| 221 |
+
if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil || body.Enabled == nil {
|
| 222 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_body", "message": "enabled is required"})
|
| 223 |
+
return
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
h.mu.Lock()
|
| 227 |
+
ensurePluginConfigMap(h.cfg)
|
| 228 |
+
item := h.cfg.Plugins.Configs[id]
|
| 229 |
+
node := pluginConfigNode(item)
|
| 230 |
+
setYAMLMappingValue(node, "enabled", boolYAMLNode(*body.Enabled))
|
| 231 |
+
updated, errConfig := pluginInstanceConfigFromNode(node)
|
| 232 |
+
if errConfig != nil {
|
| 233 |
+
h.mu.Unlock()
|
| 234 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_config", "message": errConfig.Error()})
|
| 235 |
+
return
|
| 236 |
+
}
|
| 237 |
+
h.cfg.Plugins.Configs[id] = updated
|
| 238 |
+
cfgSnapshot, okSnapshot := h.saveConfigAndSnapshotLocked(c)
|
| 239 |
+
h.mu.Unlock()
|
| 240 |
+
if !okSnapshot {
|
| 241 |
+
return
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
h.reloadConfigAfterManagementSaveAsync(c.Request.Context(), cfgSnapshot)
|
| 245 |
+
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
// PutPluginConfig replaces plugins.configs.<id> with the request object.
|
| 249 |
+
func (h *Handler) PutPluginConfig(c *gin.Context) {
|
| 250 |
+
id, okID := pluginIDFromRequest(c)
|
| 251 |
+
if !okID {
|
| 252 |
+
return
|
| 253 |
+
}
|
| 254 |
+
body, okBody := readPluginConfigObject(c)
|
| 255 |
+
if !okBody {
|
| 256 |
+
return
|
| 257 |
+
}
|
| 258 |
+
node, errNode := yamlNodeFromJSONObject(body)
|
| 259 |
+
if errNode != nil {
|
| 260 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_body", "message": errNode.Error()})
|
| 261 |
+
return
|
| 262 |
+
}
|
| 263 |
+
updated, errConfig := pluginInstanceConfigFromNode(node)
|
| 264 |
+
if errConfig != nil {
|
| 265 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_config", "message": errConfig.Error()})
|
| 266 |
+
return
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
h.mu.Lock()
|
| 270 |
+
defer h.mu.Unlock()
|
| 271 |
+
ensurePluginConfigMap(h.cfg)
|
| 272 |
+
h.cfg.Plugins.Configs[id] = updated
|
| 273 |
+
h.persistLocked(c)
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
// PatchPluginConfig shallow-merges plugins.configs.<id> with the request object.
|
| 277 |
+
func (h *Handler) PatchPluginConfig(c *gin.Context) {
|
| 278 |
+
id, okID := pluginIDFromRequest(c)
|
| 279 |
+
if !okID {
|
| 280 |
+
return
|
| 281 |
+
}
|
| 282 |
+
body, okBody := readPluginConfigObject(c)
|
| 283 |
+
if !okBody {
|
| 284 |
+
return
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
h.mu.Lock()
|
| 288 |
+
defer h.mu.Unlock()
|
| 289 |
+
ensurePluginConfigMap(h.cfg)
|
| 290 |
+
node := pluginConfigNode(h.cfg.Plugins.Configs[id])
|
| 291 |
+
keys := make([]string, 0, len(body))
|
| 292 |
+
for key := range body {
|
| 293 |
+
keys = append(keys, key)
|
| 294 |
+
}
|
| 295 |
+
sort.Strings(keys)
|
| 296 |
+
for _, key := range keys {
|
| 297 |
+
value := body[key]
|
| 298 |
+
if value == nil {
|
| 299 |
+
deleteYAMLMappingKey(node, key)
|
| 300 |
+
continue
|
| 301 |
+
}
|
| 302 |
+
valueNode, errNode := yamlNodeFromJSONValue(value)
|
| 303 |
+
if errNode != nil {
|
| 304 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_body", "message": errNode.Error()})
|
| 305 |
+
return
|
| 306 |
+
}
|
| 307 |
+
setYAMLMappingValue(node, key, valueNode)
|
| 308 |
+
}
|
| 309 |
+
updated, errConfig := pluginInstanceConfigFromNode(node)
|
| 310 |
+
if errConfig != nil {
|
| 311 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_config", "message": errConfig.Error()})
|
| 312 |
+
return
|
| 313 |
+
}
|
| 314 |
+
h.cfg.Plugins.Configs[id] = updated
|
| 315 |
+
h.persistLocked(c)
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
// DeletePlugin removes the selected local plugin file and its saved config.
|
| 319 |
+
func (h *Handler) DeletePlugin(c *gin.Context) {
|
| 320 |
+
id, okID := pluginIDFromRequest(c)
|
| 321 |
+
if !okID {
|
| 322 |
+
return
|
| 323 |
+
}
|
| 324 |
+
if h == nil {
|
| 325 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "plugin_not_found", "message": "plugin not found"})
|
| 326 |
+
return
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
h.mu.Lock()
|
| 330 |
+
if h.cfg == nil {
|
| 331 |
+
h.mu.Unlock()
|
| 332 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "plugin_not_found", "message": "plugin not found"})
|
| 333 |
+
return
|
| 334 |
+
}
|
| 335 |
+
pluginsDir := normalizedPluginsDir(h.cfg.Plugins.Dir)
|
| 336 |
+
item, configured := h.cfg.Plugins.Configs[id]
|
| 337 |
+
host := h.pluginHost
|
| 338 |
+
h.mu.Unlock()
|
| 339 |
+
|
| 340 |
+
resolvedPluginsDir, errResolvePluginsDir := config.ResolvePluginsDir(pluginsDir)
|
| 341 |
+
if errResolvePluginsDir != nil {
|
| 342 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_directory_invalid", "message": errResolvePluginsDir.Error()})
|
| 343 |
+
return
|
| 344 |
+
}
|
| 345 |
+
pluginsDir = resolvedPluginsDir
|
| 346 |
+
var desiredVersions map[string]string
|
| 347 |
+
if configured {
|
| 348 |
+
desiredVersions = pluginStoreDesiredVersions(map[string]config.PluginInstanceConfig{id: item})
|
| 349 |
+
}
|
| 350 |
+
path, errPath := pluginFilePath(pluginsDir, id, desiredVersions)
|
| 351 |
+
if errPath != nil {
|
| 352 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_discovery_failed", "message": errPath.Error()})
|
| 353 |
+
return
|
| 354 |
+
}
|
| 355 |
+
if path == "" && !configured {
|
| 356 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "plugin_not_found", "message": "plugin not found"})
|
| 357 |
+
return
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
if pluginBusy(host, id) && (host == nil || !host.UnloadPlugin(id)) && pluginBusy(host, id) {
|
| 361 |
+
c.JSON(http.StatusConflict, gin.H{
|
| 362 |
+
"error": "plugin_delete_requires_restart",
|
| 363 |
+
"message": "loaded plugin cannot be deleted while the server is running",
|
| 364 |
+
"restart_required": true,
|
| 365 |
+
})
|
| 366 |
+
return
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
fileDeleted := false
|
| 370 |
+
if path != "" {
|
| 371 |
+
if errRemove := os.Remove(path); errRemove != nil {
|
| 372 |
+
if !errors.Is(errRemove, os.ErrNotExist) {
|
| 373 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": "plugin_delete_failed", "message": errRemove.Error()})
|
| 374 |
+
return
|
| 375 |
+
}
|
| 376 |
+
} else {
|
| 377 |
+
fileDeleted = true
|
| 378 |
+
}
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
h.mu.Lock()
|
| 382 |
+
delete(h.cfg.Plugins.Configs, id)
|
| 383 |
+
if configured {
|
| 384 |
+
if errSave := config.SaveConfigPreserveComments(h.configFilePath, h.cfg); errSave != nil {
|
| 385 |
+
h.mu.Unlock()
|
| 386 |
+
c.JSON(http.StatusInternalServerError, gin.H{
|
| 387 |
+
"error": "config_save_failed",
|
| 388 |
+
"message": fmt.Sprintf("plugin deleted but saving config failed: %s", errSave.Error()),
|
| 389 |
+
"file_deleted": fileDeleted,
|
| 390 |
+
"path": path,
|
| 391 |
+
})
|
| 392 |
+
return
|
| 393 |
+
}
|
| 394 |
+
}
|
| 395 |
+
cfgSnapshot := h.reloadSnapshotConfigLocked()
|
| 396 |
+
h.mu.Unlock()
|
| 397 |
+
|
| 398 |
+
h.reloadConfigAfterManagementSaveAsync(c.Request.Context(), cfgSnapshot)
|
| 399 |
+
c.JSON(http.StatusOK, gin.H{
|
| 400 |
+
"status": "deleted",
|
| 401 |
+
"id": htmlsanitize.String(id),
|
| 402 |
+
"path": htmlsanitize.String(path),
|
| 403 |
+
"file_deleted": fileDeleted,
|
| 404 |
+
"configured_removed": configured,
|
| 405 |
+
"restart_required": false,
|
| 406 |
+
})
|
| 407 |
+
}
|
| 408 |
+
|
| 409 |
+
func normalizedPluginsDir(dir string) string {
|
| 410 |
+
dir = strings.TrimSpace(dir)
|
| 411 |
+
if dir == "" {
|
| 412 |
+
return "plugins"
|
| 413 |
+
}
|
| 414 |
+
return dir
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
func pluginInstanceEnabled(item config.PluginInstanceConfig) bool {
|
| 418 |
+
if item.Enabled == nil {
|
| 419 |
+
return false
|
| 420 |
+
}
|
| 421 |
+
return *item.Enabled
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
func pluginRegistered(host *pluginhost.Host, id string) bool {
|
| 425 |
+
if host == nil {
|
| 426 |
+
return false
|
| 427 |
+
}
|
| 428 |
+
for _, info := range host.RegisteredPlugins() {
|
| 429 |
+
if info.ID == id {
|
| 430 |
+
return true
|
| 431 |
+
}
|
| 432 |
+
}
|
| 433 |
+
return false
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
func pluginDiscovered(pluginsDir string, id string) (bool, error) {
|
| 437 |
+
files, errDiscover := pluginhost.DiscoverPluginFiles(pluginsDir)
|
| 438 |
+
if errDiscover != nil {
|
| 439 |
+
return false, errDiscover
|
| 440 |
+
}
|
| 441 |
+
for _, file := range files {
|
| 442 |
+
if file.ID == id {
|
| 443 |
+
return true, nil
|
| 444 |
+
}
|
| 445 |
+
}
|
| 446 |
+
return false, nil
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
func pluginFilePath(pluginsDir string, id string, desiredVersions ...map[string]string) (string, error) {
|
| 450 |
+
files, errDiscover := pluginhost.DiscoverPluginFiles(pluginsDir, desiredVersions...)
|
| 451 |
+
if errDiscover != nil {
|
| 452 |
+
return "", errDiscover
|
| 453 |
+
}
|
| 454 |
+
for _, file := range files {
|
| 455 |
+
if file.ID == id {
|
| 456 |
+
return file.Path, nil
|
| 457 |
+
}
|
| 458 |
+
}
|
| 459 |
+
return "", nil
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
func pluginConfigFields(fields []pluginapi.ConfigField) []pluginConfigFieldInfo {
|
| 463 |
+
out := make([]pluginConfigFieldInfo, 0, len(fields))
|
| 464 |
+
for _, field := range fields {
|
| 465 |
+
out = append(out, pluginConfigFieldInfo{
|
| 466 |
+
Name: htmlsanitize.String(field.Name),
|
| 467 |
+
Type: htmlsanitize.String(string(field.Type)),
|
| 468 |
+
EnumValues: htmlsanitize.Strings(field.EnumValues),
|
| 469 |
+
Description: htmlsanitize.String(field.Description),
|
| 470 |
+
})
|
| 471 |
+
}
|
| 472 |
+
return out
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
func pluginMenus(menus []pluginhost.RegisteredPluginMenu) []pluginMenuInfo {
|
| 476 |
+
out := make([]pluginMenuInfo, 0, len(menus))
|
| 477 |
+
for _, menu := range menus {
|
| 478 |
+
out = append(out, pluginMenuInfo{
|
| 479 |
+
Path: htmlsanitize.String(menu.Path),
|
| 480 |
+
Menu: htmlsanitize.String(menu.Menu),
|
| 481 |
+
Description: htmlsanitize.String(menu.Description),
|
| 482 |
+
})
|
| 483 |
+
}
|
| 484 |
+
return out
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
func pluginMetadata(meta pluginapi.Metadata) *pluginMetadataInfo {
|
| 488 |
+
return &pluginMetadataInfo{
|
| 489 |
+
Name: htmlsanitize.String(meta.Name),
|
| 490 |
+
Version: htmlsanitize.String(meta.Version),
|
| 491 |
+
Author: htmlsanitize.String(meta.Author),
|
| 492 |
+
GitHubRepository: htmlsanitize.String(meta.GitHubRepository),
|
| 493 |
+
Logo: htmlsanitize.String(meta.Logo),
|
| 494 |
+
ConfigFields: pluginConfigFields(meta.ConfigFields),
|
| 495 |
+
}
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
func pluginIDFromRequest(c *gin.Context) (string, bool) {
|
| 499 |
+
id := strings.TrimSpace(c.Param("id"))
|
| 500 |
+
if !pluginhost.ValidatePluginID(id) {
|
| 501 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_plugin_id", "message": "invalid plugin id"})
|
| 502 |
+
return "", false
|
| 503 |
+
}
|
| 504 |
+
return id, true
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
func readPluginConfigObject(c *gin.Context) (map[string]any, bool) {
|
| 508 |
+
decoder := json.NewDecoder(c.Request.Body)
|
| 509 |
+
decoder.UseNumber()
|
| 510 |
+
var body map[string]any
|
| 511 |
+
if errDecode := decoder.Decode(&body); errDecode != nil {
|
| 512 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_body", "message": errDecode.Error()})
|
| 513 |
+
return nil, false
|
| 514 |
+
}
|
| 515 |
+
if body == nil {
|
| 516 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_body", "message": "body must be a JSON object"})
|
| 517 |
+
return nil, false
|
| 518 |
+
}
|
| 519 |
+
return body, true
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
func ensurePluginConfigMap(cfg *config.Config) {
|
| 523 |
+
if cfg == nil {
|
| 524 |
+
return
|
| 525 |
+
}
|
| 526 |
+
cfg.NormalizePluginsConfig()
|
| 527 |
+
}
|
| 528 |
+
|
| 529 |
+
func pluginConfigNode(item config.PluginInstanceConfig) *yaml.Node {
|
| 530 |
+
if item.Raw.Kind == yaml.MappingNode {
|
| 531 |
+
return cloneYAMLNode(&item.Raw)
|
| 532 |
+
}
|
| 533 |
+
node := emptyYAMLMappingNode()
|
| 534 |
+
if item.Enabled != nil {
|
| 535 |
+
setYAMLMappingValue(node, "enabled", boolYAMLNode(*item.Enabled))
|
| 536 |
+
}
|
| 537 |
+
if item.Priority != 0 {
|
| 538 |
+
setYAMLMappingValue(node, "priority", intYAMLNode(item.Priority))
|
| 539 |
+
}
|
| 540 |
+
return node
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
func pluginConfigJSONObject(item config.PluginInstanceConfig) (map[string]any, error) {
|
| 544 |
+
value, errValue := yamlNodeToJSONValue(pluginConfigNode(item))
|
| 545 |
+
if errValue != nil {
|
| 546 |
+
return nil, errValue
|
| 547 |
+
}
|
| 548 |
+
body, ok := value.(map[string]any)
|
| 549 |
+
if !ok || body == nil {
|
| 550 |
+
return map[string]any{}, nil
|
| 551 |
+
}
|
| 552 |
+
return body, nil
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
func pluginInstanceConfigFromNode(node *yaml.Node) (config.PluginInstanceConfig, error) {
|
| 556 |
+
if node == nil {
|
| 557 |
+
node = emptyYAMLMappingNode()
|
| 558 |
+
}
|
| 559 |
+
var item config.PluginInstanceConfig
|
| 560 |
+
if errDecode := node.Decode(&item); errDecode != nil {
|
| 561 |
+
return config.PluginInstanceConfig{}, errDecode
|
| 562 |
+
}
|
| 563 |
+
return item, nil
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
func yamlNodeFromJSONObject(body map[string]any) (*yaml.Node, error) {
|
| 567 |
+
node := emptyYAMLMappingNode()
|
| 568 |
+
keys := make([]string, 0, len(body))
|
| 569 |
+
for key := range body {
|
| 570 |
+
keys = append(keys, key)
|
| 571 |
+
}
|
| 572 |
+
sort.Strings(keys)
|
| 573 |
+
for _, key := range keys {
|
| 574 |
+
valueNode, errNode := yamlNodeFromJSONValue(body[key])
|
| 575 |
+
if errNode != nil {
|
| 576 |
+
return nil, fmt.Errorf("%s: %w", key, errNode)
|
| 577 |
+
}
|
| 578 |
+
setYAMLMappingValue(node, key, valueNode)
|
| 579 |
+
}
|
| 580 |
+
return node, nil
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
func yamlNodeFromJSONValue(value any) (*yaml.Node, error) {
|
| 584 |
+
switch typed := value.(type) {
|
| 585 |
+
case nil:
|
| 586 |
+
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!null", Value: "null"}, nil
|
| 587 |
+
case string:
|
| 588 |
+
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: typed}, nil
|
| 589 |
+
case bool:
|
| 590 |
+
return boolYAMLNode(typed), nil
|
| 591 |
+
case json.Number:
|
| 592 |
+
if _, errInt64 := typed.Int64(); errInt64 == nil {
|
| 593 |
+
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: typed.String()}, nil
|
| 594 |
+
}
|
| 595 |
+
if _, errFloat64 := typed.Float64(); errFloat64 == nil {
|
| 596 |
+
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!float", Value: typed.String()}, nil
|
| 597 |
+
}
|
| 598 |
+
return nil, fmt.Errorf("invalid number %q", typed.String())
|
| 599 |
+
case float64:
|
| 600 |
+
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!float", Value: strconv.FormatFloat(typed, 'f', -1, 64)}, nil
|
| 601 |
+
case []any:
|
| 602 |
+
node := &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq"}
|
| 603 |
+
for _, item := range typed {
|
| 604 |
+
child, errChild := yamlNodeFromJSONValue(item)
|
| 605 |
+
if errChild != nil {
|
| 606 |
+
return nil, errChild
|
| 607 |
+
}
|
| 608 |
+
node.Content = append(node.Content, child)
|
| 609 |
+
}
|
| 610 |
+
return node, nil
|
| 611 |
+
case map[string]any:
|
| 612 |
+
return yamlNodeFromJSONObject(typed)
|
| 613 |
+
default:
|
| 614 |
+
return nil, fmt.Errorf("unsupported value type %T", value)
|
| 615 |
+
}
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
func yamlNodeToJSONValue(node *yaml.Node) (any, error) {
|
| 619 |
+
if node == nil {
|
| 620 |
+
return nil, nil
|
| 621 |
+
}
|
| 622 |
+
switch node.Kind {
|
| 623 |
+
case yaml.MappingNode:
|
| 624 |
+
out := make(map[string]any, len(node.Content)/2)
|
| 625 |
+
for index := 0; index+1 < len(node.Content); index += 2 {
|
| 626 |
+
key := node.Content[index]
|
| 627 |
+
value := node.Content[index+1]
|
| 628 |
+
if key == nil {
|
| 629 |
+
continue
|
| 630 |
+
}
|
| 631 |
+
child, errChild := yamlNodeToJSONValue(value)
|
| 632 |
+
if errChild != nil {
|
| 633 |
+
return nil, fmt.Errorf("%s: %w", key.Value, errChild)
|
| 634 |
+
}
|
| 635 |
+
out[key.Value] = child
|
| 636 |
+
}
|
| 637 |
+
return out, nil
|
| 638 |
+
case yaml.SequenceNode:
|
| 639 |
+
out := make([]any, 0, len(node.Content))
|
| 640 |
+
for _, childNode := range node.Content {
|
| 641 |
+
child, errChild := yamlNodeToJSONValue(childNode)
|
| 642 |
+
if errChild != nil {
|
| 643 |
+
return nil, errChild
|
| 644 |
+
}
|
| 645 |
+
out = append(out, child)
|
| 646 |
+
}
|
| 647 |
+
return out, nil
|
| 648 |
+
case yaml.ScalarNode:
|
| 649 |
+
if node.Tag == "!!str" || node.Tag == "" {
|
| 650 |
+
return node.Value, nil
|
| 651 |
+
}
|
| 652 |
+
var value any
|
| 653 |
+
if errDecode := node.Decode(&value); errDecode != nil {
|
| 654 |
+
return nil, errDecode
|
| 655 |
+
}
|
| 656 |
+
return value, nil
|
| 657 |
+
case yaml.AliasNode:
|
| 658 |
+
return yamlNodeToJSONValue(node.Alias)
|
| 659 |
+
default:
|
| 660 |
+
return nil, fmt.Errorf("unsupported YAML node kind %d", node.Kind)
|
| 661 |
+
}
|
| 662 |
+
}
|
| 663 |
+
|
| 664 |
+
func emptyYAMLMappingNode() *yaml.Node {
|
| 665 |
+
return &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
|
| 666 |
+
}
|
| 667 |
+
|
| 668 |
+
func boolYAMLNode(value bool) *yaml.Node {
|
| 669 |
+
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!bool", Value: strconv.FormatBool(value)}
|
| 670 |
+
}
|
| 671 |
+
|
| 672 |
+
func intYAMLNode(value int) *yaml.Node {
|
| 673 |
+
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: strconv.Itoa(value)}
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
func setYAMLMappingValue(mapping *yaml.Node, key string, value *yaml.Node) {
|
| 677 |
+
if mapping.Kind != yaml.MappingNode {
|
| 678 |
+
*mapping = *emptyYAMLMappingNode()
|
| 679 |
+
}
|
| 680 |
+
for index := 0; index+1 < len(mapping.Content); index += 2 {
|
| 681 |
+
if mapping.Content[index] != nil && mapping.Content[index].Value == key {
|
| 682 |
+
mapping.Content[index+1] = value
|
| 683 |
+
return
|
| 684 |
+
}
|
| 685 |
+
}
|
| 686 |
+
mapping.Content = append(mapping.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key}, value)
|
| 687 |
+
}
|
| 688 |
+
|
| 689 |
+
func deleteYAMLMappingKey(mapping *yaml.Node, key string) {
|
| 690 |
+
if mapping == nil || mapping.Kind != yaml.MappingNode {
|
| 691 |
+
return
|
| 692 |
+
}
|
| 693 |
+
for index := 0; index+1 < len(mapping.Content); index += 2 {
|
| 694 |
+
if mapping.Content[index] != nil && mapping.Content[index].Value == key {
|
| 695 |
+
mapping.Content = append(mapping.Content[:index], mapping.Content[index+2:]...)
|
| 696 |
+
return
|
| 697 |
+
}
|
| 698 |
+
}
|
| 699 |
+
}
|
| 700 |
+
|
| 701 |
+
func cloneYAMLNode(node *yaml.Node) *yaml.Node {
|
| 702 |
+
if node == nil {
|
| 703 |
+
return nil
|
| 704 |
+
}
|
| 705 |
+
out := *node
|
| 706 |
+
if len(node.Content) > 0 {
|
| 707 |
+
out.Content = make([]*yaml.Node, 0, len(node.Content))
|
| 708 |
+
for _, child := range node.Content {
|
| 709 |
+
out.Content = append(out.Content, cloneYAMLNode(child))
|
| 710 |
+
}
|
| 711 |
+
}
|
| 712 |
+
return &out
|
| 713 |
+
}
|
internal/api/handlers/management/plugins_test.go
ADDED
|
@@ -0,0 +1,852 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"bytes"
|
| 5 |
+
"context"
|
| 6 |
+
"encoding/json"
|
| 7 |
+
"html"
|
| 8 |
+
"net/http"
|
| 9 |
+
"net/http/httptest"
|
| 10 |
+
"os"
|
| 11 |
+
"path/filepath"
|
| 12 |
+
"runtime"
|
| 13 |
+
"strings"
|
| 14 |
+
"testing"
|
| 15 |
+
"time"
|
| 16 |
+
|
| 17 |
+
"github.com/gin-gonic/gin"
|
| 18 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 19 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
|
| 20 |
+
"github.com/router-for-me/CLIProxyAPI/v7/sdk/pluginapi"
|
| 21 |
+
"gopkg.in/yaml.v3"
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
func waitForAsyncReload(t *testing.T, reloads <-chan *config.Config) *config.Config {
|
| 25 |
+
t.Helper()
|
| 26 |
+
select {
|
| 27 |
+
case cfg := <-reloads:
|
| 28 |
+
return cfg
|
| 29 |
+
case <-time.After(time.Second):
|
| 30 |
+
t.Fatal("timed out waiting for async config reload")
|
| 31 |
+
return nil
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
func waitForReloadDone(t *testing.T, done <-chan struct{}) {
|
| 36 |
+
t.Helper()
|
| 37 |
+
select {
|
| 38 |
+
case <-done:
|
| 39 |
+
case <-time.After(time.Second):
|
| 40 |
+
t.Fatal("timed out waiting for config reload hook to finish")
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
func captureConfigReload(h *Handler) (<-chan *config.Config, <-chan struct{}) {
|
| 45 |
+
reloads := make(chan *config.Config, 1)
|
| 46 |
+
done := make(chan struct{})
|
| 47 |
+
h.SetConfigReloadHook(func(_ context.Context, cfg *config.Config) {
|
| 48 |
+
defer close(done)
|
| 49 |
+
reloads <- cfg
|
| 50 |
+
})
|
| 51 |
+
return reloads, done
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
func TestConfigReloadGenerationSkipsOlderSnapshot(t *testing.T) {
|
| 55 |
+
t.Parallel()
|
| 56 |
+
|
| 57 |
+
h := &Handler{
|
| 58 |
+
cfg: &config.Config{
|
| 59 |
+
Plugins: config.PluginsConfig{
|
| 60 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 61 |
+
"sample": pluginConfigFromYAML(t, "enabled: true\nmode: old\n"),
|
| 62 |
+
},
|
| 63 |
+
},
|
| 64 |
+
},
|
| 65 |
+
}
|
| 66 |
+
reloadedModes := make([]string, 0, 1)
|
| 67 |
+
h.SetConfigReloadHook(func(_ context.Context, cfg *config.Config) {
|
| 68 |
+
reloadedModes = append(reloadedModes, pluginRawScalarValue(t, cfg.Plugins.Configs["sample"], "mode"))
|
| 69 |
+
})
|
| 70 |
+
|
| 71 |
+
h.mu.Lock()
|
| 72 |
+
older := h.reloadSnapshotConfigLocked()
|
| 73 |
+
item := h.cfg.Plugins.Configs["sample"]
|
| 74 |
+
setPluginRawScalarValue(t, &item.Raw, "mode", "new")
|
| 75 |
+
h.cfg.Plugins.Configs["sample"] = item
|
| 76 |
+
newer := h.reloadSnapshotConfigLocked()
|
| 77 |
+
h.mu.Unlock()
|
| 78 |
+
|
| 79 |
+
h.reloadConfigAfterManagementSave(context.Background(), newer)
|
| 80 |
+
h.reloadConfigAfterManagementSave(context.Background(), older)
|
| 81 |
+
|
| 82 |
+
if len(reloadedModes) != 1 || reloadedModes[0] != "new" {
|
| 83 |
+
t.Fatalf("reloaded modes = %#v, want only new snapshot", reloadedModes)
|
| 84 |
+
}
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
func TestListPluginsIncludesScannedAndConfiguredPlugins(t *testing.T) {
|
| 88 |
+
t.Parallel()
|
| 89 |
+
|
| 90 |
+
pluginsDir := writeManagementPluginFile(t, "scanned")
|
| 91 |
+
disabled := false
|
| 92 |
+
h := &Handler{
|
| 93 |
+
cfg: &config.Config{
|
| 94 |
+
Plugins: config.PluginsConfig{
|
| 95 |
+
Enabled: false,
|
| 96 |
+
Dir: pluginsDir,
|
| 97 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 98 |
+
"configured-only": {Enabled: &disabled},
|
| 99 |
+
},
|
| 100 |
+
},
|
| 101 |
+
},
|
| 102 |
+
configFilePath: writeTestConfigFile(t),
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
rec := httptest.NewRecorder()
|
| 106 |
+
c, _ := gin.CreateTestContext(rec)
|
| 107 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugins", nil)
|
| 108 |
+
|
| 109 |
+
h.ListPlugins(c)
|
| 110 |
+
|
| 111 |
+
if rec.Code != http.StatusOK {
|
| 112 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
var body struct {
|
| 116 |
+
PluginsEnabled bool `json:"plugins_enabled"`
|
| 117 |
+
Plugins []struct {
|
| 118 |
+
ID string `json:"id"`
|
| 119 |
+
Path string `json:"path"`
|
| 120 |
+
Configured bool `json:"configured"`
|
| 121 |
+
Registered bool `json:"registered"`
|
| 122 |
+
Enabled bool `json:"enabled"`
|
| 123 |
+
EffectiveEnabled bool `json:"effective_enabled"`
|
| 124 |
+
SupportsOAuth bool `json:"supports_oauth"`
|
| 125 |
+
OAuthProvider string `json:"oauth_provider"`
|
| 126 |
+
Logo string `json:"logo"`
|
| 127 |
+
ConfigFields []any `json:"config_fields"`
|
| 128 |
+
Menus []any `json:"menus"`
|
| 129 |
+
} `json:"plugins"`
|
| 130 |
+
}
|
| 131 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 132 |
+
t.Fatalf("decode response: %v; body=%s", errDecode, rec.Body.String())
|
| 133 |
+
}
|
| 134 |
+
if body.PluginsEnabled {
|
| 135 |
+
t.Fatal("plugins_enabled = true, want false")
|
| 136 |
+
}
|
| 137 |
+
entries := map[string]struct {
|
| 138 |
+
Configured bool
|
| 139 |
+
Registered bool
|
| 140 |
+
Enabled bool
|
| 141 |
+
EffectiveEnabled bool
|
| 142 |
+
Path string
|
| 143 |
+
}{}
|
| 144 |
+
for _, item := range body.Plugins {
|
| 145 |
+
entries[item.ID] = struct {
|
| 146 |
+
Configured bool
|
| 147 |
+
Registered bool
|
| 148 |
+
Enabled bool
|
| 149 |
+
EffectiveEnabled bool
|
| 150 |
+
Path string
|
| 151 |
+
}{
|
| 152 |
+
Configured: item.Configured,
|
| 153 |
+
Registered: item.Registered,
|
| 154 |
+
Enabled: item.Enabled,
|
| 155 |
+
EffectiveEnabled: item.EffectiveEnabled,
|
| 156 |
+
Path: item.Path,
|
| 157 |
+
}
|
| 158 |
+
if item.Registered ||
|
| 159 |
+
item.SupportsOAuth ||
|
| 160 |
+
item.OAuthProvider != "" ||
|
| 161 |
+
item.Logo != "" ||
|
| 162 |
+
len(item.ConfigFields) != 0 ||
|
| 163 |
+
len(item.Menus) != 0 {
|
| 164 |
+
t.Fatalf("unregistered plugin entry has runtime fields: %#v", item)
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
if got, ok := entries["scanned"]; !ok || got.Configured || got.Enabled || got.EffectiveEnabled || got.Path == "" {
|
| 168 |
+
t.Fatalf("scanned entry = %#v, exists=%v", got, ok)
|
| 169 |
+
}
|
| 170 |
+
if got, ok := entries["configured-only"]; !ok || !got.Configured || got.Enabled || got.EffectiveEnabled || got.Path != "" {
|
| 171 |
+
t.Fatalf("configured-only entry = %#v, exists=%v", got, ok)
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
func TestListPluginsUsesConfiguredStoreVersionWhenFilesCoexist(t *testing.T) {
|
| 176 |
+
t.Parallel()
|
| 177 |
+
|
| 178 |
+
pluginsDir := t.TempDir()
|
| 179 |
+
archDir := filepath.Join(pluginsDir, runtime.GOOS, runtime.GOARCH)
|
| 180 |
+
if errMkdirAll := os.MkdirAll(archDir, 0o755); errMkdirAll != nil {
|
| 181 |
+
t.Fatalf("MkdirAll(%s) error = %v", archDir, errMkdirAll)
|
| 182 |
+
}
|
| 183 |
+
extension := managementPluginExtension(runtime.GOOS)
|
| 184 |
+
pinnedPath := filepath.Join(archDir, "sample-provider-v0.1.0"+extension)
|
| 185 |
+
newerPath := filepath.Join(archDir, "sample-provider-v0.2.0"+extension)
|
| 186 |
+
for _, path := range []string{pinnedPath, newerPath} {
|
| 187 |
+
if errWriteFile := os.WriteFile(path, []byte("x"), 0o644); errWriteFile != nil {
|
| 188 |
+
t.Fatalf("WriteFile(%s) error = %v", path, errWriteFile)
|
| 189 |
+
}
|
| 190 |
+
}
|
| 191 |
+
h := &Handler{
|
| 192 |
+
cfg: &config.Config{
|
| 193 |
+
Plugins: config.PluginsConfig{
|
| 194 |
+
Enabled: true,
|
| 195 |
+
Dir: pluginsDir,
|
| 196 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 197 |
+
"sample-provider": pluginConfigFromYAML(t, "enabled: true\nstore:\n version: 0.1.0\n"),
|
| 198 |
+
},
|
| 199 |
+
},
|
| 200 |
+
},
|
| 201 |
+
configFilePath: writeTestConfigFile(t),
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
rec := httptest.NewRecorder()
|
| 205 |
+
c, _ := gin.CreateTestContext(rec)
|
| 206 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugins", nil)
|
| 207 |
+
|
| 208 |
+
h.ListPlugins(c)
|
| 209 |
+
|
| 210 |
+
if rec.Code != http.StatusOK {
|
| 211 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 212 |
+
}
|
| 213 |
+
var body pluginListResponse
|
| 214 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 215 |
+
t.Fatalf("decode response: %v; body=%s", errDecode, rec.Body.String())
|
| 216 |
+
}
|
| 217 |
+
for _, entry := range body.Plugins {
|
| 218 |
+
if entry.ID != "sample-provider" {
|
| 219 |
+
continue
|
| 220 |
+
}
|
| 221 |
+
if entry.Path != pinnedPath || !entry.Configured || !entry.Enabled {
|
| 222 |
+
t.Fatalf("plugin entry = %#v, want pinned path %s", entry, pinnedPath)
|
| 223 |
+
}
|
| 224 |
+
return
|
| 225 |
+
}
|
| 226 |
+
t.Fatalf("sample-provider entry missing: %#v", body.Plugins)
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
func TestGetPluginConfigReturnsPreservedRawConfig(t *testing.T) {
|
| 230 |
+
t.Parallel()
|
| 231 |
+
|
| 232 |
+
h := &Handler{
|
| 233 |
+
cfg: &config.Config{
|
| 234 |
+
Plugins: config.PluginsConfig{
|
| 235 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 236 |
+
"sample": pluginConfigFromYAML(t, `
|
| 237 |
+
enabled: false
|
| 238 |
+
priority: 7
|
| 239 |
+
mode: safe
|
| 240 |
+
allowed_models:
|
| 241 |
+
- gemini-2.5-pro
|
| 242 |
+
- claude-sonnet-4
|
| 243 |
+
options:
|
| 244 |
+
retries: 2
|
| 245 |
+
strict: true
|
| 246 |
+
`),
|
| 247 |
+
},
|
| 248 |
+
},
|
| 249 |
+
},
|
| 250 |
+
configFilePath: writeTestConfigFile(t),
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
rec := httptest.NewRecorder()
|
| 254 |
+
c, _ := gin.CreateTestContext(rec)
|
| 255 |
+
c.Params = gin.Params{{Key: "id", Value: "sample"}}
|
| 256 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugins/sample/config", nil)
|
| 257 |
+
|
| 258 |
+
h.GetPluginConfig(c)
|
| 259 |
+
|
| 260 |
+
if rec.Code != http.StatusOK {
|
| 261 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
var body struct {
|
| 265 |
+
Enabled bool `json:"enabled"`
|
| 266 |
+
Priority int `json:"priority"`
|
| 267 |
+
Mode string `json:"mode"`
|
| 268 |
+
AllowedModels []string `json:"allowed_models"`
|
| 269 |
+
Options map[string]any `json:"options"`
|
| 270 |
+
}
|
| 271 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 272 |
+
t.Fatalf("decode response: %v; body=%s", errDecode, rec.Body.String())
|
| 273 |
+
}
|
| 274 |
+
if body.Enabled || body.Priority != 7 || body.Mode != "safe" {
|
| 275 |
+
t.Fatalf("base fields = enabled %v priority %d mode %q, want false 7 safe", body.Enabled, body.Priority, body.Mode)
|
| 276 |
+
}
|
| 277 |
+
if len(body.AllowedModels) != 2 || body.AllowedModels[0] != "gemini-2.5-pro" || body.AllowedModels[1] != "claude-sonnet-4" {
|
| 278 |
+
t.Fatalf("allowed_models = %#v", body.AllowedModels)
|
| 279 |
+
}
|
| 280 |
+
if body.Options["retries"] != float64(2) || body.Options["strict"] != true {
|
| 281 |
+
t.Fatalf("options = %#v", body.Options)
|
| 282 |
+
}
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
func TestGetPluginConfigReturnsEmptyObjectForKnownUnconfiguredPlugin(t *testing.T) {
|
| 286 |
+
t.Parallel()
|
| 287 |
+
|
| 288 |
+
pluginsDir := writeManagementPluginFile(t, "scanned")
|
| 289 |
+
h := &Handler{
|
| 290 |
+
cfg: &config.Config{
|
| 291 |
+
Plugins: config.PluginsConfig{
|
| 292 |
+
Dir: pluginsDir,
|
| 293 |
+
},
|
| 294 |
+
},
|
| 295 |
+
configFilePath: writeTestConfigFile(t),
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
rec := httptest.NewRecorder()
|
| 299 |
+
c, _ := gin.CreateTestContext(rec)
|
| 300 |
+
c.Params = gin.Params{{Key: "id", Value: "scanned"}}
|
| 301 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugins/scanned/config", nil)
|
| 302 |
+
|
| 303 |
+
h.GetPluginConfig(c)
|
| 304 |
+
|
| 305 |
+
if rec.Code != http.StatusOK {
|
| 306 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 307 |
+
}
|
| 308 |
+
var body map[string]any
|
| 309 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 310 |
+
t.Fatalf("decode response: %v; body=%s", errDecode, rec.Body.String())
|
| 311 |
+
}
|
| 312 |
+
if len(body) != 0 {
|
| 313 |
+
t.Fatalf("body = %#v, want empty object", body)
|
| 314 |
+
}
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
func TestGetPluginConfigReturnsNotFoundForUnknownPlugin(t *testing.T) {
|
| 318 |
+
t.Parallel()
|
| 319 |
+
|
| 320 |
+
h := &Handler{
|
| 321 |
+
cfg: &config.Config{},
|
| 322 |
+
configFilePath: writeTestConfigFile(t),
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
rec := httptest.NewRecorder()
|
| 326 |
+
c, _ := gin.CreateTestContext(rec)
|
| 327 |
+
c.Params = gin.Params{{Key: "id", Value: "missing"}}
|
| 328 |
+
c.Request = httptest.NewRequest(http.MethodGet, "/v0/management/plugins/missing/config", nil)
|
| 329 |
+
|
| 330 |
+
h.GetPluginConfig(c)
|
| 331 |
+
|
| 332 |
+
if rec.Code != http.StatusNotFound {
|
| 333 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusNotFound, rec.Body.String())
|
| 334 |
+
}
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
func TestPatchPluginEnabledUpdatesOnlyPluginConfig(t *testing.T) {
|
| 338 |
+
t.Parallel()
|
| 339 |
+
|
| 340 |
+
h := &Handler{
|
| 341 |
+
cfg: &config.Config{
|
| 342 |
+
Plugins: config.PluginsConfig{
|
| 343 |
+
Enabled: false,
|
| 344 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 345 |
+
"sample": pluginConfigFromYAML(t, "enabled: false\npriority: 2\nmode: safe\n"),
|
| 346 |
+
},
|
| 347 |
+
},
|
| 348 |
+
},
|
| 349 |
+
configFilePath: writeTestConfigFile(t),
|
| 350 |
+
}
|
| 351 |
+
reloads, reloadDone := captureConfigReload(h)
|
| 352 |
+
|
| 353 |
+
rec := httptest.NewRecorder()
|
| 354 |
+
c, _ := gin.CreateTestContext(rec)
|
| 355 |
+
c.Params = gin.Params{{Key: "id", Value: "sample"}}
|
| 356 |
+
c.Request = httptest.NewRequest(http.MethodPatch, "/v0/management/plugins/sample/enabled", strings.NewReader(`{"enabled":true}`))
|
| 357 |
+
c.Request.Header.Set("Content-Type", "application/json")
|
| 358 |
+
|
| 359 |
+
h.PatchPluginEnabled(c)
|
| 360 |
+
|
| 361 |
+
if rec.Code != http.StatusOK {
|
| 362 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 363 |
+
}
|
| 364 |
+
cfgSnapshot := waitForAsyncReload(t, reloads)
|
| 365 |
+
waitForReloadDone(t, reloadDone)
|
| 366 |
+
if cfgSnapshot == h.cfg {
|
| 367 |
+
t.Fatalf("reload config = handler config %p, want independent snapshot", h.cfg)
|
| 368 |
+
}
|
| 369 |
+
if cfgSnapshot.Plugins.Enabled {
|
| 370 |
+
t.Fatal("snapshot global Plugins.Enabled changed to true")
|
| 371 |
+
}
|
| 372 |
+
snapshotItem := cfgSnapshot.Plugins.Configs["sample"]
|
| 373 |
+
if snapshotItem.Enabled == nil || !*snapshotItem.Enabled {
|
| 374 |
+
t.Fatalf("snapshot sample enabled = %#v, want true", snapshotItem.Enabled)
|
| 375 |
+
}
|
| 376 |
+
if raw := marshalPluginRaw(t, snapshotItem); !strings.Contains(raw, "mode: safe") {
|
| 377 |
+
t.Fatalf("snapshot raw config lost custom field:\n%s", raw)
|
| 378 |
+
}
|
| 379 |
+
if h.cfg.Plugins.Enabled {
|
| 380 |
+
t.Fatal("global Plugins.Enabled changed to true")
|
| 381 |
+
}
|
| 382 |
+
item := h.cfg.Plugins.Configs["sample"]
|
| 383 |
+
if item.Enabled == nil || !*item.Enabled {
|
| 384 |
+
t.Fatalf("sample enabled = %#v, want true", item.Enabled)
|
| 385 |
+
}
|
| 386 |
+
raw := marshalPluginRaw(t, item)
|
| 387 |
+
if !strings.Contains(raw, "mode: safe") {
|
| 388 |
+
t.Fatalf("raw config lost custom field:\n%s", raw)
|
| 389 |
+
}
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
func TestPatchPluginEnabledReloadSnapshotRawImmutability(t *testing.T) {
|
| 393 |
+
t.Parallel()
|
| 394 |
+
h := &Handler{
|
| 395 |
+
cfg: &config.Config{
|
| 396 |
+
Plugins: config.PluginsConfig{
|
| 397 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 398 |
+
"sample": pluginConfigFromYAML(t, "enabled: false\nmode: first\n"),
|
| 399 |
+
},
|
| 400 |
+
},
|
| 401 |
+
},
|
| 402 |
+
configFilePath: writeTestConfigFile(t),
|
| 403 |
+
}
|
| 404 |
+
reloads := make(chan *config.Config, 1)
|
| 405 |
+
releaseReload := make(chan struct{})
|
| 406 |
+
reloadDone := make(chan struct{})
|
| 407 |
+
h.SetConfigReloadHook(func(_ context.Context, cfg *config.Config) {
|
| 408 |
+
defer close(reloadDone)
|
| 409 |
+
reloads <- cfg
|
| 410 |
+
<-releaseReload
|
| 411 |
+
})
|
| 412 |
+
|
| 413 |
+
rec := httptest.NewRecorder()
|
| 414 |
+
c, _ := gin.CreateTestContext(rec)
|
| 415 |
+
c.Params = gin.Params{{Key: "id", Value: "sample"}}
|
| 416 |
+
c.Request = httptest.NewRequest(http.MethodPatch, "/v0/management/plugins/sample/enabled", strings.NewReader(`{"enabled":true}`))
|
| 417 |
+
c.Request.Header.Set("Content-Type", "application/json")
|
| 418 |
+
|
| 419 |
+
h.PatchPluginEnabled(c)
|
| 420 |
+
|
| 421 |
+
if rec.Code != http.StatusOK {
|
| 422 |
+
close(releaseReload)
|
| 423 |
+
waitForReloadDone(t, reloadDone)
|
| 424 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 425 |
+
}
|
| 426 |
+
cfgSnapshot := waitForAsyncReload(t, reloads)
|
| 427 |
+
|
| 428 |
+
h.mu.Lock()
|
| 429 |
+
item := h.cfg.Plugins.Configs["sample"]
|
| 430 |
+
setPluginRawScalarValue(t, &item.Raw, "mode", "second")
|
| 431 |
+
h.cfg.Plugins.Configs["sample"] = item
|
| 432 |
+
h.mu.Unlock()
|
| 433 |
+
|
| 434 |
+
if cfgSnapshot == h.cfg {
|
| 435 |
+
t.Fatalf("reload config = handler config %p, want independent snapshot", h.cfg)
|
| 436 |
+
}
|
| 437 |
+
snapshotItem := cfgSnapshot.Plugins.Configs["sample"]
|
| 438 |
+
if snapshotItem.Enabled == nil || !*snapshotItem.Enabled {
|
| 439 |
+
t.Fatalf("snapshot sample enabled = %#v, want true", snapshotItem.Enabled)
|
| 440 |
+
}
|
| 441 |
+
if got := pluginRawScalarValue(t, snapshotItem, "mode"); got != "first" {
|
| 442 |
+
t.Fatalf("snapshot raw mode = %q, want first", got)
|
| 443 |
+
}
|
| 444 |
+
h.mu.Lock()
|
| 445 |
+
handlerItem := h.cfg.Plugins.Configs["sample"]
|
| 446 |
+
h.mu.Unlock()
|
| 447 |
+
if got := pluginRawScalarValue(t, handlerItem, "mode"); got != "second" {
|
| 448 |
+
t.Fatalf("handler raw mode = %q, want second", got)
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
close(releaseReload)
|
| 452 |
+
waitForReloadDone(t, reloadDone)
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
func TestPutPluginConfigReplacesPluginConfig(t *testing.T) {
|
| 456 |
+
t.Parallel()
|
| 457 |
+
|
| 458 |
+
h := &Handler{
|
| 459 |
+
cfg: &config.Config{
|
| 460 |
+
Plugins: config.PluginsConfig{
|
| 461 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 462 |
+
"sample": pluginConfigFromYAML(t, "enabled: false\nmode: safe\nold: true\n"),
|
| 463 |
+
},
|
| 464 |
+
},
|
| 465 |
+
},
|
| 466 |
+
configFilePath: writeTestConfigFile(t),
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
rec := httptest.NewRecorder()
|
| 470 |
+
c, _ := gin.CreateTestContext(rec)
|
| 471 |
+
c.Params = gin.Params{{Key: "id", Value: "sample"}}
|
| 472 |
+
c.Request = httptest.NewRequest(http.MethodPut, "/v0/management/plugins/sample/config", bytes.NewBufferString(`{"enabled":true,"priority":7,"mode":"fast"}`))
|
| 473 |
+
c.Request.Header.Set("Content-Type", "application/json")
|
| 474 |
+
|
| 475 |
+
h.PutPluginConfig(c)
|
| 476 |
+
|
| 477 |
+
if rec.Code != http.StatusOK {
|
| 478 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 479 |
+
}
|
| 480 |
+
item := h.cfg.Plugins.Configs["sample"]
|
| 481 |
+
if item.Enabled == nil || !*item.Enabled || item.Priority != 7 {
|
| 482 |
+
t.Fatalf("plugin host fields = enabled %#v priority %d, want true priority 7", item.Enabled, item.Priority)
|
| 483 |
+
}
|
| 484 |
+
raw := marshalPluginRaw(t, item)
|
| 485 |
+
if !strings.Contains(raw, "mode: fast") || strings.Contains(raw, "old:") {
|
| 486 |
+
t.Fatalf("raw config =\n%s", raw)
|
| 487 |
+
}
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
func TestPatchPluginConfigMergesAndDeletesFields(t *testing.T) {
|
| 491 |
+
t.Parallel()
|
| 492 |
+
|
| 493 |
+
h := &Handler{
|
| 494 |
+
cfg: &config.Config{
|
| 495 |
+
Plugins: config.PluginsConfig{
|
| 496 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 497 |
+
"sample": pluginConfigFromYAML(t, "enabled: false\npriority: 3\nmode: safe\nremove: yes\n"),
|
| 498 |
+
},
|
| 499 |
+
},
|
| 500 |
+
},
|
| 501 |
+
configFilePath: writeTestConfigFile(t),
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
rec := httptest.NewRecorder()
|
| 505 |
+
c, _ := gin.CreateTestContext(rec)
|
| 506 |
+
c.Params = gin.Params{{Key: "id", Value: "sample"}}
|
| 507 |
+
c.Request = httptest.NewRequest(http.MethodPatch, "/v0/management/plugins/sample/config", strings.NewReader(`{"mode":"fast","remove":null,"count":3}`))
|
| 508 |
+
c.Request.Header.Set("Content-Type", "application/json")
|
| 509 |
+
|
| 510 |
+
h.PatchPluginConfig(c)
|
| 511 |
+
|
| 512 |
+
if rec.Code != http.StatusOK {
|
| 513 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 514 |
+
}
|
| 515 |
+
item := h.cfg.Plugins.Configs["sample"]
|
| 516 |
+
if item.Enabled == nil || *item.Enabled || item.Priority != 3 {
|
| 517 |
+
t.Fatalf("plugin host fields = enabled %#v priority %d, want false priority 3", item.Enabled, item.Priority)
|
| 518 |
+
}
|
| 519 |
+
raw := marshalPluginRaw(t, item)
|
| 520 |
+
if !strings.Contains(raw, "mode: fast") || !strings.Contains(raw, "count: 3") || strings.Contains(raw, "remove:") {
|
| 521 |
+
t.Fatalf("raw config =\n%s", raw)
|
| 522 |
+
}
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
func TestDeletePluginRejectsUnresolvedPluginsDir(t *testing.T) {
|
| 526 |
+
workspace := t.TempDir()
|
| 527 |
+
t.Setenv("HOME", "")
|
| 528 |
+
t.Setenv("USERPROFILE", "")
|
| 529 |
+
t.Chdir(workspace)
|
| 530 |
+
|
| 531 |
+
literalPluginsDir := filepath.Join(workspace, "~", ".cli-proxy-api", "plugins")
|
| 532 |
+
targetDir := filepath.Join(literalPluginsDir, runtime.GOOS, runtime.GOARCH)
|
| 533 |
+
if errMkdir := os.MkdirAll(targetDir, 0o755); errMkdir != nil {
|
| 534 |
+
t.Fatalf("MkdirAll(%s) error = %v", targetDir, errMkdir)
|
| 535 |
+
}
|
| 536 |
+
target := filepath.Join(targetDir, "sample"+managementPluginExtension(runtime.GOOS))
|
| 537 |
+
if errWrite := os.WriteFile(target, []byte("library-data"), 0o644); errWrite != nil {
|
| 538 |
+
t.Fatalf("WriteFile(%s) error = %v", target, errWrite)
|
| 539 |
+
}
|
| 540 |
+
h := &Handler{
|
| 541 |
+
cfg: &config.Config{
|
| 542 |
+
Plugins: config.PluginsConfig{
|
| 543 |
+
Dir: "~/.cli-proxy-api/plugins",
|
| 544 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 545 |
+
"sample": pluginConfigFromYAML(t, "enabled: false\n"),
|
| 546 |
+
},
|
| 547 |
+
},
|
| 548 |
+
},
|
| 549 |
+
configFilePath: writeTestConfigFile(t),
|
| 550 |
+
}
|
| 551 |
+
rec := httptest.NewRecorder()
|
| 552 |
+
c, _ := gin.CreateTestContext(rec)
|
| 553 |
+
c.Params = gin.Params{{Key: "id", Value: "sample"}}
|
| 554 |
+
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/plugins/sample", nil)
|
| 555 |
+
|
| 556 |
+
h.DeletePlugin(c)
|
| 557 |
+
|
| 558 |
+
if rec.Code != http.StatusInternalServerError {
|
| 559 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusInternalServerError, rec.Body.String())
|
| 560 |
+
}
|
| 561 |
+
var body map[string]any
|
| 562 |
+
if errDecode := json.Unmarshal(rec.Body.Bytes(), &body); errDecode != nil {
|
| 563 |
+
t.Fatalf("Unmarshal() error = %v; body=%s", errDecode, rec.Body.String())
|
| 564 |
+
}
|
| 565 |
+
if body["error"] != "plugin_directory_invalid" {
|
| 566 |
+
t.Fatalf("error = %#v, want plugin_directory_invalid", body["error"])
|
| 567 |
+
}
|
| 568 |
+
if _, errStat := os.Stat(target); errStat != nil {
|
| 569 |
+
t.Fatalf("literal tilde target stat error = %v, want retained", errStat)
|
| 570 |
+
}
|
| 571 |
+
if _, configured := h.cfg.Plugins.Configs["sample"]; !configured {
|
| 572 |
+
t.Fatal("plugin config removed after directory resolution failure")
|
| 573 |
+
}
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
func TestDeletePluginRemovesDiscoveredFileAndConfig(t *testing.T) {
|
| 577 |
+
t.Parallel()
|
| 578 |
+
|
| 579 |
+
pluginsDir := writeManagementPluginFile(t, "sample")
|
| 580 |
+
configPath := filepath.Join(t.TempDir(), "config.yaml")
|
| 581 |
+
if errWrite := os.WriteFile(configPath, []byte("plugins:\n configs:\n sample:\n enabled: true\n mode: safe\n keep:\n enabled: true\n mode: retained\n"), 0o600); errWrite != nil {
|
| 582 |
+
t.Fatalf("failed to write test config: %v", errWrite)
|
| 583 |
+
}
|
| 584 |
+
h := &Handler{
|
| 585 |
+
cfg: &config.Config{
|
| 586 |
+
Plugins: config.PluginsConfig{
|
| 587 |
+
Dir: pluginsDir,
|
| 588 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 589 |
+
"sample": pluginConfigFromYAML(t, "enabled: true\nmode: safe\n"),
|
| 590 |
+
"keep": pluginConfigFromYAML(t, "enabled: true\nmode: retained\n"),
|
| 591 |
+
},
|
| 592 |
+
},
|
| 593 |
+
},
|
| 594 |
+
configFilePath: configPath,
|
| 595 |
+
}
|
| 596 |
+
reloads := make(chan *config.Config, 1)
|
| 597 |
+
releaseReload := make(chan struct{})
|
| 598 |
+
reloadDone := make(chan struct{})
|
| 599 |
+
h.SetConfigReloadHook(func(_ context.Context, cfg *config.Config) {
|
| 600 |
+
defer close(reloadDone)
|
| 601 |
+
reloads <- cfg
|
| 602 |
+
<-releaseReload
|
| 603 |
+
})
|
| 604 |
+
|
| 605 |
+
path, errPath := pluginFilePath(pluginsDir, "sample")
|
| 606 |
+
if errPath != nil {
|
| 607 |
+
t.Fatalf("pluginFilePath() error = %v", errPath)
|
| 608 |
+
}
|
| 609 |
+
if path == "" {
|
| 610 |
+
t.Fatal("plugin path is empty")
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
+
rec := httptest.NewRecorder()
|
| 614 |
+
c, _ := gin.CreateTestContext(rec)
|
| 615 |
+
c.Params = gin.Params{{Key: "id", Value: "sample"}}
|
| 616 |
+
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/plugins/sample", nil)
|
| 617 |
+
|
| 618 |
+
done := make(chan struct{})
|
| 619 |
+
go func() {
|
| 620 |
+
h.DeletePlugin(c)
|
| 621 |
+
close(done)
|
| 622 |
+
}()
|
| 623 |
+
|
| 624 |
+
select {
|
| 625 |
+
case <-done:
|
| 626 |
+
case <-time.After(time.Second):
|
| 627 |
+
t.Fatal("DeletePlugin blocked waiting for config reload")
|
| 628 |
+
}
|
| 629 |
+
|
| 630 |
+
if rec.Code != http.StatusOK {
|
| 631 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 632 |
+
}
|
| 633 |
+
if _, ok := h.cfg.Plugins.Configs["sample"]; ok {
|
| 634 |
+
t.Fatal("plugin config still exists after delete")
|
| 635 |
+
}
|
| 636 |
+
if _, ok := h.cfg.Plugins.Configs["keep"]; !ok {
|
| 637 |
+
t.Fatal("retained plugin config was removed")
|
| 638 |
+
}
|
| 639 |
+
data, errReadConfig := os.ReadFile(configPath)
|
| 640 |
+
if errReadConfig != nil {
|
| 641 |
+
t.Fatalf("failed to read saved config: %v", errReadConfig)
|
| 642 |
+
}
|
| 643 |
+
text := string(data)
|
| 644 |
+
if strings.Contains(text, "sample:") || strings.Contains(text, "mode: safe") {
|
| 645 |
+
t.Fatalf("saved config still contains removed plugin:\n%s", text)
|
| 646 |
+
}
|
| 647 |
+
if !strings.Contains(text, "keep:") || !strings.Contains(text, "mode: retained") {
|
| 648 |
+
t.Fatalf("saved config lost retained plugin:\n%s", text)
|
| 649 |
+
}
|
| 650 |
+
if _, errStat := os.Stat(path); !os.IsNotExist(errStat) {
|
| 651 |
+
t.Fatalf("plugin file stat error = %v, want not exist", errStat)
|
| 652 |
+
}
|
| 653 |
+
cfgSnapshot := waitForAsyncReload(t, reloads)
|
| 654 |
+
if cfgSnapshot == h.cfg {
|
| 655 |
+
close(releaseReload)
|
| 656 |
+
waitForReloadDone(t, reloadDone)
|
| 657 |
+
t.Fatalf("reload config = handler config %p, want independent snapshot", h.cfg)
|
| 658 |
+
}
|
| 659 |
+
if _, ok := cfgSnapshot.Plugins.Configs["sample"]; ok {
|
| 660 |
+
close(releaseReload)
|
| 661 |
+
waitForReloadDone(t, reloadDone)
|
| 662 |
+
t.Fatal("snapshot plugin config still exists after delete")
|
| 663 |
+
}
|
| 664 |
+
close(releaseReload)
|
| 665 |
+
waitForReloadDone(t, reloadDone)
|
| 666 |
+
}
|
| 667 |
+
|
| 668 |
+
func TestDeletePluginUsesConfiguredStoreVersionWhenFilesCoexist(t *testing.T) {
|
| 669 |
+
t.Parallel()
|
| 670 |
+
|
| 671 |
+
pluginsDir := t.TempDir()
|
| 672 |
+
archDir := filepath.Join(pluginsDir, runtime.GOOS, runtime.GOARCH)
|
| 673 |
+
if errMkdirAll := os.MkdirAll(archDir, 0o755); errMkdirAll != nil {
|
| 674 |
+
t.Fatalf("MkdirAll(%s) error = %v", archDir, errMkdirAll)
|
| 675 |
+
}
|
| 676 |
+
extension := managementPluginExtension(runtime.GOOS)
|
| 677 |
+
pinnedPath := filepath.Join(archDir, "sample-provider-v0.1.0"+extension)
|
| 678 |
+
newerPath := filepath.Join(archDir, "sample-provider-v0.2.0"+extension)
|
| 679 |
+
for _, path := range []string{pinnedPath, newerPath} {
|
| 680 |
+
if errWriteFile := os.WriteFile(path, []byte("x"), 0o644); errWriteFile != nil {
|
| 681 |
+
t.Fatalf("WriteFile(%s) error = %v", path, errWriteFile)
|
| 682 |
+
}
|
| 683 |
+
}
|
| 684 |
+
h := &Handler{
|
| 685 |
+
cfg: &config.Config{
|
| 686 |
+
Plugins: config.PluginsConfig{
|
| 687 |
+
Dir: pluginsDir,
|
| 688 |
+
Configs: map[string]config.PluginInstanceConfig{
|
| 689 |
+
"sample-provider": pluginConfigFromYAML(t, "enabled: true\nstore:\n version: 0.1.0\n"),
|
| 690 |
+
},
|
| 691 |
+
},
|
| 692 |
+
},
|
| 693 |
+
configFilePath: writeTestConfigFile(t),
|
| 694 |
+
}
|
| 695 |
+
|
| 696 |
+
rec := httptest.NewRecorder()
|
| 697 |
+
c, _ := gin.CreateTestContext(rec)
|
| 698 |
+
c.Params = gin.Params{{Key: "id", Value: "sample-provider"}}
|
| 699 |
+
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/plugins/sample-provider", nil)
|
| 700 |
+
|
| 701 |
+
h.DeletePlugin(c)
|
| 702 |
+
|
| 703 |
+
if rec.Code != http.StatusOK {
|
| 704 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusOK, rec.Body.String())
|
| 705 |
+
}
|
| 706 |
+
if _, ok := h.cfg.Plugins.Configs["sample-provider"]; ok {
|
| 707 |
+
t.Fatal("plugin config still exists after delete")
|
| 708 |
+
}
|
| 709 |
+
if _, errStat := os.Stat(pinnedPath); !os.IsNotExist(errStat) {
|
| 710 |
+
t.Fatalf("pinned plugin stat error = %v, want not exist", errStat)
|
| 711 |
+
}
|
| 712 |
+
if _, errStat := os.Stat(newerPath); errStat != nil {
|
| 713 |
+
t.Fatalf("newer plugin stat error = %v, want still exists", errStat)
|
| 714 |
+
}
|
| 715 |
+
}
|
| 716 |
+
|
| 717 |
+
func TestDeletePluginReturnsNotFoundForUnknownPlugin(t *testing.T) {
|
| 718 |
+
t.Parallel()
|
| 719 |
+
|
| 720 |
+
h := &Handler{
|
| 721 |
+
cfg: &config.Config{},
|
| 722 |
+
configFilePath: writeTestConfigFile(t),
|
| 723 |
+
}
|
| 724 |
+
|
| 725 |
+
rec := httptest.NewRecorder()
|
| 726 |
+
c, _ := gin.CreateTestContext(rec)
|
| 727 |
+
c.Params = gin.Params{{Key: "id", Value: "missing"}}
|
| 728 |
+
c.Request = httptest.NewRequest(http.MethodDelete, "/v0/management/plugins/missing", nil)
|
| 729 |
+
|
| 730 |
+
h.DeletePlugin(c)
|
| 731 |
+
|
| 732 |
+
if rec.Code != http.StatusNotFound {
|
| 733 |
+
t.Fatalf("status = %d, want %d; body=%s", rec.Code, http.StatusNotFound, rec.Body.String())
|
| 734 |
+
}
|
| 735 |
+
}
|
| 736 |
+
|
| 737 |
+
func TestPluginDisplayFieldsEscapeHTML(t *testing.T) {
|
| 738 |
+
t.Parallel()
|
| 739 |
+
|
| 740 |
+
fields := pluginConfigFields([]pluginapi.ConfigField{{
|
| 741 |
+
Name: `<img src=x onerror=alert(1)>`,
|
| 742 |
+
Type: pluginapi.ConfigFieldTypeEnum,
|
| 743 |
+
EnumValues: []string{`<fast>`, `safe & sound`},
|
| 744 |
+
Description: `"quoted" 'single' <b>mode</b>`,
|
| 745 |
+
}})
|
| 746 |
+
if len(fields) != 1 {
|
| 747 |
+
t.Fatalf("fields len = %d, want 1", len(fields))
|
| 748 |
+
}
|
| 749 |
+
if fields[0].Name != html.EscapeString(`<img src=x onerror=alert(1)>`) {
|
| 750 |
+
t.Fatalf("field name = %q, want escaped", fields[0].Name)
|
| 751 |
+
}
|
| 752 |
+
if fields[0].EnumValues[0] != html.EscapeString(`<fast>`) || fields[0].EnumValues[1] != html.EscapeString(`safe & sound`) {
|
| 753 |
+
t.Fatalf("enum values = %#v, want escaped values", fields[0].EnumValues)
|
| 754 |
+
}
|
| 755 |
+
if fields[0].Description != html.EscapeString(`"quoted" 'single' <b>mode</b>`) {
|
| 756 |
+
t.Fatalf("description = %q, want escaped", fields[0].Description)
|
| 757 |
+
}
|
| 758 |
+
|
| 759 |
+
menus := pluginMenus([]pluginhost.RegisteredPluginMenu{{
|
| 760 |
+
Path: `/v0/resource/plugins/sample/<status>`,
|
| 761 |
+
Menu: `<b>Status</b>`,
|
| 762 |
+
Description: `Shows <script>alert(1)</script>.`,
|
| 763 |
+
}})
|
| 764 |
+
if len(menus) != 1 {
|
| 765 |
+
t.Fatalf("menus len = %d, want 1", len(menus))
|
| 766 |
+
}
|
| 767 |
+
if menus[0].Path != html.EscapeString(`/v0/resource/plugins/sample/<status>`) ||
|
| 768 |
+
menus[0].Menu != html.EscapeString(`<b>Status</b>`) ||
|
| 769 |
+
menus[0].Description != html.EscapeString(`Shows <script>alert(1)</script>.`) {
|
| 770 |
+
t.Fatalf("menu = %#v, want escaped strings", menus[0])
|
| 771 |
+
}
|
| 772 |
+
|
| 773 |
+
meta := pluginMetadata(pluginapi.Metadata{
|
| 774 |
+
Name: `<script>alert(1)</script>`,
|
| 775 |
+
Version: `1.0.0&evil=true`,
|
| 776 |
+
Author: `"attacker"`,
|
| 777 |
+
GitHubRepository: `https://example.com/repo?x=<script>`,
|
| 778 |
+
Logo: `<svg onload=alert(1)>`,
|
| 779 |
+
})
|
| 780 |
+
if meta.Name != html.EscapeString(`<script>alert(1)</script>`) ||
|
| 781 |
+
meta.Version != html.EscapeString(`1.0.0&evil=true`) ||
|
| 782 |
+
meta.Author != html.EscapeString(`"attacker"`) ||
|
| 783 |
+
meta.GitHubRepository != html.EscapeString(`https://example.com/repo?x=<script>`) ||
|
| 784 |
+
meta.Logo != html.EscapeString(`<svg onload=alert(1)>`) {
|
| 785 |
+
t.Fatalf("metadata = %#v, want escaped strings", meta)
|
| 786 |
+
}
|
| 787 |
+
}
|
| 788 |
+
|
| 789 |
+
func writeManagementPluginFile(t *testing.T, id string) string {
|
| 790 |
+
t.Helper()
|
| 791 |
+
root := t.TempDir()
|
| 792 |
+
archDir := filepath.Join(root, runtime.GOOS, runtime.GOARCH)
|
| 793 |
+
if errMkdirAll := os.MkdirAll(archDir, 0o755); errMkdirAll != nil {
|
| 794 |
+
t.Fatalf("MkdirAll() error = %v", errMkdirAll)
|
| 795 |
+
}
|
| 796 |
+
path := filepath.Join(archDir, id+managementPluginExtension(runtime.GOOS))
|
| 797 |
+
if errWriteFile := os.WriteFile(path, []byte("x"), 0o644); errWriteFile != nil {
|
| 798 |
+
t.Fatalf("WriteFile(%s) error = %v", path, errWriteFile)
|
| 799 |
+
}
|
| 800 |
+
return root
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
func managementPluginExtension(goos string) string {
|
| 804 |
+
switch goos {
|
| 805 |
+
case "darwin":
|
| 806 |
+
return ".dylib"
|
| 807 |
+
case "windows":
|
| 808 |
+
return ".dll"
|
| 809 |
+
default:
|
| 810 |
+
return ".so"
|
| 811 |
+
}
|
| 812 |
+
}
|
| 813 |
+
|
| 814 |
+
func pluginConfigFromYAML(t *testing.T, text string) config.PluginInstanceConfig {
|
| 815 |
+
t.Helper()
|
| 816 |
+
var item config.PluginInstanceConfig
|
| 817 |
+
if errUnmarshal := yaml.Unmarshal([]byte(text), &item); errUnmarshal != nil {
|
| 818 |
+
t.Fatalf("unmarshal plugin config: %v", errUnmarshal)
|
| 819 |
+
}
|
| 820 |
+
return item
|
| 821 |
+
}
|
| 822 |
+
|
| 823 |
+
func marshalPluginRaw(t *testing.T, item config.PluginInstanceConfig) string {
|
| 824 |
+
t.Helper()
|
| 825 |
+
data, errMarshal := yaml.Marshal(&item.Raw)
|
| 826 |
+
if errMarshal != nil {
|
| 827 |
+
t.Fatalf("marshal plugin raw: %v", errMarshal)
|
| 828 |
+
}
|
| 829 |
+
return string(data)
|
| 830 |
+
}
|
| 831 |
+
|
| 832 |
+
func pluginRawScalarValue(t *testing.T, item config.PluginInstanceConfig, key string) string {
|
| 833 |
+
t.Helper()
|
| 834 |
+
for i := 0; i+1 < len(item.Raw.Content); i += 2 {
|
| 835 |
+
if item.Raw.Content[i] != nil && item.Raw.Content[i].Value == key && item.Raw.Content[i+1] != nil {
|
| 836 |
+
return item.Raw.Content[i+1].Value
|
| 837 |
+
}
|
| 838 |
+
}
|
| 839 |
+
t.Fatalf("plugin raw missing scalar key %q", key)
|
| 840 |
+
return ""
|
| 841 |
+
}
|
| 842 |
+
|
| 843 |
+
func setPluginRawScalarValue(t *testing.T, node *yaml.Node, key, value string) {
|
| 844 |
+
t.Helper()
|
| 845 |
+
for i := 0; i+1 < len(node.Content); i += 2 {
|
| 846 |
+
if node.Content[i] != nil && node.Content[i].Value == key && node.Content[i+1] != nil {
|
| 847 |
+
node.Content[i+1].Value = value
|
| 848 |
+
return
|
| 849 |
+
}
|
| 850 |
+
}
|
| 851 |
+
t.Fatalf("plugin raw missing scalar key %q", key)
|
| 852 |
+
}
|
internal/api/handlers/management/quota.go
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"fmt"
|
| 5 |
+
"net/http"
|
| 6 |
+
"strings"
|
| 7 |
+
|
| 8 |
+
"github.com/gin-gonic/gin"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
// Quota exceeded toggles
|
| 12 |
+
func (h *Handler) GetSwitchProject(c *gin.Context) {
|
| 13 |
+
c.JSON(200, gin.H{"switch-project": h.cfg.QuotaExceeded.SwitchProject})
|
| 14 |
+
}
|
| 15 |
+
func (h *Handler) PutSwitchProject(c *gin.Context) {
|
| 16 |
+
h.updateBoolField(c, func(v bool) { h.cfg.QuotaExceeded.SwitchProject = v })
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
func (h *Handler) GetSwitchPreviewModel(c *gin.Context) {
|
| 20 |
+
c.JSON(200, gin.H{"switch-preview-model": h.cfg.QuotaExceeded.SwitchPreviewModel})
|
| 21 |
+
}
|
| 22 |
+
func (h *Handler) PutSwitchPreviewModel(c *gin.Context) {
|
| 23 |
+
h.updateBoolField(c, func(v bool) { h.cfg.QuotaExceeded.SwitchPreviewModel = v })
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
// ResetQuota clears quota/cooldown routing state for one auth index.
|
| 27 |
+
func (h *Handler) ResetQuota(c *gin.Context) {
|
| 28 |
+
if h.authManager == nil {
|
| 29 |
+
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "core auth manager unavailable"})
|
| 30 |
+
return
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
var req struct {
|
| 34 |
+
AuthIndex string `json:"auth_index"`
|
| 35 |
+
}
|
| 36 |
+
if errBindJSON := c.ShouldBindJSON(&req); errBindJSON != nil {
|
| 37 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
| 38 |
+
return
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
authIndex := strings.TrimSpace(req.AuthIndex)
|
| 42 |
+
if authIndex == "" {
|
| 43 |
+
c.JSON(http.StatusBadRequest, gin.H{"error": "auth_index is required"})
|
| 44 |
+
return
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
auth := h.authByIndex(authIndex)
|
| 48 |
+
if auth == nil {
|
| 49 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "auth not found"})
|
| 50 |
+
return
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
updated, models, errReset := h.authManager.ResetQuota(c.Request.Context(), auth.ID)
|
| 54 |
+
if errReset != nil {
|
| 55 |
+
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to reset quota: %v", errReset)})
|
| 56 |
+
return
|
| 57 |
+
}
|
| 58 |
+
if updated == nil {
|
| 59 |
+
c.JSON(http.StatusNotFound, gin.H{"error": "auth not found"})
|
| 60 |
+
return
|
| 61 |
+
}
|
| 62 |
+
updated.EnsureIndex()
|
| 63 |
+
|
| 64 |
+
c.JSON(http.StatusOK, gin.H{
|
| 65 |
+
"status": "ok",
|
| 66 |
+
"auth_index": updated.Index,
|
| 67 |
+
"models": models,
|
| 68 |
+
})
|
| 69 |
+
}
|
internal/api/handlers/management/quota_test.go
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package management
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"encoding/json"
|
| 6 |
+
"net/http"
|
| 7 |
+
"net/http/httptest"
|
| 8 |
+
"strings"
|
| 9 |
+
"testing"
|
| 10 |
+
"time"
|
| 11 |
+
|
| 12 |
+
"github.com/gin-gonic/gin"
|
| 13 |
+
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
|
| 14 |
+
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
func TestResetQuota_UsesAuthIndex(t *testing.T) {
|
| 18 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 19 |
+
|
| 20 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 21 |
+
next := time.Now().Add(time.Hour)
|
| 22 |
+
auth := &coreauth.Auth{
|
| 23 |
+
ID: "reset-auth-id",
|
| 24 |
+
FileName: "reset-auth-file.json",
|
| 25 |
+
Provider: "claude",
|
| 26 |
+
Status: coreauth.StatusError,
|
| 27 |
+
StatusMessage: "quota exhausted",
|
| 28 |
+
Unavailable: true,
|
| 29 |
+
NextRetryAfter: next,
|
| 30 |
+
Quota: coreauth.QuotaState{Exceeded: true, Reason: "quota", NextRecoverAt: next, BackoffLevel: 2},
|
| 31 |
+
ModelStates: map[string]*coreauth.ModelState{
|
| 32 |
+
"claude-reset-model": {
|
| 33 |
+
Status: coreauth.StatusError,
|
| 34 |
+
StatusMessage: "quota exhausted",
|
| 35 |
+
Unavailable: true,
|
| 36 |
+
NextRetryAfter: next,
|
| 37 |
+
Quota: coreauth.QuotaState{Exceeded: true, Reason: "quota", NextRecoverAt: next, BackoffLevel: 2},
|
| 38 |
+
},
|
| 39 |
+
},
|
| 40 |
+
}
|
| 41 |
+
authIndex := auth.EnsureIndex()
|
| 42 |
+
if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil {
|
| 43 |
+
t.Fatalf("failed to register auth record: %v", errRegister)
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
| 47 |
+
|
| 48 |
+
rec := httptest.NewRecorder()
|
| 49 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 50 |
+
req := httptest.NewRequest(http.MethodPost, "/v0/management/reset-quota", strings.NewReader(`{"auth_index":"`+authIndex+`"}`))
|
| 51 |
+
req.Header.Set("Content-Type", "application/json")
|
| 52 |
+
ctx.Request = req
|
| 53 |
+
h.ResetQuota(ctx)
|
| 54 |
+
|
| 55 |
+
if rec.Code != http.StatusOK {
|
| 56 |
+
t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String())
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
var payload map[string]any
|
| 60 |
+
if errUnmarshal := json.Unmarshal(rec.Body.Bytes(), &payload); errUnmarshal != nil {
|
| 61 |
+
t.Fatalf("failed to decode response: %v", errUnmarshal)
|
| 62 |
+
}
|
| 63 |
+
if payload["auth_index"] != authIndex {
|
| 64 |
+
t.Fatalf("auth_index = %#v, want %q", payload["auth_index"], authIndex)
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
updated, ok := manager.GetByID("reset-auth-id")
|
| 68 |
+
if !ok || updated == nil {
|
| 69 |
+
t.Fatalf("expected auth record to exist after reset")
|
| 70 |
+
}
|
| 71 |
+
if updated.Status != coreauth.StatusActive || updated.StatusMessage != "" || updated.Unavailable || !updated.NextRetryAfter.IsZero() {
|
| 72 |
+
t.Fatalf("updated auth state = status %q message %q unavailable %v next %v", updated.Status, updated.StatusMessage, updated.Unavailable, updated.NextRetryAfter)
|
| 73 |
+
}
|
| 74 |
+
if updated.Quota.Exceeded || updated.Quota.Reason != "" || !updated.Quota.NextRecoverAt.IsZero() || updated.Quota.BackoffLevel != 0 {
|
| 75 |
+
t.Fatalf("updated auth quota = %+v, want cleared", updated.Quota)
|
| 76 |
+
}
|
| 77 |
+
state := updated.ModelStates["claude-reset-model"]
|
| 78 |
+
if state == nil {
|
| 79 |
+
t.Fatalf("expected model state to remain")
|
| 80 |
+
}
|
| 81 |
+
if state.Status != coreauth.StatusActive || state.StatusMessage != "" || state.Unavailable || !state.NextRetryAfter.IsZero() {
|
| 82 |
+
t.Fatalf("updated model state = status %q message %q unavailable %v next %v", state.Status, state.StatusMessage, state.Unavailable, state.NextRetryAfter)
|
| 83 |
+
}
|
| 84 |
+
if state.Quota.Exceeded || state.Quota.Reason != "" || !state.Quota.NextRecoverAt.IsZero() || state.Quota.BackoffLevel != 0 {
|
| 85 |
+
t.Fatalf("updated model quota = %+v, want cleared", state.Quota)
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
func TestResetQuota_DoesNotAcceptAuthIDOrFileName(t *testing.T) {
|
| 90 |
+
t.Setenv("MANAGEMENT_PASSWORD", "")
|
| 91 |
+
|
| 92 |
+
manager := coreauth.NewManager(nil, nil, nil)
|
| 93 |
+
auth := &coreauth.Auth{
|
| 94 |
+
ID: "reset-auth-id-only",
|
| 95 |
+
FileName: "reset-auth-file-only.json",
|
| 96 |
+
Provider: "claude",
|
| 97 |
+
Status: coreauth.StatusError,
|
| 98 |
+
}
|
| 99 |
+
authIndex := auth.EnsureIndex()
|
| 100 |
+
if authIndex == auth.ID || authIndex == auth.FileName {
|
| 101 |
+
t.Fatalf("test auth_index unexpectedly matches id or file name: %q", authIndex)
|
| 102 |
+
}
|
| 103 |
+
if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil {
|
| 104 |
+
t.Fatalf("failed to register auth record: %v", errRegister)
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
|
| 108 |
+
|
| 109 |
+
tests := []struct {
|
| 110 |
+
name string
|
| 111 |
+
body string
|
| 112 |
+
wantCode int
|
| 113 |
+
}{
|
| 114 |
+
{name: "auth_id field ignored", body: `{"auth_id":"reset-auth-id-only"}`, wantCode: http.StatusBadRequest},
|
| 115 |
+
{name: "id field ignored", body: `{"id":"reset-auth-id-only"}`, wantCode: http.StatusBadRequest},
|
| 116 |
+
{name: "file name is not an index", body: `{"auth_index":"reset-auth-file-only.json"}`, wantCode: http.StatusNotFound},
|
| 117 |
+
{name: "auth id is not an index", body: `{"auth_index":"reset-auth-id-only"}`, wantCode: http.StatusNotFound},
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
for _, tt := range tests {
|
| 121 |
+
t.Run(tt.name, func(t *testing.T) {
|
| 122 |
+
rec := httptest.NewRecorder()
|
| 123 |
+
ctx, _ := gin.CreateTestContext(rec)
|
| 124 |
+
req := httptest.NewRequest(http.MethodPost, "/v0/management/reset-quota", strings.NewReader(tt.body))
|
| 125 |
+
req.Header.Set("Content-Type", "application/json")
|
| 126 |
+
ctx.Request = req
|
| 127 |
+
h.ResetQuota(ctx)
|
| 128 |
+
|
| 129 |
+
if rec.Code != tt.wantCode {
|
| 130 |
+
t.Fatalf("status = %d, want %d with body %s", rec.Code, tt.wantCode, rec.Body.String())
|
| 131 |
+
}
|
| 132 |
+
})
|
| 133 |
+
}
|
| 134 |
+
}
|