Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions cmd/laas/gen_external_ref_schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand All @@ -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
Expand Down Expand Up @@ -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"})
Expand Down
26 changes: 26 additions & 0 deletions pkg/api/licenses.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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{
Expand Down
13 changes: 6 additions & 7 deletions pkg/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"errors"
"fmt"
"html"
"log"
"net/http"
"os"
"strconv"
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand All @@ -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
}

Expand All @@ -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
}

Expand All @@ -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"
Expand Down
65 changes: 28 additions & 37 deletions pkg/utils/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,24 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"reflect"
"strconv"
"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 (
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
Expand All @@ -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()))
}
}

Expand All @@ -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()))
}
}
}
Expand All @@ -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))
}
}

Expand Down
70 changes: 47 additions & 23 deletions tests/licenses_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@ import (

func TestCreateLicense(t *testing.T) {
license := models.LicenseCreateDTO{
Shortname: "MIT1",
Fullname: "MIT License",
Text: `MIT1 License copyright (c) <year> <copyright holders> 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) <year> <copyright holders> 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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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
Expand Down
Loading