@langwatch/server 3.1.0-beta.7 → 3.1.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/package.json +1 -6
  2. package/packages/server/dist/cli.cjs +23 -17
  3. package/cmd/service/main.go +0 -68
  4. package/go.mod +0 -117
  5. package/go.sum +0 -299
  6. package/pkg/breaker/breaker.go +0 -157
  7. package/pkg/breaker/breaker_test.go +0 -131
  8. package/pkg/clog/LICENSE +0 -26
  9. package/pkg/clog/clog.go +0 -90
  10. package/pkg/clog/clog_test.go +0 -56
  11. package/pkg/clog/panic.go +0 -39
  12. package/pkg/config/LICENSE +0 -26
  13. package/pkg/config/config.go +0 -86
  14. package/pkg/config/config_test.go +0 -70
  15. package/pkg/config/otel.go +0 -50
  16. package/pkg/config/server.go +0 -61
  17. package/pkg/config/validate.go +0 -80
  18. package/pkg/config/validate_test.go +0 -74
  19. package/pkg/contexts/contexts_test.go +0 -34
  20. package/pkg/contexts/request_id.go +0 -1
  21. package/pkg/contexts/service_info.go +0 -33
  22. package/pkg/errfuncs/errfuncs.go +0 -9
  23. package/pkg/errfuncs/errfuncs_test.go +0 -28
  24. package/pkg/forkedcontext/forkedcontext.go +0 -57
  25. package/pkg/health/health.go +0 -123
  26. package/pkg/health/health_test.go +0 -84
  27. package/pkg/herr/LICENSE +0 -26
  28. package/pkg/herr/code.go +0 -14
  29. package/pkg/herr/herr.go +0 -112
  30. package/pkg/herr/herr_test.go +0 -78
  31. package/pkg/herr/http.go +0 -133
  32. package/pkg/herr/http_test.go +0 -103
  33. package/pkg/herr/validate.go +0 -72
  34. package/pkg/herr/validate_test.go +0 -75
  35. package/pkg/httpmiddleware/bearer.go +0 -47
  36. package/pkg/httpmiddleware/httputil_test.go +0 -167
  37. package/pkg/httpmiddleware/inflight.go +0 -23
  38. package/pkg/httpmiddleware/maxbody.go +0 -30
  39. package/pkg/httpmiddleware/recover.go +0 -38
  40. package/pkg/httpmiddleware/requestid.go +0 -40
  41. package/pkg/httpmiddleware/telemetry.go +0 -96
  42. package/pkg/httpmiddleware/version.go +0 -16
  43. package/pkg/jwtverify/verifier.go +0 -72
  44. package/pkg/jwtverify/verifier_test.go +0 -134
  45. package/pkg/ksuid/LICENSE +0 -26
  46. package/pkg/ksuid/ksuid.go +0 -157
  47. package/pkg/ksuid/ksuid_test.go +0 -107
  48. package/pkg/ksuid/resources.go +0 -13
  49. package/pkg/lifecycle/group.go +0 -175
  50. package/pkg/lifecycle/group_test.go +0 -236
  51. package/pkg/lifecycle/service.go +0 -112
  52. package/pkg/netprobe/netprobe.go +0 -89
  53. package/pkg/netprobe/netprobe_test.go +0 -55
  54. package/pkg/otelsetup/otelsetup.go +0 -226
  55. package/pkg/otelsetup/otelsetup_test.go +0 -130
  56. package/pkg/ptr/LICENSE +0 -26
  57. package/pkg/ptr/ptr.go +0 -34
  58. package/pkg/ptr/ptr_test.go +0 -66
  59. package/pkg/retry/bench_test.go +0 -67
  60. package/pkg/retry/retry.go +0 -188
  61. package/pkg/retry/retry_test.go +0 -222
  62. package/pkg/slicefuncs/LICENSE +0 -26
  63. package/pkg/slicefuncs/slicefuncs.go +0 -10
  64. package/pkg/slicefuncs/slicefuncs_test.go +0 -29
  65. package/pkg/stacktrace/LICENSE +0 -26
  66. package/pkg/stacktrace/frames.go +0 -77
  67. package/pkg/stacktrace/frames_test.go +0 -73
  68. package/services/aigateway/BENCHMARKS.md +0 -110
  69. package/services/aigateway/README.md +0 -156
  70. package/services/aigateway/adapters/authresolver/bench_test.go +0 -13
  71. package/services/aigateway/adapters/authresolver/redis.go +0 -61
  72. package/services/aigateway/adapters/authresolver/service.go +0 -442
  73. package/services/aigateway/adapters/authresolver/service_test.go +0 -435
  74. package/services/aigateway/adapters/budget/bench_test.go +0 -50
  75. package/services/aigateway/adapters/budget/budget.go +0 -59
  76. package/services/aigateway/adapters/cacherules/evaluator.go +0 -134
  77. package/services/aigateway/adapters/cacherules/evaluator_test.go +0 -207
  78. package/services/aigateway/adapters/controlplane/bench_test.go +0 -40
  79. package/services/aigateway/adapters/controlplane/client.go +0 -213
  80. package/services/aigateway/adapters/controlplane/client_test.go +0 -73
  81. package/services/aigateway/adapters/controlplane/config_wire.go +0 -310
  82. package/services/aigateway/adapters/controlplane/guardrails.go +0 -88
  83. package/services/aigateway/adapters/controlplane/signer.go +0 -95
  84. package/services/aigateway/adapters/controlplane/signer_test.go +0 -64
  85. package/services/aigateway/adapters/customertracebridge/context.go +0 -48
  86. package/services/aigateway/adapters/customertracebridge/context_test.go +0 -24
  87. package/services/aigateway/adapters/customertracebridge/emitter.go +0 -329
  88. package/services/aigateway/adapters/customertracebridge/emitter_test.go +0 -93
  89. package/services/aigateway/adapters/customertracebridge/registry.go +0 -82
  90. package/services/aigateway/adapters/customertracebridge/transport.go +0 -122
  91. package/services/aigateway/adapters/gatewaytracer/attrs.go +0 -28
  92. package/services/aigateway/adapters/gatewaytracer/attrs_genai.go +0 -24
  93. package/services/aigateway/adapters/gatewaytracer/headers.go +0 -8
  94. package/services/aigateway/adapters/gatewaytracer/tracer.go +0 -101
  95. package/services/aigateway/adapters/httpapi/bench_test.go +0 -83
  96. package/services/aigateway/adapters/httpapi/middleware.go +0 -123
  97. package/services/aigateway/adapters/httpapi/router.go +0 -635
  98. package/services/aigateway/adapters/httpapi/router_test.go +0 -633
  99. package/services/aigateway/adapters/modelresolver/resolver.go +0 -107
  100. package/services/aigateway/adapters/modelresolver/resolver_test.go +0 -140
  101. package/services/aigateway/adapters/policy/matcher.go +0 -250
  102. package/services/aigateway/adapters/policy/matcher_test.go +0 -124
  103. package/services/aigateway/adapters/providers/bifrost.go +0 -798
  104. package/services/aigateway/adapters/providers/bifrost_parser.go +0 -201
  105. package/services/aigateway/adapters/providers/bifrost_test.go +0 -181
  106. package/services/aigateway/adapters/ratelimit/limiter.go +0 -122
  107. package/services/aigateway/adapters/ratelimit/limiter_test.go +0 -81
  108. package/services/aigateway/app/app.go +0 -104
  109. package/services/aigateway/app/dispatch.go +0 -89
  110. package/services/aigateway/app/dispatch_test.go +0 -475
  111. package/services/aigateway/app/handlers.go +0 -79
  112. package/services/aigateway/app/peek_bench_test.go +0 -21
  113. package/services/aigateway/app/pipeline/bench_test.go +0 -34
  114. package/services/aigateway/app/pipeline/budget.go +0 -55
  115. package/services/aigateway/app/pipeline/cache.go +0 -34
  116. package/services/aigateway/app/pipeline/cachecontrol.go +0 -86
  117. package/services/aigateway/app/pipeline/cachecontrol_test.go +0 -110
  118. package/services/aigateway/app/pipeline/guardrail.go +0 -121
  119. package/services/aigateway/app/pipeline/pipeline.go +0 -159
  120. package/services/aigateway/app/pipeline/policy.go +0 -23
  121. package/services/aigateway/app/pipeline/ratelimit.go +0 -21
  122. package/services/aigateway/app/pipeline/rawframing_test.go +0 -67
  123. package/services/aigateway/app/pipeline/resolve.go +0 -44
  124. package/services/aigateway/app/pipeline/trace.go +0 -129
  125. package/services/aigateway/app/ports.go +0 -61
  126. package/services/aigateway/cmd/root.go +0 -42
  127. package/services/aigateway/config.go +0 -86
  128. package/services/aigateway/deps.go +0 -177
  129. package/services/aigateway/domain/bundle.go +0 -203
  130. package/services/aigateway/domain/errors.go +0 -23
  131. package/services/aigateway/domain/model.go +0 -24
  132. package/services/aigateway/domain/provider.go +0 -38
  133. package/services/aigateway/domain/request.go +0 -65
  134. package/services/aigateway/domain/response.go +0 -56
  135. package/services/aigateway/domain/verdict.go +0 -55
  136. package/services/aigateway/serve.go +0 -45
  137. package/services/aigateway/tests/matrix/README.md +0 -71
  138. package/services/aigateway/tests/matrix/anthropic_test.go +0 -61
  139. package/services/aigateway/tests/matrix/azure_test.go +0 -52
  140. package/services/aigateway/tests/matrix/bedrock_test.go +0 -69
  141. package/services/aigateway/tests/matrix/gemini_test.go +0 -117
  142. package/services/aigateway/tests/matrix/matrix_test.go +0 -601
  143. package/services/aigateway/tests/matrix/openai_test.go +0 -66
  144. package/services/aigateway/tests/matrix/vertex_test.go +0 -160
