Enable TLS on asset-transfer-basic external chaincode

1. Introduce environment variables to enable or disable TLS
at runtime. Also, introduce environment variables which carries
the server key, cert and the client machine's root CA cert
information.
2. Read the environment variables to decide with appropriate
assumptions on default values to work as is today.

Signed-off-by: S m, Aruna <arun.s.m.cse@gmail.com>
This commit is contained in:
S m, Aruna 2021-04-18 04:38:11 +05:30
parent c5e190680f
commit 95d39673ea
No known key found for this signature in database
GPG key ID: 0E27DEADAA8A3DD4

View file

@ -7,8 +7,10 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"os" "os"
"strconv"
"github.com/hyperledger/fabric-chaincode-go/shim" "github.com/hyperledger/fabric-chaincode-go/shim"
"github.com/hyperledger/fabric-contract-api-go/contractapi" "github.com/hyperledger/fabric-contract-api-go/contractapi"
@ -224,12 +226,58 @@ func main() {
CCID: config.CCID, CCID: config.CCID,
Address: config.Address, Address: config.Address,
CC: chaincode, CC: chaincode,
TLSProps: shim.TLSProperties{ TLSProps: getTLSProperties(),
Disabled: true,
},
} }
if err := server.Start(); err != nil { if err := server.Start(); err != nil {
log.Panicf("error starting asset-transfer-basic chaincode: %s", err) log.Panicf("error starting asset-transfer-basic chaincode: %s", err)
} }
} }
func getTLSProperties() shim.TLSProperties {
// Check if chaincode is TLS enabled
tlsDisabledStr := getEnvOrDefault("CHAINCODE_TLS_DISABLED", "true")
key := getEnvOrDefault("CHAINCODE_TLS_KEY", "")
cert := getEnvOrDefault("CHAINCODE_TLS_CERT", "")
clientCACert := getEnvOrDefault("CHAINCODE_CLIENT_CA_CERT", "")
// convert tlsDisabledStr to boolean
tlsDisabled := getBoolOrDefault(tlsDisabledStr, false)
keyBytes, err := ioutil.ReadFile(key)
if err != nil {
log.Panicf("error while reading the crypto file: %s", err)
}
certBytes, err := ioutil.ReadFile(cert)
if err != nil {
log.Panicf("error while reading the crypto file: %s", err)
}
clientCACertBytes, err := ioutil.ReadFile(clientCACert)
if err != nil {
log.Panicf("error while reading the crypto file: %s", err)
}
return shim.TLSProperties{
Disabled: tlsDisabled,
Key: keyBytes,
Cert: certBytes,
ClientCACerts: clientCACertBytes,
}
}
func getEnvOrDefault(env, defaultVal string) string {
value, ok := os.LookupEnv(env)
if !ok {
value = defaultVal
}
return value
}
// Note that the method returns default value if the string
// cannot be parsed!
func getBoolOrDefault(value string, defaultVal bool) bool {
parsed, err := strconv.ParseBool(value)
if err!= nil {
return defaultVal
}
return parsed
}