From 27bb1201f4a27b3c439eb8dc467cfd1887a33f49 Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Thu, 23 Jan 2025 12:01:06 +0100 Subject: [PATCH] make it harder to insert invalid routes Signed-off-by: Kristoffer Dalby --- hscontrol/db/db.go | 21 +++++++++++++++++++++ hscontrol/types/routes.go | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/hscontrol/db/db.go b/hscontrol/db/db.go index 0d9120c2..553d7f0e 100644 --- a/hscontrol/db/db.go +++ b/hscontrol/db/db.go @@ -521,6 +521,27 @@ func NewHeadscaleDatabase( }, Rollback: func(db *gorm.DB) error { return nil }, }, + { + // Add a constraint to routes ensuring they cannot exist without a node. + ID: "202501221827", + Migrate: func(tx *gorm.DB) error { + // Remove any invalid routes associated with a node that does not exist. + if tx.Migrator().HasTable(&types.Route{}) && tx.Migrator().HasTable(&types.Node{}) { + err := tx.Exec("delete from routes where node_id not in (select id from nodes)").Error + if err != nil { + return err + } + } + + err := tx.AutoMigrate(&types.Route{}) + if err != nil { + return err + } + + return nil + }, + Rollback: func(db *gorm.DB) error { return nil }, + }, }, ) diff --git a/hscontrol/types/routes.go b/hscontrol/types/routes.go index 4ef3621f..f98c037d 100644 --- a/hscontrol/types/routes.go +++ b/hscontrol/types/routes.go @@ -13,7 +13,7 @@ import ( type Route struct { gorm.Model - NodeID uint64 + NodeID uint64 `gorm:"not null"` Node *Node // TODO(kradalby): change this custom type to netip.Prefix