oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package equipo
2
3import (
4 "amadan.net/oficina/equipo/internal/equipo/setup"
5 "context"
6 "errors"
7 "mime"
8 "net/http"
9 "strconv"
10 "strings"
11
12 "amadan.net/oficina/equipo/internal/equipo/identity"
13 "amadan.net/oficina/equipo/internal/equipo/team"
14 "amadan.net/oficina/equipo/internal/runnerproto"
15 "amadan.net/rastrillo/rastrillo"
16 "github.com/go-chi/chi/v5"
17)
18
19type runnerContextKey struct{}
20
21func RunnerFrom(r *http.Request) (RunnerPrincipal, bool) {
22 p, ok := r.Context().Value(runnerContextKey{}).(RunnerPrincipal)
23 return p, ok
24}
25
26func runnerJSON(w http.ResponseWriter, status int, value any) {
27 w.Header().Set("Cache-Control", "no-store")
28 w.Header().Set("Content-Type", "application/json")
29 w.WriteHeader(status)
30 data, _ := runnerproto.Marshal(value)
31 _, _ = w.Write(append(data, '\n'))
32}
33func runnerFailure(w http.ResponseWriter, err error) {
34 status, key := runnerStatus(w, err)
35 runnerJSON(w, status, runnerproto.ErrorResponse{Version: 2, Error: key})
36}
37
38// deviceFailure is runnerFailure for a machine enrolling, which has no
39// other way to say what went wrong: a server error is logged, with the
40// route and the error (never the request body, which holds the secret).
41func (a *application) deviceFailure(w http.ResponseWriter, r *http.Request, err error) {
42 status, key := runnerStatus(w, err)
43 if status >= 500 && a.logger != nil {
44 a.logger.Warn(copyRunnerAPIFailed, "route", r.URL.Path, "status", status, "err", err)
45 }
46 runnerJSON(w, status, runnerproto.ErrorResponse{Version: 2, Error: key})
47}
48
49func runnerStatus(w http.ResponseWriter, err error) (int, string) {
50 status, key := 503, "service.unavailable"
51 switch {
52 case errors.Is(err, ErrRunnerRateLimited):
53 status, key = 429, "runner.rate-limited"
54 w.Header().Set("Retry-After", "5")
55 case errors.Is(err, ErrEnrolmentPending):
56 status, key = 409, "runner.pending"
57 case errors.Is(err, ErrInvalid), errors.Is(err, team.ErrInvalid), errors.Is(err, team.ErrSize), errors.Is(err, team.ErrUnknownKind):
58 status, key = 422, "form.invalid"
59 case errors.Is(err, ErrForbidden), errors.Is(err, ErrNotFound), errors.Is(err, team.ErrScope), errors.Is(err, team.ErrFence), errors.Is(err, team.ErrLeaseExpired), errors.Is(err, team.ErrAdmissionExpired), errors.Is(err, team.ErrGrantRevoked), errors.Is(err, team.ErrGrantStale):
60 status, key = 403, "form.forbidden"
61 case errors.Is(err, team.ErrBudget):
62 status, key = 409, "runner.budget"
63 case errors.Is(err, team.ErrQuota):
64 status, key = 409, "runner.quota"
65 case errors.Is(err, team.ErrEvidence):
66 status, key = 422, "runner.evidence"
67 case errors.Is(err, team.ErrContainment):
68 status, key = 409, "runner.containment"
69 case errors.Is(err, team.ErrReplayUnsafe):
70 status, key = 409, "runner.replay"
71 case errors.Is(err, team.ErrUncertain):
72 status, key = 409, "runner.uncertain"
73 case errors.Is(err, ErrConflict), errors.Is(err, team.ErrConflict), errors.Is(err, team.ErrRevision), errors.Is(err, team.ErrState), errors.Is(err, team.ErrDependency), errors.Is(err, team.ErrWorkspace), errors.Is(err, team.ErrReceiptConflict):
74 status, key = 409, "form.conflict"
75 }
76 return status, key
77}
78
79func (a *application) RequireRunner(next http.Handler) http.Handler {
80 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
81 w.Header().Set("Cache-Control", "no-store")
82 authorization := r.Header.Values("Authorization")
83 if len(r.Header.Values("Cookie")) != 0 || len(authorization) != 1 || !strings.HasPrefix(authorization[0], "Bearer ") {
84 runnerFailure(w, ErrForbidden)
85 return
86 }
87 principal, err := a.store.AuthenticateRunner(r.Context(), strings.TrimPrefix(authorization[0], "Bearer "))
88 if err != nil {
89 runnerFailure(w, err)
90 return
91 }
92 next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), runnerContextKey{}, principal)))
93 })
94}
95
96func deviceRequest(w http.ResponseWriter, r *http.Request, value any) bool {
97 w.Header().Set("Cache-Control", "no-store")
98 if len(r.Header.Values("Authorization")) != 0 || len(r.Header.Values("Cookie")) != 0 {
99 runnerFailure(w, ErrForbidden)
100 return false
101 }
102 content, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
103 if err != nil || content != "application/json" || runnerproto.Decode(r.Body, value) != nil {
104 runnerFailure(w, ErrInvalid)
105 return false
106 }
107 return true
108}
109
110func (a *application) beginEnrolment(w http.ResponseWriter, r *http.Request) {
111 var input runnerproto.BeginEnrolmentRequest
112 if !deviceRequest(w, r, &input) {
113 return
114 }
115 if input.Validate() != nil {
116 runnerFailure(w, ErrInvalid)
117 return
118 }
119 result, err := a.store.BeginEnrolment(r.Context(), input.MachinePublicKey, input.Label, input.WorkerOnly)
120 if err != nil {
121 a.deviceFailure(w, r, err)
122 return
123 }
124 result.VerificationURI = a.origin + "/runners/enrol"
125 runnerJSON(w, http.StatusCreated, result)
126}
127func (a *application) exchangeEnrolment(w http.ResponseWriter, r *http.Request) {
128 var input runnerproto.ExchangeEnrolmentRequest
129 if !deviceRequest(w, r, &input) {
130 return
131 }
132 if input.Validate() != nil {
133 runnerFailure(w, ErrInvalid)
134 return
135 }
136 result, err := a.store.ExchangeEnrolment(r.Context(), input.DeviceSecret, input.Proof)
137 if err != nil {
138 a.deviceFailure(w, r, err)
139 return
140 }
141 runnerJSON(w, http.StatusOK, result)
142}
143
144// enrolmentPage is GET /runners/enrol, the address a runner prints
145// (its VerificationURI, which the runner checks, so it stays): with the
146// machine's code it is the Add a machine page showing that machine with
147// its one button (approval is still the confirmed POST below); without,
148// the Machines list.
149func (a *application) enrolmentPage(w http.ResponseWriter, r *http.Request) {
150 a.machinesScreen(w, r, r.URL.Query().Get("code") != "")
151}
152
153// machinesList is GET /conversation/settings/machines.
154func (a *application) machinesList(w http.ResponseWriter, r *http.Request) {
155 a.machinesScreen(w, r, false)
156}
157
158// machinesAdd is GET /conversation/settings/machines/add, with ?code=
159// as at /runners/enrol.
160func (a *application) machinesAdd(w http.ResponseWriter, r *http.Request) {
161 a.machinesScreen(w, r, true)
162}
163
164func (a *application) machinesScreen(w http.ResponseWriter, r *http.Request, adding bool) {
165 w.Header().Set("Cache-Control", "no-store")
166 w.Header().Set("Referrer-Policy", "no-referrer")
167 id, ok := identity.From(r)
168 if !ok {
169 a.failure(w, r, ErrForbidden)
170 return
171 }
172 data, err := a.machinesData(r, id.Address, adding)
173 if err != nil {
174 a.failure(w, r, err)
175 return
176 }
177 if code := r.URL.Query().Get("code"); adding && code != "" && len(code) <= 16 {
178 data.Enrolment, err = a.store.approveOrInspect(r.Context(), Actor{Address: id.Address}, code, false)
179 if err != nil {
180 a.runnerFormFailure(w, r, err)
181 return
182 }
183 data.UserCode = code
184 data.PairingConfirmation = setup.PairingConfirmation(a.store.invitationKey, id.Address, code, a.store.runnerClock.Now())
185 }
186 render(w, "runners", data)
187}
188
189// machinesData is a Machines screen's page: Settings with Machines
190// current, and the machines the person may see.
191func (a *application) machinesData(r *http.Request, address string, adding bool) (pageData, error) {
192 data, err := a.settingsPage(r, "machines", false)
193 if err != nil {
194 return data, err
195 }
196 data.Title = "runner.title"
197 if adding {
198 data.Title = "machines.add"
199 }
200 data.Origin = a.origin
201 records, err := a.store.runnersFor(r.Context(), Actor{Address: address})
202 if err != nil {
203 return data, err
204 }
205 // The install line is the one /install.sh answers, shown only when
206 // that answers (installScript's own conditions).
207 install := ""
208 if instance, err := runnerInstance(a.store.db.G); err == nil && a.installAssets.CachedAvailable() {
209 if _, err := installScriptBody(a.origin, rastrillo.BuildVersion, instance); err == nil {
210 install = "curl -fsSL " + a.origin + "/install.sh | sh"
211 }
212 }
213 data.Machines, data.MachinesStream = machinesPage(records, address, a.store.runnerClock.Now(), adding, install), true
214 return data, nil
215}
216func (a *application) approveEnrolment(w http.ResponseWriter, r *http.Request) {
217 w.Header().Set("Cache-Control", "no-store")
218 w.Header().Set("Referrer-Policy", "no-referrer")
219 r.Body = http.MaxBytesReader(w, r.Body, 4096)
220 if r.ParseForm() != nil {
221 a.failure(w, r, ErrInvalid)
222 return
223 }
224 id, ok := identity.From(r)
225 if !ok {
226 a.failure(w, r, ErrForbidden)
227 return
228 }
229 code := r.PostForm.Get("user_code")
230 for k, v := range r.PostForm {
231 if len(v) != 1 || (k != "user_code" && k != "action" && k != "confirmation") {
232 a.failure(w, r, ErrInvalid)
233 return
234 }
235 }
236 if r.PostForm.Get("action") == "inspect" {
237 data, err := a.machinesData(r, id.Address, true)
238 if err != nil {
239 a.failure(w, r, err)
240 return
241 }
242 data.Enrolment, err = a.store.approveOrInspect(r.Context(), Actor{Address: id.Address}, code, false)
243 if err != nil {
244 a.runnerFormFailure(w, r, err)
245 return
246 }
247 data.UserCode = code
248 data.PairingConfirmation = setup.PairingConfirmation(a.store.invitationKey, id.Address, code, a.store.runnerClock.Now())
249 render(w, "runners", data)
250 return
251 }
252 if r.PostForm.Get("action") != "approve" || !setup.ConfirmPairing(a.store.invitationKey, id.Address, code, r.PostForm.Get("confirmation"), a.store.runnerClock.Now()) {
253 a.failure(w, r, ErrForbidden)
254 return
255 }
256 if err := a.store.ApproveEnrolment(r.Context(), Actor{Address: id.Address}, r.PostForm.Get("user_code")); err != nil {
257 a.runnerFormFailure(w, r, err)
258 return
259 }
260 http.Redirect(w, r, "/conversation/settings/machines/add", http.StatusSeeOther)
261}
262func (a *application) revokeRunner(w http.ResponseWriter, r *http.Request) {
263 r.Body = http.MaxBytesReader(w, r.Body, 4096)
264 if r.ParseForm() != nil {
265 a.failure(w, r, ErrInvalid)
266 return
267 }
268 revision, err := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64)
269 if err != nil || revision < 1 {
270 a.failure(w, r, ErrInvalid)
271 return
272 }
273 id, ok := identity.From(r)
274 if !ok {
275 a.failure(w, r, ErrForbidden)
276 return
277 }
278 if err := a.store.RevokeRunner(r.Context(), Actor{Address: id.Address}, chi.URLParam(r, "id"), revision); err != nil {
279 a.failure(w, r, err)
280 return
281 }
282 http.Redirect(w, r, "/conversation/settings/machines", http.StatusSeeOther)
283}
284
285// removeRunnerNow removes a lost or compromised machine at once.
286func (a *application) removeRunnerNow(w http.ResponseWriter, r *http.Request) {
287 r.Body = http.MaxBytesReader(w, r.Body, 4096)
288 if r.ParseForm() != nil {
289 a.failure(w, r, ErrInvalid)
290 return
291 }
292 revision, err := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64)
293 if err != nil || revision < 1 {
294 a.failure(w, r, ErrInvalid)
295 return
296 }
297 id, ok := identity.From(r)
298 if !ok {
299 a.failure(w, r, ErrForbidden)
300 return
301 }
302 if err := a.store.RemoveRunnerNow(r.Context(), Actor{Address: id.Address}, chi.URLParam(r, "id"), revision); err != nil {
303 a.failure(w, r, err)
304 return
305 }
306 http.Redirect(w, r, "/conversation/settings/machines", http.StatusSeeOther)
307}
308
309func (a *application) runnerFormFailure(w http.ResponseWriter, r *http.Request, err error) {
310 if errors.Is(err, ErrRunnerNeedsPrimary) {
311 renderStatus(w, http.StatusConflict, "form_error", pageData{Nav: Navigation(), Key: "connections", Title: "runner.title", ErrorKey: "runner.needs_primary", Back: "/conversation/settings/machines/add"})
312 return
313 }
314 if !errors.Is(err, ErrRunnerRateLimited) {
315 a.failure(w, r, err)
316 return
317 }
318 w.Header().Set("Retry-After", "60")
319 renderStatus(w, 429, "form_error", pageData{Nav: Navigation(), Key: "connections", Title: "runner.title", ErrorKey: "runner.rate-limited", Back: "/conversation/settings/machines/add"})
320}
321