Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: JWS for signature package #76

Merged
merged 8 commits into from
Sep 21, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
519 changes: 0 additions & 519 deletions signature/jws.go

This file was deleted.

183 changes: 183 additions & 0 deletions signature/jws/conformance_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
package jws

import (
"crypto/elliptic"
"crypto/x509"
"encoding/json"
"os"
"reflect"
"sort"
"strings"
"testing"
"time"

"github.com/notaryproject/notation-core-go/signature"
"github.com/notaryproject/notation-core-go/testhelper"
)

var (
// prepare signing time
signingTime, _ = time.Parse("2006-01-02 15:04:05", "2022-08-29 13:50:00")
expiry, _ = time.Parse("2006-01-02 15:04:05", "2099-08-29 13:50:00")
// signedAttributes for signing request
signedAttributes = signature.SignedAttributes{
SigningScheme: "notary.x509",
SigningTime: signingTime.Truncate(time.Second),
Expiry: expiry.Truncate(time.Second).Add(time.Hour * 24),
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
ExtendedAttributes: sortAttributes([]signature.Attribute{
{Key: "signedCritKey1", Value: "signedCritValue1", Critical: true},
{Key: "signedKey1", Value: "signedValue1", Critical: false},
{Key: "signedKey2", Value: "signedValue1", Critical: false},
{Key: "signedKey3", Value: "signedValue1", Critical: false},
{Key: "signedKey4", Value: "signedValue1", Critical: false},
}),
}
// unsignedAttributes for signing request
unsignedAttributes = signature.UnsignedAttributes{
SigningAgent: "NotationConformanceTest/1.0.0",
}
// payload to be signed
payload = signature.Payload{
ContentType: "application/vnd.cncf.notary.payload.v1+json",
Content: []byte(`{"key":"hello JWS"}`),
}
// certificate chain for signer
leafCertTuple = testhelper.GetECCertTuple(elliptic.P256())
certs = []*x509.Certificate{leafCertTuple.Cert, testhelper.GetECRootCertificate().Cert}
)

func conformanceTestSignReq() *signature.SignRequest {
signer, err := signature.NewLocalSigner(certs, leafCertTuple.PrivateKey)
if err != nil {
panic(err)
}

return &signature.SignRequest{
Payload: payload,
Signer: signer,
SigningTime: signedAttributes.SigningTime,
Expiry: signedAttributes.Expiry,
ExtendedSignedAttributes: signedAttributes.ExtendedAttributes,
SigningAgent: unsignedAttributes.SigningAgent,
SigningScheme: signedAttributes.SigningScheme,
}
}

// TestSignedMessageConformance check the conformance between the encoded message
// and the valid encoded message in conformance.json
//
// check payload, protected and signingAgent section
func TestSignedMessageConformance(t *testing.T) {
// get encoded message
env := envelope{}
signReq := conformanceTestSignReq()
encoded, err := env.Sign(signReq)
checkNoError(t, err)

// parse encoded message to be a map
envMap, err := unmarshalEncodedMessage(encoded)
checkNoError(t, err)
// load validation encoded message
validEnvMap, err := getValidEnvelopeMap()
checkNoError(t, err)

// check payload section conformance
if !reflect.DeepEqual(envMap["payload"], validEnvMap["payload"]) {
t.Fatal("signed message payload test failed.")
}

// check protected section conformance
if !reflect.DeepEqual(envMap["protected"], validEnvMap["protected"]) {
t.Fatal("signed message protected test failed.")
}

// prepare header
header, ok := envMap["header"].(map[string]interface{})
if !ok {
t.Fatal("signed message header format error.")
}
validHeader, ok := validEnvMap["header"].(map[string]interface{})
if !ok {
t.Fatal("conformance.json header format error.")
}
// check io.cncf.notary.signingAgent conformance
if !reflect.DeepEqual(header["io.cncf.notary.signingAgent"], validHeader["io.cncf.notary.signingAgent"]) {
t.Fatal("signed message signingAgent test failed.")
}
}

func getValidEnvelopeMap() (map[string]interface{}, error) {
encoded, err := os.ReadFile("./testdata/conformance.json")
if err != nil {
return nil, err
}
return unmarshalEncodedMessage(encoded)
}

func unmarshalEncodedMessage(encoded []byte) (envelopeMap map[string]interface{}, err error) {
err = json.Unmarshal(encoded, &envelopeMap)
return
}

