| 1 | package store |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "time" |
| 8 | ) |
| 9 | |
| 10 | // Equipo link states. Pending waits for the member to approve the sign-in |
| 11 | // code in Equipo; connected holds a bearer; lost is a bearer Equipo refused |
| 12 | // (revoked, or the member's Equipo session ended), which needs reconnecting. |
| 13 | const ( |
| 14 | EquipoPending = "pending" |
| 15 | EquipoConnected = "connected" |
| 16 | EquipoLost = "lost" |
| 17 | ) |
| 18 | |
| 19 | // EquipoLink is a member's connection to the Equipo at Origin. Sealed is |
| 20 | // opaque here: the web package seals and opens it. Revision is the |
| 21 | // device's revision in Equipo, which revoking it names. Person is the |
| 22 | // Equipo address the bearer speaks for, empty until Base has read it. |
| 23 | type EquipoLink struct { |
| 24 | MemberID, Origin, State string |
| 25 | DeviceID string |
| 26 | UserCode, VerificationURI string |
| 27 | Sealed []byte |
| 28 | ExpiresAt time.Time |
| 29 | Revision int64 |
| 30 | PolledAt *time.Time |
| 31 | Person string |
| 32 | } |
| 33 | |
| 34 | const equipoCols = `member_id, origin, state, device_id, user_code, |
| 35 | verification_uri, sealed, expires_at, revision, polled_at, person` |
| 36 | |
| 37 | // EquipoLinkFor is the member's link; ok is false when there is none. |
| 38 | func EquipoLinkFor(ctx context.Context, db *sql.DB, memberID string) (l EquipoLink, ok bool, err error) { |
| 39 | var polled sql.NullTime |
| 40 | err = db.QueryRowContext(ctx, `SELECT `+equipoCols+` FROM equipo_links WHERE member_id = ?`, memberID). |
| 41 | Scan(&l.MemberID, &l.Origin, &l.State, &l.DeviceID, &l.UserCode, |
| 42 | &l.VerificationURI, &l.Sealed, &l.ExpiresAt, &l.Revision, &polled, &l.Person) |
| 43 | if errors.Is(err, sql.ErrNoRows) { |
| 44 | return EquipoLink{}, false, nil |
| 45 | } |
| 46 | if err != nil { |
| 47 | return EquipoLink{}, false, err |
| 48 | } |
| 49 | if polled.Valid { |
| 50 | t := polled.Time |
| 51 | l.PolledAt = &t |
| 52 | } |
| 53 | return l, true, nil |
| 54 | } |
| 55 | |
| 56 | // ErrAskDisconnected: the member has disconnected Ask, so an automatic |
| 57 | // save stores nothing (SaveConnectedEquipoLink). |
| 58 | var ErrAskDisconnected = errors.New("store: Ask disconnected by the member") |
| 59 | |
| 60 | // SaveEquipoLink stores l as the member's only link, replacing any other, |
| 61 | // and forgets the member's host token in the same transaction: a new |
| 62 | // connection may be another Equipo person, and gets its own once ready. |
| 63 | // It leaves AskDisconnected as it is: a pending code is not a connection. |
| 64 | func SaveEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink) error { |
| 65 | return inTx(ctx, db, func(tx *sql.Tx) error { return saveEquipoLink(ctx, tx, l) }) |
| 66 | } |
| 67 | |
| 68 | // SaveConnectedEquipoLink is SaveEquipoLink for a connected link, made in |
| 69 | // one go (Ask set up with Oficina ID). An explicit one, which the member |
| 70 | // asked for, clears AskDisconnected in the same transaction. An automatic |
| 71 | // one leaves it, and while it is set stores nothing and answers |
| 72 | // ErrAskDisconnected: the flag is checked where the link is written, not |
| 73 | // only by the caller. |
| 74 | func SaveConnectedEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink, explicit bool) error { |
| 75 | return inTx(ctx, db, func(tx *sql.Tx) error { |
| 76 | if explicit { |
| 77 | if _, err := tx.ExecContext(ctx, `UPDATE members SET ask_disconnected = 0 WHERE id = ?`, l.MemberID); err != nil { |
| 78 | return err |
| 79 | } |
| 80 | } else { |
| 81 | var disconnected bool |
| 82 | if err := tx.QueryRowContext(ctx, `SELECT ask_disconnected FROM members WHERE id = ?`, l.MemberID).Scan(&disconnected); err != nil { |
| 83 | return err |
| 84 | } |
| 85 | if disconnected { |
| 86 | return ErrAskDisconnected |
| 87 | } |
| 88 | } |
| 89 | return saveEquipoLink(ctx, tx, l) |
| 90 | }) |
| 91 | } |
| 92 | |
| 93 | func saveEquipoLink(ctx context.Context, tx *sql.Tx, l EquipoLink) error { |
| 94 | var polled any |
| 95 | if l.PolledAt != nil { |
| 96 | polled = l.PolledAt.UTC() |
| 97 | } |
| 98 | if _, err := tx.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, l.MemberID); err != nil { |
| 99 | return err |
| 100 | } |
| 101 | _, err := tx.ExecContext(ctx, `INSERT INTO equipo_links (`+equipoCols+`, updated_at) |
| 102 | VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| 103 | ON CONFLICT (member_id) DO UPDATE SET origin = excluded.origin, state = excluded.state, |
| 104 | device_id = excluded.device_id, user_code = excluded.user_code, |
| 105 | verification_uri = excluded.verification_uri, sealed = excluded.sealed, |
| 106 | expires_at = excluded.expires_at, revision = excluded.revision, |
| 107 | polled_at = excluded.polled_at, person = excluded.person, |
| 108 | exchanging_until = NULL, updated_at = excluded.updated_at`, |
| 109 | l.MemberID, l.Origin, l.State, l.DeviceID, l.UserCode, l.VerificationURI, |
| 110 | l.Sealed, l.ExpiresAt.UTC(), l.Revision, polled, l.Person, time.Now().UTC()) |
| 111 | return err |
| 112 | } |
| 113 | |
| 114 | func inTx(ctx context.Context, db *sql.DB, fn func(*sql.Tx) error) error { |
| 115 | tx, err := db.BeginTx(ctx, nil) |
| 116 | if err != nil { |
| 117 | return err |
| 118 | } |
| 119 | defer tx.Rollback() |
| 120 | if err := fn(tx); err != nil { |
| 121 | return err |
| 122 | } |
| 123 | return tx.Commit() |
| 124 | } |
| 125 | |
| 126 | // ClaimEquipoPoll claims the right to ask Equipo now whether the member's |
| 127 | // pending device dev was approved. Only one caller wins: the claim moves |
| 128 | // polled_at and holds the link until now+hold (exchanging_until), so no |
| 129 | // one claims again while that exchange is in flight, nor until every has |
| 130 | // passed since it began. Release (or ConnectEquipoLink) ends the hold; |
| 131 | // hold should outlast the exchange's own timeout. It fails for a link |
| 132 | // that is not that pending device. |
| 133 | func ClaimEquipoPoll(ctx context.Context, db *sql.DB, memberID, dev string, now time.Time, every, hold time.Duration) (bool, error) { |
| 134 | res, err := db.ExecContext(ctx, `UPDATE equipo_links SET polled_at = ?, exchanging_until = ?, updated_at = ? |
| 135 | WHERE member_id = ? AND device_id = ? AND state = ? |
| 136 | AND (polled_at IS NULL OR polled_at <= ?) AND (exchanging_until IS NULL OR exchanging_until <= ?)`, |
| 137 | now.UTC(), now.Add(hold).UTC(), time.Now().UTC(), memberID, dev, EquipoPending, now.Add(-every).UTC(), now.UTC()) |
| 138 | return affected(res, err) |
| 139 | } |
| 140 | |
| 141 | // ReleaseEquipoPoll ends the hold of an exchange on device dev. |
| 142 | func ReleaseEquipoPoll(ctx context.Context, db *sql.DB, memberID, dev string) error { |
| 143 | _, err := db.ExecContext(ctx, `UPDATE equipo_links SET exchanging_until = NULL WHERE member_id = ? AND device_id = ?`, |
| 144 | memberID, dev) |
| 145 | return err |
| 146 | } |
| 147 | |
| 148 | // ConnectEquipoLink stores the bearer an exchange brought back, sealed, but |
| 149 | // only while the member's link is still that pending device. false means |
| 150 | // it is not (disconnected, or replaced by a newer Connect): the caller must |
| 151 | // revoke the bearer instead. Stored, it is the member's connection, made |
| 152 | // with their approval in Equipo, so it clears AskDisconnected in the same |
| 153 | // transaction. |
| 154 | func ConnectEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string, sealed []byte, expires time.Time, revision int64) (stored bool, err error) { |
| 155 | err = inTx(ctx, db, func(tx *sql.Tx) error { |
| 156 | res, err := tx.ExecContext(ctx, `UPDATE equipo_links SET state = ?, sealed = ?, expires_at = ?, revision = ?, |
| 157 | user_code = '', exchanging_until = NULL, updated_at = ? WHERE member_id = ? AND device_id = ? AND state = ?`, |
| 158 | EquipoConnected, sealed, expires.UTC(), revision, time.Now().UTC(), memberID, dev, EquipoPending) |
| 159 | if stored, err = affected(res, err); err != nil || !stored { |
| 160 | return err |
| 161 | } |
| 162 | _, err = tx.ExecContext(ctx, `UPDATE members SET ask_disconnected = 0 WHERE id = ?`, memberID) |
| 163 | return err |
| 164 | }) |
| 165 | if err != nil { |
| 166 | stored = false |
| 167 | } |
| 168 | return stored, err |
| 169 | } |
| 170 | |
| 171 | func affected(res sql.Result, err error) (bool, error) { |
| 172 | if err != nil { |
| 173 | return false, err |
| 174 | } |
| 175 | n, err := res.RowsAffected() |
| 176 | return n == 1, err |
| 177 | } |
| 178 | |
| 179 | // SetEquipoLinkState moves the member's link to state, if it is still |
| 180 | // device dev. |
| 181 | func SetEquipoLinkState(ctx context.Context, db *sql.DB, memberID, dev, state string) error { |
| 182 | _, err := db.ExecContext(ctx, `UPDATE equipo_links SET state = ?, updated_at = ? WHERE member_id = ? AND device_id = ?`, |
| 183 | state, time.Now().UTC(), memberID, dev) |
| 184 | return err |
| 185 | } |
| 186 | |
| 187 | // LoseEquipoLink records that Equipo refused the bearer of the member's |
| 188 | // device dev, and forgets their host token, in one transaction; it does |
| 189 | // neither if the link has moved on to another device. |
| 190 | func LoseEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string) error { |
| 191 | return inTx(ctx, db, func(tx *sql.Tx) error { |
| 192 | ok, err := affected(tx.ExecContext(ctx, `UPDATE equipo_links SET state = ?, updated_at = ? WHERE member_id = ? AND device_id = ?`, |
| 193 | EquipoLost, time.Now().UTC(), memberID, dev)) |
| 194 | if err != nil || !ok { |
| 195 | return err |
| 196 | } |
| 197 | _, err = tx.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, memberID) |
| 198 | return err |
| 199 | }) |
| 200 | } |
| 201 | |
| 202 | // DisconnectEquipo forgets the member's link, whichever device it is now, |
| 203 | // and their host token, and marks Ask disconnected by the member |
| 204 | // (AskDisconnected), in one transaction: all three or none. |
| 205 | func DisconnectEquipo(ctx context.Context, db *sql.DB, memberID string) error { |
| 206 | return inTx(ctx, db, func(tx *sql.Tx) error { |
| 207 | if _, err := tx.ExecContext(ctx, `DELETE FROM equipo_links WHERE member_id = ?`, memberID); err != nil { |
| 208 | return err |
| 209 | } |
| 210 | if _, err := tx.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, memberID); err != nil { |
| 211 | return err |
| 212 | } |
| 213 | _, err := tx.ExecContext(ctx, `UPDATE members SET ask_disconnected = 1 WHERE id = ?`, memberID) |
| 214 | return err |
| 215 | }) |
| 216 | } |
| 217 | |
| 218 | // AskDisconnected reports whether the member has disconnected Ask and not |
| 219 | // connected it since. |
| 220 | func AskDisconnected(ctx context.Context, q QueryRower, memberID string) (bool, error) { |
| 221 | var v bool |
| 222 | err := q.QueryRowContext(ctx, `SELECT ask_disconnected FROM members WHERE id = ?`, memberID).Scan(&v) |
| 223 | return v, err |
| 224 | } |
| 225 | |
| 226 | // SetEquipoPerson records the Equipo address the member's device dev |
| 227 | // speaks for, if the link is still that device. |
| 228 | func SetEquipoPerson(ctx context.Context, db *sql.DB, memberID, dev, person string) error { |
| 229 | _, err := db.ExecContext(ctx, `UPDATE equipo_links SET person = ?, updated_at = ? WHERE member_id = ? AND device_id = ?`, |
| 230 | person, time.Now().UTC(), memberID, dev) |
| 231 | return err |
| 232 | } |
| 233 | |
| 234 | // DeleteEquipoLink forgets the member's link, if it is still device dev. |
| 235 | func DeleteEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string) error { |
| 236 | _, err := db.ExecContext(ctx, `DELETE FROM equipo_links WHERE member_id = ? AND device_id = ?`, memberID, dev) |
| 237 | return err |
| 238 | } |
| 239 | |