oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package setup
2
3import (
4 "amadan.net/oficina/equipo/internal/runnerproto"
5 "context"
6 "crypto/ed25519"
7 "crypto/rand"
8 "encoding/base32"
9 "errors"
10 "gorm.io/gorm"
11 "strings"
12 "time"
13)
14
15type Enrolments struct {
16 Replay func(*gorm.DB, context.Context, *Runner) (bool, error)
17 SaveResult func(*gorm.DB, context.Context, Runner) error
18 Write func(context.Context, func(*gorm.DB) error) error
19 Now func() time.Time
20 Instance func(*gorm.DB) (string, error)
21 Rate func(*gorm.DB, string, time.Time, time.Duration, int) (bool, error)
22 Secret func() string
23 Hash func(string, string) string
24 Member func(*gorm.DB, string) (Member, error)
25 Audit func(*gorm.DB, Actor, string, string) error
26 Error func(error) error
27 Runner func(*gorm.DB, string, string) (RunnerRecord, error)
28 Mint func(*gorm.DB, RunnerRecord, time.Time) (runnerproto.RunnerCredential, error)
29 Invalid, Forbidden, Conflict, RunnerRateLimited, EnrolmentPending error
30 // NeedsPrimary refuses a worker-only machine (a Mac) for a person who
31 // has no primary runner: it would be made their primary.
32 NeedsPrimary error
33}
34
35func (s *Enrolments) BeginEnrolment(ctx context.Context, machinePublicKey, label string, workerOnly ...bool) (runnerproto.DeviceCode, error) {
36 if (runnerproto.BeginEnrolmentRequest{Version: 1, MachinePublicKey: machinePublicKey, Label: label}).Validate() != nil {
37 return runnerproto.DeviceCode{}, s.Invalid
38 }
39 var result runnerproto.DeviceCode
40 var denied error
41 err := s.Write(ctx, func(tx *gorm.DB) error {
42 instance, err := s.Instance(tx)
43 if err != nil {
44 return err
45 }
46 now := s.Now().UTC()
47 hash := runnerproto.MachineKeyHash(machinePublicKey)
48 for _, rate := range []struct {
49 key string
50 period time.Duration
51 limit int
52 }{{"create:" + instance, time.Minute, 60}, {"machine:" + instance + ":" + hash, 10 * time.Minute, 5}} {
53 allowed, err := s.Rate(tx, rate.key, now, rate.period, rate.limit)
54 if err != nil {
55 return err
56 }
57 if !allowed {
58 denied = s.RunnerRateLimited
59 return nil
60 }
61 }
62 userBytes := make([]byte, 7)
63 rand.Read(userBytes)
64 userCode := base32.NewEncoding("0123456789ABCDEFGHJKMNPQRSTVWXYZ").WithPadding(base32.NoPadding).EncodeToString(userBytes)[:10]
65 secret := s.Secret()
66 grant := EnrolmentRecord{ID: rand.Text(), InstanceID: instance, Audience: runnerproto.DeviceAudience, MachinePublicKey: machinePublicKey, MachineKeyHash: hash, Label: label, CreatedAt: now, DeviceSecretHash: s.Hash(runnerproto.DeviceAudience, secret), UserCodeHash: s.Hash(instance, userCode), Challenge: s.Secret(), ExpiresAt: now.Add(10 * time.Minute), NextPollAt: now, WorkerOnly: len(workerOnly) == 1 && workerOnly[0]}
67 if err := tx.Create(&grant).Error; err != nil {
68 return s.Error(err)
69 }
70 result = runnerproto.DeviceCode{Version: 1, EnrolmentID: grant.ID, InstanceID: instance, DeviceSecret: secret, UserCode: userCode, Challenge: grant.Challenge, ExpiresAt: grant.ExpiresAt, PollIntervalSeconds: runnerproto.PollIntervalSeconds}
71 return s.Audit(tx, Actor{Address: "device"}, "runner.enrolment.begin", grant.ID)
72 })
73 if err != nil {
74 return runnerproto.DeviceCode{}, err
75 }
76 if denied != nil {
77 return runnerproto.DeviceCode{}, denied
78 }
79 return result, nil
80}
81
82func validUserCode(code string) bool {
83 return len(code) == 10 && strings.Trim(code, "0123456789ABCDEFGHJKMNPQRSTVWXYZ") == ""
84}
85
86func (s *Enrolments) byCode(tx *gorm.DB, instance, code string, now time.Time) (EnrolmentRecord, error) {
87 var grant EnrolmentRecord
88 if !validUserCode(code) {
89 return grant, s.Invalid
90 }
91 if err := tx.Where("user_code_hash = ?", s.Hash(instance, code)).First(&grant).Error; err != nil {
92 if errors.Is(err, gorm.ErrRecordNotFound) {
93 return grant, s.Forbidden
94 }
95 return grant, s.Error(err)
96 }
97 if grant.CreatedAt.IsZero() || grant.InstanceID != instance || grant.Audience != runnerproto.DeviceAudience || !now.Before(grant.ExpiresAt) || grant.ApprovedAt != nil || grant.ConsumedAt != nil || grant.RevokedAt != nil {
98 return grant, s.Forbidden
99 }
100 return grant, nil
101}
102
103func (s *Enrolments) ApproveOrInspect(ctx context.Context, actor Actor, userCode string, approve bool) (Runner, error) {
104 var result Runner
105 var denied error
106 err := s.Write(ctx, func(tx *gorm.DB) error {
107 member, err := s.Member(tx, actor.Address)
108 if err != nil {
109 return err
110 }
111 instance, err := s.Instance(tx)
112 if err != nil {
113 return err
114 }
115 if approve && s.Replay != nil {
116 if replay, e := s.Replay(tx, ctx, &result); e != nil || replay {
117 return e
118 }
119 }
120 now := s.Now().UTC()
121 allowed, err := s.Rate(tx, "approve:"+instance+":"+member.Address, now, time.Minute, 10)
122 if err != nil {
123 return err
124 }
125 if !allowed {
126 denied = s.RunnerRateLimited
127 return nil
128 }
129 grant, err := s.byCode(tx, instance, userCode, now)
130 if err != nil {
131 if errors.Is(err, s.Forbidden) || errors.Is(err, s.Invalid) {
132 denied = err
133 return nil
134 }
135 return err
136 }
137 result = Runner{Person: member.Address, MachineKeyHash: grant.MachineKeyHash, Label: grant.Label, RequestedAt: grant.CreatedAt, Revision: 1}
138 // A person's first runner is the primary; later ones are workers.
139 // Replacing a primary means revoking it first. A machine that can
140 // only be a worker is refused, shown or approved, until the person
141 // has a primary: it would become one.
142 var primaries int64
143 if err := tx.Model(&RunnerRecord{}).Where("instance_id=? AND person=? AND revoked_at IS NULL AND removing_at IS NULL AND coalesce(role,'') IN ('primary','')", instance, member.Address).Count(&primaries).Error; err != nil {
144 return s.Error(err)
145 }
146 if grant.WorkerOnly && primaries == 0 && s.NeedsPrimary != nil {
147 denied = s.NeedsPrimary
148 return nil
149 }
150 if !approve {
151 return nil
152 }
153 var existing int64
154 if err := tx.Model(&RunnerRecord{}).Where("instance_id=? AND machine_key_hash=? AND revoked_at IS NULL", instance, grant.MachineKeyHash).Count(&existing).Error; err != nil {
155 return s.Error(err)
156 }
157 if existing != 0 {
158 return s.Conflict
159 }
160 result.ID = rand.Text()
161 result.Role = RolePrimary
162 if primaries != 0 {
163 result.Role = RoleWorker
164 }
165 if err := tx.Create(&RunnerRecord{Runner: result, InstanceID: instance}).Error; err != nil {
166 return s.Error(err)
167 }
168 grant.Person = member.Address
169 grant.RunnerID = result.ID
170 grant.ApprovedAt = &now
171 updated := tx.Model(&EnrolmentRecord{}).Where("id = ? AND approved_at IS NULL AND revoked_at IS NULL", grant.ID).Select("Person", "RunnerID", "ApprovedAt").Updates(&grant)
172 if updated.Error != nil {
173 return s.Error(updated.Error)
174 }
175 if updated.RowsAffected != 1 {
176 return s.Conflict
177 }
178 if e := s.Audit(tx, actor, "runner.enrolment.approve", result.ID); e != nil {
179 return e
180 }
181 if s.SaveResult != nil {
182 return s.SaveResult(tx, ctx, result)
183 }
184 return nil
185 })
186 if err != nil {
187 return Runner{}, err
188 }
189 if denied != nil {
190 return Runner{}, denied
191 }
192 return result, nil
193}
194
195func (s *Enrolments) ApproveEnrolment(ctx context.Context, actor Actor, userCode string) error {
196 _, err := s.ApproveOrInspect(ctx, actor, userCode, true)
197 return err
198}
199
200func (s *Enrolments) ExchangeEnrolment(ctx context.Context, deviceSecret string, proof runnerproto.ExchangeProof) (runnerproto.RunnerCredential, error) {
201 if (runnerproto.ExchangeEnrolmentRequest{Version: 1, DeviceSecret: deviceSecret, Proof: proof}).Validate() != nil {
202 return runnerproto.RunnerCredential{}, s.Forbidden
203 }
204 var result runnerproto.RunnerCredential
205 var denied error
206 err := s.Write(ctx, func(tx *gorm.DB) error {
207 instance, err := s.Instance(tx)
208 if err != nil {
209 return err
210 }
211 now := s.Now().UTC()
212 var grant EnrolmentRecord
213 if err := tx.Where("device_secret_hash = ?", s.Hash(runnerproto.DeviceAudience, deviceSecret)).First(&grant).Error; err != nil {
214 if errors.Is(err, gorm.ErrRecordNotFound) {
215 return s.Forbidden
216 }
217 return s.Error(err)
218 }
219 if grant.Audience != runnerproto.DeviceAudience || grant.InstanceID != instance || grant.ID != proof.EnrolmentID || grant.Challenge != proof.Challenge || !now.Before(grant.ExpiresAt) || grant.ConsumedAt != nil || grant.RevokedAt != nil {
220 return s.Forbidden
221 }
222 key, err := runnerproto.DecodeBytes(grant.MachinePublicKey, ed25519.PublicKeySize)
223 if err != nil || runnerproto.MachineKeyHash(grant.MachinePublicKey) != grant.MachineKeyHash {
224 return s.Forbidden
225 }
226 signature, _ := runnerproto.DecodeBytes(proof.Signature, ed25519.SignatureSize)
227 if !ed25519.Verify(key, runnerproto.EnrolmentProofMessage(instance, proof), signature) {
228 return s.Forbidden
229 }
230 if now.Before(grant.NextPollAt) {
231 denied = s.RunnerRateLimited
232 return nil
233 }
234 grant.NextPollAt = now.Add(5 * time.Second)
235 if err := tx.Model(&EnrolmentRecord{}).Where("id = ?", grant.ID).Select("NextPollAt").Updates(&grant).Error; err != nil {
236 return s.Error(err)
237 }
238 if grant.ApprovedAt == nil {
239 denied = s.EnrolmentPending
240 return nil
241 }
242 runner, err := s.Runner(tx, instance, grant.RunnerID)
243 if err != nil {
244 return err
245 }
246 if runner.Person != grant.Person || runner.MachineKeyHash != grant.MachineKeyHash {
247 return s.Forbidden
248 }
249 if _, err := s.Member(tx, runner.Person); err != nil {
250 return err
251 }
252 grant.ConsumedAt = &now
253 updated := tx.Model(&EnrolmentRecord{}).Where("id = ? AND consumed_at IS NULL AND revoked_at IS NULL", grant.ID).Select("ConsumedAt").Updates(&grant)
254 if updated.Error != nil {
255 return s.Error(updated.Error)
256 }
257 if updated.RowsAffected != 1 {
258 return s.Conflict
259 }
260 result, err = s.Mint(tx, runner, now)
261 if err != nil {
262 return err
263 }
264 return s.Audit(tx, Actor{Address: runner.Person}, "runner.enrolment.exchange", runner.ID)
265 })
266 if err != nil {
267 return runnerproto.RunnerCredential{}, err
268 }
269 if denied != nil {
270 return runnerproto.RunnerCredential{}, denied
271 }
272 return result, nil
273}
274