| 1 | package linkstore |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/hmac" |
| 7 | "database/sql" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "io" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/home/handoff" |
| 14 | ) |
| 15 | |
| 16 | type flow struct { |
| 17 | Started int64 `json:"started,omitempty"` |
| 18 | PersonBinding string `json:"person_binding"` |
| 19 | Version int `json:"v"` |
| 20 | PersonID int64 `json:"person"` |
| 21 | SessionHash string `json:"session"` |
| 22 | LocalAuth int64 `json:"local_auth"` |
| 23 | Issuer string `json:"issuer"` |
| 24 | NonceHash string `json:"nonce,omitempty"` |
| 25 | Subject string `json:"subject,omitempty"` |
| 26 | HomeAuth int64 `json:"home_auth,omitempty"` |
| 27 | ReturnPath string `json:"return"` |
| 28 | Expires int64 `json:"expires"` |
| 29 | } |
| 30 | |
| 31 | func (s *Store) purpose(stage, id string) string { |
| 32 | return "identity-link/v1/" + stage + "/" + id + "/" + s.origin |
| 33 | } |
| 34 | func (s *Store) put(ctx context.Context, tx *sql.Tx, stage, id string, f flow) error { |
| 35 | raw, err := json.Marshal(f) |
| 36 | if err != nil { |
| 37 | return ErrStorage |
| 38 | } |
| 39 | sealed, err := s.seal.Seal(s.purpose(stage, id), raw) |
| 40 | if err != nil { |
| 41 | return ErrStorage |
| 42 | } |
| 43 | _, err = tx.ExecContext(ctx, "INSERT INTO home_link_flows (id_hash, stage, expires_at, payload) VALUES (?, ?, ?, ?)", id, stage, f.Expires, sealed) |
| 44 | if err != nil { |
| 45 | return ErrStorage |
| 46 | } |
| 47 | return nil |
| 48 | } |
| 49 | |
| 50 | // load deletes a presented row before interpreting it when consume is true. |
| 51 | // Callers commit refusals, so a rejected conflict or mixed-up browser cannot |
| 52 | // reuse its proof. Storage failures roll back and never install a mapping. |
| 53 | func (s *Store) load(ctx context.Context, tx *sql.Tx, stage, id string, high int64, consume bool) (flow, error) { |
| 54 | var raw []byte |
| 55 | var expires int64 |
| 56 | err := tx.QueryRowContext(ctx, "SELECT expires_at, payload FROM home_link_flows WHERE id_hash = ? AND stage = ?", id, stage).Scan(&expires, &raw) |
| 57 | if errors.Is(err, sql.ErrNoRows) { |
| 58 | return flow{}, ErrRefused |
| 59 | } |
| 60 | if err != nil { |
| 61 | return flow{}, ErrStorage |
| 62 | } |
| 63 | if consume { |
| 64 | if _, err := tx.ExecContext(ctx, "DELETE FROM home_link_flows WHERE id_hash = ? AND stage = ?", id, stage); err != nil { |
| 65 | return flow{}, ErrStorage |
| 66 | } |
| 67 | } |
| 68 | if len(raw) > 8192 || expires <= high { |
| 69 | return flow{}, ErrRefused |
| 70 | } |
| 71 | opened, err := s.seal.Open(s.purpose(stage, id), raw) |
| 72 | if err != nil { |
| 73 | return flow{}, ErrRefused |
| 74 | } |
| 75 | var f flow |
| 76 | dec := json.NewDecoder(bytes.NewReader(opened)) |
| 77 | dec.DisallowUnknownFields() |
| 78 | if dec.Decode(&f) != nil || dec.Decode(new(any)) != io.EOF { |
| 79 | return flow{}, ErrRefused |
| 80 | } |
| 81 | if f.Version != 1 || f.Expires != expires || f.Issuer != s.issuer || !handoff.SafePath(f.ReturnPath) { |
| 82 | return flow{}, ErrRefused |
| 83 | } |
| 84 | return f, nil |
| 85 | } |
| 86 | func (s *Store) matches(f flow, local Local, now, high int64) bool { |
| 87 | return validLocal(local, now, high) && f.PersonID == local.PersonID && f.SessionHash == hash(local.SessionToken) && f.LocalAuth == local.AuthTime.Unix() && fresh(f.LocalAuth, now, high) |
| 88 | } |
| 89 | func (s *Store) currentBinding(ctx context.Context, tx *sql.Tx, id int64) (string, error) { |
| 90 | label, err := s.lookup(ctx, tx, id) |
| 91 | if errors.Is(err, sql.ErrNoRows) { |
| 92 | return "", nil |
| 93 | } |
| 94 | if err != nil { |
| 95 | return "", ErrStorage |
| 96 | } |
| 97 | if label == "" { |
| 98 | return "", nil |
| 99 | } |
| 100 | return s.personBinding(id, label), nil |
| 101 | } |
| 102 | |
| 103 | // Start is called only by an explicit same-origin local-account link POST. |
| 104 | // The returned secret belongs in a host-only Secure/HttpOnly/Lax cookie. |
| 105 | func (s *Store) Start(ctx context.Context, local Local, returnPath string, now time.Time) (string, error) { |
| 106 | return s.start(ctx, local, returnPath, now, false) |
| 107 | } |
| 108 | |
| 109 | // StartFresh requires Home authentication at or after this initiation. |
| 110 | func (s *Store) StartFresh(ctx context.Context, local Local, returnPath string, now time.Time) (string, error) { |
| 111 | return s.start(ctx, local, returnPath, now, true) |
| 112 | } |
| 113 | func (s *Store) start(ctx context.Context, local Local, returnPath string, now time.Time, fresh bool) (string, error) { |
| 114 | tx, _, err := s.begin(ctx, now) |
| 115 | if err != nil { |
| 116 | return "", err |
| 117 | } |
| 118 | defer tx.Rollback() |
| 119 | result, err := s.startOn(ctx, tx, local, returnPath, now, fresh) |
| 120 | if err != nil && !errors.Is(err, ErrRefused) { |
| 121 | return "", err |
| 122 | } |
| 123 | if e := commit(tx); e != nil { |
| 124 | return "", e |
| 125 | } |
| 126 | return result, err |
| 127 | } |
| 128 | |
| 129 | // StartFreshOn creates fresh linking intent inside the caller's transaction. |
| 130 | func (s *Store) StartFreshOn(ctx context.Context, tx *sql.Tx, local Local, returnPath string, now time.Time) (string, error) { |
| 131 | return s.startOn(ctx, tx, local, returnPath, now, true) |
| 132 | } |
| 133 | func (s *Store) startOn(ctx context.Context, tx *sql.Tx, local Local, returnPath string, now time.Time, fresh bool) (string, error) { |
| 134 | high, err := s.clockOn(ctx, tx, now) |
| 135 | if err != nil { |
| 136 | return "", err |
| 137 | } |
| 138 | if err = sweep(ctx, tx, high); err != nil { |
| 139 | return "", err |
| 140 | } |
| 141 | if !validLocal(local, now.Unix(), high) { |
| 142 | return "", ErrRefused |
| 143 | } |
| 144 | binding, err := s.currentBinding(ctx, tx, local.PersonID) |
| 145 | if err != nil { |
| 146 | return "", err |
| 147 | } |
| 148 | if binding == "" { |
| 149 | return "", ErrRefused |
| 150 | } |
| 151 | var count int |
| 152 | if err := tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM home_link_flows").Scan(&count); err != nil { |
| 153 | return "", ErrStorage |
| 154 | } |
| 155 | if count >= maxFlows { |
| 156 | return "", ErrRefused |
| 157 | } |
| 158 | secret, err := newSecret() |
| 159 | if err != nil { |
| 160 | return "", err |
| 161 | } |
| 162 | expires := min(now.Unix()+maxAge, local.AuthTime.Unix()+maxAge) |
| 163 | if expires <= high { |
| 164 | return "", ErrRefused |
| 165 | } |
| 166 | f := flow{PersonBinding: binding, Version: 1, PersonID: local.PersonID, SessionHash: hash(local.SessionToken), LocalAuth: local.AuthTime.Unix(), Issuer: s.issuer, ReturnPath: safePath(returnPath), Expires: expires} |
| 167 | if fresh { |
| 168 | f.Started = now.Unix() |
| 169 | } |
| 170 | if err := s.put(ctx, tx, "init", hash(secret), f); err != nil { |
| 171 | return "", err |
| 172 | } |
| 173 | return secret, nil |
| 174 | } |
| 175 | |
| 176 | // BindNonce is the shared consumer's start hook. It accepts one generated |
| 177 | // nonce exactly once, before that consumer sets its cookie or redirects. |
| 178 | func (s *Store) BindNonce(ctx context.Context, secret string, local Local, nonce string, now time.Time) error { |
| 179 | id, ok := secretHash(secret) |
| 180 | if !ok { |
| 181 | return ErrRefused |
| 182 | } |
| 183 | tx, high, err := s.begin(ctx, now) |
| 184 | if err != nil { |
| 185 | return err |
| 186 | } |
| 187 | defer tx.Rollback() |
| 188 | f, err := s.load(ctx, tx, "init", id, high, true) |
| 189 | if errors.Is(err, ErrRefused) { |
| 190 | return refuse(tx) |
| 191 | } |
| 192 | if err != nil { |
| 193 | return err |
| 194 | } |
| 195 | if !s.matches(f, local, now.Unix(), high) || !handoff.ValidNonce(nonce) || f.NonceHash != "" { |
| 196 | return refuse(tx) |
| 197 | } |
| 198 | binding, err := s.currentBinding(ctx, tx, local.PersonID) |
| 199 | if err != nil { |
| 200 | return err |
| 201 | } |
| 202 | if binding == "" || !hmac.Equal([]byte(binding), []byte(f.PersonBinding)) { |
| 203 | return refuse(tx) |
| 204 | } |
| 205 | f.NonceHash = hash(nonce) |
| 206 | if err := s.put(ctx, tx, "init", id, f); err != nil { |
| 207 | return err |
| 208 | } |
| 209 | return commit(tx) |
| 210 | } |
| 211 | |
| 212 | // Complete consumes the initiation after the shared consumer has consumed and |
| 213 | // verified the Home assertion. It keeps the local Docs session intact. |
| 214 | func (s *Store) Complete(ctx context.Context, secret string, local Local, home Home, now time.Time) (string, error) { |
| 215 | tx, _, err := s.begin(ctx, now) |
| 216 | if err != nil { |
| 217 | return "", err |
| 218 | } |
| 219 | defer tx.Rollback() |
| 220 | result, err := s.CompleteOn(ctx, tx, secret, local, home, now) |
| 221 | if err != nil && !errors.Is(err, ErrRefused) { |
| 222 | return "", err |
| 223 | } |
| 224 | if e := commit(tx); e != nil { |
| 225 | return "", e |
| 226 | } |
| 227 | return result, err |
| 228 | } |
| 229 | |
| 230 | // CompleteOn uses the caller-owned writer transaction; it never commits. |
| 231 | func (s *Store) CompleteOn(ctx context.Context, tx *sql.Tx, secret string, local Local, home Home, now time.Time) (string, error) { |
| 232 | id, ok := secretHash(secret) |
| 233 | if !ok { |
| 234 | return "", ErrRefused |
| 235 | } |
| 236 | high, err := s.clockOn(ctx, tx, now) |
| 237 | if err != nil { |
| 238 | return "", err |
| 239 | } |
| 240 | f, err := s.load(ctx, tx, "init", id, high, true) |
| 241 | if errors.Is(err, ErrRefused) { |
| 242 | return "", ErrRefused |
| 243 | } |
| 244 | if err != nil { |
| 245 | return "", err |
| 246 | } |
| 247 | if !s.matches(f, local, now.Unix(), high) || !handoff.ValidNonce(home.Nonce) || f.NonceHash != hash(home.Nonce) || home.Issuer != s.issuer || !validSubject(home.Subject) || !fresh(home.AuthTime.Unix(), now.Unix(), high) || home.AuthTime.Unix() < f.Started { |
| 248 | return "", ErrRefused |
| 249 | } |
| 250 | binding, err := s.currentBinding(ctx, tx, local.PersonID) |
| 251 | if err != nil { |
| 252 | return "", err |
| 253 | } |
| 254 | if binding == "" || !hmac.Equal([]byte(binding), []byte(f.PersonBinding)) { |
| 255 | return "", ErrRefused |
| 256 | } |
| 257 | pending, err := newSecret() |
| 258 | if err != nil { |
| 259 | return "", err |
| 260 | } |
| 261 | f.Subject, f.HomeAuth = home.Subject, home.AuthTime.Unix() |
| 262 | f.Expires = min(f.Expires, f.HomeAuth+maxAge) |
| 263 | if f.Expires <= high { |
| 264 | return "", ErrRefused |
| 265 | } |
| 266 | if err := s.put(ctx, tx, "pending", hash(pending), f); err != nil { |
| 267 | return "", err |
| 268 | } |
| 269 | return pending, nil |
| 270 | } |
| 271 | |
| 272 | func validPending(f flow, now, high int64) bool { |
| 273 | return f.NonceHash != "" && validSubject(f.Subject) && fresh(f.HomeAuth, now, high) |
| 274 | } |
| 275 | func pendingView(f flow) Pending { |
| 276 | return Pending{PersonID: f.PersonID, ReturnPath: f.ReturnPath, HomeAuthTime: time.Unix(f.HomeAuth, 0)} |
| 277 | } |
| 278 | |
| 279 | // Pending reads a still-valid continuation for its current local session. |
| 280 | // Invalid presented state is consumed; reading valid state creates no link. |
| 281 | func (s *Store) Pending(ctx context.Context, secret string, local Local, now time.Time) (Pending, error) { |
| 282 | id, ok := secretHash(secret) |
| 283 | if !ok { |
| 284 | return Pending{}, ErrRefused |
| 285 | } |
| 286 | tx, high, err := s.begin(ctx, now) |
| 287 | if err != nil { |
| 288 | return Pending{}, err |
| 289 | } |
| 290 | defer tx.Rollback() |
| 291 | f, err := s.load(ctx, tx, "pending", id, high, true) |
| 292 | if errors.Is(err, ErrRefused) { |
| 293 | return Pending{}, refuse(tx) |
| 294 | } |
| 295 | if err != nil { |
| 296 | return Pending{}, err |
| 297 | } |
| 298 | if !s.matches(f, local, now.Unix(), high) || !validPending(f, now.Unix(), high) { |
| 299 | return Pending{}, refuse(tx) |
| 300 | } |
| 301 | binding, err := s.currentBinding(ctx, tx, local.PersonID) |
| 302 | if err != nil { |
| 303 | return Pending{}, err |
| 304 | } |
| 305 | if binding == "" || !hmac.Equal([]byte(binding), []byte(f.PersonBinding)) { |
| 306 | return Pending{}, refuse(tx) |
| 307 | } |
| 308 | if err := s.put(ctx, tx, "pending", id, f); err != nil { |
| 309 | return Pending{}, err |
| 310 | } |
| 311 | if err := commit(tx); err != nil { |
| 312 | return Pending{}, err |
| 313 | } |
| 314 | return pendingView(f), nil |
| 315 | } |
| 316 | |
| 317 | // Confirm requires an explicit same-origin POST. The proof deletion and unique |
| 318 | // mapping write commit together. A separate proof for the same mapping is |
| 319 | // idempotent; a reused cookie or conflicting mapping is consumed and refused. |
| 320 | func (s *Store) Confirm(ctx context.Context, secret string, local Local, now time.Time) (Pending, error) { |
| 321 | tx, _, err := s.begin(ctx, now) |
| 322 | if err != nil { |
| 323 | return Pending{}, err |
| 324 | } |
| 325 | defer tx.Rollback() |
| 326 | result, err := s.ConfirmOn(ctx, tx, secret, local, now) |
| 327 | if err != nil && !errors.Is(err, ErrRefused) { |
| 328 | return Pending{}, err |
| 329 | } |
| 330 | if e := commit(tx); e != nil { |
| 331 | return Pending{}, e |
| 332 | } |
| 333 | return result, err |
| 334 | } |
| 335 | |
| 336 | // ConfirmOn uses the caller-owned writer transaction; it never commits. |
| 337 | func (s *Store) ConfirmOn(ctx context.Context, tx *sql.Tx, secret string, local Local, now time.Time) (Pending, error) { |
| 338 | id, ok := secretHash(secret) |
| 339 | if !ok { |
| 340 | return Pending{}, ErrRefused |
| 341 | } |
| 342 | high, err := s.clockOn(ctx, tx, now) |
| 343 | if err != nil { |
| 344 | return Pending{}, err |
| 345 | } |
| 346 | f, err := s.load(ctx, tx, "pending", id, high, true) |
| 347 | if errors.Is(err, ErrRefused) { |
| 348 | return Pending{}, ErrRefused |
| 349 | } |
| 350 | if err != nil { |
| 351 | return Pending{}, err |
| 352 | } |
| 353 | if !s.matches(f, local, now.Unix(), high) || !validPending(f, now.Unix(), high) { |
| 354 | return Pending{}, ErrRefused |
| 355 | } |
| 356 | binding, err := s.currentBinding(ctx, tx, local.PersonID) |
| 357 | if err != nil { |
| 358 | return Pending{}, err |
| 359 | } |
| 360 | if binding == "" || !hmac.Equal([]byte(binding), []byte(f.PersonBinding)) { |
| 361 | return Pending{}, ErrRefused |
| 362 | } |
| 363 | _, err = tx.ExecContext(ctx, "INSERT INTO home_identity_links (issuer, subject, person_id, person_binding) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", s.issuer, f.Subject, f.PersonID, f.PersonBinding) |
| 364 | if err != nil { |
| 365 | return Pending{}, ErrStorage |
| 366 | } |
| 367 | var person int64 |
| 368 | var storedBinding string |
| 369 | err = tx.QueryRowContext(ctx, "SELECT person_id, person_binding FROM home_identity_links WHERE issuer = ? AND subject = ?", s.issuer, f.Subject).Scan(&person, &storedBinding) |
| 370 | if errors.Is(err, sql.ErrNoRows) { |
| 371 | return Pending{}, ErrRefused |
| 372 | } |
| 373 | if err != nil { |
| 374 | return Pending{}, ErrStorage |
| 375 | } |
| 376 | if person != f.PersonID || !hmac.Equal([]byte(storedBinding), []byte(f.PersonBinding)) { |
| 377 | return Pending{}, ErrRefused |
| 378 | } |
| 379 | return pendingView(f), nil |
| 380 | } |
| 381 | |
| 382 | func (s *Store) clockOn(ctx context.Context, tx *sql.Tx, now time.Time) (int64, error) { |
| 383 | if _, err := tx.ExecContext(ctx, "UPDATE home_link_clock SET high_water=MAX(high_water,?) WHERE id=1", now.Unix()); err != nil { |
| 384 | return 0, ErrStorage |
| 385 | } |
| 386 | var high int64 |
| 387 | if err := tx.QueryRowContext(ctx, "SELECT high_water FROM home_link_clock WHERE id=1").Scan(&high); err != nil { |
| 388 | return 0, ErrStorage |
| 389 | } |
| 390 | if now.Unix() < high-30 { |
| 391 | return 0, ErrRefused |
| 392 | } |
| 393 | return high, nil |
| 394 | } |
| 395 | |