| 1 | package personapi |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/aes" |
| 6 | "crypto/cipher" |
| 7 | "crypto/ed25519" |
| 8 | "crypto/hmac" |
| 9 | "crypto/rand" |
| 10 | "crypto/sha256" |
| 11 | "encoding/base64" |
| 12 | "encoding/hex" |
| 13 | "encoding/json" |
| 14 | "errors" |
| 15 | "strings" |
| 16 | "time" |
| 17 | "unicode/utf8" |
| 18 | |
| 19 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 20 | "amadan.net/rastrillo/rastrillo/sessions" |
| 21 | "gorm.io/gorm" |
| 22 | ) |
| 23 | |
| 24 | const PersonAudience = "equipo.person.v1" |
| 25 | const DeviceAudience = "equipo.person.device.v1" |
| 26 | |
| 27 | var ErrDeviceExpired = errors.New("api.device_expired") |
| 28 | var ErrSlowDown = errors.New("api.slow_down") |
| 29 | var ErrPending = errors.New("api.authorization_pending") |
| 30 | |
| 31 | type PersonDeviceChallenge struct { |
| 32 | ID string `json:"id"` |
| 33 | DeviceSecret string `json:"device_secret"` |
| 34 | UserCode string `json:"user_code"` |
| 35 | Challenge string `json:"challenge"` |
| 36 | VerificationURI string `json:"verification_uri"` |
| 37 | ExpiresAt time.Time `json:"expires_at"` |
| 38 | PollIntervalSeconds int `json:"poll_interval_seconds"` |
| 39 | } |
| 40 | type PersonDeviceProof struct { |
| 41 | ID string `json:"id"` |
| 42 | DeviceSecret string `json:"device_secret"` |
| 43 | Challenge string `json:"challenge"` |
| 44 | Nonce string `json:"nonce"` |
| 45 | Signature string `json:"signature"` |
| 46 | } |
| 47 | type PersonCredential struct { |
| 48 | Revision int64 `json:"-"` |
| 49 | ID string `json:"id"` |
| 50 | Token string `json:"token"` |
| 51 | Audience string `json:"audience"` |
| 52 | InstanceID string `json:"instance_id"` |
| 53 | ExpiresAt time.Time `json:"expires_at"` |
| 54 | } |
| 55 | type Device struct { |
| 56 | ID string `json:"id"` |
| 57 | Label string `json:"label"` |
| 58 | CreatedAt time.Time `json:"created_at"` |
| 59 | ExpiresAt time.Time `json:"expires_at"` |
| 60 | RevokedAt *time.Time `json:"revoked_at"` |
| 61 | Revision int64 `json:"revision"` |
| 62 | LastUsedAt *time.Time `json:"last_used_at"` |
| 63 | Approved bool `json:"-"` |
| 64 | } |
| 65 | type DeviceRecord struct { |
| 66 | ID string `gorm:"primaryKey"` |
| 67 | NativeSessionHash string `gorm:"index:person_device_native_session"` |
| 68 | RequestHash string `gorm:"uniqueIndex:person_device_request"` |
| 69 | InputHash, PublicKey, Label, SecretHash, CodeHash, Challenge string |
| 70 | InstanceID, Person string |
| 71 | SessionEpoch, Revision int64 |
| 72 | CreatedAt, ExpiresAt time.Time |
| 73 | ApprovedAt, ExchangedAt, RevokedAt *time.Time |
| 74 | LastPoll *time.Time |
| 75 | LastUsedAt *time.Time |
| 76 | TokenHash string `gorm:"index:person_device_token"` |
| 77 | TokenExpiresAt time.Time |
| 78 | NonceHash, BeginCipher, ResultCipher string |
| 79 | ResultExpiresAt time.Time |
| 80 | } |
| 81 | |
| 82 | func (DeviceRecord) TableName() string { return "person_devices" } |
| 83 | |
| 84 | type DeviceRate struct { |
| 85 | Key string `gorm:"primaryKey"` |
| 86 | StartedAt time.Time |
| 87 | Count int |
| 88 | } |
| 89 | |
| 90 | func (DeviceRate) TableName() string { return "person_device_rates" } |
| 91 | |
| 92 | type DeviceStore struct { |
| 93 | NativeSession func(*gorm.DB, string) (sessions.Session, error) |
| 94 | Write func(context.Context, func(*gorm.DB) error) error |
| 95 | Read func(context.Context, func(*gorm.DB) error) error |
| 96 | Member func(*gorm.DB, string) (kernel.Member, error) |
| 97 | Instance func(*gorm.DB) (string, error) |
| 98 | Audit func(*gorm.DB, kernel.Actor, string, string) error |
| 99 | Key, Origin string |
| 100 | Now func() time.Time |
| 101 | Invalid, Forbidden, NotFound, Conflict error |
| 102 | |
| 103 | // Revoked runs in the revoking transaction: what else the device |
| 104 | // held goes with it (its push registration). Nil is nothing. |
| 105 | Revoked func(tx *gorm.DB, id string) error |
| 106 | } |
| 107 | |
| 108 | func (s *DeviceStore) mac(domain, value string) string { |
| 109 | h := hmac.New(sha256.New, kernel.PurposeKey(s.Key, "person-device-hmac")) |
| 110 | h.Write([]byte(domain + "\x00" + value)) |
| 111 | return hex.EncodeToString(h.Sum(nil)) |
| 112 | } |
| 113 | func (s *DeviceStore) seal(domain string, v any) (string, error) { |
| 114 | b, err := json.Marshal(v) |
| 115 | if err != nil { |
| 116 | return "", err |
| 117 | } |
| 118 | key := kernel.PurposeKey(s.Key, "person-device-results") |
| 119 | block, err := aes.NewCipher(key) |
| 120 | if err != nil { |
| 121 | return "", err |
| 122 | } |
| 123 | g, err := cipher.NewGCM(block) |
| 124 | if err != nil { |
| 125 | return "", err |
| 126 | } |
| 127 | nonce := make([]byte, g.NonceSize()) |
| 128 | if _, err = rand.Read(nonce); err != nil { |
| 129 | return "", err |
| 130 | } |
| 131 | return base64.RawURLEncoding.EncodeToString(g.Seal(nonce, nonce, b, []byte(domain))), nil |
| 132 | } |
| 133 | func (s *DeviceStore) open(domain, raw string, v any) error { |
| 134 | b, err := base64.RawURLEncoding.DecodeString(raw) |
| 135 | if err != nil { |
| 136 | return err |
| 137 | } |
| 138 | key := kernel.PurposeKey(s.Key, "person-device-results") |
| 139 | block, err := aes.NewCipher(key) |
| 140 | if err != nil { |
| 141 | return err |
| 142 | } |
| 143 | g, err := cipher.NewGCM(block) |
| 144 | if err != nil { |
| 145 | return err |
| 146 | } |
| 147 | if len(b) < g.NonceSize() { |
| 148 | return s.Forbidden |
| 149 | } |
| 150 | b, err = g.Open(nil, b[:g.NonceSize()], b[g.NonceSize():], []byte(domain)) |
| 151 | if err != nil { |
| 152 | return err |
| 153 | } |
| 154 | return json.Unmarshal(b, v) |
| 155 | } |
| 156 | |
| 157 | // Seal and Open are the store's sealing with the instance key, bound to |
| 158 | // domain, for another secret the instance keeps (the Assistant's host |
| 159 | // tokens, domain "assistant.host"). |
| 160 | func (s *DeviceStore) Seal(domain string, v any) (string, error) { return s.seal(domain, v) } |
| 161 | func (s *DeviceStore) Open(domain, raw string, v any) error { return s.open(domain, raw, v) } |
| 162 | |
| 163 | func DeviceProofMessage(instance string, p PersonDeviceProof) []byte { |
| 164 | b, _ := json.Marshal([]string{DeviceAudience, instance, p.ID, p.Challenge, p.Nonce}) |
| 165 | return b |
| 166 | } |
| 167 | func (s *DeviceStore) rate(tx *gorm.DB, scope string, now time.Time, limit int) (bool, error) { |
| 168 | key := s.mac("rate", scope) |
| 169 | var row DeviceRate |
| 170 | err := tx.First(&row, "key=?", key).Error |
| 171 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 172 | return true, tx.Create(&DeviceRate{Key: key, StartedAt: now, Count: 1}).Error |
| 173 | } |
| 174 | if err != nil { |
| 175 | return false, err |
| 176 | } |
| 177 | if now.Sub(row.StartedAt) >= time.Minute { |
| 178 | row.StartedAt = now |
| 179 | row.Count = 0 |
| 180 | } |
| 181 | row.Count++ |
| 182 | return row.Count <= limit, tx.Model(&DeviceRate{}).Where("key=?", key).Select("started_at", "count").Updates(&row).Error |
| 183 | } |
| 184 | func (s *DeviceStore) clean(tx *gorm.DB, now time.Time) error { |
| 185 | if err := tx.Model(&DeviceRecord{}).Where("expires_at<=? AND begin_cipher<>''", now).Update("begin_cipher", "").Error; err != nil { |
| 186 | return err |
| 187 | } |
| 188 | if err := tx.Model(&DeviceRecord{}).Where("result_expires_at<=? AND result_cipher<>''", now).Update("result_cipher", "").Error; err != nil { |
| 189 | return err |
| 190 | } |
| 191 | if err := tx.Where("id IN (?)", tx.Model(&DeviceRecord{}).Select("id").Where("expires_at<=? AND approved_at IS NULL AND exchanged_at IS NULL AND revoked_at IS NULL", now).Order("expires_at, id").Limit(100)).Delete(&DeviceRecord{}).Error; err != nil { |
| 192 | return err |
| 193 | } |
| 194 | return tx.Where("started_at<?", now.Add(-time.Hour)).Delete(&DeviceRate{}).Error |
| 195 | } |
| 196 | |
| 197 | type sourceKey struct{} |
| 198 | |
| 199 | func WithDeviceSource(ctx context.Context, source string) context.Context { |
| 200 | return context.WithValue(ctx, sourceKey{}, source) |
| 201 | } |
| 202 | func source(ctx context.Context) string { v, _ := ctx.Value(sourceKey{}).(string); return v } |
| 203 | func (s *DeviceStore) Begin(ctx context.Context, key, label, request string) (out PersonDeviceChallenge, err error) { |
| 204 | pub, e := base64.RawURLEncoding.DecodeString(key) |
| 205 | if s.Key == "" || e != nil || len(pub) != ed25519.PublicKeySize || len(label) < 1 || len(label) > 128 || !utf8.ValidString(label) || strings.ContainsAny(label, "\x00\r\n") || len(request) < 1 || len(request) > 256 { |
| 206 | return out, s.Invalid |
| 207 | } |
| 208 | var refusal error |
| 209 | err = s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error { |
| 210 | now := s.Now().UTC() |
| 211 | if e := s.clean(tx, now); e != nil { |
| 212 | return e |
| 213 | } |
| 214 | ok, e := s.rate(tx, "begin/"+source(ctx), now, 10) |
| 215 | if e != nil { |
| 216 | return e |
| 217 | } |
| 218 | if !ok { |
| 219 | refusal = ErrSlowDown |
| 220 | return nil |
| 221 | } |
| 222 | instance, e := s.Instance(tx) |
| 223 | if e != nil { |
| 224 | return e |
| 225 | } |
| 226 | rh := s.mac("request", key+"\x00"+request) |
| 227 | ih, _ := CanonicalHash([]string{key, label}) |
| 228 | var row DeviceRecord |
| 229 | e = tx.First(&row, "request_hash=?", rh).Error |
| 230 | if e == nil { |
| 231 | if row.InputHash != ih { |
| 232 | refusal = s.Conflict |
| 233 | return nil |
| 234 | } |
| 235 | if !now.Before(row.ExpiresAt) || row.BeginCipher == "" { |
| 236 | refusal = ErrDeviceExpired |
| 237 | return nil |
| 238 | } |
| 239 | return s.open("begin/"+row.ID, row.BeginCipher, &out) |
| 240 | } |
| 241 | if !errors.Is(e, gorm.ErrRecordNotFound) { |
| 242 | return e |
| 243 | } |
| 244 | id := rand.Text() |
| 245 | secret := DeviceAudience + "." + rand.Text() |
| 246 | code := strings.ToUpper(rand.Text()[:8]) |
| 247 | challengeData, _ := json.Marshal([]string{instance, rand.Text()}) |
| 248 | challenge := base64.RawURLEncoding.EncodeToString(challengeData) |
| 249 | out = PersonDeviceChallenge{id, secret, code, challenge, s.Origin + "/auth/devices/" + id, now.Add(10 * time.Minute), 5} |
| 250 | sealed, e := s.seal("begin/"+id, out) |
| 251 | if e != nil { |
| 252 | return e |
| 253 | } |
| 254 | row = DeviceRecord{ID: id, RequestHash: rh, InputHash: ih, PublicKey: key, Label: label, SecretHash: s.mac(DeviceAudience, secret), CodeHash: s.mac("code", code), Challenge: challenge, InstanceID: instance, Revision: 1, CreatedAt: now, ExpiresAt: out.ExpiresAt, BeginCipher: sealed} |
| 255 | return tx.Create(&row).Error |
| 256 | }) |
| 257 | if err == nil { |
| 258 | err = refusal |
| 259 | } |
| 260 | if err != nil { |
| 261 | out = PersonDeviceChallenge{} |
| 262 | } |
| 263 | return |
| 264 | } |
| 265 | func (s *DeviceStore) member(tx *gorm.DB, person string, epoch int64) error { |
| 266 | m, e := s.Member(tx, person) |
| 267 | if e != nil { |
| 268 | return s.Forbidden |
| 269 | } |
| 270 | if !m.Active || epoch < m.SessionEpoch { |
| 271 | return s.Forbidden |
| 272 | } |
| 273 | return nil |
| 274 | } |
| 275 | func (s *DeviceStore) Approve(ctx context.Context, a kernel.Actor, id, code string, m kernel.Mutation) error { |
| 276 | p, ok := PrincipalFrom(ctx) |
| 277 | if !ok || p.Address == "" || p.Address != a.Address || p.CredentialID != "" || p.Pending { |
| 278 | return ErrUnauthenticated |
| 279 | } |
| 280 | // An Oficina ID session's devices expire with it; approving a paired |
| 281 | // device from one would mint a 30-day credential that outlives it. |
| 282 | if p.SessionHash != "" { |
| 283 | return s.Forbidden |
| 284 | } |
| 285 | code = strings.ToUpper(strings.TrimSpace(code)) |
| 286 | if !m.Valid() { |
| 287 | return s.Invalid |
| 288 | } |
| 289 | var requestErr error |
| 290 | ctx, requestErr = ApplicationRequest(ctx, a, "person_device.approve", id, struct { |
| 291 | CodeHash string |
| 292 | Revision int64 |
| 293 | }{s.mac("approval-input", code), m.Revision}, m) |
| 294 | if requestErr != nil { |
| 295 | return requestErr |
| 296 | } |
| 297 | |
| 298 | if len(code) != 8 { |
| 299 | return s.Invalid |
| 300 | } |
| 301 | var denied error |
| 302 | err := s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error { |
| 303 | now := s.Now().UTC() |
| 304 | epoch := p.SessionEpoch |
| 305 | if err := s.member(tx, a.Address, epoch); err != nil { |
| 306 | return err |
| 307 | } |
| 308 | ok, e := s.rate(tx, "approve/"+a.Address+"/"+id, now, 5) |
| 309 | if e != nil { |
| 310 | return e |
| 311 | } |
| 312 | if !ok { |
| 313 | denied = ErrSlowDown |
| 314 | return nil |
| 315 | } |
| 316 | var row DeviceRecord |
| 317 | if e = tx.First(&row, "id=?", id).Error; e != nil { |
| 318 | return s.NotFound |
| 319 | } |
| 320 | if !hmac.Equal([]byte(row.CodeHash), []byte(s.mac("code", code))) { |
| 321 | denied = s.Forbidden |
| 322 | return nil |
| 323 | } |
| 324 | if !now.Before(row.ExpiresAt) { |
| 325 | denied = ErrDeviceExpired |
| 326 | return nil |
| 327 | } |
| 328 | var ack Ack |
| 329 | if replay, e := Replay(tx, ctx, &ack, s.Conflict); e != nil || replay { |
| 330 | return e |
| 331 | } |
| 332 | if row.ApprovedAt != nil || row.Revision != m.Revision { |
| 333 | return s.Conflict |
| 334 | } |
| 335 | row.Person = a.Address |
| 336 | row.SessionEpoch = epoch |
| 337 | row.ApprovedAt = &now |
| 338 | row.Revision++ |
| 339 | if e = tx.Model(&DeviceRecord{}).Where("id=? AND revision=?", id, m.Revision).Select("person", "session_epoch", "approved_at", "revision").Updates(&row).Error; e != nil { |
| 340 | return e |
| 341 | } |
| 342 | if e = s.Audit(tx, a, "person_device.approve", id); e != nil { |
| 343 | return e |
| 344 | } |
| 345 | return SaveResult(tx, ctx, Ack{row.Revision}, s.Conflict) |
| 346 | }) |
| 347 | if err == nil { |
| 348 | return denied |
| 349 | } |
| 350 | return err |
| 351 | } |
| 352 | func (s *DeviceStore) Exchange(ctx context.Context, p PersonDeviceProof) (out PersonCredential, err error) { |
| 353 | if len(p.ID) > 128 || len(p.DeviceSecret) > 256 || len(p.Nonce) < 16 || len(p.Nonce) > 256 || len(p.Signature) > 256 { |
| 354 | return out, s.Invalid |
| 355 | } |
| 356 | var denied error |
| 357 | err = s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error { |
| 358 | now := s.Now().UTC() |
| 359 | if e := s.clean(tx, now); e != nil { |
| 360 | return e |
| 361 | } |
| 362 | // Failed proofs share a source limit, never the real device's polling clock. |
| 363 | invalidProof := func() error { |
| 364 | ok, e := s.rate(tx, "exchange/"+source(ctx), now, 60) |
| 365 | if e != nil { |
| 366 | return e |
| 367 | } |
| 368 | denied = s.Forbidden |
| 369 | if !ok { |
| 370 | denied = ErrSlowDown |
| 371 | } |
| 372 | return nil |
| 373 | } |
| 374 | var row DeviceRecord |
| 375 | if e := tx.First(&row, "id=?", p.ID).Error; e != nil { |
| 376 | if errors.Is(e, gorm.ErrRecordNotFound) { |
| 377 | return invalidProof() |
| 378 | } |
| 379 | return e |
| 380 | } |
| 381 | pub, _ := base64.RawURLEncoding.DecodeString(row.PublicKey) |
| 382 | sig, _ := base64.RawURLEncoding.DecodeString(p.Signature) |
| 383 | valid := hmac.Equal([]byte(row.SecretHash), []byte(s.mac(DeviceAudience, p.DeviceSecret))) && p.Challenge == row.Challenge && len(pub) == ed25519.PublicKeySize && ed25519.Verify(pub, DeviceProofMessage(row.InstanceID, p), sig) |
| 384 | if !valid { |
| 385 | return invalidProof() |
| 386 | } |
| 387 | if row.RevokedAt != nil { |
| 388 | denied = s.Forbidden |
| 389 | return nil |
| 390 | } |
| 391 | if row.ExchangedAt != nil { |
| 392 | if e := s.member(tx, row.Person, row.SessionEpoch); e != nil { |
| 393 | denied = e |
| 394 | return nil |
| 395 | } |
| 396 | if row.NonceHash != s.mac("nonce", p.Nonce) { |
| 397 | denied = s.Forbidden |
| 398 | return nil |
| 399 | } |
| 400 | if !now.Before(row.ResultExpiresAt) || row.ResultCipher == "" { |
| 401 | denied = ErrDeviceExpired |
| 402 | return nil |
| 403 | } |
| 404 | err := s.open("exchange/"+row.ID, row.ResultCipher, &out) |
| 405 | out.Revision = row.Revision |
| 406 | return err |
| 407 | } |
| 408 | if !now.Before(row.ExpiresAt) { |
| 409 | denied = ErrDeviceExpired |
| 410 | return nil |
| 411 | } |
| 412 | if row.LastPoll != nil && now.Sub(*row.LastPoll) < 5*time.Second { |
| 413 | denied = ErrSlowDown |
| 414 | return nil |
| 415 | } |
| 416 | if e := tx.Model(&DeviceRecord{}).Where("id=?", row.ID).Update("last_poll", now).Error; e != nil { |
| 417 | return e |
| 418 | } |
| 419 | if row.ApprovedAt == nil { |
| 420 | denied = ErrPending |
| 421 | return nil |
| 422 | } |
| 423 | if e := s.member(tx, row.Person, row.SessionEpoch); e != nil { |
| 424 | denied = e |
| 425 | return nil |
| 426 | } |
| 427 | token := PersonAudience + "." + rand.Text() |
| 428 | out = PersonCredential{ID: row.ID, Token: token, Audience: PersonAudience, InstanceID: row.InstanceID, ExpiresAt: now.Add(30 * 24 * time.Hour)} |
| 429 | sealed, e := s.seal("exchange/"+row.ID, out) |
| 430 | if e != nil { |
| 431 | return e |
| 432 | } |
| 433 | row.TokenHash = s.mac(PersonAudience, token) |
| 434 | row.TokenExpiresAt = out.ExpiresAt |
| 435 | row.NonceHash = s.mac("nonce", p.Nonce) |
| 436 | row.ResultCipher = sealed |
| 437 | row.ResultExpiresAt = now.Add(10 * time.Minute) |
| 438 | row.ExchangedAt = &now |
| 439 | row.Revision++ |
| 440 | result := tx.Model(&DeviceRecord{}).Where("id=? AND exchanged_at IS NULL", row.ID).Select("token_hash", "token_expires_at", "nonce_hash", "result_cipher", "result_expires_at", "exchanged_at", "revision").Updates(&row) |
| 441 | if result.Error != nil { |
| 442 | return result.Error |
| 443 | } |
| 444 | if result.RowsAffected != 1 { |
| 445 | return s.Conflict |
| 446 | } |
| 447 | if err := tx.Model(&DeviceRecord{}).Select("revision").Where("id=?", row.ID).Scan(&out.Revision).Error; err != nil { |
| 448 | return err |
| 449 | } |
| 450 | return s.Audit(tx, kernel.Actor{Address: row.Person}, "person_device.exchange", row.ID) |
| 451 | }) |
| 452 | if err == nil { |
| 453 | err = denied |
| 454 | } |
| 455 | if err != nil { |
| 456 | out = PersonCredential{} |
| 457 | } |
| 458 | return |
| 459 | } |
| 460 | func (s *DeviceStore) VerifyAt(tx *gorm.DB, id, token string) (p PersonPrincipal, err error) { |
| 461 | var row DeviceRecord |
| 462 | q := tx.Where("id=?", id) |
| 463 | if token != "" { |
| 464 | if !strings.HasPrefix(token, PersonAudience+".") { |
| 465 | return p, ErrUnauthenticated |
| 466 | } |
| 467 | q = tx.Where("token_hash=?", s.mac(PersonAudience, token)) |
| 468 | } |
| 469 | if e := q.First(&row).Error; e != nil { |
| 470 | return p, ErrUnauthenticated |
| 471 | } |
| 472 | instance, e := s.Instance(tx) |
| 473 | if e != nil || instance != row.InstanceID || row.ExchangedAt == nil || row.RevokedAt != nil || !s.Now().Before(row.TokenExpiresAt) { |
| 474 | return p, ErrUnauthenticated |
| 475 | } |
| 476 | if e := s.member(tx, row.Person, row.SessionEpoch); e != nil { |
| 477 | return p, ErrUnauthenticated |
| 478 | } |
| 479 | return PersonPrincipal{Address: row.Person, CredentialID: row.ID, SessionEpoch: row.SessionEpoch}, nil |
| 480 | } |
| 481 | |
| 482 | // What PushState says of a device credential, for a push to it. |
| 483 | const ( |
| 484 | PushCurrent = "current" // valid: it takes pushes |
| 485 | PushGone = "gone" // revoked, never exchanged, another person's or instance's, or signed out everywhere: never again |
| 486 | PushExpired = "expired" // its token expired: not now, but its registration stays |
| 487 | ) |
| 488 | |
| 489 | // PushState is VerifyAt for a push: it tells a device gone for good from |
| 490 | // one only expired, and an error is a lookup that failed, never either. |
| 491 | func (s *DeviceStore) PushState(tx *gorm.DB, id, person string) (string, error) { |
| 492 | var row DeviceRecord |
| 493 | if e := tx.Where("id=?", id).Take(&row).Error; errors.Is(e, gorm.ErrRecordNotFound) { |
| 494 | return PushGone, nil |
| 495 | } else if e != nil { |
| 496 | return "", e |
| 497 | } |
| 498 | instance, e := s.Instance(tx) |
| 499 | if e != nil { |
| 500 | return "", e |
| 501 | } |
| 502 | if instance != row.InstanceID || row.ExchangedAt == nil || row.RevokedAt != nil || row.Person != person { |
| 503 | return PushGone, nil |
| 504 | } |
| 505 | m, e := s.Member(tx, row.Person) |
| 506 | if e != nil { |
| 507 | return "", e |
| 508 | } |
| 509 | if !m.Active || row.SessionEpoch < m.SessionEpoch { |
| 510 | return PushGone, nil |
| 511 | } |
| 512 | if !s.Now().Before(row.TokenExpiresAt) { |
| 513 | return PushExpired, nil |
| 514 | } |
| 515 | return PushCurrent, nil |
| 516 | } |
| 517 | |
| 518 | func (s *DeviceStore) Verify(ctx context.Context, token string) (p PersonPrincipal, err error) { |
| 519 | err = s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error { |
| 520 | var e error |
| 521 | p, e = s.VerifyAt(tx, "", token) |
| 522 | if e != nil { |
| 523 | return e |
| 524 | } |
| 525 | return tx.Model(&DeviceRecord{}).Where("id=?", p.CredentialID).Update("last_used_at", s.Now().UTC()).Error |
| 526 | }) |
| 527 | return |
| 528 | } |
| 529 | func (s *DeviceStore) List(ctx context.Context, a kernel.Actor) (out []Device, err error) { |
| 530 | out = []Device{} |
| 531 | err = s.Read(ctx, func(tx *gorm.DB) error { |
| 532 | epoch := s.Now().Unix() |
| 533 | if p, ok := PrincipalFrom(ctx); ok { |
| 534 | epoch = p.SessionEpoch |
| 535 | if p.CredentialID != "" { |
| 536 | if _, e := s.VerifyAt(tx, p.CredentialID, ""); e != nil { |
| 537 | return e |
| 538 | } |
| 539 | } |
| 540 | } |
| 541 | if e := s.member(tx, a.Address, epoch); e != nil { |
| 542 | return e |
| 543 | } |
| 544 | var rows []DeviceRecord |
| 545 | if e := tx.Where("person=?", a.Address).Order("id").Find(&rows).Error; e != nil { |
| 546 | return e |
| 547 | } |
| 548 | for _, r := range rows { |
| 549 | expiry := r.TokenExpiresAt |
| 550 | if r.ExchangedAt == nil { |
| 551 | expiry = r.ExpiresAt |
| 552 | } |
| 553 | out = append(out, Device{ID: r.ID, Label: r.Label, CreatedAt: r.CreatedAt, ExpiresAt: expiry, RevokedAt: r.RevokedAt, Revision: r.Revision, LastUsedAt: r.LastUsedAt, Approved: r.ApprovedAt != nil}) |
| 554 | } |
| 555 | return nil |
| 556 | }) |
| 557 | return |
| 558 | } |
| 559 | func (s *DeviceStore) Approval(ctx context.Context, id string) (out Device, err error) { |
| 560 | err = s.Read(ctx, func(tx *gorm.DB) error { |
| 561 | var r DeviceRecord |
| 562 | if e := tx.First(&r, "id=?", id).Error; e != nil { |
| 563 | return s.NotFound |
| 564 | } |
| 565 | if !s.Now().Before(r.ExpiresAt) { |
| 566 | return ErrDeviceExpired |
| 567 | } |
| 568 | out = Device{ID: r.ID, Label: r.Label, CreatedAt: r.CreatedAt, ExpiresAt: r.ExpiresAt, Revision: r.Revision, Approved: r.ApprovedAt != nil} |
| 569 | return nil |
| 570 | }) |
| 571 | return |
| 572 | } |
| 573 | func (s *DeviceStore) Revoke(ctx context.Context, a kernel.Actor, id string, m kernel.Mutation) error { |
| 574 | _, err := s.RevokeRevision(ctx, a, id, m) |
| 575 | return err |
| 576 | } |
| 577 | func (s *DeviceStore) RevokeRevision(ctx context.Context, a kernel.Actor, id string, m kernel.Mutation) (revision int64, err error) { |
| 578 | if !m.Valid() { |
| 579 | return 0, s.Invalid |
| 580 | } |
| 581 | var requestErr error |
| 582 | ctx, requestErr = ApplicationRequest(ctx, a, "person_device.revoke", id, m, m) |
| 583 | if requestErr != nil { |
| 584 | return 0, requestErr |
| 585 | } |
| 586 | |
| 587 | err = s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error { |
| 588 | if e := s.member(tx, a.Address, s.Now().Unix()); e != nil { |
| 589 | return e |
| 590 | } |
| 591 | var r DeviceRecord |
| 592 | if e := tx.First(&r, "id=? AND person=?", id, a.Address).Error; e != nil { |
| 593 | return s.NotFound |
| 594 | } |
| 595 | var ack Ack |
| 596 | if replay, e := Replay(tx, ctx, &ack, s.Conflict); e != nil || replay { |
| 597 | revision = ack.Revision |
| 598 | return e |
| 599 | } |
| 600 | if r.Revision != m.Revision { |
| 601 | return s.Conflict |
| 602 | } |
| 603 | now := s.Now().UTC() |
| 604 | r.RevokedAt = &now |
| 605 | r.ResultCipher = "" |
| 606 | r.BeginCipher = "" |
| 607 | r.Revision++ |
| 608 | if e := tx.Model(&DeviceRecord{}).Where("id=?", id).Select("revoked_at", "revision", "result_cipher", "begin_cipher").Updates(&r).Error; e != nil { |
| 609 | return e |
| 610 | } |
| 611 | if s.Revoked != nil { |
| 612 | if e := s.Revoked(tx, id); e != nil { |
| 613 | return e |
| 614 | } |
| 615 | } |
| 616 | if e := s.Audit(tx, a, "person_device.revoke", id); e != nil { |
| 617 | return e |
| 618 | } |
| 619 | if err := tx.Model(&DeviceRecord{}).Select("revision").Where("id=?", id).Scan(&revision).Error; err != nil { |
| 620 | return err |
| 621 | } |
| 622 | return SaveResult(tx, ctx, Ack{revision}, s.Conflict) |
| 623 | }) |
| 624 | return |
| 625 | } |
| 626 | |
| 627 | func (s *DeviceStore) Sweep(ctx context.Context) error { |
| 628 | return s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error { return s.clean(tx, s.Now().UTC()) }) |
| 629 | } |
| 630 | |