Compare commits

...
Author SHA1 Message Date
Lukas Hirt 14ca73fa83 feat: [OCISDEV-1061] add llm proxy service
Add a new llm service that proxies chat-completion requests from AI web extensions to a configured OpenAI-compatible endpoint, replacing the standalone Node.js sidecar. It is part of the oCIS single binary, opt-in via OCIS_ADD_RUN_SERVICES=llm, and exposed through the proxy at POST /graph/v1beta1/extensions/org.libregraph/llm/chat/completions.

Authentication is delegated to oCIS. Requests are rate-limited per user with a sliding window backed by the shared store, and the request body is sanitized before forwarding. Streaming requests are rejected.

Signed-off-by: Lukas Hirt <info@hirt.cz>
2026-10-15 14:31:07 +02:00
37 changed files with 2075 additions and 0 deletions

No files matched your search

+1
View File
@@ -41,6 +41,7 @@ OCIS_MODULES = \
services/idm \
services/idp \
services/invitations \
services/llm \
services/nats \
services/notifications \
services/ocdav \
@@ -0,0 +1,13 @@
Enhancement: Add LLM proxy service
oCIS now ships a native `llm` microservice, as part of the single binary,
that proxies chat-completion requests from AI web extensions to a
configured OpenAI-compatible LLM endpoint, so AI-enabled oCIS deployments
no longer need a separate process or image.
The service trusts oCIS's existing authentication (no independent OIDC
validation), rate-limits requests per user using oCIS's shared store
abstraction (shared across multiple replicas), and forwards a sanitized
request body — only the fields the LLM needs are passed through.
https://github.com/owncloud/ocis/pull/12965
+2
View File
@@ -22,6 +22,7 @@ import (
idm "github.com/owncloud/ocis/v2/services/idm/pkg/config"
idp "github.com/owncloud/ocis/v2/services/idp/pkg/config"
invitations "github.com/owncloud/ocis/v2/services/invitations/pkg/config"
llm "github.com/owncloud/ocis/v2/services/llm/pkg/config"
nats "github.com/owncloud/ocis/v2/services/nats/pkg/config"
notifications "github.com/owncloud/ocis/v2/services/notifications/pkg/config"
ocdav "github.com/owncloud/ocis/v2/services/ocdav/pkg/config"
@@ -103,6 +104,7 @@ type Config struct {
IDM *idm.Config `yaml:"idm"`
IDP *idp.Config `yaml:"idp"`
Invitations *invitations.Config `yaml:"invitations"`
LLM *llm.Config `yaml:"llm"`
Nats *nats.Config `yaml:"nats"`
Notifications *notifications.Config `yaml:"notifications"`
OCDav *ocdav.Config `yaml:"ocdav"`
+2
View File
@@ -22,6 +22,7 @@ import (
idm "github.com/owncloud/ocis/v2/services/idm/pkg/config/defaults"
idp "github.com/owncloud/ocis/v2/services/idp/pkg/config/defaults"
invitations "github.com/owncloud/ocis/v2/services/invitations/pkg/config/defaults"
llm "github.com/owncloud/ocis/v2/services/llm/pkg/config/defaults"
nats "github.com/owncloud/ocis/v2/services/nats/pkg/config/defaults"
notifications "github.com/owncloud/ocis/v2/services/notifications/pkg/config/defaults"
ocdav "github.com/owncloud/ocis/v2/services/ocdav/pkg/config/defaults"
@@ -77,6 +78,7 @@ func DefaultConfig() *Config {
IDM: idm.DefaultConfig(),
IDP: idp.DefaultConfig(),
Invitations: invitations.DefaultConfig(),
LLM: llm.DefaultConfig(),
Nats: nats.DefaultConfig(),
Notifications: notifications.DefaultConfig(),
OCDav: ocdav.DefaultConfig(),
+6
View File
@@ -28,6 +28,7 @@ import (
idm "github.com/owncloud/ocis/v2/services/idm/pkg/command"
idp "github.com/owncloud/ocis/v2/services/idp/pkg/command"
invitations "github.com/owncloud/ocis/v2/services/invitations/pkg/command"
llm "github.com/owncloud/ocis/v2/services/llm/pkg/command"
nats "github.com/owncloud/ocis/v2/services/nats/pkg/command"
notifications "github.com/owncloud/ocis/v2/services/notifications/pkg/command"
ocdav "github.com/owncloud/ocis/v2/services/ocdav/pkg/command"
@@ -58,6 +59,11 @@ var svccmds = []register.Command{
cfg.Activitylog.Commons = cfg.Commons
})
},
func(cfg *config.Config) *cli.Command {
return ServiceCommand(cfg, cfg.LLM.Service.Name, llm.GetCommands(cfg.LLM), func(c *config.Config) {
cfg.LLM.Commons = cfg.Commons
})
},
func(cfg *config.Config) *cli.Command {
return ServiceCommand(cfg, cfg.Antivirus.Service.Name, antivirus.GetCommands(cfg.Antivirus), func(c *config.Config) {
// cfg.Antivirus.Commons = cfg.Commons // antivirus needs no commons atm
+6
View File
@@ -48,6 +48,7 @@ import (
idm "github.com/owncloud/ocis/v2/services/idm/pkg/command"
idp "github.com/owncloud/ocis/v2/services/idp/pkg/command"
invitations "github.com/owncloud/ocis/v2/services/invitations/pkg/command"
llm "github.com/owncloud/ocis/v2/services/llm/pkg/command"
nats "github.com/owncloud/ocis/v2/services/nats/pkg/command"
ocdav "github.com/owncloud/ocis/v2/services/ocdav/pkg/command"
ocm "github.com/owncloud/ocis/v2/services/ocm/pkg/command"
@@ -355,6 +356,11 @@ func NewService(ctx context.Context, options ...Option) (*Service, error) {
cfg.Notifications.Commons = cfg.Commons
return runServerCommand(ctx, notifications.Server(cfg.Notifications))
})
areg(opts.Config.LLM.Service.Name, func(ctx context.Context, cfg *ociscfg.Config) error {
cfg.LLM.Context = ctx
cfg.LLM.Commons = cfg.Commons
return runServerCommand(ctx, llm.Server(cfg.LLM))
})
return s, nil
}
+37
View File
@@ -0,0 +1,37 @@
SHELL := bash
NAME := llm
include ../../.make/recursion.mk
############ tooling ############
ifneq (, $(shell command -v go 2> /dev/null)) # suppress `command not found warnings` for non go targets in CI
include ../../.bingo/Variables.mk
endif
############ go tooling ############
include ../../.make/go.mk
############ release ############
include ../../.make/release.mk
############ docs generate ############
include ../../.make/docs.mk
.PHONY: docs-generate
docs-generate: config-docs-generate
############ generate ############
include ../../.make/generate.mk
.PHONY: ci-go-generate
ci-go-generate: # CI runs ci-node-generate automatically before this target
.PHONY: ci-node-generate
ci-node-generate:
############ licenses ############
.PHONY: ci-node-check-licenses
ci-node-check-licenses:
.PHONY: ci-node-save-licenses
ci-node-save-licenses:
+46
View File
@@ -0,0 +1,46 @@
# LLM Proxy
The `llm` service proxies chat-completion requests from oCIS AI web
extensions to a configured, OpenAI-compatible LLM endpoint, so extensions
never see the upstream API key.
The public endpoint is reached through the `proxy` service at
`POST /graph/v1beta1/extensions/org.libregraph/llm/chat/completions`.
`LLM_ENDPOINT` is a **required** environment variable; the service will not
start without it. `llm` is an **opt-in** service — it must be explicitly
enabled via `OCIS_ADD_RUN_SERVICES=llm` (the same way `antivirus`,
`auth-app`, and `invitations` are enabled) for `ocis server` to run it.
## Limitations
Streaming responses are not supported. Requests with `"stream": true` are
rejected with `400 Bad Request`; the full completion is always returned as a
single JSON response.
## Auth
The `llm` service does not authenticate callers itself. It trusts the
`proxy` service, which validates the caller's OIDC token and forwards a
signed identity via the `X-Access-Token` header before the request reaches
`llm`.
## Rate limiting
Requests are rate-limited per user using a sliding window backed by the
configured store (`LLM_STORE`, defaults to `nats-js-kv`), so the limit is
shared across replicas when `llm` runs multiple instances. Configure the
window and request ceiling with `LLM_RATE_LIMIT_WINDOW` /
`LLM_RATE_LIMIT_MAX_REQUESTS`.
Each request is stored as its own record, so concurrent replicas never
overwrite each other's counts; under heavy concurrency at the limit a
request may be rejected, but the limit is never exceeded. Only requests
that are forwarded to the LLM count. Expiry is handled by the store, so
`LLM_STORE_TTL` must not be shorter than `LLM_RATE_LIMIT_WINDOW` (the
service refuses to start otherwise).
## Configuration
See the `LLM_*` environment variables in `pkg/config` for the upstream
endpoint, API key, model override, timeout, and body-size limit.
+20
View File
@@ -0,0 +1,20 @@
// services/llm/cmd/llm/main.go
package main
import (
"context"
"os"
"os/signal"
"syscall"
"github.com/owncloud/ocis/v2/services/llm/pkg/command"
"github.com/owncloud/ocis/v2/services/llm/pkg/config/defaults"
)
func main() {
cfg := defaults.DefaultConfig()
cfg.Context, _ = signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP)
if err := command.Execute(cfg); err != nil {
os.Exit(1)
}
}
+41
View File
@@ -0,0 +1,41 @@
// services/llm/pkg/command/health.go
package command
import (
"fmt"
"net/http"
"github.com/owncloud/ocis/v2/ocis-pkg/config/configlog"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/owncloud/ocis/v2/services/llm/pkg/config/parser"
"github.com/owncloud/ocis/v2/services/llm/pkg/logging"
"github.com/urfave/cli/v2"
)
// Health is the entrypoint for the health command.
func Health(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "health",
Usage: "check health status",
Category: "info",
Before: func(c *cli.Context) error {
return configlog.ReturnError(parser.ParseConfig(cfg))
},
Action: func(c *cli.Context) error {
logger := logging.Configure(cfg.Service.Name, cfg.Log)
resp, err := http.Get(fmt.Sprintf("http://%s/healthz", cfg.Debug.Addr))
if err != nil {
logger.Fatal().Err(err).Msg("Failed to request health check")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
logger.Fatal().Int("code", resp.StatusCode).Msg("Health seems to be in bad state")
}
logger.Debug().Int("code", resp.StatusCode).Msg("Health got a good state")
return nil
},
}
}
+30
View File
@@ -0,0 +1,30 @@
// services/llm/pkg/command/root.go
package command
import (
"os"
"github.com/owncloud/ocis/v2/ocis-pkg/clihelper"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/urfave/cli/v2"
)
// GetCommands provides all commands for this service.
func GetCommands(cfg *config.Config) cli.Commands {
return []*cli.Command{
Server(cfg),
Health(cfg),
Version(cfg),
}
}
// Execute is the entry point for the ocis llm command.
func Execute(cfg *config.Config) error {
app := clihelper.DefaultApp(&cli.App{
Name: "llm",
Usage: "serve the LLM proxy for oCIS AI extensions",
Commands: GetCommands(cfg),
})
return app.RunContext(cfg.Context, os.Args)
}
+104
View File
@@ -0,0 +1,104 @@
// services/llm/pkg/command/server.go
package command
import (
"context"
"fmt"
"os/signal"
"github.com/owncloud/reva/v2/pkg/store"
"github.com/urfave/cli/v2"
microstore "go-micro.dev/v4/store"
"github.com/owncloud/ocis/v2/ocis-pkg/config/configlog"
"github.com/owncloud/ocis/v2/ocis-pkg/runner"
"github.com/owncloud/ocis/v2/ocis-pkg/tracing"
"github.com/owncloud/ocis/v2/ocis-pkg/version"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/owncloud/ocis/v2/services/llm/pkg/config/parser"
"github.com/owncloud/ocis/v2/services/llm/pkg/logging"
"github.com/owncloud/ocis/v2/services/llm/pkg/metrics"
"github.com/owncloud/ocis/v2/services/llm/pkg/ratelimit"
"github.com/owncloud/ocis/v2/services/llm/pkg/server/debug"
"github.com/owncloud/ocis/v2/services/llm/pkg/server/http"
)
// Server is the entrypoint for the server command.
func Server(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "server",
Usage: fmt.Sprintf("start the %s service without runtime (unsupervised mode)", cfg.Service.Name),
Category: "server",
Before: func(c *cli.Context) error {
return configlog.ReturnFatal(parser.ParseConfig(cfg))
},
Action: func(c *cli.Context) error {
logger := logging.Configure(cfg.Service.Name, cfg.Log)
tracerProvider, err := tracing.GetServiceTraceProvider(cfg.Tracing, cfg.Service.Name)
if err != nil {
logger.Error().Err(err).Msg("Failed to initialize tracer")
return err
}
var cancel context.CancelFunc
if cfg.Context == nil {
cfg.Context, cancel = signal.NotifyContext(context.Background(), runner.StopSignals...)
defer cancel()
}
ctx := cfg.Context
m := metrics.New()
m.BuildInfo.WithLabelValues(version.GetString()).Set(1)
rateLimitStore := store.Create(
store.Store(cfg.Store.Store),
store.TTL(cfg.Store.TTL),
microstore.Nodes(cfg.Store.Nodes...),
microstore.Database(cfg.Store.Database),
microstore.Table(cfg.Store.Table),
store.Authentication(cfg.Store.AuthUsername, cfg.Store.AuthPassword),
store.TLS(cfg.Store.EnableTLS, cfg.Store.TLSInsecure, cfg.Store.TLSRootCACertificate),
)
limiter := ratelimit.New(rateLimitStore, cfg.RateLimit.Window, cfg.RateLimit.MaxRequests)
gr := runner.NewGroup()
{
httpServer, err := http.Server(
http.Logger(logger),
http.Context(ctx),
http.Config(cfg),
http.Limiter(limiter),
http.TraceProvider(tracerProvider),
)
if err != nil {
logger.Info().Err(err).Str("server", "http").Msg("Failed to initialize server")
return err
}
gr.Add(runner.NewGoMicroHttpServerRunner(cfg.Service.Name+".http", httpServer))
}
{
debugServer, err := debug.Server(
debug.Logger(logger),
debug.Context(ctx),
debug.Config(cfg),
)
if err != nil {
logger.Info().Err(err).Str("transport", "debug").Msg("Failed to initialize server")
return err
}
gr.Add(runner.NewGolangHttpServerRunner(cfg.Service.Name+".debug", debugServer))
}
logger.Warn().Msgf("starting service %s", cfg.Service.Name)
grResults := gr.Run(ctx)
if err := runner.ProcessResults(grResults); err != nil {
logger.Error().Err(err).Msgf("service %s stopped with error", cfg.Service.Name)
return err
}
logger.Warn().Msgf("service %s stopped without error", cfg.Service.Name)
return nil
},
}
}
+49
View File
@@ -0,0 +1,49 @@
// services/llm/pkg/command/version.go
package command
import (
"fmt"
"os"
"github.com/olekukonko/tablewriter"
"github.com/owncloud/ocis/v2/ocis-pkg/registry"
"github.com/owncloud/ocis/v2/ocis-pkg/version"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/urfave/cli/v2"
)
// Version prints the service versions of all running instances.
func Version(cfg *config.Config) *cli.Command {
return &cli.Command{
Name: "version",
Usage: "print the version of this binary and the running service instances",
Category: "info",
Action: func(c *cli.Context) error {
fmt.Println("Version: " + version.GetString())
fmt.Printf("Compiled: %s\n", version.Compiled())
fmt.Println("")
reg := registry.GetRegistry()
services, err := reg.GetService(cfg.HTTP.Namespace + "." + cfg.Service.Name)
if err != nil {
fmt.Println(fmt.Errorf("could not get %s services from the registry: %v", cfg.Service.Name, err))
return err
}
if len(services) == 0 {
fmt.Println("No running " + cfg.Service.Name + " service found.")
return nil
}
table := tablewriter.NewTable(os.Stdout)
table.Header("Version", "Address", "Id")
for _, s := range services {
for _, n := range s.Nodes {
table.Append([]string{s.Version, n.Address, n.Id})
}
}
table.Render()
return nil
},
}
}
+64
View File
@@ -0,0 +1,64 @@
package config
import (
"context"
"time"
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
)
// Config combines all available configuration parts.
type Config struct {
Commons *shared.Commons `yaml:"-"` // don't use this directly as configuration for a service
Service Service `yaml:"-"`
Tracing *Tracing `yaml:"tracing"`
Log *Log `yaml:"log"`
Debug Debug `yaml:"debug"`
HTTP HTTP `yaml:"http"`
TokenManager *TokenManager `yaml:"token_manager"`
Store Store `yaml:"store"`
RateLimit RateLimit `yaml:"rate_limit"`
LLM LLM `yaml:"llm"`
Context context.Context `yaml:"-"`
}
// TokenManager is the config for using the reva token manager.
type TokenManager struct {
JWTSecret string `yaml:"jwt_secret" env:"OCIS_JWT_SECRET;LLM_JWT_SECRET" desc:"The secret to mint and validate jwt tokens." introductionVersion:"%%NEXT%%"`
}
// Store configures the store used for per-user rate limiting.
type Store struct {
Store string `yaml:"store" env:"OCIS_PERSISTENT_STORE;LLM_STORE" desc:"The type of the store. Supported values are: 'memory', 'nats-js-kv', 'redis-sentinel', 'noop'. See the text description for details." introductionVersion:"%%NEXT%%"`
Nodes []string `yaml:"nodes" env:"OCIS_PERSISTENT_STORE_NODES;LLM_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
Database string `yaml:"database" env:"LLM_STORE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"%%NEXT%%"`
Table string `yaml:"table" env:"LLM_STORE_TABLE" desc:"The database table the store should use." introductionVersion:"%%NEXT%%"`
TTL time.Duration `yaml:"ttl" env:"OCIS_PERSISTENT_STORE_TTL;LLM_STORE_TTL" desc:"Time to live for rate-limit entries in the store. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
AuthUsername string `yaml:"username" env:"OCIS_PERSISTENT_STORE_AUTH_USERNAME;LLM_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"%%NEXT%%"`
AuthPassword string `yaml:"password" env:"OCIS_PERSISTENT_STORE_AUTH_PASSWORD;LLM_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"%%NEXT%%"`
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;LLM_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"%%NEXT%%"`
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_PERSISTENT_STORE_TLS_INSECURE;LLM_STORE_TLS_INSECURE" desc:"Disable TLS certificate verification for the store connection. Only applies when store type 'nats-js-kv' is configured. Do not enable this in production because it disables authentication of the NATS server. Use it only for testing with self-signed certificates." introductionVersion:"%%NEXT%%"`
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_PERSISTENT_STORE_TLS_ROOT_CA_CERTIFICATE;LLM_STORE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"%%NEXT%%"`
}
// RateLimit configures the per-user request rate limit.
type RateLimit struct {
Window time.Duration `yaml:"window" env:"LLM_RATE_LIMIT_WINDOW" desc:"The sliding time window over which requests per user are counted. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
MaxRequests int `yaml:"max_requests" env:"LLM_RATE_LIMIT_MAX_REQUESTS" desc:"The maximum number of chat completion requests a single user may make within the configured window. Set to 0 to disable rate limiting." introductionVersion:"%%NEXT%%"`
}
// LLM configures the upstream OpenAI-compatible LLM endpoint.
type LLM struct {
Endpoint string `yaml:"endpoint" env:"LLM_ENDPOINT" desc:"The base URL of the OpenAI-compatible LLM endpoint, without the trailing '/chat/completions' path, e.g. 'https://api.openai.com/v1'." introductionVersion:"%%NEXT%%"`
APIKey string `yaml:"api_key" env:"LLM_API_KEY" desc:"The API key used to authenticate with the LLM endpoint. Leave empty for LLM endpoints that require no authentication." introductionVersion:"%%NEXT%%" mask:"password"`
Model string `yaml:"model" env:"LLM_MODEL" desc:"When set, overrides the 'model' field of every client request, regardless of what the client sent." introductionVersion:"%%NEXT%%"`
MaxTokensLimit int `yaml:"max_tokens_limit" env:"LLM_MAX_TOKENS_LIMIT" desc:"Hard ceiling on the 'max_tokens' value forwarded to the LLM. A client-requested value above this is clamped to it." introductionVersion:"%%NEXT%%"`
Timeout time.Duration `yaml:"timeout" env:"LLM_TIMEOUT" desc:"Timeout for the upstream LLM request. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
MaxBodyBytes int64 `yaml:"max_body_bytes" env:"LLM_MAX_BODY_BYTES" desc:"Maximum request body size in bytes the service will buffer from a client before rejecting the request." introductionVersion:"%%NEXT%%"`
}
+9
View File
@@ -0,0 +1,9 @@
package config
// Debug defines the available debug configuration.
type Debug struct {
Addr string `yaml:"addr" env:"LLM_DEBUG_ADDR" desc:"Bind address of the debug server, where metrics, health, config and debug endpoints will be exposed." introductionVersion:"%%NEXT%%"`
Token string `yaml:"token" env:"LLM_DEBUG_TOKEN" desc:"Token to secure the metrics endpoint." introductionVersion:"%%NEXT%%"`
Pprof bool `yaml:"pprof" env:"LLM_DEBUG_PPROF" desc:"Enables pprof, which can be used for profiling." introductionVersion:"%%NEXT%%"`
Zpages bool `yaml:"zpages" env:"LLM_DEBUG_ZPAGES" desc:"Enables zpages, which can be used for collecting and viewing in-memory traces." introductionVersion:"%%NEXT%%"`
}
@@ -0,0 +1,101 @@
package defaults
import (
"time"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
)
// FullDefaultConfig returns the full default config.
func FullDefaultConfig() *config.Config {
cfg := DefaultConfig()
EnsureDefaults(cfg)
Sanitize(cfg)
return cfg
}
// DefaultConfig returns the default configuration.
func DefaultConfig() *config.Config {
return &config.Config{
Debug: config.Debug{
Addr: "127.0.0.1:9346",
Token: "",
Pprof: false,
Zpages: false,
},
Service: config.Service{
Name: "llm",
},
HTTP: config.HTTP{
Addr: "127.0.0.1:9345",
Root: "/",
Namespace: "com.owncloud.web",
CORS: config.CORS{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"POST"},
AllowedHeaders: []string{"Authorization", "Origin", "Content-Type", "Accept", "X-Requested-With", "X-Request-Id"},
AllowCredentials: true,
},
},
Store: config.Store{
Store: "nats-js-kv",
Nodes: []string{"127.0.0.1:9233"},
Database: "llm",
Table: "rate-limit",
TTL: 10 * time.Minute,
},
RateLimit: config.RateLimit{
Window: time.Minute,
MaxRequests: 20,
},
LLM: config.LLM{
MaxTokensLimit: 4096,
Timeout: 60 * time.Second,
MaxBodyBytes: 6291456, // 6 MiB, covers a 4 MiB image after base64 encoding
},
}
}
// EnsureDefaults ensures the config contains default values.
func EnsureDefaults(cfg *config.Config) {
// provide with defaults for shared logging, since we need a valid destination address for "envdecode".
if cfg.Log == nil && cfg.Commons != nil && cfg.Commons.Log != nil {
cfg.Log = &config.Log{
Level: cfg.Commons.Log.Level,
Pretty: cfg.Commons.Log.Pretty,
Color: cfg.Commons.Log.Color,
File: cfg.Commons.Log.File,
}
} else if cfg.Log == nil {
cfg.Log = &config.Log{}
}
if cfg.TokenManager == nil && cfg.Commons != nil && cfg.Commons.TokenManager != nil {
cfg.TokenManager = &config.TokenManager{
JWTSecret: cfg.Commons.TokenManager.JWTSecret,
}
} else if cfg.TokenManager == nil {
cfg.TokenManager = &config.TokenManager{}
}
if cfg.Commons != nil {
cfg.HTTP.TLS = cfg.Commons.HTTPServiceTLS
}
// provide with defaults for shared tracing, since we need a valid destination address for "envdecode".
if cfg.Tracing == nil && cfg.Commons != nil && cfg.Commons.Tracing != nil {
cfg.Tracing = &config.Tracing{
Enabled: cfg.Commons.Tracing.Enabled,
Type: cfg.Commons.Tracing.Type,
Endpoint: cfg.Commons.Tracing.Endpoint,
Collector: cfg.Commons.Tracing.Collector,
}
} else if cfg.Tracing == nil {
cfg.Tracing = &config.Tracing{}
}
}
// Sanitize sanitizes the config.
func Sanitize(cfg *config.Config) {
// sanitize config
}
+20
View File
@@ -0,0 +1,20 @@
package config
import "github.com/owncloud/ocis/v2/ocis-pkg/shared"
// CORS defines the available cors configuration.
type CORS struct {
AllowedOrigins []string `yaml:"allow_origins" env:"OCIS_CORS_ALLOW_ORIGINS;LLM_CORS_ALLOW_ORIGINS" desc:"A list of allowed CORS origins. See following chapter for more details: *Access-Control-Allow-Origin* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
AllowedMethods []string `yaml:"allow_methods" env:"OCIS_CORS_ALLOW_METHODS;LLM_CORS_ALLOW_METHODS" desc:"A list of allowed CORS methods. See following chapter for more details: *Access-Control-Request-Method* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Method. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
AllowedHeaders []string `yaml:"allow_headers" env:"OCIS_CORS_ALLOW_HEADERS;LLM_CORS_ALLOW_HEADERS" desc:"A list of allowed CORS headers. See following chapter for more details: *Access-Control-Request-Headers* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Headers. See the Environment Variable Types description for more details." introductionVersion:"%%NEXT%%"`
AllowCredentials bool `yaml:"allow_credentials" env:"OCIS_CORS_ALLOW_CREDENTIALS;LLM_CORS_ALLOW_CREDENTIALS" desc:"Allow credentials for CORS. See following chapter for more details: *Access-Control-Allow-Credentials* at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials." introductionVersion:"%%NEXT%%"`
}
// HTTP defines the available http configuration.
type HTTP struct {
Addr string `yaml:"addr" env:"LLM_HTTP_ADDR" desc:"The bind address of the HTTP service." introductionVersion:"%%NEXT%%"`
Namespace string `yaml:"-"`
Root string `yaml:"root" env:"LLM_HTTP_ROOT" desc:"Subdirectory that serves as the root for this HTTP service." introductionVersion:"%%NEXT%%"`
CORS CORS `yaml:"cors"`
TLS shared.HTTPServiceTLS `yaml:"tls"`
}
+9
View File
@@ -0,0 +1,9 @@
package config
// Log defines the available log configuration.
type Log struct {
Level string `mapstructure:"level" env:"OCIS_LOG_LEVEL;LLM_LOG_LEVEL" desc:"The log level. Valid values are: 'panic', 'fatal', 'error', 'warn', 'info', 'debug', 'trace'." introductionVersion:"%%NEXT%%"`
Pretty bool `mapstructure:"pretty" env:"OCIS_LOG_PRETTY;LLM_LOG_PRETTY" desc:"Activates pretty log output." introductionVersion:"%%NEXT%%"`
Color bool `mapstructure:"color" env:"OCIS_LOG_COLOR;LLM_LOG_COLOR" desc:"Activates colorized log output." introductionVersion:"%%NEXT%%"`
File string `mapstructure:"file" env:"OCIS_LOG_FILE;LLM_LOG_FILE" desc:"The path to the log file. Activates logging to this file if set." introductionVersion:"%%NEXT%%"`
}
+61
View File
@@ -0,0 +1,61 @@
package parser
import (
"errors"
"fmt"
"net/url"
ociscfg "github.com/owncloud/ocis/v2/ocis-pkg/config"
"github.com/owncloud/ocis/v2/ocis-pkg/config/envdecode"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/owncloud/ocis/v2/services/llm/pkg/config/defaults"
)
// ParseConfig loads configuration from known paths.
func ParseConfig(cfg *config.Config) error {
err := ociscfg.BindSourcesToStructs(cfg.Service.Name, cfg)
if err != nil {
return err
}
defaults.EnsureDefaults(cfg)
// load all env variables relevant to the config in the current context.
if err := envdecode.Decode(cfg); err != nil {
// no environment variable set for this config is an expected "error"
if !errors.Is(err, envdecode.ErrNoTargetFieldsAreSet) {
return err
}
}
defaults.Sanitize(cfg)
return Validate(cfg)
}
// Validate validates the config.
func Validate(cfg *config.Config) error {
if cfg.LLM.Endpoint == "" {
return errors.New("llm: LLM_ENDPOINT is required")
}
u, err := url.Parse(cfg.LLM.Endpoint)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return fmt.Errorf("llm: LLM_ENDPOINT must be an http(s) URL, got %q", cfg.LLM.Endpoint)
}
if cfg.LLM.MaxTokensLimit <= 0 {
return errors.New("llm: LLM_MAX_TOKENS_LIMIT must be greater than 0")
}
if cfg.LLM.Timeout < 0 {
return errors.New("llm: LLM_TIMEOUT must not be negative")
}
if cfg.RateLimit.Window < 0 || cfg.RateLimit.MaxRequests < 0 {
return errors.New("llm: LLM_RATE_LIMIT_WINDOW and LLM_RATE_LIMIT_MAX_REQUESTS must not be negative")
}
// Rate-limit records are expired by the store; a store TTL shorter than
// the window would silently shrink the effective window.
if cfg.RateLimit.Window > 0 && cfg.RateLimit.MaxRequests > 0 &&
cfg.Store.TTL > 0 && cfg.Store.TTL < cfg.RateLimit.Window {
return fmt.Errorf("llm: LLM_STORE_TTL (%s) must not be shorter than LLM_RATE_LIMIT_WINDOW (%s)", cfg.Store.TTL, cfg.RateLimit.Window)
}
return nil
}
@@ -0,0 +1,68 @@
package parser
import (
"testing"
"time"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
)
func TestValidate_RequiresEndpoint(t *testing.T) {
cfg := &config.Config{}
if err := Validate(cfg); err == nil {
t.Fatal("expected an error when LLM.Endpoint is empty")
}
}
func TestValidate_PassesWhenEndpointSet(t *testing.T) {
cfg := validConfig()
if err := Validate(cfg); err != nil {
t.Fatalf("expected no error when LLM.Endpoint is set, got: %v", err)
}
}
func validConfig() *config.Config {
return &config.Config{
LLM: config.LLM{
Endpoint: "https://api.example.com/v1",
MaxTokensLimit: 4096,
},
}
}
func TestValidate_RejectsInvalidValues(t *testing.T) {
tests := map[string]func(*config.Config){
"endpoint without scheme": func(c *config.Config) { c.LLM.Endpoint = "api.example.com/v1" },
"endpoint wrong scheme": func(c *config.Config) { c.LLM.Endpoint = "ftp://api.example.com" },
"zero max tokens": func(c *config.Config) { c.LLM.MaxTokensLimit = 0 },
"negative timeout": func(c *config.Config) { c.LLM.Timeout = -time.Second },
"negative window": func(c *config.Config) { c.RateLimit.Window = -time.Second },
"store ttl below window": func(c *config.Config) {
c.RateLimit.Window = time.Hour
c.RateLimit.MaxRequests = 10
c.Store.TTL = 10 * time.Minute
},
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
cfg := validConfig()
mutate(cfg)
if err := Validate(cfg); err == nil {
t.Fatal("expected a validation error")
}
})
}
}
func TestValidate_AcceptsStoreTTLCoveringWindow(t *testing.T) {
cfg := validConfig()
cfg.RateLimit.Window = time.Minute
cfg.RateLimit.MaxRequests = 20
cfg.Store.TTL = 10 * time.Minute
if err := Validate(cfg); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
+6
View File
@@ -0,0 +1,6 @@
package config
// Service defines the available service configuration.
type Service struct {
Name string `yaml:"-"`
}
+21
View File
@@ -0,0 +1,21 @@
package config
import "github.com/owncloud/ocis/v2/ocis-pkg/tracing"
// Tracing defines the available tracing configuration.
type Tracing struct {
Enabled bool `yaml:"enabled" env:"OCIS_TRACING_ENABLED;LLM_TRACING_ENABLED" desc:"Activates tracing." introductionVersion:"%%NEXT%%"`
Type string `yaml:"type" env:"OCIS_TRACING_TYPE;LLM_TRACING_TYPE" desc:"The type of tracing. Defaults to '', which is the same as 'jaeger'. Allowed tracing types are 'jaeger', 'otlp' and '' as of now." introductionVersion:"%%NEXT%%"`
Endpoint string `yaml:"endpoint" env:"OCIS_TRACING_ENDPOINT;LLM_TRACING_ENDPOINT" desc:"The endpoint of the tracing agent." introductionVersion:"%%NEXT%%"`
Collector string `yaml:"collector" env:"OCIS_TRACING_COLLECTOR;LLM_TRACING_COLLECTOR" desc:"The HTTP endpoint for sending spans directly to a collector, i.e. http://jaeger-collector:14268/api/traces. Only used if the tracing endpoint is unset." introductionVersion:"%%NEXT%%"`
}
// Convert Tracing to the tracing package's Config struct.
func (t Tracing) Convert() tracing.Config {
return tracing.Config{
Enabled: t.Enabled,
Type: t.Type,
Endpoint: t.Endpoint,
Collector: t.Collector,
}
}
+18
View File
@@ -0,0 +1,18 @@
// services/llm/pkg/logging/logging.go
package logging
import (
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
)
// Configure initializes a service-specific logger instance.
func Configure(name string, cfg *config.Log) log.Logger {
return log.NewLogger(
log.Name(name),
log.Level(cfg.Level),
log.Pretty(cfg.Pretty),
log.Color(cfg.Color),
log.File(cfg.File),
)
}
+33
View File
@@ -0,0 +1,33 @@
// services/llm/pkg/metrics/metrics.go
package metrics
import "github.com/prometheus/client_golang/prometheus"
var (
// Namespace defines the namespace for the defined metrics.
Namespace = "ocis"
// Subsystem defines the subsystem for the defined metrics.
Subsystem = "llm"
)
// Metrics defines the available metrics of this service.
type Metrics struct {
BuildInfo *prometheus.GaugeVec
}
// New initializes the available metrics.
func New() *Metrics {
m := &Metrics{
BuildInfo: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: Namespace,
Subsystem: Subsystem,
Name: "build_info",
Help: "Build information",
}, []string{"version"}),
}
_ = prometheus.Register(m.BuildInfo)
return m
}
+105
View File
@@ -0,0 +1,105 @@
// Package ratelimit implements a per-key sliding-window request limiter
// backed by a go-micro store.
//
// The go-micro store interface has no compare-and-swap, so a read-modify-write
// of a single shared counter would let concurrent replicas overwrite each
// other. Instead every request writes its own record (key "<key>/<unixnano>-<nonce>")
// and then counts the key's records within the window. A request that finds
// itself over the limit removes its own record and is denied. Because records
// are never overwritten, the limit holds across replicas: concurrent requests
// at the boundary may all be denied, but more than the maximum are never
// admitted.
//
// Records are expired by the store (a per-write TTL where supported, the
// store-wide TTL otherwise, which must therefore be at least the window).
package ratelimit
import (
"crypto/rand"
"encoding/hex"
"strconv"
"strings"
"time"
microstore "go-micro.dev/v4/store"
)
const separator = "/"
// Limiter enforces a per-key sliding-window request limit.
type Limiter struct {
store microstore.Store
window time.Duration
maxRequests int
}
// New creates a Limiter. If window <= 0 or maxRequests <= 0, the limiter is
// disabled and Allow always returns true.
func New(store microstore.Store, window time.Duration, maxRequests int) *Limiter {
return &Limiter{
store: store,
window: window,
maxRequests: maxRequests,
}
}
// Allow registers a request for key and reports whether it is within the
// configured limit. A denied request does not count against the limit.
func (l *Limiter) Allow(key string) (bool, error) {
if l == nil {
return true, nil
}
if l.window <= 0 || l.maxRequests <= 0 {
return true, nil
}
nonce := make([]byte, 4)
if _, err := rand.Read(nonce); err != nil {
return false, err
}
now := time.Now()
recordKey := key + separator + strconv.FormatInt(now.UnixNano(), 10) + "-" + hex.EncodeToString(nonce)
if err := l.store.Write(&microstore.Record{Key: recordKey}, microstore.WriteTTL(l.window)); err != nil {
return false, err
}
prefix := key + separator
keys, err := l.store.List(microstore.ListPrefix(prefix))
if err != nil {
// do not leave an uncounted-for record behind when we cannot decide
_ = l.store.Delete(recordKey)
return false, err
}
cutoff := now.Add(-l.window).UnixNano()
count := 0
for _, k := range keys {
if recordTime(k, prefix) >= cutoff {
count++
}
}
if count > l.maxRequests {
if err := l.store.Delete(recordKey); err != nil && err != microstore.ErrNotFound {
return false, err
}
return false, nil
}
return true, nil
}
// recordTime extracts the request timestamp from a record key. Keys that do
// not belong to prefix or are malformed yield 0 (i.e. "expired").
func recordTime(recordKey, prefix string) int64 {
if !strings.HasPrefix(recordKey, prefix) {
return 0
}
suffix := strings.TrimPrefix(recordKey, prefix)
ts, _, _ := strings.Cut(suffix, "-")
n, err := strconv.ParseInt(ts, 10, 64)
if err != nil {
return 0
}
return n
}
@@ -0,0 +1,181 @@
package ratelimit
import (
"sync"
"sync/atomic"
"testing"
"time"
microstore "go-micro.dev/v4/store"
)
func TestLimiter_AllowsUpToMax(t *testing.T) {
l := New(microstore.NewMemoryStore(), time.Minute, 3)
for i := 0; i < 3; i++ {
allowed, err := l.Allow("user-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !allowed {
t.Fatalf("request %d should have been allowed", i+1)
}
}
}
func TestLimiter_DeniesOverMax(t *testing.T) {
l := New(microstore.NewMemoryStore(), time.Minute, 2)
for i := 0; i < 2; i++ {
if _, err := l.Allow("user-1"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
allowed, err := l.Allow("user-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if allowed {
t.Fatal("third request should have been denied")
}
}
func TestLimiter_TracksUsersIndependently(t *testing.T) {
l := New(microstore.NewMemoryStore(), time.Minute, 1)
allowed, err := l.Allow("user-1")
if err != nil || !allowed {
t.Fatalf("user-1 first request should be allowed, got allowed=%v err=%v", allowed, err)
}
allowed, err = l.Allow("user-2")
if err != nil || !allowed {
t.Fatalf("user-2 first request should be allowed, got allowed=%v err=%v", allowed, err)
}
allowed, err = l.Allow("user-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if allowed {
t.Fatal("user-1 second request should have been denied")
}
}
func TestLimiter_WindowExpiryClearsOldEntries(t *testing.T) {
l := New(microstore.NewMemoryStore(), 10*time.Millisecond, 1)
allowed, err := l.Allow("user-1")
if err != nil || !allowed {
t.Fatalf("first request should be allowed, got allowed=%v err=%v", allowed, err)
}
time.Sleep(20 * time.Millisecond)
allowed, err = l.Allow("user-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !allowed {
t.Fatal("request after window expiry should have been allowed")
}
}
func TestLimiter_DisabledWhenMaxRequestsIsZero(t *testing.T) {
l := New(microstore.NewMemoryStore(), time.Minute, 0)
for i := 0; i < 50; i++ {
allowed, err := l.Allow("user-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !allowed {
t.Fatalf("request %d should have been allowed when the limiter is disabled", i+1)
}
}
}
// Two limiters sharing one store stand in for two llm replicas.
func TestLimiter_SharedAcrossReplicas(t *testing.T) {
shared := microstore.NewMemoryStore()
a := New(shared, time.Minute, 4)
b := New(shared, time.Minute, 4)
for i := 0; i < 2; i++ {
for _, l := range []*Limiter{a, b} {
allowed, err := l.Allow("user-1")
if err != nil || !allowed {
t.Fatalf("request should be allowed, got allowed=%v err=%v", allowed, err)
}
}
}
for _, l := range []*Limiter{a, b} {
allowed, err := l.Allow("user-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if allowed {
t.Fatal("request beyond the shared limit should have been denied")
}
}
}
func TestLimiter_ConcurrentRequestsNeverExceedMax(t *testing.T) {
shared := microstore.NewMemoryStore()
const max = 5
var admitted int32
var wg sync.WaitGroup
for i := 0; i < 40; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
// each goroutine is its own "replica" with no shared mutex
allowed, err := New(shared, time.Minute, max).Allow("user-1")
if err != nil {
t.Errorf("unexpected error: %v", err)
return
}
if allowed {
atomic.AddInt32(&admitted, 1)
}
}(i)
}
wg.Wait()
if admitted > max {
t.Fatalf("admitted %d requests, limit is %d", admitted, max)
}
}
func TestLimiter_DeniedRequestsDoNotCount(t *testing.T) {
l := New(microstore.NewMemoryStore(), 50*time.Millisecond, 1)
if allowed, _ := l.Allow("user-1"); !allowed {
t.Fatal("first request should be allowed")
}
for i := 0; i < 5; i++ {
if allowed, _ := l.Allow("user-1"); allowed {
t.Fatal("request should be denied")
}
}
time.Sleep(80 * time.Millisecond)
if allowed, _ := l.Allow("user-1"); !allowed {
t.Fatal("denied requests must not extend the window")
}
}
func TestLimiter_KeyPrefixDoesNotLeak(t *testing.T) {
l := New(microstore.NewMemoryStore(), time.Minute, 1)
if allowed, _ := l.Allow("user"); !allowed {
t.Fatal("first request should be allowed")
}
if allowed, _ := l.Allow("user/other"); !allowed {
t.Fatal("a key that merely starts with another key must be tracked separately")
}
}
+75
View File
@@ -0,0 +1,75 @@
// Package sanitize validates and sanitizes the JSON body a client sends to
// the chat-completions endpoint before it is forwarded to the upstream LLM.
// Only the fields the LLM actually needs are forwarded; everything else the
// client sent is dropped, so a client cannot inject unexpected upstream
// parameters.
package sanitize
import "errors"
// Request is the sanitized body forwarded to the upstream LLM.
type Request struct {
Model string `json:"model"`
Messages []interface{} `json:"messages"`
MaxTokens int `json:"max_tokens"`
Temperature *float64 `json:"temperature,omitempty"`
}
// Body validates and sanitizes a client's decoded JSON body.
//
// modelOverride, when non-empty, replaces whatever model the client sent.
// maxTokensLimit is a hard ceiling: the client's max_tokens is used only if
// positive, and is always clamped to this limit, which must itself be positive.
func Body(raw map[string]interface{}, modelOverride string, maxTokensLimit int) (Request, error) {
if maxTokensLimit <= 0 {
return Request{}, errors.New("max tokens limit must be positive")
}
if stream, ok := raw["stream"].(bool); ok && stream {
return Request{}, errors.New("streaming is not supported")
}
model := modelOverride
if model == "" {
if m, ok := raw["model"].(string); ok {
model = m
}
}
if model == "" {
return Request{}, errors.New("model is required")
}
messages, ok := raw["messages"].([]interface{})
if !ok || len(messages) == 0 {
return Request{}, errors.New("messages must be a non-empty array")
}
for _, m := range messages {
msg, ok := m.(map[string]interface{})
if !ok {
return Request{}, errors.New("each message must be an object")
}
if _, ok := msg["role"].(string); !ok {
return Request{}, errors.New("each message must have a string role")
}
}
maxTokens := maxTokensLimit
if v, ok := raw["max_tokens"].(float64); ok && v > 0 {
maxTokens = int(v)
}
if maxTokens > maxTokensLimit {
maxTokens = maxTokensLimit
}
req := Request{
Model: model,
Messages: messages,
MaxTokens: maxTokens,
}
if t, ok := raw["temperature"].(float64); ok {
req.Temperature = &t
}
return req, nil
}
+172
View File
@@ -0,0 +1,172 @@
package sanitize
import "testing"
var validMessages = []interface{}{map[string]interface{}{"role": "user", "content": "hi"}}
func TestBody_RequiresModel(t *testing.T) {
_, err := Body(map[string]interface{}{
"messages": validMessages,
}, "", 4096)
if err == nil {
t.Fatal("expected an error when model is missing and no override is set")
}
}
func TestBody_ModelOverrideWins(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "client-requested-model",
"messages": validMessages,
}, "forced-model", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.Model != "forced-model" {
t.Fatalf("expected model override to win, got %q", req.Model)
}
}
func TestBody_ClientModelUsedWhenNoOverride(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "client-model",
"messages": validMessages,
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.Model != "client-model" {
t.Fatalf("expected client model, got %q", req.Model)
}
}
func TestBody_RequiresMessagesArray(t *testing.T) {
_, err := Body(map[string]interface{}{
"model": "m",
"messages": "not-an-array",
}, "", 4096)
if err == nil {
t.Fatal("expected an error when messages is not an array")
}
}
func TestBody_MaxTokensClampedToLimit(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "m",
"messages": validMessages,
"max_tokens": float64(999999),
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.MaxTokens != 4096 {
t.Fatalf("expected max_tokens clamped to 4096, got %d", req.MaxTokens)
}
}
func TestBody_MaxTokensDefaultsToLimitWhenAbsent(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "m",
"messages": validMessages,
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.MaxTokens != 4096 {
t.Fatalf("expected max_tokens to default to the limit, got %d", req.MaxTokens)
}
}
func TestBody_MaxTokensDefaultsToLimitWhenNotPositive(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "m",
"messages": validMessages,
"max_tokens": float64(-1),
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.MaxTokens != 4096 {
t.Fatalf("expected max_tokens to default to the limit for a non-positive value, got %d", req.MaxTokens)
}
}
func TestBody_TemperaturePassedThrough(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "m",
"messages": validMessages,
"temperature": float64(0.7),
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.Temperature == nil || *req.Temperature != 0.7 {
t.Fatalf("expected temperature 0.7, got %v", req.Temperature)
}
}
func TestBody_TemperatureOmittedWhenAbsent(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "m",
"messages": validMessages,
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.Temperature != nil {
t.Fatalf("expected temperature to be nil, got %v", req.Temperature)
}
}
func TestBody_DropsUnknownFields(t *testing.T) {
req, err := Body(map[string]interface{}{
"model": "m",
"messages": validMessages,
"some_random_field": "should be dropped",
}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if req.Model != "m" || len(req.Messages) != 1 {
t.Fatalf("unexpected sanitized request: %+v", req)
}
}
func TestBody_RejectsInvalidMessages(t *testing.T) {
tests := map[string][]interface{}{
"empty": {},
"non-object": {"hi"},
"missing role": {map[string]interface{}{"content": "hi"}},
"non-string role": {map[string]interface{}{"role": 1}},
}
for name, messages := range tests {
t.Run(name, func(t *testing.T) {
_, err := Body(map[string]interface{}{"model": "m", "messages": messages}, "", 4096)
if err == nil {
t.Fatal("expected an error")
}
})
}
}
func TestBody_RejectsNonPositiveMaxTokensLimit(t *testing.T) {
for _, limit := range []int{0, -1} {
_, err := Body(map[string]interface{}{"model": "m", "messages": validMessages}, "", limit)
if err == nil {
t.Fatalf("expected an error for limit %d", limit)
}
}
}
func TestBody_RejectsStreaming(t *testing.T) {
_, err := Body(map[string]interface{}{"model": "m", "messages": validMessages, "stream": true}, "", 4096)
if err == nil {
t.Fatal("expected an error when stream is true")
}
}
func TestBody_AllowsStreamFalse(t *testing.T) {
_, err := Body(map[string]interface{}{"model": "m", "messages": validMessages, "stream": false}, "", 4096)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
+43
View File
@@ -0,0 +1,43 @@
// services/llm/pkg/server/debug/option.go
package debug
import (
"context"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
)
// Option defines a single option function.
type Option func(o *Options)
// Options defines the available options for this package.
type Options struct {
Logger log.Logger
Context context.Context
Config *config.Config
}
// newOptions initializes the available default options.
func newOptions(opts ...Option) Options {
opt := Options{}
for _, o := range opts {
o(&opt)
}
return opt
}
// Logger provides a function to set the logger option.
func Logger(val log.Logger) Option {
return func(o *Options) { o.Logger = val }
}
// Context provides a function to set the context option.
func Context(val context.Context) Option {
return func(o *Options) { o.Context = val }
}
// Config provides a function to set the config option.
func Config(val *config.Config) Option {
return func(o *Options) { o.Config = val }
}
+38
View File
@@ -0,0 +1,38 @@
// services/llm/pkg/server/debug/server.go
package debug
import (
"net/http"
"github.com/owncloud/ocis/v2/ocis-pkg/checks"
"github.com/owncloud/ocis/v2/ocis-pkg/handlers"
"github.com/owncloud/ocis/v2/ocis-pkg/service/debug"
"github.com/owncloud/ocis/v2/ocis-pkg/version"
)
// Server initializes the debug service and server.
func Server(opts ...Option) (*http.Server, error) {
options := newOptions(opts...)
checkHandler := handlers.NewCheckHandler(
handlers.NewCheckHandlerConfiguration().
WithLogger(options.Logger).
WithCheck("llm reachability", checks.NewHTTPCheck(options.Config.HTTP.Addr)),
)
return debug.NewService(
debug.Logger(options.Logger),
debug.Name(options.Config.Service.Name),
debug.Version(version.GetString()),
debug.Address(options.Config.Debug.Addr),
debug.Token(options.Config.Debug.Token),
debug.Pprof(options.Config.Debug.Pprof),
debug.Zpages(options.Config.Debug.Zpages),
debug.Health(checkHandler),
debug.Ready(checkHandler),
debug.CorsAllowedOrigins(options.Config.HTTP.CORS.AllowedOrigins),
debug.CorsAllowedMethods(options.Config.HTTP.CORS.AllowedMethods),
debug.CorsAllowedHeaders(options.Config.HTTP.CORS.AllowedHeaders),
debug.CorsAllowCredentials(options.Config.HTTP.CORS.AllowCredentials),
), nil
}
+67
View File
@@ -0,0 +1,67 @@
// services/llm/pkg/server/http/option.go
package http
import (
"context"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/noop"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/owncloud/ocis/v2/services/llm/pkg/ratelimit"
"github.com/urfave/cli/v2"
)
// Option defines a single option function.
type Option func(o *Options)
// Options defines the available options for this package.
type Options struct {
Logger log.Logger
Context context.Context
Config *config.Config
Flags []cli.Flag
Limiter *ratelimit.Limiter
TraceProvider trace.TracerProvider
}
// newOptions initializes the available default options.
func newOptions(opts ...Option) Options {
opt := Options{}
for _, o := range opts {
o(&opt)
}
return opt
}
// Logger provides a function to set the logger option.
func Logger(val log.Logger) Option {
return func(o *Options) { o.Logger = val }
}
// Context provides a function to set the context option.
func Context(val context.Context) Option {
return func(o *Options) { o.Context = val }
}
// Config provides a function to set the config option.
func Config(val *config.Config) Option {
return func(o *Options) { o.Config = val }
}
// Limiter provides a function to set the rate limiter option.
func Limiter(val *ratelimit.Limiter) Option {
return func(o *Options) { o.Limiter = val }
}
// TraceProvider provides a function to configure the trace provider.
func TraceProvider(traceProvider trace.TracerProvider) Option {
return func(o *Options) {
if traceProvider != nil {
o.TraceProvider = traceProvider
} else {
o.TraceProvider = noop.NewTracerProvider()
}
}
}
+94
View File
@@ -0,0 +1,94 @@
// services/llm/pkg/server/http/server.go
package http
import (
nethttp "net/http"
"github.com/go-chi/chi/v5"
chimiddleware "github.com/go-chi/chi/v5/middleware"
"go-micro.dev/v4"
"github.com/owncloud/ocis/v2/ocis-pkg/account"
"github.com/owncloud/ocis/v2/ocis-pkg/cors"
"github.com/owncloud/ocis/v2/ocis-pkg/middleware"
ohttp "github.com/owncloud/ocis/v2/ocis-pkg/service/http"
"github.com/owncloud/ocis/v2/ocis-pkg/version"
"github.com/owncloud/ocis/v2/services/llm/pkg/service"
)
// Server initializes the http service and server.
func Server(opts ...Option) (ohttp.Service, error) {
options := newOptions(opts...)
newService, err := ohttp.NewService(
ohttp.TLSConfig(options.Config.HTTP.TLS),
ohttp.Logger(options.Logger),
ohttp.Namespace(options.Config.HTTP.Namespace),
ohttp.Name(options.Config.Service.Name),
ohttp.Version(version.GetString()),
ohttp.Address(options.Config.HTTP.Addr),
ohttp.Context(options.Context),
ohttp.Flags(options.Flags...),
ohttp.TraceProvider(options.TraceProvider),
)
if err != nil {
options.Logger.Error().Err(err).Msg("Error initializing http service")
return ohttp.Service{}, err
}
svc := service.New(options.Config, options.Limiter, options.Logger)
mux := chi.NewMux()
mux.Use(
middleware.GetOtelhttpMiddleware(options.Config.Service.Name, options.TraceProvider),
chimiddleware.RequestID,
middleware.Version(options.Config.Service.Name, version.GetString()),
middleware.Logger(options.Logger),
requireIdentity(middleware.ExtractAccountUUID(
account.Logger(options.Logger),
account.JWTSecret(options.Config.TokenManager.JWTSecret),
)),
middleware.Cors(
cors.Logger(options.Logger),
cors.AllowedOrigins(options.Config.HTTP.CORS.AllowedOrigins),
cors.AllowedMethods(options.Config.HTTP.CORS.AllowedMethods),
cors.AllowedHeaders(options.Config.HTTP.CORS.AllowedHeaders),
cors.AllowCredentials(options.Config.HTTP.CORS.AllowCredentials),
),
)
mux.Route(options.Config.HTTP.Root, func(r chi.Router) {
// proxy forwards the original request path unchanged (it does not
// strip the matched prefix — see activitylog's route registration
// for the same pattern), so this must be the full external path.
r.Post("/graph/v1beta1/extensions/org.libregraph/llm/chat/completions", svc.HandleChatCompletions)
})
if err := micro.RegisterHandler(newService.Server(), mux); err != nil {
options.Logger.Error().Err(err).Msg("failed to register the handler")
return ohttp.Service{}, err
}
newService.Init()
return newService, nil
}
// requireIdentity wraps the account middleware, which silently returns an
// empty 200 when the token is invalid or out of scope. Reject those requests
// explicitly instead.
func requireIdentity(extract func(nethttp.Handler) nethttp.Handler) func(nethttp.Handler) nethttp.Handler {
return func(next nethttp.Handler) nethttp.Handler {
return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {
passed := false
extract(nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {
passed = true
next.ServeHTTP(w, r)
})).ServeHTTP(w, r)
if !passed {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(nethttp.StatusUnauthorized)
_, _ = w.Write([]byte(`{"error":"invalid access token"}` + "\n"))
}
})
}
}
@@ -0,0 +1,40 @@
package http
import (
nethttp "net/http"
"net/http/httptest"
"testing"
)
func TestRequireIdentity_RejectsWhenAccountMiddlewareStopsTheRequest(t *testing.T) {
// stands in for ExtractAccountUUID returning early on an invalid token
extract := func(next nethttp.Handler) nethttp.Handler {
return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {})
}
called := false
h := requireIdentity(extract)(nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) { called = true }))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(nethttp.MethodPost, "/", nil))
if rec.Code != nethttp.StatusUnauthorized {
t.Fatalf("expected 401, got %d", rec.Code)
}
if called {
t.Fatal("next handler must not run")
}
}
func TestRequireIdentity_PassesThroughWhenAccountMiddlewareContinues(t *testing.T) {
extract := func(next nethttp.Handler) nethttp.Handler { return next }
h := requireIdentity(extract)(nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {
w.WriteHeader(nethttp.StatusNoContent)
}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(nethttp.MethodPost, "/", nil))
if rec.Code != nethttp.StatusNoContent {
t.Fatalf("expected 204, got %d", rec.Code)
}
}
+21
View File
@@ -0,0 +1,21 @@
package service
import (
"errors"
"io"
)
var errBodyTooLarge = errors.New("request body too large")
// readLimited reads r fully, returning errBodyTooLarge if the body exceeds
// maxBytes.
func readLimited(r io.Reader, maxBytes int64) ([]byte, error) {
data, err := io.ReadAll(io.LimitReader(r, maxBytes+1))
if err != nil {
return nil, err
}
if int64(len(data)) > maxBytes {
return nil, errBodyTooLarge
}
return data, nil
}
+168
View File
@@ -0,0 +1,168 @@
package service
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"time"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/owncloud/ocis/v2/services/llm/pkg/ratelimit"
"github.com/owncloud/ocis/v2/services/llm/pkg/sanitize"
)
// maxUpstreamResponseBytes caps how much of the upstream LLM's response body
// this service will buffer before giving up.
const maxUpstreamResponseBytes = 10 * 1024 * 1024 // 10 MiB
// Service handles chat completion requests, proxying them to the configured
// upstream LLM endpoint.
type Service struct {
cfg *config.Config
limiter *ratelimit.Limiter
client *http.Client
log log.Logger
}
// New creates a new Service.
func New(cfg *config.Config, limiter *ratelimit.Limiter, logger log.Logger) *Service {
return &Service{
cfg: cfg,
limiter: limiter,
client: &http.Client{},
log: logger,
}
}
// HandleChatCompletions handles POST requests forwarding chat completions to
// the configured LLM.
func (s *Service) HandleChatCompletions(w http.ResponseWriter, r *http.Request) {
user, ok := revactx.ContextGetUser(r.Context())
if !ok {
writeError(w, http.StatusUnauthorized, "missing authenticated user")
return
}
body, err := readLimited(r.Body, s.cfg.LLM.MaxBodyBytes)
if err != nil {
if errors.Is(err, errBodyTooLarge) {
writeError(w, http.StatusRequestEntityTooLarge, "request body too large")
} else {
writeError(w, http.StatusBadRequest, "could not read request body")
}
return
}
var raw map[string]interface{}
if err := json.Unmarshal(body, &raw); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
sanitized, err := sanitize.Body(raw, s.cfg.LLM.Model, s.cfg.LLM.MaxTokensLimit)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
// only requests that are valid and about to hit the upstream count
// against the user's quota.
allowed, err := s.limiter.Allow(user.GetId().GetOpaqueId())
if err != nil {
s.log.Warn().Err(err).Msg("rate limit check failed")
writeError(w, http.StatusInternalServerError, "rate limit check failed")
return
}
if !allowed {
writeError(w, http.StatusTooManyRequests, "rate limit exceeded. Please slow down.")
return
}
payload, err := json.Marshal(sanitized)
if err != nil {
writeError(w, http.StatusInternalServerError, "could not encode upstream request")
return
}
ctx, cancel := contextWithTimeout(r.Context(), s.cfg.LLM.Timeout)
defer cancel()
upstreamURL := strings.TrimSuffix(s.cfg.LLM.Endpoint, "/") + "/chat/completions"
upstreamReq, err := http.NewRequestWithContext(ctx, http.MethodPost, upstreamURL, bytes.NewReader(payload))
if err != nil {
writeError(w, http.StatusInternalServerError, "could not build upstream request")
return
}
upstreamReq.Header.Set("Content-Type", "application/json")
if s.cfg.LLM.APIKey != "" {
upstreamReq.Header.Set("Authorization", "Bearer "+s.cfg.LLM.APIKey)
}
resp, err := s.client.Do(upstreamReq)
if err != nil {
s.log.Warn().Err(err).Msg("could not reach upstream LLM endpoint")
writeError(w, http.StatusBadGateway, "could not reach LLM endpoint")
return
}
defer resp.Body.Close()
respBody, err := readLimited(resp.Body, maxUpstreamResponseBytes)
if err != nil {
s.log.Warn().Err(err).Msg("could not read upstream LLM response")
writeError(w, http.StatusBadGateway, "could not read LLM response")
return
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
// Do not relay upstream errors: a 401/403 caused by a bad API key
// would look like an expired session to the web client, and the
// error text can contain provider account details.
s.log.Warn().
Int("status", resp.StatusCode).
Str("body", truncate(string(respBody), 512)).
Msg("upstream LLM endpoint returned an error")
if resp.StatusCode == http.StatusTooManyRequests {
writeError(w, http.StatusTooManyRequests, "the LLM endpoint is busy. Please try again later.")
} else {
writeError(w, http.StatusBadGateway, "the LLM endpoint returned an error")
}
return
}
contentType := resp.Header.Get("Content-Type")
if contentType == "" {
contentType = "application/json"
}
w.Header().Set("Content-Type", contentType)
w.WriteHeader(resp.StatusCode)
_, _ = w.Write(respBody)
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "..."
}
func writeError(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": message})
}
// contextWithTimeout wraps context.WithTimeout; a timeout <= 0 means "no
// explicit timeout beyond whatever the parent context already has" instead
// of expiring immediately.
func contextWithTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
if timeout <= 0 {
return parent, func() {}
}
return context.WithTimeout(parent, timeout)
}
+300
View File
@@ -0,0 +1,300 @@
package service
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
revactx "github.com/owncloud/reva/v2/pkg/ctx"
microstore "go-micro.dev/v4/store"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/llm/pkg/config"
"github.com/owncloud/ocis/v2/services/llm/pkg/ratelimit"
)
func testUser(id string) *userpb.User {
return &userpb.User{Id: &userpb.UserId{OpaqueId: id}}
}
func newTestService(t *testing.T, llmServerURL string, maxRequests int) *Service {
t.Helper()
cfg := &config.Config{
LLM: config.LLM{
Endpoint: llmServerURL,
MaxTokensLimit: 4096,
Timeout: 5 * time.Second,
MaxBodyBytes: 1024,
},
}
limiter := ratelimit.New(microstore.NewMemoryStore(), time.Minute, maxRequests)
return New(cfg, limiter, log.NewLogger(log.Level("error")))
}
func requestWithUser(body []byte, userID string) *http.Request {
req := httptest.NewRequest(http.MethodPost, "/chat/completions", bytes.NewReader(body))
if userID != "" {
ctx := revactx.ContextSetUser(req.Context(), testUser(userID))
req = req.WithContext(ctx)
}
return req
}
func TestHandleChatCompletions_NoUser_Returns401(t *testing.T) {
svc := newTestService(t, "http://unused.invalid", 20)
req := requestWithUser([]byte(`{}`), "")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", rec.Code)
}
}
func TestHandleChatCompletions_RateLimited_Returns429(t *testing.T) {
svc := newTestService(t, "http://unused.invalid", 1)
// first request consumes the only allowed slot; the upstream call will
// fail (no server listening at unused.invalid), which is fine — we only
// care about the rate limiter state after this call.
first := requestWithUser([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`), "user-1")
svc.HandleChatCompletions(httptest.NewRecorder(), first)
second := requestWithUser([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`), "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, second)
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("expected 429, got %d", rec.Code)
}
}
func TestHandleChatCompletions_OversizedBody_Returns413(t *testing.T) {
svc := newTestService(t, "http://unused.invalid", 20)
oversized := bytes.Repeat([]byte("a"), 2048)
req := requestWithUser(oversized, "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("expected 413, got %d", rec.Code)
}
}
func TestHandleChatCompletions_InvalidJSON_Returns400(t *testing.T) {
svc := newTestService(t, "http://unused.invalid", 20)
req := requestWithUser([]byte(`not json`), "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", rec.Code)
}
}
func TestHandleChatCompletions_MissingMessages_Returns400(t *testing.T) {
svc := newTestService(t, "http://unused.invalid", 20)
req := requestWithUser([]byte(`{"model":"m"}`), "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", rec.Code)
}
}
func TestHandleChatCompletions_HappyPath_RelaysUpstreamResponse(t *testing.T) {
var receivedPath string
var receivedAuth string
var receivedBody []byte
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedPath = r.URL.Path
receivedAuth = r.Header.Get("Authorization")
receivedBody, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"choices":[{"message":{"content":"hi"}}]}`))
}))
defer upstream.Close()
svc := newTestService(t, upstream.URL, 20)
svc.cfg.LLM.APIKey = "test-key"
req := requestWithUser([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":999999,"some_unknown_field":"should be dropped"}`), "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d, body: %s", rec.Code, rec.Body.String())
}
if receivedPath != "/chat/completions" {
t.Fatalf("expected upstream path /chat/completions, got %q", receivedPath)
}
if receivedAuth != "Bearer test-key" {
t.Fatalf("expected upstream Authorization header, got %q", receivedAuth)
}
var got map[string]interface{}
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatalf("expected valid JSON relayed back, got error: %v, body: %s", err, rec.Body.String())
}
var forwarded map[string]interface{}
if err := json.Unmarshal(receivedBody, &forwarded); err != nil {
t.Fatalf("expected valid JSON forwarded to upstream, got error: %v, body: %s", err, receivedBody)
}
if _, present := forwarded["some_unknown_field"]; present {
t.Fatalf("expected unknown field to be dropped from forwarded body, got: %s", receivedBody)
}
maxTokens, ok := forwarded["max_tokens"].(float64)
if !ok {
t.Fatalf("expected max_tokens to be forwarded, got: %s", receivedBody)
}
if int(maxTokens) != svc.cfg.LLM.MaxTokensLimit {
t.Fatalf("expected max_tokens clamped to %d, got %v", svc.cfg.LLM.MaxTokensLimit, maxTokens)
}
}
func TestHandleChatCompletions_ModelOverride_ReplacesClientModel(t *testing.T) {
var receivedBody []byte
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedBody, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"choices":[{"message":{"content":"hi"}}]}`))
}))
defer upstream.Close()
svc := newTestService(t, upstream.URL, 20)
svc.cfg.LLM.Model = "forced-model"
req := requestWithUser([]byte(`{"model":"client-requested-model","messages":[{"role":"user","content":"hi"}]}`), "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d, body: %s", rec.Code, rec.Body.String())
}
var forwarded map[string]interface{}
if err := json.Unmarshal(receivedBody, &forwarded); err != nil {
t.Fatalf("expected valid JSON forwarded to upstream, got error: %v, body: %s", err, receivedBody)
}
if forwarded["model"] != "forced-model" {
t.Fatalf("expected forwarded model to be overridden to %q, got %v", "forced-model", forwarded["model"])
}
}
func TestHandleChatCompletions_UpstreamUnreachable_Returns502(t *testing.T) {
svc := newTestService(t, "http://127.0.0.1:1", 20) // nothing listens here
req := requestWithUser([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`), "user-1")
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, req)
if rec.Code != http.StatusBadGateway {
t.Fatalf("expected 502, got %d", rec.Code)
}
}
func TestHandleChatCompletions_ClientDisconnect_CancelsUpstreamCall(t *testing.T) {
upstreamStarted := make(chan struct{})
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Drain the request body before waiting: net/http's server only starts
// watching the connection for a client disconnect (which cancels
// r.Context()) once the request body has been fully read. Without this,
// r.Context().Done() below would never fire and the test would hang -
// this is standard net/http behavior, not something the handler under
// test can influence, since it is the *client* whose context we cancel.
_, _ = io.Copy(io.Discard, r.Body)
close(upstreamStarted)
<-r.Context().Done() // the client cancellation below should propagate here
}))
defer upstream.Close()
svc := newTestService(t, upstream.URL, 20)
ctx, cancel := context.WithCancel(context.Background())
req := httptest.NewRequest(http.MethodPost, "/chat/completions", bytes.NewReader([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`)))
req = req.WithContext(revactx.ContextSetUser(ctx, testUser("user-1")))
done := make(chan struct{})
go func() {
svc.HandleChatCompletions(httptest.NewRecorder(), req)
close(done)
}()
<-upstreamStarted
cancel()
select {
case <-done:
// handler returned once the client context was canceled, as expected
case <-time.After(5 * time.Second):
t.Fatal("handler did not return after client disconnect")
}
}
func TestHandleChatCompletions_InvalidRequestDoesNotConsumeQuota(t *testing.T) {
svc := newTestService(t, "http://unused.invalid", 1)
for i := 0; i < 3; i++ {
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, requestWithUser([]byte(`{"model":"m","messages":[]}`), "user-1"))
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", rec.Code)
}
}
// the single allowed slot is still free, so this reaches the (dead) upstream
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, requestWithUser([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`), "user-1"))
if rec.Code != http.StatusBadGateway {
t.Fatalf("expected 502, got %d", rec.Code)
}
}
func TestHandleChatCompletions_UpstreamErrors_AreNotRelayed(t *testing.T) {
tests := []struct {
upstream int
want int
}{
{http.StatusUnauthorized, http.StatusBadGateway},
{http.StatusForbidden, http.StatusBadGateway},
{http.StatusInternalServerError, http.StatusBadGateway},
{http.StatusTooManyRequests, http.StatusTooManyRequests},
}
for _, tt := range tests {
t.Run(http.StatusText(tt.upstream), func(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.upstream)
_, _ = w.Write([]byte(`{"error":"secret provider account detail"}`))
}))
defer upstream.Close()
svc := newTestService(t, upstream.URL, 20)
rec := httptest.NewRecorder()
svc.HandleChatCompletions(rec, requestWithUser([]byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`), "user-1"))
if rec.Code != tt.want {
t.Fatalf("expected %d, got %d", tt.want, rec.Code)
}
if strings.Contains(rec.Body.String(), "secret provider account detail") {
t.Fatal("upstream error body must not be relayed to the client")
}
})
}
}
@@ -270,6 +270,10 @@ func DefaultPolicies() []config.Policy {
Endpoint: "/graph/v1.0/invitations",
Service: "com.owncloud.web.invitations",
},
{
Endpoint: "/graph/v1beta1/extensions/org.libregraph/llm/",
Service: "com.owncloud.web.llm",
},
{
Endpoint: "/graph/",
Service: "com.owncloud.web.graph",