feat(ml): add isolated embeddings service and scoped client

This commit is contained in:
Anya Tokugawa committed 2026-11-30 23:03:13 +09:00
1 parent 46c185d928
commit 0c7897d695
13 files changed
+1112

No files matched your search

+177
View File
@@ -0,0 +1,177 @@
// Package machinelearning implements the private Pages Machine Learning v1
// transport. Callers must authorize corpus scope and external transmission,
// enqueue work, and recheck revision/policy generations before persisting results.
// This package does not discover documents, retry requests, or change City paths.
package machinelearning
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
)
const maxBody = 128 * 1024
const maxResponse = 2 * 1024 * 1024
var safeToken = regexp.MustCompile(`^[A-Za-z0-9_-]{32,256}$`)
var safeID = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,128}$`)
var modelHash = regexp.MustCompile(`^[0-9a-f]{64}$`)
type Input struct {
ID string `json:"id"`
Text string `json:"text"`
}
type Request struct {
Protocol string `json:"protocol"`
DomainUUID string `json:"domain_uuid"`
ScopeUUID string `json:"scope_uuid"`
Provider string `json:"provider"`
Model string `json:"model"`
Dimensions int `json:"dimensions"`
Inputs []Input `json:"inputs"`
AllowExternal bool `json:"allow_external"`
}
type Output struct {
ID string `json:"id"`
InputSHA256 string `json:"input_sha256"`
Vector []float64 `json:"vector"`
}
type Result struct {
Protocol string `json:"protocol"`
DomainUUID string `json:"domain_uuid"`
ScopeUUID string `json:"scope_uuid"`
Provider string `json:"provider"`
Model string `json:"model"`
ModelRevision string `json:"model_revision"`
Dimensions int `json:"dimensions"`
Tokenizer string `json:"tokenizer"`
Outputs []Output `json:"outputs"`
Usage struct {
TotalTokens int64 `json:"total_tokens"`
} `json:"usage"`
}
// StatusError intentionally excludes the remote response body and request URL.
// Retry scheduling belongs to Pages; failures can include uncertain API charges.
type StatusError struct{ Status int }
func (e *StatusError) Error() string { return fmt.Sprintf("machine learning HTTP status %d", e.Status) }
type Client struct {
endpoint string
token string
http *http.Client
}
// NewClient accepts an operator-configured private service origin, never a
// document-provided URL. HTTP is for an isolated local network only; use HTTPS
// and network access control for remote hosts. There is no insecure TLS option.
func NewClient(origin, token string) (*Client, error) {
u, err := url.Parse(origin)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") || !safeToken.MatchString(token) {
return nil, errors.New("invalid machine learning service configuration")
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.Proxy = nil // Do not leak the private shared token to an env proxy.
return &Client{endpoint: strings.TrimSuffix(origin, "/") + "/v1/embeddings", token: token,
http: &http.Client{Transport: transport, Timeout: 40 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
}
func validUUID(s string) bool { id, err := uuid.Parse(s); return err == nil && id.String() == s }
func validate(req Request) error {
if req.Protocol != "1" || !validUUID(req.DomainUUID) || !validUUID(req.ScopeUUID) || req.Dimensions < 1 || req.Dimensions > 1536 || len(req.Inputs) < 1 || len(req.Inputs) > 16 {
return errors.New("invalid machine learning request")
}
if req.Provider == "openai" {
if !req.AllowExternal || req.Model != "text-embedding-3-small" {
return errors.New("external embeddings not permitted or unsupported model")
}
} else if req.Provider != "doc2vec" || !modelHash.MatchString(req.Model) {
return errors.New("invalid machine learning provider/model")
}
seen := make(map[string]bool)
for _, input := range req.Inputs {
if !safeID.MatchString(input.ID) || seen[input.ID] || strings.TrimSpace(input.Text) == "" || !utf8.ValidString(input.Text) || len(input.Text) > 6000 {
return errors.New("invalid machine learning input")
}
seen[input.ID] = true
}
return nil
}
func (c *Client) Embed(ctx context.Context, input Request) (*Result, error) {
if err := validate(input); err != nil {
return nil, err
}
body, err := json.Marshal(input)
if err != nil || len(body) > maxBody {
return nil, errors.New("machine learning input too large")
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(body))
if err != nil {
return nil, errors.New("machine learning request failed")
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.token)
response, err := c.http.Do(req)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, errors.New("machine learning transport failed")
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, &StatusError{Status: response.StatusCode}
}
raw, err := io.ReadAll(io.LimitReader(response.Body, maxResponse+1))
if err != nil || len(raw) > maxResponse {
return nil, errors.New("invalid machine learning response")
}
var result Result
if json.Unmarshal(raw, &result) != nil || result.Protocol != input.Protocol || result.DomainUUID != input.DomainUUID || result.ScopeUUID != input.ScopeUUID || result.Provider != input.Provider || result.Model != input.Model || result.ModelRevision != input.Model || result.Dimensions != input.Dimensions || len(result.Outputs) != len(input.Inputs) || result.Usage.TotalTokens < 0 {
return nil, errors.New("machine learning result metadata mismatch")
}
expectedTokenizer := "provider"
if input.Provider == "doc2vec" {
expectedTokenizer = "unicode-cjk-bigram-v1"
}
if result.Tokenizer != expectedTokenizer {
return nil, errors.New("machine learning tokenizer mismatch")
}
for i, output := range result.Outputs {
hash := sha256.Sum256([]byte(input.Inputs[i].Text))
if output.ID != input.Inputs[i].ID || output.InputSHA256 != hex.EncodeToString(hash[:]) || len(output.Vector) != input.Dimensions {
return nil, errors.New("machine learning output mismatch")
}
nonzero := false
for _, value := range output.Vector {
if math.IsNaN(value) || math.IsInf(value, 0) {
return nil, errors.New("non-finite machine learning vector")
}
nonzero = nonzero || value != 0
}
if !nonzero {
return nil, errors.New("empty machine learning vector")
}
}
return &result, nil
}
+134
View File
@@ -0,0 +1,134 @@
package machinelearning
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)
func fixture() Request {
return Request{Protocol: "1", DomainUUID: "11111111-1111-4111-8111-111111111111", ScopeUUID: "22222222-2222-4222-8222-222222222222", Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 2, Inputs: []Input{{ID: "page:chunk0", Text: "合成文書 library books"}}}
}
func resultFor(req Request) Result {
r := Result{Protocol: req.Protocol, DomainUUID: req.DomainUUID, ScopeUUID: req.ScopeUUID, Provider: req.Provider, Model: req.Model, ModelRevision: req.Model, Dimensions: req.Dimensions, Tokenizer: "unicode-cjk-bigram-v1"}
for _, item := range req.Inputs {
hash := sha256.Sum256([]byte(item.Text))
r.Outputs = append(r.Outputs, Output{ID: item.ID, InputSHA256: hex.EncodeToString(hash[:]), Vector: []float64{0.5, -0.2}})
}
return r
}
func TestClient(t *testing.T) {
req := fixture()
for _, test := range []struct {
name string
mutate func(*Result)
wantErr bool
}{
{"valid", func(*Result) {}, false},
{"wrong-domain", func(r *Result) { r.DomainUUID = req.ScopeUUID }, true},
{"wrong-scope", func(r *Result) { r.ScopeUUID = req.DomainUUID }, true},
{"wrong-hash", func(r *Result) { r.Outputs[0].InputSHA256 = "wrong" }, true},
{"wrong-dimensions", func(r *Result) { r.Outputs[0].Vector = []float64{1} }, true},
{"wrong-model", func(r *Result) { r.ModelRevision = "other" }, true},
{"wrong-tokenizer", func(r *Result) { r.Tokenizer = "other" }, true},
{"zero", func(r *Result) { r.Outputs[0].Vector = []float64{0, 0} }, true},
} {
t.Run(test.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/embeddings" || r.Method != "POST" || r.Header.Get("Authorization") != "Bearer "+strings.Repeat("t", 40) {
t.Error("request contract")
}
var sent Request
if err := json.NewDecoder(r.Body).Decode(&sent); err != nil || sent.Inputs[0].Text != req.Inputs[0].Text {
t.Error("input changed")
}
result := resultFor(req)
test.mutate(&result)
_ = json.NewEncoder(w).Encode(result)
}))
defer server.Close()
client, err := NewClient(server.URL, strings.Repeat("t", 40))
if err != nil {
t.Fatal(err)
}
_, err = client.Embed(context.Background(), req)
if (err != nil) != test.wantErr {
t.Fatalf("unexpected error: %v", err)
}
})
}
}
func TestNoRedirectRetryOrSecretErrors(t *testing.T) {
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
w.Header().Set("Location", "/secret")
w.WriteHeader(307)
_, _ = w.Write([]byte("secret provider body"))
}))
defer server.Close()
client, _ := NewClient(server.URL, strings.Repeat("t", 40))
_, err := client.Embed(context.Background(), fixture())
var status *StatusError
if !errors.As(err, &status) || status.Status != 307 || calls != 1 || strings.Contains(err.Error(), "secret") {
t.Fatalf("redirect/error handling: %v calls=%d", err, calls)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err = client.Embed(ctx, fixture())
if !errors.Is(err, context.Canceled) {
t.Fatal(err)
}
}
func TestRequestValidation(t *testing.T) {
for _, mutate := range []func(*Request){
func(r *Request) { r.DomainUUID = "../" }, func(r *Request) { r.Inputs[0].Text = strings.Repeat("x", 6001) },
func(r *Request) { r.Provider = "openai"; r.Model = "text-embedding-3-small" },
func(r *Request) { r.Inputs = append(r.Inputs, r.Inputs[0]) }, func(r *Request) { r.Dimensions = 1537 },
} {
req := fixture()
mutate(&req)
if validate(req) == nil {
t.Fatal("accepted invalid request")
}
}
for _, origin := range []string{"file:///tmp/x", "http://user:pass@localhost", "https://ml.invalid/path", "https://ml.invalid?x=1"} {
if _, err := NewClient(origin, strings.Repeat("t", 40)); err == nil {
t.Fatal("accepted origin", origin)
}
}
}
// Optional end-to-end contract test against a local synthetic fixture service.
// No real Pages documents, credentials, or paid OpenAI requests are used.
func TestLocalDoc2VecService(t *testing.T) {
origin := os.Getenv("PAGES_ML_TEST_ORIGIN")
if origin == "" {
t.Skip("set PAGES_ML_TEST_ORIGIN for synthetic service integration")
}
client, err := NewClient(origin, strings.Repeat("t", 40))
if err != nil {
t.Fatal(err)
}
req := fixture()
req.Model = os.Getenv("PAGES_ML_TEST_MODEL")
req.Dimensions = 8
result, err := client.Embed(context.Background(), req)
if err != nil {
t.Fatal(err)
}
if len(result.Outputs) != 1 || len(result.Outputs[0].Vector) != 8 {
t.Fatal("wrong result shape")
}
}
+119
View File
@@ -0,0 +1,119 @@
package machinelearning
import (
"errors"
"path"
"strings"
"unicode"
"unicode/utf8"
)
var ErrPolicy = errors.New("invalid machine learning policy")
var ErrNotAllowed = errors.New("machine learning scope is disabled, stale or excluded")
// Policy contains no credentials. Generation changes on every saved update,
// including disable/re-enable, so queued work cannot reuse old consent.
type Policy struct {
Generation string `json:"generation"`
Enabled bool `json:"enabled"`
ScopeUUID string `json:"scope_uuid"`
Provider string `json:"provider"`
Model string `json:"model"`
Dimensions int `json:"dimensions"`
Prefixes []string `json:"prefixes"`
Exclude []string `json:"exclude"`
AllowExternal bool `json:"allow_external"`
MaxBatchBytes int `json:"max_batch_bytes"`
DailyInputBytes int64 `json:"daily_input_bytes"`
}
// Canonical paths are decoded logical Wiki paths, not URLs or raw request URIs.
// Reject ambiguous encodings instead of silently broadening a configured scope.
func canonicalPath(p string) bool {
return utf8.ValidString(p) && len(p) <= 4096 && strings.HasPrefix(p, "/") && path.Clean(p) == p &&
!strings.ContainsAny(p, "%?#\\") && strings.IndexFunc(p, unicode.IsControl) < 0
}
func (p Policy) Validate() error {
if p.DailyInputBytes < 0 || p.DailyInputBytes > 1000000000 {
return ErrPolicy
}
if !validUUID(p.Generation) {
return ErrPolicy
}
// A new disabled configuration may have no model yet.
if !p.Enabled && p.Provider == "" && p.ScopeUUID == "" && p.Model == "" && p.Dimensions == 0 && len(p.Prefixes) == 0 && len(p.Exclude) == 0 && !p.AllowExternal && p.MaxBatchBytes == 0 {
return nil
}
if !validUUID(p.ScopeUUID) || p.Dimensions < 1 || p.Dimensions > 1536 || len(p.Prefixes) < 1 || len(p.Prefixes) > 64 || len(p.Exclude) > 64 || p.MaxBatchBytes < 1 || p.MaxBatchBytes > 96000 {
return ErrPolicy
}
switch p.Provider {
case "doc2vec":
if !modelHash.MatchString(p.Model) || p.AllowExternal {
return ErrPolicy
}
case "openai":
if p.Model != "text-embedding-3-small" || (p.Enabled && !p.AllowExternal) {
return ErrPolicy
}
default:
return ErrPolicy
}
for _, paths := range [][]string{p.Prefixes, p.Exclude} {
seen := map[string]bool{}
for _, prefix := range paths {
if !canonicalPath(prefix) || seen[prefix] {
return ErrPolicy
}
seen[prefix] = true
}
}
return nil
}
func under(p, prefix string) bool {
return prefix == "/" || p == prefix || strings.HasPrefix(p, prefix+"/")
}
// Allows is an additional scope check, NOT document authorization. Callers must
// still check the current principal, revision, and learning cohort membership.
func (p Policy) Allows(logicalPath, generation string) bool {
if p.Validate() != nil || !p.Enabled || generation != p.Generation || !canonicalPath(logicalPath) {
return false
}
for _, prefix := range p.Exclude {
if under(logicalPath, prefix) {
return false
}
}
for _, prefix := range p.Prefixes {
if under(logicalPath, prefix) {
return true
}
}
return false
}
// Prepare binds model and consent to a freshly loaded policy rather than to
// caller-provided JSON. Inputs must be authorized chunks of this one document.
// The batch limit is not a daily budget or a monetary cost ceiling.
func (p Policy) Prepare(domain, logicalPath, generation string, inputs []Input) (Request, error) {
if !p.Allows(logicalPath, generation) {
return Request{}, ErrNotAllowed
}
bytes := 0
for _, input := range inputs {
bytes += len(input.Text)
if bytes > p.MaxBatchBytes {
return Request{}, ErrNotAllowed
}
}
req := Request{Protocol: "1", DomainUUID: domain, ScopeUUID: p.ScopeUUID, Provider: p.Provider, Model: p.Model, Dimensions: p.Dimensions, Inputs: inputs, AllowExternal: p.AllowExternal}
if err := validate(req); err != nil {
return Request{}, err
}
// Do not retain caller-owned slice memory across a queued operation.
req.Inputs = append([]Input(nil), inputs...)
return req, nil
}
+72
View File
@@ -0,0 +1,72 @@
package machinelearning
import (
"strings"
"testing"
)
func policyFixture() Policy {
return Policy{Generation: "33333333-3333-4333-8333-333333333333", Enabled: true, ScopeUUID: fixture().ScopeUUID, Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 8, Prefixes: []string{"/lab"}, Exclude: []string{"/lab/private"}, MaxBatchBytes: 12000}
}
func TestPolicyPaths(t *testing.T) {
p := policyFixture()
for _, tc := range []struct {
path string
allow bool
}{
{"/lab", true}, {"/lab/文書", true}, {"/labs", false}, {"/lab/private", false}, {"/lab/private/child", false},
{"/lab/private-other", true}, {"/lab/../secret", false}, {"/lab/%70rivate", false}, {"/lab//a", false}, {"https://example.com/lab", false}, {"/lab/a?b", false},
} {
if p.Allows(tc.path, p.Generation) != tc.allow {
t.Errorf("path %q", tc.path)
}
}
p.Prefixes = []string{"/"}
if !p.Allows("/other", p.Generation) || p.Allows("/lab/private/x", p.Generation) {
t.Fatal("root/exclusion")
}
if p.Allows("/lab", "stale") {
t.Fatal("stale generation accepted")
}
p.Enabled = false
if p.Allows("/lab", p.Generation) {
t.Fatal("disabled scope accepted")
}
}
func TestPolicyValidationAndPrepare(t *testing.T) {
for _, mutate := range []func(*Policy){
func(p *Policy) { p.Prefixes = []string{"/lab/"} }, func(p *Policy) { p.Exclude = []string{"relative"} },
func(p *Policy) { p.AllowExternal = true }, func(p *Policy) { p.MaxBatchBytes = 0 },
func(p *Policy) { p.Provider = "openai"; p.Model = "text-embedding-3-small" },
} {
p := policyFixture()
mutate(&p)
if p.Validate() == nil {
t.Fatal("invalid policy accepted")
}
}
p := policyFixture()
inputs := []Input{{ID: "chunk:0", Text: "合成文書"}}
req, err := p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs)
if err != nil {
t.Fatal(err)
}
inputs[0].Text = "changed"
if req.Inputs[0].Text == "changed" || req.AllowExternal {
t.Fatal("input/consent binding")
}
p.MaxBatchBytes = 2
if _, err = p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs); err == nil {
t.Fatal("batch budget")
}
p = policyFixture()
p.Provider = "openai"
p.Model = "text-embedding-3-small"
p.AllowExternal = true
req, err = p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs)
if err != nil || !req.AllowExternal {
t.Fatalf("explicit external policy: %v", err)
}
}