github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/value/signature/jws/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 jws 19 20 import ( 21 "context" 22 "fmt" 23 24 "gopkg.in/square/go-jose.v2" 25 26 "github.com/zntrio/harp/v2/pkg/sdk/types" 27 "github.com/zntrio/harp/v2/pkg/sdk/value/signature" 28 ) 29 30 type jwsTransformer struct { 31 key jose.SigningKey 32 } 33 34 // ----------------------------------------------------------------------------- 35 36 func (d *jwsTransformer) To(ctx context.Context, input []byte) ([]byte, error) { 37 if types.IsNil(d.key.Key) { 38 return nil, fmt.Errorf("jws: signer key must not be nil") 39 } 40 41 opts := &jose.SignerOptions{} 42 43 // If not deterministic add nonce in the protected header 44 if !signature.IsDeterministic(ctx) { 45 opts.NonceSource = &nonceSource{} 46 } 47 48 // Initialize a signer 49 signer, err := jose.NewSigner(d.key, opts) 50 if err != nil { 51 return nil, fmt.Errorf("jws: unable to initialize a signer: %w", err) 52 } 53 54 // Sign input 55 sig, err := signer.Sign(input) 56 if err != nil { 57 return nil, fmt.Errorf("jws: unable to sign the content: %w", err) 58 } 59 60 // Serialize content 61 out, errSerialization := sig.CompactSerialize() 62 63 if errSerialization != nil { 64 return nil, fmt.Errorf("jws: unable to serialize final payload: %w", errSerialization) 65 } 66 67 // No error 68 return []byte(out), nil 69 } 70 71 func (d *jwsTransformer) From(ctx context.Context, input []byte) ([]byte, error) { 72 // Parse the signed object 73 sig, err := jose.ParseSigned(string(input)) 74 if err != nil { 75 return nil, fmt.Errorf("jws: unable to parse input: %w", err) 76 } 77 78 // Verify signature 79 payload, err := sig.Verify(d.key.Key) 80 if err != nil { 81 return nil, fmt.Errorf("jws: unable to validate signature: %w", err) 82 } 83 84 // No error 85 return payload, nil 86 }