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/ownermode"
5 "amadan.net/oficina/equipo/internal/equipo/personapi"
6 "amadan.net/oficina/equipo/internal/equipo/team"
7 "context"
8 "crypto/rand"
9
10 "encoding/json"
11 "errors"
12 "slices"
13 "sort"
14 "strings"
15 "time"
16
17 "amadan.net/oficina/equipo/internal/equipo/planning"
18 "amadan.net/oficina/equipo/internal/runnerproto"
19 "gorm.io/gorm"
20)
21
22var reportTuple = ownermode.Tuple
23
24func (s *Store) confined(r ConnectionReport) bool {
25 return r.PaseoVersion == "" && r.LauncherVersion != "" && r.BwrapVersion != "" && r.PolicyVersion != "" && !r.TrialReady && r.ReadIsolation && (slices.Contains(s.verifiedIsolation, reportTuple(r)) || r.OwnerMode && hexHash(r.IsolationConfigHash))
26}
27
28var hexHash = ownermode.HexHash
29
30var reportValid = ownermode.ReportValid
31
32var sameProfile = ownermode.SameProfile
33var securityHash = ownermode.SecurityHash
34
35func decodeConnection(c *connectionRecord) error {
36 return storeError(json.Unmarshal([]byte(c.ReportsJSON), &c.Reports))
37}
38func runnerPrincipalAt(tx *gorm.DB, p RunnerPrincipal, now time.Time) (runnerRecord, error) {
39 instance, err := runnerInstance(tx)
40 if err != nil {
41 return runnerRecord{}, err
42 }
43 r, err := runnerAt(tx, instance, p.RunnerID)
44 if err != nil {
45 return r, err
46 }
47 if r.Person != p.Person {
48 return r, ErrForbidden
49 }
50 if _, err := currentRunnerMember(tx, r.Person); err != nil {
51 return r, err
52 }
53 var c runnerCredentialRecord
54 if err := tx.Where("id = ?", p.CredentialID).First(&c).Error; err != nil {
55 return r, storeError(err)
56 }
57 if c.RunnerID != r.ID || c.Person != r.Person || c.InstanceID != instance || c.MachineKeyHash != r.MachineKeyHash || c.Audience != runnerproto.RunnerAudience || c.RevokedAt != nil || !now.Before(c.ExpiresAt) {
58 return r, ErrForbidden
59 }
60 return r, nil
61}
62func invalidateConnection(tx *gorm.DB, c connectionRecord, reason string, now time.Time) error {
63 return storeError(tx.Create(&ConnectionInvalidation{ConnectionID: c.ID, Revision: c.Revision, Reason: reason, At: now}).Error)
64}
65
66func (s *Store) ReportConnections(ctx context.Context, principal RunnerPrincipal, reports []ConnectionReport) error {
67 if len(reports) > 256 {
68 return ErrInvalid
69 }
70 invalid := false
71 groups := map[string][]ConnectionReport{}
72 for _, r := range reports {
73 if !reportValid(r) {
74 invalid = true
75 }
76 r.ReadIsolation = s.confined(r)
77 if !r.AllowanceKnown {
78 r.AllowanceRemaining = 0
79 }
80 for _, prior := range groups[r.LocalID] {
81 if prior.Model == r.Model || !sameProfile(prior, r) || securityHash(prior) != securityHash(r) {
82 invalid = true
83 }
84 }
85 groups[r.LocalID] = append(groups[r.LocalID], r)
86 }
87 err := s.write(ctx, func(tx *gorm.DB) error {
88 now := s.runnerClock.Now().UTC()
89 runner, err := runnerPrincipalAt(tx, principal, now)
90 if err != nil {
91 return err
92 }
93 var existing []connectionRecord
94 if err := tx.Where("runner_id = ?", runner.ID).Find(&existing).Error; err != nil {
95 return storeError(err)
96 }
97 byLocal := map[string]connectionRecord{}
98 for _, c := range existing {
99 if err := decodeConnection(&c); err != nil {
100 return err
101 }
102 byLocal[c.LocalID] = c
103 }
104 for local, rows := range groups {
105 if c, exists := byLocal[local]; exists && (c.Person != runner.Person || len(c.Reports) == 0 || !sameProfile(c.Reports[0], rows[0])) {
106 invalid = true
107 }
108 }
109 if invalid {
110 if err := tx.Model(&supervisedTrialRecord{}).Where("runner_id=? AND revoked_at IS NULL", runner.ID).Select("RevokedAt").Updates(&supervisedTrialRecord{RevokedAt: &now}).Error; err != nil {
111 return storeError(err)
112 }
113 for _, c := range byLocal {
114 c.Revision++
115 for i := range c.Reports {
116 c.Reports[i].Available = false
117 c.Reports[i].TrialReady = false
118 }
119 data, _ := json.Marshal(c.Reports)
120 c.ReportsJSON = string(data)
121 if err := tx.Model(&connectionRecord{}).Where("id = ?", c.ID).Select("Revision", "ReportsJSON").Updates(&c).Error; err != nil {
122 return storeError(err)
123 }
124 if err := invalidateConnection(tx, c, "report_rejected", now); err != nil {
125 return err
126 }
127 }
128 return appendAudit(tx, Actor{Address: runner.Person}, "connection.report.rejected", runner.ID)
129 }
130 locals := make([]string, 0, len(groups))
131 for local := range groups {
132 locals = append(locals, local)
133 }
134 sort.Strings(locals)
135 for _, local := range locals {
136 rows := groups[local]
137 slices.SortFunc(rows, func(a, b ConnectionReport) int { return strings.Compare(a.Model, b.Model) })
138 c, exists := byLocal[local]
139 if !exists {
140 c = connectionRecord{Connection: Connection{ID: rand.Text(), RunnerID: runner.ID, Person: runner.Person, LocalID: local, Revision: 1}}
141 }
142 hash := securityHash(rows[0])
143 changed := exists && c.SecurityHash != hash
144 if changed {
145 c.Revision++
146 if err := invalidateConnection(tx, c, "security_changed", now); err != nil {
147 return err
148 }
149 }
150 if exists && !changed {
151 for _, prior := range c.Reports {
152 present := false
153 for _, next := range rows {
154 if next.Model == prior.Model && next.Available {
155 present = true
156 }
157 }
158 if prior.Available && !present {
159 if err := invalidateConnection(tx, c, "model_unavailable", now); err != nil {
160 return err
161 }
162 break
163 }
164 }
165 }
166 if c.RevokedAt != nil {
167 for i := range rows {
168 rows[i].Available = false
169 }
170 }
171 c.SecurityHash = hash
172 c.LastSeen = now
173 data, _ := json.Marshal(rows)
174 c.ReportsJSON = string(data)
175 if exists {
176 if err := tx.Model(&connectionRecord{}).Where("id = ?", c.ID).Select("Revision", "LastSeen", "ReportsJSON", "SecurityHash").Updates(&c).Error; err != nil {
177 return storeError(err)
178 }
179 } else if err := tx.Create(&c).Error; err != nil {
180 return storeError(err)
181 }
182 }
183 // Each report is a complete discovery snapshot for this runner. Missing
184 // profiles remain as unavailable records so pins and history keep identity.
185 for _, c := range existing {
186 if _, ok := groups[c.LocalID]; ok {
187 continue
188 }
189 if err := decodeConnection(&c); err != nil {
190 return err
191 }
192 changed := false
193 for i := range c.Reports {
194 if c.Reports[i].Available {
195 changed = true
196 }
197 c.Reports[i].Available = false
198 c.Reports[i].TrialReady = false
199 }
200 if changed {
201 if err := invalidateConnection(tx, c, "profile_missing", now); err != nil {
202 return err
203 }
204 }
205 data, _ := json.Marshal(c.Reports)
206 c.ReportsJSON = string(data)
207 if err := tx.Model(&connectionRecord{}).Where("id = ?", c.ID).Select("ReportsJSON").Updates(&c).Error; err != nil {
208 return storeError(err)
209 }
210 }
211 if s.execution != nil {
212 for _, r := range reports {
213 if r.OwnerMode && r.Available && r.Kind == "subscription" && s.confined(r) {
214 if err = s.execution.ownerDefaults(tx.Statement.Context, tx, Selection{RunnerID: runner.ID, Person: runner.Person, Isolation: team.IsolationSnapshot{Mode: "owner mode"}}); err != nil {
215 return err
216 }
217 break
218 }
219 }
220 }
221 return appendAudit(tx, Actor{Address: runner.Person}, "connection.report", runner.ID)
222 })
223 if err != nil {
224 return err
225 }
226 if invalid {
227 return ErrInvalid
228 }
229 return nil
230}
231
232func (s *Store) Connections(ctx context.Context, actor Actor) ([]Connection, error) {
233 var result []Connection
234 err := s.readTeam(ctx, actor, func(tx *gorm.DB, _ Team) error {
235 m, err := currentRunnerMember(tx, actor.Address)
236 if err != nil {
237 return err
238 }
239 var rows []connectionRecord
240 if err := tx.Where("person = ?", m.Address).Order("id").Find(&rows).Error; err != nil {
241 return storeError(err)
242 }
243 for _, c := range rows {
244 if err := decodeConnection(&c); err != nil {
245 return err
246 }
247 result = append(result, c.Connection)
248 }
249 return nil
250 })
251 if err != nil {
252 return nil, err
253 }
254 return result, nil
255}
256func choiceAt(tx *gorm.DB, person string, project int64) (connectionChoiceRecord, []string, error) {
257 c, ids, err := planning.ConnectionChoiceAt(tx, person, project)
258 return c, ids, storeError(err)
259}
260func (s *Store) SaveConnectionChoice(ctx context.Context, actor Actor, choice ConnectionChoice) error {
261 choice, err := planning.NormalizeConnectionChoice(choice, ErrInvalid)
262 if err != nil {
263 return err
264 }
265 ids := choice.ConnectionIDs
266 return s.write(ctx, func(tx *gorm.DB) error {
267 m, err := currentRunnerMember(tx, actor.Address)
268 if err != nil {
269 return err
270 }
271 var ack personapi.Ack
272 if replay, err := personapi.Replay(tx, ctx, &ack, ErrConflict); err != nil || replay {
273 return err
274 }
275 var project Project
276 if err := tx.First(&project, choice.ProjectID).Error; err != nil {
277 return storeError(err)
278 }
279 old, oldIDs, err := choiceAt(tx, m.Address, project.ID)
280 exists := err == nil
281 if err != nil && !errors.Is(err, ErrNotFound) {
282 return err
283 }
284 if old.Revision != choice.Revision {
285 return ErrConflict
286 }
287 for _, id := range ids {
288 var c connectionRecord
289 if err := tx.Where("id = ?", id).First(&c).Error; err != nil {
290 return storeError(err)
291 }
292 if c.Person != m.Address {
293 return ErrForbidden
294 }
295 }
296 raw, _ := json.Marshal(ids)
297 c := connectionChoiceRecord{Person: m.Address, ProjectID: project.ID, Revision: old.Revision + 1, ConnectionIDsJSON: string(raw), PinnedID: choice.PinnedID, Mode: choice.Mode}
298 if exists {
299 if err := tx.Model(&connectionChoiceRecord{}).Where("person = ? AND project_id = ?", m.Address, project.ID).Select("Revision", "ConnectionIDsJSON", "PinnedID", "Mode").Updates(&c).Error; err != nil {
300 return storeError(err)
301 }
302 } else if err := tx.Create(&c).Error; err != nil {
303 return storeError(err)
304 }
305 for _, id := range ids {
306 if !slices.Contains(oldIDs, id) {
307 var row connectionRecord
308 if err := tx.Where("id = ?", id).First(&row).Error; err != nil {
309 return storeError(err)
310 }
311 if err := invalidateConnection(tx, row, "connection_enabled", s.runnerClock.Now().UTC()); err != nil {
312 return err
313 }
314 }
315 }
316 for _, id := range oldIDs {
317 if !slices.Contains(ids, id) || old.PinnedID != choice.PinnedID || old.Mode != choice.Mode {
318 var row connectionRecord
319 if err := tx.Where("id = ?", id).First(&row).Error; err != nil {
320 return storeError(err)
321 }
322 if err := invalidateConnection(tx, row, "choice_changed", s.runnerClock.Now().UTC()); err != nil {
323 return err
324 }
325 }
326 }
327 choice.Revision = c.Revision
328 auditChoice, _ := json.Marshal(choice)
329 if err := appendAudit(tx, actor, "connection.choice", string(auditChoice)); err != nil {
330 return err
331 }
332 return personapi.SaveResult(tx, ctx, personapi.Ack{Revision: c.Revision}, ErrConflict)
333 })
334}
335
336func (s *Store) RenameConnection(ctx context.Context, a Actor, id, label string, m Mutation) error {
337 trimmed := strings.TrimSpace(label)
338 if trimmed == "" || len(label) > 128 || strings.ContainsAny(label, "\x00\r\n") {
339 return ErrInvalid
340 }
341 return s.changeConnection(ctx, a, id, label, false, m)
342}
343func (s *Store) RevokeConnection(ctx context.Context, a Actor, id string, m Mutation) error {
344 return s.changeConnection(ctx, a, id, "", true, m)
345}
346func (s *Store) changeConnection(ctx context.Context, a Actor, id, label string, revoke bool, m Mutation) error {
347 if !m.Valid() {
348 return ErrInvalid
349 }
350 op := "connection.rename"
351 if revoke {
352 op = "connection.revoke"
353 }
354 var err error
355 ctx, err = personapi.ApplicationRequest(ctx, a, op, id, struct {
356 Label string
357 Revision int64
358 }{label, m.Revision}, m)
359 if err != nil {
360 return err
361 }
362
363 return s.write(ctx, func(tx *gorm.DB) error {
364 if _, err := currentRunnerMember(tx, a.Address); err != nil {
365 return err
366 }
367 var row connectionRecord
368 if err := tx.First(&row, "id=? AND person=?", id, a.Address).Error; err != nil {
369 return storeError(err)
370 }
371 var ack personapi.Ack
372 if replay, err := personapi.Replay(tx, ctx, &ack, ErrConflict); err != nil || replay {
373 return err
374 }
375 if row.Revision != m.Revision || row.RevokedAt != nil {
376 return ErrConflict
377 }
378 row.Revision++
379 kind := "connection.rename"
380 if revoke {
381 now := s.runnerClock.Now().UTC()
382 row.RevokedAt = &now
383 kind = "connection.revoke"
384 if err := decodeConnection(&row); err != nil {
385 return err
386 }
387 for i := range row.Reports {
388 row.Reports[i].Available = false
389 }
390 raw, _ := json.Marshal(row.Reports)
391 row.ReportsJSON = string(raw)
392 } else {
393 row.Label = strings.TrimSpace(label)
394 }
395 if err := tx.Model(&connectionRecord{}).Where("id=?", id).Select("label", "revoked_at", "revision", "reports_json").Updates(&row).Error; err != nil {
396 return err
397 }
398 if revoke {
399 if err := s.coordinatorApplication().RevokeConnectionAt(tx, a, id); err != nil {
400 return err
401 }
402 if err := invalidateConnection(tx, row, "revoked", s.runnerClock.Now().UTC()); err != nil {
403 return err
404 }
405 }
406 if err := appendAudit(tx, a, kind, id); err != nil {
407 return err
408 }
409 return personapi.SaveResult(tx, ctx, personapi.Ack{Revision: row.Revision}, ErrConflict)
410 })
411}
412