fix: follow the current lease for questions and tools
14 files changed,
+556
−58
.rastrillo/budgets.txt+2 −1internal/equipo/copy.go+1 −1internal/equipo/questions.go+72 −15internal/equipo/questions_test.go+29 −0internal/equipotest/questions_fixes_test.go+77 −0internal/equipotest/questions_test.go+4 −1internal/runner/questions.go+21 −11internal/runner/questions_test.go+64 −6internal/runner/task13_fixes_test.go+182 −0internal/runner/tool_journal.go+9 −0internal/runner/tool_socket.go+61 −13internal/runner/tool_socket_test.go+19 −3internal/runner/tools.go+13 −6internal/runner/tools_test.go+2 −1
CI failed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 02af385b..8c4b732b 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -15,5 +15,6 @@ time internal/equipo/team 15s Copied core crash, recovery and concurrency tests |
| time internal/equipotest 25s Task 6 keeps the mandated connections tests in this package; its focused authority, isolation, atomic-write and real-session checks took 15.5s on the shared machine, above the prior 15s allowance. |
| size internal/equipo 7400 - Task 14 raises 7000 after adding the mandated runner adapters, validated durable receipt lookup and publication protocol routes beside the existing runner API (7087 lines). |
| -size internal/equipotest - 9100 Task 12 keeps runner_events_test.go beside the existing activation fixtures to verify crash replay, atomic settlement, epoch replacement, authority, HTTP ingestion and migration reopen. |
| +size internal/equipotest - 9400 Task 13 fix round 1 keeps question renewal and stale-answer batch regressions beside the existing activation fixtures (9169 test lines). |
| time internal/runner/checks 15s Task 11 runs real Go fixtures and Codex sandbox sentinels, including timeout and child-process cleanup; the targeted suite took 10.710s on the shared machine. |
| +time internal/runner 15s Task 13 fix round 1 tests renewed socket expiry, 128 durable pending submissions and the real tool binary; its focused suite took 10.015s on the shared machine. |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 34107e76..25eabe04 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -184,7 +184,7 @@ const CopyToolCandidate = "Submit a candidate commit for this task. Reuse the re |
| const CopyToolReview = "Submit a review of this task's candidate. Reuse the request ID only for an identical retry." |
| // COPY REVIEW REQUIRED: Task 13 tool description. |
| -const CopyToolReproduction = "Submit reproduction files and test names for this task. Encode file bytes as base64. Reuse the request ID only for an identical retry." |
| +const CopyToolReproduction = "Submit reproduction files and test names for this task. Encode file bytes as base64. The complete request must fit within 64 KiB. Reuse the request ID only for an identical retry." |
| func RunnerToolCopy() runner.ToolCopy { |
| return runner.ToolCopy{Accepted: CopyToolAccepted, Rejected: CopyToolRejected, Ask: CopyToolAsk, Candidate: CopyToolCandidate, Review: CopyToolReview, Reproduction: CopyToolReproduction} |
diff --git a/internal/equipo/questions.go b/internal/equipo/questions.go| index f3ec2321..194afd85 100644 |
| --- a/internal/equipo/questions.go |
| +++ b/internal/equipo/questions.go |
| @@ -52,6 +52,9 @@ func (e *Execution) recordQuestion(ctx context.Context, tx *gorm.DB, a runnerAss |
| if old.AssignmentID != a.ID || old.InputHash != hash { |
| return nil, ErrConflict |
| } |
| + if err := e.questionCurrent(ctx, tx, &old); err != nil { |
| + return nil, err |
| + } |
| return old.value() |
| } |
| if !errors.Is(err, gorm.ErrRecordNotFound) { |
| @@ -63,6 +66,9 @@ func (e *Execution) recordQuestion(ctx context.Context, tx *gorm.DB, a runnerAss |
| return nil, storeError(err) |
| } |
| row := questionRecord{ID: q.ID, TaskID: a.TaskID, AssignmentID: a.ID, ServerID: q.ServerID, AgentID: q.AgentID, SessionID: q.SessionID, PermissionID: q.PermissionID, Kind: q.Kind, Attempt: a.AttemptID, Fence: a.Fence, Revision: 1, RawRequest: string(q.RawRequest), InputHash: hash, State: "pending", ExpiresAt: a.LeaseDeadline} |
| + if err := e.questionCurrent(ctx, tx, &row); err != nil { |
| + return nil, err |
| + } |
| if err := tx.Create(&row).Error; err != nil { |
| return nil, storeError(err) |
| } |
| @@ -71,9 +77,9 @@ func (e *Execution) recordQuestion(ctx context.Context, tx *gorm.DB, a runnerAss |
| } |
| return row.value() |
| } |
| -func (e *Execution) questionCurrent(ctx context.Context, tx *gorm.DB, q questionRecord) error { |
| +func (e *Execution) questionCurrent(ctx context.Context, tx *gorm.DB, q *questionRecord) error { |
| now := e.store.runnerClock.Now() |
| - if (q.State != "pending" && q.State != "answered") || !now.Before(q.ExpiresAt) { |
| + if q.State != "pending" && q.State != "answered" { |
| return ErrConflict |
| } |
| var a runnerAssignment |
| @@ -93,7 +99,38 @@ func (e *Execution) questionCurrent(ctx context.Context, tx *gorm.DB, q question |
| if _, err := e.assignmentCurrent(ctx, tx, RunnerPrincipal{RunnerID: a.RunnerID, Person: a.Person, CredentialID: cred.ID}, a); err != nil { |
| return err |
| } |
| - return e.Core.ValidateHandle(ctx, team.Scope{Account: team.AccountID(a.TeamID), Job: team.JobID(a.JobID)}, team.Handle{Attempt: team.AttemptID(a.AttemptID), Fence: a.Fence, Runner: a.RunnerID}) |
| + scope := team.Scope{Account: team.AccountID(a.TeamID), Job: team.JobID(a.JobID)} |
| + if err := e.Core.ValidateHandle(ctx, scope, team.Handle{Attempt: team.AttemptID(a.AttemptID), Fence: a.Fence, Runner: a.RunnerID}); err != nil { |
| + return err |
| + } |
| + job, err := e.Core.GetJob(ctx, scope) |
| + if err != nil { |
| + return err |
| + } |
| + attempts, err := e.Core.Attempts(ctx, scope) |
| + if err != nil { |
| + return err |
| + } |
| + for _, attempt := range attempts { |
| + if int64(attempt.ID) != a.AttemptID { |
| + continue |
| + } |
| + if attempt.CreatedAt.IsZero() || job.Policy.AttemptSeconds <= 0 { |
| + return ErrConflict |
| + } |
| + q.ExpiresAt = attempt.CreatedAt.Add(time.Duration(job.Policy.AttemptSeconds) * time.Second) |
| + if a.LeaseDeadline.Before(q.ExpiresAt) { |
| + q.ExpiresAt = a.LeaseDeadline |
| + } |
| + if attempt.LeaseDeadline.Before(q.ExpiresAt) { |
| + q.ExpiresAt = attempt.LeaseDeadline |
| + } |
| + if !now.Before(q.ExpiresAt) { |
| + return ErrConflict |
| + } |
| + return nil |
| + } |
| + return ErrConflict |
| } |
| func (s *Store) AnswerQuestion(ctx context.Context, actor Actor, id string, revision int64, answer runnerproto.QuestionAnswer) error { |
| return s.answerQuestion(ctx, actor, "", id, revision, answer) |
| @@ -121,13 +158,13 @@ func (s *Store) answerQuestion(ctx context.Context, actor Actor, taskID, id stri |
| if err := tx.First(&task, "id=?", q.TaskID).Error; err != nil { |
| return storeError(err) |
| } |
| - if member.Address != task.Requester && member.Role != RoleOwner { |
| + if !questionAnswerAllowed(member, task) { |
| return ErrForbidden |
| } |
| if q.Revision != revision { |
| return ErrConflict |
| } |
| - if err := s.execution.questionCurrent(ctx, tx, q); err != nil { |
| + if err := s.execution.questionCurrent(ctx, tx, &q); err != nil { |
| return err |
| } |
| value, err := q.value() |
| @@ -137,11 +174,19 @@ func (s *Store) answerQuestion(ctx context.Context, actor Actor, taskID, id stri |
| if value.ValidateAnswer(answer) != nil { |
| return ErrInvalid |
| } |
| - raw, _ := json.Marshal(answer) |
| + raw, err := json.Marshal(answer) |
| + if err != nil { |
| + return ErrInvalid |
| + } |
| // Canonicalize opaque answers so object key order cannot create new effects. |
| var canonical any |
| - _ = json.Unmarshal(raw, &canonical) |
| - raw, _ = json.Marshal(canonical) |
| + if err := json.Unmarshal(raw, &canonical); err != nil { |
| + return ErrInvalid |
| + } |
| + raw, err = json.Marshal(canonical) |
| + if err != nil { |
| + return ErrInvalid |
| + } |
| if q.State == "answered" { |
| if q.Answer != string(raw) || q.AnsweredBy != member.Address { |
| return ErrConflict |
| @@ -164,19 +209,27 @@ func (e *Execution) questionAnswers(ctx context.Context, tx *gorm.DB, a runnerAs |
| } |
| out := []runnerproto.Question{} |
| for _, q := range rows { |
| - if !e.store.runnerClock.Now().Before(q.ExpiresAt) { |
| - continue |
| - } |
| - if err := e.questionCurrent(ctx, tx, q); err != nil { |
| + if err := e.questionCurrent(ctx, tx, &q); err != nil { |
| return nil, err |
| } |
| // An answerer's removal/demotion must also revoke an undelivered answer. |
| member, err := memberAt(tx, q.AnsweredBy) |
| - if err != nil { |
| + if err != nil && !errors.Is(err, ErrNotFound) { |
| return nil, err |
| } |
| - if !member.Active || (member.Address != a.Person && member.Role != RoleOwner) { |
| - return nil, ErrForbidden |
| + var task Task |
| + if err := tx.First(&task, "id=?", q.TaskID).Error; err != nil { |
| + return nil, storeError(err) |
| + } |
| + if errors.Is(err, ErrNotFound) || !questionAnswerAllowed(member, task) { |
| + q.State, q.Answer, q.AnsweredBy = "pending", "", "" |
| + if err := tx.Model(&questionRecord{}).Where("id=?", q.ID).Select("State", "Answer", "AnsweredBy").Updates(&q).Error; err != nil { |
| + return nil, storeError(err) |
| + } |
| + if err := appendAudit(tx, Actor{Address: a.Person}, "question.reopen", q.ID); err != nil { |
| + return nil, err |
| + } |
| + continue |
| } |
| v, err := q.value() |
| if err != nil { |
| @@ -230,3 +283,7 @@ func (e *Execution) resolveQuestion(ctx context.Context, tx *gorm.DB, a runnerAs |
| } |
| return appendAudit(tx, Actor{Address: a.Person}, "question.resolve", old.ID) |
| } |
| + |
| +func questionAnswerAllowed(member Member, task Task) bool { |
| + return member.Active && (member.Address == task.Requester || member.Role == RoleOwner) |
| +} |
diff --git a/internal/equipo/questions_test.go b/internal/equipo/questions_test.go| new file mode 100644 |
| index 00000000..4521031f |
| --- /dev/null |
| +++ b/internal/equipo/questions_test.go |
| @@ -0,0 +1,29 @@ |
| +package equipo |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestQuestionAnswerAuthority(t *testing.T) { |
| + task := Task{Requester: "requester@example.com"} |
| + for _, v := range []struct { |
| + member Member |
| + allowed bool |
| + }{ |
| + {Member{Address: task.Requester, Role: RoleMember, Active: true}, true}, |
| + {Member{Address: "assignment-person@example.com", Role: RoleMember, Active: true}, false}, |
| + {Member{Address: "owner@example.com", Role: RoleOwner, Active: true}, true}, |
| + {Member{Address: task.Requester, Role: RoleMember, Active: false}, false}, |
| + } { |
| + if questionAnswerAllowed(v.member, task) != v.allowed { |
| + t.Fatal("question authority must follow task requester or current owner", v) |
| + } |
| + } |
| +} |
| + |
| +func TestAgentToolFrameDescription(t *testing.T) { |
| + if !strings.Contains(RunnerToolCopy().Reproduction, "64 KiB") { |
| + t.Fatal("reproduction description omits frame limit") |
| + } |
| +} |
diff --git a/internal/equipotest/questions_fixes_test.go b/internal/equipotest/questions_fixes_test.go| new file mode 100644 |
| index 00000000..c4a3304b |
| --- /dev/null |
| +++ b/internal/equipotest/questions_fixes_test.go |
| @@ -0,0 +1,77 @@ |
| +package equipotest |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestQuestionRenewedLease(t *testing.T) { |
| + f, q := questionFixture(t) |
| + original := f.claim.LeaseDeadline |
| + f.clock.Advance(original.Sub(f.clock.Now()) / 2) |
| + r := f.request() |
| + r.RequestID = "renew-question" |
| + result, err := f.x.Mutate(connectionContext, f.principal, "renew", r) |
| + executionMust(t, err) |
| + renewed := result.(time.Time) |
| + f.clock.Advance(original.Sub(f.clock.Now()) + time.Millisecond) |
| + answer := runnerproto.QuestionAnswer{Behavior: "deny"} |
| + executionMust(t, f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, answer)) |
| + r.RequestID = "poll-renewed" |
| + result, err = f.x.Mutate(connectionContext, f.principal, "answers", r) |
| + executionMust(t, err) |
| + answers := result.([]runnerproto.Question) |
| + if len(answers) != 1 || !answers[0].ExpiresAt.Equal(renewed) { |
| + t.Fatal("poll did not return current lease bound", answers) |
| + } |
| + f.clock.Advance(renewed.Sub(f.clock.Now())) |
| + if f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, answer) == nil { |
| + t.Fatal("lost lease accepted answer") |
| + } |
| + if _, err = f.x.Mutate(connectionContext, f.principal, "answers", r); err == nil { |
| + t.Fatal("lost lease polled answer") |
| + } |
| +} |
| + |
| +func TestQuestionAttemptDeadline(t *testing.T) { |
| + f, q := questionFixture(t) |
| + mustSQL(t, f.d, "UPDATE attempts SET created_at=? WHERE id=?", f.clock.Now().Add(-24*time.Hour).Format(time.RFC3339Nano), f.claim.Handle.Attempt) |
| + if f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil { |
| + t.Fatal("attempt deadline ignored") |
| + } |
| +} |
| + |
| +func TestQuestionStaleAnswerDoesNotBlockPoll(t *testing.T) { |
| + for _, change := range []string{"demoted", "removed", "missing"} { |
| + t.Run(change, func(t *testing.T) { |
| + f, q := questionFixture(t) |
| + actor := equipo.Actor{Address: "answerer@example.com"} |
| + mustSQL(t, f.d, "INSERT INTO members(address,role,active,revision,session_epoch) VALUES(?,'owner',1,1,0)", actor.Address) |
| + executionMust(t, f.s.AnswerQuestion(connectionContext, actor, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "deny"})) |
| + // Seed a second answered row to exercise a poll batch with a stale first row. |
| + mustSQL(t, f.d, `INSERT INTO questions SELECT 'z-valid', assignment_id, task_id, server_id, agent_id, session_id, 'second-permission', kind, attempt, fence, revision, replace(raw_request,'permission','second-permission'), input_hash, state, answer, ?, expires_at FROM questions WHERE id=?`, ownerAddress, q.ID) |
| + switch change { |
| + case "demoted": |
| + mustSQL(t, f.d, "UPDATE members SET role='member' WHERE address=?", actor.Address) |
| + case "removed": |
| + mustSQL(t, f.d, "UPDATE members SET active=0 WHERE address=?", actor.Address) |
| + case "missing": |
| + mustSQL(t, f.d, "DELETE FROM members WHERE address=?", actor.Address) |
| + } |
| + r := f.request() |
| + r.RequestID = "poll-batch" |
| + result, err := f.x.Mutate(connectionContext, f.principal, "answers", r) |
| + executionMust(t, err) |
| + answers := result.([]runnerproto.Question) |
| + if len(answers) != 1 || answers[0].ID != "z-valid" { |
| + t.Fatal("stale row blocked valid answer", answers) |
| + } |
| + if scalar(t, f.d, "SELECT count(*) FROM questions WHERE id='question' AND state='pending' AND answer='' AND answered_by=''") != 1 { |
| + t.Fatal("stale answer not reopened") |
| + } |
| + executionMust(t, f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "deny"})) |
| + }) |
| + } |
| +} |
diff --git a/internal/equipotest/questions_test.go b/internal/equipotest/questions_test.go| index 3c3a02fa..4ae8fd39 100644 |
| --- a/internal/equipotest/questions_test.go |
| +++ b/internal/equipotest/questions_test.go |
| @@ -138,9 +138,12 @@ func TestQuestionCurrentOwnerAndPolling(t *testing.T) { |
| t.Fatal("owner answer unavailable") |
| } |
| mustSQL(t, f.d, "UPDATE members SET role='member' WHERE address=?", actor.Address) |
| - if _, err := f.x.Mutate(connectionContext, f.principal, "answers", r); err == nil { |
| + result, err = f.x.Mutate(connectionContext, f.principal, "answers", r) |
| + executionMust(t, err) |
| + if len(result.([]runnerproto.Question)) != 0 { |
| t.Fatal("demoted answerer polled") |
| } |
| + executionMust(t, f.s.AnswerQuestion(connectionContext, ownerActor, q.ID, 1, runnerproto.QuestionAnswer{Behavior: "deny"})) |
| if _, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "answers", r); err == nil { |
| t.Fatal("cleanup polled answers") |
| } |
diff --git a/internal/runner/questions.go b/internal/runner/questions.go| index 340bc6c8..7fd37fbf 100644 |
| --- a/internal/runner/questions.go |
| +++ b/internal/runner/questions.go |
| @@ -16,7 +16,7 @@ type QuestionClient interface { |
| } |
| func DeliverAnswer(ctx context.Context, client QuestionClient, agent paseo.Agent, q runnerproto.Question, answer runnerproto.QuestionAnswer) error { |
| - if client == nil || q.Validate() != nil || q.ValidateAnswer(answer) != nil || agent.ServerID != q.ServerID || agent.AgentID != q.AgentID || agent.ProviderSessionID != q.SessionID || (!q.ExpiresAt.IsZero() && !time.Now().Before(q.ExpiresAt)) { |
| + if client == nil || q.Validate() != nil || q.ValidateAnswer(answer) != nil || agent.ServerID != q.ServerID || agent.AgentID != q.AgentID || agent.ProviderSessionID != q.SessionID || (q.ExpiresAt.IsZero() || !time.Now().Before(q.ExpiresAt)) { |
| return runnerproto.ErrInvalid |
| } |
| return client.Respond(ctx, agent, paseo.PermissionResponse{RequestID: q.PermissionID, Behavior: answer.Behavior, UpdatedInput: answer.UpdatedInput}) |
| @@ -68,17 +68,20 @@ type QuestionRelay struct { |
| Journal *Journal |
| Client QuestionClient |
| Agent paseo.Agent |
| - Current func(context.Context, runnerproto.Question) error |
| + // Current returns the trusted current lease bound, capped by the attempt deadline. |
| + Current func(context.Context, runnerproto.Question) (time.Time, error) |
| } |
| func (r *QuestionRelay) Deliver(ctx context.Context, q runnerproto.Question, answer runnerproto.QuestionAnswer) error { |
| if r.Journal == nil || r.Client == nil || r.Current == nil || q.Attempt <= 0 || q.Fence <= 0 || q.ExpiresAt.IsZero() || q.Validate() != nil || q.ValidateAnswer(answer) != nil { |
| return runnerproto.ErrInvalid |
| } |
| - if err := r.Current(ctx, q); err != nil { |
| + var err error |
| + q.ExpiresAt, err = r.Current(ctx, q) |
| + if err != nil { |
| return err |
| } |
| - if !time.Now().Before(q.ExpiresAt) { |
| + if q.ExpiresAt.IsZero() || !time.Now().Before(q.ExpiresAt) { |
| return runnerproto.ErrInvalid |
| } |
| key := runnerproto.EventHash([]any{q.TaskID, q.Attempt, q.Fence, q.ServerID, q.AgentID, q.SessionID, q.PermissionID}) |
| @@ -116,7 +119,8 @@ func (r *QuestionRelay) Deliver(ctx context.Context, q runnerproto.Question, ans |
| if err = tx.Commit(); err != nil { |
| return r.Journal.fail() |
| } |
| - if err = r.Current(ctx, q); err != nil { |
| + q.ExpiresAt, err = r.Current(ctx, q) |
| + if err != nil { |
| return err |
| } |
| if err = DeliverAnswer(ctx, r.Client, r.Agent, q, answer); err != nil { |
| @@ -153,20 +157,26 @@ func (r *QuestionRelay) Wait(ctx context.Context, q runnerproto.Question, poll f |
| } |
| return cause |
| } |
| - ctx, cancel := context.WithDeadline(ctx, q.ExpiresAt) |
| - defer cancel() |
| timer := time.NewTimer(time.Until(q.ExpiresAt)) |
| defer timer.Stop() |
| tick := time.NewTicker(100 * time.Millisecond) |
| defer tick.Stop() |
| for { |
| - if err := r.Current(ctx, q); err != nil { |
| + deadline, err := r.Current(ctx, q) |
| + if err != nil { |
| return stop(err) |
| } |
| - if !time.Now().Before(q.ExpiresAt) { |
| + q.ExpiresAt = deadline |
| + if q.ExpiresAt.IsZero() || !time.Now().Before(q.ExpiresAt) { |
| return stop(runnerproto.ErrInvalid) |
| } |
| - answer, err := poll(ctx) |
| + timer.Reset(time.Until(q.ExpiresAt)) |
| + pollCtx, cancel := context.WithDeadline(ctx, q.ExpiresAt) |
| + answer, err := poll(pollCtx) |
| + cancel() |
| + if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil && !time.Now().Before(q.ExpiresAt) { |
| + continue |
| + } |
| if err != nil { |
| return stop(err) |
| } |
| @@ -180,7 +190,7 @@ func (r *QuestionRelay) Wait(ctx context.Context, q runnerproto.Question, poll f |
| case <-ctx.Done(): |
| return stop(ctx.Err()) |
| case <-timer.C: |
| - return stop(runnerproto.ErrInvalid) |
| + // Recheck trusted renewal before treating the prior bound as expired. |
| case <-tick.C: |
| } |
| } |
diff --git a/internal/runner/questions_test.go b/internal/runner/questions_test.go| index 8826d776..8ade8f73 100644 |
| --- a/internal/runner/questions_test.go |
| +++ b/internal/runner/questions_test.go |
| @@ -27,6 +27,7 @@ func (c *answerClient) Send(_ context.Context, _ paseo.Agent, _, _ string) error |
| func TestQuestionPermissionID(t *testing.T) { |
| a := paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} |
| q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "original", Kind: "question", Revision: 1, RawRequest: json.RawMessage(`{"id":"original","kind":"question","provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?","header":"Which?"}]}}`)} |
| + q.ExpiresAt = time.Now().Add(time.Minute) |
| c := &answerClient{} |
| answer := runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"Which?":"Yes"}}`)} |
| if err := DeliverAnswer(context.Background(), c, a, q, answer); err != nil { |
| @@ -70,11 +71,11 @@ func TestQuestionDeliveryReplay(t *testing.T) { |
| q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "original", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(time.Minute), RawRequest: json.RawMessage(`{"id":"original","kind":"question","provider":"claude","name":"AskUserQuestion","input":{"questions":[{"question":"Which?"}]}}`)} |
| c := &answerClient{} |
| current := true |
| - relay := QuestionRelay{Journal: j, Client: c, Agent: paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) error { |
| + relay := QuestionRelay{Journal: j, Client: c, Agent: paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) (time.Time, error) { |
| if !current { |
| - return runnerproto.ErrInvalid |
| + return time.Time{}, runnerproto.ErrInvalid |
| } |
| - return nil |
| + return q.ExpiresAt, nil |
| }} |
| answer := runnerproto.QuestionAnswer{Behavior: "deny"} |
| mustJournal(t, relay.Deliver(context.Background(), q, answer)) |
| @@ -120,7 +121,7 @@ func TestQuestionExpiredWaitContains(t *testing.T) { |
| defer j.Close() |
| q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(-time.Second), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} |
| c := &answerClient{} |
| - r := QuestionRelay{Journal: j, Client: c, Agent: paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) error { return nil }} |
| + r := QuestionRelay{Journal: j, Client: c, Agent: paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return q.ExpiresAt, nil }} |
| contained := 0 |
| if r.Wait(context.Background(), q, func(context.Context) (*runnerproto.QuestionAnswer, error) { |
| t.Fatal("polled expired wait") |
| @@ -146,7 +147,7 @@ func TestQuestionUncertainDelivery(t *testing.T) { |
| mustJournal(t, err) |
| q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(time.Minute), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} |
| c := &uncertainAnswerClient{} |
| - r := QuestionRelay{Journal: j, Client: c, Agent: paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) error { return nil }} |
| + r := QuestionRelay{Journal: j, Client: c, Agent: paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return q.ExpiresAt, nil }} |
| if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil { |
| t.Fatal("lost response treated as delivered") |
| } |
| @@ -196,8 +197,9 @@ func TestQuestionDeliveryBindingAndExpiry(t *testing.T) { |
| q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} |
| a := paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} |
| answer := runnerproto.QuestionAnswer{Behavior: "deny"} |
| - for _, field := range []string{"server", "agent", "session", "expiry"} { |
| + for _, field := range []string{"server", "agent", "session", "expiry", "zero_expiry"} { |
| bad := q |
| + bad.ExpiresAt = time.Now().Add(time.Minute) |
| switch field { |
| case "server": |
| bad.ServerID = "other" |
| @@ -205,6 +207,8 @@ func TestQuestionDeliveryBindingAndExpiry(t *testing.T) { |
| bad.AgentID = "other" |
| case "session": |
| bad.SessionID = "other" |
| + case "zero_expiry": |
| + bad.ExpiresAt = time.Time{} |
| case "expiry": |
| bad.ExpiresAt = time.Now().Add(-time.Second) |
| } |
| @@ -213,3 +217,57 @@ func TestQuestionDeliveryBindingAndExpiry(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func TestQuestionWaitRenewedLease(t *testing.T) { |
| + j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(-time.Second), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} |
| + c := &answerClient{} |
| + live := time.Now().Add(time.Minute) |
| + r := QuestionRelay{Journal: j, Client: c, Agent: paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}} |
| + // The supervisor has renewed the lease before the earlier bound expired. |
| + r.Current = func(context.Context, runnerproto.Question) (time.Time, error) { return live, nil } |
| + contained := 0 |
| + mustJournal(t, r.Wait(context.Background(), q, func(context.Context) (*runnerproto.QuestionAnswer, error) { |
| + return &runnerproto.QuestionAnswer{Behavior: "deny"}, nil |
| + }, func(context.Context) error { contained++; return nil })) |
| + if len(c.responses) != 1 || contained != 0 { |
| + t.Fatal("renewed wait lost answer") |
| + } |
| + live = time.Now().Add(-time.Second) |
| + if r.Wait(context.Background(), q, func(context.Context) (*runnerproto.QuestionAnswer, error) { |
| + t.Fatal("polled lost lease") |
| + return nil, nil |
| + }, func(context.Context) error { contained++; return nil }) == nil || contained != 1 { |
| + t.Fatal("lost wait not contained") |
| + } |
| + live = time.Now().Add(time.Minute) |
| + if r.Deliver(context.Background(), q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil || len(c.responses) != 1 { |
| + t.Fatal("lost permission revived") |
| + } |
| +} |
| + |
| +func TestQuestionWaitRenewedDuringPoll(t *testing.T) { |
| + j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + q := runnerproto.Question{ID: "q", TaskID: "task", ServerID: "server", AgentID: "agent", SessionID: "session", PermissionID: "p", Kind: "question", Attempt: 1, Fence: 1, Revision: 1, ExpiresAt: time.Now().Add(200 * time.Millisecond), RawRequest: json.RawMessage(`{"id":"p","kind":"question"}`)} |
| + bound := q.ExpiresAt |
| + c := &answerClient{} |
| + r := QuestionRelay{Journal: j, Client: c, Agent: paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"}, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return bound, nil }} |
| + polls := 0 |
| + err = r.Wait(context.Background(), q, func(ctx context.Context) (*runnerproto.QuestionAnswer, error) { |
| + polls++ |
| + if polls == 1 { |
| + bound = bound.Add(time.Second) |
| + <-ctx.Done() |
| + return nil, ctx.Err() |
| + } |
| + return &runnerproto.QuestionAnswer{Behavior: "deny"}, nil |
| + }, func(context.Context) error { t.Error("renewal during poll contained live wait"); return nil }) |
| + mustJournal(t, err) |
| + if len(c.responses) != 1 { |
| + t.Fatal("renewal during poll lost answer") |
| + } |
| +} |
diff --git a/internal/runner/task13_fixes_test.go b/internal/runner/task13_fixes_test.go| new file mode 100644 |
| index 00000000..615d7fbc |
| --- /dev/null |
| +++ b/internal/runner/task13_fixes_test.go |
| @@ -0,0 +1,182 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func toolRequestFixture(s *AttemptSocket, b ToolBinding) toolRequest { |
| + return toolRequest{Capability: s.capability.Secret, InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, RequestID: "round1", Name: "ask_person", Arguments: json.RawMessage(`{"question":"Which?"}`)} |
| +} |
| + |
| +func TestToolSocketRenewedLease(t *testing.T) { |
| + base, b := toolFixture(t) |
| + b.LeaseDeadline = time.Now().Add(300 * time.Millisecond) |
| + root := filepath.Dir(filepath.Dir(filepath.Dir(base.SocketPath))) |
| + s, err := NewAttemptSocket(context.Background(), root, b) |
| + mustJournal(t, err) |
| + defer s.Cleanup(context.Background(), func(context.Context) error { return nil }) |
| + renewal, ok := any(s).(interface { |
| + RenewLease(context.Context, time.Time) error |
| + }) |
| + if !ok { |
| + t.Fatal("socket has no trusted lease renewal") |
| + } |
| + deadline := time.Now().Add(time.Second) |
| + mustJournal(t, renewal.RenewLease(context.Background(), deadline)) |
| + mustJournal(t, renewal.RenewLease(context.Background(), b.LeaseDeadline)) |
| + time.Sleep(time.Until(b.LeaseDeadline) + 50*time.Millisecond) |
| + input := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}` + "\n" + |
| + `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ask_person","arguments":{"request_id":"renewed","question":"Which?"}}}` + "\n" |
| + var out strings.Builder |
| + mustJournal(t, ServeTools(context.Background(), strings.NewReader(input), &out, s.SocketPath, s.CapabilityPath)) |
| + if strings.Contains(out.String(), `"error"`) { |
| + t.Fatal("renewed lease tool failed", out.String()) |
| + } |
| + rows, err := b.Journal.ToolSubmissions(context.Background(), 10) |
| + mustJournal(t, err) |
| + if len(rows) != 1 { |
| + t.Fatal("renewed lease lost submission") |
| + } |
| + select { |
| + case <-s.done: |
| + t.Fatal("renewal did not extend timer") |
| + default: |
| + } |
| + select { |
| + case <-s.done: |
| + case <-time.After(time.Until(deadline) + time.Second): |
| + t.Fatal("lost lease did not invalidate idle socket") |
| + } |
| + if renewal.RenewLease(context.Background(), time.Now().Add(time.Minute)) == nil { |
| + t.Fatal("lost lease revived") |
| + } |
| + if callToolSocket(context.Background(), s.SocketPath, toolRequestFixture(s, b)) == nil { |
| + t.Fatal("lost lease accepted tool") |
| + } |
| +} |
| + |
| +func TestToolSocketUnauthenticatedCannotInvalidate(t *testing.T) { |
| + s, b := toolFixture(t) |
| + calls := 0 |
| + s.mu.Lock() |
| + s.binding.Current = func(context.Context) error { calls++; return runnerproto.ErrInvalid } |
| + s.mu.Unlock() |
| + q := toolRequestFixture(s, b) |
| + q.Capability = "wrong" |
| + if callToolSocket(context.Background(), s.SocketPath, q) == nil { |
| + t.Fatal("unauthenticated call accepted") |
| + } |
| + s.mu.Lock() |
| + invalid := s.invalid |
| + checked := calls |
| + s.binding.Current = func(context.Context) error { return nil } |
| + s.mu.Unlock() |
| + if invalid || checked != 0 { |
| + t.Fatal("unauthenticated frame checked authority or closed socket") |
| + } |
| + q.Capability = s.capability.Secret |
| + mustJournal(t, callToolSocket(context.Background(), s.SocketPath, q)) |
| +} |
| + |
| +func TestAgentToolJournalCapacity(t *testing.T) { |
| + s, b := toolFixture(t) |
| + q := toolRequestFixture(s, b) |
| + b.Journal.maxBytes = 1 |
| + if s.submit(context.Background(), q) == nil { |
| + t.Fatal("full journal accepted tool") |
| + } |
| + mustJournal(t, b.Journal.AdmissionAllowed(context.Background())) |
| + b.Journal.maxBytes = 128 << 20 |
| + mustJournal(t, s.submit(context.Background(), q)) |
| +} |
| + |
| +func TestAgentToolAttemptCapacity(t *testing.T) { |
| + s, b := toolFixture(t) |
| + q := toolRequestFixture(s, b) |
| + for i := 0; i < 128; i++ { |
| + q.RequestID = fmt.Sprint(i) |
| + mustJournal(t, s.submit(context.Background(), q)) |
| + } |
| + q.RequestID = "overflow" |
| + if s.submit(context.Background(), q) == nil { |
| + t.Fatal("attempt exhausted shared journal without a cap") |
| + } |
| + mustJournal(t, b.Journal.AdmissionAllowed(context.Background())) |
| + b.TaskID = "other-task" |
| + other, err := NewAttemptSocket(context.Background(), filepath.Dir(filepath.Dir(filepath.Dir(s.SocketPath))), b) |
| + mustJournal(t, err) |
| + defer other.Cleanup(context.Background(), func(context.Context) error { return nil }) |
| + mustJournal(t, other.submit(context.Background(), toolRequestFixture(other, b))) |
| + rows, err := b.Journal.ToolSubmissions(context.Background(), 1024) |
| + mustJournal(t, err) |
| + mustJournal(t, b.Journal.AckTool(context.Background(), rows[0])) |
| + mustJournal(t, s.submit(context.Background(), q)) |
| +} |
| + |
| +func TestAgentToolReproductionFields(t *testing.T) { |
| + good := runnerproto.Reproduction{ExpectedSymptom: "wrong value", Files: []runnerproto.CheckFile{{Path: "sub/bug_test.go", Bytes: []byte("test")}}, TestNames: []team.TestIdentity{{Package: "fixture", Name: "TestBug"}}} |
| + for _, field := range []string{"valid", "package", "name", "nested_git"} { |
| + t.Run(field, func(t *testing.T) { |
| + v := good |
| + v.Files = append([]runnerproto.CheckFile(nil), good.Files...) |
| + v.TestNames = append([]team.TestIdentity(nil), good.TestNames...) |
| + switch field { |
| + case "package": |
| + v.TestNames[0].Package = "" |
| + case "name": |
| + v.TestNames[0].Name = "" |
| + case "nested_git": |
| + v.Files[0].Path = "sub/.git/config" |
| + } |
| + raw, err := json.Marshal(v) |
| + mustJournal(t, err) |
| + err = validateToolArguments("submit_reproduction", raw) |
| + if field == "valid" { |
| + mustJournal(t, err) |
| + } else if err == nil { |
| + t.Fatal("invalid reproduction accepted", field) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestToolSocketCapabilityEncodingFailure(t *testing.T) { |
| + s, b := toolFixture(t) |
| + root := filepath.Dir(filepath.Dir(filepath.Dir(s.SocketPath))) |
| + dir := filepath.Join(root, "encoding-failure") |
| + mustJournal(t, os.Mkdir(dir, 0700)) |
| + b.LeaseDeadline = time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC) |
| + bad, err := ServeAttemptSocket(context.Background(), filepath.Join(dir, "tool.sock"), b) |
| + if err == nil { |
| + bad.Cleanup(context.Background(), func(context.Context) error { return nil }) |
| + t.Fatal("unencodable capability published") |
| + } |
| + entries, err := os.ReadDir(dir) |
| + mustJournal(t, err) |
| + if len(entries) != 0 { |
| + t.Fatal("encoding failure left authority files") |
| + } |
| +} |
| + |
| +func TestAgentToolAttemptByteCapacity(t *testing.T) { |
| + s, b := toolFixture(t) |
| + b.Journal.maxBytes = 8192 |
| + q := toolRequestFixture(s, b) |
| + q.Arguments = json.RawMessage(`{"question":"` + strings.Repeat("x", 2048) + `"}`) |
| + if s.submit(context.Background(), q) == nil { |
| + t.Fatal("attempt exceeded its byte share") |
| + } |
| + mustJournal(t, b.Journal.AdmissionAllowed(context.Background())) |
| + q.Arguments = json.RawMessage(`{"question":"Which?"}`) |
| + mustJournal(t, s.submit(context.Background(), q)) |
| +} |
diff --git a/internal/runner/tool_journal.go b/internal/runner/tool_journal.go| index 1d90be77..7cf9aaff 100644 |
| --- a/internal/runner/tool_journal.go |
| +++ b/internal/runner/tool_journal.go |
| @@ -52,9 +52,18 @@ func (j *Journal) appendTool(ctx context.Context, v ToolSubmission, inputHash st |
| return j.fail() |
| } |
| if size+int64(len(raw)) > j.maxBytes { |
| + return ErrJournal |
| + } |
| + var pending, attemptBytes int64 |
| + if err = tx.QueryRowContext(ctx, `SELECT count(*), COALESCE(SUM(length(body)),0) FROM journal_tools WHERE acked=0 |
| + AND json_extract(body,'$.instance_id')=? AND json_extract(body,'$.task_id')=? |
| + AND json_extract(body,'$.attempt')=? AND json_extract(body,'$.fence')=?`, v.InstanceID, v.TaskID, v.Attempt, v.Fence).Scan(&pending, &attemptBytes); err != nil { |
| tx.Rollback() |
| return j.fail() |
| } |
| + if pending >= 128 || attemptBytes+int64(len(raw)) > j.maxBytes/4 { |
| + return ErrJournal |
| + } |
| if _, err = tx.ExecContext(ctx, "INSERT INTO journal_tools(request_key,content_hash,body,acked) VALUES(?,?,?,0)", key, hash, raw); err != nil { |
| tx.Rollback() |
| return j.fail() |
diff --git a/internal/runner/tool_socket.go b/internal/runner/tool_socket.go| index 217c4c04..0b825ae1 100644 |
| --- a/internal/runner/tool_socket.go |
| +++ b/internal/runner/tool_socket.go |
| @@ -34,7 +34,7 @@ type ToolBinding struct { |
| Agent paseo.Agent |
| Isolation team.IsolationSnapshot |
| Journal *Journal |
| - // Current must revalidate the captured lease, fence, agent/session and trusted |
| + // Current must revalidate the current lease, fence, agent/session and trusted |
| // read policy. Failure permanently invalidates this socket, even if renewed. |
| Current func(context.Context) error |
| } |
| @@ -66,6 +66,7 @@ type AttemptSocket struct { |
| mu sync.Mutex |
| invalid bool |
| done chan struct{} |
| + renewed chan struct{} |
| workers sync.WaitGroup |
| } |
| @@ -138,7 +139,7 @@ func ServeAttemptSocket(ctx context.Context, path string, b ToolBinding) (*Attem |
| } |
| defer parent.Close() |
| b.Tools = slices.Clone(b.Tools) |
| - s := &AttemptSocket{SocketPath: path, CapabilityPath: filepath.Join(filepath.Dir(path), "capability.json"), binding: b, done: make(chan struct{})} |
| + s := &AttemptSocket{SocketPath: path, CapabilityPath: filepath.Join(filepath.Dir(path), "capability.json"), binding: b, done: make(chan struct{}), renewed: make(chan struct{}, 1)} |
| s.capability = toolCapability{Copy: b.Copy, Secret: rand.Text() + rand.Text(), InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Tools: b.Tools, ExpiresAt: b.LeaseDeadline} |
| // Never overwrite an old socket or capability: restart needs a fresh directory. |
| if _, err := os.Lstat(path); !os.IsNotExist(err) { |
| @@ -163,7 +164,11 @@ func ServeAttemptSocket(ctx context.Context, path string, b ToolBinding) (*Attem |
| } |
| tempPath := temp.Name() |
| defer os.Remove(tempPath) |
| - raw, _ := json.Marshal(s.capability) |
| + raw, err := json.Marshal(s.capability) |
| + if err != nil { |
| + temp.Close() |
| + return fail() |
| + } |
| if _, err = temp.Write(raw); err != nil { |
| temp.Close() |
| return fail() |
| @@ -189,16 +194,58 @@ func ServeAttemptSocket(ctx context.Context, path string, b ToolBinding) (*Attem |
| defer s.workers.Done() |
| timer := time.NewTimer(time.Until(b.LeaseDeadline)) |
| defer timer.Stop() |
| - select { |
| - case <-ctx.Done(): |
| - s.Invalidate() |
| - case <-timer.C: |
| - s.Invalidate() |
| - case <-s.done: |
| + for { |
| + select { |
| + case <-ctx.Done(): |
| + s.Invalidate() |
| + return |
| + case <-s.done: |
| + return |
| + case <-timer.C: |
| + case <-s.renewed: |
| + } |
| + s.mu.Lock() |
| + remaining := time.Until(s.binding.LeaseDeadline) |
| + if remaining <= 0 { |
| + s.invalidateLocked() |
| + } |
| + invalid := s.invalid |
| + s.mu.Unlock() |
| + if invalid { |
| + return |
| + } |
| + timer.Reset(remaining) |
| } |
| }() |
| return s, nil |
| } |
| + |
| +// RenewLease accepts a trusted supervisor's renewed monotonic deadline. |
| +// It cannot revive a lost lease or change the attempt, fence or capability. |
| +func (s *AttemptSocket) RenewLease(ctx context.Context, deadline time.Time) error { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + if s.invalid || !time.Now().Before(s.binding.LeaseDeadline) { |
| + s.invalidateLocked() |
| + return runnerproto.ErrInvalid |
| + } |
| + if err := s.binding.Current(ctx); err != nil { |
| + s.invalidateLocked() |
| + return err |
| + } |
| + if deadline.IsZero() || !time.Now().Before(deadline) { |
| + return runnerproto.ErrInvalid |
| + } |
| + if deadline.After(s.binding.LeaseDeadline) { |
| + s.binding.LeaseDeadline = deadline |
| + select { |
| + case s.renewed <- struct{}{}: |
| + default: |
| + } |
| + } |
| + return nil |
| +} |
| + |
| func (s *AttemptSocket) Invalidate() { s.mu.Lock(); defer s.mu.Unlock(); s.invalidateLocked() } |
| func (s *AttemptSocket) invalidateLocked() { |
| if !s.invalid { |
| @@ -273,6 +320,9 @@ func (s *AttemptSocket) submit(ctx context.Context, q toolRequest) error { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| b := s.binding |
| + if subtle.ConstantTimeCompare([]byte(q.Capability), []byte(s.capability.Secret)) != 1 || q.InstanceID != b.InstanceID || q.TaskID != b.TaskID || q.Attempt != b.Attempt || q.Fence != b.Fence || !slices.Contains(b.Tools, q.Name) || q.RequestID == "" || len(q.RequestID) > 256 { |
| + return runnerproto.ErrInvalid |
| + } |
| if s.invalid || !time.Now().Before(b.LeaseDeadline) { |
| s.invalidateLocked() |
| return runnerproto.ErrInvalid |
| @@ -281,9 +331,7 @@ func (s *AttemptSocket) submit(ctx context.Context, q toolRequest) error { |
| s.invalidateLocked() |
| return err |
| } |
| - if subtle.ConstantTimeCompare([]byte(q.Capability), []byte(s.capability.Secret)) != 1 || q.InstanceID != b.InstanceID || q.TaskID != b.TaskID || q.Attempt != b.Attempt || q.Fence != b.Fence || !slices.Contains(b.Tools, q.Name) || q.RequestID == "" || len(q.RequestID) > 256 { |
| - return runnerproto.ErrInvalid |
| - } |
| + |
| if err := validateToolArguments(q.Name, q.Arguments); err != nil { |
| return err |
| } |
| @@ -384,7 +432,7 @@ func readToolCapability(path string) (toolCapability, error) { |
| if !privateInfo(f, 0600, false) { |
| return cap, runnerproto.ErrInvalid |
| } |
| - if runnerproto.DecodeLimit(io.LimitReader(f, 8193), &cap, 8192) != nil || len(cap.Secret) < 32 || !time.Now().Before(cap.ExpiresAt) { |
| + if runnerproto.DecodeLimit(io.LimitReader(f, 8193), &cap, 8192) != nil || len(cap.Secret) < 32 { |
| return toolCapability{}, runnerproto.ErrInvalid |
| } |
| return cap, nil |
diff --git a/internal/runner/tool_socket_test.go b/internal/runner/tool_socket_test.go| index 7f4162f2..bded586c 100644 |
| --- a/internal/runner/tool_socket_test.go |
| +++ b/internal/runner/tool_socket_test.go |
| @@ -190,6 +190,22 @@ func TestAgentToolJournalReopen(t *testing.T) { |
| t.Fatal("ACK before durable request") |
| } |
| mustJournal(t, j.AckTool(context.Background(), rows[0])) |
| + saved := rows[0] |
| + mustJournal(t, j.Close()) |
| + j, err = OpenJournal(context.Background(), b.Journal.path) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + changed := saved |
| + changed.Arguments = json.RawMessage(`{"commit":"` + strings.Repeat("b", 40) + `"}`) |
| + if j.appendTool(context.Background(), changed, runnerproto.EventHash(changed.Arguments)) == nil { |
| + t.Fatal("changed replay accepted after ACK and reopen") |
| + } |
| + var effects int |
| + mustJournal(t, j.db.QueryRow("SELECT count(*) FROM journal_tools").Scan(&effects)) |
| + if effects != 1 { |
| + t.Fatal("changed replay duplicated effect") |
| + } |
| + |
| mustJournal(t, j.appendTool(context.Background(), rows[0], runnerproto.EventHash(json.RawMessage(q.Arguments)))) |
| rows, err = j.ToolSubmissions(context.Background(), 10) |
| mustJournal(t, err) |
| @@ -268,14 +284,14 @@ func TestToolSocketPublicStateAndStorageFailure(t *testing.T) { |
| } |
| } |
| -func TestToolSocketExpiredCapabilityFile(t *testing.T) { |
| +func TestToolSocketStaleCapabilityFile(t *testing.T) { |
| s, _ := toolFixture(t) |
| cap, err := readToolCapability(s.CapabilityPath) |
| mustJournal(t, err) |
| cap.ExpiresAt = time.Now().Add(-time.Second) |
| raw, _ := json.Marshal(cap) |
| mustJournal(t, os.WriteFile(s.CapabilityPath, raw, 0600)) |
| - if _, err := readToolCapability(s.CapabilityPath); err == nil { |
| - t.Fatal("expired capability file accepted") |
| + if _, err := readToolCapability(s.CapabilityPath); err != nil { |
| + t.Fatal("stale file expiry overrode trusted socket lease") |
| } |
| } |
diff --git a/internal/runner/tools.go b/internal/runner/tools.go| index f902a786..915388fb 100644 |
| --- a/internal/runner/tools.go |
| +++ b/internal/runner/tools.go |
| @@ -67,9 +67,14 @@ func validateToolArguments(name string, raw json.RawMessage) error { |
| if decode(&v) != nil || strings.TrimSpace(v.ExpectedSymptom) == "" || len(v.ExpectedSymptom) > 8192 || len(v.Files) == 0 || len(v.Files) > 32 || len(v.TestNames) == 0 { |
| return runnerproto.ErrInvalid |
| } |
| + for _, test := range v.TestNames { |
| + if strings.TrimSpace(test.Package) == "" || strings.TrimSpace(test.Name) == "" || !utf8.ValidString(test.Package) || !utf8.ValidString(test.Name) { |
| + return runnerproto.ErrInvalid |
| + } |
| + } |
| seen := map[string]bool{} |
| for _, f := range v.Files { |
| - if f.Path == "" || filepath.IsAbs(f.Path) || filepath.Clean(f.Path) != f.Path || strings.HasPrefix(f.Path, "../") || f.Path == ".." || strings.Contains(f.Path, "\\") || strings.HasPrefix(f.Path, ".git/") || f.Path == ".git" || seen[f.Path] || len(f.Bytes) == 0 { |
| + if f.Path == "" || filepath.IsAbs(f.Path) || filepath.Clean(f.Path) != f.Path || strings.HasPrefix(f.Path, "../") || f.Path == ".." || strings.Contains(f.Path, "\\") || slices.Contains(strings.Split(f.Path, "/"), ".git") || seen[f.Path] || len(f.Bytes) == 0 { |
| return runnerproto.ErrInvalid |
| } |
| seen[f.Path] = true |
| @@ -119,10 +124,7 @@ func ServeTools(ctx context.Context, input io.Reader, output io.Writer, socketPa |
| return runnerproto.ErrInvalid |
| } |
| if len(q.ID) == 0 { |
| - if q.Method == "notifications/initialized" && initialized { |
| - continue |
| - } |
| - return runnerproto.ErrInvalid |
| + continue |
| } |
| var id any |
| if json.Unmarshal(q.ID, &id) != nil { |
| @@ -169,6 +171,7 @@ func ServeTools(ctx context.Context, input io.Reader, output io.Writer, socketPa |
| } |
| var params struct { |
| Name string `json:"name"` |
| + Meta json.RawMessage `json:"_meta,omitempty"` |
| Arguments map[string]json.RawMessage `json:"arguments"` |
| } |
| if runnerproto.DecodeLimit(bytes.NewReader(q.Params), ¶ms, maxToolFrame) != nil || !slices.Contains(cap.Tools, params.Name) { |
| @@ -181,7 +184,11 @@ func ServeTools(ctx context.Context, input io.Reader, output io.Writer, socketPa |
| break |
| } |
| delete(params.Arguments, "request_id") |
| - args, _ := json.Marshal(params.Arguments) |
| + args, encodeErr := json.Marshal(params.Arguments) |
| + if encodeErr != nil { |
| + err = runnerproto.ErrInvalid |
| + break |
| + } |
| if err = validateToolArguments(params.Name, args); err != nil { |
| break |
| } |
diff --git a/internal/runner/tools_test.go b/internal/runner/tools_test.go| index b95b0dcc..559f57da 100644 |
| --- a/internal/runner/tools_test.go |
| +++ b/internal/runner/tools_test.go |
| @@ -66,8 +66,9 @@ func TestToolVerbUnderFakeHarness(t *testing.T) { |
| } |
| rpc(1, "initialize", map[string]any{"protocolVersion": "2024-11-05", "capabilities": map[string]any{}, "clientInfo": map[string]any{"name": "fake", "version": "1"}}) |
| mustJournal(t, enc.Encode(map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized"})) |
| + mustJournal(t, enc.Encode(map[string]any{"jsonrpc": "2.0", "method": "notifications/cancelled", "params": map[string]any{"requestId": 99}})) |
| rpc(2, "tools/list", map[string]any{}) |
| - rpc(3, "tools/call", map[string]any{"name": "ask_person", "arguments": map[string]any{"request_id": "harness-1", "question": "Which colour?"}}) |
| + rpc(3, "tools/call", map[string]any{"name": "ask_person", "_meta": map[string]any{"progressToken": "progress"}, "arguments": map[string]any{"request_id": "harness-1", "question": "Which colour?"}}) |
| in.Close() |
| mustJournal(t, cmd.Wait()) |
| if strings.Contains(logs.String(), cap.Secret) { |