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
12 changes: 12 additions & 0 deletions cmd/server/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,15 @@ func TestNotFound(t *testing.T) {
t.Fatalf("got status %d, want 404", rec.Code)
}
}

func TestInvalidVideoID(t *testing.T) {
t.Parallel()
h := newTestHandler(t)
req := httptest.NewRequest(http.MethodGet, "/favicon.png", nil)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)

if rec.Code != http.StatusBadRequest {
t.Fatalf("got status %d, want 400", rec.Code)
}
}
7 changes: 5 additions & 2 deletions internal/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"html/template"
"log/slog"
"net/http"
"regexp"
"strings"

yt "github.com/shanehull/yt-transcript"
Expand Down Expand Up @@ -132,6 +133,8 @@ type pageData struct {
Version string
}

var videoIDRe = regexp.MustCompile(`^[A-Za-z0-9_-]{11}$`)

var indexPage = template.Must(template.New("index").Parse(indexHTML))

// Healthz returns a 200 OK status for health checks.
Expand Down Expand Up @@ -160,8 +163,8 @@ func Index(baseURL, version string) http.Handler {
func Transcript(client *yt.Client, transcriptCache *cache.Cache) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
videoID := r.PathValue("video_id")
if videoID == "" {
writeError(w, http.StatusBadRequest, "missing video_id")
if videoID == "" || !videoIDRe.MatchString(videoID) {
writeError(w, http.StatusBadRequest, "invalid video_id")
return
}

Expand Down