Files
smt/controllers/store_secrets.go
Nathan Coad dbc2276d68
All checks were successful
continuous-integration/drone/push Build is passing
test
2024-01-09 09:51:32 +11:00

343 lines
10 KiB
Go

package controllers
import (
"errors"
"fmt"
"log"
"net/http"
"smt/models"
"smt/utils/token"
"github.com/gin-gonic/gin"
)
// bindings are validated by https://github.com/go-playground/validator
type StoreInput struct {
//RoleId int `json:"roleId"`
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"`
}
func StoreSecret(c *gin.Context) {
var err error
var input StoreInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON received : " + err.Error()})
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
}
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
if input.RoleId != 0 {
s.RoleId = input.RoleId
} else {
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 == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "cannot store secret with empty deviceName and empty deviceCategory"})
return
}
// TODO - replace this with a call to SecretsGetMultipleSafes
// 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 StoreInput
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)
// 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
}
*/
/*
user_id, err := token.ExtractTokenID(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "error determining user"})
return
}
*/
user_id := c.GetInt("user-id")
// Populate fields
s := models.Secret{}
s.UserName = input.UserName
s.DeviceName = input.DeviceName
s.DeviceCategory = input.DeviceCategory
// TODO:
// Get a list of matching secrets - SecretsSearchAllSafes
//secretList, err := models.SecretsSearchAllSafes(&s)
// Check if user has access to the safes containing those secrets - something like UserGetSafesAllowed but not quite
//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
}
// Query which safes the current user is allowed to access
/*
safeId := SecretCheckSafeAllowed(int(user_id), input)
if safeId == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "error determining safe"})
return
}
s.SafeId = safeId
*/
// 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
}
}
func SecretCheckSafeAllowed(user_id int, input StoreInput) 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
}
*/
}