| 1 | package oficinaid |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/hmac" |
| 6 | "crypto/sha256" |
| 7 | "database/sql" |
| 8 | "encoding/hex" |
| 9 | "errors" |
| 10 | "strconv" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/home/connect" |
| 14 | "amadan.net/oficina/home/connect/linkstore" |
| 15 | "amadan.net/oficina/home/handoff" |
| 16 | "amadan.net/oficina/home/handoff/seal" |
| 17 | "amadan.net/rastrillo/rastrillo/assertion" |
| 18 | "amadan.net/rastrillo/rastrillo/sessions" |
| 19 | ) |
| 20 | |
| 21 | const Method = "oficina-id" |
| 22 | |
| 23 | var ErrRefused = errors.New("oficina identity refused") |
| 24 | var ErrUnlinked = errors.New("oficina identity unlinked") |
| 25 | |
| 26 | // ErrUnavailable is a session that could not be read: storage failed, so |
| 27 | // nothing is known about it. Never a refusal (the door's probe reads a 5xx |
| 28 | // as undecided). |
| 29 | var ErrUnavailable = errors.New("oficina identity unavailable") |
| 30 | |
| 31 | // lookupError is a session lookup's err: refused for a row that is not |
| 32 | // there, unavailable for anything else. |
| 33 | func lookupError(err error) error { |
| 34 | if errors.Is(err, sql.ErrNoRows) || errors.Is(err, linkstore.ErrRefused) { |
| 35 | return ErrRefused |
| 36 | } |
| 37 | return ErrUnavailable |
| 38 | } |
| 39 | |
| 40 | const SchemaSQL = `CREATE TABLE equipo_id_accounts (id INTEGER PRIMARY KEY AUTOINCREMENT, binding TEXT NOT NULL UNIQUE, member_key TEXT NOT NULL UNIQUE, linked_at INTEGER NOT NULL DEFAULT 0); |
| 41 | CREATE TABLE equipo_id_reauth (id_hash TEXT PRIMARY KEY, account_id INTEGER NOT NULL, session_hash TEXT NOT NULL, started INTEGER NOT NULL, expires INTEGER NOT NULL, purpose TEXT NOT NULL, ready INTEGER NOT NULL DEFAULT 0);` |
| 42 | |
| 43 | type Account struct { |
| 44 | MemberKey string `gorm:"not null;unique"` |
| 45 | ID int64 |
| 46 | Binding string `gorm:"not null;unique"` |
| 47 | LinkedAt int64 `gorm:"not null;default:0"` |
| 48 | } |
| 49 | |
| 50 | func (Account) TableName() string { return "equipo_id_accounts" } |
| 51 | |
| 52 | type Reauth struct { |
| 53 | IDHash string `gorm:"primaryKey"` |
| 54 | AccountID int64 `gorm:"not null"` |
| 55 | SessionHash string `gorm:"not null"` |
| 56 | Started int64 `gorm:"not null"` |
| 57 | Expires int64 `gorm:"not null"` |
| 58 | Purpose string `gorm:"not null"` |
| 59 | Ready int64 `gorm:"not null;default:0"` |
| 60 | } |
| 61 | |
| 62 | func (Reauth) TableName() string { return "equipo_id_reauth" } |
| 63 | |
| 64 | var Models = []any{&Account{}, &Reauth{}} |
| 65 | |
| 66 | type Store struct { |
| 67 | DB *sql.DB |
| 68 | Origin string |
| 69 | Config *connect.DecodedCredentials |
| 70 | Exchange *handoff.Store |
| 71 | Links *linkstore.Store |
| 72 | seal *seal.Sealer |
| 73 | } |
| 74 | |
| 75 | func New(db *sql.DB, origin string, cfg *connect.DecodedCredentials) (*Store, error) { |
| 76 | if cfg == nil { |
| 77 | return nil, nil |
| 78 | } |
| 79 | sealed, e := seal.New(cfg.DEK, "oficina/equipo") |
| 80 | if e != nil { |
| 81 | return nil, e |
| 82 | } |
| 83 | s := &Store{DB: db, Origin: origin, Config: cfg, seal: sealed} |
| 84 | s.Exchange, e = handoff.NewStore(db, sealed, cfg.Issuer, origin, cfg.Keys) |
| 85 | if e != nil { |
| 86 | return nil, e |
| 87 | } |
| 88 | s.Links, e = linkstore.New(db, cfg.DEK, origin, cfg.Issuer, "oficina/equipo", s.lookup) |
| 89 | if e != nil { |
| 90 | return nil, e |
| 91 | } |
| 92 | return s, nil |
| 93 | } |
| 94 | func (s *Store) binding(address string) string { |
| 95 | m := hmac.New(sha256.New, s.Config.DEK) |
| 96 | m.Write([]byte("equipo-local-account\x00" + address)) |
| 97 | return hex.EncodeToString(m.Sum(nil)) |
| 98 | } |
| 99 | func (s *Store) lookup(ctx context.Context, q linkstore.Queryer, id int64) (string, error) { |
| 100 | var address string |
| 101 | var active bool |
| 102 | if e := q.QueryRowContext(ctx, "SELECT m.address,m.active FROM equipo_id_accounts a JOIN members m ON m.identity_key=a.member_key WHERE a.id=?", id).Scan(&address, &active); e != nil { |
| 103 | return "", e |
| 104 | } |
| 105 | if !active { |
| 106 | return "", sql.ErrNoRows |
| 107 | } |
| 108 | return address, nil |
| 109 | } |
| 110 | func (s *Store) account(ctx context.Context, tx *sql.Tx, address string) (int64, error) { |
| 111 | var active bool |
| 112 | var memberKey string |
| 113 | if e := tx.QueryRowContext(ctx, "SELECT active,identity_key FROM members WHERE address=?", address).Scan(&active, &memberKey); e != nil || !active || memberKey == "" { |
| 114 | return 0, ErrRefused |
| 115 | } |
| 116 | binding := s.binding(address) |
| 117 | var id int64 |
| 118 | e := tx.QueryRowContext(ctx, "SELECT id FROM equipo_id_accounts WHERE binding=?", binding).Scan(&id) |
| 119 | if e == nil { |
| 120 | return id, nil |
| 121 | } |
| 122 | if !errors.Is(e, sql.ErrNoRows) { |
| 123 | return 0, e |
| 124 | } |
| 125 | result, e := tx.ExecContext(ctx, "INSERT INTO equipo_id_accounts(binding,member_key) VALUES(?,?)", binding, memberKey) |
| 126 | if e != nil { |
| 127 | return 0, e |
| 128 | } |
| 129 | return result.LastInsertId() |
| 130 | } |
| 131 | func (s *Store) begin(ctx context.Context, now time.Time) (*sql.Tx, error) { |
| 132 | tx, e := s.DB.BeginTx(ctx, nil) |
| 133 | if e != nil { |
| 134 | return nil, e |
| 135 | } |
| 136 | if _, e = s.clock(ctx, tx, now); e != nil { |
| 137 | tx.Rollback() |
| 138 | return nil, e |
| 139 | } |
| 140 | return tx, nil |
| 141 | } |
| 142 | func (s *Store) clock(ctx context.Context, tx *sql.Tx, now time.Time) (int64, error) { |
| 143 | result, e := tx.ExecContext(ctx, "UPDATE home_link_clock SET high_water=MAX(high_water,?) WHERE id=1 AND high_water<=?", now.Unix(), now.Unix()+30) |
| 144 | if e != nil { |
| 145 | return 0, e |
| 146 | } |
| 147 | n, e := result.RowsAffected() |
| 148 | if e != nil || n != 1 { |
| 149 | return 0, ErrRefused |
| 150 | } |
| 151 | var high int64 |
| 152 | e = tx.QueryRowContext(ctx, "SELECT MAX(high_water,(SELECT observed FROM oficina_handoff_clock WHERE id=1)) FROM home_link_clock WHERE id=1").Scan(&high) |
| 153 | if e != nil { |
| 154 | return 0, e |
| 155 | } |
| 156 | if now.Unix() < high-30 { |
| 157 | return 0, ErrRefused |
| 158 | } |
| 159 | return high, nil |
| 160 | } |
| 161 | |
| 162 | func (s *Store) session(ctx context.Context, q linkstore.Queryer, token string, now time.Time) (sessions.Session, error) { |
| 163 | if token == "" { |
| 164 | return sessions.Session{}, ErrRefused |
| 165 | } |
| 166 | return s.sessionHash(ctx, q, sessions.HashToken(token), now) |
| 167 | } |
| 168 | func (s *Store) sessionHash(ctx context.Context, q linkstore.Queryer, hash string, now time.Time) (sessions.Session, error) { |
| 169 | var out sessions.Session |
| 170 | var at, auth, expires string |
| 171 | e := q.QueryRowContext(ctx, "SELECT subject,method,auth_time,created_at,expires_at FROM sessions WHERE token_hash=?", hash).Scan(&out.Subject, &out.Method, &auth, &at, &expires) |
| 172 | if e != nil { |
| 173 | return out, lookupError(e) |
| 174 | } |
| 175 | out.At, e = time.Parse(time.RFC3339, at) |
| 176 | if e != nil { |
| 177 | return out, ErrRefused |
| 178 | } |
| 179 | expiry, e := time.Parse(time.RFC3339, expires) |
| 180 | if e != nil || !expiry.After(now) { |
| 181 | return out, ErrRefused |
| 182 | } |
| 183 | if auth != "" { |
| 184 | out.AuthTime, e = time.Parse(time.RFC3339, auth) |
| 185 | if e != nil { |
| 186 | return out, ErrRefused |
| 187 | } |
| 188 | } |
| 189 | address := out.Subject |
| 190 | if out.Method == NativeMethod && !now.Before(out.At.Add(NativeLifetime)) { |
| 191 | return out, ErrRefused |
| 192 | } |
| 193 | if IsHomeDerived(out.Method) { |
| 194 | _, address, e = s.Links.ResolveOn(ctx, q, s.Config.Issuer, out.Subject) |
| 195 | if e != nil { |
| 196 | return out, lookupError(e) |
| 197 | } |
| 198 | } |
| 199 | var active bool |
| 200 | var epoch int64 |
| 201 | if e = q.QueryRowContext(ctx, "SELECT active,session_epoch FROM members WHERE address=?", address).Scan(&active, &epoch); e != nil { |
| 202 | return out, lookupError(e) |
| 203 | } |
| 204 | if !active || out.At.Unix() < epoch { |
| 205 | return out, ErrRefused |
| 206 | } |
| 207 | out.Subject = address |
| 208 | return out, nil |
| 209 | } |
| 210 | func (s *Store) Session(ctx context.Context, token string, now time.Time) (sessions.Session, error) { |
| 211 | return s.session(ctx, s.DB, token, now) |
| 212 | } |
| 213 | func (s *Store) local(ctx context.Context, tx *sql.Tx, token string, now time.Time) (linkstore.Local, error) { |
| 214 | sess, e := s.session(ctx, tx, token, now) |
| 215 | if e != nil || (sess.Method != "magiclink" && sess.Method != "keymail") { |
| 216 | return linkstore.Local{}, ErrRefused |
| 217 | } |
| 218 | high, e := s.clock(ctx, tx, now) |
| 219 | if e != nil { |
| 220 | return linkstore.Local{}, e |
| 221 | } |
| 222 | at := sess.AuthTime |
| 223 | if at.IsZero() { |
| 224 | if sess.Method == "keymail" { |
| 225 | return linkstore.Local{}, ErrRefused |
| 226 | } |
| 227 | at = sess.At |
| 228 | } |
| 229 | if at.After(now) || high-at.Unix() > 300 { |
| 230 | return linkstore.Local{}, ErrRefused |
| 231 | } |
| 232 | id, e := s.account(ctx, tx, sess.Subject) |
| 233 | return linkstore.Local{PersonID: id, SessionToken: token, AuthTime: at}, e |
| 234 | } |
| 235 | func (s *Store) Finish(ctx context.Context, secret, handle, token, init string, now time.Time) (string, string, error) { |
| 236 | var minted string |
| 237 | _, path, e := s.Exchange.FinishAtomic(ctx, secret, handle, "", now, func(tx *sql.Tx, c assertion.Claims, path string) error { |
| 238 | if init != "" { |
| 239 | local, e := s.local(ctx, tx, token, now) |
| 240 | if e != nil { |
| 241 | return e |
| 242 | } |
| 243 | minted, e = s.Links.CompleteOn(ctx, tx, init, local, linkstore.Home{Issuer: c.Issuer, Subject: c.Subject, Nonce: c.Nonce, AuthTime: time.Unix(c.AuthTime, 0)}, now) |
| 244 | return e |
| 245 | } |
| 246 | if path == "/account/home/confirm" { |
| 247 | return ErrRefused |
| 248 | } |
| 249 | id, address, e := s.Links.ResolveOn(ctx, tx, c.Issuer, c.Subject) |
| 250 | if errors.Is(e, linkstore.ErrRefused) { |
| 251 | return ErrUnlinked |
| 252 | } |
| 253 | if e != nil { |
| 254 | return e |
| 255 | } |
| 256 | if token != "" { |
| 257 | current, e := s.session(ctx, tx, token, now) |
| 258 | if e != nil || current.Subject != address { |
| 259 | return ErrRefused |
| 260 | } |
| 261 | } |
| 262 | var epoch int64 |
| 263 | if e = tx.QueryRowContext(ctx, "SELECT session_epoch FROM members WHERE address=? AND active=1", address).Scan(&epoch); e != nil || now.Unix() < epoch { |
| 264 | return ErrRefused |
| 265 | } |
| 266 | var hash string |
| 267 | minted, hash, e = sessions.NewToken() |
| 268 | if e != nil { |
| 269 | return e |
| 270 | } |
| 271 | _, e = tx.ExecContext(ctx, "INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, c.Subject, Method, time.Unix(c.AuthTime, 0).UTC().Format(time.RFC3339), now.UTC().Format(time.RFC3339), now.Add(30*24*time.Hour).UTC().Format(time.RFC3339)) |
| 272 | if e != nil { |
| 273 | return e |
| 274 | } |
| 275 | return s.audit(ctx, tx, id, "oficina_id.signin", now) |
| 276 | }) |
| 277 | if e != nil { |
| 278 | return "", "", e |
| 279 | } |
| 280 | return minted, path, nil |
| 281 | } |
| 282 | func (s *Store) audit(ctx context.Context, tx *sql.Tx, id int64, kind string, now time.Time) error { |
| 283 | _, e := tx.ExecContext(ctx, "INSERT INTO audit_events(actor,kind,record_id,at) VALUES(?,?,?,?)", "local-account:"+strconv.FormatInt(id, 10), kind, strconv.FormatInt(id, 10), now.UTC()) |
| 284 | return e |
| 285 | } |
| 286 | |
| 287 | // NativeSessionOn revalidates the source session using the caller's transaction. |
| 288 | func (s *Store) NativeSessionOn(ctx context.Context, q linkstore.Queryer, hash string, now time.Time) (sessions.Session, error) { |
| 289 | sess, err := s.sessionHash(ctx, q, hash, now) |
| 290 | if err != nil || sess.Method != NativeMethod { |
| 291 | return sessions.Session{}, ErrRefused |
| 292 | } |
| 293 | return sess, nil |
| 294 | } |
| 295 | |
| 296 | // LinkedAddress is the Equipo address the Oficina ID subject is linked to, |
| 297 | // "" when it is linked to none; any other failure is an error. |
| 298 | func (s *Store) LinkedAddress(ctx context.Context, subject string) (string, error) { |
| 299 | _, address, err := s.Links.Resolve(ctx, s.Config.Issuer, subject) |
| 300 | if errors.Is(err, linkstore.ErrRefused) { |
| 301 | return "", nil |
| 302 | } |
| 303 | return address, err |
| 304 | } |
| 305 | |