// TestVerifyConformance generates JWS encoded message, parses the encoded message and
// verify the payload, signed/unsigned attributes conformance.
func TestVerifyConformance(t *testing.T) {
env := envelope{}
signReq := conformanceTestSignReq()
encoded, err := env.Sign(signReq)
checkNoError(t, err)

// parse envelope
var e jwsEnvelope
err = json.Unmarshal(encoded, &e)
checkNoError(t, err)
newEnv := envelope{base: &e}

// verify validity
content, err := newEnv.Verify()
checkNoError(t, err)

// check payload conformance
verifyPayload(t, &content.Payload)

// check signed/unsigned attributes conformance
verifyAttributes(t, &content.SignerInfo)
}

func verifyPayload(t *testing.T, gotPayload *signature.Payload) {
if !reflect.DeepEqual(&payload, gotPayload) {
t.Fatalf("verify payload failed. want: %+v got: %+v\n", &payload, gotPayload)
}
}

func verifyAttributes(t *testing.T, signerInfo *signature.SignerInfo) {
// check unsigned attributes
if !reflect.DeepEqual(&unsignedAttributes, &signerInfo.UnsignedAttributes) {
t.Fatalf("verify UnsignedAttributes failed. want: %+v got: %+v\n", &unsignedAttributes, &signerInfo.UnsignedAttributes)
}

// check signed attributes
sortAttributes(signerInfo.SignedAttributes.ExtendedAttributes)
if !reflect.DeepEqual(&signedAttributes, &signerInfo.SignedAttributes) {
t.Fatalf("verify SignedAttributes failed. want: %+v got: %+v\n", &signedAttributes, &signerInfo.SignedAttributes)
}

// check signature algorithm
keySpec, err := signature.ExtractKeySpec(certs[0])
checkNoError(t, err)
if keySpec.SignatureAlgorithm() != signerInfo.SignatureAlgorithm {
t.Fatalf("verify signature algorithm failed. want: %d got: %d\n", keySpec.SignatureAlgorithm(), signerInfo.SignatureAlgorithm)
}

// check certificate chain
if !reflect.DeepEqual(signerInfo.CertificateChain, certs) {
t.Fatalf("verify certificate chain failed. want: %+v got: %+v\n", &signerInfo.CertificateChain, certs)
}
}

func sortAttributes(attributes []signature.Attribute) []signature.Attribute {
sort.Slice(attributes, func(i, j int) bool {
return strings.Compare(attributes[i].Key, attributes[j].Key) < 0
})
return attributes
}
209 changes: 209 additions & 0 deletions signature/jws/envelope.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
package jws

import (
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"

"github.com/golang-jwt/jwt/v4"
"github.com/notaryproject/notation-core-go/signature"
"github.com/notaryproject/notation-core-go/signature/internal/base"
)

// MediaTypeEnvelope defines the media type name of JWS envelope.
const MediaTypeEnvelope = "application/jose+json"

func init() {
if err := signature.RegisterEnvelopeType(MediaTypeEnvelope, NewEnvelope, ParseEnvelope); err != nil {
panic(err)
}
}

type envelope struct {
base *jwsEnvelope
}

// NewEnvelope generates an JWS envelope.
func NewEnvelope() signature.Envelope {
return &base.Envelope{
Envelope: &envelope{},
}
}

// ParseEnvelope parses the envelope bytes and return a JWS envelope.
func ParseEnvelope(envelopeBytes []byte) (signature.Envelope, error) {
var e jwsEnvelope
err := json.Unmarshal(envelopeBytes, &e)
if err != nil {
return nil, &signature.InvalidSignatureError{Msg: err.Error()}
}
return &base.Envelope{
Envelope: &envelope{base: &e},
Raw: envelopeBytes,
}, nil
}

// Sign generates and sign the envelope according to the sign request.
func (e *envelope) Sign(req *signature.SignRequest) ([]byte, error) {
// get signingMethod for JWT package
method, err := getSigningMethod(req.Signer)
if err != nil {
return nil, &signature.InvalidSignRequestError{Msg: err.Error()}
}

// get all attributes ready to be signed
signedAttrs, err := getSignedAttributes(req, method.Alg())
if err != nil {
return nil, &signature.InvalidSignRequestError{Msg: err.Error()}
}

// parse payload as jwt.MapClaims
// [jwt-go]: https://pkg.go.dev/github.com/dgrijalva/jwt-go#MapClaims
var payload jwt.MapClaims
if err = json.Unmarshal(req.Payload.Content, &payload); err != nil {
return nil, &signature.InvalidSignRequestError{
Msg: fmt.Sprintf("payload format error: %v", err.Error())}
}

// JWT sign and get certificate chain
compact, certs, err := sign(payload, signedAttrs, method)
if err != nil {
return nil, &signature.InvalidSignRequestError{Msg: err.Error()}
}

// generate envelope
env, err := generateJWS(compact, req, certs)
if err != nil {
return nil, &signature.InvalidSignatureError{Msg: err.Error()}
}

encoded, err := json.Marshal(env)
if err != nil {
return nil, &signature.InvalidSignatureError{Msg: err.Error()}
}
e.base = env
return encoded, nil
}

