diff --git a/client/auth.go b/client/auth.go new file mode 100644 index 00000000..41a3884e --- /dev/null +++ b/client/auth.go @@ -0,0 +1,117 @@ +package client + +import ( + "context" + "fmt" + "net/http" + "time" +) + +// LoginRequest is the body for POST /api/v1/auth/login. +type LoginRequest struct { + Email string `json:"email"` + Password string `json:"password"` +} + +// LoginResponse is the body returned by POST /api/v1/auth/login. +// +// Token is the JWT access token; RefreshToken renews it via Auth.Refresh. +type LoginResponse struct { + Success bool `json:"success"` + Message string `json:"message,omitempty"` + User *AuthUser `json:"user,omitempty"` + Tenant *AuthTenant `json:"tenant,omitempty"` + Token string `json:"token,omitempty"` + RefreshToken string `json:"refresh_token,omitempty"` +} + +// AuthUser is the principal returned by /auth/login and /auth/me. +// +// Fields mirror the server's UserInfo projection (no PasswordHash). +type AuthUser struct { + ID string `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + Avatar string `json:"avatar,omitempty"` + TenantID uint64 `json:"tenant_id"` + IsActive bool `json:"is_active"` + CanAccessAllTenants bool `json:"can_access_all_tenants,omitempty"` + CreatedAt time.Time `json:"created_at,omitempty"` +} + +// AuthTenant is the tenant projection returned alongside AuthUser. +type AuthTenant struct { + ID uint64 `json:"id"` + Name string `json:"name"` +} + +// CurrentUserResponse is the body of GET /api/v1/auth/me. +type CurrentUserResponse struct { + Success bool `json:"success"` + Data struct { + User *AuthUser `json:"user,omitempty"` + Tenant *AuthTenant `json:"tenant,omitempty"` + } `json:"data"` +} + +// RefreshTokenResponse is the body of POST /api/v1/auth/refresh. +type RefreshTokenResponse struct { + Success bool `json:"success"` + Message string `json:"message,omitempty"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` +} + +// Login authenticates with email + password and returns the JWT access token, +// refresh token, and principal info. Maps to POST /api/v1/auth/login. +// +// Used by `weknora auth login`. +func (c *Client) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error) { + resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/auth/login", req, nil) + if err != nil { + return nil, fmt.Errorf("login request: %w", err) + } + var out LoginResponse + if err := parseResponse(resp, &out); err != nil { + return nil, err + } + return &out, nil +} + +// GetCurrentUser returns the currently authenticated principal and the +// tenant projection. Maps to GET /api/v1/auth/me; the bearer token must +// already be set on the client (use WithBearerToken). +// +// Used by `weknora auth status` and `weknora whoami`. +func (c *Client) GetCurrentUser(ctx context.Context) (*CurrentUserResponse, error) { + resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/auth/me", nil, nil) + if err != nil { + return nil, fmt.Errorf("get current user: %w", err) + } + var out CurrentUserResponse + if err := parseResponse(resp, &out); err != nil { + return nil, err + } + return &out, nil +} + +// RefreshToken renews the JWT access token using a refresh token. +// Maps to POST /api/v1/auth/refresh. +// +// Callers (`weknora auth refresh`) read the refresh token from secrets, +// invoke this method, and persist both new tokens. The SDK does not touch +// the secrets store directly — it stays a transport-only layer. +func (c *Client) RefreshToken(ctx context.Context, refreshToken string) (*RefreshTokenResponse, error) { + body := struct { + RefreshToken string `json:"refreshToken"` + }{RefreshToken: refreshToken} + resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/auth/refresh", body, nil) + if err != nil { + return nil, fmt.Errorf("refresh token: %w", err) + } + var out RefreshTokenResponse + if err := parseResponse(resp, &out); err != nil { + return nil, err + } + return &out, nil +} diff --git a/client/client.go b/client/client.go index 3fb3e961..ee7b342d 100644 --- a/client/client.go +++ b/client/client.go @@ -14,12 +14,21 @@ import ( "time" ) -// Client is the client for interacting with the WeKnora service +// Client is the client for interacting with the WeKnora service. +// +// Authentication uses one of two credential kinds: +// - API key (long-lived, set via X-API-Key) — see WithAPIKey +// - Bearer JWT (short-lived, set via Authorization)— see WithBearerToken +// +// Both may be configured simultaneously; X-API-Key takes precedence at the +// HTTP layer. The legacy WithToken is kept as an alias for WithAPIKey for two +// minor versions of compatibility. type Client struct { - baseURL string - httpClient *http.Client - token string - tenantID *uint64 + baseURL string + httpClient *http.Client + apiKey string + bearerToken string + tenantID *uint64 } // ClientOption defines client configuration options @@ -32,15 +41,39 @@ func WithTimeout(timeout time.Duration) ClientOption { } } -// WithToken sets the authentication token -func WithToken(token string) ClientOption { +// WithAPIKey sets the long-lived API key sent as the X-API-Key header. +func WithAPIKey(key string) ClientOption { return func(c *Client) { - c.token = token + c.apiKey = key } } -// WithTenantID sets the tenant ID that will be included in requests as the X-Tenant-ID header. -// It can be overridden per-request by setting the "TenantID" value in the request context. +// WithBearerToken sets the JWT bearer token sent as the Authorization header. +// Used after a successful auth.login to call authenticated endpoints with the +// short-lived access token. +func WithBearerToken(token string) ClientOption { + return func(c *Client) { + c.bearerToken = token + } +} + +// WithToken is the v0.x compatibility alias for WithAPIKey. Prefer WithAPIKey +// (or WithBearerToken for JWT). Will be removed in the next major; the alias +// is preserved for two minor versions per ADR. +// +// Deprecated: use WithAPIKey for X-API-Key, WithBearerToken for JWT. +func WithToken(token string) ClientOption { + return WithAPIKey(token) +} + +// WithTenantID sets X-Tenant-ID on every request. Use only for explicit +// cross-tenant access by callers with CanAccessAllTenants — the server's +// auth middleware runs the cross-tenant gate whenever this header is +// present on a bearer request, even when the value matches the credential's +// own tenant, and 403s normal users. JWT bearer tokens and tenant-scoped +// API keys carry tenant identity intrinsically, so the header is redundant +// (and harmful) for default-tenant traffic. Per-request override via the +// "TenantID" context value still applies. func WithTenantID(tenantID uint64) ClientOption { return func(c *Client) { c.tenantID = &tenantID @@ -87,16 +120,29 @@ func (c *Client) doRequest(ctx context.Context, } req.Header.Set("Content-Type", "application/json") - if c.token != "" { - req.Header.Set("X-API-Key", c.token) + c.applyAuthHeaders(ctx, req) + + return c.httpClient.Do(req) +} + +// applyAuthHeaders sets X-API-Key, Authorization, X-Request-ID, and X-Tenant-ID +// on req based on client config and ctx values. Used by doRequest and any +// caller that builds its own *http.Request (currently CreateKnowledgeFromFile, +// which uses multipart and can't go through doRequest). +func (c *Client) applyAuthHeaders(ctx context.Context, req *http.Request) { + if c.apiKey != "" { + req.Header.Set("X-API-Key", c.apiKey) + } + if c.bearerToken != "" { + req.Header.Set("Authorization", "Bearer "+c.bearerToken) } if requestID := ctx.Value("RequestID"); requestID != nil { - req.Header.Set("X-Request-ID", requestID.(string)) + if s, ok := requestID.(string); ok { + req.Header.Set("X-Request-ID", s) + } } - // Tenant header: prefer per-request context value, fall back to client-level tenantID tenantID := c.tenantID - if ctxTenant := ctx.Value("TenantID"); ctxTenant != nil { switch v := ctxTenant.(type) { case *uint64: @@ -104,41 +150,27 @@ func (c *Client) doRequest(ctx context.Context, tenantID = v } case uint64: - tmp := v - tenantID = &tmp + tenantID = &v case string: if parsed, err := strconv.ParseUint(v, 10, 64); err == nil { - tmp := parsed - tenantID = &tmp + tenantID = &parsed } } } - - // 2) Fallback: plain string key "TenantID" (some callers may use this) - if tenantID == nil { - if ctxTenant := ctx.Value("TenantID"); ctxTenant != nil { - switch v := ctxTenant.(type) { - case *uint64: - if v != nil { - tenantID = v - } - case uint64: - tmp := v - tenantID = &tmp - case string: - if parsed, err := strconv.ParseUint(v, 10, 64); err == nil { - tmp := parsed - tenantID = &tmp - } - } - } - } - if tenantID != nil { req.Header.Set("X-Tenant-ID", strconv.FormatUint(*tenantID, 10)) } +} - return c.httpClient.Do(req) +// Raw performs a raw HTTP request against the WeKnora API with the client's +// auth headers, X-Request-ID, and X-Tenant-ID injection applied. +// +// Experimental: this method is intended for one-off integrations and the +// `weknora api` CLI passthrough. The signature, return type, and behavior may +// change in any minor version. Prefer typed methods (ListKnowledgeBases, +// GetKnowledgeBase, etc.) when they exist. +func (c *Client) Raw(ctx context.Context, method, path string, body interface{}) (*http.Response, error) { + return c.doRequest(ctx, method, path, body, nil) } // parseResponse parses an HTTP response diff --git a/client/knowledge.go b/client/knowledge.go index da1bcad2..6d9ec8d4 100644 --- a/client/knowledge.go +++ b/client/knowledge.go @@ -164,14 +164,8 @@ func (c *Client) CreateKnowledgeFromFile(ctx context.Context, return nil, fmt.Errorf("failed to close writer: %w", err) } - // Set request headers req.Header.Set("Content-Type", writer.FormDataContentType()) - if c.token != "" { - req.Header.Set("X-API-Key", c.token) - } - if requestID := ctx.Value("RequestID"); requestID != nil { - req.Header.Set("X-Request-ID", requestID.(string)) - } + c.applyAuthHeaders(ctx, req) // Set the request body req.Body = io.NopCloser(body) diff --git a/client/knowledgebase.go b/client/knowledgebase.go index a9686c34..17fb5c64 100644 --- a/client/knowledgebase.go +++ b/client/knowledgebase.go @@ -138,7 +138,37 @@ type KnowledgeBaseListResponse struct { Data []KnowledgeBase `json:"data"` } -// SearchResult represents search result +// MatchType records which retrieval channel produced a SearchResult. +// Numeric values are the wire contract; they mirror the iota order in +// server-side internal/types/embedding.go — do not reorder without +// coordinating a server bump. Server-side names are preserved as +// trailing comments so cross-repo grep works in both directions. +// +// Channel grouping: 0-1 primary text channels (vector + keyword); +// 2-5 enrichment chunks (added in addition to primary matches, score=0); +// 6-9 alternate sources (graph DB, web search, raw load, data analysis). +type MatchType int + +const ( + MatchTypeVector MatchType = 0 // server: MatchTypeEmbedding + MatchTypeKeyword MatchType = 1 // server: MatchTypeKeywords + MatchTypeNearby MatchType = 2 // server: MatchTypeNearByChunk + MatchTypeHistory MatchType = 3 // server: MatchTypeHistory + MatchTypeParent MatchType = 4 // server: MatchTypeParentChunk + MatchTypeRelation MatchType = 5 // server: MatchTypeRelationChunk + MatchTypeGraph MatchType = 6 // server: MatchTypeGraph + MatchTypeWeb MatchType = 7 // server: MatchTypeWebSearch + MatchTypeDirect MatchType = 8 // server: MatchTypeDirectLoad — chunk loaded by ID without scoring + MatchTypeData MatchType = 9 // server: MatchTypeDataAnalysis — produced by analytical pipeline, not retrieval +) + +// SearchResult represents search result. +// +// Score is the RRF (reciprocal-rank-fusion) score combining vector and +// keyword channels — typically in the [0, ~0.03] range when both channels +// hit, NOT the raw vector similarity. Use MatchType to tell which channel +// produced each result. Per-channel thresholds (vector_threshold, +// keyword_threshold) filter pre-fusion at retrieval time, before RRF runs. type SearchResult struct { ID string `json:"id"` Content string `json:"content"` @@ -149,12 +179,13 @@ type SearchResult struct { EndAt int `json:"end_at"` Seq int `json:"seq"` Score float64 `json:"score"` + MatchType MatchType `json:"match_type"` ChunkType string `json:"chunk_type"` ImageInfo string `json:"image_info"` Metadata map[string]string `json:"metadata"` KnowledgeFilename string `json:"knowledge_filename"` - KnowledgeSource string `json:"knowledge_source"` - KnowledgeChannel string `json:"knowledge_channel"` + KnowledgeSource string `json:"knowledge_source"` + KnowledgeChannel string `json:"knowledge_channel"` // MatchedContent is the actual content that was matched in vector search // For FAQ: this is the matched question text (standard or similar question) MatchedContent string `json:"matched_content,omitempty"`