|
| 1 | +package db |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + |
| 6 | + "github.com/juanfont/headscale/hscontrol/types" |
| 7 | + "gorm.io/gorm" |
| 8 | +) |
| 9 | + |
| 10 | +// migrateToCredentials backfills the unified credentials table from the four |
| 11 | +// per-kind tables and drops them. Pre-auth keys are migrated first preserving |
| 12 | +// their ids so nodes.auth_key_id stays valid; the nodes FK is then retargeted to |
| 13 | +// credentials(id). Runs with foreign keys enabled on SQLite (per runMigrations), |
| 14 | +// so the steps are ordered to never leave a dangling reference. |
| 15 | +func migrateToCredentials(tx *gorm.DB) error { |
| 16 | + // Clear node references to legacy plaintext pre-auth keys (empty prefix); |
| 17 | + // these are not migrated, so a node pointing at one would dangle. |
| 18 | + err := tx.Exec(`UPDATE nodes SET auth_key_id = NULL |
| 19 | +WHERE auth_key_id IN (SELECT id FROM pre_auth_keys WHERE prefix IS NULL OR prefix = '')`).Error |
| 20 | + if err != nil { |
| 21 | + return fmt.Errorf("clearing plaintext auth_key references: %w", err) |
| 22 | + } |
| 23 | + |
| 24 | + // Pre-auth keys first, preserving ids so nodes.auth_key_id stays valid. |
| 25 | + err = tx.Exec(`INSERT INTO credentials |
| 26 | + (id, kind, identifier, hash, user_id, description, reusable, ephemeral, used, tags, expiration, revoked, created_at) |
| 27 | +SELECT id, ?, prefix, hash, user_id, description, reusable, ephemeral, used, tags, expiration, revoked, created_at |
| 28 | +FROM pre_auth_keys WHERE prefix IS NOT NULL AND prefix != ''`, types.CredentialPreAuthKey).Error |
| 29 | + if err != nil { |
| 30 | + return fmt.Errorf("backfilling pre-auth keys: %w", err) |
| 31 | + } |
| 32 | + |
| 33 | + // Postgres does not advance the id sequence on explicit-id inserts; nudge it |
| 34 | + // past the pre-auth ids before the auto-id inserts below. SQLite's |
| 35 | + // AUTOINCREMENT already tracks max(id). |
| 36 | + if tx.Name() != "sqlite" { |
| 37 | + err = tx.Exec(`SELECT setval(pg_get_serial_sequence('credentials','id'), |
| 38 | +GREATEST((SELECT COALESCE(MAX(id), 1) FROM credentials), 1))`).Error |
| 39 | + if err != nil { |
| 40 | + return fmt.Errorf("resetting credentials id sequence: %w", err) |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + err = tx.Exec(`INSERT INTO credentials (kind, identifier, hash, user_id, last_seen, expiration, created_at) |
| 45 | +SELECT ?, prefix, hash, user_id, last_seen, expiration, created_at FROM api_keys`, types.CredentialAPIKey).Error |
| 46 | + if err != nil { |
| 47 | + return fmt.Errorf("backfilling api keys: %w", err) |
| 48 | + } |
| 49 | + |
| 50 | + err = tx.Exec(`INSERT INTO credentials (kind, identifier, hash, scopes, tags, description, user_id, revoked, created_at) |
| 51 | +SELECT ?, client_id, secret_hash, scopes, tags, description, user_id, revoked, created_at FROM oauth_clients`, types.CredentialOAuthClient).Error |
| 52 | + if err != nil { |
| 53 | + return fmt.Errorf("backfilling oauth clients: %w", err) |
| 54 | + } |
| 55 | + |
| 56 | + err = tx.Exec(`INSERT INTO credentials (kind, identifier, hash, client_id, scopes, tags, expiration, created_at) |
| 57 | +SELECT ?, prefix, hash, client_id, scopes, tags, expiration, created_at FROM oauth_access_tokens`, types.CredentialOAuthToken).Error |
| 58 | + if err != nil { |
| 59 | + return fmt.Errorf("backfilling oauth access tokens: %w", err) |
| 60 | + } |
| 61 | + |
| 62 | + if err := retargetNodesAuthKeyFK(tx); err != nil { //nolint:noinlineerr |
| 63 | + return err |
| 64 | + } |
| 65 | + |
| 66 | + for _, table := range []string{"pre_auth_keys", "api_keys", "oauth_clients", "oauth_access_tokens"} { |
| 67 | + if err := tx.Migrator().DropTable(table); err != nil { //nolint:noinlineerr |
| 68 | + return fmt.Errorf("dropping %s: %w", table, err) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return nil |
| 73 | +} |
| 74 | + |
| 75 | +// retargetNodesAuthKeyFK repoints the nodes.auth_key_id foreign key from |
| 76 | +// pre_auth_keys(id) to credentials(id). Postgres alters the constraint in place; |
| 77 | +// SQLite, which cannot alter a foreign key, rebuilds the table. The rebuild runs |
| 78 | +// with foreign keys enabled: no table references nodes, and every retained |
| 79 | +// auth_key_id now points at a credentials row, so no FK toggling is required. |
| 80 | +func retargetNodesAuthKeyFK(tx *gorm.DB) error { |
| 81 | + if tx.Name() != "sqlite" { |
| 82 | + err := tx.Exec(`ALTER TABLE nodes DROP CONSTRAINT IF EXISTS fk_nodes_auth_key`).Error |
| 83 | + if err != nil { |
| 84 | + return fmt.Errorf("dropping nodes auth_key constraint: %w", err) |
| 85 | + } |
| 86 | + |
| 87 | + err = tx.Exec(`ALTER TABLE nodes ADD CONSTRAINT fk_nodes_auth_key |
| 88 | +FOREIGN KEY (auth_key_id) REFERENCES credentials(id)`).Error |
| 89 | + if err != nil { |
| 90 | + return fmt.Errorf("adding nodes auth_key constraint: %w", err) |
| 91 | + } |
| 92 | + |
| 93 | + return nil |
| 94 | + } |
| 95 | + |
| 96 | + stmts := []string{ |
| 97 | + `CREATE TABLE nodes_new( |
| 98 | + id integer PRIMARY KEY AUTOINCREMENT, |
| 99 | + machine_key text, |
| 100 | + node_key text, |
| 101 | + disco_key text, |
| 102 | + endpoints text, |
| 103 | + host_info text, |
| 104 | + ipv4 text, |
| 105 | + ipv6 text, |
| 106 | + hostname text, |
| 107 | + given_name varchar(63), |
| 108 | + user_id integer, |
| 109 | + register_method text, |
| 110 | + tags text, |
| 111 | + auth_key_id integer, |
| 112 | + last_seen datetime, |
| 113 | + expiry datetime, |
| 114 | + approved_routes text, |
| 115 | +
|
| 116 | + created_at datetime, |
| 117 | + updated_at datetime, |
| 118 | + deleted_at datetime, |
| 119 | +
|
| 120 | + CONSTRAINT fk_nodes_user FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE, |
| 121 | + CONSTRAINT fk_nodes_auth_key FOREIGN KEY(auth_key_id) REFERENCES credentials(id) |
| 122 | +)`, |
| 123 | + `INSERT INTO nodes_new |
| 124 | + (id, machine_key, node_key, disco_key, endpoints, host_info, ipv4, ipv6, hostname, given_name, user_id, register_method, tags, auth_key_id, last_seen, expiry, approved_routes, created_at, updated_at, deleted_at) |
| 125 | +SELECT id, machine_key, node_key, disco_key, endpoints, host_info, ipv4, ipv6, hostname, given_name, user_id, register_method, tags, auth_key_id, last_seen, expiry, approved_routes, created_at, updated_at, deleted_at |
| 126 | +FROM nodes`, |
| 127 | + `DROP TABLE nodes`, |
| 128 | + `ALTER TABLE nodes_new RENAME TO nodes`, |
| 129 | + } |
| 130 | + |
| 131 | + for _, stmt := range stmts { |
| 132 | + if err := tx.Exec(stmt).Error; err != nil { //nolint:noinlineerr |
| 133 | + return fmt.Errorf("rebuilding nodes table: %w", err) |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + return nil |
| 138 | +} |
0 commit comments