| 1 | // Package linkstore binds an existing local person to an independently verified |
| 2 | // Home identity. It creates no people, sessions, membership or document grants. |
| 3 | package linkstore |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/hmac" |
| 8 | "crypto/rand" |
| 9 | "crypto/sha256" |
| 10 | "database/sql" |
| 11 | "embed" |
| 12 | "encoding/base64" |
| 13 | "encoding/binary" |
| 14 | "encoding/hex" |
| 15 | "errors" |
| 16 | "net/url" |
| 17 | "strings" |
| 18 | "time" |
| 19 | "unicode/utf8" |
| 20 | |
| 21 | "amadan.net/oficina/home/handoff" |
| 22 | "amadan.net/oficina/home/handoff/seal" |
| 23 | ) |
| 24 | |
| 25 | //go:embed migrations/*.sql |
| 26 | var migrations embed.FS |
| 27 | |
| 28 | // Migrations must be applied before construction. |
| 29 | var Migrations = migrations |
| 30 | |
| 31 | const SchemaNamespace = "oficina_connect_link" |
| 32 | |
| 33 | var ( |
| 34 | ErrRefused = errors.New("home link: refused") |
| 35 | ErrStorage = errors.New("home link: storage unavailable") |
| 36 | ) |
| 37 | |
| 38 | const maxFlows = 10000 |
| 39 | const maxAge = 300 |
| 40 | |
| 41 | // Local is supplied only after the caller verifies the actual local session |
| 42 | // and its method-aware authentication time. Home assertions cannot supply it. |
| 43 | // SessionToken is the actual cookie value, never a subject or a minted alias. |
| 44 | type Local struct { |
| 45 | PersonID int64 |
| 46 | SessionToken string |
| 47 | AuthTime time.Time |
| 48 | } |
| 49 | |
| 50 | // Home contains already verified, consumed shared-handoff claims. The caller |
| 51 | // must not construct it from query parameters or an unverified assertion. |
| 52 | type Home struct { |
| 53 | Issuer, Subject, Nonce string |
| 54 | AuthTime time.Time |
| 55 | } |
| 56 | |
| 57 | // Pending is safe server-side continuation state, not an authentication token. |
| 58 | type Pending struct { |
| 59 | PersonID int64 |
| 60 | ReturnPath string |
| 61 | HomeAuthTime time.Time |
| 62 | } |
| 63 | |
| 64 | type Store struct { |
| 65 | db *sql.DB |
| 66 | seal *seal.Sealer |
| 67 | origin, issuer string |
| 68 | lookup LookupPerson |
| 69 | bindingKey []byte |
| 70 | namespace string |
| 71 | } |
| 72 | |
| 73 | // New uses a dedicated handoff/storage DEK, never an application content key. |
| 74 | // Apply Schema first, then call Sweep at boot before accepting requests. |
| 75 | func New(db *sql.DB, dek []byte, origin, issuer, namespace string, lookup LookupPerson) (*Store, error) { |
| 76 | if lookup == nil || db == nil || !validOrigin(origin) || !validOrigin(issuer) { |
| 77 | return nil, ErrRefused |
| 78 | } |
| 79 | sealer, err := seal.New(dek, namespace) |
| 80 | if err != nil { |
| 81 | return nil, ErrRefused |
| 82 | } |
| 83 | return &Store{db: db, seal: sealer, origin: origin, issuer: issuer, lookup: lookup, bindingKey: append([]byte(nil), dek...), namespace: namespace}, nil |
| 84 | } |
| 85 | |
| 86 | func validOrigin(v string) bool { |
| 87 | u, err := url.Parse(v) |
| 88 | return err == nil && len(v) <= 2048 && u.Scheme == "https" && u.Host != "" && u.Hostname() != "" && u.User == nil && u.Path == "" && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && u.Opaque == "" && u.String() == v && !strings.ContainsAny(v, "\\\r\n\t ") |
| 89 | } |
| 90 | |
| 91 | func hash(v string) string { sum := sha256.Sum256([]byte(v)); return hex.EncodeToString(sum[:]) } |
| 92 | func secretHash(v string) (string, bool) { |
| 93 | if len(v) != 43 { |
| 94 | return "", false |
| 95 | } |
| 96 | b, err := base64.RawURLEncoding.Strict().DecodeString(v) |
| 97 | return hash(v), err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == v |
| 98 | } |
| 99 | func newSecret() (string, error) { |
| 100 | b := make([]byte, 32) |
| 101 | if _, err := rand.Read(b); err != nil { |
| 102 | return "", ErrStorage |
| 103 | } |
| 104 | return base64.RawURLEncoding.EncodeToString(b), nil |
| 105 | } |
| 106 | func fresh(at int64, now, high int64) bool { return at > 0 && at <= now && high-at <= maxAge } |
| 107 | func validLocal(local Local, now, high int64) bool { |
| 108 | return local.PersonID > 0 && local.SessionToken != "" && len(local.SessionToken) <= 4096 && fresh(local.AuthTime.Unix(), now, high) |
| 109 | } |
| 110 | func validSubject(v string) bool { |
| 111 | if v == "" || len(v) > 512 || !utf8.ValidString(v) { |
| 112 | return false |
| 113 | } |
| 114 | for _, r := range v { |
| 115 | if r <= 32 || r == 127 { |
| 116 | return false |
| 117 | } |
| 118 | } |
| 119 | return true |
| 120 | } |
| 121 | |
| 122 | // begin obtains the write lock before any reads, including capacity checks. |
| 123 | // A persisted clock prevents stale evidence becoming fresh after a restart or |
| 124 | // a clock rollback. Match the shared handoff's 30-second rollback tolerance. |
| 125 | func (s *Store) begin(ctx context.Context, now time.Time) (*sql.Tx, int64, error) { |
| 126 | if now.Unix() <= 0 { |
| 127 | return nil, 0, ErrRefused |
| 128 | } |
| 129 | tx, err := s.db.BeginTx(ctx, nil) |
| 130 | if err != nil { |
| 131 | return nil, 0, ErrStorage |
| 132 | } |
| 133 | if _, err = tx.ExecContext(ctx, "UPDATE home_link_clock SET high_water = MAX(high_water, ?) WHERE id = 1", now.Unix()); err != nil { |
| 134 | tx.Rollback() |
| 135 | return nil, 0, ErrStorage |
| 136 | } |
| 137 | var high int64 |
| 138 | if err = tx.QueryRowContext(ctx, "SELECT high_water FROM home_link_clock WHERE id = 1").Scan(&high); err != nil { |
| 139 | tx.Rollback() |
| 140 | return nil, 0, ErrStorage |
| 141 | } |
| 142 | if now.Unix() < high-30 { |
| 143 | tx.Rollback() |
| 144 | return nil, 0, ErrRefused |
| 145 | } |
| 146 | return tx, high, nil |
| 147 | } |
| 148 | func refuse(tx *sql.Tx) error { |
| 149 | if err := tx.Commit(); err != nil { |
| 150 | return ErrStorage |
| 151 | } |
| 152 | return ErrRefused |
| 153 | } |
| 154 | func commit(tx *sql.Tx) error { |
| 155 | if err := tx.Commit(); err != nil { |
| 156 | return ErrStorage |
| 157 | } |
| 158 | return nil |
| 159 | } |
| 160 | func sweep(ctx context.Context, tx *sql.Tx, high int64) error { |
| 161 | for _, table := range []string{"home_link_flows", "home_choice_proofs"} { |
| 162 | if _, err := tx.ExecContext(ctx, "DELETE FROM "+table+" WHERE expires_at <= ?", high); err != nil { |
| 163 | return ErrStorage |
| 164 | } |
| 165 | } |
| 166 | return nil |
| 167 | } |
| 168 | func (s *Store) Sweep(ctx context.Context, now time.Time) error { |
| 169 | tx, high, err := s.begin(ctx, now) |
| 170 | if err != nil { |
| 171 | return err |
| 172 | } |
| 173 | defer tx.Rollback() |
| 174 | if err := sweep(ctx, tx, high); err != nil { |
| 175 | return err |
| 176 | } |
| 177 | return commit(tx) |
| 178 | } |
| 179 | |
| 180 | // Resolve reads the current existing person, never EnsurePerson or a cached |
| 181 | // address. A deleted or unlinked person is refused without creating anything. |
| 182 | func (s *Store) Resolve(ctx context.Context, issuer, subject string) (int64, string, error) { |
| 183 | return s.ResolveOn(ctx, s.db, issuer, subject) |
| 184 | } |
| 185 | |
| 186 | // ResolveOn repeats the complete identity check on the caller's connection. |
| 187 | // A transaction remains caller-owned. LookupPerson must also use q, so this |
| 188 | // never opens another SQL connection while a caller holds SQLite's writer. |
| 189 | func (s *Store) ResolveOn(ctx context.Context, q Queryer, issuer, subject string) (int64, string, error) { |
| 190 | if q == nil || issuer != s.issuer || !validSubject(subject) { |
| 191 | return 0, "", ErrRefused |
| 192 | } |
| 193 | var id int64 |
| 194 | var address, binding string |
| 195 | err := q.QueryRowContext(ctx, `SELECT person_id, person_binding FROM home_identity_links WHERE issuer = ? AND subject = ?`, issuer, subject).Scan(&id, &binding) |
| 196 | if errors.Is(err, sql.ErrNoRows) { |
| 197 | return 0, "", ErrRefused |
| 198 | } |
| 199 | if err != nil { |
| 200 | return 0, "", ErrStorage |
| 201 | } |
| 202 | address, err = s.lookup(ctx, q, id) |
| 203 | if errors.Is(err, sql.ErrNoRows) { |
| 204 | return 0, "", ErrRefused |
| 205 | } |
| 206 | if err != nil { |
| 207 | return 0, "", ErrStorage |
| 208 | } |
| 209 | if id <= 0 || address == "" || !hmac.Equal([]byte(binding), []byte(s.personBinding(id, address))) { |
| 210 | return 0, "", ErrRefused |
| 211 | } |
| 212 | return id, address, nil |
| 213 | } |
| 214 | |
| 215 | // Linked reports whether the person has a stored link to an identity at |
| 216 | // this issuer, whichever way the current session signed in. It is one |
| 217 | // lookup on the UNIQUE (issuer, person_id) index, cheap enough for every |
| 218 | // page that draws the account menu. |
| 219 | func (s *Store) Linked(ctx context.Context, person int64) (bool, error) { |
| 220 | if person <= 0 { |
| 221 | return false, nil |
| 222 | } |
| 223 | var one int |
| 224 | err := s.db.QueryRowContext(ctx, "SELECT 1 FROM home_identity_links WHERE issuer = ? AND person_id = ?", s.issuer, person).Scan(&one) |
| 225 | if errors.Is(err, sql.ErrNoRows) { |
| 226 | return false, nil |
| 227 | } |
| 228 | if err != nil { |
| 229 | return false, ErrStorage |
| 230 | } |
| 231 | return true, nil |
| 232 | } |
| 233 | |
| 234 | // Adopt records a link an app already holds in its own table, for a one-time |
| 235 | // move onto this one. The row is the row Confirm would write for the same |
| 236 | // person and subject: its person binding is computed here, from the address |
| 237 | // LookupPerson returns for personID inside tx, so the address is hashed under |
| 238 | // the key and never written. It proves nothing about the subject; the caller |
| 239 | // vouches that its own table bound this person to it after an explicit link. |
| 240 | // |
| 241 | // tx must be a transaction on the Store's database. Adopt never commits or |
| 242 | // rolls it back, so an app can carry every row and retire its old table in |
| 243 | // one transaction. A link already stored for the same person and subject |
| 244 | // with a matching binding is not an error. ErrRefused means nothing was |
| 245 | // written: a foreign issuer, an invalid subject, a person LookupPerson does |
| 246 | // not return (missing or not admitted now, so the link would not resolve |
| 247 | // anyway), the subject linked to another person, the person linked under |
| 248 | // another subject, or a stored row whose binding does not match (unbound or |
| 249 | // for an old address; Adopt never repairs one). ErrStorage means tx should |
| 250 | // be rolled back. Adopt does not consult Config.HomeOnly: an app with |
| 251 | // Home-only people keeps their subjects disjoint from links itself. |
| 252 | func (s *Store) Adopt(ctx context.Context, tx *sql.Tx, issuer, subject string, personID int64) error { |
| 253 | if tx == nil || issuer != s.issuer || !validSubject(subject) || personID <= 0 { |
| 254 | return ErrRefused |
| 255 | } |
| 256 | binding, err := s.currentBinding(ctx, tx, personID) |
| 257 | if err != nil { |
| 258 | return err |
| 259 | } |
| 260 | if binding == "" { |
| 261 | return ErrRefused |
| 262 | } |
| 263 | _, err = tx.ExecContext(ctx, "INSERT INTO home_identity_links (issuer, subject, person_id, person_binding) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", s.issuer, subject, personID, binding) |
| 264 | if err != nil { |
| 265 | return ErrStorage |
| 266 | } |
| 267 | var person int64 |
| 268 | var stored string |
| 269 | err = tx.QueryRowContext(ctx, "SELECT person_id, person_binding FROM home_identity_links WHERE issuer = ? AND subject = ?", s.issuer, subject).Scan(&person, &stored) |
| 270 | if errors.Is(err, sql.ErrNoRows) { |
| 271 | return ErrRefused |
| 272 | } |
| 273 | if err != nil { |
| 274 | return ErrStorage |
| 275 | } |
| 276 | if person != personID || !hmac.Equal([]byte(stored), []byte(binding)) { |
| 277 | return ErrRefused |
| 278 | } |
| 279 | return nil |
| 280 | } |
| 281 | |
| 282 | func safePath(v string) string { |
| 283 | if handoff.SafePath(v) { |
| 284 | return v |
| 285 | } |
| 286 | return "/" |
| 287 | } |
| 288 | |
| 289 | // Queryer permits lookups inside the same transaction as link writes. |
| 290 | type Queryer interface { |
| 291 | QueryRowContext(context.Context, string, ...any) *sql.Row |
| 292 | } |
| 293 | |
| 294 | // LookupPerson returns the canonical verified local address, never a display name. |
| 295 | // IDs must never be reused; deletion must remove links in the same transaction. It must never |
| 296 | // create one, and must use q rather than opening a separate transaction. |
| 297 | // Missing or currently inadmissible people return sql.ErrNoRows. |
| 298 | type LookupPerson func(ctx context.Context, q Queryer, id int64) (string, error) |
| 299 | |
| 300 | // personBinding prevents a stale numeric link from resolving a different address. |
| 301 | // Length-prefixed fields keep the namespace, origin, ID and address unambiguous. |
| 302 | func (s *Store) personBinding(id int64, address string) string { |
| 303 | m := hmac.New(sha256.New, s.bindingKey) |
| 304 | for _, field := range []string{"home-connect/person-binding/v1", s.namespace, s.origin, s.issuer} { |
| 305 | _ = binary.Write(m, binary.BigEndian, uint64(len(field))) |
| 306 | _, _ = m.Write([]byte(field)) |
| 307 | } |
| 308 | _ = binary.Write(m, binary.BigEndian, id) |
| 309 | _ = binary.Write(m, binary.BigEndian, uint64(len(address))) |
| 310 | _, _ = m.Write([]byte(address)) |
| 311 | return hex.EncodeToString(m.Sum(nil)) |
| 312 | } |
| 313 | |