// Verify verifies the envelope and returns its enclosed payload and signer info.
func (e *envelope) Verify() (*signature.EnvelopeContent, error) {
if e.base == nil {
return nil, &signature.SignatureEnvelopeNotFoundError{}
}

if len(e.base.Header.CertChain) == 0 {
return nil, &signature.InvalidSignatureError{Msg: "certificate chain is not set"}
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
}

cert, err := x509.ParseCertificate(e.base.Header.CertChain[0])
if err != nil {
return nil, &signature.InvalidSignatureError{Msg: "malformed leaf certificate"}
}

// verify JWT
compact := compactJWS(e.base)
if err = verifyJWT(compact, cert.PublicKey); err != nil {
return nil, err
}

return e.Content()
}

// Content returns the payload and signer information of the envelope.
// Content is trusted only after the successful call to `Verify()`.
func (e *envelope) Content() (*signature.EnvelopeContent, error) {
if e.base == nil {
return nil, &signature.SignatureEnvelopeNotFoundError{}
}

// parse protected headers
protected, err := parseProtectedHeaders(e.base.Protected)
if err != nil {
return nil, err
}

// extract payload
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
payload, err := e.payload(protected)
if err != nil {
return nil, err
}

// extract signer info
signerInfo, err := e.signerInfo(protected)
if err != nil {
return nil, err
}
return &signature.EnvelopeContent{
SignerInfo: *signerInfo,
Payload: *payload,
}, nil
}

// payload returns the payload of JWS envelope.
func (e *envelope) payload(protected *jwsProtectedHeader) (*signature.Payload, error) {
payload, err := base64.RawURLEncoding.DecodeString(e.base.Payload)
if err != nil {
return nil, &signature.InvalidSignatureError{
Msg: fmt.Sprintf("payload error: %v", err)}
}

return &signature.Payload{
Content: payload,
ContentType: protected.ContentType,
}, nil
}

// signerInfo returns the SignerInfo of JWS envelope.
func (e *envelope) signerInfo(protected *jwsProtectedHeader) (*signature.SignerInfo, error) {
var signerInfo signature.SignerInfo

// populate protected header to signerInfo
if err := populateProtectedHeaders(protected, &signerInfo); err != nil {
return nil, err
}

// parse signature
sig, err := base64.RawURLEncoding.DecodeString(e.base.Signature)
if err != nil {
return nil, &signature.InvalidSignatureError{Msg: err.Error()}
}
if len(sig) == 0 {
return nil, &signature.InvalidSignatureError{Msg: "cose envelope missing signature"}
JeyJeyGao marked this conversation as resolved.
Show resolved Hide resolved
}
signerInfo.Signature = sig

// parse headers
var certs []*x509.Certificate
for _, certBytes := range e.base.Header.CertChain {
cert, err := x509.ParseCertificate(certBytes)
if err != nil {
return nil, &signature.InvalidSignatureError{Msg: err.Error()}
}
certs = append(certs, cert)
}
signerInfo.CertificateChain = certs
signerInfo.UnsignedAttributes.SigningAgent = e.base.Header.SigningAgent
signerInfo.UnsignedAttributes.TimestampSignature = e.base.Header.TimestampSignature
return &signerInfo, nil
}

// sign the given payload and headers using the given signature provider.
func sign(payload jwt.MapClaims, headers map[string]interface{}, method signingMethod) (string, []*x509.Certificate, error) {
// generate token
token := jwt.NewWithClaims(method, payload)
token.Header = headers

// sign and return compact JWS
compact, err := token.SignedString(method.PrivateKey())
if err != nil {
return "", nil, err
}

// access certificate chain after sign
certs, err := method.CertificateChain()
if err != nil {
return "", nil, err
}
return compact, certs, nil
}
Loading