From 2f0d3197c01711f151e2cf747a5e6902f233fa44 Mon Sep 17 00:00:00 2001 From: bntvllnt <32437578+bntvllnt@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:41:26 +0000 Subject: [PATCH 1/8] feat(auth): add Mistral Vibe browser sign-in client Adds internal/auth/mistral: PKCE S256 sign-in (start, poll, exchange) against the Mistral console API, origin and path validation of returned URLs, no-redirect HTTP client, and credential metadata/file naming that keeps the API key out of names and labels. --- internal/auth/mistral/mistral.go | 558 ++++++++++++++++++++++++++ internal/auth/mistral/mistral_test.go | 511 +++++++++++++++++++++++ 2 files changed, 1069 insertions(+) create mode 100644 internal/auth/mistral/mistral.go create mode 100644 internal/auth/mistral/mistral_test.go diff --git a/internal/auth/mistral/mistral.go b/internal/auth/mistral/mistral.go new file mode 100644 index 00000000000..cd261478c70 --- /dev/null +++ b/internal/auth/mistral/mistral.go @@ -0,0 +1,558 @@ +// Package mistral implements the Mistral Vibe browser sign-in used by Le Chat Pro +// and Vibe plans. The flow is PKCE based: the client starts a sign-in process, +// the user approves it in a browser, and the client polls until it can exchange +// the approval for a long-lived Mistral API key. The key never expires and has +// no refresh token. +package mistral + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "path" + "strings" + "sync" + "time" + "unicode" + + "github.com/MoeForge/moego/base64" + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/util" + log "github.com/sirupsen/logrus" +) + +const ( + // DefaultSignInBaseURL is the unauthenticated Mistral console API that runs the sign-in flow. + DefaultSignInBaseURL = "https://console.mistral.ai/api" + // DefaultAPIBaseURL is the OpenAI-compatible Mistral inference API. + DefaultAPIBaseURL = "https://api.mistral.ai/v1" + // DefaultPollInterval is how often the sign-in status is polled. + DefaultPollInterval = 3 * time.Second + // MaxSignInDuration bounds the wait for browser approval when the server + // reports no usable expiry. Mistral sign-in processes live about ten minutes. + MaxSignInDuration = 15 * time.Minute + + // WorkspaceNotEligibleMessage is shown when the chosen workspace cannot create Vibe keys. + WorkspaceNotEligibleMessage = "Your current workspace can't be used for Mistral Vibe. " + + "Sign in again and select another workspace in the browser, or contact your administrator." + + // httpClientTimeout bounds each credential-acquisition HTTP call. + httpClientTimeout = 30 * time.Second + // maxConsecutivePollFailures matches Vibe: transient poll failures are retried this many times. + maxConsecutivePollFailures = 3 + // maxResponseBytes caps every response body read from the sign-in API. + maxResponseBytes = 1 << 20 + // maxDetailLength caps server-provided text echoed into errors. + maxDetailLength = 200 + // codeVerifierBytes matches Vibe's secrets.token_urlsafe(64). + codeVerifierBytes = 64 + // workspaceNotEligibleCode is the exchange error_code for ineligible workspaces. + workspaceNotEligibleCode = 9004 + // userAgent is a neutral client identifier; the sign-in API needs no vendor identity. + userAgent = "cli-proxy-api" +) + +// Sign-in outcomes callers can match with errors.Is. +var ( + ErrExpired = errors.New("sign-in expired") + ErrDenied = errors.New("sign-in was denied") + ErrProviderError = errors.New("sign-in failed") + ErrUnknownStatus = errors.New("sign-in returned an unknown status") + ErrMissingExchangeToken = errors.New("sign-in completed without an exchange token") + ErrMissingAPIKey = errors.New("exchange did not return an API key") + ErrWorkspaceNotEligible = errors.New(WorkspaceNotEligibleMessage) + ErrUntrustedURL = errors.New("sign-in URL does not belong to the Mistral sign-in service") +) + +// endpoints holds the process-wide sign-in settings. They exist so tests in other +// packages can point the real client at a fake server; production never changes them. +var ( + endpointMu sync.RWMutex + signInBaseURL = DefaultSignInBaseURL + apiBaseURL = DefaultAPIBaseURL + pollInterval = DefaultPollInterval +) + +// OverrideEndpointsForTest points sign-in at a fake server, sets the inference base URL +// written into new credentials, and shortens the poll interval. It returns a restore function. +func OverrideEndpointsForTest(signIn, api string, interval time.Duration) func() { + endpointMu.Lock() + prevSignIn, prevAPI, prevInterval := signInBaseURL, apiBaseURL, pollInterval + signInBaseURL, apiBaseURL, pollInterval = signIn, api, interval + endpointMu.Unlock() + return func() { + endpointMu.Lock() + signInBaseURL, apiBaseURL, pollInterval = prevSignIn, prevAPI, prevInterval + endpointMu.Unlock() + } +} + +// SignIn is a started browser sign-in. Show URL to the user, then pass it to WaitForSignIn. +type SignIn struct { + // ProcessID identifies the server-side sign-in process. + ProcessID string + // URL is the page the user opens to approve the sign-in. It is a bearer-like + // link and must not be logged. + URL string + // PollURL is the status endpoint polled until approval. + PollURL string + // Lifetime is how long the user has to approve, clamped to a sane range. + Lifetime time.Duration + + codeVerifier string +} + +// Credential is the API key a completed sign-in provisions. +type Credential struct { + APIKey string + BaseURL string +} + +// MistralAuth runs the Mistral browser sign-in. +type MistralAuth struct { + httpClient *http.Client + signInBase string + apiBase string + pollInterval time.Duration +} + +// NewMistralAuth creates a MistralAuth that uses the configured proxy. +func NewMistralAuth(cfg *config.Config) *MistralAuth { + return NewMistralAuthWithProxyURL(cfg, "") +} + +// NewMistralAuthWithProxyURL creates a MistralAuth with an optional per-call proxy URL. +func NewMistralAuthWithProxyURL(cfg *config.Config, proxyURL string) *MistralAuth { + effectiveProxyURL := strings.TrimSpace(proxyURL) + var sdkCfg config.SDKConfig + if cfg != nil { + sdkCfg = cfg.SDKConfig + if effectiveProxyURL == "" { + effectiveProxyURL = strings.TrimSpace(cfg.ProxyURL) + } + } + sdkCfg.ProxyURL = effectiveProxyURL + + client := &http.Client{ + Timeout: httpClientTimeout, + // Never follow redirects: the exchange request carries the PKCE verifier. + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } + + endpointMu.RLock() + defer endpointMu.RUnlock() + return &MistralAuth{ + httpClient: util.SetProxy(&sdkCfg, client), + signInBase: strings.TrimRight(strings.TrimSpace(signInBaseURL), "/"), + apiBase: strings.TrimSpace(apiBaseURL), + pollInterval: pollInterval, + } +} + +// StartSignIn creates a sign-in process and returns the URL the user must open. +func (a *MistralAuth) StartSignIn(ctx context.Context) (*SignIn, error) { + if ctx == nil { + ctx = context.Background() + } + verifier, err := newCodeVerifier() + if err != nil { + return nil, fmt.Errorf("mistral sign-in: %w", err) + } + + doc := ojson.NewDocString("{}") + if err = doc.Set("code_challenge", codeChallenge(verifier)); err != nil { + return nil, fmt.Errorf("mistral sign-in: encode request: %w", err) + } + if err = doc.Set("code_challenge_method", "S256"); err != nil { + return nil, fmt.Errorf("mistral sign-in: encode request: %w", err) + } + + status, body, err := a.doJSON(ctx, http.MethodPost, a.signInBase+"/vibe/sign-in", doc.Bytes()) + if err != nil { + return nil, fmt.Errorf("mistral sign-in: start request failed: %w", err) + } + if status < 200 || status >= 300 { + return nil, fmt.Errorf("mistral sign-in: start failed (HTTP %d)%s", status, detailSuffix(body)) + } + payload, err := parseObject(body) + if err != nil { + return nil, fmt.Errorf("mistral sign-in: parse start response: %w", err) + } + + processID := strings.TrimSpace(payload.Get("process_id").String()) + signInURL := strings.TrimSpace(payload.Get("sign_in_url").String()) + pollURL := strings.TrimSpace(payload.Get("poll_url").String()) + if processID == "" || signInURL == "" || pollURL == "" { + return nil, errors.New("mistral sign-in: start response missing process_id, sign_in_url or poll_url") + } + if err = validateURL(signInURL, a.consoleBase(), ""); err != nil { + return nil, fmt.Errorf("mistral sign-in: sign_in_url: %w", err) + } + if err = validateURL(pollURL, a.signInBase, a.signInBase); err != nil { + return nil, fmt.Errorf("mistral sign-in: poll_url: %w", err) + } + + return &SignIn{ + ProcessID: processID, + URL: signInURL, + PollURL: pollURL, + Lifetime: lifetimeFromExpiry(payload.Get("expires_at").String(), time.Now()), + codeVerifier: verifier, + }, nil +} + +// WaitForSignIn polls until the user approves, then exchanges the approval for an API key. +// It stops when ctx is canceled or the sign-in lifetime ends. +func (a *MistralAuth) WaitForSignIn(ctx context.Context, signIn *SignIn) (*Credential, error) { + if ctx == nil { + ctx = context.Background() + } + if signIn == nil || signIn.codeVerifier == "" || strings.TrimSpace(signIn.ProcessID) == "" { + return nil, errors.New("mistral sign-in: missing started sign-in") + } + if err := validateURL(signIn.PollURL, a.signInBase, a.signInBase); err != nil { + return nil, fmt.Errorf("mistral sign-in: poll_url: %w", err) + } + + lifetime := signIn.Lifetime + if lifetime <= 0 || lifetime > MaxSignInDuration { + lifetime = MaxSignInDuration + } + ctx, cancel := context.WithTimeout(ctx, lifetime) + defer cancel() + + timer := time.NewTimer(a.pollInterval) + defer timer.Stop() + + failures := 0 + for { + select { + case <-ctx.Done(): + return nil, fmt.Errorf("mistral sign-in: timed out or canceled: %w", ctx.Err()) + case <-timer.C: + } + + exchangeToken, err := a.pollOnce(ctx, signIn.PollURL) + switch { + case err == nil && exchangeToken != "": + return a.exchange(ctx, signIn, exchangeToken) + case err == nil: + failures = 0 + case ctx.Err() != nil: + return nil, fmt.Errorf("mistral sign-in: timed out or canceled: %w", ctx.Err()) + case isTerminal(err): + return nil, err + default: + failures++ + if failures >= maxConsecutivePollFailures { + return nil, fmt.Errorf("mistral sign-in: status check failed %d times in a row: %w", failures, err) + } + log.Warnf("mistral sign-in: status check failed (%d/%d), retrying: %v", failures, maxConsecutivePollFailures, err) + } + timer.Reset(a.pollInterval) + } +} + +// pollOnce checks the sign-in status. It returns a non-empty exchange token when the +// user approved, an empty token when still pending, and a terminal error for any +// other final outcome. +func (a *MistralAuth) pollOnce(ctx context.Context, pollURL string) (string, error) { + status, body, err := a.doJSON(ctx, http.MethodGet, pollURL, nil) + if err != nil { + return "", err + } + if status == http.StatusGone { + return "", fmt.Errorf("mistral sign-in: %w", ErrExpired) + } + if status < 200 || status >= 300 { + return "", fmt.Errorf("status check returned HTTP %d", status) + } + payload, err := parseObject(body) + if err != nil { + return "", fmt.Errorf("parse status response: %w", err) + } + + switch state := payload.Get("status").String(); state { + case "pending": + return "", nil + case "completed": + token := strings.TrimSpace(payload.Get("exchange_token").String()) + if token == "" { + return "", fmt.Errorf("mistral sign-in: %w", ErrMissingExchangeToken) + } + return token, nil + case "expired": + return "", fmt.Errorf("mistral sign-in: %w", ErrExpired) + case "denied": + return "", fmt.Errorf("mistral sign-in: %w", ErrDenied) + case "error": + return "", fmt.Errorf("mistral sign-in: %w%s", ErrProviderError, messageSuffix(payload.Get("message").String())) + default: + return "", fmt.Errorf("mistral sign-in: %w", ErrUnknownStatus) + } +} + +// exchange trades the approved sign-in for an API key. +func (a *MistralAuth) exchange(ctx context.Context, signIn *SignIn, exchangeToken string) (*Credential, error) { + doc := ojson.NewDocString("{}") + if err := doc.Set("exchange_token", exchangeToken); err != nil { + return nil, fmt.Errorf("mistral sign-in: encode exchange request: %w", err) + } + if err := doc.Set("code_verifier", signIn.codeVerifier); err != nil { + return nil, fmt.Errorf("mistral sign-in: encode exchange request: %w", err) + } + + endpoint := a.signInBase + "/vibe/sign-in/" + url.PathEscape(signIn.ProcessID) + "/exchange" + status, body, err := a.doJSON(ctx, http.MethodPost, endpoint, doc.Bytes()) + if err != nil { + return nil, fmt.Errorf("mistral sign-in: exchange request failed: %w", err) + } + if status == http.StatusForbidden && ojson.GetBytes(body, "error_code").Int() == workspaceNotEligibleCode { + return nil, fmt.Errorf("mistral sign-in: %w", ErrWorkspaceNotEligible) + } + if status < 200 || status >= 300 { + return nil, fmt.Errorf("mistral sign-in: exchange failed (HTTP %d)%s", status, detailSuffix(body)) + } + payload, err := parseObject(body) + if err != nil { + return nil, fmt.Errorf("mistral sign-in: parse exchange response: %w", err) + } + apiKey := strings.TrimSpace(payload.Get("api_key").String()) + if apiKey == "" { + return nil, fmt.Errorf("mistral sign-in: %w", ErrMissingAPIKey) + } + return &Credential{APIKey: apiKey, BaseURL: a.apiBase}, nil +} + +// doJSON sends one request and returns the status and a size-capped body. +func (a *MistralAuth) doJSON(ctx context.Context, method, target string, body []byte) (int, []byte, error) { + var reader io.Reader + if body != nil { + reader = bytes.NewReader(body) + } + req, err := http.NewRequestWithContext(ctx, method, target, reader) + if err != nil { + return 0, nil, fmt.Errorf("create request: %w", stripURL(err)) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", userAgent) + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + + resp, err := a.httpClient.Do(req) + if err != nil { + return 0, nil, stripURL(err) + } + defer func() { + if errClose := resp.Body.Close(); errClose != nil { + log.Errorf("mistral sign-in: close response body error: %v", errClose) + } + }() + data, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes)) + if err != nil { + return 0, nil, fmt.Errorf("read response: %w", err) + } + return resp.StatusCode, data, nil +} + +// consoleBase is the origin of the sign-in API. The browser page lives on the same +// origin but outside the /api path. +func (a *MistralAuth) consoleBase() string { + parsed, err := url.Parse(a.signInBase) + if err != nil || parsed.Host == "" { + return a.signInBase + } + return parsed.Scheme + "://" + parsed.Host +} + +// validateURL accepts target only when it shares the origin of base and, when +// pathBase is set, lives under that base path. +func validateURL(target, base, pathBase string) error { + got, err := url.Parse(target) + if err != nil { + return ErrUntrustedURL + } + want, err := url.Parse(base) + if err != nil { + return ErrUntrustedURL + } + if !sameOrigin(got, want) { + return ErrUntrustedURL + } + if pathBase == "" { + return nil + } + basePath := normalizePath(want.Path) + gotPath := normalizePath(got.Path) + if basePath == "/" || gotPath == basePath || strings.HasPrefix(gotPath, basePath+"/") { + return nil + } + return ErrUntrustedURL +} + +func sameOrigin(a, b *url.URL) bool { + if a.Hostname() == "" || b.Hostname() == "" { + return false + } + return strings.EqualFold(a.Scheme, b.Scheme) && + strings.EqualFold(a.Hostname(), b.Hostname()) && + effectivePort(a) == effectivePort(b) +} + +func effectivePort(u *url.URL) string { + if port := u.Port(); port != "" { + return port + } + switch strings.ToLower(u.Scheme) { + case "https": + return "443" + case "http": + return "80" + } + return "" +} + +// normalizePath decodes and cleans a URL path so "..", "//" and encoded dots cannot +// escape the base path. +func normalizePath(p string) string { + if decoded, err := url.PathUnescape(p); err == nil { + p = decoded + } + if p == "" { + return "/" + } + return path.Clean("/" + p) +} + +// lifetimeFromExpiry converts the server expiry into a wait budget. A missing, +// malformed, past or too-distant expiry (for example from clock skew) falls back to +// MaxSignInDuration; the server still ends the sign-in with an expired status. +func lifetimeFromExpiry(expiresAt string, now time.Time) time.Duration { + parsed, err := time.Parse(time.RFC3339, strings.TrimSpace(expiresAt)) + if err != nil { + return MaxSignInDuration + } + if lifetime := parsed.Sub(now); lifetime > 0 && lifetime <= MaxSignInDuration { + return lifetime + } + return MaxSignInDuration +} + +// newCodeVerifier returns a PKCE verifier of 64 random bytes, base64url without padding. +func newCodeVerifier() (string, error) { + buf := make([]byte, codeVerifierBytes) + if _, err := rand.Read(buf); err != nil { + return "", fmt.Errorf("generate code verifier: %w", err) + } + return base64.RawURLEncoding.EncodeToString(buf), nil +} + +// codeChallenge returns the S256 PKCE challenge for verifier. +func codeChallenge(verifier string) string { + sum := sha256.Sum256([]byte(verifier)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +func parseObject(body []byte) (ojson.Result, error) { + if !ojson.ValidBytes(body) { + return ojson.Result{}, errors.New("response is not valid JSON") + } + parsed := ojson.ParseBytes(body) + if !parsed.IsObject() { + return ojson.Result{}, errors.New("response is not a JSON object") + } + return parsed, nil +} + +// isTerminal reports whether err is a final sign-in outcome that must not be retried. +func isTerminal(err error) bool { + for _, target := range []error{ + ErrExpired, ErrDenied, ErrProviderError, ErrUnknownStatus, ErrMissingExchangeToken, ErrUntrustedURL, + } { + if errors.Is(err, target) { + return true + } + } + return false +} + +// stripURL removes the request URL from transport errors so URLs never reach logs. +func stripURL(err error) error { + var urlErr *url.Error + if errors.As(err, &urlErr) { + return urlErr.Err + } + return err +} + +// detailSuffix returns ": " for the first textual detail field, or "". +func detailSuffix(body []byte) string { + if !ojson.ValidBytes(body) { + return "" + } + for _, key := range []string{"detail", "message", "error"} { + if value := ojson.GetBytes(body, key); value.Type == ojson.String { + return messageSuffix(value.String()) + } + } + return "" +} + +func messageSuffix(message string) string { + message = strings.Map(func(r rune) rune { + if unicode.IsControl(r) { + return ' ' + } + return r + }, strings.TrimSpace(message)) + if message == "" { + return "" + } + if runes := []rune(message); len(runes) > maxDetailLength { + message = string(runes[:maxDetailLength-3]) + "..." + } + return ": " + message +} + +// CredentialFileName derives a stable file name from the API key hash, so signing in +// again with the same key overwrites its file and different keys never collide. The +// key itself never appears in the name. +func CredentialFileName(apiKey string) string { + return fmt.Sprintf("mistral-%s.json", keyFingerprint(apiKey)) +} + +// CredentialLabel returns a display name with a short non-secret suffix. +func CredentialLabel(apiKey string) string { + return fmt.Sprintf("Mistral (%s)", keyFingerprint(apiKey)[:6]) +} + +func keyFingerprint(apiKey string) string { + sum := sha256.Sum256([]byte(strings.TrimSpace(apiKey))) + return hex.EncodeToString(sum[:8]) +} + +// Metadata returns the auth file content for this credential. The key is stored as an +// "oauth" account credential: it comes from an account sign-in, never expires and has +// no refresh token. +func (c *Credential) Metadata() map[string]any { + baseURL := strings.TrimSpace(c.BaseURL) + if baseURL == "" { + baseURL = DefaultAPIBaseURL + } + return map[string]any{ + "type": "mistral", + "auth_kind": "oauth", + "api_key": c.APIKey, + "base_url": baseURL, + "label": CredentialLabel(c.APIKey), + } +} diff --git a/internal/auth/mistral/mistral_test.go b/internal/auth/mistral/mistral_test.go new file mode 100644 index 00000000000..350d1ebd174 --- /dev/null +++ b/internal/auth/mistral/mistral_test.go @@ -0,0 +1,511 @@ +package mistral + +import ( + "context" + "crypto/sha256" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/MoeForge/moego/base64" + "github.com/MoeForge/moego/ojson" +) + +type reply struct { + status int + body string +} + +// fakeMistral serves the sign-in endpoints. Poll replies are consumed in order and +// the last one repeats. +type fakeMistral struct { + srv *httptest.Server + + mu sync.Mutex + startBody []byte + exchangeBody []byte + exchangePath string + polls int + pollHeaders http.Header + pollScript []reply + exchangeReply reply + // startPayload overrides the start response; it receives the fake server URL. + startPayload func(base string) string + pollSeen chan struct{} + pollSeenOnce sync.Once +} + +func newFakeMistral(t *testing.T) *fakeMistral { + t.Helper() + f := &fakeMistral{ + pollScript: []reply{{200, `{"status":"completed","exchange_token":"exch-1"}`}}, + exchangeReply: reply{200, `{"api_key":"key-123"}`}, + pollSeen: make(chan struct{}), + } + mux := http.NewServeMux() + mux.HandleFunc("POST /api/vibe/sign-in", func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + f.mu.Lock() + f.startBody = body + payload := f.startPayload + f.mu.Unlock() + if payload == nil { + payload = func(base string) string { + return `{"process_id":"pid-1","sign_in_url":"` + base + `/vibe/sign-in/pid-1?complete_token=tok",` + + `"poll_url":"` + base + `/api/vibe/sign-in/pid-1/poll","expires_at":"` + + time.Now().Add(10*time.Minute).UTC().Format(time.RFC3339) + `"}` + } + } + writeReply(w, reply{200, payload(f.srv.URL)}) + }) + mux.HandleFunc("GET /api/vibe/sign-in/pid-1/poll", func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + idx := f.polls + f.polls++ + f.pollHeaders = r.Header.Clone() + script := f.pollScript + f.mu.Unlock() + f.pollSeenOnce.Do(func() { close(f.pollSeen) }) + if idx >= len(script) { + idx = len(script) - 1 + } + writeReply(w, script[idx]) + }) + mux.HandleFunc("POST /api/vibe/sign-in/{id}/exchange", func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + f.mu.Lock() + f.exchangeBody = body + f.exchangePath = r.URL.Path + rep := f.exchangeReply + f.mu.Unlock() + writeReply(w, rep) + }) + f.srv = httptest.NewServer(mux) + t.Cleanup(f.srv.Close) + return f +} + +func writeReply(w http.ResponseWriter, r reply) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(r.status) + _, _ = io.WriteString(w, r.body) +} + +func (f *fakeMistral) auth() *MistralAuth { + a := NewMistralAuth(nil) + a.signInBase = f.srv.URL + "/api" + a.apiBase = f.srv.URL + "/v1" + a.pollInterval = time.Millisecond + return a +} + +func (f *fakeMistral) pollCount() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.polls +} + +func (f *fakeMistral) start() []byte { + f.mu.Lock() + defer f.mu.Unlock() + return f.startBody +} + +func (f *fakeMistral) exchange() (body []byte, path string) { + f.mu.Lock() + defer f.mu.Unlock() + return f.exchangeBody, f.exchangePath +} + +func (f *fakeMistral) lastPollHeaders() http.Header { + f.mu.Lock() + defer f.mu.Unlock() + return f.pollHeaders +} + +func signInOrFatal(t *testing.T, a *MistralAuth) *SignIn { + t.Helper() + signIn, err := a.StartSignIn(context.Background()) + if err != nil { + t.Fatalf("StartSignIn: %v", err) + } + return signIn +} + +func TestMistralSignIn_SendsS256ChallengeAndVerifierOnExchange(t *testing.T) { + f := newFakeMistral(t) + a := f.auth() + + signIn := signInOrFatal(t, a) + if signIn.ProcessID != "pid-1" || !strings.Contains(signIn.URL, "complete_token=tok") { + t.Fatalf("unexpected sign-in: %+v", signIn) + } + if _, err := a.WaitForSignIn(context.Background(), signIn); err != nil { + t.Fatalf("WaitForSignIn: %v", err) + } + + startBody := f.start() + exchangeBody, exchangePath := f.exchange() + challenge := ojson.GetBytes(startBody, "code_challenge").String() + if method := ojson.GetBytes(startBody, "code_challenge_method").String(); method != "S256" { + t.Fatalf("code_challenge_method = %q, want S256", method) + } + verifier := ojson.GetBytes(exchangeBody, "code_verifier").String() + sum := sha256.Sum256([]byte(verifier)) + if want := base64.RawURLEncoding.EncodeToString(sum[:]); challenge != want { + t.Fatalf("challenge %q is not S256(verifier) %q", challenge, want) + } + if len(verifier) < 43 || len(verifier) > 128 || strings.ContainsAny(verifier, "=+/") { + t.Fatalf("verifier %q is not RFC 7636 base64url", verifier) + } + if got := ojson.GetBytes(exchangeBody, "exchange_token").String(); got != "exch-1" { + t.Fatalf("exchange_token = %q, want exch-1", got) + } + if exchangePath != "/api/vibe/sign-in/pid-1/exchange" { + t.Fatalf("exchange path = %q", exchangePath) + } +} + +func TestMistralSignIn_SuccessAfterPendingPolls(t *testing.T) { + f := newFakeMistral(t) + f.pollScript = []reply{ + {200, `{"status":"pending"}`}, + {200, `{"status":"pending"}`}, + {200, `{"status":"completed","exchange_token":"exch-1"}`}, + } + a := f.auth() + + cred, err := a.WaitForSignIn(context.Background(), signInOrFatal(t, a)) + if err != nil { + t.Fatalf("WaitForSignIn: %v", err) + } + if cred.APIKey != "key-123" || cred.BaseURL != f.srv.URL+"/v1" { + t.Fatalf("credential = %+v", cred) + } + if got := f.pollCount(); got != 3 { + t.Fatalf("poll count = %d, want 3", got) + } + headers := f.lastPollHeaders() + if ua := headers.Get("User-Agent"); ua != userAgent { + t.Fatalf("User-Agent = %q, want %q", ua, userAgent) + } + if headers.Get("Authorization") != "" { + t.Fatal("poll must be unauthenticated") + } +} + +func TestMistralSignIn_TerminalPollOutcomes(t *testing.T) { + tests := []struct { + name string + reply reply + want error + contain string + }{ + {"http 410 is expired", reply{410, ``}, ErrExpired, ""}, + {"expired status", reply{200, `{"status":"expired"}`}, ErrExpired, ""}, + {"denied status", reply{200, `{"status":"denied"}`}, ErrDenied, ""}, + {"error status carries message", reply{200, `{"status":"error","message":"boom\nline"}`}, ErrProviderError, "boom line"}, + {"unknown status", reply{200, `{"status":"weird"}`}, ErrUnknownStatus, ""}, + {"completed without exchange token", reply{200, `{"status":"completed"}`}, ErrMissingExchangeToken, ""}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + f := newFakeMistral(t) + f.pollScript = []reply{tc.reply} + a := f.auth() + + _, err := a.WaitForSignIn(context.Background(), signInOrFatal(t, a)) + if !errors.Is(err, tc.want) { + t.Fatalf("err = %v, want %v", err, tc.want) + } + if tc.contain != "" && !strings.Contains(err.Error(), tc.contain) { + t.Fatalf("err = %q, want it to contain %q", err, tc.contain) + } + if f.pollCount() != 1 { + t.Fatalf("terminal outcome must not be retried, polls = %d", f.pollCount()) + } + if body, _ := f.exchange(); body != nil { + t.Fatal("exchange must not run after a terminal poll outcome") + } + }) + } +} + +func TestMistralSignIn_TransientPollFailures(t *testing.T) { + t.Run("recovers within three consecutive failures", func(t *testing.T) { + f := newFakeMistral(t) + f.pollScript = []reply{ + {500, `oops`}, {200, `not json`}, {200, `{"status":"pending"}`}, {500, ``}, {500, ``}, + {200, `{"status":"completed","exchange_token":"exch-1"}`}, + } + a := f.auth() + if _, err := a.WaitForSignIn(context.Background(), signInOrFatal(t, a)); err != nil { + t.Fatalf("WaitForSignIn: %v", err) + } + }) + t.Run("gives up after three consecutive failures", func(t *testing.T) { + f := newFakeMistral(t) + f.pollScript = []reply{{500, ``}} + a := f.auth() + _, err := a.WaitForSignIn(context.Background(), signInOrFatal(t, a)) + if err == nil || !strings.Contains(err.Error(), "HTTP 500") { + t.Fatalf("err = %v, want HTTP 500 failure", err) + } + if got := f.pollCount(); got != maxConsecutivePollFailures { + t.Fatalf("poll count = %d, want %d", got, maxConsecutivePollFailures) + } + }) +} + +func TestMistralSignIn_ExchangeFailures(t *testing.T) { + t.Run("workspace not eligible", func(t *testing.T) { + f := newFakeMistral(t) + f.exchangeReply = reply{403, `{"error_code":9004,"message":"nope"}`} + a := f.auth() + _, err := a.WaitForSignIn(context.Background(), signInOrFatal(t, a)) + if !errors.Is(err, ErrWorkspaceNotEligible) || !strings.Contains(err.Error(), WorkspaceNotEligibleMessage) { + t.Fatalf("err = %v, want workspace message", err) + } + }) + t.Run("other 403 is a generic failure", func(t *testing.T) { + f := newFakeMistral(t) + f.exchangeReply = reply{403, `{"error_code":1234,"message":"denied here"}`} + a := f.auth() + _, err := a.WaitForSignIn(context.Background(), signInOrFatal(t, a)) + if err == nil || errors.Is(err, ErrWorkspaceNotEligible) || !strings.Contains(err.Error(), "HTTP 403") { + t.Fatalf("err = %v, want generic HTTP 403 failure", err) + } + }) + t.Run("missing api_key", func(t *testing.T) { + f := newFakeMistral(t) + f.exchangeReply = reply{200, `{"api_key":" "}`} + a := f.auth() + _, err := a.WaitForSignIn(context.Background(), signInOrFatal(t, a)) + if !errors.Is(err, ErrMissingAPIKey) { + t.Fatalf("err = %v, want ErrMissingAPIKey", err) + } + }) + t.Run("exchange redirect is not followed", func(t *testing.T) { + var leaked atomic.Bool + foreign := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { leaked.Store(true) })) + defer foreign.Close() + redirecting := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, foreign.URL+"/steal", http.StatusTemporaryRedirect) + })) + defer redirecting.Close() + + a := NewMistralAuth(nil) + a.signInBase = redirecting.URL + "/api" + signIn := &SignIn{ProcessID: "pid-1", PollURL: redirecting.URL + "/api/p", Lifetime: time.Minute, codeVerifier: "v"} + _, err := a.exchange(context.Background(), signIn, "exch-1") + if err == nil || !strings.Contains(err.Error(), "HTTP 307") || leaked.Load() { + t.Fatalf("err = %v, leaked = %v; redirect must fail without reaching the foreign host", err, leaked.Load()) + } + }) +} + +func TestMistralSignIn_RejectsUntrustedURLs(t *testing.T) { + foreign := httptest.NewServer(http.NotFoundHandler()) + defer foreign.Close() + + tests := []struct { + name string + payload func(base string) string + }{ + {"foreign origin sign_in_url", func(base string) string { + return `{"process_id":"p","sign_in_url":"` + foreign.URL + `/x","poll_url":"` + base + `/api/vibe/sign-in/p/poll","expires_at":"2099-01-01T00:00:00Z"}` + }}, + {"foreign origin poll_url", func(base string) string { + return `{"process_id":"p","sign_in_url":"` + base + `/x","poll_url":"` + foreign.URL + `/api/vibe/sign-in/p/poll","expires_at":"2099-01-01T00:00:00Z"}` + }}, + {"poll_url outside the sign-in path", func(base string) string { + return `{"process_id":"p","sign_in_url":"` + base + `/x","poll_url":"` + base + `/other/poll","expires_at":"2099-01-01T00:00:00Z"}` + }}, + {"poll_url escaping with dot segments", func(base string) string { + return `{"process_id":"p","sign_in_url":"` + base + `/x","poll_url":"` + base + `/api/../admin","expires_at":"2099-01-01T00:00:00Z"}` + }}, + {"poll_url escaping with encoded dot segments", func(base string) string { + return `{"process_id":"p","sign_in_url":"` + base + `/x","poll_url":"` + base + `/api/%2e%2e/admin","expires_at":"2099-01-01T00:00:00Z"}` + }}, + {"poll_url sibling prefix", func(base string) string { + return `{"process_id":"p","sign_in_url":"` + base + `/x","poll_url":"` + base + `/apix/poll","expires_at":"2099-01-01T00:00:00Z"}` + }}, + {"scheme downgrade", func(base string) string { + return `{"process_id":"p","sign_in_url":"` + strings.Replace(base, "http://", "https://", 1) + `/x","poll_url":"` + base + `/api/p","expires_at":"2099-01-01T00:00:00Z"}` + }}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + f := newFakeMistral(t) + f.startPayload = tc.payload + _, err := f.auth().StartSignIn(context.Background()) + if !errors.Is(err, ErrUntrustedURL) { + t.Fatalf("err = %v, want ErrUntrustedURL", err) + } + }) + } + + t.Run("sign_in_url on the console origin outside /api is accepted", func(t *testing.T) { + f := newFakeMistral(t) + signIn := signInOrFatal(t, f.auth()) + if !strings.HasPrefix(signIn.URL, f.srv.URL+"/vibe/sign-in/") { + t.Fatalf("sign-in URL = %q", signIn.URL) + } + }) + t.Run("poll URL is revalidated before polling", func(t *testing.T) { + f := newFakeMistral(t) + a := f.auth() + signIn := signInOrFatal(t, a) + signIn.PollURL = foreign.URL + "/poll" + if _, err := a.WaitForSignIn(context.Background(), signIn); !errors.Is(err, ErrUntrustedURL) { + t.Fatalf("err = %v, want ErrUntrustedURL", err) + } + }) +} + +func TestMistralSignIn_StartFailures(t *testing.T) { + tests := []struct { + name string + payload func(base string) string + }{ + {"missing process_id", func(base string) string { + return `{"sign_in_url":"` + base + `/x","poll_url":"` + base + `/api/p"}` + }}, + {"missing poll_url", func(base string) string { + return `{"process_id":"p","sign_in_url":"` + base + `/x"}` + }}, + {"not an object", func(string) string { return `[]` }}, + {"not json", func(string) string { return `` }}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + f := newFakeMistral(t) + f.startPayload = tc.payload + if _, err := f.auth().StartSignIn(context.Background()); err == nil { + t.Fatal("expected an error") + } + }) + } +} + +func TestMistralSignIn_ContextCancelStopsPolling(t *testing.T) { + f := newFakeMistral(t) + f.pollScript = []reply{{200, `{"status":"pending"}`}} + a := f.auth() + signIn := signInOrFatal(t, a) + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + _, err := a.WaitForSignIn(ctx, signIn) + done <- err + }() + <-f.pollSeen + cancel() + + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v, want context.Canceled", err) + } + case <-time.After(5 * time.Second): + t.Fatal("WaitForSignIn did not stop after cancel") + } + if body, _ := f.exchange(); body != nil { + t.Fatal("exchange must not run after cancel") + } +} + +func TestMistralSignIn_LifetimeEndsPolling(t *testing.T) { + f := newFakeMistral(t) + f.pollScript = []reply{{200, `{"status":"pending"}`}} + f.startPayload = func(base string) string { + return `{"process_id":"pid-1","sign_in_url":"` + base + `/x","poll_url":"` + base + `/api/vibe/sign-in/pid-1/poll","expires_at":"` + + time.Now().Add(100*time.Millisecond).UTC().Format(time.RFC3339Nano) + `"}` + } + a := f.auth() + signIn := signInOrFatal(t, a) + if signIn.Lifetime <= 0 || signIn.Lifetime > time.Second { + t.Fatalf("lifetime = %v, want about 100ms", signIn.Lifetime) + } + if _, err := a.WaitForSignIn(context.Background(), signIn); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("err = %v, want context.DeadlineExceeded", err) + } +} + +func TestLifetimeFromExpiry(t *testing.T) { + now := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + tests := []struct { + name string + expiresAt string + want time.Duration + }{ + {"within range", "2026-11-21T12:10:00Z", 10 * time.Minute}, + {"offset timezone", "2026-11-21T14:05:00+02:00", 5 * time.Minute}, + {"already past (clock skew)", "2026-11-21T11:00:00Z", MaxSignInDuration}, + {"too far away", "2027-01-01T00:00:00Z", MaxSignInDuration}, + {"malformed", "tomorrow", MaxSignInDuration}, + {"empty", "", MaxSignInDuration}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := lifetimeFromExpiry(tc.expiresAt, now); got != tc.want { + t.Fatalf("lifetime = %v, want %v", got, tc.want) + } + }) + } +} + +func TestCredentialMetadataKeepsSecretOutOfNames(t *testing.T) { + cred := &Credential{APIKey: "sk-secret-value"} + name := CredentialFileName(cred.APIKey) + label := CredentialLabel(cred.APIKey) + if strings.Contains(name, "secret") || strings.Contains(label, "secret") { + t.Fatalf("name %q or label %q leaks the key", name, label) + } + if name != CredentialFileName(" sk-secret-value ") || name == CredentialFileName("sk-other") { + t.Fatalf("file name %q must be stable per key and distinct across keys", name) + } + if !strings.HasPrefix(label, "Mistral (") { + t.Fatalf("label = %q", label) + } + + meta := cred.Metadata() + want := map[string]any{ + "type": "mistral", + "auth_kind": "oauth", + "api_key": "sk-secret-value", + "base_url": DefaultAPIBaseURL, + "label": label, + } + if len(meta) != len(want) { + t.Fatalf("metadata = %v, want %v", meta, want) + } + for k, v := range want { + if meta[k] != v { + t.Fatalf("metadata[%q] = %v, want %v", k, meta[k], v) + } + } + if custom := (&Credential{APIKey: "k", BaseURL: "http://x/v1"}).Metadata(); custom["base_url"] != "http://x/v1" { + t.Fatalf("custom base_url lost: %v", custom) + } +} + +func TestOverrideEndpointsForTest(t *testing.T) { + restore := OverrideEndpointsForTest("http://sign.example/api/", "http://api.example/v1", 7*time.Millisecond) + a := NewMistralAuth(nil) + if a.signInBase != "http://sign.example/api" || a.apiBase != "http://api.example/v1" || a.pollInterval != 7*time.Millisecond { + t.Fatalf("override not applied: %+v", a) + } + restore() + b := NewMistralAuth(nil) + if b.signInBase != DefaultSignInBaseURL || b.apiBase != DefaultAPIBaseURL || b.pollInterval != DefaultPollInterval { + t.Fatalf("defaults not restored: %+v", b) + } +} From 2b17d6f728bb369cf4c4ea609d70dfd2248d7778 Mon Sep 17 00:00:00 2001 From: bntvllnt <32437578+bntvllnt@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:51:14 +0000 Subject: [PATCH 2/8] feat(executor): read OpenAI-compatible credentials from auth Metadata Auth files restored from disk carry api_key and base_url in Metadata only. Fall back to Metadata when Attributes lack them so file-based API-key providers such as Mistral work, while keeping the raw key out of Attributes and usage records. Adds mistral request-path tests, including the payload-config-last regression. --- .../executor/openai_compat_executor.go | 9 + .../openai_compat_executor_mistral_test.go | 228 ++++++++++++++++++ 2 files changed, 237 insertions(+) create mode 100644 internal/runtime/executor/openai_compat_executor_mistral_test.go diff --git a/internal/runtime/executor/openai_compat_executor.go b/internal/runtime/executor/openai_compat_executor.go index 9acc199719d..58bfd60cc25 100644 --- a/internal/runtime/executor/openai_compat_executor.go +++ b/internal/runtime/executor/openai_compat_executor.go @@ -1148,6 +1148,15 @@ func (e *OpenAICompatExecutor) resolveCredentials(auth *cliproxyauth.Auth) (base baseURL = strings.TrimSpace(auth.Attributes["base_url"]) apiKey = strings.TrimSpace(auth.Attributes["api_key"]) } + // Credentials restored from auth files (for example Mistral sign-in) keep the key + // and base URL in Metadata only; Attributes stay free of the raw key so usage + // records never carry it. + if baseURL == "" { + baseURL = metadataString(auth.Metadata, "base_url") + } + if apiKey == "" { + apiKey = metadataString(auth.Metadata, "api_key") + } return } diff --git a/internal/runtime/executor/openai_compat_executor_mistral_test.go b/internal/runtime/executor/openai_compat_executor_mistral_test.go new file mode 100644 index 00000000000..13d7661a2bb --- /dev/null +++ b/internal/runtime/executor/openai_compat_executor_mistral_test.go @@ -0,0 +1,228 @@ +package executor + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +// mistralMetadataAuth mirrors an auth file written by the Mistral sign-in: the key and +// base URL live in Metadata only, with no api_key attribute. +func mistralMetadataAuth(baseURL string) *cliproxyauth.Auth { + return &cliproxyauth.Auth{ + ID: "mistral-test.json", + Provider: "mistral", + Metadata: map[string]any{ + "type": "mistral", + "auth_kind": "oauth", + "api_key": "mistral-key", + "base_url": baseURL, + }, + } +} + +type capturedUpstream struct { + mu sync.Mutex + path string + headers http.Header + body []byte +} + +func (c *capturedUpstream) snapshot() (string, http.Header, []byte) { + c.mu.Lock() + defer c.mu.Unlock() + return c.path, c.headers, c.body +} + +// newMistralUpstream answers like api.mistral.ai: JSON for plain requests, SSE for streams. +func newMistralUpstream(t *testing.T) (*httptest.Server, *capturedUpstream) { + t.Helper() + captured := &capturedUpstream{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + captured.mu.Lock() + captured.path, captured.headers, captured.body = r.URL.Path, r.Header.Clone(), body + captured.mu.Unlock() + if ojson.GetBytes(body, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"model\":\"mistral-large-latest\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"OK\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"mistral-large-latest","choices":[{"index":0,"message":{"role":"assistant","content":"OK"},"finish_reason":"stop"}]}`) + })) + t.Cleanup(server.Close) + return server, captured +} + +// withStreamFlag mirrors the API handlers, which put "stream":true in the payload of streaming requests. +func withStreamFlag(payload string, stream bool) []byte { + if !stream { + return []byte(payload) + } + return []byte(strings.Replace(payload, `{"model"`, `{"stream":true,"model"`, 1)) +} + +func runMistralRequest(t *testing.T, executor *OpenAICompatExecutor, auth *cliproxyauth.Auth, req cliproxyexecutor.Request, opts cliproxyexecutor.Options) { + t.Helper() + if opts.Stream { + result, err := executor.ExecuteStream(context.Background(), auth, req, opts) + if err != nil { + t.Fatalf("ExecuteStream: %v", err) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatalf("stream chunk: %v", chunk.Err) + } + } + return + } + if _, err := executor.Execute(context.Background(), auth, req, opts); err != nil { + t.Fatalf("Execute: %v", err) + } +} + +func TestOpenAICompatExecutor_ResolvesCredentialsFromMetadata(t *testing.T) { + executor := NewOpenAICompatExecutor("mistral", &config.Config{}) + + tests := []struct { + name string + auth *cliproxyauth.Auth + wantBaseURL string + wantAPIKey string + }{ + {"nil auth", nil, "", ""}, + {"metadata only", mistralMetadataAuth("https://api.mistral.ai/v1"), "https://api.mistral.ai/v1", "mistral-key"}, + {"attributes win over metadata", &cliproxyauth.Auth{ + Attributes: map[string]string{"base_url": "https://attr.example/v1", "api_key": "attr-key"}, + Metadata: map[string]any{"base_url": "https://meta.example/v1", "api_key": "meta-key"}, + }, "https://attr.example/v1", "attr-key"}, + {"each value falls back independently", &cliproxyauth.Auth{ + Attributes: map[string]string{"base_url": "https://attr.example/v1"}, + Metadata: map[string]any{"base_url": "https://meta.example/v1", "api_key": " meta-key "}, + }, "https://attr.example/v1", "meta-key"}, + {"non-string metadata is ignored", &cliproxyauth.Auth{ + Metadata: map[string]any{"base_url": 42, "api_key": true}, + }, "", ""}, + {"empty auth", &cliproxyauth.Auth{}, "", ""}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + baseURL, apiKey := executor.resolveCredentials(tc.auth) + if baseURL != tc.wantBaseURL || apiKey != tc.wantAPIKey { + t.Fatalf("resolveCredentials = (%q, %q), want (%q, %q)", baseURL, apiKey, tc.wantBaseURL, tc.wantAPIKey) + } + }) + } +} + +func TestOpenAICompatExecutor_MistralMetadataCredentialReachesUpstream(t *testing.T) { + server, captured := newMistralUpstream(t) + executor := NewOpenAICompatExecutor("mistral", &config.Config{}) + auth := mistralMetadataAuth(server.URL + "/v1") + + for _, stream := range []bool{false, true} { + name := map[bool]string{false: "execute", true: "stream"}[stream] + t.Run(name, func(t *testing.T) { + runMistralRequest(t, executor, auth, cliproxyexecutor.Request{ + Model: "mistral-large-latest", + Payload: withStreamFlag(`{"model":"mistral-large-latest","messages":[{"role":"user","content":"hi"}]}`, stream), + }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatOpenAI, Stream: stream}) + + path, headers, body := captured.snapshot() + if path != "/v1/chat/completions" { + t.Fatalf("upstream path = %q, want /v1/chat/completions", path) + } + if got := headers.Get("Authorization"); got != "Bearer mistral-key" { + t.Fatalf("Authorization = %q, want Bearer mistral-key", got) + } + if got := ojson.GetBytes(body, "model").String(); got != "mistral-large-latest" { + t.Fatalf("upstream model = %q; body=%s", got, body) + } + }) + } + + t.Run("PrepareRequest injects the metadata key", func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, server.URL+"/v1/models", nil) + if err := executor.PrepareRequest(req, auth); err != nil { + t.Fatalf("PrepareRequest: %v", err) + } + if got := req.Header.Get("Authorization"); got != "Bearer mistral-key" { + t.Fatalf("Authorization = %q, want Bearer mistral-key", got) + } + }) +} + +// TestOpenAICompatExecutor_MistralPayloadConfigIsAppliedLast guards the AGENTS.md payload +// barrier on the mistral request path: translation, normalization and injection happen +// first, then user payload rules run once on the final body, so a rule always wins. +func TestOpenAICompatExecutor_MistralPayloadConfigIsAppliedLast(t *testing.T) { + cfg := &config.Config{Payload: config.PayloadConfig{ + Override: []config.PayloadRule{{ + Models: []config.PayloadModelRule{{Name: "mistral-large-latest"}}, + Params: map[string]any{"temperature": 0.2, "safe_prompt": true, "max_tokens": 321}, + }}, + Filter: []config.PayloadFilterRule{{ + Models: []config.PayloadModelRule{{Name: "mistral-large-latest"}}, + Params: []string{"top_p", "stream_options"}, + }}, + }} + unmatched := &config.Config{} + + formats := []struct { + name string + source sdktranslator.Format + payload string + }{ + {"openai", sdktranslator.FormatOpenAI, `{"model":"mistral-large-latest","temperature":1,"top_p":0.9,"max_tokens":50,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"hi"}]}`}, + {"claude", sdktranslator.FormatClaude, `{"model":"mistral-large-latest","temperature":1,"top_p":0.9,"max_tokens":50,"messages":[{"role":"user","content":"hi"}]}`}, + } + for _, format := range formats { + for _, stream := range []bool{false, true} { + name := format.name + "/" + map[bool]string{false: "execute", true: "stream"}[stream] + t.Run(name, func(t *testing.T) { + server, captured := newMistralUpstream(t) + auth := mistralMetadataAuth(server.URL + "/v1") + req := cliproxyexecutor.Request{Model: "mistral-large-latest", Payload: withStreamFlag(format.payload, stream)} + opts := cliproxyexecutor.Options{SourceFormat: format.source, Stream: stream} + + runMistralRequest(t, NewOpenAICompatExecutor("mistral", cfg), auth, req, opts) + _, _, body := captured.snapshot() + if got := ojson.GetBytes(body, "temperature").Float(); got != 0.2 { + t.Fatalf("temperature = %v, want the override 0.2; body=%s", got, body) + } + if got := ojson.GetBytes(body, "max_tokens").Int(); got != 321 { + t.Fatalf("max_tokens = %d, want the override 321; body=%s", got, body) + } + if !ojson.GetBytes(body, "safe_prompt").Bool() { + t.Fatalf("safe_prompt override missing; body=%s", body) + } + for _, filtered := range []string{"top_p", "stream_options"} { + if ojson.GetBytes(body, filtered).Exists() { + t.Fatalf("%s survived the filter rule; body=%s", filtered, body) + } + } + + // Same request without matching rules proves the rules, not the builtin path, caused the result. + runMistralRequest(t, NewOpenAICompatExecutor("mistral", unmatched), auth, req, opts) + _, _, plain := captured.snapshot() + if got := ojson.GetBytes(plain, "temperature").Float(); got != 1 { + t.Fatalf("baseline temperature = %v, want 1; body=%s", got, plain) + } + if ojson.GetBytes(plain, "safe_prompt").Exists() { + t.Fatalf("baseline must not contain safe_prompt; body=%s", plain) + } + }) + } + } +} From 35203179465eba565295a8ec493a725e2e74c4d4 Mon Sep 17 00:00:00 2001 From: bntvllnt <32437578+bntvllnt@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:53:24 +0000 Subject: [PATCH 3/8] feat(registry): add static Mistral model list Hard-codes the Mistral Vibe model IDs instead of extending models.json, because the remote catalog refresh replaces models.json wholesale and has no Mistral section. --- internal/registry/mistral_models.go | 45 +++++++++++++++++++ internal/registry/mistral_models_test.go | 56 ++++++++++++++++++++++++ internal/registry/model_definitions.go | 4 ++ 3 files changed, 105 insertions(+) create mode 100644 internal/registry/mistral_models.go create mode 100644 internal/registry/mistral_models_test.go diff --git a/internal/registry/mistral_models.go b/internal/registry/mistral_models.go new file mode 100644 index 00000000000..b4ea2ef9ade --- /dev/null +++ b/internal/registry/mistral_models.go @@ -0,0 +1,45 @@ +package registry + +// staticMistralModels lists the models a Mistral Vibe sign-in key serves. The IDs come +// from the Mistral Vibe CLI defaults. The list is hard-coded, not part of models.json, +// because the remote catalog refresh replaces models.json wholesale and has no +// Mistral section. +var staticMistralModels = []*ModelInfo{ + { + ID: "mistral-large-4-0", + Object: "model", + Type: "mistral", + OwnedBy: "mistralai", + DisplayName: "Mistral Large 4", + ContextLength: 1048576, + SupportedInputModalities: []string{"text", "image"}, + }, + { + ID: "mistral-vibe-cli-latest", + Object: "model", + Type: "mistral", + OwnedBy: "mistralai", + DisplayName: "Mistral Medium 3.5 (Vibe CLI)", + ContextLength: 262144, + SupportedInputModalities: []string{"text", "image"}, + }, + { + ID: "mistral-vibe-cli-fast", + Object: "model", + Type: "mistral", + OwnedBy: "mistralai", + DisplayName: "Mistral Small (Vibe CLI fast)", + }, + { + ID: "mistral-small-latest", + Object: "model", + Type: "mistral", + OwnedBy: "mistralai", + DisplayName: "Mistral Small", + }, +} + +// GetMistralModels returns the built-in Mistral model definitions. +func GetMistralModels() []*ModelInfo { + return cloneModelInfos(staticMistralModels) +} diff --git a/internal/registry/mistral_models_test.go b/internal/registry/mistral_models_test.go new file mode 100644 index 00000000000..b4bd6125488 --- /dev/null +++ b/internal/registry/mistral_models_test.go @@ -0,0 +1,56 @@ +package registry + +import "testing" + +func TestGetMistralModels(t *testing.T) { + models := GetMistralModels() + if len(models) == 0 { + t.Fatal("expected built-in Mistral models") + } + seen := map[string]bool{} + for _, model := range models { + if model == nil || model.ID == "" { + t.Fatalf("invalid model entry: %+v", model) + } + if seen[model.ID] { + t.Fatalf("duplicate model id %q", model.ID) + } + seen[model.ID] = true + if model.Type != "mistral" || model.OwnedBy != "mistralai" { + t.Fatalf("model %q has type %q owned_by %q, want mistral/mistralai", model.ID, model.Type, model.OwnedBy) + } + if model.Thinking != nil { + t.Fatalf("model %q must not declare thinking support: no Mistral thinking applier exists", model.ID) + } + } + for _, id := range []string{"mistral-large-4-0", "mistral-vibe-cli-latest", "mistral-vibe-cli-fast", "mistral-small-latest"} { + if !seen[id] { + t.Fatalf("missing model %q", id) + } + } +} + +func TestGetMistralModelsReturnsClones(t *testing.T) { + first := GetMistralModels() + first[0].DisplayName = "mutated" + first[0].SupportedInputModalities[0] = "mutated" + if got := GetMistralModels()[0]; got.DisplayName == "mutated" || got.SupportedInputModalities[0] == "mutated" { + t.Fatalf("caller mutation leaked into the static list: %+v", got) + } +} + +func TestMistralModelsAreAvailableByChannelAndLookup(t *testing.T) { + byChannel := GetStaticModelDefinitionsByChannel(" Mistral ") + if len(byChannel) != len(GetMistralModels()) { + t.Fatalf("channel lookup returned %d models, want %d", len(byChannel), len(GetMistralModels())) + } + if info := LookupStaticModelInfoByChannel("mistral-large-4-0", "mistral"); info == nil || info.ContextLength != 1048576 { + t.Fatalf("channel model lookup = %+v", info) + } + if info := LookupStaticModelInfo("mistral-vibe-cli-latest"); info == nil || info.Type != "mistral" { + t.Fatalf("global model lookup = %+v", info) + } + if info := LookupStaticModelInfoByChannel("mistral-large-4-0", "meta"); info != nil { + t.Fatalf("Mistral model must not resolve under another provider: %+v", info) + } +} diff --git a/internal/registry/model_definitions.go b/internal/registry/model_definitions.go index f8885c104e6..a53655fad32 100644 --- a/internal/registry/model_definitions.go +++ b/internal/registry/model_definitions.go @@ -566,6 +566,7 @@ func cloneModelInfos(models []*ModelInfo) []*ModelInfo { // - xai // - devin // - meta +// - mistral func GetStaticModelDefinitionsByChannel(channel string) []*ModelInfo { key := strings.ToLower(strings.TrimSpace(channel)) switch key { @@ -591,6 +592,8 @@ func GetStaticModelDefinitionsByChannel(channel string) []*ModelInfo { return GetDevinModels() case "meta", "muse": return GetMetaModels() + case "mistral": + return GetMistralModels() default: return nil } @@ -645,6 +648,7 @@ func LookupStaticModelInfo(modelID string) *ModelInfo { data.XAI, GetDevinModels(), GetMetaModels(), + GetMistralModels(), } for _, models := range allModels { for _, m := range models { From fc260ea304d95d8ac985a32d6bf6bd70c2763a34 Mon Sep 17 00:00:00 2001 From: bntvllnt <32437578+bntvllnt@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:57:01 +0000 Subject: [PATCH 4/8] feat(cli): add --mistral-login and Mistral authenticator Registers the Mistral authenticator with the CLI auth manager and refresh registry (no scheduled refresh: the provisioned key does not expire), adds the --mistral-login flag, and builds auth records with the key in Metadata only. --- cmd/server/main.go | 8 +- internal/cmd/auth_manager.go | 3 +- internal/cmd/mistral_login.go | 39 +++++++++ sdk/auth/mistral.go | 93 +++++++++++++++++++++ sdk/auth/mistral_test.go | 133 ++++++++++++++++++++++++++++++ sdk/auth/refresh_registry.go | 1 + sdk/auth/refresh_registry_test.go | 1 + 7 files changed, 275 insertions(+), 3 deletions(-) create mode 100644 internal/cmd/mistral_login.go create mode 100644 sdk/auth/mistral.go create mode 100644 sdk/auth/mistral_test.go diff --git a/cmd/server/main.go b/cmd/server/main.go index 119783f1406..c2fadeec54c 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -131,6 +131,7 @@ func run() (exitStatus int) { var xaiLogin bool var devinLogin bool var metaLogin bool + var mistralLogin bool var discoverGateways bool var discoverTimeout int var discoverJSON bool @@ -162,6 +163,7 @@ func run() (exitStatus int) { flag.BoolVar(&xaiLogin, "xai-login", false, "Login to xAI using OAuth") flag.BoolVar(&devinLogin, "devin-login", false, "Login to Devin using OAuth") flag.BoolVar(&metaLogin, "meta-login", false, "Login to Meta using OAuth") + flag.BoolVar(&mistralLogin, "mistral-login", false, "Login to Mistral (Vibe / Le Chat Pro) using browser sign-in") flag.BoolVar(&discoverGateways, "discover", false, "Discover local AI gateways and CPA instances on the LAN") flag.IntVar(&discoverTimeout, "discover-timeout", 3, "Timeout in seconds for LAN discovery (default 3s)") flag.BoolVar(&discoverJSON, "discover-json", false, "Output discovered gateways in JSON format") @@ -683,7 +685,7 @@ func run() (exitStatus int) { ProxyURL: loginProxyURL, } - commandMode := vertexImport != "" || siwcBind != "" || antigravityLogin || codexLogin || codexDeviceLogin || claudeLogin || kimiLogin || kimiAILogin || xaiLogin || devinLogin || metaLogin + commandMode := vertexImport != "" || siwcBind != "" || antigravityLogin || codexLogin || codexDeviceLogin || claudeLogin || kimiLogin || kimiAILogin || xaiLogin || devinLogin || metaLogin || mistralLogin cloudConfigMissing := isCloudDeploy && !configFileExists homeMode := configLoadedFromHome || (cfg != nil && cfg.Home.Enabled) exampleAPIKeySafeMode := shouldEnableExampleAPIKeySafeMode(cfg, commandMode, tuiMode, standalone, cloudConfigMissing, homeMode) @@ -763,6 +765,8 @@ func run() (exitStatus int) { cmd.DoDevinLogin(cfg, options) } else if metaLogin { cmd.DoMetaLogin(cfg, options) + } else if mistralLogin { + cmd.DoMistralLogin(cfg, options) } else { // In cloud deploy mode without config file, just wait for shutdown signals if isCloudDeploy && !configFileExists { @@ -1010,7 +1014,7 @@ func argvEnablesBoolFlag(args []string, name string) bool { func argvFlagConsumesValue(name string) bool { switch name { case "codex-login", "codex-device-login", "claude-login", "no-browser", - "antigravity-login", "kimi-login", "kimi-ai-login", "xai-login", "devin-login", "meta-login", + "antigravity-login", "kimi-login", "kimi-ai-login", "xai-login", "devin-login", "meta-login", "mistral-login", "discover", "discover-json", "home-disable-cluster-discovery", "tui", "standalone", "local-model": return false diff --git a/internal/cmd/auth_manager.go b/internal/cmd/auth_manager.go index 79356cbbbb6..ad1dfb3e363 100644 --- a/internal/cmd/auth_manager.go +++ b/internal/cmd/auth_manager.go @@ -6,7 +6,7 @@ import ( // newAuthManager creates a new authentication manager instance with all supported // authenticators and a file-based token store. It initializes authenticators for -// Codex, Claude, Antigravity, Kimi, xAI, Devin, and Meta providers. +// Codex, Claude, Antigravity, Kimi, xAI, Devin, Meta, and Mistral providers. // // Returns: // - *sdkAuth.Manager: A configured authentication manager instance @@ -22,6 +22,7 @@ func newAuthManager() *sdkAuth.Manager { sdkAuth.NewXAIAuthenticator(), sdkAuth.NewDevinAuthenticator(), sdkAuth.NewMetaAuthenticator(), + sdkAuth.NewMistralAuthenticator(), ) return manager } diff --git a/internal/cmd/mistral_login.go b/internal/cmd/mistral_login.go new file mode 100644 index 00000000000..55b696d5c6f --- /dev/null +++ b/internal/cmd/mistral_login.go @@ -0,0 +1,39 @@ +package cmd + +import ( + "context" + "fmt" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + sdkAuth "github.com/router-for-me/CLIProxyAPI/v8/sdk/auth" + log "github.com/sirupsen/logrus" +) + +// DoMistralLogin runs the Mistral Vibe browser sign-in and saves the provisioned API key. +func DoMistralLogin(cfg *config.Config, options *LoginOptions) { + if options == nil { + options = &LoginOptions{} + } + + manager := newAuthManager() + authOpts := &sdkAuth.LoginOptions{ + NoBrowser: options.NoBrowser, + CallbackPort: options.CallbackPort, + ProxyURL: options.ProxyURL, + Metadata: map[string]string{}, + } + + record, savedPath, err := manager.Login(context.Background(), "mistral", cfg, authOpts) + if err != nil { + log.Errorf("Mistral authentication failed: %v", err) + return + } + + if savedPath != "" { + fmt.Printf("Authentication saved to %s\n", savedPath) + } + if record != nil && record.Label != "" { + fmt.Printf("Authenticated as %s\n", record.Label) + } + fmt.Println("Mistral authentication successful!") +} diff --git a/sdk/auth/mistral.go b/sdk/auth/mistral.go new file mode 100644 index 00000000000..776f240674c --- /dev/null +++ b/sdk/auth/mistral.go @@ -0,0 +1,93 @@ +package auth + +import ( + "context" + "fmt" + "strings" + "time" + + mistralauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/mistral" + "github.com/router-for-me/CLIProxyAPI/v8/internal/browser" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + log "github.com/sirupsen/logrus" +) + +// MistralAuthenticator implements the Mistral Vibe browser sign-in. The sign-in +// provisions a long-lived API key used for inference on api.mistral.ai. +type MistralAuthenticator struct{} + +// NewMistralAuthenticator constructs a new Mistral authenticator. +func NewMistralAuthenticator() Authenticator { + return &MistralAuthenticator{} +} + +// Provider returns the provider key for Mistral. +func (MistralAuthenticator) Provider() string { + return "mistral" +} + +// RefreshLead disables scheduled refresh: the provisioned key does not expire and +// has no refresh token. A rejected key is handled like any other invalid credential. +func (MistralAuthenticator) RefreshLead() *time.Duration { + return nil +} + +// NewMistralAuthRecord builds the auth record persisted for a completed Mistral sign-in. +// The key stays in Metadata only, so it never reaches Attributes or usage records. +func NewMistralAuthRecord(cred *mistralauth.Credential) *coreauth.Auth { + fileName := mistralauth.CredentialFileName(cred.APIKey) + return &coreauth.Auth{ + ID: fileName, + Provider: "mistral", + FileName: fileName, + Label: mistralauth.CredentialLabel(cred.APIKey), + Metadata: cred.Metadata(), + } +} + +// Login runs the browser sign-in and returns the auth record to persist. +func (a MistralAuthenticator) Login(ctx context.Context, cfg *config.Config, opts *LoginOptions) (*coreauth.Auth, error) { + if cfg == nil { + return nil, fmt.Errorf("cliproxy auth: configuration is required") + } + if ctx == nil { + ctx = context.Background() + } + if opts == nil { + opts = &LoginOptions{} + } + + authSvc := mistralauth.NewMistralAuth(cfg) + + fmt.Println("Starting Mistral authentication...") + signIn, err := authSvc.StartSignIn(ctx) + if err != nil { + return nil, fmt.Errorf("mistral: failed to start sign-in: %w", err) + } + + signInURL := strings.TrimSpace(signIn.URL) + fmt.Printf("\nTo authenticate, please visit:\n%s\n\n", signInURL) + if !opts.NoBrowser { + if browser.IsAvailable() { + if errOpen := browser.OpenURL(signInURL); errOpen != nil { + log.Warnf("Failed to open browser automatically: %v", errOpen) + } else { + fmt.Println("Browser opened automatically.") + } + } else { + log.Warn("No browser available; please open the URL manually") + } + } + + fmt.Println("Waiting for authorization...") + fmt.Printf("(This will time out in %d seconds if not approved)\n", int(signIn.Lifetime/time.Second)) + + cred, err := authSvc.WaitForSignIn(ctx, signIn) + if err != nil { + return nil, fmt.Errorf("mistral: %w", err) + } + + fmt.Println("Mistral authentication successful") + return NewMistralAuthRecord(cred), nil +} diff --git a/sdk/auth/mistral_test.go b/sdk/auth/mistral_test.go new file mode 100644 index 00000000000..1e89c1e14cf --- /dev/null +++ b/sdk/auth/mistral_test.go @@ -0,0 +1,133 @@ +package auth + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "time" + + mistralauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/mistral" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" +) + +// newMistralSignInServer fakes the Mistral sign-in API. pollStatus is the poll body. +func newMistralSignInServer(t *testing.T, pollBody string) *httptest.Server { + t.Helper() + var server *httptest.Server + mux := http.NewServeMux() + mux.HandleFunc("POST /api/vibe/sign-in", func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + _, _ = io.WriteString(w, `{"process_id":"pid","sign_in_url":"`+server.URL+`/vibe/sign-in/pid?complete_token=t","poll_url":"`+ + server.URL+`/api/vibe/sign-in/pid/poll","expires_at":"`+time.Now().Add(5*time.Minute).UTC().Format(time.RFC3339)+`"}`) + }) + mux.HandleFunc("GET /api/vibe/sign-in/pid/poll", func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, pollBody) + }) + mux.HandleFunc("POST /api/vibe/sign-in/pid/exchange", func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + _, _ = io.WriteString(w, `{"api_key":"sk-login-test-key"}`) + }) + server = httptest.NewServer(mux) + t.Cleanup(server.Close) + t.Cleanup(mistralauth.OverrideEndpointsForTest(server.URL+"/api", server.URL+"/v1", time.Millisecond)) + return server +} + +func TestMistralLoginReturnsRecordWithKeyOnlyInMetadata(t *testing.T) { + server := newMistralSignInServer(t, `{"status":"completed","exchange_token":"exch"}`) + + record, err := NewMistralAuthenticator().Login(context.Background(), &config.Config{}, &LoginOptions{NoBrowser: true}) + if err != nil { + t.Fatalf("Login: %v", err) + } + + if record.Provider != "mistral" || record.Storage != nil { + t.Fatalf("record provider/storage = %q/%v", record.Provider, record.Storage) + } + if !regexp.MustCompile(`^mistral-[0-9a-f]{16}\.json$`).MatchString(record.FileName) || record.ID != record.FileName { + t.Fatalf("record id/file = %q/%q", record.ID, record.FileName) + } + if !strings.HasPrefix(record.Label, "Mistral (") || strings.Contains(record.Label, "sk-login") { + t.Fatalf("label = %q", record.Label) + } + want := map[string]any{"type": "mistral", "auth_kind": "oauth", "api_key": "sk-login-test-key", "base_url": server.URL + "/v1", "label": record.Label} + for key, value := range want { + if record.Metadata[key] != value { + t.Fatalf("metadata[%q] = %v, want %v", key, record.Metadata[key], value) + } + } + if len(record.Attributes) != 0 { + t.Fatalf("attributes must stay empty so the raw key never reaches usage records: %v", record.Attributes) + } + if kind, value := record.AccountInfo(); kind != "oauth" || value != "" { + t.Fatalf("AccountInfo = (%q, %q), want (oauth, empty)", kind, value) + } +} + +func TestMistralLoginViaManagerWritesPrivateAuthFile(t *testing.T) { + server := newMistralSignInServer(t, `{"status":"completed","exchange_token":"exch"}`) + authDir := t.TempDir() + cfg := &config.Config{AuthDir: authDir} + manager := NewManager(NewFileTokenStore(), NewMistralAuthenticator()) + + record, savedPath, err := manager.Login(context.Background(), "mistral", cfg, &LoginOptions{NoBrowser: true}) + if err != nil { + t.Fatalf("Login: %v", err) + } + if savedPath != filepath.Join(authDir, record.FileName) { + t.Fatalf("saved path = %q, want it inside %q", savedPath, authDir) + } + info, errStat := os.Stat(savedPath) + if errStat != nil { + t.Fatalf("auth file missing: %v", errStat) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("auth file mode = %v, want 0600", info.Mode().Perm()) + } + raw, _ := os.ReadFile(savedPath) + var saved map[string]any + if errUnmarshal := json.Unmarshal(raw, &saved); errUnmarshal != nil { + t.Fatalf("auth file is not JSON: %v", errUnmarshal) + } + if saved["type"] != "mistral" || saved["api_key"] != "sk-login-test-key" || saved["base_url"] != server.URL+"/v1" || saved["auth_kind"] != "oauth" { + t.Fatalf("saved file = %v", saved) + } + if _, hasExpiry := saved["expired"]; hasExpiry { + t.Fatalf("a key that never expires must not carry an expiry: %v", saved) + } + + // The file must round-trip through the store the server uses at startup. + store := NewFileTokenStore() + store.SetBaseDir(authDir) + auths, errList := store.List(context.Background()) + if errList != nil || len(auths) != 1 || auths[0].Provider != "mistral" || auths[0].Metadata["api_key"] != "sk-login-test-key" { + t.Fatalf("store.List = %v, %v", auths, errList) + } +} + +func TestMistralLoginDeniedSavesNothing(t *testing.T) { + newMistralSignInServer(t, `{"status":"denied"}`) + authDir := t.TempDir() + manager := NewManager(NewFileTokenStore(), NewMistralAuthenticator()) + + _, savedPath, err := manager.Login(context.Background(), "mistral", &config.Config{AuthDir: authDir}, &LoginOptions{NoBrowser: true}) + if err == nil || !strings.Contains(err.Error(), "denied") || savedPath != "" { + t.Fatalf("err = %v, savedPath = %q; want a denied error and no saved path", err, savedPath) + } + if entries, _ := os.ReadDir(authDir); len(entries) != 0 { + t.Fatalf("denied sign-in must not write files, found %d", len(entries)) + } +} + +func TestMistralLoginRequiresConfig(t *testing.T) { + if _, err := NewMistralAuthenticator().Login(context.Background(), nil, nil); err == nil { + t.Fatal("expected an error for a nil config") + } +} diff --git a/sdk/auth/refresh_registry.go b/sdk/auth/refresh_registry.go index cfa50993419..e22d807c777 100644 --- a/sdk/auth/refresh_registry.go +++ b/sdk/auth/refresh_registry.go @@ -16,6 +16,7 @@ func init() { registerRefreshLead("xai", func() Authenticator { return NewXAIAuthenticator() }) registerRefreshLead("devin", func() Authenticator { return NewDevinAuthenticator() }) registerRefreshLead("meta", func() Authenticator { return NewMetaAuthenticator() }) + registerRefreshLead("mistral", func() Authenticator { return NewMistralAuthenticator() }) } func registerRefreshLead(provider string, factory func() Authenticator) { diff --git a/sdk/auth/refresh_registry_test.go b/sdk/auth/refresh_registry_test.go index 402ef69aec5..050dcf9a0da 100644 --- a/sdk/auth/refresh_registry_test.go +++ b/sdk/auth/refresh_registry_test.go @@ -21,6 +21,7 @@ func TestProviderRefreshLeads(t *testing.T) { {name: "xai", authenticator: NewXAIAuthenticator(), want: 5 * time.Minute}, {name: "devin", authenticator: NewDevinAuthenticator(), wantNil: true}, {name: "meta", authenticator: NewMetaAuthenticator(), wantNil: true}, + {name: "mistral", authenticator: NewMistralAuthenticator(), wantNil: true}, } for _, test := range tests { From 6982c751ac6b85dfe0da9b302e26393b9ad92aaa Mon Sep 17 00:00:00 2001 From: bntvllnt <32437578+bntvllnt@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:15:02 +0000 Subject: [PATCH 5/8] feat(management): add Mistral sign-in to v8 OAuth API Dispatch provider=mistral from /v8/management/oauth/auth-url to a sign-in flow that returns the sign-in url and state. Status and cancel reuse the generic v8 OAuth session routes. Mistral keys carry no email or account id, so targeted re-login is allowed like Kimi. --- .../auth_files_mistral_oauth_test.go | 391 ++++++++++++++++++ .../management/auth_files_provider_oauth.go | 73 +++- .../api/handlers/management/auth_files_v8.go | 2 + 3 files changed, 465 insertions(+), 1 deletion(-) create mode 100644 internal/api/handlers/management/auth_files_mistral_oauth_test.go diff --git a/internal/api/handlers/management/auth_files_mistral_oauth_test.go b/internal/api/handlers/management/auth_files_mistral_oauth_test.go new file mode 100644 index 00000000000..67b11f60ecf --- /dev/null +++ b/internal/api/handlers/management/auth_files_mistral_oauth_test.go @@ -0,0 +1,391 @@ +package management + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "strings" + "sync" + "testing" + "time" + + "github.com/gin-gonic/gin" + mistralauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/mistral" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +const mistralTestAPIKey = "sk-mgmt-test-key" + +// mistralSignInFake serves the Mistral sign-in endpoints. The poll answer is switchable +// so a test decides when the user "approves" the sign-in. +type mistralSignInFake struct { + server *httptest.Server + // polled is closed once the first poll request has been served. + polled chan struct{} + pollOnce sync.Once + + mu sync.Mutex + pollBody string + startStatus int + exchanges int +} + +func newMistralSignInFake(t *testing.T, pollInterval time.Duration) *mistralSignInFake { + t.Helper() + fake := &mistralSignInFake{polled: make(chan struct{}), pollBody: `{"status":"pending"}`} + mux := http.NewServeMux() + mux.HandleFunc("POST /api/vibe/sign-in", func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + fake.mu.Lock() + status := fake.startStatus + fake.mu.Unlock() + if status != 0 { + http.Error(w, `{"message":"Too many requests."}`, status) + return + } + _, _ = io.WriteString(w, `{"process_id":"pid","sign_in_url":"`+fake.server.URL+`/vibe/sign-in/pid?complete_token=secret","poll_url":"`+ + fake.server.URL+`/api/vibe/sign-in/pid/poll","expires_at":"`+time.Now().Add(5*time.Minute).UTC().Format(time.RFC3339)+`"}`) + }) + mux.HandleFunc("GET /api/vibe/sign-in/pid/poll", func(w http.ResponseWriter, _ *http.Request) { + fake.mu.Lock() + body := fake.pollBody + fake.mu.Unlock() + _, _ = io.WriteString(w, body) + fake.pollOnce.Do(func() { close(fake.polled) }) + }) + mux.HandleFunc("POST /api/vibe/sign-in/pid/exchange", func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + fake.mu.Lock() + fake.exchanges++ + fake.mu.Unlock() + _, _ = io.WriteString(w, `{"api_key":"`+mistralTestAPIKey+`"}`) + }) + fake.server = httptest.NewServer(mux) + t.Cleanup(fake.server.Close) + t.Cleanup(mistralauth.OverrideEndpointsForTest(fake.server.URL+"/api", fake.server.URL+"/v1", pollInterval)) + return fake +} + +// waitForFirstPoll blocks until the sign-in waiter has made one real poll request. +func (f *mistralSignInFake) waitForFirstPoll(t *testing.T) { + t.Helper() + select { + case <-f.polled: + case <-time.After(10 * time.Second): + t.Fatal("sign-in waiter never polled") + } +} + +func (f *mistralSignInFake) setPollBody(body string) { + f.mu.Lock() + f.pollBody = body + f.mu.Unlock() +} + +func (f *mistralSignInFake) exchangeCount() int { + f.mu.Lock() + defer f.mu.Unlock() + return f.exchanges +} + +// observedMistralService wraps the real client and reports when the sign-in waiter ends. +type observedMistralService struct { + mistralOAuthService + waitReturned chan error +} + +func (o *observedMistralService) WaitForSignIn(ctx context.Context, signIn *mistralauth.SignIn) (*mistralauth.Credential, error) { + cred, err := o.mistralOAuthService.WaitForSignIn(ctx, signIn) + o.waitReturned <- err + return cred, err +} + +func observeMistralWaiter(t *testing.T) chan error { + t.Helper() + waitReturned := make(chan error, 1) + orig := newMistralOAuthService + newMistralOAuthService = func(cfg *config.Config, proxyURL string) mistralOAuthService { + return &observedMistralService{mistralOAuthService: orig(cfg, proxyURL), waitReturned: waitReturned} + } + t.Cleanup(func() { newMistralOAuthService = orig }) + return waitReturned +} + +func newMistralOAuthRouter(authDir string, manager *coreauth.Manager) *gin.Engine { + gin.SetMode(gin.TestMode) + h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir, Port: 8317}, manager) + router := gin.New() + router.GET("/v8/management/oauth/auth-url", h.StartOAuthV8) + router.POST("/v8/management/oauth/auth-url", h.StartOAuthV8) + router.GET("/v8/management/oauth/status", h.GetAuthStatus) + router.DELETE("/v8/management/oauth/session", h.CancelAuthSession) + return router +} + +func doMistralRequest(t *testing.T, router http.Handler, method, target, body string) (int, map[string]any, string) { + t.Helper() + req := httptest.NewRequest(method, target, strings.NewReader(body)) + if body != "" { + req.Header.Set("Content-Type", "application/json") + } + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + var parsed map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &parsed) + return rec.Code, parsed, rec.Body.String() +} + +func jsonFilesIn(t *testing.T, dir string) []string { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatalf("ReadDir: %v", err) + } + var names []string + for _, entry := range entries { + if strings.HasSuffix(entry.Name(), ".json") { + names = append(names, entry.Name()) + } + } + return names +} + +func TestStartOAuthV8MistralSignInSavesPrivateAuthFile(t *testing.T) { + fake := newMistralSignInFake(t, 10*time.Millisecond) + authDir := t.TempDir() + router := newMistralOAuthRouter(authDir, coreauth.NewManager(nil, nil, nil)) + + code, start, rawStart := doMistralRequest(t, router, http.MethodGet, "/v8/management/oauth/auth-url?provider=mistral", "") + if code != http.StatusOK || start["status"] != "ok" { + t.Fatalf("auth-url = %d %s", code, rawStart) + } + state, _ := start["state"].(string) + t.Cleanup(func() { CancelOAuthSession(state) }) + if !strings.HasPrefix(state, "mistral-") { + t.Fatalf("state = %q, want a mistral- prefix", state) + } + if want := fake.server.URL + "/vibe/sign-in/pid?complete_token=secret"; start["url"] != want { + t.Fatalf("url = %v, want %q", start["url"], want) + } + if start["flow"] != "device" { + t.Fatalf("flow = %v, want device", start["flow"]) + } + if expiresIn, _ := start["expires_in"].(float64); expiresIn <= 0 || expiresIn > 900 { + t.Fatalf("expires_in = %v, want within (0, 900]", start["expires_in"]) + } + if _, hasUserCode := start["user_code"]; hasUserCode { + t.Fatalf("Mistral sign-in has no user code: %s", rawStart) + } + + // Not approved yet: after at least one real poll the session is still waiting. + fake.waitForFirstPoll(t) + _, waiting, rawWaiting := doMistralRequest(t, router, http.MethodGet, "/v8/management/oauth/status?state="+state, "") + if waiting["status"] != "wait" { + t.Fatalf("status before approval = %s, want wait", rawWaiting) + } + if files := jsonFilesIn(t, authDir); len(files) != 0 { + t.Fatalf("auth files before approval: %v", files) + } + + fake.setPollBody(`{"status":"completed","exchange_token":"exch"}`) + done := pollOAuthStatusUntilDone(t, router, state) + if done["status"] != "ok" { + t.Fatalf("status after approval = %v", done) + } + if fake.exchangeCount() != 1 { + t.Fatalf("exchange calls = %d, want 1", fake.exchangeCount()) + } + + // The session completes only after the save, so the file is already on disk. + files := jsonFilesIn(t, authDir) + if len(files) != 1 || !regexp.MustCompile(`^mistral-[0-9a-f]{16}\.json$`).MatchString(files[0]) { + t.Fatalf("auth files = %v, want exactly one mistral-.json", files) + } + savedPath := filepath.Join(authDir, files[0]) + info, err := os.Stat(savedPath) + if err != nil { + t.Fatalf("auth file missing: %v", err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("auth file mode = %v, want 0600", info.Mode().Perm()) + } + raw, _ := os.ReadFile(savedPath) + var saved map[string]any + if err := json.Unmarshal(raw, &saved); err != nil { + t.Fatalf("auth file is not JSON: %v", err) + } + wantFields := map[string]any{"type": "mistral", "auth_kind": "oauth", "api_key": mistralTestAPIKey, "base_url": fake.server.URL + "/v1"} + for key, want := range wantFields { + if saved[key] != want { + t.Fatalf("saved[%q] = %v, want %v", key, saved[key], want) + } + } + if label, _ := saved["label"].(string); !strings.HasPrefix(label, "Mistral (") || strings.Contains(label, mistralTestAPIKey) { + t.Fatalf("saved label = %q", label) + } + + // The provisioned key must never be echoed to the management client. + for _, body := range []string{rawStart, rawWaiting} { + if strings.Contains(body, mistralTestAPIKey) { + t.Fatalf("management response leaked the api key: %s", body) + } + } + _, _, rawDone := doMistralRequest(t, router, http.MethodGet, "/v8/management/oauth/status?state="+state, "") + if strings.Contains(rawDone, mistralTestAPIKey) { + t.Fatalf("completed status leaked the api key: %s", rawDone) + } +} + +func TestStartOAuthV8MistralSignInFailuresReportErrorAndWriteNothing(t *testing.T) { + cases := []struct { + name string + pollBody string + wantErr string + }{ + {name: "denied", pollBody: `{"status":"denied"}`, wantErr: "sign-in was denied"}, + {name: "expired", pollBody: `{"status":"expired"}`, wantErr: "sign-in expired"}, + {name: "provider error", pollBody: `{"status":"error","message":"boom"}`, wantErr: "sign-in failed"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + fake := newMistralSignInFake(t, 10*time.Millisecond) + fake.setPollBody(tc.pollBody) + authDir := t.TempDir() + router := newMistralOAuthRouter(authDir, coreauth.NewManager(nil, nil, nil)) + + code, start, rawStart := doMistralRequest(t, router, http.MethodGet, "/v8/management/oauth/auth-url?provider=mistral", "") + if code != http.StatusOK { + t.Fatalf("auth-url = %d %s", code, rawStart) + } + state, _ := start["state"].(string) + t.Cleanup(func() { CancelOAuthSession(state) }) + + done := pollOAuthStatusUntilDone(t, router, state) + message, _ := done["error"].(string) + if done["status"] != "error" || !strings.Contains(message, tc.wantErr) { + t.Fatalf("status = %v, want an error containing %q", done, tc.wantErr) + } + if fake.exchangeCount() != 0 { + t.Fatalf("a failed sign-in must not reach the exchange step, got %d calls", fake.exchangeCount()) + } + if files := jsonFilesIn(t, authDir); len(files) != 0 { + t.Fatalf("failed sign-in wrote auth files: %v", files) + } + }) + } +} + +func TestStartOAuthV8MistralStartFailureReturnsServerError(t *testing.T) { + fake := newMistralSignInFake(t, 10*time.Millisecond) + fake.mu.Lock() + fake.startStatus = http.StatusTooManyRequests + fake.mu.Unlock() + authDir := t.TempDir() + router := newMistralOAuthRouter(authDir, coreauth.NewManager(nil, nil, nil)) + + code, _, raw := doMistralRequest(t, router, http.MethodGet, "/v8/management/oauth/auth-url?provider=mistral", "") + if code != http.StatusInternalServerError || !strings.Contains(raw, "failed to start sign-in") { + t.Fatalf("auth-url = %d %s, want 500 failed to start sign-in", code, raw) + } + if strings.Contains(raw, fake.server.URL) { + t.Fatalf("error body leaked the upstream URL: %s", raw) + } + if files := jsonFilesIn(t, authDir); len(files) != 0 { + t.Fatalf("failed start wrote auth files: %v", files) + } +} + +func TestCancelAuthSessionStopsMistralSignIn(t *testing.T) { + fake := newMistralSignInFake(t, 10*time.Millisecond) + waitReturned := observeMistralWaiter(t) + authDir := t.TempDir() + router := newMistralOAuthRouter(authDir, coreauth.NewManager(nil, nil, nil)) + + code, start, rawStart := doMistralRequest(t, router, http.MethodGet, "/v8/management/oauth/auth-url?provider=mistral", "") + if code != http.StatusOK { + t.Fatalf("auth-url = %d %s", code, rawStart) + } + state, _ := start["state"].(string) + t.Cleanup(func() { CancelOAuthSession(state) }) + fake.waitForFirstPoll(t) + + code, cancelled, raw := doMistralRequest(t, router, http.MethodDelete, "/v8/management/oauth/session?state="+state, "") + if code != http.StatusOK || cancelled["status"] != "ok" || cancelled["cancelled"] != true { + t.Fatalf("cancel = %d %s", code, raw) + } + + // The session watcher notices the cancellation within a couple of seconds and stops polling. + select { + case err := <-waitReturned: + if !errors.Is(err, context.Canceled) { + t.Fatalf("waiter ended with %v, want context.Canceled", err) + } + case <-time.After(10 * time.Second): + t.Fatal("sign-in waiter did not stop after the session was cancelled") + } + + // An approval arriving after the cancel must not produce credentials. + fake.setPollBody(`{"status":"completed","exchange_token":"exch"}`) + _, after, rawAfter := doMistralRequest(t, router, http.MethodGet, "/v8/management/oauth/status?state="+state, "") + if after["status"] == "ok" { + t.Fatalf("cancelled session reports ok: %s", rawAfter) + } + if fake.exchangeCount() != 0 { + t.Fatalf("cancelled sign-in reached the exchange step %d times", fake.exchangeCount()) + } + if files := jsonFilesIn(t, authDir); len(files) != 0 { + t.Fatalf("cancelled sign-in wrote auth files: %v", files) + } +} + +func TestTargetedOAuthReloginMistralReplacesRejectedKeyInPlace(t *testing.T) { + fake := newMistralSignInFake(t, 10*time.Millisecond) + fake.setPollBody(`{"status":"completed","exchange_token":"exch"}`) + authDir := t.TempDir() + + targetFile := "mistral-0123456789abcdef.json" + targetPath := filepath.Join(authDir, targetFile) + oldMetadata := map[string]any{"type": "mistral", "auth_kind": "oauth", "api_key": "sk-old-rejected-key", "base_url": fake.server.URL + "/v1"} + rawOld, _ := json.Marshal(oldMetadata) + if err := os.WriteFile(targetPath, rawOld, 0o600); err != nil { + t.Fatalf("write target file: %v", err) + } + manager := coreauth.NewManager(nil, nil, nil) + if _, err := manager.Register(context.Background(), &coreauth.Auth{ + ID: targetFile, + FileName: targetFile, + Provider: "mistral", + RequiresSignIn: true, + Metadata: oldMetadata, + Attributes: map[string]string{coreauth.AttributePath: targetPath}, + }); err != nil { + t.Fatalf("register target: %v", err) + } + router := newMistralOAuthRouter(authDir, manager) + + code, start, raw := doMistralRequest(t, router, http.MethodPost, "/v8/management/oauth/auth-url", `{"provider":"mistral","name":"`+targetFile+`"}`) + if code != http.StatusOK || start["target_auth_id"] != targetFile { + t.Fatalf("targeted auth-url = %d %s", code, raw) + } + state, _ := start["state"].(string) + t.Cleanup(func() { CancelOAuthSession(state) }) + + done := pollOAuthStatusUntilDone(t, router, state) + if done["status"] != "ok" || done["auth_id"] != targetFile || done["saved"] != true { + t.Fatalf("targeted status = %v", done) + } + if files := jsonFilesIn(t, authDir); len(files) != 1 || files[0] != targetFile { + t.Fatalf("auth files = %v, want only %s", files, targetFile) + } + rawSaved, _ := os.ReadFile(targetPath) + if !strings.Contains(string(rawSaved), mistralTestAPIKey) || strings.Contains(string(rawSaved), "sk-old-rejected-key") { + t.Fatalf("target file was not updated in place: %s", rawSaved) + } +} diff --git a/internal/api/handlers/management/auth_files_provider_oauth.go b/internal/api/handlers/management/auth_files_provider_oauth.go index 0d057981660..8506ef4b961 100644 --- a/internal/api/handlers/management/auth_files_provider_oauth.go +++ b/internal/api/handlers/management/auth_files_provider_oauth.go @@ -21,6 +21,7 @@ import ( "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/kimi" metaauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/meta" + mistralauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/mistral" xaiauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/xai" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" "github.com/router-for-me/CLIProxyAPI/v8/internal/misc" @@ -69,6 +70,11 @@ type metaOAuthService interface { CreateTokenStorage(bundle *metaauth.MetaAuthBundle) *metaauth.MetaTokenStorage } +type mistralOAuthService interface { + StartSignIn(ctx context.Context) (*mistralauth.SignIn, error) + WaitForSignIn(ctx context.Context, signIn *mistralauth.SignIn) (*mistralauth.Credential, error) +} + var ( newClaudeOAuthService = func(cfg *config.Config, proxyURL string) claudeOAuthService { return claude.NewClaudeAuthWithProxyURL(cfg, proxyURL) @@ -82,6 +88,9 @@ var ( newMetaOAuthService = func(cfg *config.Config, proxyURL string) metaOAuthService { return metaauth.NewMetaAuthWithProxyURL(cfg, proxyURL) } + newMistralOAuthService = func(cfg *config.Config, proxyURL string) mistralOAuthService { + return mistralauth.NewMistralAuthWithProxyURL(cfg, proxyURL) + } ) func bindOAuthSessionTarget(c *gin.Context, state string, respPayload gin.H) (oauthRecoveryTarget, bool) { @@ -422,7 +431,7 @@ func (h *Handler) RequestCodexToken(c *gin.Context) { func isIdentitylessOAuthProvider(provider string) bool { trimmed := strings.ToLower(strings.TrimSpace(provider)) - return trimmed == "kimi" || trimmed == "kimi-ai" + return trimmed == "kimi" || trimmed == "kimi-ai" || trimmed == "mistral" } func matchesOAuthRecoveryTarget(target oauthRecoveryTarget, email, accountID, candidateFileName string) bool { @@ -1080,6 +1089,68 @@ func (h *Handler) RequestMetaToken(c *gin.Context) { c.JSON(200, response) } +// RequestMistralToken starts the Mistral Vibe browser sign-in. The caller opens the +// returned url; progress and cancellation use the generic OAuth status/session routes. +func (h *Handler) RequestMistralToken(c *gin.Context) { + ctx := context.Background() + ctx = PopulateAuthContext(ctx, c) + + fmt.Println("Initializing Mistral authentication...") + + sessionProxyURL := oauthSessionProxyURLFromContext(c) + cfg := h.oauthConfigWithProxy(sessionProxyURL) + state := fmt.Sprintf("mistral-%d", time.Now().UnixNano()) + authSvc := newMistralOAuthService(cfg, sessionProxyURL) + + signIn, errStartSignIn := authSvc.StartSignIn(ctx) + if errStartSignIn != nil { + log.Errorf("Failed to start Mistral sign-in: %s", redactSessionProxyInString(errStartSignIn.Error(), sessionProxyURL)) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start sign-in"}) + return + } + + RegisterOAuthSessionWithProxy(state, "mistral", sessionProxyURL) + response := gin.H{ + "status": "ok", + "url": strings.TrimSpace(signIn.URL), + "state": state, + "flow": "device", + "expires_in": int(signIn.Lifetime / time.Second), + } + bindOAuthSessionTarget(c, state, response) + + go func() { + pollCtx, cancelPoll := context.WithCancel(ctx) + defer cancelPoll() + go watchOAuthSessionCancel(pollCtx, cancelPoll, state, "mistral") + + fmt.Println("Waiting for Mistral authentication...") + cred, errWaitForSignIn := authSvc.WaitForSignIn(pollCtx, signIn) + if errWaitForSignIn != nil { + if !IsOAuthSessionPending(state, "mistral") { + return + } + log.Errorf("Mistral authentication failed: %s", redactSessionProxyInString(errWaitForSignIn.Error(), sessionProxyURL)) + SetOAuthSessionError(state, redactSessionProxyInString(oauthSessionErrorWithCause("Authentication failed", errWaitForSignIn), sessionProxyURL)) + return + } + if !IsOAuthSessionPending(state, "mistral") { + return + } + + record := sdkAuth.NewMistralAuthRecord(cred) + savedPath, okSaved := h.commitAndCompleteBuiltinOAuthSession(ctx, state, "mistral", sessionProxyURL, record, "Failed to save token to file", false) + if !okSaved { + return + } + + fmt.Printf("Authentication successful! Token saved to %s\n", savedPath) + fmt.Println("You can now use Mistral services through this CLI") + }() + + c.JSON(200, response) +} + func buildMetaAuthRecord(bundle *metaauth.MetaAuthBundle, tokenStorage *metaauth.MetaTokenStorage) *coreauth.Auth { fileName := metaauth.CredentialFileName(tokenStorage.Email, tokenStorage.DCAToken) label := strings.TrimSpace(tokenStorage.Email) diff --git a/internal/api/handlers/management/auth_files_v8.go b/internal/api/handlers/management/auth_files_v8.go index 721d1d9a53a..b6e4e4a0fb4 100644 --- a/internal/api/handlers/management/auth_files_v8.go +++ b/internal/api/handlers/management/auth_files_v8.go @@ -419,6 +419,8 @@ func (h *Handler) StartOAuthV8(c *gin.Context) { h.RequestDevinToken(c) case "meta": h.RequestMetaToken(c) + case "mistral": + h.RequestMistralToken(c) default: if !h.ServePluginAuthURL(c) { c.JSON(http.StatusNotFound, gin.H{"error": "provider_not_found"}) From 2b4e7792b9db1dd832bb6e6dfee100c4291d5bbc Mon Sep 17 00:00:00 2001 From: bntvllnt <32437578+bntvllnt@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:34:59 +0000 Subject: [PATCH 6/8] feat(sdk): register Mistral executor and models for sign-in credentials Bind the Mistral provider to the shared OpenAI-compatible executor and publish the static Mistral model list for each Mistral credential, honoring oauth-excluded-models. --- sdk/cliproxy/service_executors.go | 4 ++ sdk/cliproxy/service_mistral_test.go | 89 ++++++++++++++++++++++++++++ sdk/cliproxy/service_models.go | 3 + 3 files changed, 96 insertions(+) create mode 100644 sdk/cliproxy/service_mistral_test.go diff --git a/sdk/cliproxy/service_executors.go b/sdk/cliproxy/service_executors.go index 0ad196e297b..36b697b0e3f 100644 --- a/sdk/cliproxy/service_executors.go +++ b/sdk/cliproxy/service_executors.go @@ -222,6 +222,7 @@ func baselineExecutorAuths() []*coreauth.Auth { "xai", "devin", "meta", + "mistral", "openai-compatibility", } auths := make([]*coreauth.Auth, 0, len(providers)) @@ -333,6 +334,9 @@ func (s *Service) registerExecutorForAuth(a *coreauth.Auth, forceReplace bool) { s.coreManager.RegisterExecutor(executor.NewDevinExecutor(cfg)) case "meta": s.coreManager.RegisterExecutor(executor.NewMetaExecutor(cfg)) + case "mistral": + // Mistral serves an OpenAI-compatible API; the sign-in credential carries its base URL and key. + s.registerOpenAICompatProviderExecutor("mistral", a, cfg, forceReplace, false) default: providerKey := strings.ToLower(strings.TrimSpace(a.Provider)) if providerKey == "" { diff --git a/sdk/cliproxy/service_mistral_test.go b/sdk/cliproxy/service_mistral_test.go new file mode 100644 index 00000000000..6b7195525f7 --- /dev/null +++ b/sdk/cliproxy/service_mistral_test.go @@ -0,0 +1,89 @@ +package cliproxy + +import ( + "context" + "testing" + + internalregistry "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" +) + +// mistralSignInAuth is the shape of a credential produced by the Mistral sign-in: the key +// and base URL live in Metadata only. +func mistralSignInAuth() *coreauth.Auth { + return &coreauth.Auth{ + ID: "mistral-0123456789abcdef.json", + Provider: "mistral", + Status: coreauth.StatusActive, + Metadata: map[string]any{ + "type": "mistral", + "auth_kind": "oauth", + "api_key": "sk-service-test-key", + "base_url": "https://api.mistral.ai/v1", + }, + } +} + +func TestRegisterExecutorForAuth_MistralUsesOpenAICompatExecutor(t *testing.T) { + service := &Service{ + cfg: &config.Config{}, + coreManager: coreauth.NewManager(nil, nil, nil), + } + + service.ensureExecutorsForAuth(mistralSignInAuth()) + + registered, ok := service.coreManager.Executor("mistral") + if !ok || registered == nil { + t.Fatal("expected a mistral executor after binding a mistral credential") + } + if _, isCompat := registered.(*executor.OpenAICompatExecutor); !isCompat { + t.Fatalf("mistral executor type = %T, want *executor.OpenAICompatExecutor", registered) + } + if registered.Identifier() != "mistral" { + t.Fatalf("mistral executor identifier = %q", registered.Identifier()) + } +} + +func TestBaselineExecutorAuthsIncludeMistral(t *testing.T) { + for _, auth := range baselineExecutorAuths() { + if auth.Provider == "mistral" { + return + } + } + t.Fatal("baseline executors must include mistral so the executor exists before the first credential loads") +} + +func TestRegisterModelsForAuth_MistralPublishesStaticModelsAndHonorsExclusions(t *testing.T) { + service := &Service{ + cfg: &config.Config{ + OAuthExcludedModels: map[string][]string{ + "mistral": {"mistral-small-latest"}, + }, + }, + } + auth := mistralSignInAuth() + + registry := GlobalModelRegistry() + registry.UnregisterClient(auth.ID) + t.Cleanup(func() { registry.UnregisterClient(auth.ID) }) + + service.registerModelsForAuth(context.Background(), auth) + + registered := map[string]bool{} + for _, model := range registry.GetModelsForClient(auth.ID) { + if model != nil { + registered[model.ID] = true + } + } + for _, model := range internalregistry.GetMistralModels() { + excluded := model.ID == "mistral-small-latest" + if excluded && registered[model.ID] { + t.Fatalf("model %q is excluded by oauth-excluded-models but was registered", model.ID) + } + if !excluded && !registered[model.ID] { + t.Fatalf("model %q was not registered for a mistral credential (registered: %v)", model.ID, registered) + } + } +} diff --git a/sdk/cliproxy/service_models.go b/sdk/cliproxy/service_models.go index 7daa6ed1667..ca308423873 100644 --- a/sdk/cliproxy/service_models.go +++ b/sdk/cliproxy/service_models.go @@ -211,6 +211,9 @@ func (s *Service) registerModelsForAuthWithConfigAndCache(ctx context.Context, c } } models = applyExcludedModels(models, excluded) + case "mistral": + models = registry.GetMistralModels() + models = applyExcludedModels(models, excluded) default: // Handle OpenAI-compatibility providers by name using config if cfg != nil { From 207756a2e241173a551716c65bf91c04732cd35b Mon Sep 17 00:00:00 2001 From: bntvllnt <32437578+bntvllnt@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:35:59 +0000 Subject: [PATCH 7/8] feat(tui,docs): list Mistral sign-in in the TUI and v8 docs Add Mistral to the TUI OAuth provider list and the v8 provider table, and document the mistral provider in the v8 management API docs. --- docs/management-api-v8.md | 12 +++++++++++- internal/tui/client.go | 1 + internal/tui/client_v8_test.go | 30 ++++++++++++++++++++++++++++++ internal/tui/oauth_tab.go | 1 + 4 files changed, 43 insertions(+), 1 deletion(-) diff --git a/docs/management-api-v8.md b/docs/management-api-v8.md index 3dbc15daf73..5fe415c054f 100644 --- a/docs/management-api-v8.md +++ b/docs/management-api-v8.md @@ -164,7 +164,7 @@ retain the corresponding business operation's fields. The login URL is shared by all providers. Set the required `provider` query parameter to `claude`, `codex`, `antigravity`, `kimi`, `kimi-ai`, `xai`, `devin`, -`meta`, or a registered plugin provider ID. For example: +`meta`, `mistral`, or a registered plugin provider ID. For example: ```http GET /v8/management/oauth/auth-url?provider=codex @@ -189,6 +189,16 @@ an explicit provider must match that state. Poll until the status is `ok` or `error`; `wait` means the login is still pending. Callback acceptance alone does not mean credential exchange and persistence have completed. +`mistral` signs in a Mistral Vibe or Le Chat Pro account through the browser. +The response has `flow: "device"`, the sign-in `url` to open, the `state`, and +`expires_in` (seconds); there is no `user_code`. Poll `/oauth/status` until it is +`ok` or `error`, or cancel with `DELETE /oauth/session`. A successful sign-in +saves `mistral-.json` (mode `0600`) holding an API key that does not +expire and has no refresh token. Requests use that key against +`https://api.mistral.ai/v1`. If Mistral rejects the key, re-run the sign-in +with `name` set to the credential file to replace it in place. The CLI flag is +`--mistral-login`. + Import uses `POST /v8/management/oauth/import?provider=vertex`. The `provider` query parameter is required; Vertex is currently the supported import provider. diff --git a/internal/tui/client.go b/internal/tui/client.go index c7f5d9442e4..edd411bdcb9 100644 --- a/internal/tui/client.go +++ b/internal/tui/client.go @@ -1058,6 +1058,7 @@ var oauthV8Provider = map[string]string{ "xai-auth-url": "xai", "devin-auth-url": "devin", "meta-auth-url": "meta", + "mistral-auth-url": "mistral", } // StartOAuthFlow begins an OAuth login for the given provider. It prefers the diff --git a/internal/tui/client_v8_test.go b/internal/tui/client_v8_test.go index 90f5a13b265..0ebf5e2588d 100644 --- a/internal/tui/client_v8_test.go +++ b/internal/tui/client_v8_test.go @@ -265,6 +265,36 @@ func TestClient_V8OAuthStartPrefersSharedEndpoint(t *testing.T) { } } +// TestOAuthProvidersMapToV8Providers keeps the TUI provider list and the v8 provider +// table in step, and checks the Mistral entry starts a device-style v8 flow. +func TestOAuthProvidersMapToV8Providers(t *testing.T) { + var mistral *oauthProvider + for i, p := range oauthProviders { + if oauthV8Provider[p.apiPath] == "" { + t.Errorf("provider %q (%s) has no v8 provider mapping", p.name, p.apiPath) + } + if p.apiPath == "mistral-auth-url" { + mistral = &oauthProviders[i] + } + } + if mistral == nil || !mistral.deviceFlow { + t.Fatalf("expected a Mistral device-flow entry in oauthProviders, got %+v", mistral) + } + + var gotProvider string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotProvider = r.URL.Query().Get("provider") + writeJSON(t, w, map[string]any{"url": "https://x", "state": "s", "flow": "device"}) + })) + defer srv.Close() + if _, err := NewClientWithBaseURL(srv.URL, "secret").StartOAuthFlow(mistral.apiPath); err != nil { + t.Fatalf("StartOAuthFlow: %v", err) + } + if gotProvider != "mistral" { + t.Fatalf("provider = %q, want mistral", gotProvider) + } +} + // TestClient_V8MissingNodeWrites verifies that an absent config node is treated // as an empty value on the v8 contract (not a missing route), so the TUI can // create the first access.api-keys entry and reads empty provider lists. diff --git a/internal/tui/oauth_tab.go b/internal/tui/oauth_tab.go index 545ccee1746..0e15a7edf1d 100644 --- a/internal/tui/oauth_tab.go +++ b/internal/tui/oauth_tab.go @@ -27,6 +27,7 @@ var oauthProviders = []oauthProvider{ {"Kimi (kimi.ai)", "kimi-ai-auth-url", "🟫", true}, {"xAI", "xai-auth-url", "⬛", true}, {"Meta", "meta-auth-url", "🔵", true}, + {"Mistral (Vibe / Le Chat Pro)", "mistral-auth-url", "🟠", true}, } // oauthTabModel handles OAuth login flows. From d7e02d2402d736953175a61d2d14b322a7edeb34 Mon Sep 17 00:00:00 2001 From: bntvllnt <32437578+bntvllnt@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:45:36 +0000 Subject: [PATCH 8/8] test: cover Mistral sign-in end to end and watcher reload Drive the v8 sign-in against a fake Mistral service, then serve OpenAI and Claude format requests (stream and non-stream) with the provisioned key. Add denied sign-in and upstream 401 cases, and a service-level test that a saved credential file is picked up by the watcher. --- sdk/cliproxy/service_mistral_test.go | 58 ++++ test/mistral_login_e2e_test.go | 494 +++++++++++++++++++++++++++ 2 files changed, 552 insertions(+) create mode 100644 test/mistral_login_e2e_test.go diff --git a/sdk/cliproxy/service_mistral_test.go b/sdk/cliproxy/service_mistral_test.go index 6b7195525f7..13b9500ed07 100644 --- a/sdk/cliproxy/service_mistral_test.go +++ b/sdk/cliproxy/service_mistral_test.go @@ -3,9 +3,12 @@ package cliproxy import ( "context" "testing" + "time" + mistralauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/mistral" internalregistry "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + sdkAuth "github.com/router-for-me/CLIProxyAPI/v8/sdk/auth" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" ) @@ -87,3 +90,58 @@ func TestRegisterModelsForAuth_MistralPublishesStaticModelsAndHonorsExclusions(t } } } + +// TestMistralCredentialFileIsServedAfterWatcherReload covers the seam the CLI sign-in relies +// on: a saved mistral auth file is picked up by the running service, which binds the +// executor, publishes the models, and keeps the key available to requests. +func TestMistralCredentialFileIsServedAfterWatcherReload(t *testing.T) { + h := newIssue6631Harness(t) + cfg := h.service.currentConfig() + // The harness builds the watcher without starting it, and pauses its first config reload. + // Release that pause, then start the watcher so file events flow. + h.releaseFirst() + watcherCtx, cancelWatcher := context.WithCancel(context.Background()) + t.Cleanup(cancelWatcher) + if err := h.service.currentWatcher().Start(watcherCtx); err != nil { + t.Fatalf("start watcher: %v", err) + } + + record := sdkAuth.NewMistralAuthRecord(&mistralauth.Credential{APIKey: "sk-watcher-test-key", BaseURL: "https://api.mistral.ai/v1"}) + registry := GlobalModelRegistry() + t.Cleanup(func() { registry.UnregisterClient(record.ID) }) + + store := sdkAuth.NewFileTokenStore() + store.SetBaseDir(cfg.AuthDir) + if _, err := store.Save(context.Background(), record); err != nil { + t.Fatalf("save credential: %v", err) + } + + // The watcher debounces file events; this deadline only guards against an update that never arrives. + deadline := time.After(15 * time.Second) + poll := time.NewTicker(10 * time.Millisecond) + defer poll.Stop() + for len(registry.GetModelsForClient(record.ID)) == 0 { + select { + case <-deadline: + t.Fatal("the watcher never published models for the saved mistral credential") + case <-poll.C: + } + } + + published := map[string]bool{} + for _, model := range registry.GetModelsForClient(record.ID) { + published[model.ID] = true + } + for _, model := range internalregistry.GetMistralModels() { + if !published[model.ID] { + t.Fatalf("model %q missing after reload (published: %v)", model.ID, published) + } + } + if _, ok := h.service.coreManager.Executor("mistral"); !ok { + t.Fatal("no mistral executor bound after reload") + } + loaded, ok := h.service.coreManager.GetByID(record.ID) + if !ok || loaded.Provider != "mistral" || loaded.Metadata["api_key"] != "sk-watcher-test-key" || loaded.Metadata["base_url"] != "https://api.mistral.ai/v1" { + t.Fatalf("reloaded credential = %+v, want the saved key and base URL in metadata", loaded) + } +} diff --git a/test/mistral_login_e2e_test.go b/test/mistral_login_e2e_test.go new file mode 100644 index 00000000000..577c80a2e43 --- /dev/null +++ b/test/mistral_login_e2e_test.go @@ -0,0 +1,494 @@ +package test + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "golang.org/x/crypto/bcrypt" + + configaccess "github.com/router-for-me/CLIProxyAPI/v8/internal/access/config_access" + "github.com/router-for-me/CLIProxyAPI/v8/internal/api" + mistralauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/mistral" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + runtimeexecutor "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor" + _ "github.com/router-for-me/CLIProxyAPI/v8/internal/translator" + "github.com/router-for-me/CLIProxyAPI/v8/internal/watcher/synthesizer" + sdkaccess "github.com/router-for-me/CLIProxyAPI/v8/sdk/access" + sdkAuth "github.com/router-for-me/CLIProxyAPI/v8/sdk/auth" + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +const ( + mistralE2EManagementKey = "mistral-e2e-management-key" + mistralE2EClientKey = "mistral-e2e-client-key" + mistralE2EProvisioned = "sk-e2e-provisioned-key" + mistralE2EModel = "mistral-large-4-0" + mistralE2EReply = "hello from fake mistral" +) + +type mistralUpstreamRequest struct { + Path string + Authorization string + APIKeyHeader string + Body map[string]any +} + +// fakeMistralService plays both Mistral sides: the console sign-in API and the +// OpenAI-compatible inference API. +type fakeMistralService struct { + server *httptest.Server + // exchanged is closed once the sign-in exchange endpoint has been served. + exchanged chan struct{} + once sync.Once + + mu sync.Mutex + pollBody string + chat []mistralUpstreamRequest + chatStatus int +} + +func newFakeMistralService(t *testing.T) *fakeMistralService { + t.Helper() + fake := &fakeMistralService{exchanged: make(chan struct{}), pollBody: `{"status":"pending"}`} + mux := http.NewServeMux() + mux.HandleFunc("POST /api/vibe/sign-in", func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + _, _ = io.WriteString(w, `{"process_id":"pid","sign_in_url":"`+fake.server.URL+`/vibe/sign-in/pid?complete_token=t","poll_url":"`+ + fake.server.URL+`/api/vibe/sign-in/pid/poll","expires_at":"`+time.Now().Add(5*time.Minute).UTC().Format(time.RFC3339)+`"}`) + }) + mux.HandleFunc("GET /api/vibe/sign-in/pid/poll", func(w http.ResponseWriter, _ *http.Request) { + fake.mu.Lock() + body := fake.pollBody + fake.mu.Unlock() + _, _ = io.WriteString(w, body) + }) + mux.HandleFunc("POST /api/vibe/sign-in/pid/exchange", func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + _, _ = io.WriteString(w, `{"api_key":"`+mistralE2EProvisioned+`"}`) + fake.once.Do(func() { close(fake.exchanged) }) + }) + mux.HandleFunc("POST /v1/chat/completions", fake.serveChat) + fake.server = httptest.NewServer(mux) + t.Cleanup(fake.server.Close) + t.Cleanup(mistralauth.OverrideEndpointsForTest(fake.server.URL+"/api", fake.server.URL+"/v1", 10*time.Millisecond)) + return fake +} + +func (f *fakeMistralService) serveChat(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + var body map[string]any + _ = json.Unmarshal(raw, &body) + f.mu.Lock() + f.chat = append(f.chat, mistralUpstreamRequest{ + Path: r.URL.Path, + Authorization: r.Header.Get("Authorization"), + APIKeyHeader: r.Header.Get("X-Api-Key"), + Body: body, + }) + status := f.chatStatus + f.mu.Unlock() + + if status != 0 { + w.WriteHeader(status) + _, _ = io.WriteString(w, `{"message":"Unauthorized","request_id":"r1"}`) + return + } + if stream, _ := body["stream"].(bool); stream { + w.Header().Set("Content-Type", "text/event-stream") + chunk := func(delta, finish string) string { + return fmt.Sprintf(`data: {"id":"chatcmpl-e2e","object":"chat.completion.chunk","created":1,"model":%q,"choices":[{"index":0,"delta":%s,"finish_reason":%s}]}`+"\n\n", + mistralE2EModel, delta, finish) + } + _, _ = io.WriteString(w, chunk(`{"role":"assistant","content":"hello "}`, "null")) + _, _ = io.WriteString(w, chunk(`{"content":"from fake mistral"}`, "null")) + _, _ = io.WriteString(w, chunk(`{}`, `"stop"`)) + _, _ = io.WriteString(w, "data: [DONE]\n\n") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"id":"chatcmpl-e2e","object":"chat.completion","created":1,"model":"`+mistralE2EModel+ + `","choices":[{"index":0,"message":{"role":"assistant","content":"`+mistralE2EReply+`"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":4,"total_tokens":7}}`) +} + +func (f *fakeMistralService) setPollBody(body string) { + f.mu.Lock() + f.pollBody = body + f.mu.Unlock() +} + +func (f *fakeMistralService) setChatStatus(status int) { + f.mu.Lock() + f.chatStatus = status + f.mu.Unlock() +} + +func (f *fakeMistralService) chatRequests() []mistralUpstreamRequest { + f.mu.Lock() + defer f.mu.Unlock() + return append([]mistralUpstreamRequest(nil), f.chat...) +} + +// mistralProxy is the real API server (routes, access control, v8 management, executors) +// over a real auth manager and the real file store. +type mistralProxy struct { + t *testing.T + url string + authDir string + cfg *config.Config + manager *coreauth.Manager +} + +func newMistralProxy(t *testing.T) *mistralProxy { + t.Helper() + dir := t.TempDir() + authDir := filepath.Join(dir, "auths") + if err := os.MkdirAll(authDir, 0o700); err != nil { + t.Fatal(err) + } + hashed, err := bcrypt.GenerateFromPassword([]byte(mistralE2EManagementKey), bcrypt.MinCost) + if err != nil { + t.Fatal(err) + } + configPath := filepath.Join(dir, "config.yaml") + raw := fmt.Sprintf("port: 8317\nauth-dir: %q\napi-keys: [%q]\nremote-management:\n allow-remote: true\n secret-key: %q\n", + filepath.ToSlash(authDir), mistralE2EClientKey, string(hashed)) + if err := os.WriteFile(configPath, []byte(raw), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := config.LoadConfig(configPath) + if err != nil { + t.Fatal(err) + } + + store := sdkAuth.GetTokenStore() + if setter, ok := store.(interface{ SetBaseDir(string) }); ok { + setter.SetBaseDir(authDir) + } + manager := coreauth.NewManager(store, &coreauth.RoundRobinSelector{}, nil) + manager.SetConfig(cfg) + // The service binds this executor for the mistral provider (covered in sdk/cliproxy tests). + manager.RegisterExecutor(runtimeexecutor.NewOpenAICompatExecutor("mistral", cfg)) + + configaccess.Register(&cfg.SDKConfig) + accessManager := sdkaccess.NewManager() + accessManager.SetProviders(sdkaccess.RegisteredProviders()) + + server := api.NewServer(cfg, manager, accessManager, configPath) + if server == nil { + t.Fatal("api.NewServer returned nil") + } + httpServer := httptest.NewServer(server.Handler()) + t.Cleanup(httpServer.Close) + return &mistralProxy{t: t, url: httpServer.URL, authDir: authDir, cfg: cfg, manager: manager} +} + +func (p *mistralProxy) do(method, path string, headers map[string]string, body string) (int, http.Header, string) { + p.t.Helper() + req, err := http.NewRequest(method, p.url+path, strings.NewReader(body)) + if err != nil { + p.t.Fatal(err) + } + if body != "" { + req.Header.Set("Content-Type", "application/json") + } + for k, v := range headers { + req.Header.Set(k, v) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + p.t.Fatalf("%s %s: %v", method, path, err) + } + defer func() { _ = resp.Body.Close() }() + raw, _ := io.ReadAll(resp.Body) + return resp.StatusCode, resp.Header, string(raw) +} + +func (p *mistralProxy) management(method, path string) (int, map[string]any) { + p.t.Helper() + code, _, raw := p.do(method, path, map[string]string{"Authorization": "Bearer " + mistralE2EManagementKey}, "") + var parsed map[string]any + _ = json.Unmarshal([]byte(raw), &parsed) + return code, parsed +} + +// waitForSignInResult polls the v8 status route until the session leaves "wait". +func (p *mistralProxy) waitForSignInResult(state string) map[string]any { + p.t.Helper() + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + code, status := p.management(http.MethodGet, "/v8/management/oauth/status?state="+state) + if code != http.StatusOK { + p.t.Fatalf("oauth status HTTP %d", code) + } + if status["status"] != "wait" { + return status + } + } + p.t.Fatalf("sign-in %s did not finish", state) + return nil +} + +func (p *mistralProxy) authFiles() []string { + p.t.Helper() + entries, err := os.ReadDir(p.authDir) + if err != nil { + p.t.Fatal(err) + } + var names []string + for _, entry := range entries { + if strings.HasSuffix(entry.Name(), ".json") { + names = append(names, entry.Name()) + } + } + return names +} + +// adoptSavedCredentials loads the saved auth files the way the file watcher does and +// publishes the credential and its models to the runtime. +func (p *mistralProxy) adoptSavedCredentials() *coreauth.Auth { + p.t.Helper() + auths, err := synthesizer.NewFileSynthesizer().Synthesize(&synthesizer.SynthesisContext{ + Config: p.cfg, + AuthDir: p.authDir, + Now: time.Now(), + IDGenerator: synthesizer.NewStableIDGenerator(), + }) + if err != nil || len(auths) != 1 { + p.t.Fatalf("synthesize = %v, %v; want exactly one credential", auths, err) + } + auth := auths[0] + if auth.Provider != "mistral" { + p.t.Fatalf("synthesized provider = %q, want mistral", auth.Provider) + } + if _, err := p.manager.Register(coreauth.WithSkipPersist(context.Background()), auth); err != nil { + p.t.Fatalf("register credential: %v", err) + } + registry.GetGlobalRegistry().RegisterClient(auth.ID, "mistral", registry.GetMistralModels()) + p.t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + return auth +} + +// signIn drives the v8 management API through an approved Mistral sign-in. +func (p *mistralProxy) signIn(fake *fakeMistralService) { + p.t.Helper() + code, start := p.management(http.MethodGet, "/v8/management/oauth/auth-url?provider=mistral") + if code != http.StatusOK || start["status"] != "ok" { + p.t.Fatalf("auth-url = %d %v", code, start) + } + state, _ := start["state"].(string) + if !strings.HasPrefix(state, "mistral-") || start["url"] == "" || start["flow"] != "device" { + p.t.Fatalf("auth-url response = %v", start) + } + _, waiting := p.management(http.MethodGet, "/v8/management/oauth/status?state="+state) + if waiting["status"] != "wait" { + p.t.Fatalf("status before approval = %v, want wait", waiting) + } + fake.setPollBody(`{"status":"completed","exchange_token":"exch"}`) + select { + case <-fake.exchanged: + case <-time.After(10 * time.Second): + p.t.Fatal("sign-in was never exchanged") + } + if done := p.waitForSignInResult(state); done["status"] != "ok" { + p.t.Fatalf("status after approval = %v, want ok", done) + } +} + +func TestMistralLoginE2E_SignInThenServeOpenAIAndClaudeRequests(t *testing.T) { + fake := newFakeMistralService(t) + proxy := newMistralProxy(t) + + // Management routes are access controlled. + if code, _, _ := proxy.do(http.MethodGet, "/v8/management/oauth/auth-url?provider=mistral", nil, ""); code != http.StatusUnauthorized { + t.Fatalf("auth-url without a management key = %d, want 401", code) + } + + proxy.signIn(fake) + + files := proxy.authFiles() + if len(files) != 1 || !strings.HasPrefix(files[0], "mistral-") { + t.Fatalf("auth files = %v, want one mistral-.json", files) + } + info, err := os.Stat(filepath.Join(proxy.authDir, files[0])) + if err != nil || info.Mode().Perm() != 0o600 { + t.Fatalf("auth file stat = %v, %v; want mode 0600", info, err) + } + + auth := proxy.adoptSavedCredentials() + if auth.Metadata["api_key"] != mistralE2EProvisioned || auth.Metadata["base_url"] != fake.server.URL+"/v1" { + t.Fatalf("reloaded credential lost its key or base URL: %v", auth.Metadata) + } + + t.Run("openai chat completions", func(t *testing.T) { + headers := map[string]string{"Authorization": "Bearer " + mistralE2EClientKey} + code, _, body := proxy.do(http.MethodPost, "/v1/chat/completions", headers, + `{"model":"`+mistralE2EModel+`","messages":[{"role":"user","content":"hi"}]}`) + if code != http.StatusOK { + t.Fatalf("status = %d: %s", code, body) + } + var parsed struct { + Choices []struct { + Message struct{ Content string } `json:"message"` + } `json:"choices"` + } + if err := json.Unmarshal([]byte(body), &parsed); err != nil || len(parsed.Choices) != 1 || parsed.Choices[0].Message.Content != mistralE2EReply { + t.Fatalf("response = %s (err %v), want content %q", body, err, mistralE2EReply) + } + assertLastMistralUpstreamRequest(t, fake, false) + }) + + t.Run("openai chat completions stream", func(t *testing.T) { + headers := map[string]string{"Authorization": "Bearer " + mistralE2EClientKey} + code, respHeaders, body := proxy.do(http.MethodPost, "/v1/chat/completions", headers, + `{"model":"`+mistralE2EModel+`","stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != http.StatusOK || !strings.Contains(respHeaders.Get("Content-Type"), "text/event-stream") { + t.Fatalf("status = %d content-type = %q: %s", code, respHeaders.Get("Content-Type"), body) + } + if !strings.Contains(body, "hello ") || !strings.Contains(body, "from fake mistral") || !strings.Contains(body, "[DONE]") { + t.Fatalf("stream is missing the upstream text or the terminator: %s", body) + } + assertLastMistralUpstreamRequest(t, fake, true) + }) + + t.Run("claude messages", func(t *testing.T) { + headers := map[string]string{"X-Api-Key": mistralE2EClientKey, "Anthropic-Version": "2023-06-01"} + code, _, body := proxy.do(http.MethodPost, "/v1/messages", headers, + `{"model":"`+mistralE2EModel+`","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`) + if code != http.StatusOK { + t.Fatalf("status = %d: %s", code, body) + } + var parsed struct { + Type string `json:"type"` + Role string `json:"role"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"content"` + } + if err := json.Unmarshal([]byte(body), &parsed); err != nil || parsed.Type != "message" || parsed.Role != "assistant" || + len(parsed.Content) == 0 || parsed.Content[0].Text != mistralE2EReply { + t.Fatalf("claude response = %s (err %v), want an assistant message with %q", body, err, mistralE2EReply) + } + assertLastMistralUpstreamRequest(t, fake, false) + }) + + t.Run("claude messages stream", func(t *testing.T) { + headers := map[string]string{"X-Api-Key": mistralE2EClientKey, "Anthropic-Version": "2023-06-01"} + code, respHeaders, body := proxy.do(http.MethodPost, "/v1/messages", headers, + `{"model":"`+mistralE2EModel+`","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != http.StatusOK || !strings.Contains(respHeaders.Get("Content-Type"), "text/event-stream") { + t.Fatalf("status = %d content-type = %q: %s", code, respHeaders.Get("Content-Type"), body) + } + for _, want := range []string{"event: message_start", "content_block_delta", "from fake mistral", "event: message_stop"} { + if !strings.Contains(body, want) { + t.Fatalf("claude stream is missing %q: %s", want, body) + } + } + assertLastMistralUpstreamRequest(t, fake, true) + }) + + t.Run("client access key is required", func(t *testing.T) { + before := len(fake.chatRequests()) + code, _, _ := proxy.do(http.MethodPost, "/v1/chat/completions", map[string]string{"Authorization": "Bearer wrong-key"}, + `{"model":"`+mistralE2EModel+`","messages":[{"role":"user","content":"hi"}]}`) + if code != http.StatusUnauthorized { + t.Fatalf("status with a wrong client key = %d, want 401", code) + } + if after := len(fake.chatRequests()); after != before { + t.Fatalf("a rejected request still reached Mistral (%d -> %d upstream calls)", before, after) + } + }) +} + +// assertLastMistralUpstreamRequest checks what the proxy sent to Mistral for the last client request. +func assertLastMistralUpstreamRequest(t *testing.T, fake *fakeMistralService, wantStream bool) { + t.Helper() + requests := fake.chatRequests() + if len(requests) == 0 { + t.Fatal("no request reached the fake Mistral inference API") + } + got := requests[len(requests)-1] + if got.Path != "/v1/chat/completions" { + t.Errorf("upstream path = %q, want /v1/chat/completions", got.Path) + } + if got.Authorization != "Bearer "+mistralE2EProvisioned { + t.Errorf("upstream Authorization = %q, want the key provisioned by sign-in", got.Authorization) + } + if got.APIKeyHeader != "" { + t.Errorf("client key leaked upstream in X-Api-Key: %q", got.APIKeyHeader) + } + if got.Body["model"] != mistralE2EModel { + t.Errorf("upstream model = %v, want %s", got.Body["model"], mistralE2EModel) + } + if stream, _ := got.Body["stream"].(bool); stream != wantStream { + t.Errorf("upstream stream = %v, want %v", got.Body["stream"], wantStream) + } + if messages, _ := got.Body["messages"].([]any); len(messages) == 0 { + t.Errorf("upstream body has no OpenAI messages: %v", got.Body) + } +} + +func TestMistralLoginE2E_DeniedSignInSavesNothingAndServesNothing(t *testing.T) { + fake := newFakeMistralService(t) + fake.setPollBody(`{"status":"denied"}`) + proxy := newMistralProxy(t) + + code, start := proxy.management(http.MethodGet, "/v8/management/oauth/auth-url?provider=mistral") + if code != http.StatusOK { + t.Fatalf("auth-url = %d %v", code, start) + } + state, _ := start["state"].(string) + done := proxy.waitForSignInResult(state) + if message, _ := done["error"].(string); done["status"] != "error" || !strings.Contains(message, "denied") { + t.Fatalf("status = %v, want an error that mentions the denial", done) + } + if files := proxy.authFiles(); len(files) != 0 { + t.Fatalf("denied sign-in wrote auth files: %v", files) + } + + // No credential means no models: the proxy must not forward the request anywhere. + code, _, body := proxy.do(http.MethodPost, "/v1/chat/completions", map[string]string{"Authorization": "Bearer " + mistralE2EClientKey}, + `{"model":"`+mistralE2EModel+`","messages":[{"role":"user","content":"hi"}]}`) + if code == http.StatusOK { + t.Fatalf("request succeeded without a credential: %s", body) + } + if got := len(fake.chatRequests()); got != 0 { + t.Fatalf("%d requests reached Mistral without a credential", got) + } +} + +func TestMistralLoginE2E_UpstreamRejectionOfKeySurfacesToClient(t *testing.T) { + fake := newFakeMistralService(t) + proxy := newMistralProxy(t) + proxy.signIn(fake) + auth := proxy.adoptSavedCredentials() + + fake.setChatStatus(http.StatusUnauthorized) + code, _, body := proxy.do(http.MethodPost, "/v1/chat/completions", map[string]string{"Authorization": "Bearer " + mistralE2EClientKey}, + `{"model":"`+mistralE2EModel+`","messages":[{"role":"user","content":"hi"}]}`) + if code != http.StatusUnauthorized { + t.Fatalf("status = %d, want the upstream 401 to reach the client: %s", code, body) + } + + updated, ok := proxy.manager.GetByID(auth.ID) + if !ok || updated == nil { + t.Fatal("credential disappeared after an upstream 401") + } + // Same handling as other providers: the credential is held back with its error until the + // retry window passes. Re-signing in replaces the key (see the management tests). + if !updated.Unavailable || updated.Status != coreauth.StatusError || updated.LastError == nil { + t.Fatalf("a rejected key must be marked unusable, got unavailable=%v status=%v lastError=%v", + updated.Unavailable, updated.Status, updated.LastError) + } +}