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 "context"
5 "crypto/sha256"
6 "encoding/base64"
7 "encoding/hex"
8 "encoding/json"
9 "net/url"
10 "strings"
11 "time"
12
13 "amadan.net/oficina/equipo/internal/equipo/oficinaid"
14 "amadan.net/oficina/equipo/internal/equipo/personapi"
15 "amadan.net/oficina/equipo/internal/wire"
16 "golang.org/x/net/idna"
17 "gorm.io/gorm"
18)
19
20type previewBinding struct {
21 Instance, Person, Candidate, StepID, Fingerprint string
22 Credential string `gorm:"index:,composite:device_task,priority:1"`
23 TaskID string `gorm:"index:,composite:device_task,priority:2"`
24 Epoch, Attempt int64
25}
26type previewPassRecord struct {
27 Hash string `gorm:"primaryKey"`
28 ID string
29 Binding previewBinding `gorm:"embedded"`
30 ExpiresAt time.Time `gorm:"index:preview_pass_expiry"`
31 GrantExpiresAt time.Time
32 ConsumedAt *time.Time
33}
34
35func (previewPassRecord) TableName() string { return "preview_passes" }
36
37type previewGrantRecord struct {
38 Hash string `gorm:"primaryKey"`
39 ID string
40 Binding previewBinding `gorm:"embedded"`
41 ExpiresAt time.Time `gorm:"index:preview_grant_expiry"`
42}
43
44func (previewGrantRecord) TableName() string { return "preview_grants" }
45
46func previewHash(secret string) string {
47 raw, err := base64.RawURLEncoding.Strict().DecodeString(secret)
48 if err != nil || len(raw) != 32 || base64.RawURLEncoding.EncodeToString(raw) != secret {
49 return ""
50 }
51 sum := sha256.Sum256(raw)
52 return hex.EncodeToString(sum[:])
53}
54func (s *Store) previewDevice(tx *gorm.DB, p PersonPrincipal) (personapi.DeviceRecord, error) {
55 var row personapi.DeviceRecord
56 if p.CredentialID == "" || p.Address == "" || p.Pending {
57 return row, ErrPreviewAccess
58 }
59 current, err := s.personDevices().VerifyAt(tx, p.CredentialID, "")
60 if err != nil || current.Address != p.Address || current.SessionEpoch != p.SessionEpoch {
61 return row, ErrPreviewAccess
62 }
63 if err = tx.Where("id = ?", p.CredentialID).First(&row).Error; err != nil {
64 return row, ErrPreviewAccess
65 }
66 if row.NativeSessionHash != "" {
67 if s.personNativeSession == nil {
68 return row, ErrPreviewAccess
69 }
70 sess, e := s.personNativeSession(tx, row.NativeSessionHash)
71 if e != nil || sess.Subject != p.Address || string(sess.Method) != oficinaid.NativeMethod || sess.At.Unix() != p.SessionEpoch || !s.runnerClock.Now().Before(sess.At.Add(oficinaid.NativeLifetime)) {
72 return row, ErrPreviewAccess
73 }
74 }
75 return row, nil
76}
77func (s *Store) previewTask(tx *gorm.DB, b previewBinding) (wire.Task, error) {
78 p := PersonPrincipal{Address: b.Person, CredentialID: b.Credential, SessionEpoch: b.Epoch}
79 device, err := s.previewDevice(tx, p)
80 if err != nil || device.InstanceID != b.Instance {
81 return wire.Task{}, ErrPreviewAccess
82 }
83 task, err := s.Chat().TaskAt(personapi.WithVerifiedPrincipal(tx.Statement.Context, p), tx, b.TaskID)
84 if err != nil {
85 return wire.Task{}, ErrPreviewAccess
86 }
87 return task, nil
88}
89func selectedPreview(task wire.Task) (wire.Step, bool) {
90 for i := len(task.Steps) - 1; i >= 0; i-- {
91 if task.Steps[i].Specialist == wire.SpecialistPreview {
92 return task.Steps[i], true
93 }
94 }
95 return wire.Step{}, false
96}
97func (s *Store) previewDeployment(task wire.Task) (wire.Step, string, error) {
98 step, ok := selectedPreview(task)
99 if !ok || step.Preview == nil || step.Preview.Outcome != wire.PreviewDeployed || step.Preview.URL == "" {
100 return step, "", ErrPreviewAccess
101 }
102 p := step.Preview
103 u, e := url.Parse(p.URL)
104 own, ownErr := url.Parse(s.personOrigin)
105 if e != nil || ownErr != nil || canonicalPreviewHost(u.Hostname()) == "" || canonicalPreviewHost(u.Hostname()) == canonicalPreviewHost(own.Hostname()) {
106 return step, "", ErrPreviewAccess
107 }
108 if _, _, err := previewWrapper(p.URL, p.Unsafe); err != nil {
109 return step, "", ErrPreviewAccess
110 }
111 raw, _ := json.Marshal(p)
112 sum := sha256.Sum256(raw)
113 return step, hex.EncodeToString(sum[:]), nil
114}
115func (s *Store) validatePreview(task wire.Task, b previewBinding) error {
116 step, fingerprint, err := s.previewDeployment(task)
117 // Of the task's candidate, or, once it is done, of its merged commit
118 // (a preview run again after the merge).
119 merged := task.Stage == wire.StageDone && task.Merged != nil && task.Merged.SHA != "" && step.CandidateSHA == task.Merged.SHA
120 if task.CandidateSHA != b.Candidate || err != nil || step.CandidateSHA != b.Candidate && !merged || step.ID != b.StepID || step.Attempt != b.Attempt || fingerprint != b.Fingerprint {
121 return ErrPreviewChanged
122 }
123 // A devbox link comes down with its task, unless it came up after the
124 // task was done (a preview run again on a merged task).
125 if (step.Preview.ExpiresAt != nil && !s.runnerClock.Now().Before(*step.Preview.ExpiresAt)) || (strings.HasPrefix(step.Preview.App, "eq-") && wire.FinalStage(task.Stage) && !devboxAfterDone(task, step)) {
126 return ErrPreviewExpired
127 }
128 return nil
129}
130func (s *Store) previewRate(tx *gorm.DB, kind, ip, device string) (bool, error) {
131 limit := 10
132 if kind == "read" {
133 limit = 120
134 }
135 ok, e := runnerRateAt(tx, "preview:"+kind+":ip:"+runnerHash(s.personKey, ip), s.runnerClock.Now(), time.Minute, limit*3)
136 if e != nil || !ok {
137 return ok, e
138 }
139 if device != "" {
140 return runnerRateAt(tx, "preview:"+kind+":device:"+device, s.runnerClock.Now(), time.Minute, limit)
141 }
142 return true, nil
143}
144func (s *Store) prunePreviews(tx *gorm.DB) error {
145 // Indexed expiry predicates; no secret lookup ever scans these tables.
146 cutoff := s.runnerClock.Now()
147 if err := tx.Where("expires_at <= ?", cutoff).Delete(&previewPassRecord{}).Error; err != nil {
148 return err
149 }
150 return tx.Where("expires_at <= ?", cutoff).Delete(&previewGrantRecord{}).Error
151}
152func minPreviewTime(a, b time.Time) time.Time {
153 if b.Before(a) {
154 return b
155 }
156 return a
157}
158func previewPrincipal(ctx context.Context, p PersonPrincipal) bool {
159 actual, ok := personapi.PrincipalFrom(ctx)
160 return ok && actual.Address == p.Address && actual.CredentialID == p.CredentialID && actual.SessionEpoch == p.SessionEpoch
161}
162
163func canonicalPreviewHost(host string) string {
164 ascii, err := idna.Lookup.ToASCII(strings.TrimSuffix(host, "."))
165 if err != nil {
166 return ""
167 }
168 return strings.ToLower(ascii)
169}
170