58 lines
2.1 KiB
Go
58 lines
2.1 KiB
Go
package handlers_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"github.com/tradarr/backend/internal/api"
|
|
"github.com/tradarr/backend/internal/api/handlers"
|
|
"github.com/tradarr/backend/internal/auth"
|
|
"github.com/tradarr/backend/internal/config"
|
|
"github.com/tradarr/backend/internal/models"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
const generationHTTPSecret = "ticket-27-http-contract-secret"
|
|
|
|
type fakeJobStarter struct{ user string }
|
|
|
|
func (f *fakeJobStarter) Start(_ context.Context, user string) (models.GenerationJob, error) {
|
|
f.user = user
|
|
return models.GenerationJob{ID: "job-id", Status: "running"}, nil
|
|
}
|
|
func TestGenerateSummaryHTTPAcceptsJobUsingJWTUser(t *testing.T) {
|
|
h := handlers.New(nil, &config.Config{JWTSecret: generationHTTPSecret}, nil, nil, nil, nil)
|
|
starter := &fakeJobStarter{}
|
|
h.SetGenerationJobs(starter)
|
|
router := api.SetupRouter(h, generationHTTPSecret)
|
|
token, _ := auth.GenerateToken("jwt-owner", "owner@example.test", "user", generationHTTPSecret)
|
|
request := httptest.NewRequest(http.MethodPost, "/api/summaries/generate", strings.NewReader(`{"user_id":"attacker","content":"candidate-secret"}`))
|
|
request.Header.Set("Authorization", "Bearer "+token)
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, request)
|
|
if response.Code != 202 || starter.user != "jwt-owner" {
|
|
t.Fatalf("status=%d user=%s body=%s", response.Code, starter.user, response.Body)
|
|
}
|
|
if response.Header().Get("Location") != "/api/summaries/generation-jobs/job-id" {
|
|
t.Fatal("missing poll location")
|
|
}
|
|
var envelope struct {
|
|
Data models.GenerationJob `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(response.Body.Bytes(), &envelope); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if envelope.Data.Status != "running" || strings.Contains(response.Body.String(), "candidate-secret") {
|
|
t.Fatal(response.Body)
|
|
}
|
|
for _, path := range []string{"/api/summaries/generation-jobs/recent", "/api/summaries/generation-jobs/id"} {
|
|
response = httptest.NewRecorder()
|
|
router.ServeHTTP(response, httptest.NewRequest("GET", path, nil))
|
|
if response.Code != 401 {
|
|
t.Fatalf("%s: %d", path, response.Code)
|
|
}
|
|
}
|
|
}
|