@@ -1,207 +0,0 @@
1
- package cacherules
2
-
3
- import (
4
- "context"
5
- "testing"
6
-
7
- "github.com/stretchr/testify/assert"
8
- "github.com/stretchr/testify/require"
9
-
10
- "github.com/langwatch/langwatch/services/aigateway/domain"
11
- )
12
-
13
- func TestEvaluate_NoRules(t *testing.T) {
14
- e := NewEvaluator()
15
- got := e.Evaluate(context.Background(), nil, domain.CacheEvalContext{Model: "gpt-4"})
16
- assert.Nil(t, got)
17
- }
18
-
19
- func TestEvaluate_MatchAll(t *testing.T) {
20
- e := NewEvaluator()
21
- rules := []domain.CacheRule{
22
- {ID: "r1", Priority: 1, Match: domain.CacheRuleMatch{}, Action: domain.CacheActionDisable},
23
- }
24
-
25
- got := e.Evaluate(context.Background(), rules, domain.CacheEvalContext{Model: "any-model"})
26
- require.NotNil(t, got)
27
- assert.Equal(t, domain.CacheActionDisable, got.Action)
28
- assert.Equal(t, "r1", got.RuleID)
29
- }
30
-
31
- func TestEvaluate_GlobMatch(t *testing.T) {
32
- e := NewEvaluator()
33
- rules := []domain.CacheRule{
34
- {ID: "r1", Priority: 1, Match: domain.CacheRuleMatch{Models: []string{"gpt-*"}}, Action: domain.CacheActionForce},
35
- }
36
-
37
- got := e.Evaluate(context.Background(), rules, domain.CacheEvalContext{Model: "gpt-4"})
38
- require.NotNil(t, got)
39
- assert.Equal(t, domain.CacheActionForce, got.Action)
40
- assert.Equal(t, "r1", got.RuleID)
41
- }
42
-
43
- func TestEvaluate_NoMatch(t *testing.T) {
44
- e := NewEvaluator()
45
- rules := []domain.CacheRule{
46
- {ID: "r1", Priority: 1, Match: domain.CacheRuleMatch{Models: []string{"claude-*"}}, Action: domain.CacheActionForce},
47
- }
48
-
49
- got := e.Evaluate(context.Background(), rules, domain.CacheEvalContext{Model: "gpt-4"})
50
- assert.Nil(t, got)
51
- }
52
-
53
- func TestEvaluate_PriorityOrder(t *testing.T) {
54
- e := NewEvaluator()
55
- rules := []domain.CacheRule{
56
- {ID: "high-pri", Priority: 10, Match: domain.CacheRuleMatch{}, Action: domain.CacheActionDisable},
57
- {ID: "low-pri", Priority: 1, Match: domain.CacheRuleMatch{}, Action: domain.CacheActionForce},
58
- }
59
-
60
- got := e.Evaluate(context.Background(), rules, domain.CacheEvalContext{Model: "gpt-4"})
61
- require.NotNil(t, got)
62
- assert.Equal(t, "low-pri", got.RuleID, "lower priority number wins")
63
- assert.Equal(t, domain.CacheActionForce, got.Action)
64
- }
65
-
66
- func TestEvaluate_ReturnsAction(t *testing.T) {
67
- e := NewEvaluator()
68
- rules := []domain.CacheRule{
69
- {ID: "cache-rule-42", Priority: 5, Match: domain.CacheRuleMatch{Models: []string{"gpt-4"}}, Action: domain.CacheActionRespect},
70
- }
71
-
72
- got := e.Evaluate(context.Background(), rules, domain.CacheEvalContext{Model: "gpt-4"})
73
- require.NotNil(t, got)
74
- assert.Equal(t, domain.CacheActionRespect, got.Action)
75
- assert.Equal(t, "cache-rule-42", got.RuleID)
76
- }
77
-
78
- // VKPrefix matcher — iter-110 root cause regression. The seed's
79
- // `disable-cache-evals` rule (vk_prefix=lw_vk_eval_) was matching every VK
80
- // because the wire DTO silently dropped the matcher and collapsed it to
81
- // "match all". Verify the matcher is honored: a rule gated on
82
- // vk_prefix=lw_vk_eval_ must NOT match a lw_vk_live_* matrix VK.
83
- func TestEvaluate_VKPrefix_NoMatch(t *testing.T) {
84
- e := NewEvaluator()
85
- rules := []domain.CacheRule{
86
- {ID: "disable-evals", Priority: 1, Match: domain.CacheRuleMatch{VKPrefixes: []string{"lw_vk_eval_"}}, Action: domain.CacheActionDisable},
87
- }
88
-
89
- got := e.Evaluate(context.Background(), rules, domain.CacheEvalContext{
90
- Model: "claude-sonnet-4-5",
91
- VKDisplayPrefix: "lw_vk_live_01KP",
92
- })
93
- assert.Nil(t, got, "lw_vk_live_* VK must not match a vk_prefix=lw_vk_eval_ rule")
94
- }
95
-
96
- func TestEvaluate_VKPrefix_Match(t *testing.T) {
97
- e := NewEvaluator()
98
- rules := []domain.CacheRule{
99
- {ID: "disable-evals", Priority: 1, Match: domain.CacheRuleMatch{VKPrefixes: []string{"lw_vk_eval_"}}, Action: domain.CacheActionDisable},
100
- }
101
-
102
- got := e.Evaluate(context.Background(), rules, domain.CacheEvalContext{
103
- Model: "claude-sonnet-4-5",
104
- VKDisplayPrefix: "lw_vk_eval_01KP",
105
- })
106
- require.NotNil(t, got)
107
- assert.Equal(t, domain.CacheActionDisable, got.Action)
108
- }
109
-
110
- // Empty VKDisplayPrefix on the eval context with a non-empty matcher
111
- // prefix must NOT match — fail-safe so wiring gaps don't accidentally
112
- // apply a vk_prefix rule to traffic the operator didn't intend.
113
- func TestEvaluate_VKPrefix_EmptyContext_NoMatch(t *testing.T) {
114
- e := NewEvaluator()
115
- rules := []domain.CacheRule{
116
- {ID: "disable-evals", Priority: 1, Match: domain.CacheRuleMatch{VKPrefixes: []string{"lw_vk_eval_"}}, Action: domain.CacheActionDisable},
117
- }
118
-
119
- got := e.Evaluate(context.Background(), rules, domain.CacheEvalContext{Model: "any"})
120
- assert.Nil(t, got, "missing VKDisplayPrefix in eval context must not match a vk_prefix rule")
121
- }
122
-
123
- // VKTag AND-semantics: rule with vk_tags=["enterprise"] must not match a
124
- // VK whose tag set lacks the tag. Empty VKTags on the bundle is the common
125
- // case (the schema doesn't carry tags yet).
126
- func TestEvaluate_VKTags_RequiredButMissing_NoMatch(t *testing.T) {
127
- e := NewEvaluator()
128
- rules := []domain.CacheRule{
129
- {ID: "force-enterprise", Priority: 1, Match: domain.CacheRuleMatch{VKTags: []string{"tier=enterprise"}}, Action: domain.CacheActionForce},
130
- }
131
-
132
- got := e.Evaluate(context.Background(), rules, domain.CacheEvalContext{
133
- Model: "claude-sonnet-4-5",
134
- VKDisplayPrefix: "lw_vk_live_01KP",
135
- // VKTags intentionally empty
136
- })
137
- assert.Nil(t, got, "rule gated on a tag the VK lacks must not match")
138
- }
139
-
140
- func TestEvaluate_VKTags_AllPresent_Match(t *testing.T) {
141
- e := NewEvaluator()
142
- rules := []domain.CacheRule{
143
- {ID: "force-enterprise", Priority: 1, Match: domain.CacheRuleMatch{VKTags: []string{"tier=enterprise"}}, Action: domain.CacheActionForce},
144
- }
145
-
146
- got := e.Evaluate(context.Background(), rules, domain.CacheEvalContext{
147
- Model: "claude-sonnet-4-5",
148
- VKTags: []string{"tier=enterprise", "stack=prod"},
149
- })
150
- require.NotNil(t, got)
151
- assert.Equal(t, domain.CacheActionForce, got.Action)
152
- }
153
-
154
- // AND across matcher kinds: model matches but vk_prefix doesn't ⇒ no match.
155
- func TestEvaluate_AndAcrossMatchers(t *testing.T) {
156
- e := NewEvaluator()
157
- rules := []domain.CacheRule{
158
- {
159
- ID: "scoped-disable",
160
- Priority: 1,
161
- Match: domain.CacheRuleMatch{
162
- Models: []string{"claude-*"},
163
- VKPrefixes: []string{"lw_vk_eval_"},
164
- },
165
- Action: domain.CacheActionDisable,
166
- },
167
- }
168
-
169
- got := e.Evaluate(context.Background(), rules, domain.CacheEvalContext{
170
- Model: "claude-sonnet-4-5",
171
- VKDisplayPrefix: "lw_vk_live_01KP",
172
- })
173
- assert.Nil(t, got, "model matches but vk_prefix doesn't — rule must not fire")
174
- }
175
-
176
- // Iter-110 end-to-end seed simulation: three rules emulating the dogfood
177
- // seed (force vk_tags / disable vk_prefix / respect haiku) — a lw_vk_live_*
178
- // matrix VK on claude-sonnet-4-5 should resolve to FORCE (not DISABLE),
179
- // because the disable rule's vk_prefix gate now actually filters.
180
- func TestEvaluate_IterDogfoodSeed_MatrixVK(t *testing.T) {
181
- e := NewEvaluator()
182
- rules := []domain.CacheRule{
183
- {
184
- ID: "force-cache-enterprise", Priority: 300,
185
- Match: domain.CacheRuleMatch{VKTags: []string{"tier=enterprise"}},
186
- Action: domain.CacheActionForce,
187
- },
188
- {
189
- ID: "disable-cache-evals", Priority: 200,
190
- Match: domain.CacheRuleMatch{VKPrefixes: []string{"lw_vk_eval_"}},
191
- Action: domain.CacheActionDisable,
192
- },
193
- {
194
- ID: "respect-on-haiku", Priority: 100,
195
- Match: domain.CacheRuleMatch{Models: []string{"claude-haiku-4-5-20251001"}},
196
- Action: domain.CacheActionRespect,
197
- },
198
- }
199
-
200
- matrixVK := domain.CacheEvalContext{
201
- Model: "claude-sonnet-4-5-20250929",
202
- VKID: "vk_1777027536276_matrix-anthropic",
203
- VKDisplayPrefix: "lw_vk_live_01KPZHGNCA",
204
- }
205
- got := e.Evaluate(context.Background(), rules, matrixVK)
206
- assert.Nil(t, got, "matrix-anthropic on sonnet matches no rule (haiku-only respect, eval-only disable, enterprise-only force) — cache_control on inbound body should pass through unchanged")
207
- }
@@ -1,40 +0,0 @@
1
- package controlplane
2
-
3
- import (
4
- "net/http"
5
- "testing"
6
- )
7
-
8
- // BenchmarkSign measures the canonical HMAC signing path used on every
9
- // internal gateway→control-plane call (resolve-key, config, budget/debit,
10
- // guardrail/check).
11
- func BenchmarkSign(b *testing.B) {
12
- s, err := NewSigner("shared-test-secret-32byteslong!!", "gw-bench")
13
- if err != nil {
14
- b.Fatal(err)
15
- }
16
- body := []byte(`{"key_presented":"lw_vk_live_01HZX0123456789ABCDEFGHIJ","gateway_node_id":"gw-bench"}`)
17
-
18
- b.ResetTimer()
19
- b.ReportAllocs()
20
- for i := 0; i < b.N; i++ {
21
- req, _ := http.NewRequest(http.MethodPost, "http://cp/api/internal/gateway/resolve-key", nil)
22
- s.Sign(req, body)
23
- }
24
- }
25
-
26
- // BenchmarkSign_EmptyBody stresses the GET path (FetchConfig /
27
- // WaitForChanges) where body is nil.
28
- func BenchmarkSign_EmptyBody(b *testing.B) {
29
- s, err := NewSigner("shared-test-secret-32byteslong!!", "gw-bench")
30
- if err != nil {
31
- b.Fatal(err)
32
- }
33
-
34
- b.ResetTimer()
35
- b.ReportAllocs()
36
- for i := 0; i < b.N; i++ {
37
- req, _ := http.NewRequest(http.MethodGet, "http://cp/api/internal/gateway/config/vk_01", nil)
38
- s.Sign(req, nil)
39
- }
40
- }
@@ -1,213 +0,0 @@
1
- // Package controlplane provides the unified HTTP client for all control plane RPCs.
2
- package controlplane
3
-
4
- import (
5
- "bytes"
6
- "context"
7
- "encoding/json"
8
- "fmt"
9
- "io"
10
- "net/http"
11
- "net/url"
12
- "time"
13
-
14
- "go.uber.org/zap"
15
-
16
- "github.com/langwatch/langwatch/pkg/herr"
17
- "github.com/langwatch/langwatch/pkg/jwtverify"
18
- "github.com/langwatch/langwatch/services/aigateway/domain"
19
- )
20
-
21
- // ClientOptions configures the control plane client.
22
- type ClientOptions struct {
23
- BaseURL string
24
- Sign func(req *http.Request, body []byte)
25
- Verifier *jwtverify.JWTVerifier
26
- HTTPClient *http.Client
27
- Logger *zap.Logger
28
- GuardrailTimeouts GuardrailTimeouts
29
- // UserAgent is the value sent in the User-Agent header on every outbound
30
- // request to the control plane. Typically "langwatch-aigateway/<version>".
31
- UserAgent string
32
- }
33
-
34
- // GuardrailTimeouts configures per-direction budgets for guardrail evaluation.
35
- type GuardrailTimeouts struct {
36
- Pre time.Duration
37
- Post time.Duration
38
- StreamChunk time.Duration
39
- }
40
-
41
- // Client calls the LangWatch control plane for key resolution, config fetching,
42
- // guardrail evaluation, and budget debit.
43
- type Client struct {
44
- baseURL string
45
- userAgent string
46
- sign func(req *http.Request, body []byte)
47
- verifier *jwtverify.JWTVerifier
48
- client *http.Client
49
- logger *zap.Logger
50
- guardrailTimeouts GuardrailTimeouts
51
- }
52
-
53
- // NewClient creates a control plane client with the given options.
54
- func NewClient(opts ClientOptions) *Client {
55
- if opts.HTTPClient == nil {
56
- opts.HTTPClient = &http.Client{
57
- Timeout: 10 * time.Second,
58
- Transport: &http.Transport{
59
- MaxIdleConnsPerHost: 100,
60
- IdleConnTimeout: 90 * time.Second,
61
- ForceAttemptHTTP2: true,
62
- },
63
- }
64
- }
65
- if opts.Logger == nil {
66
- opts.Logger = zap.NewNop()
67
- }
68
- if opts.GuardrailTimeouts.Pre == 0 {
69
- opts.GuardrailTimeouts.Pre = 5 * time.Second
70
- }
71
- if opts.GuardrailTimeouts.Post == 0 {
72
- opts.GuardrailTimeouts.Post = 5 * time.Second
73
- }
74
- if opts.GuardrailTimeouts.StreamChunk == 0 {
75
- opts.GuardrailTimeouts.StreamChunk = 50 * time.Millisecond
76
- }
77
- return &Client{
78
- baseURL: opts.BaseURL,
79
- userAgent: opts.UserAgent,
80
- sign: opts.Sign,
81
- verifier: opts.Verifier,
82
- client: opts.HTTPClient,
83
- logger: opts.Logger,
84
- guardrailTimeouts: opts.GuardrailTimeouts,
85
- }
86
- }
87
-
88
- // ResolveKey exchanges a raw virtual key for a domain.Bundle.
89
- func (c *Client) ResolveKey(ctx context.Context, rawKey string) (*domain.Bundle, error) {
90
- payload, _ := json.Marshal(map[string]string{"key_presented": rawKey})
91
- endpoint, _ := url.JoinPath(c.baseURL, "/api/internal/gateway/resolve-key")
92
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))
93
- if err != nil {
94
- return nil, herr.New(ctx, domain.ErrAuthUpstream, nil, err)
95
- }
96
- req.Header.Set("Content-Type", "application/json")
97
- c.setCommonHeaders(req)
98
- c.sign(req, payload)
99
-
100
- resp, err := c.client.Do(req)
101
- if err != nil {
102
- return nil, herr.New(ctx, domain.ErrAuthUpstream, nil, err)
103
- }
104
- defer func() { _ = resp.Body.Close() }()
105
- respBody, _ := io.ReadAll(resp.Body)
106
-
107
- switch {
108
- case resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusUnauthorized:
109
- return nil, herr.New(ctx, domain.ErrInvalidAPIKey, nil)
110
- case resp.StatusCode == http.StatusForbidden:
111
- return nil, herr.New(ctx, domain.ErrKeyRevoked, nil)
112
- case resp.StatusCode != http.StatusOK:
113
- return nil, herr.New(ctx, domain.ErrAuthUpstream, nil, fmt.Errorf("control plane returned %d", resp.StatusCode))
114
- }
115
-
116
- var result struct {
117
- Token string `json:"jwt"`
118
- }
119
- if err := json.Unmarshal(respBody, &result); err != nil {
120
- return nil, herr.New(ctx, domain.ErrAuthUpstream, nil, err)
121
- }
122
-
123
- mapClaims, err := c.verifier.Verify(result.Token)
124
- if err != nil {
125
- return nil, herr.New(ctx, domain.ErrAuthUpstream, nil, err)
126
- }
127
-
128
- return claimsToBundle(extractClaims(mapClaims)), nil
129
- }
130
-
131
- // FetchConfig retrieves the VK's full config from the control plane.
132
- func (c *Client) FetchConfig(ctx context.Context, vkID string) (domain.BundleConfig, error) {
133
- endpoint, _ := url.JoinPath(c.baseURL, "/api/internal/gateway/config", url.PathEscape(vkID))
134
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
135
- if err != nil {
136
- return domain.BundleConfig{}, err
137
- }
138
- c.setCommonHeaders(req)
139
- c.sign(req, nil)
140
-
141
- resp, err := c.client.Do(req)
142
- if err != nil {
143
- return domain.BundleConfig{}, err
144
- }
145
- defer func() { _ = resp.Body.Close() }()
146
- body, _ := io.ReadAll(resp.Body)
147
-
148
- if resp.StatusCode != http.StatusOK {
149
- return domain.BundleConfig{}, fmt.Errorf("config fetch returned %d", resp.StatusCode)
150
- }
151
-
152
- var wire configWire
153
- if err := json.Unmarshal(body, &wire); err != nil {
154
- return domain.BundleConfig{}, err
155
- }
156
- return wire.toDomain(), nil
157
- }
158
-
159
- // --- Internal helpers ---
160
-
161
- // Claims are the gateway-relevant fields extracted from a control-plane JWT.
162
- type Claims struct {
163
- VirtualKeyID string
164
- ProjectID string
165
- TeamID string
166
- ExpiresAt int64
167
- }
168
-
169
- func extractClaims(m map[string]any) *Claims {
170
- c := &Claims{}
171
- if v, ok := m["vk_id"].(string); ok {
172
- c.VirtualKeyID = v
173
- }
174
- if v, ok := m["project_id"].(string); ok {
175
- c.ProjectID = v
176
- }
177
- if v, ok := m["team_id"].(string); ok {
178
- c.TeamID = v
179
- }
180
- if v, ok := m["exp"].(float64); ok {
181
- c.ExpiresAt = int64(v)
182
- }
183
- return c
184
- }
185
-
186
- func claimsToBundle(c *Claims) *domain.Bundle {
187
- return &domain.Bundle{
188
- VirtualKeyID: c.VirtualKeyID,
189
- ProjectID: c.ProjectID,
190
- TeamID: c.TeamID,
191
- ExpiresAt: time.Unix(c.ExpiresAt, 0),
192
- }
193
- }
194
-
195
- // setCommonHeaders stamps headers shared by every outbound control-plane request.
196
- func (c *Client) setCommonHeaders(req *http.Request) {
197
- if c.userAgent != "" {
198
- req.Header.Set("User-Agent", c.userAgent)
199
- }
200
- }
201
-
202
- // signedPost is a helper for POST requests to the control plane.
203
- func (c *Client) signedPost(ctx context.Context, path string, body []byte) (*http.Response, error) {
204
- endpoint, _ := url.JoinPath(c.baseURL, path)
205
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
206
- if err != nil {
207
- return nil, err
208
- }
209
- req.Header.Set("Content-Type", "application/json")
210
- c.setCommonHeaders(req)
211
- c.sign(req, body)
212
- return c.client.Do(req)
213
- }
@@ -1,73 +0,0 @@
1
- package controlplane
2
-
3
- import (
4
- "context"
5
- "net/http"
6
- "net/http/httptest"
7
- "testing"
8
-
9
- "github.com/stretchr/testify/assert"
10
- "github.com/stretchr/testify/require"
11
-
12
- "github.com/langwatch/langwatch/pkg/jwtverify"
13
- )
14
-
15
- func TestFetchConfig_EscapesVKID(t *testing.T) {
16
- tests := []struct {
17
- name string
18
- vkID string
19
- wantURI string
20
- }{
21
- {
22
- name: "normal id",
23
- vkID: "vk-abc123",
24
- wantURI: "/api/internal/gateway/config/vk-abc123",
25
- },
26
- {
27
- name: "path traversal attempt",
28
- vkID: "../../admin/secrets",
29
- wantURI: "/api/internal/gateway/config/..%2F..%2Fadmin%2Fsecrets",
30
- },
31
- {
32
- name: "query injection attempt",
33
- vkID: "test?admin=1",
34
- wantURI: "/api/internal/gateway/config/test%3Fadmin=1",
35
- },
36
- {
37
- name: "fragment injection",
38
- vkID: "test#fragment",
39
- wantURI: "/api/internal/gateway/config/test%23fragment",
40
- },
41
- {
42
- name: "slashes in id",
43
- vkID: "a/b/c",
44
- wantURI: "/api/internal/gateway/config/a%2Fb%2Fc",
45
- },
46
- }
47
-
48
- for _, tt := range tests {
49
- t.Run(tt.name, func(t *testing.T) {
50
- var capturedURI string
51
- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
52
- capturedURI = r.RequestURI
53
- w.WriteHeader(http.StatusOK)
54
- _, _ = w.Write([]byte(`{}`))
55
- }))
56
- defer srv.Close()
57
-
58
- signer, err := NewSigner("test-secret", "node-1")
59
- require.NoError(t, err)
60
- verifier := jwtverify.NewJWTVerifier("jwt-secret", "")
61
- cp := NewClient(ClientOptions{
62
- BaseURL: srv.URL,
63
- Sign: signer.Sign,
64
- Verifier: verifier,
65
- HTTPClient: srv.Client(),
66
- })
67
-
68
- _, _ = cp.FetchConfig(context.Background(), tt.vkID)
69
-
70
- assert.Equal(t, tt.wantURI, capturedURI)
71
- })
72
- }
73
- }