154 lines
4.9 KiB
Go
154 lines
4.9 KiB
Go
// 公开文本生成代理:用项目专属凭据授权后,把受限任务通过 Unix IPC 转发给 worker。
|
||
package codex
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"crypto/sha256"
|
||
"crypto/subtle"
|
||
"encoding/hex"
|
||
"encoding/json"
|
||
"errors"
|
||
"io"
|
||
"net"
|
||
"net/http"
|
||
"os"
|
||
"strings"
|
||
"time"
|
||
)
|
||
|
||
// 公开请求 32 KiB、返回 512 KiB;worker 执行期限九十秒,IPC 客户端另留两秒收尾。
|
||
const (
|
||
maxRequest = 32 << 10
|
||
maxOutput = 512 << 10
|
||
timeout = 90 * time.Second
|
||
)
|
||
|
||
// task 仅允许 prompt,公开调用方不能传 sandbox、工具配置或可执行参数。
|
||
type task struct {
|
||
Prompt string `json:"prompt"`
|
||
}
|
||
|
||
// writeJSON 统一输出 JSON 并禁用缓存,内部调用者须在此之前完成状态码选择。
|
||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.Header().Set("Cache-Control", "no-store")
|
||
w.WriteHeader(status)
|
||
_ = json.NewEncoder(w).Encode(value)
|
||
}
|
||
|
||
// fail 将依赖或授权失败转换为稳定错误码,避免向公开 API 泄露本地路径和配置。
|
||
func fail(w http.ResponseWriter, status int, code string) {
|
||
writeJSON(w, status, map[string]string{"error": code})
|
||
}
|
||
|
||
// readTask 限制 JSON 大小、未知字段、尾随值与空白 prompt;失败时已写响应。
|
||
func readTask(w http.ResponseWriter, r *http.Request, limit int64) (task, bool) {
|
||
var input task
|
||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit))
|
||
decoder.DisallowUnknownFields()
|
||
err := decoder.Decode(&input)
|
||
if err == nil {
|
||
err = decoder.Decode(new(any))
|
||
if err == io.EOF && strings.TrimSpace(input.Prompt) != "" {
|
||
return input, true
|
||
}
|
||
}
|
||
var tooLarge *http.MaxBytesError
|
||
if errors.As(err, &tooLarge) {
|
||
fail(w, 413, "request_too_large")
|
||
} else {
|
||
fail(w, 400, "invalid_task")
|
||
}
|
||
return task{}, false
|
||
}
|
||
|
||
// Register enables the public endpoint only when both configuration files are supplied.
|
||
// Each credential digest belongs to exactly one project.
|
||
// Register 在两项配置齐备时挂载路由,凭据文件每次请求重新读取以支持撤销。
|
||
func Register(mux *http.ServeMux, projects map[string]string, socket, grantsFile string) error {
|
||
if socket == "" && grantsFile == "" {
|
||
return nil
|
||
}
|
||
if socket == "" || grantsFile == "" {
|
||
return errors.New("Codex requires both a socket and a grants file")
|
||
}
|
||
transport := &http.Transport{
|
||
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
|
||
},
|
||
DisableKeepAlives: true,
|
||
}
|
||
client := &http.Client{
|
||
Transport: transport,
|
||
Timeout: timeout + 2*time.Second,
|
||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||
}
|
||
mux.HandleFunc("POST /projects/{project}/codex/exec", func(w http.ResponseWriter, r *http.Request) {
|
||
scheme, token, _ := strings.Cut(r.Header.Get("Authorization"), " ")
|
||
key, err := hex.DecodeString(token)
|
||
if !strings.EqualFold(scheme, "Bearer") || err != nil || len(key) != 32 {
|
||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||
fail(w, 401, "unauthorized")
|
||
return
|
||
}
|
||
data, err := os.ReadFile(grantsFile)
|
||
var grants map[string]string
|
||
if err != nil || json.Unmarshal(data, &grants) != nil {
|
||
fail(w, 503, "codex_unavailable")
|
||
return
|
||
}
|
||
// 凭据是 32 字节十六进制值;将摘要与授权表恒定时间比较,再核对目标项目作用域。
|
||
hash := sha256.Sum256(key)
|
||
var scope string
|
||
for digest, project := range grants {
|
||
value, err := hex.DecodeString(digest)
|
||
if err == nil && subtle.ConstantTimeCompare(hash[:], value) == 1 {
|
||
scope = project
|
||
}
|
||
}
|
||
if scope == "" {
|
||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||
fail(w, 401, "unauthorized")
|
||
return
|
||
}
|
||
project := r.PathValue("project")
|
||
if _, exists := projects[project]; !exists || scope != project {
|
||
fail(w, 403, "forbidden")
|
||
return
|
||
}
|
||
input, ok := readTask(w, r, maxRequest)
|
||
if !ok {
|
||
return
|
||
}
|
||
// IPC 只发送解析后的任务体,不转发公开 Authorization 头;连接目的地固定为配置的 socket。
|
||
body, _ := json.Marshal(input)
|
||
req, err := http.NewRequestWithContext(r.Context(), http.MethodPost, "http://codex/exec", bytes.NewReader(body))
|
||
if err != nil {
|
||
fail(w, 502, "codex_unavailable")
|
||
return
|
||
}
|
||
resp, err := client.Do(req)
|
||
if err != nil {
|
||
if errors.Is(err, context.DeadlineExceeded) {
|
||
fail(w, 504, "codex_timeout")
|
||
} else {
|
||
fail(w, 502, "codex_unavailable")
|
||
}
|
||
return
|
||
}
|
||
defer resp.Body.Close()
|
||
// worker 响应必须在预算内且为合法 JSON;保留其状态与 Retry-After,隐藏传输错误细节。
|
||
data, err = io.ReadAll(io.LimitReader(resp.Body, maxOutput+1))
|
||
if err != nil || len(data) > maxOutput || !json.Valid(data) {
|
||
fail(w, 502, "invalid_codex_response")
|
||
return
|
||
}
|
||
if retry := resp.Header.Get("Retry-After"); retry != "" {
|
||
w.Header().Set("Retry-After", retry)
|
||
}
|
||
writeJSON(w, resp.StatusCode, json.RawMessage(data))
|
||
})
|
||
return nil
|
||
}
|