Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,11 @@ func run() (exitStatus int) {
log.Errorf("failed to initialize postgres token store: %v", err)
return 1
}
defer func() {
if errClose := pgStoreInst.Close(); errClose != nil {
log.Warnf("failed to close postgres token store: %v", errClose)
}
}()
examplePath := filepath.Join(wd, "config.example.yaml")
ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
if errBootstrap := pgStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil {
Expand Down
7 changes: 7 additions & 0 deletions cmd/server/main_exit_other_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//go:build !unix

package main

import "os/exec"

func detachControllingTTY(_ *exec.Cmd) {}
1 change: 1 addition & 0 deletions cmd/server/main_exit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ func newServerExitCommand(t *testing.T, dir string, args ...string) (*exec.Cmd,
t.Cleanup(cancel)
cmdArgs := append([]string{"-test.run=^TestServerExitHelper$", "--"}, args...)
command := exec.CommandContext(ctx, os.Args[0], cmdArgs...)
detachControllingTTY(command)
command.Dir = dir
// Isolate from host store environment variables and prevent external network calls.
command.Env = append(os.Environ(),
Expand Down
20 changes: 20 additions & 0 deletions cmd/server/main_exit_unix_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//go:build unix

package main

import (
"os/exec"
"syscall"
)

// detachControllingTTY puts the child in a new session so Bubbletea cannot open
// the parent terminal's /dev/tty when tests expect a non-interactive failure.
func detachControllingTTY(cmd *exec.Cmd) {
if cmd == nil {
return
}
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
}
cmd.SysProcAttr.Setsid = true
}
19 changes: 17 additions & 2 deletions internal/auth/meta/meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,17 +199,32 @@ func (ts *MetaTokenStorage) SaveTokenToFile(authFilePath string) error {
if err != nil {
return fmt.Errorf("meta token storage: create token file: %w", err)
}
defer func() { _ = os.Remove(file.Name()) }()
tmpPath := file.Name()
cleanupTmp := true
defer func() {
if cleanupTmp {
_ = os.Remove(tmpPath)
}
}()
if errChmod := file.Chmod(0o600); errChmod != nil {
_ = file.Close()
return fmt.Errorf("meta token storage: chmod token file: %w", errChmod)
}
if _, errWrite := file.Write(append(raw, '\n')); errWrite != nil {
_ = file.Close()
return fmt.Errorf("meta token storage: write token file: %w", errWrite)
}
if errSync := file.Sync(); errSync != nil {
_ = file.Close()
return fmt.Errorf("meta token storage: sync token file: %w", errSync)
}
if errClose := file.Close(); errClose != nil {
return fmt.Errorf("meta token storage: close token file: %w", errClose)
}
if errRename := os.Rename(file.Name(), authFilePath); errRename != nil {
if errRename := os.Rename(tmpPath, authFilePath); errRename != nil {
return fmt.Errorf("meta token storage: replace token file: %w", errRename)
}
cleanupTmp = false

return nil
}
Expand Down
53 changes: 35 additions & 18 deletions internal/kvstore/bolt_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ func WithSweepBatchSize(batchSize int) BoltStoreOption {

// BoltStore implements KVClient backed by a local bbolt database file.
type BoltStore struct {
dbMu sync.RWMutex
closed bool
db *bbolt.DB
path string
nowFunc func() time.Time
Expand Down Expand Up @@ -171,6 +173,9 @@ func (s *BoltStore) Close() error {
s.closeOnce.Do(func() {
close(s.stopCh)
<-s.doneCh
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.closed = true
if s.db != nil {
s.closeErr = s.db.Close()
}
Expand All @@ -186,12 +191,22 @@ func (s *BoltStore) now() time.Time {
}

func (s *BoltStore) view(fn func(tx *bbolt.Tx, now time.Time) error) error {
s.dbMu.RLock()
defer s.dbMu.RUnlock()
if s.closed || s.db == nil {
return errStoreClosed
}
return s.db.View(func(tx *bbolt.Tx) error {
return fn(tx, s.now())
})
}

func (s *BoltStore) update(fn func(tx *bbolt.Tx, now time.Time) error) error {
s.dbMu.RLock()
defer s.dbMu.RUnlock()
if s.closed || s.db == nil {
return errStoreClosed
}
runner := s.db.Update
if s.runUpdate != nil {
runner = s.runUpdate
Expand Down Expand Up @@ -332,26 +347,28 @@ func (s *BoltStore) KVSet(ctx context.Context, key string, value []byte, opts KV
if b == nil {
return fmt.Errorf("kvstore: bucket not found")
}
var exists bool
if raw := b.Get(keyBytes); raw != nil {
_, _, expired, errDecode := decodeEnvelope(raw, nowNano)
if errDecode != nil {
return errDecode
}
if expired {
if errDel := b.Delete(keyBytes); errDel != nil {
return errDel
if opts.NX || opts.XX {
var exists bool
if raw := b.Get(keyBytes); raw != nil {
_, _, expired, errDecode := decodeEnvelope(raw, nowNano)
if errDecode != nil {
return errDecode
}
if expired {
if errDel := b.Delete(keyBytes); errDel != nil {
return errDel
}
exists = false
} else {
exists = true
}
exists = false
} else {
exists = true
}
}
if opts.NX && exists {
return nil
}
if opts.XX && !exists {
return nil
if opts.NX && exists {
return nil
}
if opts.XX && !exists {
return nil
}
}
if errPut := b.Put(keyBytes, encodeEnvelope(value, expiresAt)); errPut != nil {
return errPut
Expand Down
20 changes: 18 additions & 2 deletions internal/quotahistory/recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,11 +175,20 @@ func (r *Recorder) Apply(s Settings) error {
if s == r.settings && running == s.Enabled {
return nil
}
prevPath := r.settings.Path
r.stopLocked()
r.settings = s
r.providers.Store(s.Providers)
r.forgetUntracked(s.Enabled)
r.pluginIDs.Store(nil)
if !s.Enabled || s.Path != prevPath {
r.plansMu.Lock()
clear(r.plans)
clear(r.profileAttempts)
clear(r.customers)
clear(r.customerAttempts)
r.plansMu.Unlock()
}
if !s.Enabled {
return nil
}
Expand Down Expand Up @@ -265,8 +274,11 @@ func (r *Recorder) run(ctx context.Context, store *Store, s Settings) {

delay := r.startupDelay
if last := store.lastTime(); last > 0 {
if remaining := s.Interval - r.now().Sub(time.UnixMilli(last)); remaining > delay {
delay = remaining
elapsed := r.now().Sub(time.UnixMilli(last))
if elapsed >= 0 {
if remaining := s.Interval - elapsed; remaining > delay {
delay = remaining
}
}
}
timer := time.NewTimer(delay)
Expand Down Expand Up @@ -644,11 +656,15 @@ func (r *Recorder) History(since, until int64) (History, error) {
}
r.mu.Lock()
store, s := r.store, r.settings
if store != nil {
r.wg.Add(1)
}
r.mu.Unlock()
out.IntervalSeconds = int64(s.Interval / time.Second)
if store == nil {
return out, nil
}
defer r.wg.Done()
out.Enabled = true
if until <= 0 {
until = out.Now
Expand Down
13 changes: 11 additions & 2 deletions internal/quotahistory/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package quotahistory

import (
"fmt"
"math"
"path/filepath"
"sort"
"strconv"
Expand Down Expand Up @@ -116,10 +117,18 @@ func parseDuration(raw string) (time.Duration, bool) {
}
if days, found := strings.CutSuffix(raw, "d"); found {
n, errParse := strconv.ParseFloat(days, 64)
if errParse != nil || n <= 0 {
if errParse != nil || math.IsNaN(n) || math.IsInf(n, 0) || n <= 0 {
return 0, false
}
return time.Duration(n * float64(24*time.Hour)), true
const maxDays = float64(math.MaxInt64) / float64(24*time.Hour)
if n >= maxDays {
return 0, false
}
d := time.Duration(n * float64(24*time.Hour))
if d <= 0 {
return 0, false
}
return d, true
}
d, errParse := time.ParseDuration(raw)
if errParse != nil || d <= 0 {
Expand Down
4 changes: 2 additions & 2 deletions internal/quotahistory/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ func (s *Store) put(rec record) error {
func (s *Store) scan(since, until int64, fn func(record)) error {
return s.db.View(func(tx *bbolt.Tx) error {
c := tx.Bucket(samplesBucket).Cursor()
limit := timeKey(until + 1)
for k, v := c.Seek(timeKey(since)); k != nil && bytes.Compare(k[:min(8, len(k))], limit) < 0; k, v = c.Next() {
untilKey := timeKey(until)
for k, v := c.Seek(timeKey(since)); k != nil && bytes.Compare(k[:min(8, len(k))], untilKey) <= 0; k, v = c.Next() {
var rec record
if errUnmarshal := json.Unmarshal(v, &rec); errUnmarshal != nil {
continue
Expand Down
13 changes: 9 additions & 4 deletions internal/runtime/executor/codex_websockets_connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,11 @@ func frameCodexWebsocketRequestBody(body []byte) []byte {
if len(body) == 0 {
return nil
}
wsReqBody, errSet := ojson.SetBytes(body, "type", "response.create")
if errSet == nil && len(wsReqBody) > 0 {
return wsReqBody
doc := ojson.NewDoc(body)
if errSet := doc.Set("type", "response.create"); errSet == nil {
if wsReqBody := doc.Bytes(); len(wsReqBody) > 0 {
return wsReqBody
}
}
return body
}
Expand Down Expand Up @@ -302,7 +304,10 @@ func newProxyAwareWebsocketDialer(ctx context.Context, cfg *config.Config, auth
return dialer
}
dialer.Proxy = nil
dialer.NetDialContext = func(_ context.Context, network, addr string) (net.Conn, error) {
dialer.NetDialContext = func(dialCtx context.Context, network, addr string) (net.Conn, error) {
if ctxDialer, ok := socksDialer.(proxy.ContextDialer); ok {
return ctxDialer.DialContext(dialCtx, network, addr)
}
return socksDialer.Dial(network, addr)
}
case "http", "https":
Expand Down
18 changes: 14 additions & 4 deletions internal/store/gitstore.go
Original file line number Diff line number Diff line change
Expand Up @@ -707,14 +707,24 @@ func (s *GitTokenStore) guardWatcherAuthRemovalLocked(message string, relPaths [
}

func (s *GitTokenStore) resolveDeletePath(id string) (string, error) {
if strings.ContainsRune(id, os.PathSeparator) || filepath.IsAbs(id) {
return id, nil
}
dir := s.baseDirSnapshot()
if filepath.IsAbs(id) {
clean := filepath.Clean(id)
if dir != "" {
if rel, errRel := filepath.Rel(dir, clean); errRel != nil || isOutsideManagedDir(rel) {
return "", fmt.Errorf("git token store: path %s outside managed auth directory", id)
}
}
return clean, nil
}
if dir == "" {
return "", fmt.Errorf("auth filestore: directory not configured")
}
return filepath.Join(dir, id), nil
clean := filepath.Clean(filepath.FromSlash(id))
if isOutsideManagedDir(clean) {
return "", fmt.Errorf("git token store: invalid auth identifier %s", id)
}
return filepath.Join(dir, clean), nil
}

func (s *GitTokenStore) readAuthFile(path, baseDir string) (*cliproxyauth.Auth, error) {
Expand Down
14 changes: 11 additions & 3 deletions internal/store/object_refresh_journal.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ func (s *ObjectTokenStore) RefreshClaim(ctx context.Context, key string) (bool,
}

func (s *ObjectTokenStore) RefreshRead(ctx context.Context, key string) ([]byte, error) {
if s == nil || s.client == nil {
return nil, fmt.Errorf("object refresh journal is unavailable")
}
object, errGet := s.client.GetObject(ctx, s.cfg.Bucket, s.refreshObjectKey(key, "receipt"), minio.GetObjectOptions{})
if errGet != nil {
return nil, errGet
Expand All @@ -57,6 +60,9 @@ func (s *ObjectTokenStore) RefreshRead(ctx context.Context, key string) ([]byte,
}

func (s *ObjectTokenStore) RefreshComplete(ctx context.Context, key string, receipt []byte) error {
if s == nil || s.client == nil {
return fmt.Errorf("object refresh journal is unavailable")
}
s.refreshClaims.Delete(key)
created, errCreate := s.createRefreshObject(ctx, s.refreshObjectKey(key, "receipt"), receipt)
if errCreate != nil {
Expand Down Expand Up @@ -211,15 +217,17 @@ func (s *ObjectTokenStore) probeRefreshConditionalCreate(ctx context.Context) er
if errFirst != nil || !first {
return fmt.Errorf("refresh journal conditional-create probe failed: %v", errFirst)
}
defer func() {
if errRemove := s.client.RemoveObject(ctx, s.cfg.Bucket, key, minio.RemoveObjectOptions{}); errRemove != nil {
log.Warnf("remove refresh journal capability probe: %v", errRemove)
}
}()
second, errSecond := s.createRefreshObject(ctx, key, []byte("probe"))
if errSecond != nil {
return errSecond
}
if second {
return fmt.Errorf("object backend does not enforce conditional creation; refresh refused")
}
if errRemove := s.client.RemoveObject(ctx, s.cfg.Bucket, key, minio.RemoveObjectOptions{}); errRemove != nil {
log.Warnf("remove refresh journal capability probe: %v", errRemove)
}
return nil
}
Loading