| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "time" |
| 7 | |
| 8 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 9 | "amadan.net/oficina/equipo/internal/wire" |
| 10 | "gorm.io/gorm" |
| 11 | ) |
| 12 | |
| 13 | var ErrPreviewAccess = errors.New("preview access refused") |
| 14 | var ErrPreviewExpired = errors.New("preview access expired") |
| 15 | var ErrPreviewChanged = errors.New("preview candidate changed") |
| 16 | |
| 17 | type previewPass struct { |
| 18 | Pass string `json:"pass"` |
| 19 | ExpiresIn int `json:"expires_in"` |
| 20 | GrantExpiresIn int `json:"grant_expires_in"` |
| 21 | ExpiresAt time.Time `json:"expires_at"` |
| 22 | GrantExpiresAt time.Time `json:"grant_expires_at"` |
| 23 | } |
| 24 | type previewGrant struct { |
| 25 | Secret string |
| 26 | ExpiresAt time.Time |
| 27 | TaskID string |
| 28 | } |
| 29 | |
| 30 | func (s *Store) mintPreviewPass(ctx context.Context, p PersonPrincipal, taskID, candidate, ip string) (out previewPass, err error) { |
| 31 | if !previewPrincipal(ctx, p) { |
| 32 | return out, ErrPreviewAccess |
| 33 | } |
| 34 | var refusal error |
| 35 | err = s.write(ctx, func(tx *gorm.DB) error { |
| 36 | ok, e := s.previewRate(tx, "mint", ip, p.CredentialID) |
| 37 | if e != nil { |
| 38 | return e |
| 39 | } |
| 40 | if !ok { |
| 41 | refusal = ErrPreviewAccess |
| 42 | return nil |
| 43 | } |
| 44 | device, e := s.previewDevice(tx, p) |
| 45 | if e != nil { |
| 46 | refusal = ErrPreviewAccess |
| 47 | return nil |
| 48 | } |
| 49 | task, e := s.Chat().TaskAt(ctx, tx, taskID) |
| 50 | if e != nil { |
| 51 | refusal = ErrPreviewAccess |
| 52 | return nil |
| 53 | } |
| 54 | deny := func(reason error) error { |
| 55 | refusal = reason |
| 56 | return previewRefusal(tx, previewBinding{Person: p.Address, TaskID: taskID}, "mint", reason) |
| 57 | } |
| 58 | if candidate == "" || candidate != task.CandidateSHA { |
| 59 | return deny(ErrPreviewChanged) |
| 60 | } |
| 61 | step, fingerprint, e := s.previewDeployment(task) |
| 62 | if e != nil { |
| 63 | return deny(ErrPreviewAccess) |
| 64 | } |
| 65 | binding := previewBinding{Instance: device.InstanceID, Person: p.Address, Credential: p.CredentialID, Epoch: p.SessionEpoch, TaskID: taskID, Candidate: candidate, StepID: step.ID, Attempt: step.Attempt, Fingerprint: fingerprint} |
| 66 | if e = s.validatePreview(task, binding); e != nil { |
| 67 | return deny(e) |
| 68 | } |
| 69 | now := s.runnerClock.Now().UTC() |
| 70 | grantExpiry := minPreviewTime(now.Add(15*time.Minute), device.TokenExpiresAt) |
| 71 | if step.Preview.ExpiresAt != nil { |
| 72 | grantExpiry = minPreviewTime(grantExpiry, *step.Preview.ExpiresAt) |
| 73 | } |
| 74 | out = previewPass{Pass: runnerSecret(), ExpiresAt: minPreviewTime(now.Add(time.Minute), grantExpiry), GrantExpiresAt: grantExpiry} |
| 75 | out.ExpiresIn = int(out.ExpiresAt.Sub(now) / time.Second) |
| 76 | out.GrantExpiresIn = int(grantExpiry.Sub(now) / time.Second) |
| 77 | if out.ExpiresIn < 1 || out.GrantExpiresIn < 1 { |
| 78 | return deny(ErrPreviewExpired) |
| 79 | } |
| 80 | if e = s.prunePreviews(tx); e != nil { |
| 81 | return e |
| 82 | } |
| 83 | // One pending pass per device/task; another tap replaces an unexchanged pass. |
| 84 | if e = tx.Model(&previewPassRecord{}).Where("credential = ? AND task_id = ? AND consumed_at IS NULL", p.CredentialID, taskID).Select("consumed_at").Updates(map[string]any{"consumed_at": now}).Error; e != nil { |
| 85 | return e |
| 86 | } |
| 87 | row := previewPassRecord{Hash: previewHash(out.Pass), ID: runnerSecret(), Binding: binding, ExpiresAt: out.ExpiresAt, GrantExpiresAt: grantExpiry} |
| 88 | if e = tx.Create(&row).Error; e != nil { |
| 89 | return e |
| 90 | } |
| 91 | return appendAudit(tx, Actor{Address: p.Address}, "preview.pass.mint", row.ID+":"+taskID) |
| 92 | }) |
| 93 | if err == nil { |
| 94 | err = refusal |
| 95 | } |
| 96 | if err != nil { |
| 97 | out = previewPass{} |
| 98 | } |
| 99 | return |
| 100 | } |
| 101 | |
| 102 | func (s *Store) exchangePreviewPass(ctx context.Context, token, taskID, candidate, ip string) (out previewGrant, err error) { |
| 103 | var refusal error |
| 104 | // Browser exchange authenticates only this pass; no ambient principal grants access. |
| 105 | ctx = personapi.WithVerifiedPrincipal(ctx, PersonPrincipal{}) |
| 106 | err = s.write(ctx, func(tx *gorm.DB) (transactionError error) { |
| 107 | defer func() { |
| 108 | if transactionError == nil { |
| 109 | transactionError = s.prunePreviews(tx) |
| 110 | } |
| 111 | }() |
| 112 | ok, e := s.previewRate(tx, "exchange", ip, "") |
| 113 | if e != nil { |
| 114 | return e |
| 115 | } |
| 116 | if !ok { |
| 117 | refusal = ErrPreviewAccess |
| 118 | return nil |
| 119 | } |
| 120 | hash := previewHash(token) |
| 121 | if hash == "" { |
| 122 | refusal = ErrPreviewAccess |
| 123 | return nil |
| 124 | } |
| 125 | var row previewPassRecord |
| 126 | if e = tx.Where("hash = ?", hash).First(&row).Error; e != nil { |
| 127 | if errors.Is(e, gorm.ErrRecordNotFound) { |
| 128 | refusal = ErrPreviewAccess |
| 129 | return nil |
| 130 | } |
| 131 | return e |
| 132 | } |
| 133 | // Device rate is separate from IP: a new source address cannot evade it. |
| 134 | ok, e = runnerRateAt(tx, "preview:exchange:device:"+row.Binding.Credential, s.runnerClock.Now(), time.Minute, 10) |
| 135 | if e != nil { |
| 136 | return e |
| 137 | } |
| 138 | if !ok { |
| 139 | refusal = ErrPreviewAccess |
| 140 | return nil |
| 141 | } |
| 142 | if row.ConsumedAt != nil { |
| 143 | refusal = ErrPreviewAccess |
| 144 | return nil |
| 145 | } |
| 146 | now := s.runnerClock.Now().UTC() |
| 147 | consumed := tx.Model(&previewPassRecord{}).Where("hash = ? AND consumed_at IS NULL", hash).Select("consumed_at").Updates(map[string]any{"consumed_at": now}) |
| 148 | if consumed.Error != nil { |
| 149 | return consumed.Error |
| 150 | } |
| 151 | if consumed.RowsAffected != 1 { |
| 152 | refusal = ErrPreviewAccess |
| 153 | return nil |
| 154 | } |
| 155 | if row.Binding.TaskID != taskID || row.Binding.Candidate != candidate { |
| 156 | refusal = ErrPreviewAccess |
| 157 | return previewRefusal(tx, row.Binding, row.ID, refusal) |
| 158 | } |
| 159 | task, e := s.previewTask(tx, row.Binding) |
| 160 | if e != nil { |
| 161 | refusal = ErrPreviewAccess |
| 162 | return previewRefusal(tx, row.Binding, row.ID, refusal) |
| 163 | } |
| 164 | refusal = s.validatePreview(task, row.Binding) |
| 165 | if refusal == nil && (!now.Before(row.ExpiresAt) || !now.Before(row.GrantExpiresAt)) { |
| 166 | refusal = ErrPreviewExpired |
| 167 | } |
| 168 | if refusal != nil { |
| 169 | return previewRefusal(tx, row.Binding, row.ID, refusal) |
| 170 | } |
| 171 | out = previewGrant{Secret: runnerSecret(), TaskID: taskID, ExpiresAt: row.GrantExpiresAt} |
| 172 | // Only the current presentation for this device/task retains a grant. |
| 173 | if e = tx.Where("credential = ? AND task_id = ?", row.Binding.Credential, taskID).Delete(&previewGrantRecord{}).Error; e != nil { |
| 174 | return e |
| 175 | } |
| 176 | grant := previewGrantRecord{Hash: previewHash(out.Secret), ID: runnerSecret(), Binding: row.Binding, ExpiresAt: out.ExpiresAt} |
| 177 | if e = tx.Create(&grant).Error; e != nil { |
| 178 | return e |
| 179 | } |
| 180 | return appendAudit(tx, Actor{Address: row.Binding.Person}, "preview.pass.exchange", grant.ID+":"+taskID) |
| 181 | }) |
| 182 | if err == nil { |
| 183 | err = refusal |
| 184 | } |
| 185 | if err != nil { |
| 186 | out = previewGrant{} |
| 187 | } |
| 188 | return |
| 189 | } |
| 190 | |
| 191 | func (s *Store) readPreviewGrant(ctx context.Context, token, taskID, ip string) (out wire.Task, err error) { |
| 192 | var refusal error |
| 193 | ctx = personapi.WithVerifiedPrincipal(ctx, PersonPrincipal{}) |
| 194 | err = s.write(ctx, func(tx *gorm.DB) (transactionError error) { |
| 195 | defer func() { |
| 196 | if transactionError == nil { |
| 197 | transactionError = s.prunePreviews(tx) |
| 198 | } |
| 199 | }() |
| 200 | ok, e := s.previewRate(tx, "read", ip, "") |
| 201 | if e != nil { |
| 202 | return e |
| 203 | } |
| 204 | if !ok { |
| 205 | refusal = ErrPreviewAccess |
| 206 | return nil |
| 207 | } |
| 208 | hash := previewHash(token) |
| 209 | if hash == "" { |
| 210 | refusal = ErrPreviewAccess |
| 211 | return nil |
| 212 | } |
| 213 | var row previewGrantRecord |
| 214 | if e = tx.Where("hash = ?", hash).First(&row).Error; e != nil { |
| 215 | if errors.Is(e, gorm.ErrRecordNotFound) { |
| 216 | refusal = ErrPreviewAccess |
| 217 | return nil |
| 218 | } |
| 219 | return e |
| 220 | } |
| 221 | ok, e = runnerRateAt(tx, "preview:read:device:"+row.Binding.Credential, s.runnerClock.Now(), time.Minute, 120) |
| 222 | if e != nil { |
| 223 | return e |
| 224 | } |
| 225 | if !ok { |
| 226 | refusal = ErrPreviewAccess |
| 227 | return nil |
| 228 | } |
| 229 | deny := func(reason error) error { |
| 230 | refusal = reason |
| 231 | if e := tx.Where("hash = ?", hash).Delete(&previewGrantRecord{}).Error; e != nil { |
| 232 | return e |
| 233 | } |
| 234 | return previewRefusal(tx, row.Binding, row.ID, reason) |
| 235 | } |
| 236 | if row.Binding.TaskID != taskID { |
| 237 | return deny(ErrPreviewAccess) |
| 238 | } |
| 239 | task, e := s.previewTask(tx, row.Binding) |
| 240 | if e != nil { |
| 241 | return deny(ErrPreviewAccess) |
| 242 | } |
| 243 | refusal = s.validatePreview(task, row.Binding) |
| 244 | if refusal == nil && !s.runnerClock.Now().Before(row.ExpiresAt) { |
| 245 | refusal = ErrPreviewExpired |
| 246 | } |
| 247 | if refusal != nil { |
| 248 | return deny(refusal) |
| 249 | } |
| 250 | out = task |
| 251 | return nil |
| 252 | }) |
| 253 | if err == nil { |
| 254 | err = refusal |
| 255 | } |
| 256 | if err != nil { |
| 257 | out = wire.Task{} |
| 258 | } |
| 259 | return |
| 260 | } |
| 261 | |
| 262 | // Audit only hashed-record identities, never submitted identity or credential text. |
| 263 | func previewRefusal(tx *gorm.DB, binding previewBinding, id string, reason error) error { |
| 264 | _, code, _ := previewError(reason) |
| 265 | return appendAudit(tx, Actor{Address: binding.Person}, "preview.pass.refused", id+":"+binding.TaskID+":"+code) |
| 266 | } |
| 267 | |