Add a secure repository Prompts review surface and prompt metadata API
Hop-State: A_06FN6MRSHG4B64ZV13086G8 Hop-Proposal: R_06FN6MQDE14FFNR65H1D28G Hop-Task: T_06FN6J8ECE1Z9XQ5PQ3Z3D8 Hop-Attempt: AT_06FN6J8ECC1SC794JMZ0TF8
This commit is contained in:
@@ -21,6 +21,7 @@ const maxWebhookBody = 2 << 20
|
||||
|
||||
type giteaClient interface {
|
||||
Repository(context.Context, string, string) (gitea.Repository, error)
|
||||
ViewerCanReadRepository(context.Context, string, string, string) (bool, error)
|
||||
}
|
||||
|
||||
type server struct {
|
||||
@@ -38,10 +39,90 @@ func New(data store.Store, client giteaClient, adminToken, webhookSecret string,
|
||||
mux.HandleFunc("GET /readyz", s.ready)
|
||||
mux.Handle("GET /api/v1/repositories", s.requireAdmin(http.HandlerFunc(s.listRepositories)))
|
||||
mux.Handle("POST /api/v1/repositories/link", s.requireAdmin(http.HandlerFunc(s.linkRepository)))
|
||||
mux.Handle("GET /api/v1/prompts", http.HandlerFunc(s.listPrompts))
|
||||
mux.Handle("POST /api/v1/repositories/{owner}/{name}/prompts", s.requireAdmin(http.HandlerFunc(s.createPrompt)))
|
||||
mux.HandleFunc("POST /api/v1/gitea/webhooks", s.giteaWebhook)
|
||||
return requestLogger(logger, mux)
|
||||
}
|
||||
|
||||
func (s *server) listPrompts(w http.ResponseWriter, r *http.Request) {
|
||||
owner, name := strings.TrimSpace(r.URL.Query().Get("owner")), strings.TrimSpace(r.URL.Query().Get("repo"))
|
||||
if !validSlug(owner) || !validSlug(name) {
|
||||
writeError(w, http.StatusBadRequest, "owner and repo are required")
|
||||
return
|
||||
}
|
||||
allowed, err := s.gitea.ViewerCanReadRepository(r.Context(), r.Header.Get("Cookie"), owner, name)
|
||||
if err != nil {
|
||||
s.logger.Error("check prompt viewer access", "owner", owner, "name", name, "error", err)
|
||||
writeError(w, http.StatusBadGateway, "could not verify repository access")
|
||||
return
|
||||
}
|
||||
if !allowed {
|
||||
writeError(w, http.StatusUnauthorized, "sign in to view this repository's prompts")
|
||||
return
|
||||
}
|
||||
prompts, err := s.store.ListPrompts(r.Context(), owner, name, 100)
|
||||
if err != nil {
|
||||
s.logger.Error("list prompts", "owner", owner, "name", name, "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "could not list prompts")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"prompts": prompts})
|
||||
}
|
||||
|
||||
func (s *server) createPrompt(w http.ResponseWriter, r *http.Request) {
|
||||
owner, name := r.PathValue("owner"), r.PathValue("name")
|
||||
if !validSlug(owner) || !validSlug(name) {
|
||||
writeError(w, http.StatusBadRequest, "owner and name are required")
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
TaskID string `json:"task_id"`
|
||||
AttemptID string `json:"attempt_id"`
|
||||
StateID string `json:"state_id"`
|
||||
Prompt string `json:"prompt"`
|
||||
AgentName string `json:"agent_name"`
|
||||
AgentModel string `json:"agent_model"`
|
||||
Status string `json:"status"`
|
||||
ResponseSummary string `json:"response_summary"`
|
||||
Metadata json.RawMessage `json:"metadata"`
|
||||
CompletedAt *time.Time `json:"completed_at"`
|
||||
}
|
||||
if err := decodeJSON(w, r, &input); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
input.Prompt = strings.TrimSpace(input.Prompt)
|
||||
if input.Prompt == "" || len(input.Prompt) > 32<<10 {
|
||||
writeError(w, http.StatusBadRequest, "prompt is required and must be at most 32 KiB")
|
||||
return
|
||||
}
|
||||
if input.Status == "" {
|
||||
input.Status = "running"
|
||||
}
|
||||
switch input.Status {
|
||||
case "running", "completed", "failed", "cancelled":
|
||||
default:
|
||||
writeError(w, http.StatusBadRequest, "invalid prompt status")
|
||||
return
|
||||
}
|
||||
if len(input.Metadata) > 16<<10 || (len(input.Metadata) > 0 && !json.Valid(input.Metadata)) {
|
||||
writeError(w, http.StatusBadRequest, "metadata must be valid JSON and at most 16 KiB")
|
||||
return
|
||||
}
|
||||
saved, err := s.store.CreatePrompt(r.Context(), store.CreatePromptInput{
|
||||
Owner: owner, Repository: name, TaskID: input.TaskID, AttemptID: input.AttemptID, StateID: input.StateID,
|
||||
Prompt: input.Prompt, AgentName: input.AgentName, AgentModel: input.AgentModel, Status: input.Status,
|
||||
ResponseSummary: input.ResponseSummary, Metadata: input.Metadata, CompletedAt: input.CompletedAt,
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.Error("create prompt", "owner", owner, "name", name, "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "could not create prompt")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, saved)
|
||||
}
|
||||
|
||||
func (s *server) health(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
|
||||
type fakeStore struct {
|
||||
repositories []store.Repository
|
||||
prompts []store.Prompt
|
||||
delivery store.WebhookDelivery
|
||||
duplicate bool
|
||||
}
|
||||
@@ -32,19 +33,31 @@ func (f *fakeStore) UpsertRepository(_ context.Context, repository gitea.Reposit
|
||||
f.repositories = append(f.repositories, saved)
|
||||
return saved, nil
|
||||
}
|
||||
func (f *fakeStore) ListPrompts(context.Context, string, string, int) ([]store.Prompt, error) {
|
||||
return f.prompts, nil
|
||||
}
|
||||
func (f *fakeStore) CreatePrompt(_ context.Context, input store.CreatePromptInput) (store.Prompt, error) {
|
||||
prompt := store.Prompt{ID: "PM_TEST", Prompt: input.Prompt, Status: input.Status, AgentName: input.AgentName, AgentModel: input.AgentModel, Metadata: input.Metadata}
|
||||
f.prompts = append(f.prompts, prompt)
|
||||
return prompt, nil
|
||||
}
|
||||
func (f *fakeStore) RecordWebhook(_ context.Context, delivery store.WebhookDelivery) (bool, error) {
|
||||
f.delivery = delivery
|
||||
return f.duplicate, nil
|
||||
}
|
||||
|
||||
type fakeGitea struct {
|
||||
repository gitea.Repository
|
||||
err error
|
||||
repository gitea.Repository
|
||||
err error
|
||||
viewerAllowed bool
|
||||
}
|
||||
|
||||
func (f fakeGitea) Repository(context.Context, string, string) (gitea.Repository, error) {
|
||||
return f.repository, f.err
|
||||
}
|
||||
func (f fakeGitea) ViewerCanReadRepository(context.Context, string, string, string) (bool, error) {
|
||||
return f.viewerAllowed, f.err
|
||||
}
|
||||
|
||||
func testServer(data store.Store, client giteaClient) http.Handler {
|
||||
return New(data, client, "admin-secret", "webhook-secret", slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
@@ -114,3 +127,43 @@ func TestWebhookRejectsInvalidSignature(t *testing.T) {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPromptsRequiresGiteaSession(t *testing.T) {
|
||||
data := &fakeStore{prompts: []store.Prompt{{ID: "PM_TEST", Prompt: "Ship the prompt view", Status: "completed"}}}
|
||||
handler := testServer(data, fakeGitea{viewerAllowed: true})
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/prompts?owner=hop&repo=demo", nil)
|
||||
req.Header.Set("Cookie", "i_like_gitea=session")
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, req)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d; body=%s", response.Code, http.StatusOK, response.Body.String())
|
||||
}
|
||||
if !bytes.Contains(response.Body.Bytes(), []byte("Ship the prompt view")) {
|
||||
t.Fatalf("prompt missing from response: %s", response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPromptsRejectsUnauthenticatedViewer(t *testing.T) {
|
||||
handler := testServer(&fakeStore{}, fakeGitea{})
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/prompts?owner=hop&repo=demo", nil)
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, req)
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want %d; body=%s", response.Code, http.StatusUnauthorized, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatePrompt(t *testing.T) {
|
||||
data := &fakeStore{}
|
||||
handler := testServer(data, fakeGitea{})
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/repositories/hop/demo/prompts", bytes.NewBufferString(`{"prompt":"Ship the prompt view","agent_name":"codex","status":"completed","metadata":{"duration_ms":1200}}`))
|
||||
req.Header.Set("Authorization", "Bearer admin-secret")
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, req)
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("status = %d, want %d; body=%s", response.Code, http.StatusCreated, response.Body.String())
|
||||
}
|
||||
if len(data.prompts) != 1 || data.prompts[0].Prompt != "Ship the prompt view" {
|
||||
t.Fatalf("prompt not created: %#v", data.prompts)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user