From 2a761913d747bbc13592288b8a74e8e65a3ac371 Mon Sep 17 00:00:00 2001 From: abhayrajjais01 Date: Mon, 12 Jan 2026 17:10:26 +0530 Subject: [PATCH 1/3] refactor: replace log with zap logger (Issue #168) --- cmd/laas/gen_external_ref_schema.go | 9 +++-- pkg/auth/auth.go | 13 +++---- pkg/utils/util.go | 58 +++++++++++------------------ tests/main_test.go | 29 ++++++++------- 4 files changed, 47 insertions(+), 62 deletions(-) diff --git a/cmd/laas/gen_external_ref_schema.go b/cmd/laas/gen_external_ref_schema.go index 571d746a..0e4d7d38 100644 --- a/cmd/laas/gen_external_ref_schema.go +++ b/cmd/laas/gen_external_ref_schema.go @@ -10,11 +10,12 @@ package main import ( "errors" "fmt" - "log" "os" "path/filepath" + logger "github.com/fossology/LicenseDb/pkg/log" + "github.com/dave/jennifer/jen" "gopkg.in/yaml.v3" ) @@ -41,12 +42,12 @@ func main() { fieldsMetadata, err := os.ReadFile(PATH_EXTERNAL_REF_CONFIG_FILE) if err != nil { - log.Fatalf("Failed to instantiate json schema for external ref in license: %v", err) + logger.LogFatal(fmt.Sprintf("Failed to instantiate json schema for external ref in license: %v", err)) } err = yaml.Unmarshal(fieldsMetadata, &externalRefFields) if err != nil { - log.Fatalf("Failed to instantiate json schema for external ref in license: %v", err) + logger.LogFatal(fmt.Sprintf("Failed to instantiate json schema for external ref in license: %v", err)) } // REUSE-IgnoreStart @@ -74,7 +75,7 @@ func main() { err = fmt.Errorf("type %s in external_ref_fields.yaml is not supported", f.Type) } if err != nil { - log.Fatalf("Failed to instantiate json schema for external ref in license: %v", err) + logger.LogFatal(fmt.Sprintf("Failed to instantiate json schema for external ref in license: %v", err)) return } field = field.Tag(map[string]string{"json": fmt.Sprintf("%s,omitempty", f.Name), "swaggerignore": "true"}) diff --git a/pkg/auth/auth.go b/pkg/auth/auth.go index 68ccf762..e3d00179 100644 --- a/pkg/auth/auth.go +++ b/pkg/auth/auth.go @@ -12,7 +12,6 @@ import ( "errors" "fmt" "html" - "log" "net/http" "os" "strconv" @@ -176,7 +175,7 @@ func CreateOidcUser(c *gin.Context) { Timestamp: time.Now().Format(time.RFC3339), } c.JSON(http.StatusInternalServerError, er) - log.Print("\033[31mError: OIDC environment variables not configured properly\033[0m") + logger.LogError("Error: OIDC environment variables not configured properly") return } @@ -213,7 +212,7 @@ func CreateOidcUser(c *gin.Context) { keyset, err := Jwks.Lookup(context.Background(), os.Getenv("JWKS_URI")) if err != nil { - log.Print("\033[31mError: Failed jwk.Cache lookup from the oidc provider's URL\033[0m") + logger.LogError("Error: Failed jwk.Cache lookup from the oidc provider's URL") er := models.LicenseError{ Status: http.StatusInternalServerError, Message: "Something went wrong", @@ -242,7 +241,7 @@ func CreateOidcUser(c *gin.Context) { } if keyError { - log.Printf("\033[31mError: Token verification failed due to invalid alg header key field \033[0m") + logger.LogError("Error: Token verification failed due to invalid alg header key field") er := models.LicenseError{ Status: http.StatusUnauthorized, Message: "Please check your credentials and try again", @@ -263,7 +262,7 @@ func CreateOidcUser(c *gin.Context) { Timestamp: time.Now().Format(time.RFC3339), } c.JSON(http.StatusUnauthorized, er) - log.Printf("\033[31mError: Token verification failed \033[0m") + logger.LogError("Error: Token verification failed") return } @@ -290,7 +289,7 @@ func CreateOidcUser(c *gin.Context) { Timestamp: time.Now().Format(time.RFC3339), } c.JSON(http.StatusUnauthorized, er) - log.Printf("\033[31mError: Issuer '%s' not supported\033[0m", iss) + logger.LogError(fmt.Sprintf("Error: Issuer '%s' not supported", iss)) return } @@ -313,7 +312,7 @@ func CreateOidcUser(c *gin.Context) { Timestamp: time.Now().Format(time.RFC3339), } c.JSON(http.StatusUnauthorized, er) - log.Printf("\033[31mError: %s\033[0m", errMessage) + logger.LogError(fmt.Sprintf("Error: %s", errMessage)) return } level := "USER" diff --git a/pkg/utils/util.go b/pkg/utils/util.go index f01be78d..575323c9 100644 --- a/pkg/utils/util.go +++ b/pkg/utils/util.go @@ -12,7 +12,6 @@ import ( "encoding/json" "errors" "fmt" - "log" "net/http" "os" "reflect" @@ -20,18 +19,17 @@ import ( "strings" "time" - "gorm.io/gorm" - "gorm.io/gorm/clause" - - "golang.org/x/crypto/bcrypt" - - "github.com/gin-gonic/gin" - "github.com/go-playground/validator/v10" - "github.com/google/uuid" - "github.com/fossology/LicenseDb/pkg/db" + logger "github.com/fossology/LicenseDb/pkg/log" "github.com/fossology/LicenseDb/pkg/models" "github.com/fossology/LicenseDb/pkg/validations" + "github.com/gin-gonic/gin" + "github.com/go-playground/validator/v10" + "github.com/google/uuid" + "go.uber.org/zap" + "golang.org/x/crypto/bcrypt" + "gorm.io/gorm" + "gorm.io/gorm/clause" ) var ( @@ -205,13 +203,9 @@ func InsertOrUpdateLicenseOnImport(lic *models.LicenseImportDTO, userId uuid.UUI } else if lic.Shortname != nil { erroredElem = *lic.Shortname } - red := "\033[31m" - reset := "\033[0m" - log.Printf("%s%s: %s%s", red, erroredElem, message, reset) + logger.LogError(fmt.Sprintf("%s: %s", erroredElem, message)) } else { - green := "\033[32m" - reset := "\033[0m" - log.Printf("%sImport for license '%s' successful%s", green, (*lic.Id).String(), reset) + logger.LogInfo(fmt.Sprintf("Import for license '%s' successful", (*lic.Id).String())) } return message, importStatus } @@ -504,25 +498,23 @@ func Populatedb(datafile string) { // Read the content of the data file. byteResult, err := os.ReadFile(datafile) if err != nil { - log.Fatalf("Unable to read JSON file: %v", err) + logger.LogFatal("Unable to read JSON file", zap.Error(err)) } // Unmarshal the JSON file data into a slice of LicenseJson structs. if err := json.Unmarshal(byteResult, &licenses); err != nil { - log.Fatalf("error reading from json file: %v", err) + logger.LogFatal("error reading from json file", zap.Error(err)) } user := models.User{} level := "SUPER_ADMIN" if err := db.DB.Where(&models.User{UserLevel: &level}).First(&user).Error; err != nil { - log.Fatalf("Failed to find a super admin") + logger.LogFatal("Failed to find a super admin") } for _, license := range licenses { result := license.Converter() if err := validations.Validate.Struct(&result); err != nil { - red := "\033[31m" - reset := "\033[0m" - log.Printf("%s%s: %s%s", red, *result.Shortname, fmt.Sprintf("field '%s' failed validation: %s\n", err.(validator.ValidationErrors)[0].Field(), err.(validator.ValidationErrors)[0].Tag()), reset) + logger.LogError(fmt.Sprintf("%s: field '%s' failed validation: %s", *result.Shortname, err.(validator.ValidationErrors)[0].Field(), err.(validator.ValidationErrors)[0].Tag())) continue } _, _ = InsertOrUpdateLicenseOnImport(&result, user.Id) @@ -539,13 +531,9 @@ func Populatedb(datafile string) { err, status := CreateObType(obType, user.Id) if status == CREATED || status == CONFLICT { - green := "\033[32m" - reset := "\033[0m" - log.Printf("%s%s: %s%s", green, obType.Type, "Obligation type created successfully", reset) + logger.LogInfo(fmt.Sprintf("%s: Obligation type created successfully", obType.Type)) } else { - red := "\033[31m" - reset := "\033[0m" - log.Printf("%s%s: %s%s", red, obType.Type, err.Error(), reset) + logger.LogError(fmt.Sprintf("%s: %s", obType.Type, err.Error())) } } @@ -560,13 +548,9 @@ func Populatedb(datafile string) { err, status := CreateObClassification(obClassification, user.Id) if status == CREATED || status == CONFLICT { - green := "\033[32m" - reset := "\033[0m" - log.Printf("%s%s: %s%s", green, obClassification.Classification, "Obligation classification created successfully", reset) + logger.LogInfo(fmt.Sprintf("%s: Obligation classification created successfully", obClassification.Classification)) } else { - red := "\033[31m" - reset := "\033[0m" - log.Printf("%s%s: %s%s", red, obClassification.Classification, err.Error(), reset) + logger.LogError(fmt.Sprintf("%s: %s", obClassification.Classification, err.Error())) } } } @@ -581,15 +565,15 @@ func SetSimilarityThreshold() { if parsed, err := strconv.ParseFloat(thresholdStr, 64); err == nil { threshold = parsed } else { - log.Printf("Invalid SIMILARITY_THRESHOLD '%s', using default %.1f", thresholdStr, defaultThreshold) + logger.LogWarn(fmt.Sprintf("Invalid SIMILARITY_THRESHOLD '%s', using default %.1f", thresholdStr, defaultThreshold)) } } else { - log.Printf("SIMILARITY_THRESHOLD not set, using default %.1f", defaultThreshold) + logger.LogInfo(fmt.Sprintf("SIMILARITY_THRESHOLD not set, using default %.1f", defaultThreshold)) } query := fmt.Sprintf("SET pg_trgm.similarity_threshold = %f", threshold) if err := db.DB.Exec(query).Error; err != nil { - log.Println("Failed to set similarity threshold:", err) + logger.LogError("Failed to set similarity threshold", zap.Error(err)) } } diff --git a/tests/main_test.go b/tests/main_test.go index 9a6fc07a..39b324d2 100644 --- a/tests/main_test.go +++ b/tests/main_test.go @@ -9,16 +9,17 @@ import ( "database/sql" "encoding/json" "fmt" - "log" "net/http/httptest" "os" "testing" "github.com/fossology/LicenseDb/pkg/api" "github.com/fossology/LicenseDb/pkg/db" + logger "github.com/fossology/LicenseDb/pkg/log" "github.com/fossology/LicenseDb/pkg/models" "github.com/fossology/LicenseDb/pkg/utils" "github.com/fossology/LicenseDb/pkg/validations" + "go.uber.org/zap" "github.com/gin-gonic/gin" "github.com/golang-migrate/migrate/v4" _ "github.com/golang-migrate/migrate/v4/database/postgres" @@ -39,7 +40,7 @@ func TestMain(m *testing.M) { err := godotenv.Load(envFile) if err != nil { - log.Fatalf("Error loading .env file: %v", err) + logger.LogFatal("Error loading .env file", zap.Error(err)) } dbname := os.Getenv("DB_NAME") user := os.Getenv("DB_USER") @@ -51,11 +52,11 @@ func TestMain(m *testing.M) { runMigrations(user, password, port, dbhost, dbname) // migrate the test db db.Connect(&dbhost, &port, &user, &dbname, &password) // connnect to the test db if err := seedFirstUser(); err != nil { // create fisrt user to the test db - log.Fatalf(" Failed to seed user: %v", err) + logger.LogFatal("Failed to seed user", zap.Error(err)) } - log.Println("First user created") + logger.LogInfo("First user created") if err := validations.RegisterValidations(); err != nil { - log.Fatalf("Failed to set up validations: %s", err) + logger.LogFatal(fmt.Sprintf("Failed to set up validations: %s", err)) } utils.Populatedb(testDataFile) // populate the nessesary tables with data from the file serverPort := os.Getenv("PORT") @@ -98,16 +99,16 @@ func createTestDB(user, password, port, host, dbname string) { dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=postgres sslmode=disable", host, port, user, password) db, err := sql.Open("postgres", dsn) if err != nil { - log.Fatalf(" Failed to connect to postgres: %v", err) + logger.LogFatal(fmt.Sprintf("Failed to connect to postgres: %v", err)) } defer db.Close() _, err = db.Exec("CREATE DATABASE " + dbname) if err != nil && !isAlreadyExistsError(err) { - log.Fatalf(" Failed to create test DB: %v", err) + logger.LogFatal(fmt.Sprintf("Failed to create test DB: %v", err)) } - log.Println(" Test DB created") + logger.LogInfo("Test DB created") } func isAlreadyExistsError(err error) bool { @@ -122,14 +123,14 @@ func runMigrations(user, password, port, host, dbname string) { dsn, ) if err != nil { - log.Fatalf(" Failed to create migration instance: %v", err) + logger.LogFatal(fmt.Sprintf("Failed to create migration instance: %v", err)) } if err := m.Up(); err != nil && err != migrate.ErrNoChange { - log.Fatalf(" Migration failed: %v", err) + logger.LogFatal(fmt.Sprintf("Migration failed: %v", err)) } - log.Println("Migrations applied") + logger.LogInfo("Migrations applied") } func seedFirstUser() error { @@ -172,7 +173,7 @@ func dropTestDB(user, password, port, host, dbname string) { dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=postgres sslmode=disable", host, port, user, password) db, err := sql.Open("postgres", dsn) if err != nil { - log.Printf(" Error opening connection to drop DB: %v", err) + logger.LogInfo(fmt.Sprintf("Error opening connection to drop DB: %v", err)) return } defer db.Close() @@ -182,8 +183,8 @@ func dropTestDB(user, password, port, host, dbname string) { _, err = db.Exec("DROP DATABASE IF EXISTS " + dbname) if err != nil { - log.Printf(" Error dropping test DB: %v", err) + logger.LogInfo(fmt.Sprintf("Error dropping test DB: %v", err)) } else { - log.Println(" Dropped test DB:", dbname) + logger.LogInfo("Dropped test DB:", zap.String("dbname", dbname)) } } From 416e7ee37d512e37bd948493c03f69a0dd623ec9 Mon Sep 17 00:00:00 2001 From: abhayrajjais01 Date: Thu, 22 Jan 2026 10:54:50 +0530 Subject: [PATCH 2/3] fix: enforce minimum one obligation requirement for licenses (Issue #136) - Add validation to CreateLicense endpoint to reject licenses without obligations - Add validation to UpdateLicense endpoint to prevent removing all obligations - Add validation to ImportLicenses flow for imported licenses - Update existing tests to include obligations - Add new test case for license creation without obligations - Create getTestObligation() helper function for tests Addresses all feedback from PR #191: - Validation occurs before database transactions (not after) - UpdateLicense endpoint now validates obligations - All test cases updated and passing - Clear, user-friendly error messages Fixes #136 Signed-off-by: abhayrajjais01 --- pkg/api/licenses.go | 26 ++++++++++++++++ pkg/utils/util.go | 7 +++++ tests/licenses_test.go | 70 ++++++++++++++++++++++++++++-------------- tests/main_test.go | 38 +++++++++++++++++++++++ 4 files changed, 118 insertions(+), 23 deletions(-) diff --git a/pkg/api/licenses.go b/pkg/api/licenses.go index b5e0a781..071407e6 100644 --- a/pkg/api/licenses.go +++ b/pkg/api/licenses.go @@ -252,6 +252,19 @@ func CreateLicense(c *gin.Context) { return } + // Validate that at least one obligation is attached + if input.Obligations == nil || len(*input.Obligations) == 0 { + er := models.LicenseError{ + Status: http.StatusBadRequest, + Message: "cannot create license without obligations", + Error: "at least one obligation must be attached to the license", + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusBadRequest, er) + return + } + lic := input.ConvertToLicenseDB() lic.UserId = userId @@ -399,6 +412,19 @@ func UpdateLicense(c *gin.Context) { return errors.New("field `text_updatable` needs to be true to update the text") } + // Validate that obligations are not being set to empty + if updates.Obligations != nil && len(*updates.Obligations) == 0 { + er := models.LicenseError{ + Status: http.StatusBadRequest, + Message: "cannot update license to have zero obligations", + Error: "at least one obligation must remain attached to the license", + Path: c.Request.URL.Path, + Timestamp: time.Now().Format(time.RFC3339), + } + c.JSON(http.StatusBadRequest, er) + return errors.New("cannot update license to have zero obligations") + } + // Overwrite values of existing keys, add new key value pairs and remove keys with null values. if err := tx.Model(&models.LicenseDB{}).Where(models.LicenseDB{Id: oldLicense.Id}).UpdateColumn("external_ref", gorm.Expr("jsonb_strip_nulls(COALESCE(external_ref, '{}'::jsonb) || ?)", updates.ExternalRef)).Error; err != nil { er := models.LicenseError{ diff --git a/pkg/utils/util.go b/pkg/utils/util.go index 575323c9..a54d4448 100644 --- a/pkg/utils/util.go +++ b/pkg/utils/util.go @@ -124,6 +124,13 @@ func InsertOrUpdateLicenseOnImport(lic *models.LicenseImportDTO, userId uuid.UUI return message, importStatus } + // Validate that at least one obligation is attached + if lic.Obligations == nil || len(*lic.Obligations) == 0 { + message = "cannot import license without obligations: at least one obligation is required" + importStatus = IMPORT_FAILED + return message, importStatus + } + _ = db.DB.Transaction(func(tx *gorm.DB) error { license := lic.ConvertToLicenseDB() license.UserId = userId diff --git a/tests/licenses_test.go b/tests/licenses_test.go index e1d0ca30..41be0a63 100644 --- a/tests/licenses_test.go +++ b/tests/licenses_test.go @@ -16,14 +16,15 @@ import ( func TestCreateLicense(t *testing.T) { license := models.LicenseCreateDTO{ - Shortname: "MIT1", - Fullname: "MIT License", - Text: `MIT1 License copyright (c) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`, - Url: ptr("https://opensource.org/licenses/MIT"), - Notes: ptr("This license is OSI approved."), - Source: ptr("spdx"), - SpdxId: "LicenseRef-MIT1", - Risk: ptr(int64(2)), + Shortname: "MIT1", + Fullname: "MIT License", + Text: `MIT1 License copyright (c) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`, + Url: ptr("https://opensource.org/licenses/MIT"), + Notes: ptr("This license is OSI approved."), + Source: ptr("spdx"), + SpdxId: "LicenseRef-MIT1", + Risk: ptr(int64(2)), + Obligations: &[]uuid.UUID{getTestObligation()}, } t.Run("success", func(t *testing.T) { @@ -57,17 +58,39 @@ func TestCreateLicense(t *testing.T) { }) t.Run("unauthorized", func(t *testing.T) { license := models.LicenseCreateDTO{ - Shortname: "UnauthorizedLicense", - Fullname: "Unauthorized License", - Text: "This license should not be created without authentication.", - Url: ptr("https://licenses.org/unauthorized"), - SpdxId: "UNAUTHORIZED", - Notes: ptr("This license is OSI approved."), - Risk: ptr(int64(2)), + Shortname: "UnauthorizedLicense", + Fullname: "Unauthorized License", + Text: "This license should not be created without authentication.", + Url: ptr("https://licenses.org/unauthorized"), + SpdxId: "UNAUTHORIZED", + Notes: ptr("This license is OSI approved."), + Risk: ptr(int64(2)), + Obligations: &[]uuid.UUID{getTestObligation()}, } w := makeRequest("POST", "/licenses", license, false) assert.Equal(t, http.StatusUnauthorized, w.Code) }) + t.Run("withoutObligations", func(t *testing.T) { + licenseWithoutObligations := models.LicenseCreateDTO{ + Shortname: "NoObligLicense", + Fullname: "License Without Obligations", + Text: "This license should not be created without obligations.", + Url: ptr("https://licenses.org/nooblig"), + SpdxId: "LicenseRef-NoOblig", + Notes: ptr("Test for obligation validation."), + Risk: ptr(int64(2)), + // Obligations intentionally omitted + } + w := makeRequest("POST", "/licenses", licenseWithoutObligations, true) + assert.Equal(t, http.StatusBadRequest, w.Code) + + var res models.LicenseError + if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil { + t.Errorf("Error unmarshalling response: %v", err) + return + } + assert.Contains(t, res.Message, "without obligations") + }) } func TestGetLicense(t *testing.T) { @@ -116,14 +139,15 @@ func TestGetLicense(t *testing.T) { func TestUpdateLicense(t *testing.T) { license := models.LicenseCreateDTO{ - Shortname: "MIT2", - Fullname: "MIT License 2", - Text: `MIT1 License copyright text`, - Url: ptr("https://opensource.org/licenses/MIT"), - Notes: ptr("This license is OSI approved."), - Source: ptr("spdx"), - SpdxId: "LicenseRef-MIT2", - Risk: ptr(int64(2)), + Shortname: "MIT2", + Fullname: "MIT License 2", + Text: `MIT1 License copyright text`, + Url: ptr("https://opensource.org/licenses/MIT"), + Notes: ptr("This license is OSI approved."), + Source: ptr("spdx"), + SpdxId: "LicenseRef-MIT2", + Risk: ptr(int64(2)), + Obligations: &[]uuid.UUID{getTestObligation()}, } w := makeRequest("POST", "/licenses", license, true) var res models.LicenseResponse diff --git a/tests/main_test.go b/tests/main_test.go index 66bd35ef..27799887 100644 --- a/tests/main_test.go +++ b/tests/main_test.go @@ -23,6 +23,7 @@ import ( "github.com/golang-migrate/migrate/v4" _ "github.com/golang-migrate/migrate/v4/database/postgres" _ "github.com/golang-migrate/migrate/v4/source/file" + "github.com/google/uuid" "github.com/joho/godotenv" _ "github.com/lib/pq" "go.uber.org/zap" @@ -93,6 +94,43 @@ func ptr[T any](v T) *T { return &v } +// getTestObligation returns a test obligation ID, creating one if it doesn't exist +func getTestObligation() uuid.UUID { + var obligation models.Obligation + // Try to find an existing obligation + if err := db.DB.First(&obligation).Error; err == nil { + return obligation.Id + } + + // If no obligation exists, create one for testing + var obType models.ObligationType + var obClassification models.ObligationClassification + + // Get or create obligation type + db.DB.Where(models.ObligationType{Type: "OBLIGATION"}).FirstOrCreate(&obType, models.ObligationType{ + Type: "OBLIGATION", + Active: ptr(true), + }) + + // Get or create obligation classification + db.DB.Where(models.ObligationClassification{Classification: "GREEN"}).FirstOrCreate(&obClassification, models.ObligationClassification{ + Classification: "GREEN", + Color: "#00FF00", + Active: ptr(true), + }) + + // Create test obligation + obligation = models.Obligation{ + Topic: ptr("Test Obligation"), + Text: ptr("This is a test obligation for license testing"), + Active: ptr(true), + ObligationTypeId: obType.Id, + ObligationClassificationId: obClassification.Id, + } + db.DB.Create(&obligation) + return obligation.Id +} + // utility functions func createTestDB(user, password, port, host, dbname string) { From 2b4df3982f9bead02298092fef6147fa795cf811 Mon Sep 17 00:00:00 2001 From: Abhayraj Jaiswal <205578164+abhayrajjais01@users.noreply.github.com> Date: Mon, 26 Jan 2026 14:35:58 +0530 Subject: [PATCH 3/3] chore: trigger GitHub signature verification Signed-off-by: Abhayraj Jaiswal <205578164+abhayrajjais01@users.noreply.github.com>