Add authenticated Codex HTTP gateway and worker
Check Codex HTTP gateway / verify (push) Successful in 11m53s
Check Codex HTTP gateway / verify (push) Successful in 11m53s
This commit is contained in:
+226
@@ -0,0 +1,226 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const publicModel = "codex"
|
||||
|
||||
type keyHashes [][sha256.Size]byte
|
||||
|
||||
func loadKeys(path string) (keyHashes, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
var keys keyHashes
|
||||
scanner := bufio.NewScanner(file)
|
||||
scanner.Buffer(make([]byte, 256), 256)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
var key [sha256.Size]byte
|
||||
if len(line) != hex.EncodedLen(len(key)) || len(keys) == 256 {
|
||||
return nil, errors.New("expected at most 256 SHA-256 hex digests")
|
||||
}
|
||||
if _, err := hex.Decode(key[:], []byte(line)); err != nil {
|
||||
return nil, errors.New("invalid SHA-256 hex digest")
|
||||
}
|
||||
keys = append(keys, key)
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return nil, errors.New("at least one key hash is required")
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func (keys keyHashes) permits(r *http.Request) bool {
|
||||
values := r.Header.Values("Authorization")
|
||||
if len(values) != 1 {
|
||||
return false
|
||||
}
|
||||
scheme, token, ok := strings.Cut(values[0], " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") {
|
||||
return false
|
||||
}
|
||||
encoded, ok := strings.CutPrefix(token, "cgw_")
|
||||
if !ok || len(encoded) != 64 {
|
||||
return false
|
||||
}
|
||||
var raw [32]byte
|
||||
if _, err := hex.Decode(raw[:], []byte(encoded)); err != nil {
|
||||
return false
|
||||
}
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
var match int
|
||||
for _, key := range keys {
|
||||
match |= subtle.ConstantTimeCompare(key[:], digest[:])
|
||||
}
|
||||
return match == 1
|
||||
}
|
||||
|
||||
type message struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type chatRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []message `json:"messages"`
|
||||
Stream bool `json:"stream"`
|
||||
}
|
||||
|
||||
type usage struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
}
|
||||
|
||||
type workerResult struct {
|
||||
Text string `json:"text"`
|
||||
Usage *usage `json:"usage,omitempty"`
|
||||
}
|
||||
|
||||
type apiError struct {
|
||||
Message string `json:"message"`
|
||||
Type string `json:"type"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
type completionChoice struct {
|
||||
Index int `json:"index"`
|
||||
Message message `json:"message"`
|
||||
FinishReason string `json:"finish_reason"`
|
||||
}
|
||||
|
||||
type completion struct {
|
||||
ID string `json:"id"`
|
||||
Object string `json:"object"`
|
||||
Created int64 `json:"created"`
|
||||
Model string `json:"model"`
|
||||
Choices []completionChoice `json:"choices"`
|
||||
Usage *usage `json:"usage,omitempty"`
|
||||
}
|
||||
|
||||
func newGateway(keys keyHashes, execute func(context.Context, string) (workerResult, int)) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if r.URL.Path != "/v1/chat/completions" {
|
||||
writeError(w, http.StatusNotFound, "invalid_request_error", "not_found", "Endpoint not found.")
|
||||
return
|
||||
}
|
||||
if !keys.permits(r) {
|
||||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||||
writeError(w, http.StatusUnauthorized, "invalid_request_error", "invalid_api_key", "A valid gateway API key is required.")
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", http.MethodPost)
|
||||
writeError(w, http.StatusMethodNotAllowed, "invalid_request_error", "method_not_allowed", "Use POST for this endpoint.")
|
||||
return
|
||||
}
|
||||
var request chatRequest
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, requestLimit))
|
||||
decoder.DisallowUnknownFields()
|
||||
err := decoder.Decode(&request)
|
||||
if err == nil {
|
||||
if trailing := decoder.Decode(new(any)); trailing != io.EOF {
|
||||
err = errors.New("expected exactly one JSON object")
|
||||
var sizeError *http.MaxBytesError
|
||||
if errors.As(trailing, &sizeError) {
|
||||
err = sizeError
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
var sizeError *http.MaxBytesError
|
||||
if errors.As(err, &sizeError) {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, "invalid_request_error", "request_too_large", "Request exceeds 128 KiB.")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusBadRequest, "invalid_request_error", "invalid_request", "Send model, text messages and optionally stream=false.")
|
||||
return
|
||||
}
|
||||
if request.Model != publicModel || request.Stream || !validMessages(request.Messages) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request_error", "unsupported_request", "Use model=codex, stream=false and text messages ending in a user message.")
|
||||
return
|
||||
}
|
||||
transcript, _ := json.Marshal(request.Messages)
|
||||
prompt := "Answer the final user message in this JSON conversation. Use earlier messages as context. Return only the text response.\n" + string(transcript)
|
||||
result, status := execute(r.Context(), prompt)
|
||||
switch status {
|
||||
case http.StatusOK:
|
||||
writeJSON(w, status, completion{
|
||||
ID: "chatcmpl-" + rand.Text(), Object: "chat.completion", Created: time.Now().Unix(), Model: publicModel,
|
||||
Choices: []completionChoice{{Index: 0, Message: message{Role: "assistant", Content: result.Text}, FinishReason: "stop"}},
|
||||
Usage: result.Usage,
|
||||
})
|
||||
case http.StatusTooManyRequests:
|
||||
w.Header().Set("Retry-After", "5")
|
||||
writeError(w, status, "rate_limit_error", "worker_busy", "Codex is already handling a request. Retry shortly.")
|
||||
case http.StatusGatewayTimeout:
|
||||
writeError(w, status, "server_error", "worker_timeout", "Codex did not finish in time.")
|
||||
case http.StatusServiceUnavailable:
|
||||
writeError(w, status, "server_error", "worker_unavailable", "Codex is unavailable.")
|
||||
default:
|
||||
writeError(w, http.StatusBadGateway, "server_error", "worker_failed", "Codex did not return a completion.")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func validMessages(messages []message) bool {
|
||||
if len(messages) == 0 || len(messages) > 128 || messages[len(messages)-1].Role != "user" {
|
||||
return false
|
||||
}
|
||||
for _, message := range messages {
|
||||
switch message.Role {
|
||||
case "system", "developer", "user", "assistant":
|
||||
default:
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(message.Content) == "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, kind, code, description string) {
|
||||
writeJSON(w, status, map[string]apiError{"error": {Message: description, Type: kind, Code: code}})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func decodeWorkerResponse(r io.Reader) (workerResult, error) {
|
||||
var result workerResult
|
||||
decoder := json.NewDecoder(io.LimitReader(r, 6*outputLimit+4096))
|
||||
if err := decoder.Decode(&result); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if len(result.Text) > outputLimit || result.Text == "" || decoder.Decode(new(any)) != io.EOF {
|
||||
return result, errors.New("invalid worker result")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
Reference in New Issue
Block a user