initial delete secret implementation
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2024-01-09 13:33:51 +11:00
parent f45a0f3aeb
commit 92dcd67381
2 changed files with 162 additions and 99 deletions

View File

@@ -6,13 +6,13 @@ import (
"log" "log"
"net/http" "net/http"
"smt/models" "smt/models"
"smt/utils/token"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// bindings are validated by https://github.com/go-playground/validator // bindings are validated by https://github.com/go-playground/validator
type StoreInput struct { /*
type StoreSecretInput struct {
SafeId int `json:"safeId"` SafeId int `json:"safeId"`
SafeName string `json:"safeName"` SafeName string `json:"safeName"`
DeviceName string `json:"deviceName"` DeviceName string `json:"deviceName"`
@@ -20,20 +20,78 @@ type StoreInput struct {
UserName string `json:"userName" binding:"required"` UserName string `json:"userName" binding:"required"`
SecretValue string `json:"secretValue" 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) { func StoreSecret(c *gin.Context) {
var err error var err error
var input StoreInput var input SecretInput
var UserId int
if err := c.ShouldBindJSON(&input); err != nil { if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON received : " + err.Error()}) c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON received : " + err.Error()})
return return
} }
if input.SafeId == 0 && len(input.SafeName) == 0 { // Perform some input validation
errString := "StoreSecret no safe specified\n" /*
log.Print(errString) if input.SafeId == 0 && len(input.SafeName) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": errString}) 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 return
} }
@@ -47,37 +105,29 @@ func StoreSecret(c *gin.Context) {
s.DeviceCategory = input.DeviceCategory s.DeviceCategory = input.DeviceCategory
// Query which safes the current user is allowed to access // 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
}
safeId := SecretCheckSafeAllowed(int(user_id), input)
if safeId == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "error determining safe"})
return
}
s.SafeId = safeId
/* /*
// If RoleID is not defined then default to the same role as the user requesting secret to be stored user_id, err := token.ExtractTokenID(c)
if input.RoleId != 0 { if err != nil {
s.RoleId = input.RoleId c.JSON(http.StatusBadRequest, gin.H{"error": "error determining user"})
} else { return
ur, _ := models.GetUserRoleFromToken(c)
log.Printf("StoreSecret RoleId was not specified, setting to RoleId of '%d'\n", ur.RoleId)
s.RoleId = ur.RoleId
} }
*/ */
if input.DeviceCategory == "" && input.DeviceName == "" { // Get userId that we stored in the context earlier
c.JSON(http.StatusBadRequest, gin.H{"error": "cannot store secret with empty deviceName and empty deviceCategory"}) if val, ok := c.Get("user-id"); !ok {
c.JSON(http.StatusBadRequest, gin.H{"error": "error determining user"})
return return
} else {
UserId = val.(int)
//log.Printf("user_id: %v\n", user_id)
} }
// TODO - replace this with a call to SecretsGetMultipleSafes 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 // If this secret already exists in the database then generate an error
checkExists, err := models.GetSecrets(&s, false) checkExists, err := models.GetSecrets(&s, false)
@@ -108,6 +158,7 @@ func StoreSecret(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "secret stored successfully"}) 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 // 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) { func CheckUpdateSecretAllowed(s *models.Secret, user_id int) (int, error) {
@@ -187,10 +238,11 @@ func CheckUpdateSecretAllowed(s *models.Secret, user_id int) (int, error) {
return 0, nil return 0, nil
} }
*/
func UpdateSecret(c *gin.Context) { func UpdateSecret(c *gin.Context) {
var err error var err error
var input StoreInput var input SecretInput
var user_id int var user_id int
if err := c.ShouldBindJSON(&input); err != nil { if err := c.ShouldBindJSON(&input); err != nil {
@@ -241,12 +293,14 @@ func UpdateSecret(c *gin.Context) {
} }
if len(secretList) == 0 { if len(secretList) == 0 {
// TODO - also check secrets allowed for user
c.JSON(http.StatusBadRequest, gin.H{"error": "no secret matching search parameters"}) c.JSON(http.StatusBadRequest, gin.H{"error": "no secret matching search parameters"})
return return
} else if len(secretList) == 1 { } else if len(secretList) == 1 {
// Update secret // Update secret
//log.Printf("mock updating secret\n") //log.Printf("secretList[0]: %v\n", secretList[0])
log.Printf("secretList[0]: %v\n", secretList[0])
s.SecretId = secretList[0].SecretId s.SecretId = secretList[0].SecretId
@@ -280,78 +334,87 @@ func UpdateSecret(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "multiple secrets matched search parameters, be more specific"}) c.JSON(http.StatusBadRequest, gin.H{"error": "multiple secrets matched search parameters, be more specific"})
return 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
}
/* /*
// TODO: if input.SafeId == 0 && len(input.SafeName) == 0 {
// Get a list of matching secrets - SecretsSearchAllSafes errString := "StoreSecret no safe specified\n"
//secretList, err := models.SecretsSearchAllSafes(&s) log.Print(errString)
// Check if user has access to the safes containing those secrets - something like UserGetSafesAllowed but not quite c.JSON(http.StatusBadRequest, gin.H{"error": errString})
//allowedSafes, err := models.UserGetSafesAllowed(user_id)
// Make sure that the access is not readonly
// If user has access to more than one safe containing the secret, generate an error
// Otherwise, update the secret
allowedUpdate, err := CheckUpdateSecretAllowed(&s, int(user_id))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error determining secret : '%s'", err)})
return
}
if allowedUpdate != 0 {
s.SafeId = allowedUpdate
}
// TODO - replace this with a call to SecretsGetMultipleSafes
// Confirm that the secret already exists
checkExists, err := models.GetSecrets(&s, false)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if len(checkExists) == 0 {
err = errors.New("UpdateSecret could not find existing secret to update")
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
} else if len(checkExists) == 1 {
// Set the secret id with the one retrieved from the database
s.SecretId = checkExists[0].SecretId
// check for empty fields in the update request and update from the existing record
if s.UserName == "" {
s.UserName = checkExists[0].UserName
}
if s.DeviceCategory == "" {
s.DeviceCategory = checkExists[0].DeviceCategory
}
if s.DeviceName == "" {
s.DeviceName = checkExists[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 {
err = errors.New("UpdateSecret found multiple secrets matching input data, be more specific")
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return 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 StoreInput) int { func SecretCheckSafeAllowed(user_id int, input SecretInput) int {
// Query which safes the current user is allowed to access // Query which safes the current user is allowed to access
// SafeId is by default the same as the safe that the user belongs to // SafeId is by default the same as the safe that the user belongs to

View File

@@ -262,7 +262,7 @@ func main() {
protected.POST("/store", controllers.StoreSecret) protected.POST("/store", controllers.StoreSecret)
protected.POST("/update", controllers.UpdateSecret) protected.POST("/update", controllers.UpdateSecret)
// TODO // TODO
//protected.POST("/delete", controllers.DeleteSecret) protected.POST("/delete", controllers.DeleteSecret)
// Support parameters in path // Support parameters in path
// See https://gin-gonic.com/docs/examples/param-in-path/ // See https://gin-gonic.com/docs/examples/param-in-path/