package controllers import ( "errors" "fmt" "log" "net/http" "smt/models" "github.com/gin-gonic/gin" ) // bindings are validated by https://github.com/go-playground/validator /* type StoreSecretInput struct { SafeId int `json:"safeId"` SafeName string `json:"safeName"` DeviceName string `json:"deviceName"` DeviceCategory string `json:"deviceCategory"` UserName string `json:"userName" binding:"required"` SecretValue string `json:"secretValue" binding:"required"` } */ type SecretInput struct { SafeId int `json:"safeId"` SafeName string `json:"safeName"` DeviceName string `json:"deviceName"` DeviceCategory string `json:"deviceCategory"` UserName string `json:"userName"` SecretValue string `json:"secretValue"` } func FindSafeId(UserId int, input SecretInput) (int, error) { // Check which safes a user is allowed to access allowedSafes, err := models.UserGetSafesAllowed(UserId) if err != nil { errString := fmt.Sprintf("error determining safe access : '%s'", err) log.Printf("StoreSecret %s\n", errString) return 0, errors.New(errString) } // Make sure that the specified safe is in the list of allowed safes if len(allowedSafes) == 0 { errString := "error accessing specified safe" log.Printf("StoreSecret %s\n", errString) return 0, errors.New(errString) } else if len(allowedSafes) == 1 && input.SafeId == 0 && len(input.SafeName) == 0 { log.Printf("StoreSecret user did not specify safe but has access to only one safe '%d'\n", allowedSafes[0].SafeId) return allowedSafes[0].SafeId, nil } else { for _, safe := range allowedSafes { if input.SafeId > 0 && len(input.SafeName) > 0 && safe.SafeId == input.SafeId && safe.SafeName == input.SafeName { return safe.SafeId, nil } else if input.SafeId > 0 && safe.SafeId == input.SafeId { return safe.SafeId, nil } else if len(input.SafeName) > 0 && safe.SafeName == input.SafeName { return safe.SafeId, nil } } errString := "error accessing specified safe" log.Printf("StoreSecret %s\n", errString) return 0, errors.New(errString) } } // TODO update to match UpdateSecret func StoreSecret(c *gin.Context) { var err error var input SecretInput var UserId int if err := c.ShouldBindJSON(&input); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON received : " + err.Error()}) return } // Perform some input validation /* if input.SafeId == 0 && len(input.SafeName) == 0 { errString := "StoreSecret no safe specified\n" log.Print(errString) c.JSON(http.StatusBadRequest, gin.H{"error": errString}) return } */ if input.DeviceCategory == "" && input.DeviceName == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "cannot store secret with empty deviceName and empty deviceCategory"}) return } if len(input.UserName) == 0 || len(input.SecretValue) == 0 { c.JSON(http.StatusBadRequest, gin.H{"error": "cannot store secret with empty UserName or SecretValue"}) return } // Don't log this since it contains plaintext secrets //log.Printf("StoreSecret received JSON input '%v'\n", input) // Populate fields s := models.Secret{} s.UserName = input.UserName s.DeviceName = input.DeviceName s.DeviceCategory = input.DeviceCategory // Query which safes the current user is allowed to access /* user_id, err := token.ExtractTokenID(c) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "error determining user"}) return } */ // Get userId that we stored in the context earlier if val, ok := c.Get("user-id"); !ok { c.JSON(http.StatusBadRequest, gin.H{"error": "error determining user"}) return } else { UserId = val.(int) //log.Printf("user_id: %v\n", user_id) } safeId, err := FindSafeId(UserId, input) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } s.SafeId = safeId // If this secret already exists in the database then generate an error checkExists, err := models.GetSecrets(&s, false) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if len(checkExists) > 0 { log.Printf("StoreSecret not storing secret with '%d' already matching secrets.\n", len(checkExists)) c.JSON(http.StatusBadRequest, gin.H{"error": "StoreSecret attempting to store secret already defined. Use update API call instead"}) return } // Encrypt secret s.Secret = input.SecretValue _, err = s.EncryptSecret() if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "StoreSecret error encrypting secret : " + err.Error()}) return } _, err = s.SaveSecret() if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "StoreSecret error saving secret : " + err.Error()}) return } c.JSON(http.StatusOK, gin.H{"message": "secret stored successfully"}) } /* // CheckUpdateSecretAllowed checks to see if a user has access to the specified secret. If so, the corresponding SafeId is returned func CheckUpdateSecretAllowed(s *models.Secret, user_id int) (int, error) { // If user has Admin access then perform update // If user has normal access to the safe the secret is stored in then perform update // If matching secret is found in multiple safes then generate error // If user doesn't have access to the safe the matching secret is in then generate error // NO. That is too complicated! // Lets try to make this more simple // A user can only be in one group // A group can have permissions on multiple safes // If a user is an admin they can do user related functions like create users, groups, assign permissions // But a user has to have a permission that maps the group to the safe in order to perform CRUD operations // What does a group being an admin give them? All users in that group can do user related function // Query all safes for secrets matching parameters specified matchingSecrets, err := models.SecretsSearchAllSafes(s) if err != nil { errString := fmt.Sprintf("CheckUpdateSecretAllowed error getting matching secrets : '%s'\n", err) log.Println(errString) return 0, errors.New(errString) } // Query which safes user has access to userSafes, err := models.UserGetSafesAllowed(int(user_id)) if err != nil { errString := fmt.Sprintf("CheckUpdateSecretAllowed error getting safes that user has access to : '%s'\n", err) log.Println(errString) return 0, errors.New(errString) } if len(matchingSecrets) == 0 { errString := "CheckUpdateSecretAllowed found zero secrets matching supplied parameters" log.Println(errString) return 0, errors.New(errString) } else if len(matchingSecrets) == 1 { log.Printf("CheckUpdateSecretAllowed found a single matching secret :\n'%+v'\n", matchingSecrets[0]) // Check to see user is allowed to access the safe holding the secret for _, secret := range matchingSecrets { for _, user := range userSafes { if user.SafeId == secret.SafeId { return user.SafeId, nil } } } } else { // Multiple matching secrets are found log.Printf("CheckUpdateSecretAllowed found multiple matching secrets\n") matchFound := false matchingSafeId := 0 for _, secret := range matchingSecrets { for _, user := range userSafes { if user.SafeId == secret.SafeId { log.Printf("CheckUpdateSecretAllowed match found for SafeId '%d':\n'%+v'\n", user.SafeId, secret) if !matchFound { matchFound = true matchingSafeId = user.SafeId } else { // Found more than one applicable secret, how do we know which one to update? errString := "CheckUpdateSecretAllowed found multiple secrets matching supplied parameters, supply more specific parameters" log.Println(errString) return 0, errors.New(errString) } } } } // only one match was found, so we are safe to return that value if matchFound { return matchingSafeId, nil } } return 0, nil } */ func UpdateSecret(c *gin.Context) { var err error var input SecretInput var user_id int if err := c.ShouldBindJSON(&input); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "UpdateSecret error binding to input JSON : " + err.Error()}) return } log.Printf("UpdateSecret received JSON input '%v'\n", input) if len(input.SecretValue) == 0 { errString := "UpdateSecret no updated secret specified\n" log.Print(errString) c.JSON(http.StatusBadRequest, gin.H{"error": errString}) return } // Temporarily disable because we should be able to figure it out without user specifying /* if input.SafeId == 0 && len(input.SafeName) == 0 { errString := "UpdateSecret no safe specified\n" log.Print(errString) c.JSON(http.StatusBadRequest, gin.H{"error": errString}) return } */ // Get userId that we stored in the context earlier if val, ok := c.Get("user-id"); !ok { c.JSON(http.StatusBadRequest, gin.H{"error": "error determining user"}) return } else { user_id = val.(int) //log.Printf("user_id: %v\n", user_id) } // Populate fields s := models.Secret{} s.UserName = input.UserName s.DeviceName = input.DeviceName s.DeviceCategory = input.DeviceCategory secretList, err := models.SecretsGetAllowedForGroup(&s, user_id) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error determining secret : '%s'", err)}) return } if len(secretList) == 0 { // TODO - also check secrets allowed for user c.JSON(http.StatusBadRequest, gin.H{"error": "no secret matching search parameters"}) return } else if len(secretList) == 1 { // Update secret //log.Printf("secretList[0]: %v\n", secretList[0]) s.SecretId = secretList[0].SecretId // check for empty fields in the update request and update from the existing record if s.UserName == "" { s.UserName = secretList[0].Secret.UserName } if s.DeviceCategory == "" { s.DeviceCategory = secretList[0].DeviceCategory } if s.DeviceName == "" { s.DeviceName = secretList[0].DeviceName } // Encrypt secret s.Secret = input.SecretValue _, err = s.EncryptSecret() if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "UpdateSecret error encrypting secret : " + err.Error()}) return } _, err = s.UpdateSecret() if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "UpdateSecret error saving secret : " + err.Error()}) return } c.JSON(http.StatusOK, gin.H{"message": "secret updated successfully"}) } else { c.JSON(http.StatusBadRequest, gin.H{"error": "multiple secrets matched search parameters, be more specific"}) return } } func DeleteSecret(c *gin.Context) { var err error var input SecretInput var UserId int if err := c.ShouldBindJSON(&input); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON received : " + err.Error()}) return } // Input validation if input.DeviceCategory == "" && input.DeviceName == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "cannot store secret with empty deviceName and empty deviceCategory"}) return } /* if input.SafeId == 0 && len(input.SafeName) == 0 { errString := "StoreSecret no safe specified\n" log.Print(errString) c.JSON(http.StatusBadRequest, gin.H{"error": errString}) return } */ // Don't log this since it contains plaintext secrets //log.Printf("StoreSecret received JSON input '%v'\n", input) // Populate fields s := models.Secret{} s.UserName = input.UserName s.DeviceName = input.DeviceName s.DeviceCategory = input.DeviceCategory // Query which safes the current user is allowed to access /* user_id, err := token.ExtractTokenID(c) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "error determining user"}) return } */ // Get userId that we stored in the context earlier if val, ok := c.Get("user-id"); !ok { c.JSON(http.StatusBadRequest, gin.H{"error": "error determining user"}) return } else { UserId = val.(int) //log.Printf("user_id: %v\n", user_id) } safeId, err := FindSafeId(UserId, input) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } s.SafeId = safeId // If this secret already exists in the database then generate an error checkExists, err := models.GetSecrets(&s, false) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if len(checkExists) == 0 { c.JSON(http.StatusBadRequest, gin.H{"error": "no secrets matched search parameters"}) return } else if len(checkExists) == 1 { c.JSON(http.StatusOK, gin.H{"message": "mock secret deleted successfully"}) // TODO delete secret } else { c.JSON(http.StatusBadRequest, gin.H{"error": "multiple secrets matched search parameters, be more specific"}) return } } func SecretCheckSafeAllowed(user_id int, input SecretInput) int { // Query which safes the current user is allowed to access // SafeId is by default the same as the safe that the user belongs to safeList, err := models.UserGetSafesAllowed(user_id) if err != nil { log.Printf("SecretCheckSafeAllowed error determining allowed safes for userId %d : '%s'\n", user_id, err) return 0 } // Verify user has access to specified safe for _, safe := range safeList { if len(input.SafeName) > 0 && safe.SafeName == input.SafeName { // Safe specifed by name return safe.SafeId } else if input.SafeId > 0 && safe.SafeId == input.SafeId { // Safe specified by id return safe.SafeId } else { log.Printf("SecretCheckSafeAllowed unexpected\n") } } log.Printf("SecretCheckSafeAllowed didn't find any safes\n") return 0 /* if !matchFound { errString := "no safe specified or no access to specified safe" log.Println(errString) c.JSON(http.StatusBadRequest, gin.H{"error": errString}) return } */ }