Skip to content

Commit

Permalink
Merge pull request #5 from cipherstash/fix/jsonb-deserialize-logic
Browse files Browse the repository at this point in the history
Add jsonb array type for serialization/deserialization
  • Loading branch information
fimac authored Nov 1, 2024
2 parents 7f1ffc5 + e97c499 commit 995e147
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions goeql.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ type EncryptedText string
// EncryptedJsonb is a jsonb value to be encrypted
type EncryptedJsonb map[string]interface{}

// EncryptedJsonb array value to be encrypted/decrypted

Check failure on line 43 in goeql.go

View workflow job for this annotation

GitHub Actions / Run test suite

comment on exported type EncryptedJsonbArray should be of the form "EncryptedJsonbArray ..." (with optional leading article)
type EncryptedJsonbArray []interface{}

// EncryptedInt is a int value to be encrypted
type EncryptedInt int

Expand Down Expand Up @@ -116,6 +119,44 @@ func (ej *EncryptedJsonb) Deserialize(data []byte) (EncryptedJsonb, error) {
return nil, fmt.Errorf("invalid format: missing 'p' field in JSONB")
}

// Serialize turns a EncryptedJsonbArray value into a jsonb payload for CipherStash Proxy
func (eja EncryptedJsonbArray) Serialize(table string, column string) ([]byte, error) {
// When setting a jsonb field in xorm to nil || an empty map || not including the field,
// the value that comes through here is map[]/
// Adding a check based on the go zero value https://go.dev/ref/spec#The_zero_value
if len(eja) == 0 {
return nil, nil
}

val, err := ToEncryptedColumn([]interface{}(eja), table, column, nil)
if err != nil {
return nil, fmt.Errorf("error serializing: %v", err)
}
return json.Marshal(val)
}

// Deserialize turns a jsonb payload from CipherStash Proxy into an EncryptedJsonbArray value
func (ej *EncryptedJsonbArray) Deserialize(data []byte) (EncryptedJsonbArray, error) {

Check failure on line 139 in goeql.go

View workflow job for this annotation

GitHub Actions / Run test suite

receiver name ej should be consistent with previous receiver name eja for EncryptedJsonbArray
if len(data) == 0 {
return nil, nil
}
var jsonData map[string]interface{}
if err := json.Unmarshal(data, &jsonData); err != nil {
return nil, err
}

if pValue, ok := jsonData["p"].(string); ok {
var pData []interface{}
if err := json.Unmarshal([]byte(pValue), &pData); err != nil {
return nil, fmt.Errorf("error unmarshaling 'p' JSON string: %v", err)
}

return EncryptedJsonbArray(pData), nil
}

return nil, fmt.Errorf("invalid format: missing 'p' field in JSONB")
}

// Serialize turns a EncryptedInt value into a jsonb payload for CipherStash Proxy
func (ei EncryptedInt) Serialize(table string, column string) ([]byte, error) {
val, err := ToEncryptedColumn(int(ei), table, column, nil)
Expand Down

0 comments on commit 995e147

Please sign in to comment.