| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "html" |
| 8 | "io" |
| 9 | "mime" |
| 10 | "net/http" |
| 11 | "regexp" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 15 | "amadan.net/rastrillo/rastrillo/carlos" |
| 16 | "amadan.net/rastrillo/rastrillo/clientip" |
| 17 | "amadan.net/rastrillo/rastrillo/csrf" |
| 18 | "github.com/go-chi/chi/v5" |
| 19 | ) |
| 20 | |
| 21 | const previewCookie = "__Host-equipo-preview-" |
| 22 | |
| 23 | var previewTaskID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`) |
| 24 | var previewCandidate = regexp.MustCompile(`^[0-9a-f]{40}$`) |
| 25 | |
| 26 | func previewIP(r *http.Request) string { |
| 27 | hops := 0 |
| 28 | if carlos.Running() { |
| 29 | hops = clientip.DefaultHops |
| 30 | } |
| 31 | return clientip.From(r, hops) |
| 32 | } |
| 33 | func previewHeaders(w http.ResponseWriter) { |
| 34 | w.Header().Set("Cache-Control", "no-store") |
| 35 | w.Header().Set("Referrer-Policy", "no-referrer") |
| 36 | w.Header().Set("X-Content-Type-Options", "nosniff") |
| 37 | } |
| 38 | func previewError(err error) (int, string, string) { |
| 39 | switch { |
| 40 | case errors.Is(err, ErrPreviewChanged): |
| 41 | return 409, "preview_changed", "evidence.candidate_changed" |
| 42 | case errors.Is(err, ErrPreviewExpired): |
| 43 | return 410, "preview_expired", "question.expired" |
| 44 | case errors.Is(err, ErrUnavailable): |
| 45 | return 503, "unavailable", "api.unavailable" |
| 46 | default: |
| 47 | return 404, "not_found", "api.not_found" |
| 48 | } |
| 49 | } |
| 50 | func previewErrorPage(w http.ResponseWriter, err error) { |
| 51 | status, _, key := previewError(err) |
| 52 | previewHeaders(w) |
| 53 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 54 | w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'self'; font-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'") |
| 55 | w.WriteHeader(status) |
| 56 | fmt.Fprintf(w, `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><link rel="stylesheet" href="/static/tokens.css"><link rel="stylesheet" href="/static/theme.css"><title>%s</title><p>%s</p></html>`, html.EscapeString(copyText("preview.wrapper_title")), html.EscapeString(copyText(key))) |
| 57 | } |
| 58 | func (s *Store) mintPreviewHTTP(auth personapi.Authenticator) http.HandlerFunc { |
| 59 | return func(w http.ResponseWriter, r *http.Request) { |
| 60 | previewHeaders(w) |
| 61 | if len(r.Header.Values("Authorization")) == 0 { |
| 62 | personapi.WriteError(w, r, 401, "unauthenticated", nil) |
| 63 | return |
| 64 | } |
| 65 | p, e := auth.Authenticate(r) |
| 66 | if e != nil { |
| 67 | personapi.WriteError(w, r, 401, "unauthenticated", nil) |
| 68 | return |
| 69 | } |
| 70 | var input struct { |
| 71 | Candidate string `json:"candidate_sha"` |
| 72 | } |
| 73 | r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| 74 | decoder := json.NewDecoder(r.Body) |
| 75 | decoder.DisallowUnknownFields() |
| 76 | var extra any |
| 77 | if r.URL.RawQuery != "" || decoder.Decode(&input) != nil || decoder.Decode(&extra) != io.EOF || !previewCandidate.MatchString(input.Candidate) || !previewTaskID.MatchString(chi.URLParam(r, "id")) { |
| 78 | personapi.WriteError(w, r, 422, "invalid_input", nil) |
| 79 | return |
| 80 | } |
| 81 | out, e := s.mintPreviewPass(personapi.WithVerifiedPrincipal(r.Context(), p), p, chi.URLParam(r, "id"), input.Candidate, previewIP(r)) |
| 82 | if e != nil { |
| 83 | switch { |
| 84 | case errors.Is(e, ErrPreviewChanged): |
| 85 | personapi.WriteError(w, r, 409, "preview_changed", nil) |
| 86 | case errors.Is(e, ErrPreviewExpired): |
| 87 | personapi.WriteError(w, r, 410, "preview_expired", nil) |
| 88 | case errors.Is(e, ErrUnavailable): |
| 89 | personapi.WriteError(w, r, 503, "unavailable", nil) |
| 90 | default: |
| 91 | personapi.WriteError(w, r, 404, "not_found", nil) |
| 92 | } |
| 93 | return |
| 94 | } |
| 95 | w.Header().Set("Content-Type", "application/json") |
| 96 | w.WriteHeader(201) |
| 97 | _ = json.NewEncoder(w).Encode(out) |
| 98 | } |
| 99 | } |
| 100 | func (a *application) exchangePreviewHTTP(w http.ResponseWriter, r *http.Request) { |
| 101 | previewHeaders(w) |
| 102 | kind, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| 103 | if r.Method != "POST" || r.URL.RawQuery != "" || len(r.Header.Values("Authorization")) != 0 || !personapi.OriginAllowed(r, a.origin) || !csrf.SameOrigin(r, a.origin) || kind != "application/x-www-form-urlencoded" { |
| 104 | previewErrorPage(w, ErrPreviewAccess) |
| 105 | return |
| 106 | } |
| 107 | r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| 108 | if r.ParseForm() != nil || len(r.PostForm) != 3 { |
| 109 | previewErrorPage(w, ErrPreviewAccess) |
| 110 | return |
| 111 | } |
| 112 | for _, key := range []string{"pass", "task", "candidate"} { |
| 113 | if len(r.PostForm[key]) != 1 { |
| 114 | previewErrorPage(w, ErrPreviewAccess) |
| 115 | return |
| 116 | } |
| 117 | } |
| 118 | task, candidate := r.PostForm.Get("task"), r.PostForm.Get("candidate") |
| 119 | if !previewTaskID.MatchString(task) || !previewCandidate.MatchString(candidate) { |
| 120 | previewErrorPage(w, ErrPreviewAccess) |
| 121 | return |
| 122 | } |
| 123 | grant, e := a.store.exchangePreviewPass(r.Context(), r.PostForm.Get("pass"), task, candidate, previewIP(r)) |
| 124 | if e != nil { |
| 125 | previewErrorPage(w, e) |
| 126 | return |
| 127 | } |
| 128 | path := "/tasks/" + grant.TaskID + "/preview" |
| 129 | left := int(grant.ExpiresAt.Sub(a.store.runnerClock.Now()) / time.Second) |
| 130 | if left <= 0 { |
| 131 | previewErrorPage(w, ErrPreviewExpired) |
| 132 | return |
| 133 | } |
| 134 | http.SetCookie(w, &http.Cookie{Name: previewCookie + grant.TaskID, Value: grant.Secret, Path: "/", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: left, Expires: grant.ExpiresAt}) |
| 135 | w.Header().Set("Location", path) |
| 136 | w.WriteHeader(http.StatusSeeOther) |
| 137 | } |
| 138 | |
| 139 | // Only this task's well-formed capability selects the restricted lane. |
| 140 | // Junk and other tasks' cookies do not block ordinary browser access. |
| 141 | func hasPreviewCookie(r *http.Request, taskID string) bool { |
| 142 | for _, cookie := range r.Cookies() { |
| 143 | if cookie.Name == previewCookie+taskID && previewHash(cookie.Value) != "" { |
| 144 | return true |
| 145 | } |
| 146 | } |
| 147 | return false |
| 148 | } |
| 149 | func (a *application) previewGrantOrBrowser(next http.Handler) http.Handler { |
| 150 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 151 | taskID := chi.URLParam(r, "id") |
| 152 | if !hasPreviewCookie(r, taskID) { |
| 153 | next.ServeHTTP(w, r) |
| 154 | return |
| 155 | } |
| 156 | var value string |
| 157 | count := 0 |
| 158 | for _, c := range r.Cookies() { |
| 159 | if c.Name == previewCookie+taskID && previewHash(c.Value) != "" { |
| 160 | value = c.Value |
| 161 | count++ |
| 162 | } |
| 163 | } |
| 164 | if count != 1 || r.Method != "GET" || r.URL.RawQuery != "" || !previewTaskID.MatchString(taskID) || r.URL.EscapedPath() != "/tasks/"+taskID+"/preview" { |
| 165 | previewErrorPage(w, ErrPreviewAccess) |
| 166 | return |
| 167 | } |
| 168 | task, e := a.store.readPreviewGrant(r.Context(), value, taskID, previewIP(r)) |
| 169 | if e != nil { |
| 170 | previewErrorPage(w, e) |
| 171 | return |
| 172 | } |
| 173 | step, _, e := a.store.previewDeployment(task) |
| 174 | if e != nil { |
| 175 | previewErrorPage(w, ErrPreviewAccess) |
| 176 | return |
| 177 | } |
| 178 | policy, page, e := previewWrapper(step.Preview.URL, step.Preview.Unsafe) |
| 179 | if e != nil { |
| 180 | previewErrorPage(w, ErrPreviewAccess) |
| 181 | return |
| 182 | } |
| 183 | previewHeaders(w) |
| 184 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 185 | w.Header().Set("Content-Security-Policy", policy) |
| 186 | _, _ = io.WriteString(w, page) |
| 187 | }) |
| 188 | } |
| 189 | |