| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "database/sql/driver" |
| 7 | _ "embed" |
| 8 | "encoding/json" |
| 9 | "log/slog" |
| 10 | "sync" |
| 11 | |
| 12 | "amadan.net/rastrillo/rastrillo/migrate" |
| 13 | ) |
| 14 | |
| 15 | const ( |
| 16 | legacyDiagnosticProfile = "legacy-directory-v1" |
| 17 | legacyDiagnosticMaxRows = 1000 |
| 18 | legacyDiagnosticNameBytes = 256 |
| 19 | legacyDiagnosticSQLBytes = 65536 |
| 20 | ) |
| 21 | |
| 22 | //go:embed diagnostic_profiles/legacy-directory-v1.json |
| 23 | var legacyDiagnosticJSON []byte |
| 24 | |
| 25 | type legacyDiagnosticObject struct{ Type, Name, Table, SQL string } |
| 26 | type legacyDiagnosticResult struct { |
| 27 | status string |
| 28 | occupied bool |
| 29 | } |
| 30 | |
| 31 | var legacyDiagnosticObjects = func() []legacyDiagnosticObject { |
| 32 | var objects []legacyDiagnosticObject |
| 33 | if err := json.Unmarshal(legacyDiagnosticJSON, &objects); err != nil { |
| 34 | panic(err) |
| 35 | } |
| 36 | return objects |
| 37 | }() |
| 38 | |
| 39 | func legacyDiagnosticMigrations() ([]migrate.Migration, bool) { |
| 40 | return uniqueLegacyMigrations(BootSchema.All(), (Runtime{role: "directory"}).Schema().All()) |
| 41 | } |
| 42 | |
| 43 | func uniqueLegacyMigrations(groups ...[]migrate.Migration) ([]migrate.Migration, bool) { |
| 44 | seen := map[string]migrate.Migration{} |
| 45 | var result []migrate.Migration |
| 46 | for _, group := range groups { |
| 47 | for _, m := range group { |
| 48 | if m.Fn != nil || m.ID == "" || m.SQL == "" { |
| 49 | return nil, false |
| 50 | } |
| 51 | if prior, exists := seen[m.ID]; exists { |
| 52 | if prior.SQL != m.SQL { |
| 53 | return nil, false |
| 54 | } |
| 55 | continue |
| 56 | } |
| 57 | seen[m.ID] = m |
| 58 | result = append(result, m) |
| 59 | } |
| 60 | } |
| 61 | return result, len(result) > 0 |
| 62 | } |
| 63 | |
| 64 | func logLegacySchemaDiagnostic(ctx context.Context, d *sql.DB, role string, logger *slog.Logger) { |
| 65 | if role != "directory" { |
| 66 | return |
| 67 | } |
| 68 | result := inspectLegacySchema(ctx, d) |
| 69 | fields := []any{"profile", legacyDiagnosticProfile, "result", result.status} |
| 70 | if result.status == "match" { |
| 71 | fields = append(fields, "legacy_credentials_present", result.occupied) |
| 72 | } |
| 73 | logger.Info("legacy schema diagnostic", fields...) |
| 74 | } |
| 75 | |
| 76 | func inspectLegacySchema(ctx context.Context, d *sql.DB) (result legacyDiagnosticResult) { |
| 77 | result.status = "unavailable" |
| 78 | if ctx == nil || d == nil || len(legacyDiagnosticObjects) == 0 { |
| 79 | return |
| 80 | } |
| 81 | conn, err := d.Conn(ctx) |
| 82 | if err != nil { |
| 83 | return |
| 84 | } |
| 85 | defer conn.Close() |
| 86 | if !beginLegacyDiagnostic(ctx, conn) { |
| 87 | return |
| 88 | } |
| 89 | defer func() { |
| 90 | if !rollbackLegacyDiagnostic(ctx, conn) { |
| 91 | result = legacyDiagnosticResult{status: "unavailable"} |
| 92 | } |
| 93 | }() |
| 94 | result = readLegacySchema(ctx, conn) |
| 95 | return |
| 96 | } |
| 97 | |
| 98 | // legacyDiagnosticAdditive is the serving schema's additive directory sets |
| 99 | // (oficina_directory_operator_http and oficina_directory_team): their ledger |
| 100 | // rows and exactly the objects they create or change are not the historical |
| 101 | // profile's business, and are skipped so that every directory boot does not |
| 102 | // read "mismatch" and hide a true one behind it. Only exact matches are |
| 103 | // skipped; a changed table is still a mismatch. The Team set alters a frozen |
| 104 | // table (memberships gains added_at), so the sets cannot be replayed alone: |
| 105 | // the whole serving schema is replayed beside the frozen one, and an object |
| 106 | // is additive when the serving replay has it and the frozen replay has it |
| 107 | // differently or not at all. If either cannot be replayed, nothing is skipped. |
| 108 | var legacyDiagnosticAdditive = sync.OnceValues(func() (map[string]string, map[string]legacyDiagnosticObject) { |
| 109 | ledger, objects := map[string]string{}, map[string]legacyDiagnosticObject{} |
| 110 | // ServingSchema less Schema: the additive set, without reaching into the |
| 111 | // operator package (TestLegacyDiagnosticCannotExpandAcceptedProfiles). |
| 112 | frozenSet := (Runtime{role: "directory"}).Schema().All() |
| 113 | frozen := map[string]bool{} |
| 114 | for _, m := range frozenSet { |
| 115 | frozen[m.ID] = true |
| 116 | } |
| 117 | serving := (Runtime{role: "directory"}).ServingSchema().All() |
| 118 | added := false |
| 119 | for _, m := range serving { |
| 120 | if !frozen[m.ID] { |
| 121 | ledger[m.ID] = migrate.Checksum(m.SQL) |
| 122 | added = true |
| 123 | } |
| 124 | } |
| 125 | if !added { |
| 126 | return nil, nil |
| 127 | } |
| 128 | before, ok := replayObjects(frozenSet) |
| 129 | if !ok { |
| 130 | return nil, nil |
| 131 | } |
| 132 | after, ok := replayObjects(serving) |
| 133 | if !ok { |
| 134 | return nil, nil |
| 135 | } |
| 136 | for key, o := range after { |
| 137 | if prior, exists := before[key]; !exists || prior != o { |
| 138 | objects[key] = o |
| 139 | } |
| 140 | } |
| 141 | return ledger, objects |
| 142 | }) |
| 143 | |
| 144 | func replayObjects(all []migrate.Migration) (map[string]legacyDiagnosticObject, bool) { |
| 145 | d, err := migrate.Replay(context.Background(), all) |
| 146 | if err != nil { |
| 147 | return nil, false |
| 148 | } |
| 149 | defer d.Close() |
| 150 | rows, err := d.Query("SELECT type,name,tbl_name,coalesce(sql,'') FROM sqlite_schema") |
| 151 | if err != nil { |
| 152 | return nil, false |
| 153 | } |
| 154 | defer rows.Close() |
| 155 | objects := map[string]legacyDiagnosticObject{} |
| 156 | for rows.Next() { |
| 157 | var o legacyDiagnosticObject |
| 158 | if rows.Scan(&o.Type, &o.Name, &o.Table, &o.SQL) != nil { |
| 159 | return nil, false |
| 160 | } |
| 161 | objects[o.Type+"/"+o.Name] = o |
| 162 | } |
| 163 | return objects, rows.Err() == nil |
| 164 | } |
| 165 | |
| 166 | func readLegacySchema(ctx context.Context, conn *sql.Conn) legacyDiagnosticResult { |
| 167 | unavailable := legacyDiagnosticResult{status: "unavailable"} |
| 168 | mismatch := legacyDiagnosticResult{status: "mismatch"} |
| 169 | migrations, ok := legacyDiagnosticMigrations() |
| 170 | if !ok { |
| 171 | return unavailable |
| 172 | } |
| 173 | additiveLedger, additiveObjects := legacyDiagnosticAdditive() |
| 174 | expected := map[string]string{} |
| 175 | for _, m := range migrations { |
| 176 | expected[m.ID] = migrate.Checksum(m.SQL) |
| 177 | } |
| 178 | rows, err := conn.QueryContext(ctx, `SELECT |
| 179 | CASE WHEN typeof(id)='text' AND length(CAST(id AS BLOB))<=256 THEN id END, |
| 180 | CASE WHEN typeof(checksum)='text' AND length(CAST(checksum AS BLOB))=64 THEN checksum END |
| 181 | FROM rastrillo_migrations LIMIT 1001`) |
| 182 | if err != nil { |
| 183 | return unavailable |
| 184 | } |
| 185 | matched, count := true, 0 |
| 186 | for rows.Next() { |
| 187 | count++ |
| 188 | var id, sum sql.NullString |
| 189 | if rows.Scan(&id, &sum) != nil { |
| 190 | rows.Close() |
| 191 | return unavailable |
| 192 | } |
| 193 | if sum.Valid && additiveLedger[id.String] == sum.String && id.Valid { |
| 194 | continue |
| 195 | } |
| 196 | if !id.Valid || !sum.Valid || count > legacyDiagnosticMaxRows || expected[id.String] != sum.String { |
| 197 | matched = false |
| 198 | } |
| 199 | delete(expected, id.String) |
| 200 | } |
| 201 | scanErr, closeErr := rows.Err(), rows.Close() |
| 202 | if scanErr != nil || closeErr != nil || ctx.Err() != nil { |
| 203 | return unavailable |
| 204 | } |
| 205 | if !matched || len(expected) != 0 { |
| 206 | return mismatch |
| 207 | } |
| 208 | objects := map[string]legacyDiagnosticObject{} |
| 209 | for _, object := range legacyDiagnosticObjects { |
| 210 | objects[object.Type+"/"+object.Name] = object |
| 211 | } |
| 212 | rows, err = conn.QueryContext(ctx, `SELECT |
| 213 | CASE WHEN typeof(type)='text' AND length(CAST(type AS BLOB))<=16 THEN type END, |
| 214 | CASE WHEN typeof(name)='text' AND length(CAST(name AS BLOB))<=256 THEN name END, |
| 215 | CASE WHEN typeof(tbl_name)='text' AND length(CAST(tbl_name AS BLOB))<=256 THEN tbl_name END, |
| 216 | CASE WHEN typeof(coalesce(sql,''))='text' AND length(CAST(coalesce(sql,'') AS BLOB))<=65536 THEN coalesce(sql,'') END |
| 217 | FROM sqlite_schema LIMIT 1001`) |
| 218 | if err != nil { |
| 219 | return unavailable |
| 220 | } |
| 221 | count = 0 |
| 222 | for rows.Next() { |
| 223 | count++ |
| 224 | var kind, name, table, statement sql.NullString |
| 225 | if rows.Scan(&kind, &name, &table, &statement) != nil { |
| 226 | rows.Close() |
| 227 | return unavailable |
| 228 | } |
| 229 | object := legacyDiagnosticObject{kind.String, name.String, table.String, statement.String} |
| 230 | key := kind.String + "/" + name.String |
| 231 | if extra, ok := additiveObjects[key]; ok && extra == object && kind.Valid && name.Valid && table.Valid && statement.Valid { |
| 232 | // An object the serving schema changed (memberships) stands in |
| 233 | // for its frozen form, which is then not missing. |
| 234 | delete(objects, key) |
| 235 | continue |
| 236 | } |
| 237 | prior, exists := objects[key] |
| 238 | if !kind.Valid || !name.Valid || !table.Valid || !statement.Valid || count > legacyDiagnosticMaxRows || !exists || prior != object { |
| 239 | matched = false |
| 240 | } |
| 241 | delete(objects, key) |
| 242 | } |
| 243 | scanErr, closeErr = rows.Err(), rows.Close() |
| 244 | if scanErr != nil || closeErr != nil || ctx.Err() != nil { |
| 245 | return unavailable |
| 246 | } |
| 247 | if !matched || len(objects) != 0 { |
| 248 | return mismatch |
| 249 | } |
| 250 | var occupied bool |
| 251 | // Pending challenges and recovery material count too: none is disposable here. |
| 252 | err = conn.QueryRowContext(ctx, `SELECT |
| 253 | EXISTS(SELECT 1 FROM people) OR EXISTS(SELECT 1 FROM signin_links) OR |
| 254 | EXISTS(SELECT 1 FROM passkey_credentials) OR EXISTS(SELECT 1 FROM passkey_challenges) OR |
| 255 | EXISTS(SELECT 1 FROM passkey_pending) OR EXISTS(SELECT 1 FROM passkey_recovery_codes)`).Scan(&occupied) |
| 256 | if err != nil || ctx.Err() != nil { |
| 257 | return unavailable |
| 258 | } |
| 259 | return legacyDiagnosticResult{status: "match", occupied: occupied} |
| 260 | } |
| 261 | |
| 262 | type legacyDiagnosticConnection interface { |
| 263 | ExecContext(context.Context, string, ...any) (sql.Result, error) |
| 264 | Raw(func(any) error) error |
| 265 | } |
| 266 | |
| 267 | func rollbackLegacyDiagnostic(ctx context.Context, conn legacyDiagnosticConnection) bool { |
| 268 | if _, err := conn.ExecContext(context.WithoutCancel(ctx), "ROLLBACK"); err != nil { |
| 269 | conn.Raw(func(any) error { return driver.ErrBadConn }) |
| 270 | return false |
| 271 | } |
| 272 | return true |
| 273 | } |
| 274 | |
| 275 | func beginLegacyDiagnostic(ctx context.Context, conn legacyDiagnosticConnection) bool { |
| 276 | if _, err := conn.ExecContext(ctx, "BEGIN"); err != nil { |
| 277 | // The driver can report cancellation after SQLite has opened the transaction. |
| 278 | conn.Raw(func(any) error { return driver.ErrBadConn }) |
| 279 | return false |
| 280 | } |
| 281 | return true |
| 282 | } |
| 283 | |