github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/value/encryption/branca/transformer.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package branca 19 20 import ( 21 "context" 22 "encoding/base64" 23 "fmt" 24 "strings" 25 26 "github.com/essentialkaos/branca" 27 28 "github.com/zntrio/harp/v2/pkg/sdk/value" 29 "github.com/zntrio/harp/v2/pkg/sdk/value/encryption" 30 ) 31 32 func init() { 33 encryption.Register("branca", Transformer) 34 } 35 36 // Transformer returns a branca encryption transformer. 37 func Transformer(key string) (value.Transformer, error) { 38 // Remove the prefix 39 key = strings.TrimPrefix(key, "branca:") 40 41 // Decode key 42 k, err := base64.URLEncoding.DecodeString(key) 43 if err != nil { 44 return nil, fmt.Errorf("branca: unable to decode key: %w", err) 45 } 46 47 // Check given keys 48 codec, err := branca.NewBranca(k) 49 if err != nil { 50 return nil, fmt.Errorf("branca: unable to initialize the key: %w", err) 51 } 52 53 // Return decorator constructor 54 return &brancaTransformer{ 55 codec: codec, 56 }, nil 57 } 58 59 // ----------------------------------------------------------------------------- 60 61 type brancaTransformer struct { 62 codec *branca.Branca 63 } 64 65 func (d *brancaTransformer) To(_ context.Context, input []byte) ([]byte, error) { 66 // Encrypt value 67 out, err := d.codec.Encode(input) 68 if err != nil { 69 return nil, fmt.Errorf("branca: unable to transform input value: %w", err) 70 } 71 72 // No error 73 return out, nil 74 } 75 76 func (d *brancaTransformer) From(_ context.Context, input []byte) ([]byte, error) { 77 // Decrypt value without checking expiration 78 out, err := d.codec.Decode(input) 79 if err != nil { 80 return nil, fmt.Errorf("branca: unable to decrypt branca token: %w", err) 81 } 82 83 // No error 84 return out.Payload(), nil 85 }