oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package github
2
3import (
4 "context"
5 "crypto/hmac"
6 "crypto/rand"
7 "crypto/sha256"
8 "encoding/base64"
9 "encoding/hex"
10 "errors"
11 "net/url"
12 "strings"
13 "time"
14
15 "amadan.net/oficina/equipo/internal/equipo/kernel"
16 "gorm.io/gorm"
17 "gorm.io/plugin/dbresolver"
18)
19
20type Store struct {
21 Maintain func(*gorm.DB) error
22 DB *gorm.DB
23 Write func(context.Context, func(*gorm.DB) error) error
24 Owner func(*gorm.DB, string) error
25 Audit func(*gorm.DB, string, string, string) error
26 Now func() time.Time
27 API *API
28 Root, Origin string
29 Enabled bool
30}
31
32// Refusal carries a public lifecycle state without an upstream body or URL.
33type Refusal struct {
34 View View
35 Cause error
36}
37
38func (e *Refusal) Error() string { return e.Cause.Error() }
39func (e *Refusal) Unwrap() error { return e.Cause }
40func (s *Store) now() time.Time {
41 if s.Now != nil {
42 return s.Now().UTC()
43 }
44 return time.Now().UTC()
45}
46func (s *Store) write(ctx context.Context, p Principal, fn func(*gorm.DB) error) error {
47 if !s.Enabled || s.Write == nil || s.Owner == nil || s.Audit == nil || p.Address == "" || p.Session == "" {
48 return ErrAccess
49 }
50 return s.Write(ctx, func(tx *gorm.DB) error {
51 if !s.Enabled {
52 return ErrAccess
53 }
54 if err := s.Owner(tx, p.Address); err != nil {
55 return err
56 }
57 return fn(tx)
58 })
59}
60func (s *Store) primary(ctx context.Context) *gorm.DB {
61 return s.DB.WithContext(ctx).Clauses(dbresolver.Write).Session(&gorm.Session{})
62}
63func (s *Store) save(tx *gorm.DB, p Principal, c *Connection, kind string) error {
64 c.Generation++
65 c.UpdatedAt = s.now()
66 fields := []string{"Generation", "State", "Login", "AccountType", "AccountID", "AppID", "Slug", "AppName", "InstallationID", "Selection", "Confirmed", "ActiveAccount", "SealedKey", "Owner", "Session", "Origin", "ManifestHash", "InstallationHash", "StartedAt", "RedirectUntil", "PendingUntil", "UninstalledAt", "Count", "CountKnown", "Claim", "ClaimUntil", "UpdatedAt"}
67 if err := tx.Model(&Connection{}).Where("id = ?", c.ID).Select(fields).Updates(c).Error; err != nil {
68 return err
69 }
70 return s.Audit(tx, p.Address, kind, c.ID)
71}
72func digest(raw string) string { sum := sha256.Sum256([]byte(raw)); return hex.EncodeToString(sum[:]) }
73func (s *Store) state(c Connection, stage string) string {
74 mac := hmac.New(sha256.New, kernel.PurposeKey(s.Root, "forge-github-redirect-state"))
75 for _, value := range []string{c.ID, stage, c.Owner, c.Session, c.Origin} {
76 mac.Write([]byte(value))
77 mac.Write([]byte{0})
78 }
79 return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
80}
81func (s *Store) view(c Connection) View {
82 settings := "https://github.com/settings/apps"
83 if c.AccountType == "Organization" {
84 settings = "https://github.com/organizations/" + url.PathEscape(c.Login) + "/settings/apps"
85 }
86 if c.Slug != "" {
87 settings += "/" + url.PathEscape(c.Slug)
88 }
89 return View{ID: c.ID, State: c.State, Login: c.Login, AccountType: c.AccountType, Slug: c.Slug, SettingsURL: settings, Generation: c.Generation, AppID: c.AppID, AccountID: c.AccountID, InstallationID: c.InstallationID, Count: c.Count, CountKnown: c.CountKnown, Confirmed: c.Confirmed}
90}
91func erase(c *Connection, state State) {
92 c.SealedKey = ""
93 c.ManifestHash = ""
94 c.InstallationHash = ""
95 c.Claim = ""
96 c.ClaimUntil = time.Time{}
97 c.ActiveAccount = nil
98 c.CountKnown = false
99 c.State = state
100}
101func (s *Store) Start(ctx context.Context, p Principal, login, kind string) (Started, error) {
102 login = strings.ToLower(strings.TrimSpace(login))
103 if !ValidAccount(login, kind) {
104 return Started{}, ErrAccess
105 }
106 var result Started
107 var forgotten int64
108 err := s.write(ctx, p, func(tx *gorm.DB) error {
109 var active Connection
110 err := tx.Where("LOWER(login) = ? AND account_type = ? AND active_account IS NOT NULL", login, kind).First(&active).Error
111 if err == nil {
112 result.View = s.view(active)
113 result.View.State = StateAlreadyConnected
114 return nil
115 }
116 if !errors.Is(err, gorm.ErrRecordNotFound) {
117 return err
118 }
119 var slot Pending
120 err = tx.First(&slot, "id = ?", 1).Error
121 if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
122 return err
123 }
124 if slot.ConnectionID != "" {
125 var old Connection
126 if err = tx.First(&old, "id = ?", slot.ConnectionID).Error; err != nil {
127 return err
128 }
129 forgotten = old.AppID
130 if calledBack(old) {
131 prior := s.view(old)
132 result.Superseded = &prior
133 erase(&old, StateSuperseded)
134 } else {
135 // No manifest callback arrived, so no App is known to exist.
136 erase(&old, StateAbandoned)
137 }
138 if err = s.save(tx, p, &old, "forge.supersede"); err != nil {
139 return err
140 }
141 }
142 now := s.now()
143 c := Connection{ID: strings.ToLower(rand.Text()), Generation: 1, State: StateManifest, Login: login, AccountType: kind, AppName: "equipo-" + strings.ToLower(rand.Text()[:12]), Owner: p.Address, Session: digest(p.Session), Origin: s.Origin, StartedAt: now, RedirectUntil: now.Add(10 * time.Minute), UpdatedAt: now}
144 raw := s.state(c, "manifest")
145 c.ManifestHash = digest(raw)
146 if err = tx.Create(&c).Error; err != nil {
147 return err
148 }
149 if slot.ID == 0 {
150 err = tx.Create(&Pending{1, c.ID}).Error
151 } else {
152 err = tx.Model(&Pending{}).Where("id = ?", 1).Select("ConnectionID").Updates(&Pending{ConnectionID: c.ID}).Error
153 }
154 if err != nil {
155 return err
156 }
157 if err = s.Audit(tx, p.Address, "forge.start", c.ID); err != nil {
158 return err
159 }
160 result.View, result.State, result.Name = s.view(c), raw, c.AppName
161 return nil
162 })
163 if err == nil && forgotten != 0 {
164 s.API.Forget(ctx, forgotten)
165 }
166 return result, err
167}
168func (s *Store) List(ctx context.Context, p Principal) ([]View, error) {
169 if !s.Enabled {
170 return nil, ErrAccess
171 }
172 tx := s.primary(ctx)
173 if err := s.Owner(tx, p.Address); err != nil {
174 return nil, err
175 }
176 var records []Connection
177 if err := tx.Order("started_at DESC").Order("id").Find(&records).Error; err != nil {
178 return nil, err
179 }
180 // Live and pending connections are listed. A dead attempt is listed only as
181 // its account's latest, only if its App exists, and only until that account
182 // is connected again.
183 account := func(c Connection) string { return strings.ToLower(c.Login) + "\x00" + c.AccountType }
184 connected := map[string]bool{}
185 for _, record := range records {
186 if record.ActiveAccount != nil {
187 connected[account(record)] = true
188 }
189 }
190 shown := map[string]bool{}
191 views := make([]View, 0, len(records))
192 for _, record := range records {
193 // A start GitHub never called back leaves the page at its redirect
194 // deadline. Its hash stays, so a late callback still gets its answer.
195 if record.State == StateManifest && !s.now().Before(record.RedirectUntil) {
196 continue
197 }
198 if record.State.Dead() {
199 key := account(record)
200 if record.State == StateAbandoned || connected[key] || shown[key] {
201 continue
202 }
203 shown[key] = true
204 }
205 views = append(views, s.view(record))
206 }
207 return views, nil
208}
209func (s *Store) Disconnect(ctx context.Context, p Principal, id string) (View, error) {
210 var c Connection
211 err := s.write(ctx, p, func(tx *gorm.DB) error {
212 if err := tx.First(&c, "id = ?", id).Error; err != nil {
213 return err
214 }
215 state := StateDisconnected
216 if !calledBack(c) {
217 state = StateAbandoned
218 }
219 erase(&c, state)
220 if err := s.save(tx, p, &c, "forge.disconnect"); err != nil {
221 return err
222 }
223 return tx.Where("connection_id = ?", id).Delete(&Pending{}).Error
224 })
225 if err == nil {
226 s.API.Forget(ctx, c.AppID)
227 }
228 return s.view(c), err
229}
230func (s *Store) app(c Connection) (App, error) {
231 key, err := openKey(s.Root, s.Origin, c.ID, c.AppID, c.SealedKey)
232 if err != nil {
233 return App{}, err
234 }
235 return App{ID: c.AppID, Slug: c.Slug, Owner: Account{c.AccountID, c.Login, c.AccountType}, Permissions: permissions(), Events: []string{}, pem: key, generation: c.Generation}, nil
236}
237
238// Sweep erases expired keys even while the feature is disabled. Maintain checks
239// the current roster as a system cleanup, without impersonating a removed owner.
240func (s *Store) Sweep(ctx context.Context) error {
241 s.API.Expire(ctx)
242 if s.Write == nil || s.Maintain == nil {
243 return ErrAccess
244 }
245 var forget []int64
246 err := s.Write(ctx, func(tx *gorm.DB) error {
247 if err := s.Maintain(tx); err != nil {
248 return err
249 }
250 var rows []Connection
251 if err := tx.Where("sealed_key <> ?", "").Find(&rows).Error; err != nil {
252 return err
253 }
254 // A conversion that neither finished nor failed within its bound
255 // (a failed transaction or a lost process) becomes a failed setup.
256 var stuck []Connection
257 if err := tx.Where("state = ? AND updated_at < ?", StateConverting, s.now().Add(-conversionBound)).Find(&stuck).Error; err != nil {
258 return err
259 }
260 for _, c := range stuck {
261 erase(&c, StateFailed)
262 if err := s.save(tx, Principal{}, &c, "forge.expire"); err != nil {
263 return err
264 }
265 if err := tx.Where("connection_id = ?", c.ID).Delete(&Pending{}).Error; err != nil {
266 return err
267 }
268 }
269 for _, c := range rows {
270 state := s.expired(c)
271 if state == "" {
272 continue
273 }
274 forget = append(forget, c.AppID)
275 erase(&c, state)
276 if err := s.save(tx, Principal{}, &c, "forge.expire"); err != nil {
277 return err
278 }
279 if err := tx.Where("connection_id = ?", c.ID).Delete(&Pending{}).Error; err != nil {
280 return err
281 }
282 }
283 return nil
284 })
285 if err == nil {
286 for _, id := range forget {
287 s.API.Forget(ctx, id)
288 }
289 }
290 return err
291}
292