diff --git a/cmd/laas/gen_external_ref_schema.go b/cmd/laas/gen_external_ref_schema.go index 571d746..0e4d7d3 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/api/licenses.go b/pkg/api/licenses.go index b5e0a78..071407e 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/auth/auth.go b/pkg/auth/auth.go index 68ccf76..e3d0017 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 f01be78..a54d444 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 ( @@ -126,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 @@ -205,13 +210,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 +505,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 +538,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 +555,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 +572,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/licenses_test.go b/tests/licenses_test.go index e1d0ca3..41be0a6 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 66bd35e..2779988 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) {