repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/basic/client.go
pkg/infra/basic/client.go
package basic import ( "context" "crypto/tls" "github.com/hyperledger-twgc/tape/internal/fabric/core/comm" "github.com/hyperledger/fabric-protos-go-apiv2/orderer" "github.com/hyperledger/fabric-protos-go-apiv2/peer" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "google.golang.org/grpc" ) func CreateGRPCClient(node Node) (*comm.GRPCClient, error) { var certs [][]byte if node.TLSCACertByte != nil { certs = append(certs, node.TLSCACertByte) } config := comm.ClientConfig{} config.SecOpts = comm.SecureOptions{ UseTLS: false, RequireClientCert: false, ServerRootCAs: certs, } if len(certs) > 0 { config.SecOpts.UseTLS = true if len(node.TLSCAKey) > 0 && len(node.TLSCARoot) > 0 { config.SecOpts.RequireClientCert = true config.SecOpts.Certificate = node.TLSCACertByte config.SecOpts.Key = node.TLSCAKeyByte if node.TLSCARootByte != nil { config.SecOpts.ClientRootCAs = append(config.SecOpts.ClientRootCAs, node.TLSCARootByte) } } } grpcClient, err := comm.NewGRPCClient(config) //to do: unit test for this error, current fails to make case for this if err != nil { return nil, errors.Wrapf(err, "error connecting to %s", node.Addr) } return grpcClient, nil } func CreateEndorserClient(node Node, logger *log.Logger) (peer.EndorserClient, error) { conn, err := DialConnection(node, logger) if err != nil { return nil, err } return peer.NewEndorserClient(conn), nil } func CreateBroadcastClient(ctx context.Context, node Node, logger *log.Logger) (orderer.AtomicBroadcast_BroadcastClient, error) { conn, err := DialConnection(node, logger) if err != nil { return nil, err } return orderer.NewAtomicBroadcastClient(conn).Broadcast(ctx) } func CreateDeliverFilteredClient(ctx context.Context, node Node, logger *log.Logger) (peer.Deliver_DeliverFilteredClient, error) { conn, err := DialConnection(node, logger) if err != nil { return nil, err } return peer.NewDeliverClient(conn).DeliverFiltered(ctx) } // TODO: use a global get logger function instead inject a logger func DialConnection(node Node, logger *log.Logger) (*grpc.ClientConn, error) { gRPCClient, err := CreateGRPCClient(node) if err != nil { return nil, err } var connError error var conn *grpc.ClientConn for i := 1; i <= 3; i++ { conn, connError = gRPCClient.NewConnection(node.Addr, func(tlsConfig *tls.Config) { tlsConfig.InsecureSkipVerify = true tlsConfig.ServerName = node.SslTargetNameOverride }) if connError == nil { return conn, nil } else { logger.Errorf("%d of 3 attempts to make connection to %s, details: %s", i, node.Addr, connError) } } return nil, errors.Wrapf(connError, "error connecting to %s", node.Addr) } func CreateDeliverClient(node Node) (orderer.AtomicBroadcast_DeliverClient, error) { gRPCClient, err := CreateGRPCClient(node) if err != nil { return nil, err } conn, err := gRPCClient.NewConnection(node.Addr, func(tlsConfig *tls.Config) { tlsConfig.InsecureSkipVerify = true tlsConfig.ServerName = node.SslTargetNameOverride }) if err != nil { return nil, err } return orderer.NewAtomicBroadcastClient(conn).Deliver(context.Background()) }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/basic/config.go
pkg/infra/basic/config.go
package basic import ( "crypto/ecdsa" "crypto/x509" "encoding/pem" "os" "sync" "github.com/opentracing/opentracing-go" "github.com/hyperledger-twgc/tape/internal/fabric/bccsp/utils" "github.com/gogo/protobuf/proto" "github.com/hyperledger/fabric-protos-go-apiv2/common" "github.com/hyperledger/fabric-protos-go-apiv2/msp" "github.com/hyperledger/fabric-protos-go-apiv2/peer" "github.com/pkg/errors" yaml "gopkg.in/yaml.v2" ) type TracingProposal struct { *peer.Proposal TxId string Span opentracing.Span } type Elements struct { TxId string Span opentracing.Span EndorsementSpan opentracing.Span SignedProp *peer.SignedProposal Responses []*peer.ProposalResponse Orgs []string Processed bool Lock sync.Mutex } type TracingEnvelope struct { Env *common.Envelope TxId string Span opentracing.Span } type Config struct { Endorsers []Node `yaml:"endorsers"` Committers []Node `yaml:"committers"` CommitThreshold int `yaml:"commitThreshold"` Orderer Node `yaml:"orderer"` PolicyFile string `yaml:"policyFile"` Rule string Channel string `yaml:"channel"` Chaincode string `yaml:"chaincode"` Version string `yaml:"version"` Args []string `yaml:"args"` MSPID string `yaml:"mspid"` PrivateKey string `yaml:"private_key"` SignCert string `yaml:"sign_cert"` NumOfConn int `yaml:"num_of_conn"` ClientPerConn int `yaml:"client_per_conn"` } type Node struct { Addr string `yaml:"addr"` SslTargetNameOverride string `yaml:"ssl_target_name_override"` TLSCACert string `yaml:"tls_ca_cert"` Org string `yaml:"org"` TLSCAKey string `yaml:"tls_ca_key"` TLSCARoot string `yaml:"tls_ca_root"` TLSCACertByte []byte TLSCAKeyByte []byte TLSCARootByte []byte } func LoadConfig(f string) (Config, error) { config := Config{} raw, err := os.ReadFile(f) if err != nil { return config, errors.Wrapf(err, "error loading %s", f) } err = yaml.Unmarshal(raw, &config) if err != nil { return config, errors.Wrapf(err, "error unmarshal %s", f) } if len(config.PolicyFile) == 0 && config.PolicyFile == "" { return config, errors.New("empty endorsement policy") } // config.Rule read from PolicyFile in, err := os.ReadFile(config.PolicyFile) if err != nil { return config, err } config.Rule = string(in) for i := range config.Endorsers { err = config.Endorsers[i].LoadConfig() if err != nil { return config, err } } for i := range config.Committers { err = config.Committers[i].LoadConfig() if err != nil { return config, err } } err = config.Orderer.LoadConfig() if err != nil { return config, err } return config, nil } func (c Config) LoadCrypto() (*CryptoImpl, error) { conf := CryptoConfig{ MSPID: c.MSPID, PrivKey: c.PrivateKey, SignCert: c.SignCert, } priv, err := GetPrivateKey(conf.PrivKey) if err != nil { return nil, errors.Wrapf(err, "error loading priv key") } cert, certBytes, err := GetCertificate(conf.SignCert) if err != nil { return nil, errors.Wrapf(err, "error loading certificate") } id := &msp.SerializedIdentity{ Mspid: conf.MSPID, IdBytes: certBytes, } name, err := proto.Marshal(id) if err != nil { return nil, errors.Wrapf(err, "error get msp id") } return &CryptoImpl{ Creator: name, PrivKey: priv, SignCert: cert, }, nil } func GetTLSCACerts(file string) ([]byte, error) { if len(file) == 0 { return nil, nil } in, err := os.ReadFile(file) if err != nil { return nil, errors.Wrapf(err, "error loading %s", file) } return in, nil } func (n *Node) LoadConfig() error { TLSCACert, err := GetTLSCACerts(n.TLSCACert) if err != nil { return errors.Wrapf(err, "fail to load TLS CA Cert %s", n.TLSCACert) } certPEM, err := GetTLSCACerts(n.TLSCAKey) if err != nil { return errors.Wrapf(err, "fail to load TLS CA Key %s", n.TLSCAKey) } TLSCARoot, err := GetTLSCACerts(n.TLSCARoot) if err != nil { return errors.Wrapf(err, "fail to load TLS CA Root %s", n.TLSCARoot) } n.TLSCACertByte = TLSCACert n.TLSCAKeyByte = certPEM n.TLSCARootByte = TLSCARoot return nil } func GetPrivateKey(f string) (*ecdsa.PrivateKey, error) { in, err := os.ReadFile(f) if err != nil { return nil, err } k, err := utils.PEMtoPrivateKey(in, []byte{}) if err != nil { return nil, err } key, ok := k.(*ecdsa.PrivateKey) if !ok { return nil, errors.Errorf("expecting ecdsa key") } return key, nil } func GetCertificate(f string) (*x509.Certificate, []byte, error) { in, err := os.ReadFile(f) if err != nil { return nil, nil, err } block, _ := pem.Decode(in) c, err := x509.ParseCertificate(block.Bytes) return c, in, err }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/basic/client_test.go
pkg/infra/basic/client_test.go
//go:build !race // +build !race package basic_test import ( "context" "github.com/hyperledger-twgc/tape/e2e/mock" "github.com/hyperledger-twgc/tape/pkg/infra/basic" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" log "github.com/sirupsen/logrus" ) var _ = Describe("Client", func() { Context("connect with mock peer", func() { var mockserver *mock.Server var peerNode, OrdererNode basic.Node logger := log.New() BeforeEach(func() { mockserver, _ = mock.NewServer(1, nil) peerNode = basic.Node{ Addr: mockserver.PeersAddresses()[0], } OrdererNode = basic.Node{ Addr: mockserver.OrderAddr(), } mockserver.Start() }) AfterEach(func() { mockserver.Stop() }) It("connect with mock endorsers", func() { _, err := basic.CreateEndorserClient(peerNode, logger) Expect(err).ShouldNot(HaveOccurred()) }) It("connect with mock broadcasters", func() { _, err := basic.CreateBroadcastClient(context.Background(), peerNode, logger) Expect(err).ShouldNot(HaveOccurred()) }) It("connect with mock DeliverFilter", func() { _, err := basic.CreateDeliverFilteredClient(context.Background(), OrdererNode, logger) Expect(err).ShouldNot(HaveOccurred()) }) It("connect with mock CreateDeliverClient", func() { _, err := basic.CreateDeliverClient(OrdererNode) Expect(err).ShouldNot(HaveOccurred()) }) It("wrong addr test", func() { dummy := basic.Node{ Addr: "invalid_addr", TLSCACertByte: []byte(""), TLSCAKey: "123", TLSCARoot: "234", TLSCARootByte: []byte(""), } _, err := basic.CreateGRPCClient(dummy) Expect(err).Should(HaveOccurred()) }) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/basic/config_test.go
pkg/infra/basic/config_test.go
package basic_test import ( "os" "text/template" "github.com/hyperledger-twgc/tape/pkg/infra/basic" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) type files struct { TlsFile string PolicyFile string } func generateConfigFile(FileName string, values interface{}) { var Text = `# Definition of nodes org1peer0: &org1peer0 addr: localhost:7051 ssl_target_name_override: peer0.org1.example.com tls_ca_cert: {{.TlsFile}} org: org1 org2peer0: &org2peer0 addr: peer0.org2.example.com:7051 tls_ca_cert: {{.TlsFile}} org: org2 org0orderer0: &org0orderer0 addr: orderer.example.com:7050 tls_ca_cert: {{.TlsFile}} org: org0 endorsers: - *org1peer0 - *org2peer0 committers: - *org2peer0 commitThreshold: 1 orderer: *org0orderer0 policyFile: {{.PolicyFile}} channel: mychannel chaincode: mycc args: - invoke - a - b - 1 mspid: Org1MSP private_key: /path/to/private.key sign_cert: /path/to/sign.cert num_of_conn: 20 client_per_conn: 40 ` tmpl, err := template.New("test").Parse(Text) if err != nil { panic(err) } file, err := os.OpenFile(FileName, os.O_CREATE|os.O_WRONLY, 0755) if err != nil { panic(err) } defer file.Close() err = tmpl.Execute(file, values) if err != nil { panic(err) } } var _ = Describe("Config", func() { Context("good", func() { It("successful loads", func() { tlsFile, err := os.CreateTemp("", "dummy-*.pem") Expect(err).NotTo(HaveOccurred()) defer os.Remove(tlsFile.Name()) _, err = tlsFile.Write([]byte("a")) Expect(err).NotTo(HaveOccurred()) policyFile, err := os.CreateTemp("", "dummy-*.pem") Expect(err).NotTo(HaveOccurred()) defer os.Remove(policyFile.Name()) _, err = policyFile.Write([]byte("b")) Expect(err).NotTo(HaveOccurred()) f, _ := os.CreateTemp("", "config-*.yaml") defer os.Remove(f.Name()) file := files{TlsFile: tlsFile.Name(), PolicyFile: policyFile.Name()} generateConfigFile(f.Name(), file) c, err := basic.LoadConfig(f.Name()) Expect(err).NotTo(HaveOccurred()) Expect(c).To(Equal(basic.Config{ Endorsers: []basic.Node{ {Addr: "localhost:7051", SslTargetNameOverride: "peer0.org1.example.com", TLSCACert: tlsFile.Name(), TLSCACertByte: []byte("a"), Org: "org1"}, {Addr: "peer0.org2.example.com:7051", TLSCACert: tlsFile.Name(), TLSCACertByte: []byte("a"), Org: "org2"}, }, Committers: []basic.Node{{Addr: "peer0.org2.example.com:7051", TLSCACert: tlsFile.Name(), TLSCACertByte: []byte("a"), Org: "org2"}}, CommitThreshold: 1, Orderer: basic.Node{Addr: "orderer.example.com:7050", TLSCACert: tlsFile.Name(), TLSCACertByte: []byte("a"), Org: "org0"}, PolicyFile: policyFile.Name(), Rule: "b", Channel: "mychannel", Chaincode: "mycc", Version: "", Args: []string{"invoke", "a", "b", "1"}, MSPID: "Org1MSP", PrivateKey: "/path/to/private.key", SignCert: "/path/to/sign.cert", NumOfConn: 20, ClientPerConn: 40, })) _, err = c.LoadCrypto() Expect(err).Should(MatchError(ContainSubstring("error loading priv key"))) }) }) Context("bad", func() { It("fails to load missing config file", func() { _, err := basic.LoadConfig("invalid_file") Expect(err).Should(MatchError(ContainSubstring("invalid_file"))) }) It("fails to load invalid config file", func() { f, _ := os.CreateTemp("", "config-*.yaml") defer os.Remove(f.Name()) file := files{TlsFile: "invalid_file", PolicyFile: "invalid_file"} generateConfigFile(f.Name(), file) _, err := basic.LoadConfig(f.Name()) Expect(err).Should(MatchError(ContainSubstring("invalid_file"))) }) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/basic/basic_suite_test.go
pkg/infra/basic/basic_suite_test.go
package basic_test import ( "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) func TestBasic(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Basic Suite") }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/basic/crypto.go
pkg/infra/basic/crypto.go
package basic import ( "crypto/ecdsa" "crypto/rand" "crypto/sha256" "crypto/x509" "encoding/asn1" "math/big" "github.com/hyperledger-twgc/tape/internal/fabric/bccsp/utils" "github.com/hyperledger-twgc/tape/internal/fabric/common/crypto" "github.com/hyperledger/fabric-protos-go-apiv2/common" ) type CryptoConfig struct { MSPID string PrivKey string SignCert string TLSCACerts []string } type ECDSASignature struct { R, S *big.Int } type CryptoImpl struct { Creator []byte PrivKey *ecdsa.PrivateKey SignCert *x509.Certificate } func (s *CryptoImpl) Sign(msg []byte) ([]byte, error) { ri, si, err := ecdsa.Sign(rand.Reader, s.PrivKey, digest(msg)) if err != nil { return nil, err } si, _, err = utils.ToLowS(&s.PrivKey.PublicKey, si) if err != nil { return nil, err } return asn1.Marshal(ECDSASignature{ri, si}) } func (s *CryptoImpl) Serialize() ([]byte, error) { return s.Creator, nil } func (s *CryptoImpl) NewSignatureHeader() (*common.SignatureHeader, error) { creator, err := s.Serialize() if err != nil { return nil, err } nonce, err := crypto.GetRandomNonce() if err != nil { return nil, err } return &common.SignatureHeader{ Creator: creator, Nonce: nonce, }, nil } func digest(in []byte) []byte { h := sha256.New() h.Write(in) return h.Sum(nil) }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/basic/logger.go
pkg/infra/basic/logger.go
package basic import ( "io" "sync" "time" "github.com/opentracing/opentracing-go" "github.com/prometheus/client_golang/prometheus" log "github.com/sirupsen/logrus" jaeger "github.com/uber/jaeger-client-go" "github.com/uber/jaeger-client-go/config" ) func LogEvent(logger *log.Logger, txid, event string) { now := time.Now() time_str := now.Format(time.RFC3339Nano) logger.Debugf("For txid %s, event %s at %s", txid, event, time_str) } // Init returns an instance of Jaeger Tracer that samples 100% // of traces and logs all spans to stdout. func Init(service string) (opentracing.Tracer, io.Closer) { cfg := &config.Configuration{ Sampler: &config.SamplerConfig{ Type: "const", Param: 1, }, Reporter: &config.ReporterConfig{ LogSpans: false, }, } cfg.ServiceName = service tracer, closer, err := cfg.NewTracer( config.Logger(jaeger.StdLogger), ) if err != nil { log.Fatalf("ERROR: cannot init Jaeger: %v", err) } return tracer, closer } const ( TRANSACTION = "TRANSACTION" TRANSACTIONSTART = "TRANSACTIONSTART" SIGN_PROPOSAL = "SIGN_PROPOSAL" ENDORSEMENT = "ENDORSEMENT" ENDORSEMENT_AT_PEER = "ENDORSEMENT_AT_PEER" COLLECT_ENDORSEMENT = "COLLECT_ENDORSEMENT" SIGN_ENVELOP = "SIGN_ENVELOP" BROADCAST = "BROADCAST" CONSESUS = "CONSESUS" COMMIT_AT_NETWORK = "COMMIT_AT_NETWORK" COMMIT_AT_PEER = "COMMIT_AT_PEER" COMMIT_AT_ALL_PEERS = "COMMIT_AT_ALL_PEERS" ) var TapeSpan *TracingSpans var LatencyM *LatencyMap var ProcessMod int var onceSpan sync.Once type LatencyMap struct { Map map[string]time.Time Lock sync.Mutex Mod int Transactionlatency, Readlatency *prometheus.SummaryVec Enable bool } type TracingSpans struct { Spans map[string]opentracing.Span Lock sync.Mutex } func (TS *TracingSpans) MakeSpan(txid, address, event string, parent opentracing.Span) opentracing.Span { str := event + address if parent == nil { return opentracing.GlobalTracer().StartSpan(str, opentracing.Tag{Key: "txid", Value: txid}) } else { return opentracing.GlobalTracer().StartSpan(str, opentracing.ChildOf(parent.Context()), opentracing.Tag{Key: "txid", Value: txid}) } } func (TS *TracingSpans) GetSpan(txid, address, event string) opentracing.Span { TS.Lock.Lock() defer TS.Lock.Unlock() str := event + txid + address span, ok := TS.Spans[str] if ok { return span } return nil } func (TS *TracingSpans) SpanIntoMap(txid, address, event string, parent opentracing.Span) opentracing.Span { TS.Lock.Lock() defer TS.Lock.Unlock() str := event + txid + address span, ok := TS.Spans[str] if !ok { span = TS.MakeSpan(txid, address, event, parent) TS.Spans[str] = span } return span } func (TS *TracingSpans) FinishWithMap(txid, address, event string) { TS.Lock.Lock() defer TS.Lock.Unlock() str := event + txid + address span, ok := TS.Spans[str] if ok { span.Finish() delete(TS.Spans, str) } } func GetGlobalSpan() *TracingSpans { onceSpan.Do(func() { Spans := make(map[string]opentracing.Span) TapeSpan = &TracingSpans{ Spans: Spans, } }) return TapeSpan } func SetMod(mod int) { ProcessMod = mod } func GetMod() int { return ProcessMod } func InitLatencyMap(Transactionlatency, Readlatency *prometheus.SummaryVec, Mod int, Enable bool) *LatencyMap { Map := make(map[string]time.Time) LatencyM = &LatencyMap{ Map: Map, Mod: Mod, Transactionlatency: Transactionlatency, Readlatency: Readlatency, Enable: Enable, } return GetLatencyMap() } func GetLatencyMap() *LatencyMap { return LatencyM } func (LM *LatencyMap) StartTracing(txid string) { if LM == nil { return } LM.Lock.Lock() defer LM.Lock.Unlock() if LM.Enable { LM.Map[txid] = time.Now() } } func (LM *LatencyMap) ReportReadLatency(txid, label string) { if LM == nil { return } LM.Lock.Lock() defer LM.Lock.Unlock() start_time, ok := LM.Map[txid] if ok && LM.Readlatency != nil { diff := time.Since(start_time) LM.Readlatency.WithLabelValues(label).Observe(diff.Seconds()) if LM.Mod == 4 || LM.Mod == 7 { delete(LM.Map, txid) } } } func (LM *LatencyMap) TransactionLatency(txid string) { if LM == nil { return } LM.Lock.Lock() defer LM.Lock.Unlock() start_time, ok := LM.Map[txid] if ok && LM.Transactionlatency != nil { diff := time.Since(start_time) LM.Transactionlatency.WithLabelValues("CommitAtPeersOverThreshold").Observe(diff.Seconds()) delete(LM.Map, txid) } }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/bitmap/bitmap_suite_test.go
pkg/infra/bitmap/bitmap_suite_test.go
package bitmap_test import ( "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) func TestBitmap(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Bitmap Suite") }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/bitmap/bitmap_test.go
pkg/infra/bitmap/bitmap_test.go
package bitmap_test import ( "github.com/hyperledger-twgc/tape/pkg/infra/bitmap" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Bitmap", func() { Context("New BitsMap", func() { It("the environment is properly set", func() { b, err := bitmap.NewBitMap(4) Expect(err).To(BeNil()) Expect(b.Cap()).To(Equal(4)) Expect(b.Count()).To(Equal(0)) Expect(b.BitsLen()).To(Equal(1)) b, err = bitmap.NewBitMap(65) Expect(err).To(BeNil()) Expect(b.Cap()).To(Equal(65)) Expect(b.Count()).To(Equal(0)) Expect(b.BitsLen()).To(Equal(2)) }) It("should error which cap is less than 1", func() { _, err := bitmap.NewBitMap(0) Expect(err).NotTo(BeNil()) _, err = bitmap.NewBitMap(-1) Expect(err).NotTo(BeNil()) }) }) Context("Operate BitsMap", func() { It("the len of bits is just one ", func() { b, err := bitmap.NewBitMap(4) Expect(err).To(BeNil()) b.Set(0) Expect(b.Count()).To(Equal(1)) b.Set(2) Expect(b.Count()).To(Equal(2)) ok := b.Has(0) Expect(ok).To(BeTrue()) ok = b.Has(2) Expect(ok).To(BeTrue()) ok = b.Has(1) Expect(ok).To(BeFalse()) ok = b.Has(4) Expect(ok).To(BeFalse()) b.Set(4) Expect(b.Count()).To(Equal(2)) b.Set(2) Expect(b.Count()).To(Equal(2)) }) It("the len of bits is more than one", func() { b, err := bitmap.NewBitMap(80) Expect(err).To(BeNil()) b.Set(0) Expect(b.Count()).To(Equal(1)) b.Set(2) Expect(b.Count()).To(Equal(2)) b.Set(70) Expect(b.Count()).To(Equal(3)) b.Set(79) Expect(b.Count()).To(Equal(4)) ok := b.Has(0) Expect(ok).To(BeTrue()) ok = b.Has(2) Expect(ok).To(BeTrue()) ok = b.Has(70) Expect(ok).To(BeTrue()) ok = b.Has(79) Expect(ok).To(BeTrue()) ok = b.Has(1) Expect(ok).To(BeFalse()) ok = b.Has(3) Expect(ok).To(BeFalse()) ok = b.Has(69) Expect(ok).To(BeFalse()) b.Set(80) Expect(b.Count()).To(Equal(4)) b.Set(2) Expect(b.Count()).To(Equal(4)) }) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/bitmap/bitmap.go
pkg/infra/bitmap/bitmap.go
package bitmap import "github.com/pkg/errors" type BitMap struct { count int // number of bits set capability int // total number of bits bits []uint64 } // Has determine whether the specified position is set func (b *BitMap) Has(num int) bool { if num >= b.capability { return false } c, bit := num/64, uint(num%64) return (c < len(b.bits)) && (b.bits[c]&(1<<bit) != 0) } // Set set the specified position // If the position has been set or exceeds the maximum number of bits, set is a no-op. func (b *BitMap) Set(num int) { if b.Has(num) { return } if b.capability <= num { return } c, bit := num/64, uint(num%64) b.bits[c] |= 1 << bit b.count++ } func (b *BitMap) Count() int { return b.count } func (b *BitMap) Cap() int { return b.capability } func (b *BitMap) BitsLen() int { return len(b.bits) } // NewBitsMap create a new BitsMap func NewBitMap(cap int) (BitMap, error) { if cap < 1 { return BitMap{}, errors.New("cap should not be less than 1") } bitsLen := cap / 64 if cap%64 > 0 { bitsLen++ } return BitMap{bits: make([]uint64, bitsLen), capability: cap}, nil }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/policyHandler.go
pkg/infra/trafficGenerator/policyHandler.go
package trafficGenerator import ( "context" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/open-policy-agent/opa/rego" ) func CheckPolicy(input *basic.Elements, rule string) (bool, error) { if input.Processed { return false, nil } rego := rego.New( rego.Query("data.tape.allow"), rego.Module("", rule), rego.Input(input.Orgs), ) rs, err := rego.Eval(context.Background()) if err != nil { return false, err } input.Processed = rs.Allowed() return rs.Allowed(), nil }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/proposal_test.go
pkg/infra/trafficGenerator/proposal_test.go
package trafficGenerator_test import ( "regexp" "strconv" "github.com/hyperledger-twgc/tape/pkg/infra/trafficGenerator" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Proposal", func() { Context("ConvertString", func() { It("work accordingly for string", func() { input := "data" data, err := trafficGenerator.ConvertString(input) Expect(err).NotTo(HaveOccurred()) Expect(data).To(Equal("data")) }) It("work accordingly for random str", func() { input := "randomString1" data, err := trafficGenerator.ConvertString(input) Expect(err).NotTo(HaveOccurred()) Expect(len(data)).To(Equal(1)) }) It("work accordingly for uuid", func() { input := "uuid" data, err := trafficGenerator.ConvertString(input) Expect(err).NotTo(HaveOccurred()) Expect(len(data) > 0).To(BeTrue()) }) It("work accordingly for randomNumber", func() { input := "randomNumber1_9" data, err := trafficGenerator.ConvertString(input) Expect(err).NotTo(HaveOccurred()) Expect(len(data)).To(Equal(1)) num, err := strconv.Atoi(data) Expect(err).NotTo(HaveOccurred()) Expect(num > 0).To(BeTrue()) }) It("work accordingly for string mix mode", func() { input := "{\"key\":\"randomNumber1_50\",\"key1\":\"randomNumber1_20\"}" data, err := trafficGenerator.ConvertString(input) Expect(err).NotTo(HaveOccurred()) regString, err := regexp.Compile("{\"key\":\"\\d*\",\"key1\":\"\\d*\"}") Expect(err).NotTo(HaveOccurred()) Expect(regString.MatchString(data)).To(BeTrue()) }) It("work accordingly for string mix mode 2", func() { input := "{\"k1\":\"uuid\",\"key2\":\"randomNumber10000_20000\",\"keys\":\"randomString10\"}" data, err := trafficGenerator.ConvertString(input) Expect(err).NotTo(HaveOccurred()) regString, err := regexp.Compile("{\"k1\":\".*\",\"key2\":\"\\d*\",\"keys\":\".*\"}") Expect(err).NotTo(HaveOccurred()) Expect(regString.MatchString(data)).To(BeTrue()) }) It("handle edge case for randmon number", func() { input := "randomNumber1_00" _, err := trafficGenerator.ConvertString(input) Expect(err).To(HaveOccurred()) }) It("handle edge case for randmon number", func() { input := "randomNumber1_1" _, err := trafficGenerator.ConvertString(input) Expect(err).To(HaveOccurred()) }) It("handle edge case for randomstring", func() { input := "0randomString166666666011010" _, err := trafficGenerator.ConvertString(input) Expect(err).To(HaveOccurred()) }) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/initiator.go
pkg/infra/trafficGenerator/initiator.go
package trafficGenerator import ( "context" "github.com/hyperledger-twgc/tape/pkg/infra" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "golang.org/x/time/rate" ) type Initiator struct { Num int Burst int R float64 Config basic.Config Crypto infra.Crypto Logger *log.Logger Raw chan *basic.TracingProposal ErrorCh chan error } func (initiator *Initiator) Start() { limit := rate.Inf ctx := context.Background() if initiator.R > 0 { limit = rate.Limit(initiator.R) } limiter := rate.NewLimiter(limit, initiator.Burst) i := 0 for { if initiator.Num > 0 { if i == initiator.Num { return } i++ } prop, err := CreateProposal( initiator.Crypto, initiator.Logger, initiator.Config.Channel, initiator.Config.Chaincode, initiator.Config.Version, initiator.Config.Args..., ) if err != nil { initiator.ErrorCh <- errors.Wrapf(err, "error creating proposal") return } if err = limiter.Wait(ctx); err != nil { initiator.ErrorCh <- errors.Wrapf(err, "error creating proposal") return } initiator.Raw <- prop } }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/fackEnvelopGenerator.go
pkg/infra/trafficGenerator/fackEnvelopGenerator.go
package trafficGenerator import ( "github.com/hyperledger-twgc/tape/internal/fabric/protoutil" "github.com/hyperledger-twgc/tape/pkg/infra" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/opentracing/opentracing-go" "github.com/hyperledger/fabric-protos-go-apiv2/common" ) type FackEnvelopGenerator struct { Num int Burst int R float64 Config basic.Config Crypto infra.Crypto Envs chan *basic.TracingEnvelope ErrorCh chan error } var nonce = []byte("nonce-abc-12345") var data = []byte("data") func (initiator *FackEnvelopGenerator) Start() { i := 0 for { if initiator.Num > 0 { if i == initiator.Num { return } i++ } creator, _ := initiator.Crypto.Serialize() txid := protoutil.ComputeTxID(nonce, creator) payloadBytes, _ := protoutil.GetBytesPayload(&common.Payload{ Header: &common.Header{ ChannelHeader: protoutil.MarshalOrPanic(&common.ChannelHeader{ Type: int32(common.HeaderType_ENDORSER_TRANSACTION), ChannelId: initiator.Config.Channel, TxId: txid, Epoch: uint64(0), }), SignatureHeader: protoutil.MarshalOrPanic(&common.SignatureHeader{ Creator: creator, Nonce: nonce, }), }, Data: data, }) signature, _ := initiator.Crypto.Sign(payloadBytes) env := &common.Envelope{ Payload: payloadBytes, Signature: signature, } span := opentracing.GlobalTracer().StartSpan("integrator for endorsements ", opentracing.Tag{Key: "txid", Value: txid}) initiator.Envs <- &basic.TracingEnvelope{Env: env, TxId: txid, Span: span} } }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/intgerator.go
pkg/infra/trafficGenerator/intgerator.go
package trafficGenerator import ( "context" "github.com/hyperledger-twgc/tape/pkg/infra" "github.com/hyperledger-twgc/tape/pkg/infra/basic" log "github.com/sirupsen/logrus" ) type Integrator struct { Signer infra.Crypto Ctx context.Context Processed chan *basic.Elements Envs chan *basic.TracingEnvelope ErrorCh chan error Logger *log.Logger } func (integrator *Integrator) assemble(e *basic.Elements) (*basic.TracingEnvelope, error) { tapeSpan := basic.GetGlobalSpan() span := tapeSpan.MakeSpan(e.TxId, "", basic.SIGN_ENVELOP, e.Span) defer span.Finish() env, err := CreateSignedTx(e.SignedProp, integrator.Signer, e.Responses) // end integration proposal basic.LogEvent(integrator.Logger, e.TxId, "CreateSignedEnvelope") if err != nil { return nil, err } return &basic.TracingEnvelope{Env: env, TxId: e.TxId, Span: e.Span}, nil } func (integrator *Integrator) Start() { for { select { case p := <-integrator.Processed: e, err := integrator.assemble(p) if err != nil { integrator.ErrorCh <- err return } integrator.Envs <- e case <-integrator.Ctx.Done(): return } } }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/generatorFactory.go
pkg/infra/trafficGenerator/generatorFactory.go
package trafficGenerator import ( "context" "github.com/hyperledger-twgc/tape/pkg/infra" "github.com/hyperledger-twgc/tape/pkg/infra/basic" log "github.com/sirupsen/logrus" ) type TrafficGenerator struct { ctx context.Context crypto infra.Crypto raw chan *basic.TracingProposal signed []chan *basic.Elements envs chan *basic.TracingEnvelope processed chan *basic.Elements config basic.Config num int burst int signerNumber int parallel int rate float64 logger *log.Logger errorCh chan error } func NewTrafficGenerator(ctx context.Context, crypto infra.Crypto, envs chan *basic.TracingEnvelope, raw chan *basic.TracingProposal, processed chan *basic.Elements, signed []chan *basic.Elements, config basic.Config, num int, burst, signerNumber, parallel int, rate float64, logger *log.Logger, errorCh chan error) *TrafficGenerator { return &TrafficGenerator{ ctx: ctx, crypto: crypto, raw: raw, signed: signed, envs: envs, processed: processed, config: config, num: num, parallel: parallel, burst: burst, signerNumber: signerNumber, rate: rate, logger: logger, errorCh: errorCh, } } // table | proposal boradcaster fake // full process | 1 1 0 6 // commit | 0 1 1 3 // query | 1 0 0 4 func (t *TrafficGenerator) CreateGeneratorWorkers(mode int) ([]infra.Worker, error) { generator_workers := make([]infra.Worker, 0) // if create proposers int/4 = 1 if mode/infra.PROPOSALFILTER == 1 { proposers, err := CreateProposers(t.ctx, t.signed, t.processed, t.config, t.logger) if err != nil { return generator_workers, err } generator_workers = append(generator_workers, proposers) assembler := &Assembler{Signer: t.crypto, Ctx: t.ctx, Raw: t.raw, Signed: t.signed, ErrorCh: t.errorCh, Logger: t.logger} Integrator := &Integrator{Signer: t.crypto, Ctx: t.ctx, Processed: t.processed, Envs: t.envs, ErrorCh: t.errorCh, Logger: t.logger} for i := 0; i < t.signerNumber; i++ { generator_workers = append(generator_workers, assembler) generator_workers = append(generator_workers, Integrator) } } // if boradcaster int mod 3 = 0 if mode%infra.COMMITFILTER == 0 { broadcaster, err := CreateBroadcasters(t.ctx, t.envs, t.errorCh, t.config, t.logger) if err != nil { return generator_workers, err } generator_workers = append(generator_workers, broadcaster) } // if not fake int mod 2 = 0 for i := 0; i < t.parallel; i++ { if mode%infra.QUERYFILTER == 0 { Initiator := &Initiator{Num: t.num, Burst: t.burst, R: t.rate, Config: t.config, Crypto: t.crypto, Logger: t.logger, Raw: t.raw, ErrorCh: t.errorCh} generator_workers = append(generator_workers, Initiator) } else { // if fake int mod 2 = 1 fackEnvelopGenerator := &FackEnvelopGenerator{Num: t.num, Burst: t.burst, R: t.rate, Config: t.config, Crypto: t.crypto, Envs: t.envs, ErrorCh: t.errorCh} generator_workers = append(generator_workers, fackEnvelopGenerator) } } return generator_workers, nil }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/assembler.go
pkg/infra/trafficGenerator/assembler.go
package trafficGenerator import ( "context" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/hyperledger-twgc/tape/pkg/infra" log "github.com/sirupsen/logrus" ) type Assembler struct { Signer infra.Crypto Ctx context.Context Raw chan *basic.TracingProposal Signed []chan *basic.Elements ErrorCh chan error Logger *log.Logger } func (a *Assembler) sign(p *basic.TracingProposal) (*basic.Elements, error) { tapeSpan := basic.GetGlobalSpan() span := tapeSpan.MakeSpan(p.TxId, "", basic.SIGN_PROPOSAL, p.Span) defer span.Finish() sprop, err := SignProposal(p.Proposal, a.Signer) if err != nil { return nil, err } basic.LogEvent(a.Logger, p.TxId, "SignProposal") EndorsementSpan := tapeSpan.MakeSpan(p.TxId, "", basic.ENDORSEMENT, p.Span) orgs := make([]string, 0) basic.GetLatencyMap().StartTracing(p.TxId) return &basic.Elements{TxId: p.TxId, SignedProp: sprop, Span: p.Span, EndorsementSpan: EndorsementSpan, Orgs: orgs}, nil } func (a *Assembler) Start() { for { select { case r := <-a.Raw: t, err := a.sign(r) if err != nil { a.ErrorCh <- err return } for _, v := range a.Signed { v <- t } case <-a.Ctx.Done(): return } } }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/fuzzing_test.go
pkg/infra/trafficGenerator/fuzzing_test.go
//go:build !race // +build !race package trafficGenerator_test import ( "testing" "unicode/utf8" "github.com/hyperledger-twgc/tape/pkg/infra/trafficGenerator" ) func FuzzConvertString(f *testing.F) { testcases := []string{"data", "randomString1", "uuid", "randomNumber1_9", "{\"k1\":\"uuid\",\"key2\":\"randomNumber10000_20000\",\"keys\":\"randomString10\"}"} for _, tc := range testcases { f.Add(tc) } f.Fuzz(func(t *testing.T, orig string) { data, err := trafficGenerator.ConvertString(orig) if utf8.ValidString(orig) && err != nil && !utf8.ValidString(data) && len(data) != 0 { t.Error(err.Error() + " " + orig + " " + data) } if !utf8.ValidString(data) { t.Error("fail to convert utf8 string" + data) } }) }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/proposer_test.go
pkg/infra/trafficGenerator/proposer_test.go
//go:build !race // +build !race package trafficGenerator_test import ( "context" "time" "github.com/hyperledger-twgc/tape/e2e/mock" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/hyperledger-twgc/tape/pkg/infra/trafficGenerator" "github.com/opentracing/opentracing-go" "github.com/hyperledger/fabric-protos-go-apiv2/peer" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/gmeasure" log "github.com/sirupsen/logrus" ) var _ = Describe("Proposer", func() { var addr string var logger = log.New() var processed chan *basic.Elements BeforeEach(func() { server, _ := mock.NewServer(1, nil) server.Start() addr = server.PeersAddresses()[0] }) Context("CreateProposer", func() { It("successfully creates a proposer", func() { dummy := basic.Node{ Addr: addr, } rule := "1 == 1" Proposer, err := trafficGenerator.CreateProposer(dummy, logger, rule) Expect(Proposer.Addr).To(Equal(addr)) Expect(err).NotTo(HaveOccurred()) }) }) Context("CreateBroadcasters", func() { It("successfully creates a broadcaster", func() { dummy := basic.Node{ Addr: addr, } Broadcaster, err := trafficGenerator.CreateBroadcaster(context.Background(), dummy, logger) Expect(Broadcaster).NotTo(BeNil()) Expect(err).NotTo(HaveOccurred()) }) It("captures connection errors", func() { dummy := basic.Node{ Addr: "invalid_addr", } _, err := trafficGenerator.CreateBroadcaster(context.Background(), dummy, logger) Expect(err).Should(MatchError(ContainSubstring("rpc error: code"))) }) }) Context("Tape should do less for prepare and summary endorsement process", func() { // 0.002 here for mac testing on azp // For ginkgo, // You may only call Measure from within a Describe, Context or When // So here only tested with concurrent as 8 peers It("it should do endorsement efficiently for 2 peers", Serial, Label("measurement"), func() { experiment := gmeasure.NewExperiment("Tape Peers") AddReportEntry(experiment.Name, experiment) tracer, closer := basic.Init("test") defer closer.Close() opentracing.SetGlobalTracer(tracer) span := opentracing.GlobalTracer().StartSpan("start transaction process") defer span.Finish() peerNum := 2 processed = make(chan *basic.Elements, 10) ctx, cancel := context.WithCancel(context.Background()) defer cancel() signeds := make([]chan *basic.Elements, peerNum) mockpeer, err := mock.NewServer(peerNum, nil) Expect(err).NotTo(HaveOccurred()) mockpeer.Start() defer mockpeer.Stop() for i := 0; i < peerNum; i++ { signeds[i] = make(chan *basic.Elements, 10) StartProposer(ctx, signeds[i], processed, logger, peerNum, mockpeer.PeersAddresses()[i]) } experiment.Sample(func(idx int) { experiment.MeasureDuration("process", func() { data := &basic.Elements{SignedProp: &peer.SignedProposal{}, TxId: "123", Span: span, EndorsementSpan: span} for _, s := range signeds { s <- data } <-processed }) }, gmeasure.SamplingConfig{N: 100, Duration: time.Second}) repaginationStats := experiment.GetStats("process") medianDuration := repaginationStats.DurationFor(gmeasure.StatMedian) Expect(medianDuration).To(BeNumerically("<", 2*time.Millisecond)) }) }) }) func StartProposer(ctx context.Context, signed, processed chan *basic.Elements, logger *log.Logger, threshold int, addr string) { peer := basic.Node{ Addr: addr, } rule := ` package tape default allow = true ` Proposer, _ := trafficGenerator.CreateProposer(peer, logger, rule) go Proposer.Start(ctx, signed, processed) }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/fackEnvelopGenerator_test.go
pkg/infra/trafficGenerator/fackEnvelopGenerator_test.go
package trafficGenerator_test import ( "os" "time" "github.com/hyperledger-twgc/tape/e2e" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/hyperledger-twgc/tape/pkg/infra/trafficGenerator" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("FackEnvelopGenerator", func() { var ( configFile *os.File tmpDir string ) BeforeEach(func() { var err error tmpDir, err = os.MkdirTemp("", "tape-") Expect(err).NotTo(HaveOccurred()) mtlsCertFile, err := os.CreateTemp(tmpDir, "mtls-*.crt") Expect(err).NotTo(HaveOccurred()) mtlsKeyFile, err := os.CreateTemp(tmpDir, "mtls-*.key") Expect(err).NotTo(HaveOccurred()) err = e2e.GenerateCertAndKeys(mtlsKeyFile, mtlsCertFile) Expect(err).NotTo(HaveOccurred()) PolicyFile, err := os.CreateTemp(tmpDir, "policy") Expect(err).NotTo(HaveOccurred()) err = e2e.GeneratePolicy(PolicyFile) Expect(err).NotTo(HaveOccurred()) mtlsCertFile.Close() mtlsKeyFile.Close() PolicyFile.Close() configFile, err = os.CreateTemp(tmpDir, "config*.yaml") Expect(err).NotTo(HaveOccurred()) configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: []string{"dummy"}, OrdererAddr: "dummy", CommitThreshold: 1, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(configFile.Name(), configValue) }) AfterEach(func() { os.RemoveAll(tmpDir) }) It("should crete proposal to raw without limit when limit is 0", func() { envs := make(chan *basic.TracingEnvelope, 1002) defer close(envs) errorCh := make(chan error, 1002) defer close(errorCh) config, err := basic.LoadConfig(configFile.Name()) Expect(err).NotTo(HaveOccurred()) crypto, err := config.LoadCrypto() Expect(err).NotTo(HaveOccurred()) t := time.Now() fackEnvelopGenerator := &trafficGenerator.FackEnvelopGenerator{ Num: 1002, Burst: 10, R: 0, Config: config, Crypto: crypto, Envs: envs, ErrorCh: errorCh, } fackEnvelopGenerator.Start() t1 := time.Now() Expect(envs).To(HaveLen(1002)) Expect(t1.Sub(t)).To(BeNumerically("<", 2*time.Second)) }) It("should crete proposal to raw with given limit bigger than 0 less than size", func() { envs := make(chan *basic.TracingEnvelope, 1002) defer close(envs) errorCh := make(chan error, 1002) defer close(errorCh) config, err := basic.LoadConfig(configFile.Name()) Expect(err).NotTo(HaveOccurred()) crypto, err := config.LoadCrypto() Expect(err).NotTo(HaveOccurred()) t := time.Now() fackEnvelopGenerator := &trafficGenerator.FackEnvelopGenerator{ Num: 12, Burst: 10, R: 1, Config: config, Crypto: crypto, Envs: envs, ErrorCh: errorCh, } fackEnvelopGenerator.Start() t1 := time.Now() Expect(envs).To(HaveLen(12)) Expect(t1.Sub(t)).To(BeNumerically("<", 2*time.Second)) }) It("should crete proposal to raw with given limit bigger than Size", func() { envs := make(chan *basic.TracingEnvelope, 1002) defer close(envs) errorCh := make(chan error, 1002) defer close(errorCh) config, err := basic.LoadConfig(configFile.Name()) Expect(err).NotTo(HaveOccurred()) crypto, err := config.LoadCrypto() Expect(err).NotTo(HaveOccurred()) t := time.Now() fackEnvelopGenerator := &trafficGenerator.FackEnvelopGenerator{ Num: 12, Burst: 10, R: 0, Config: config, Crypto: crypto, Envs: envs, ErrorCh: errorCh, } fackEnvelopGenerator.Start() t1 := time.Now() Expect(envs).To(HaveLen(12)) Expect(t1.Sub(t)).To(BeNumerically("<", 2*time.Second)) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/benchmark_test.go
pkg/infra/trafficGenerator/benchmark_test.go
//go:build !race // +build !race package trafficGenerator_test import ( "os" "testing" "github.com/hyperledger-twgc/tape/e2e" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/hyperledger-twgc/tape/pkg/infra/trafficGenerator" ) func benchmarkProposalRandom(b *testing.B, arg string) { b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _, _ = trafficGenerator.ConvertString(arg) } b.StopTimer() } func BenchmarkProposalRandomTest1(b *testing.B) { benchmarkProposalRandom(b, "data") } func BenchmarkProposalRandomTest2(b *testing.B) { benchmarkProposalRandom(b, "randomString1") } func BenchmarkProposalRandomTest3(b *testing.B) { benchmarkProposalRandom(b, "{\"key\":\"randomNumber1_50\",\"key1\":\"randomNumber1_20\"}") } func BenchmarkProposalRandomTest4(b *testing.B) { benchmarkProposalRandom(b, "{\"k1\":\"uuid\",\"key2\":\"randomNumber10000_20000\",\"keys\":\"randomString10\"}") } func BenchmarkFackEnvelopTest(b *testing.B) { errorCh := make(chan error, 1000) envs := make(chan *basic.TracingEnvelope, 1000) tmpDir, _ := os.MkdirTemp("", "tape-") mtlsCertFile, _ := os.CreateTemp(tmpDir, "mtls-*.crt") mtlsKeyFile, _ := os.CreateTemp(tmpDir, "mtls-*.key") PolicyFile, _ := os.CreateTemp(tmpDir, "policy") _ = e2e.GeneratePolicy(PolicyFile) _ = e2e.GenerateCertAndKeys(mtlsKeyFile, mtlsCertFile) mtlsCertFile.Close() mtlsKeyFile.Close() PolicyFile.Close() configFile, _ := os.CreateTemp(tmpDir, "config*.yaml") configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: nil, OrdererAddr: "", CommitThreshold: 1, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(configFile.Name(), configValue) config, _ := basic.LoadConfig(configFile.Name()) crypto, _ := config.LoadCrypto() fackEnvelopGenerator := &trafficGenerator.FackEnvelopGenerator{ Num: b.N, Burst: 1000, R: 0, Config: config, Crypto: crypto, Envs: envs, ErrorCh: errorCh, } b.ReportAllocs() b.ResetTimer() go fackEnvelopGenerator.Start() var n int for n < b.N { <-envs n++ } b.StopTimer() os.RemoveAll(tmpDir) }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/proposer.go
pkg/infra/trafficGenerator/proposer.go
package trafficGenerator import ( "context" "errors" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/hyperledger/fabric-protos-go-apiv2/peer" log "github.com/sirupsen/logrus" ) type Proposers struct { workers [][]*Proposer logger *log.Logger ctx context.Context signed []chan *basic.Elements processed chan *basic.Elements config basic.Config } func CreateProposers(ctx context.Context, signed []chan *basic.Elements, processed chan *basic.Elements, config basic.Config, logger *log.Logger) (*Proposers, error) { var ps [][]*Proposer var err error //one proposer per connection per peer for _, node := range config.Endorsers { row := make([]*Proposer, config.NumOfConn) for j := 0; j < config.NumOfConn; j++ { row[j], err = CreateProposer(node, logger, config.Rule) if err != nil { return nil, err } } ps = append(ps, row) } return &Proposers{workers: ps, logger: logger, ctx: ctx, signed: signed, processed: processed, config: config}, nil } func (ps *Proposers) Start() { ps.logger.Infof("Start sending transactions.") for i := 0; i < len(ps.config.Endorsers); i++ { // peer connection should be config.ClientPerConn * config.NumOfConn for k := 0; k < ps.config.ClientPerConn; k++ { for j := 0; j < ps.config.NumOfConn; j++ { go ps.workers[i][j].Start(ps.ctx, ps.signed[i], ps.processed) } } } } type Proposer struct { e peer.EndorserClient Addr string logger *log.Logger Org string rule string } func CreateProposer(node basic.Node, logger *log.Logger, rule string) (*Proposer, error) { if len(rule) == 0 { return nil, errors.New("empty endorsement policy") } endorser, err := basic.CreateEndorserClient(node, logger) if err != nil { return nil, err } return &Proposer{e: endorser, Addr: node.Addr, logger: logger, Org: node.Org, rule: rule}, nil } func (p *Proposer) Start(ctx context.Context, signed, processed chan *basic.Elements) { tapeSpan := basic.GetGlobalSpan() for { select { case s := <-signed: //send sign proposal to peer for endorsement span := tapeSpan.MakeSpan(s.TxId, p.Addr, basic.ENDORSEMENT_AT_PEER, s.Span) r, err := p.e.ProcessProposal(ctx, s.SignedProp) if err != nil || r.Response.Status < 200 || r.Response.Status >= 400 { // end sending proposal if r == nil { p.logger.Errorf("Err processing proposal: %s, status: unknown, addr: %s \n", err, p.Addr) } else { p.logger.Errorf("Err processing proposal: %s, status: %d, message: %s, addr: %s \n", err, r.Response.Status, r.Response.Message, p.Addr) } continue } span.Finish() s.Lock.Lock() // if prometheus // report read readlatency with peer in label basic.GetLatencyMap().ReportReadLatency(s.TxId, p.Addr) s.Responses = append(s.Responses, r) s.Orgs = append(s.Orgs, p.Org) rs, err := CheckPolicy(s, p.rule) if err != nil { p.logger.Errorf("Fails to check rule of endorsement %s \n", err) } if rs { //if len(s.Responses) >= threshold { // from value upgrade to OPA logic s.EndorsementSpan.Finish() // OPA // if already in processed queue or after, ignore // if not, send into process queue processed <- s basic.LogEvent(p.logger, s.TxId, "CompletedCollectEndorsement") } s.Lock.Unlock() case <-ctx.Done(): return } } }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/policyHandler_test.go
pkg/infra/trafficGenerator/policyHandler_test.go
package trafficGenerator_test import ( "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/hyperledger-twgc/tape/pkg/infra/trafficGenerator" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) const org1 = "org1" const org2 = "org2" var _ = Describe("PolicyHandler", func() { It("should pass when org1 with rule org1 or org2", func() { input := make([]string, 2) input[0] = org1 //input[1] = "org2" rule := `package tape default allow = false allow { input[_] == "` + org1 + `" } allow { input[_] == "` + org2 + `" }` instance := &basic.Elements{ Orgs: input, } rs, err := trafficGenerator.CheckPolicy(instance, rule) Expect(err).NotTo(HaveOccurred()) Expect(rs).To(BeTrue()) }) It("should not pass when null with rule org1 or org2", func() { input := make([]string, 2) rule := `package tape default allow = false allow { input[_] == "` + org1 + `" } allow { input[_] == "` + org2 + `" }` instance := &basic.Elements{ Orgs: input, } rs, err := trafficGenerator.CheckPolicy(instance, rule) Expect(err).NotTo(HaveOccurred()) Expect(rs).To(BeFalse()) }) It("should not pass when org1 with rule org1 and org2", func() { input := make([]string, 2) input[0] = "org1" rule := `package tape default allow = false allow { input[_] == "` + org1 + `" input[_] == "` + org2 + `" }` instance := &basic.Elements{ Orgs: input, } rs, err := trafficGenerator.CheckPolicy(instance, rule) Expect(err).NotTo(HaveOccurred()) Expect(rs).To(BeFalse()) }) It("should pass with rule org1 and org2", func() { input := make([]string, 2) input[0] = "org1" input[1] = "org2" rule := `package tape default allow = false allow { input[_] == "` + org1 + `" input[_] == "` + org2 + `" } ` instance := &basic.Elements{ Orgs: input, } rs, err := trafficGenerator.CheckPolicy(instance, rule) Expect(err).NotTo(HaveOccurred()) Expect(rs).To(BeTrue()) }) It("should pass with rule org1 and org2", func() { input := make([]string, 2) input[0] = org1 input[1] = org2 rule := `package tape default allow = false allow { 1 == 1 } ` instance := &basic.Elements{ Orgs: input, } rs, err := trafficGenerator.CheckPolicy(instance, rule) Expect(err).NotTo(HaveOccurred()) Expect(rs).To(BeTrue()) }) It("Same instance can't pass twice", func() { input := make([]string, 2) input[0] = org1 input[1] = org2 rule := `package tape default allow = false allow { input[_] == "` + org1 + `" input[_] == "` + org2 + `" } ` instance := &basic.Elements{ Orgs: input, } rs, err := trafficGenerator.CheckPolicy(instance, rule) Expect(err).NotTo(HaveOccurred()) Expect(rs).To(BeTrue()) rs, err = trafficGenerator.CheckPolicy(instance, rule) Expect(err).NotTo(HaveOccurred()) Expect(rs).To(BeFalse()) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/broadcaster.go
pkg/infra/trafficGenerator/broadcaster.go
package trafficGenerator import ( "context" "io" "github.com/hyperledger-twgc/tape/pkg/infra" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/hyperledger/fabric-protos-go-apiv2/common" "github.com/hyperledger/fabric-protos-go-apiv2/orderer" "github.com/pkg/errors" log "github.com/sirupsen/logrus" ) type Broadcasters struct { workers []*Broadcaster ctx context.Context envs chan *basic.TracingEnvelope errorCh chan error } type Broadcaster struct { c orderer.AtomicBroadcast_BroadcastClient logger *log.Logger } func CreateBroadcasters(ctx context.Context, envs chan *basic.TracingEnvelope, errorCh chan error, config basic.Config, logger *log.Logger) (*Broadcasters, error) { var workers []*Broadcaster for i := 0; i < config.NumOfConn; i++ { broadcaster, err := CreateBroadcaster(ctx, config.Orderer, logger) if err != nil { return nil, err } workers = append(workers, broadcaster) } return &Broadcasters{ workers: workers, ctx: ctx, envs: envs, errorCh: errorCh, }, nil } func (bs Broadcasters) Start() { for _, b := range bs.workers { go b.StartDraining(bs.errorCh) go b.Start(bs.ctx, bs.envs, bs.errorCh) } } func CreateBroadcaster(ctx context.Context, node basic.Node, logger *log.Logger) (*Broadcaster, error) { client, err := basic.CreateBroadcastClient(ctx, node, logger) if err != nil { return nil, err } return &Broadcaster{c: client, logger: logger}, nil } func (b *Broadcaster) Start(ctx context.Context, envs <-chan *basic.TracingEnvelope, errorCh chan error) { b.logger.Debugf("Start sending broadcast") for { select { case e := <-envs: //b.logger.Debugf("Sending broadcast envelop") tapeSpan := basic.GetGlobalSpan() span := tapeSpan.MakeSpan(e.TxId, "", basic.BROADCAST, e.Span) err := b.c.Send(e.Env) if err != nil { errorCh <- err } span.Finish() e.Span.Finish() if basic.GetMod() == infra.FULLPROCESS { Global_Span := tapeSpan.GetSpan(e.TxId, "", basic.TRANSACTION) tapeSpan.SpanIntoMap(e.TxId, "", basic.CONSESUS, Global_Span) } else { tapeSpan.SpanIntoMap(e.TxId, "", basic.CONSESUS, nil) } e = nil // end of transaction case <-ctx.Done(): return } } } func (b *Broadcaster) StartDraining(errorCh chan error) { for { res, err := b.c.Recv() if err != nil { if err == io.EOF { return } b.logger.Errorf("recv broadcast err: %+v, status: %+v\n", err, res) return } if res.Status != common.Status_SUCCESS { errorCh <- errors.Errorf("recv errouneous status %s", res.Status) return } } }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/trafficGenerator_suite_test.go
pkg/infra/trafficGenerator/trafficGenerator_suite_test.go
package trafficGenerator_test import ( "testing" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) func TestTrafficGenerator(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "TrafficGenerator Suite") }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/proposal.go
pkg/infra/trafficGenerator/proposal.go
package trafficGenerator import ( "bytes" "fmt" "math" "math/rand" "regexp" "strconv" "strings" "time" "unicode/utf8" "github.com/hyperledger-twgc/tape/internal/fabric/protoutil" "github.com/hyperledger-twgc/tape/pkg/infra" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/opentracing/opentracing-go" "github.com/google/uuid" "github.com/hyperledger/fabric-protos-go-apiv2/common" "github.com/hyperledger/fabric-protos-go-apiv2/orderer" "github.com/hyperledger/fabric-protos-go-apiv2/peer" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "google.golang.org/protobuf/proto" ) const charset = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" var seededRand *rand.Rand = rand.New( rand.NewSource(time.Now().UnixNano())) func CreateProposal(signer infra.Crypto, logger *log.Logger, channel, ccname, version string, args ...string) (*basic.TracingProposal, error) { var argsInByte [][]byte for _, arg := range args { current_arg, err := ConvertString(arg) if err != nil { return nil, err } fmt.Println(current_arg) argsInByte = append(argsInByte, []byte(current_arg)) } spec := &peer.ChaincodeSpec{ Type: peer.ChaincodeSpec_GOLANG, ChaincodeId: &peer.ChaincodeID{Name: ccname, Version: version}, Input: &peer.ChaincodeInput{Args: argsInByte}, } invocation := &peer.ChaincodeInvocationSpec{ChaincodeSpec: spec} creator, err := signer.Serialize() if err != nil { return nil, err } prop, txid, err := protoutil.CreateChaincodeProposal(common.HeaderType_ENDORSER_TRANSACTION, channel, invocation, creator) if err != nil { return nil, err } basic.LogEvent(logger, txid, "CreateChaincodeProposal") tapeSpan := basic.GetGlobalSpan() var span opentracing.Span if basic.GetMod() == infra.FULLPROCESS { Global_Span := tapeSpan.SpanIntoMap(txid, "", basic.TRANSACTION, nil) span = tapeSpan.MakeSpan(txid, "", basic.TRANSACTIONSTART, Global_Span) } else { span = tapeSpan.SpanIntoMap(txid, "", basic.TRANSACTIONSTART, nil) } return &basic.TracingProposal{Proposal: prop, TxId: txid, Span: span}, nil } func SignProposal(prop *peer.Proposal, signer infra.Crypto) (*peer.SignedProposal, error) { propBytes, err := proto.Marshal(prop) if err != nil { return nil, err } sig, err := signer.Sign(propBytes) if err != nil { return nil, err } return &peer.SignedProposal{ProposalBytes: propBytes, Signature: sig}, nil } func CreateSignedTx(signedproposal *peer.SignedProposal, signer infra.Crypto, resps []*peer.ProposalResponse) (*common.Envelope, error) { if len(resps) == 0 { return nil, errors.Errorf("at least one proposal response is required") } proposal := &peer.Proposal{} err := proto.Unmarshal(signedproposal.ProposalBytes, proposal) if err != nil { return nil, err } // the original header hdr, err := GetHeader(proposal.Header) if err != nil { return nil, err } // the original payload pPayl, err := GetChaincodeProposalPayload(proposal.Payload) if err != nil { return nil, err } // check that the signer is the same that is referenced in the header // TODO: maybe worth removing? signerBytes, err := signer.Serialize() if err != nil { return nil, err } shdr, err := GetSignatureHeader(hdr.SignatureHeader) if err != nil { return nil, err } if !bytes.Equal(signerBytes, shdr.Creator) { return nil, errors.Errorf("signer must be the same as the one referenced in the header") } endorsements := make([]*peer.Endorsement, 0) // ensure that all actions are bitwise equal and that they are successful var a1 []byte for n, r := range resps { if n == 0 { a1 = r.Payload if r.Response.Status < 200 || r.Response.Status >= 400 { return nil, errors.Errorf("proposal response was not successful, error code %d, msg %s", r.Response.Status, r.Response.Message) } } if !bytes.Equal(a1, r.Payload) { return nil, errors.Errorf("ProposalResponsePayloads from Peers do not match") } endorsements = append(endorsements, r.Endorsement) } // create ChaincodeEndorsedAction cea := &peer.ChaincodeEndorsedAction{ProposalResponsePayload: a1, Endorsements: endorsements} // obtain the bytes of the proposal payload that will go to the transaction propPayloadBytes, err := protoutil.GetBytesProposalPayloadForTx(pPayl) //, hdrExt.PayloadVisibility if err != nil { return nil, err } // serialize the chaincode action payload cap := &peer.ChaincodeActionPayload{ChaincodeProposalPayload: propPayloadBytes, Action: cea} capBytes, err := protoutil.GetBytesChaincodeActionPayload(cap) if err != nil { return nil, err } // create a transaction taa := &peer.TransactionAction{Header: hdr.SignatureHeader, Payload: capBytes} taas := make([]*peer.TransactionAction, 1) taas[0] = taa tx := &peer.Transaction{Actions: taas} // serialize the tx txBytes, err := protoutil.GetBytesTransaction(tx) if err != nil { return nil, err } // create the payload payl := &common.Payload{Header: hdr, Data: txBytes} paylBytes, err := protoutil.GetBytesPayload(payl) if err != nil { return nil, err } // sign the payload sig, err := signer.Sign(paylBytes) if err != nil { return nil, err } // here's the envelope return &common.Envelope{Payload: paylBytes, Signature: sig}, nil } func CreateSignedDeliverNewestEnv(ch string, signer infra.Crypto) (*common.Envelope, error) { start := &orderer.SeekPosition{ Type: &orderer.SeekPosition_Newest{ Newest: &orderer.SeekNewest{}, }, } stop := &orderer.SeekPosition{ Type: &orderer.SeekPosition_Specified{ Specified: &orderer.SeekSpecified{ Number: math.MaxUint64, }, }, } seekInfo := &orderer.SeekInfo{ Start: start, Stop: stop, Behavior: orderer.SeekInfo_BLOCK_UNTIL_READY, } return protoutil.CreateSignedEnvelope( common.HeaderType_DELIVER_SEEK_INFO, ch, signer, seekInfo, 0, 0, ) } func GetHeader(bytes []byte) (*common.Header, error) { hdr := &common.Header{} err := proto.Unmarshal(bytes, hdr) return hdr, errors.Wrap(err, "error unmarshaling Header") } func GetChaincodeProposalPayload(bytes []byte) (*peer.ChaincodeProposalPayload, error) { cpp := &peer.ChaincodeProposalPayload{} err := proto.Unmarshal(bytes, cpp) return cpp, errors.Wrap(err, "error unmarshaling ChaincodeProposalPayload") } func GetSignatureHeader(bytes []byte) (*common.SignatureHeader, error) { return UnmarshalSignatureHeader(bytes) } // UnmarshalChannelHeader returns a ChannelHeader from bytes func UnmarshalChannelHeader(bytes []byte) (*common.ChannelHeader, error) { chdr := &common.ChannelHeader{} err := proto.Unmarshal(bytes, chdr) return chdr, errors.Wrap(err, "error unmarshaling ChannelHeader") } func UnmarshalSignatureHeader(bytes []byte) (*common.SignatureHeader, error) { sh := &common.SignatureHeader{} if err := proto.Unmarshal(bytes, sh); err != nil { return nil, errors.Wrap(err, "error unmarshaling SignatureHeader") } return sh, nil } func newUUID() string { newUUID, _ := uuid.NewRandom() return newUUID.String() } func randomInt(min, max int) int { if min < 0 { min = 0 } if max <= 0 { max = 1 } return seededRand.Intn(max-min) + min } const maxLen = 16 const minLen = 2 func stringWithCharset(length int, charset string) string { b := make([]byte, length) for i := range b { b[i] = charset[seededRand.Intn(len(charset))] } return string(b) } func randomString(length int) string { if length <= 0 { length = seededRand.Intn(maxLen-minLen+1) + minLen } return stringWithCharset(length, charset) } func ConvertString(arg string) (string, error) { // ref to https://ghz.sh/docs/calldata // currently supports three kinds of random // support for uuid // uuid // support for random strings // randomString$length // support for random int // randomNumberMin_Max if !utf8.ValidString(arg) { return "", errors.New("invalid string") } var current_arg = arg regUUID, _ := regexp.Compile("uuid") //FindAllStringIndex // if reg.FindAllStringIndex !=nil // i=0;i<len;i=i+2 // cal value // replace 1 finds := regUUID.FindAllStringIndex(current_arg, -1) for _, v := range finds { str := fmt.Sprint(arg[v[0]:v[1]]) current_arg = strings.Replace(current_arg, str, newUUID(), 1) } randomStringreg := "randomString(\\d*)" regString, _ := regexp.Compile(randomStringreg) finds = regString.FindAllStringIndex(current_arg, -1) arg = current_arg for _, v := range finds { str := fmt.Sprint(arg[v[0]:v[1]]) length, err := strconv.Atoi(strings.TrimPrefix(str, "randomString")) if err != nil { return arg, err } if length > 4096 { return arg, fmt.Errorf("random string over length of 4096") } current_arg = strings.Replace(current_arg, str, randomString(length), 1) } randomIntReg := "randomNumber(\\d*)_(\\d*)" regNumber, _ := regexp.Compile(randomIntReg) arg = current_arg finds = regNumber.FindAllStringIndex(current_arg, -1) for _, v := range finds { str := fmt.Sprint(arg[v[0]:v[1]]) min_maxStr := strings.TrimPrefix(str, "randomNumber") min_maxArray := strings.Split(min_maxStr, "_") min, err := strconv.Atoi(min_maxArray[0]) if err != nil { return arg, err } max, err := strconv.Atoi(min_maxArray[1]) if err != nil { return arg, err } if max <= min { return arg, fmt.Errorf("max less than min, or equal") } current_arg = strings.Replace(current_arg, str, strconv.Itoa(randomInt(min, max)), 1) } return current_arg, nil }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/trafficGenerator/initiator_test.go
pkg/infra/trafficGenerator/initiator_test.go
package trafficGenerator_test import ( "os" "time" "github.com/hyperledger-twgc/tape/e2e" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/hyperledger-twgc/tape/pkg/infra/trafficGenerator" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" log "github.com/sirupsen/logrus" ) var _ = Describe("Initiator", func() { var ( configFile *os.File tmpDir string logger = log.New() ) BeforeEach(func() { var err error tmpDir, err = os.MkdirTemp("", "tape-") Expect(err).NotTo(HaveOccurred()) mtlsCertFile, err := os.CreateTemp(tmpDir, "mtls-*.crt") Expect(err).NotTo(HaveOccurred()) mtlsKeyFile, err := os.CreateTemp(tmpDir, "mtls-*.key") Expect(err).NotTo(HaveOccurred()) PolicyFile, err := os.CreateTemp(tmpDir, "policy") Expect(err).NotTo(HaveOccurred()) err = e2e.GeneratePolicy(PolicyFile) Expect(err).NotTo(HaveOccurred()) err = e2e.GenerateCertAndKeys(mtlsKeyFile, mtlsCertFile) Expect(err).NotTo(HaveOccurred()) mtlsCertFile.Close() mtlsKeyFile.Close() PolicyFile.Close() configFile, err = os.CreateTemp(tmpDir, "config*.yaml") Expect(err).NotTo(HaveOccurred()) configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: []string{"dummy"}, OrdererAddr: "dummy", CommitThreshold: 1, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(configFile.Name(), configValue) }) AfterEach(func() { os.RemoveAll(tmpDir) }) PIt("should crete proposal to raw without limit when number is 0", func() { raw := make(chan *basic.TracingProposal, 1002) //defer close(raw) errorCh := make(chan error, 1002) defer close(errorCh) config, err := basic.LoadConfig(configFile.Name()) Expect(err).NotTo(HaveOccurred()) crypto, err := config.LoadCrypto() Expect(err).NotTo(HaveOccurred()) Initiator := &trafficGenerator.Initiator{0, 10, 0, config, crypto, logger, raw, errorCh} go Initiator.Start() for i := 0; i < 1002; i++ { _, flag := <-raw Expect(flag).To(BeFalse()) } close(raw) }) It("should crete proposal to raw without limit when limit is 0", func() { raw := make(chan *basic.TracingProposal, 1002) defer close(raw) errorCh := make(chan error, 1002) defer close(errorCh) config, err := basic.LoadConfig(configFile.Name()) Expect(err).NotTo(HaveOccurred()) crypto, err := config.LoadCrypto() Expect(err).NotTo(HaveOccurred()) t := time.Now() Initiator := &trafficGenerator.Initiator{1002, 10, 0, config, crypto, logger, raw, errorCh} Initiator.Start() t1 := time.Now() Expect(raw).To(HaveLen(1002)) Expect(t1.Sub(t)).To(BeNumerically("<", 2*time.Second)) }) It("should crete proposal to raw with given limit bigger than 0 less than size", func() { raw := make(chan *basic.TracingProposal, 1002) defer close(raw) errorCh := make(chan error, 1002) defer close(errorCh) config, err := basic.LoadConfig(configFile.Name()) Expect(err).NotTo(HaveOccurred()) crypto, err := config.LoadCrypto() Expect(err).NotTo(HaveOccurred()) t := time.Now() Initiator := &trafficGenerator.Initiator{12, 10, 1, config, crypto, logger, raw, errorCh} Initiator.Start() t1 := time.Now() Expect(raw).To(HaveLen(12)) Expect(t1.Sub(t)).To(BeNumerically(">", 2*time.Second)) }) It("should crete proposal to raw with given limit bigger than Size", func() { raw := make(chan *basic.TracingProposal, 1002) defer close(raw) errorCh := make(chan error, 1002) defer close(errorCh) config, err := basic.LoadConfig(configFile.Name()) Expect(err).NotTo(HaveOccurred()) crypto, err := config.LoadCrypto() Expect(err).NotTo(HaveOccurred()) t := time.Now() Initiator := &trafficGenerator.Initiator{12, 10, 0, config, crypto, logger, raw, errorCh} Initiator.Start() t1 := time.Now() Expect(raw).To(HaveLen(12)) Expect(t1.Sub(t)).To(BeNumerically("<", 2*time.Second)) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/cmdImpl/processTemplate.go
pkg/infra/cmdImpl/processTemplate.go
package cmdImpl import ( "context" "io" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/hyperledger-twgc/tape/pkg/infra/observer" "github.com/hyperledger-twgc/tape/pkg/infra/trafficGenerator" "github.com/opentracing/opentracing-go" log "github.com/sirupsen/logrus" ) type CmdConfig struct { FinishCh chan struct{} ErrorCh chan error cancel context.CancelFunc Generator *trafficGenerator.TrafficGenerator Observerfactory *observer.ObserverFactory Closer io.Closer } func CreateCmd(configPath string, num int, burst, signerNumber, parallel int, rate float64, logger *log.Logger) (*CmdConfig, error) { config, err := basic.LoadConfig(configPath) if err != nil { return nil, err } crypto, err := config.LoadCrypto() if err != nil { return nil, err } raw := make(chan *basic.TracingProposal, burst) signed := make([]chan *basic.Elements, len(config.Endorsers)) processed := make(chan *basic.Elements, burst) envs := make(chan *basic.TracingEnvelope, burst) blockCh := make(chan *observer.AddressedBlock) finishCh := make(chan struct{}) errorCh := make(chan error, burst) ctx, cancel := context.WithCancel(context.Background()) for i := 0; i < len(config.Endorsers); i++ { signed[i] = make(chan *basic.Elements, burst) } tr, closer := basic.Init("tape") opentracing.SetGlobalTracer(tr) mytrafficGenerator := trafficGenerator.NewTrafficGenerator(ctx, crypto, envs, raw, processed, signed, config, num, burst, signerNumber, parallel, rate, logger, errorCh) Observerfactory := observer.NewObserverFactory( config, crypto, blockCh, logger, ctx, finishCh, num, parallel, envs, errorCh) cmd := &CmdConfig{ finishCh, errorCh, cancel, mytrafficGenerator, Observerfactory, closer, } return cmd, nil }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/cmdImpl/fullProcess.go
pkg/infra/cmdImpl/fullProcess.go
package cmdImpl import ( "fmt" "net/http" "os" "os/signal" "syscall" "time" "github.com/hyperledger-twgc/tape/pkg/infra" "github.com/hyperledger-twgc/tape/pkg/infra/basic" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" log "github.com/sirupsen/logrus" ) func Process(configPath string, num int, burst, signerNumber, parallel int, rate float64, enablePrometheus bool, prometheusAddr string, logger *log.Logger, processmod int) error { /*** signal ***/ c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) /*** variables ***/ cmdConfig, err := CreateCmd(configPath, num, burst, signerNumber, parallel, rate, logger) if err != nil { return err } defer cmdConfig.cancel() defer cmdConfig.Closer.Close() var Observer_workers []infra.Worker var Observers infra.ObserverWorker basic.SetMod(processmod) /*** workers ***/ if processmod != infra.TRAFFIC { Observer_workers, Observers, err = cmdConfig.Observerfactory.CreateObserverWorkers(processmod) if err != nil { return err } } var generator_workers []infra.Worker if processmod != infra.OBSERVER { if processmod == infra.TRAFFIC { generator_workers, err = cmdConfig.Generator.CreateGeneratorWorkers(processmod - 1) if err != nil { return err } } else { generator_workers, err = cmdConfig.Generator.CreateGeneratorWorkers(processmod) if err != nil { return err } } } var transactionlatency, readlatency *prometheus.SummaryVec /*** start prometheus ***/ if enablePrometheus { go func() { fmt.Println("start prometheus") http.Handle("/metrics", promhttp.Handler()) server := &http.Server{Addr: prometheusAddr, Handler: nil} err = server.ListenAndServe() if err != nil { cmdConfig.ErrorCh <- err } }() transactionlatency = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "transaction_latency_duration", Help: "Transaction latency distributions.", Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, }, []string{"transactionlatency"}, ) readlatency = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "read_latency_duration", Help: "Read latency distributions.", Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, }, []string{"readlatency"}, ) prometheus.MustRegister(transactionlatency) prometheus.MustRegister(readlatency) basic.InitLatencyMap(transactionlatency, readlatency, processmod, enablePrometheus) } /*** start workers ***/ for _, worker := range Observer_workers { go worker.Start() } for _, worker := range generator_workers { go worker.Start() } /*** waiting for complete ***/ total := num * parallel for { select { case err = <-cmdConfig.ErrorCh: fmt.Println("For FAQ, please check https://github.com/Hyperledger-TWGC/tape/wiki/FAQ") return err case <-cmdConfig.FinishCh: duration := time.Since(Observers.GetTime()) logger.Infof("Completed processing transactions.") fmt.Printf("tx: %d, duration: %+v, tps: %f\n", total, duration, float64(total)/duration.Seconds()) return nil case s := <-c: fmt.Println("Stopped by signal received" + s.String()) fmt.Println("Completed processing transactions") return nil } } }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/pkg/infra/cmdImpl/version.go
pkg/infra/cmdImpl/version.go
package cmdImpl import ( "fmt" "runtime" ) const ( programName = "tape" ) var ( Version string = "latest" CommitSHA string = "development build" BuiltTime string = "Mon Dec 21 19:00:00 2020" ) // GetVersionInfo return version information // TODO add commit hash, Built info func GetVersionInfo() string { return fmt.Sprintf( "%s:\n Version: %s\n Go version: %s\n Git commit: %s\n Built: %s\n OS/Arch: %s\n", programName, Version, runtime.Version(), CommitSHA, BuiltTime, fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), ) }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/cmd/tape/main.go
cmd/tape/main.go
package main import ( "fmt" "os" "github.com/hyperledger-twgc/tape/pkg/infra" "github.com/hyperledger-twgc/tape/pkg/infra/cmdImpl" "github.com/pkg/errors" log "github.com/sirupsen/logrus" kingpin "gopkg.in/alecthomas/kingpin.v2" ) const ( loglevel = "TAPE_LOGLEVEL" logfilename = "Tape.log" DEFAULT_PROMETHEUS_ADDR = ":8080" ) var ( app = kingpin.New("tape", "A performance test tool for Hyperledger Fabric") con = app.Flag("config", "Path to config file").Short('c').String() num = app.Flag("number", "Number of tx for shot").Short('n').Int() rate = app.Flag("rate", "[Optional] Creates tx rate, default 0 as unlimited").Default("0").Float64() burst = app.Flag("burst", "[Optional] Burst size for Tape, should bigger than rate").Default("1000").Int() signerNumber = app.Flag("signers", "[Optional] signer parallel Number for Tape, default as 5").Default("5").Int() parallelNumber = app.Flag("parallel", "[Optional] parallel Number for Tape, default as 1").Default("1").Int() enablePrometheus = app.Flag("prometheus", "[Optional] prometheus enable or not").Default("false").Bool() prometheusAddr = app.Flag("prometheus-addr", "[Optional] prometheus address, default as :8080").String() run = app.Command("run", "Start the tape program").Default() version = app.Command("version", "Show version information") commitOnly = app.Command("commitOnly", "Start tape with commitOnly mode, starts dummy envelop for test orderer only") endorsementOnly = app.Command("endorsementOnly", "Start tape with endorsementOnly mode, starts endorsement and end") trafficOnly = app.Command("traffic", "Start tape with traffic mode") observerOnly = app.Command("observer", "Start tape with observer mode") ) func main() { var err error logger := log.New() logger.SetLevel(log.WarnLevel) file, err := os.OpenFile(logfilename, os.O_CREATE|os.O_WRONLY, 0755) if err != nil { panic(err) } defer file.Close() logger.SetOutput(file) if customerLevel, customerSet := os.LookupEnv(loglevel); customerSet { if lvl, err_lvl := log.ParseLevel(customerLevel); err_lvl == nil { logger.SetLevel(lvl) } } fullCmd := kingpin.MustParse(app.Parse(os.Args[1:])) switch fullCmd { case version.FullCommand(): fmt.Println(cmdImpl.GetVersionInfo()) case commitOnly.FullCommand(): checkArgs(rate, burst, signerNumber, parallelNumber, *con, *enablePrometheus, prometheusAddr, logger) err = cmdImpl.Process(*con, *num, *burst, *signerNumber, *parallelNumber, *rate, *enablePrometheus, *prometheusAddr, logger, infra.COMMIT) case endorsementOnly.FullCommand(): checkArgs(rate, burst, signerNumber, parallelNumber, *con, *enablePrometheus, prometheusAddr, logger) err = cmdImpl.Process(*con, *num, *burst, *signerNumber, *parallelNumber, *rate, *enablePrometheus, *prometheusAddr, logger, infra.ENDORSEMENT) case run.FullCommand(): checkArgs(rate, burst, signerNumber, parallelNumber, *con, *enablePrometheus, prometheusAddr, logger) err = cmdImpl.Process(*con, *num, *burst, *signerNumber, *parallelNumber, *rate, *enablePrometheus, *prometheusAddr, logger, infra.FULLPROCESS) case trafficOnly.FullCommand(): checkArgs(rate, burst, signerNumber, parallelNumber, *con, *enablePrometheus, prometheusAddr, logger) err = cmdImpl.Process(*con, *num, *burst, *signerNumber, *parallelNumber, *rate, *enablePrometheus, *prometheusAddr, logger, infra.TRAFFIC) case observerOnly.FullCommand(): checkArgs(rate, burst, signerNumber, parallelNumber, *con, *enablePrometheus, prometheusAddr, logger) err = cmdImpl.Process(*con, *num, *burst, *signerNumber, *parallelNumber, *rate, *enablePrometheus, *prometheusAddr, logger, infra.OBSERVER) default: err = errors.Errorf("invalid command: %s", fullCmd) } if err != nil { logger.Error(err) fmt.Fprint(os.Stderr, err) os.Exit(1) } os.Exit(0) } func checkArgs(rate *float64, burst, signerNumber, parallel *int, con string, enablePrometheus bool, prometheusAddr *string, logger *log.Logger) { if len(con) == 0 { os.Stderr.WriteString("tape: error: required flag --config not provided, try --help") os.Exit(1) } if *rate < 0 { os.Stderr.WriteString("tape: error: rate must be zero (unlimited) or positive number\n") os.Exit(1) } if *burst < 1 { os.Stderr.WriteString("tape: error: burst at least 1\n") os.Exit(1) } if *signerNumber < 1 { os.Stderr.WriteString("tape: error: signerNumber at least 1\n") os.Exit(1) } if *parallel < 1 { os.Stderr.WriteString("tape: error: parallel at least 1\n") os.Exit(1) } if int64(*rate) > int64(*burst) { fmt.Printf("As rate %d is bigger than burst %d, real rate is burst\n", int64(*rate), int64(*burst)) } // enable prometheus but not provide --prometheus-addr option, use default prometheus address ":8080" if enablePrometheus { if len(*prometheusAddr) == 0 { *prometheusAddr = DEFAULT_PROMETHEUS_ADDR } logger.Infof("prometheus running at %s\n", *prometheusAddr) } // not enable prometheus but provide --prometheus-addr option, show help message if !enablePrometheus && len(*prometheusAddr) != 0 { fmt.Printf("You've provided the --prometheus-addr option to specify a Prometheus address, but you haven't enabled Prometheus using --prometheus option\n") logger.Warnf("prometheus is not available at %s, because --prometheus option is not provided\n", *prometheusAddr) } logger.Infof("Will use rate %f as send rate\n", *rate) logger.Infof("Will use %d as burst\n", burst) }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/e2e/bad_test.go
e2e/bad_test.go
package e2e_test import ( "os" "os/exec" "github.com/hyperledger-twgc/tape/e2e" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" ) var _ = Describe("Mock test for error input", func() { Context("E2E with Error Cases", func() { When("Command error", func() { It("should return unexpected command", func() { cmd := exec.Command(tapeBin, "wrongCommand") var err error tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Err).Should(Say("tape: error: unexpected wrongCommand, try --help")) }) It("should return required flag config", func() { cmd := exec.Command(tapeBin, "-n", "500") var err error tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Err).Should(Say("tape: error: required flag --config not provided, try --help")) }) PIt("should return required flag number", func() { cmd := exec.Command(tapeBin, "-c", "TestFile") var err error tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Err).Should(Say("tape: error: required flag --number not provided, try --help")) }) It("should return help info", func() { cmd := exec.Command(tapeBin, "--help") var err error tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Err).Should(Say("usage: tape .*flags.* .*command.* .*args.*")) }) It("should return error msg when negative rate", func() { config, err := os.CreateTemp("", "dummy-*.yaml") Expect(err).NotTo(HaveOccurred()) configValue := e2e.Values{ PrivSk: "N/A", SignCert: "N/A", Mtls: false, PeersAddrs: []string{"N/A"}, OrdererAddr: "N/A", CommitThreshold: 1, PolicyFile: "N/A", } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "-c", config.Name(), "-n", "500", "--rate=-1") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Err).Should(Say("tape: error: rate must be zero \\(unlimited\\) or positive number\n")) }) It("should return error msg when less than 1 burst", func() { cmd := exec.Command(tapeBin, "-c", "config", "-n", "500", "--burst", "0") var err error tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Err).Should(Say("tape: error: burst at least 1\n")) }) It("should return warning msg when rate bigger than burst", func() { cmd := exec.Command(tapeBin, "-c", "NoExitFile", "-n", "500", "--rate=10", "--burst", "1") var err error tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("As rate 10 is bigger than burst 1, real rate is burst\n")) Eventually(tapeSession.Err).Should(Say("NoExitFile")) }) It("should return warning msg when rate bigger than default burst", func() { cmd := exec.Command(tapeBin, "-c", "NoExitFile", "-n", "500", "--rate", "10000") var err error tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("As rate 10000 is bigger than burst 1000, real rate is burst\n")) Eventually(tapeSession.Err).Should(Say("NoExitFile")) }) It("should return error msg when less than 1 signerNumber", func() { cmd := exec.Command(tapeBin, "-c", "config", "-n", "500", "--signers", "0") var err error tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Err).Should(Say("tape: error: signerNumber at least 1\n")) }) }) When("Config error", func() { It("should return file not exist", func() { cmd := exec.Command(tapeBin, "-c", "NoExitFile", "-n", "500") var err error tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Err).Should(Say("NoExitFile")) }) It("should return MSP error", func() { config, err := os.CreateTemp("", "dummy-*.yaml") Expect(err).NotTo(HaveOccurred()) configValue := e2e.Values{ PrivSk: "N/A", SignCert: "N/A", Mtls: false, PeersAddrs: []string{"N/A"}, OrdererAddr: "N/A", CommitThreshold: 0, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "-c", config.Name(), "-n", "500") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Err).Should(Say("error loading priv key")) }) It("returns error if commitThreshold is greater than # of committers", func() { config, err := os.CreateTemp("", "no-tls-config-*.yaml") Expect(err).NotTo(HaveOccurred()) configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: []string{"dummy-address"}, OrdererAddr: "N/A", CommitThreshold: 2, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "-c", config.Name(), "-n", "500") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Err).Should(Say("failed to create block collector")) }) }) When("Network connection error", func() { It("should hit with error", func() { config, err := os.CreateTemp("", "dummy-*.yaml") Expect(err).NotTo(HaveOccurred()) configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: []string{"invalid_addr"}, OrdererAddr: "N/A", CommitThreshold: 1, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "-c", config.Name(), "-n", "500") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Err).Should(Say("rpc error:")) }) }) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/e2e/e2e_version_cmd_test.go
e2e/e2e_version_cmd_test.go
package e2e_test import ( "os/exec" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" ) var _ = Describe("Mock test for version", func() { Context("E2E with correct subcommand", func() { When("Version subcommand", func() { It("should return version info", func() { var err error cmd := exec.Command(tapeBin, "version") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("tape:\n Version:.*\n Go version:.*\n Git commit:.*\n Built:.*\n OS/Arch:.*\n")) }) }) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/e2e/commitOnly_test.go
e2e/commitOnly_test.go
package e2e_test import ( "os" "os/exec" "github.com/hyperledger-twgc/tape/e2e" "github.com/hyperledger-twgc/tape/e2e/mock" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" ) var _ = Describe("Mock test for good path", func() { Context("E2E with multi mocked Fabric", func() { When("envelope only", func() { PIt("should work properly", func() { server, err := mock.NewServer(2, nil) Expect(err).NotTo(HaveOccurred()) server.Start() defer server.Stop() config, err := os.CreateTemp("", "envelop-only-config-*.yaml") Expect(err).NotTo(HaveOccurred()) paddrs, oaddr := server.Addresses() configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: paddrs, OrdererAddr: oaddr, CommitThreshold: 1, } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "commitOnly", "-c", config.Name(), "-n", "500") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Err).Should(Say("Time.*Block.*Tx.*")) Eventually(tapeSession.Out).Should(Say("Time.*Block.*Tx.*")) }) }) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/e2e/single_peer_test.go
e2e/single_peer_test.go
package e2e_test import ( "crypto/tls" "crypto/x509" "net/http" "os" "os/exec" "github.com/hyperledger-twgc/tape/e2e" "github.com/hyperledger-twgc/tape/e2e/mock" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" "google.golang.org/grpc/credentials" ) var _ = Describe("Mock test for good path", func() { Context("E2E with mocked Fabric", func() { When("TLS is disabled", func() { It("should work properly", func() { server, err := mock.NewServer(1, nil) Expect(err).NotTo(HaveOccurred()) server.Start() defer server.Stop() config, err := os.CreateTemp("", "no-tls-config-*.yaml") Expect(err).NotTo(HaveOccurred()) paddrs, oaddr := server.Addresses() configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: paddrs, OrdererAddr: oaddr, CommitThreshold: 1, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "-c", config.Name(), "-n", "5000", "--prometheus") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("start prometheus")) Eventually(tapeSession.Out).Should(Say("Time.*Block.*Tx.*10.*")) client := http.Client{} _, err = client.Get("http://localhost:8080/metrics") Expect(err).NotTo(HaveOccurred()) }) }) When("client authentication is required", func() { It("should work properly", func() { peerCert, err := tls.LoadX509KeyPair(mtlsCertFile.Name(), mtlsKeyFile.Name()) Expect(err).NotTo(HaveOccurred()) caCert, err := os.ReadFile(mtlsCertFile.Name()) Expect(err).NotTo(HaveOccurred()) caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) credentials := credentials.NewTLS(&tls.Config{ Certificates: []tls.Certificate{peerCert}, ClientCAs: caCertPool, ClientAuth: tls.RequireAndVerifyClientCert, }) server, err := mock.NewServer(1, credentials) Expect(err).NotTo(HaveOccurred()) server.Start() defer server.Stop() config, err := os.CreateTemp("", "mtls-config-*.yaml") Expect(err).NotTo(HaveOccurred()) paddrs, oaddr := server.Addresses() configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: true, MtlsCrt: mtlsCertFile.Name(), MtlsKey: mtlsKeyFile.Name(), PeersAddrs: paddrs, OrdererAddr: oaddr, CommitThreshold: 1, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "-c", config.Name(), "-n", "500") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("Time.*Block.*Tx.*10.*")) }) }) When("Only rate is specified", func() { It("should work properly", func() { server, err := mock.NewServer(1, nil) Expect(err).NotTo(HaveOccurred()) server.Start() defer server.Stop() config, err := os.CreateTemp("", "Rate-*.yaml") Expect(err).NotTo(HaveOccurred()) paddrs, oaddr := server.Addresses() configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: paddrs, OrdererAddr: oaddr, CommitThreshold: 1, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "-c", config.Name(), "-n", "500", "--rate", "10") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("Time.*Block.*Tx.*10.*")) }) }) When("Only burst is specified", func() { It("should work properly", func() { server, err := mock.NewServer(1, nil) Expect(err).NotTo(HaveOccurred()) server.Start() defer server.Stop() config, err := os.CreateTemp("", "burst-*.yaml") Expect(err).NotTo(HaveOccurred()) paddrs, oaddr := server.Addresses() configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: paddrs, OrdererAddr: oaddr, CommitThreshold: 1, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "-c", config.Name(), "-n", "500", "--burst", "10") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("Time.*Block.*Tx.*10.*")) }) }) //Test with All arguments When("Both rate and burst are specificed", func() { It("should work properly", func() { server, err := mock.NewServer(1, nil) Expect(err).NotTo(HaveOccurred()) server.Start() defer server.Stop() config, err := os.CreateTemp("", "BothRateAndBurst-*.yaml") Expect(err).NotTo(HaveOccurred()) paddrs, oaddr := server.Addresses() configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: paddrs, OrdererAddr: oaddr, CommitThreshold: 1, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "-c", config.Name(), "-n", "500", "--burst", "100", "--rate", "10") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("Time.*Block.*Tx.*10.*")) }) }) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/e2e/util.go
e2e/util.go
package e2e import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "encoding/pem" "math/big" "net" "os" "text/template" "time" ) type NodeSpec struct { Addr string MtlsCrt string MtlsKey string Mtls bool } type Values struct { PrivSk string SignCert string MtlsCrt string MtlsKey string Mtls bool PeersAddrs []string OrdererAddr string PeersNodeSpecs []NodeSpec CommitThreshold int PolicyFile string } func (va Values) Load() Values { va.PeersNodeSpecs = make([]NodeSpec, 0) for _, v := range va.PeersAddrs { node := NodeSpec{ Addr: v, MtlsCrt: va.MtlsCrt, MtlsKey: va.MtlsKey, Mtls: va.Mtls, } va.PeersNodeSpecs = append(va.PeersNodeSpecs, node) } return va } func GeneratePolicy(policyFile *os.File) error { _, err := policyFile.Write([]byte(`package tape default allow = false allow { 1 == 1 }`)) return err } func GenerateCertAndKeys(key, cert *os.File) error { priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return err } privDer, err := x509.MarshalPKCS8PrivateKey(priv) if err != nil { return err } err = pem.Encode(key, &pem.Block{Type: "PRIVATE KEY", Bytes: privDer}) if err != nil { return err } template := &x509.Certificate{ SerialNumber: new(big.Int), NotAfter: time.Now().Add(time.Hour), IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, } certDer, err := x509.CreateCertificate(rand.Reader, template, template, priv.Public(), priv) if err != nil { return err } err = pem.Encode(cert, &pem.Block{Type: "CERTIFICATE", Bytes: certDer}) if err != nil { return err } return nil } func GenerateConfigFile(fileName string, values Values) { // {{range $k, $v := .Var}} {{$k}} => {{$v}} {{end}} values = values.Load() var Text = `# Definition of nodes {{range $k, $v := .PeersNodeSpecs}} node: &node{{$k}} addr: {{ .Addr }}{{ if .Mtls }} tls_ca_cert: {{.MtlsCrt}} tls_ca_key: {{.MtlsKey}} tls_ca_root: {{.MtlsCrt}} {{ end }} {{ end }} orderer1: &orderer1 addr: {{ .OrdererAddr }}{{ if .Mtls }} tls_ca_cert: {{.MtlsCrt}} tls_ca_key: {{.MtlsKey}} tls_ca_root: {{.MtlsCrt}} {{ end }} # Nodes to interact with endorsers:{{range $k, $v := .PeersNodeSpecs}} - *node{{$k}}{{end}} committers: {{range $k, $v := .PeersNodeSpecs}} - *node{{$k}}{{end}} commitThreshold: {{ .CommitThreshold }} orderer: *orderer1 policyFile: {{ .PolicyFile }} channel: test-channel chaincode: test-chaincode mspid: Org1MSP private_key: {{.PrivSk}} sign_cert: {{.SignCert}} num_of_conn: 10 client_per_conn: 10 ` var err error var tmpl *template.Template tmpl, err = template.New("test").Parse(Text) if err != nil { panic(err) } file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0755) if err != nil { panic(err) } defer file.Close() err = tmpl.Execute(file, values) if err != nil { panic(err) } }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/e2e/e2e_suite_test.go
e2e/e2e_suite_test.go
package e2e_test import ( "os" "testing" "github.com/hyperledger-twgc/tape/e2e" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/onsi/gomega/gexec" ) var ( mtlsCertFile, mtlsKeyFile, PolicyFile *os.File tmpDir, tapeBin string tapeSession *gexec.Session ) func TestE2e(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "E2e Suite") } var _ = BeforeSuite(func() { var err error tmpDir, err = os.MkdirTemp("", "tape-e2e-") Expect(err).NotTo(HaveOccurred()) mtlsCertFile, err = os.CreateTemp(tmpDir, "mtls-*.crt") Expect(err).NotTo(HaveOccurred()) mtlsKeyFile, err = os.CreateTemp(tmpDir, "mtls-*.key") Expect(err).NotTo(HaveOccurred()) err = e2e.GenerateCertAndKeys(mtlsKeyFile, mtlsCertFile) Expect(err).NotTo(HaveOccurred()) PolicyFile, err = os.CreateTemp(tmpDir, "policy") Expect(err).NotTo(HaveOccurred()) err = e2e.GeneratePolicy(PolicyFile) Expect(err).NotTo(HaveOccurred()) mtlsCertFile.Close() mtlsKeyFile.Close() PolicyFile.Close() tapeBin, err = gexec.Build("../cmd/tape") Expect(err).NotTo(HaveOccurred()) }) var _ = AfterEach(func() { if tapeSession != nil && tapeSession.ExitCode() == -1 { tapeSession.Kill() } }) var _ = AfterSuite(func() { os.RemoveAll(tmpDir) os.Remove(tapeBin) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/e2e/multi_peer_test.go
e2e/multi_peer_test.go
package e2e_test import ( "os" "os/exec" "github.com/hyperledger-twgc/tape/e2e" "github.com/hyperledger-twgc/tape/e2e/mock" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" ) var _ = Describe("Mock test for good path", func() { Context("E2E with multi mocked Fabric", func() { When("TLS is disabled", func() { It("should work properly", func() { server, err := mock.NewServer(2, nil) Expect(err).NotTo(HaveOccurred()) server.Start() defer server.Stop() config, err := os.CreateTemp("", "no-tls-config-*.yaml") Expect(err).NotTo(HaveOccurred()) paddrs, oaddr := server.Addresses() configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: paddrs, OrdererAddr: oaddr, CommitThreshold: 1, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "-c", config.Name(), "-n", "500", "--parallel", "5") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("Time.*Block.*Tx.*10.*")) }) }) When("TLS is disabled", func() { It("should work properly", func() { server, err := mock.NewServer(2, nil) Expect(err).NotTo(HaveOccurred()) server.Start() defer server.Stop() config, err := os.CreateTemp("", "no-tls-config-*.yaml") Expect(err).NotTo(HaveOccurred()) paddrs, oaddr := server.Addresses() configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: paddrs, OrdererAddr: oaddr, CommitThreshold: 2, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "-c", config.Name(), "-n", "500", "--signers", "2") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("Time.*Block.*Tx.*10.*")) Eventually(tapeSession.Out).Should(Say("Time.*Block.*Tx.*10.*")) }) It("should work properly without number", func() { server, err := mock.NewServer(2, nil) Expect(err).NotTo(HaveOccurred()) server.Start() defer server.Stop() config, err := os.CreateTemp("", "no-tls-config-*.yaml") Expect(err).NotTo(HaveOccurred()) paddrs, oaddr := server.Addresses() configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: paddrs, OrdererAddr: oaddr, CommitThreshold: 2, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "-c", config.Name(), "--signers", "2") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("Time.*Block.*Tx.*10.*")) Eventually(tapeSession.Out).Should(Say("Time.*Block.*Tx.*10.*")) }) }) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/e2e/endorsementOnly_test.go
e2e/endorsementOnly_test.go
package e2e_test import ( "os" "os/exec" "github.com/hyperledger-twgc/tape/e2e" "github.com/hyperledger-twgc/tape/e2e/mock" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" ) var _ = Describe("Mock test for good path", func() { Context("E2E with multi mocked Fabric", func() { When("endorsement only", func() { It("should work properly", func() { server, err := mock.NewServer(2, nil) Expect(err).NotTo(HaveOccurred()) server.Start() defer server.Stop() config, err := os.CreateTemp("", "endorsement-only-config-*.yaml") Expect(err).NotTo(HaveOccurred()) paddrs, oaddr := server.Addresses() configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: paddrs, OrdererAddr: oaddr, CommitThreshold: 1, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd := exec.Command(tapeBin, "endorsementOnly", "-c", config.Name(), "-n", "500") tapeSession, err = gexec.Start(cmd, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("Time.*Tx.*")) }) }) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/e2e/TrafficAndObserver_test.go
e2e/TrafficAndObserver_test.go
package e2e_test import ( "os" "os/exec" "github.com/hyperledger-twgc/tape/e2e" "github.com/hyperledger-twgc/tape/e2e/mock" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" . "github.com/onsi/gomega/gbytes" "github.com/onsi/gomega/gexec" ) var _ = Describe("Mock test for good path", func() { Context("E2E with multi mocked Fabric", func() { When("traffic and observer mode", func() { It("should work properly", func() { server, err := mock.NewServer(2, nil) Expect(err).NotTo(HaveOccurred()) server.Start() defer server.Stop() config, err := os.CreateTemp("", "endorsement-only-config-*.yaml") Expect(err).NotTo(HaveOccurred()) paddrs, oaddr := server.Addresses() configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: paddrs, OrdererAddr: oaddr, CommitThreshold: 1, } e2e.GenerateConfigFile(config.Name(), configValue) cmd0 := exec.Command(tapeBin, "traffic", "-c", config.Name(), "--rate=10") //cmd1 := exec.Command(tapeBin, "observer", "-c", config.Name()) tapeSession, err = gexec.Start(cmd0, nil, nil) Expect(err).NotTo(HaveOccurred()) //_, err = gexec.Start(cmd0, nil, nil) //Expect(err).NotTo(HaveOccurred()) //Eventually(tapeSession.Out).Should(Say("Time.*Tx.*")) }) It("should work properly", func() { server, err := mock.NewServer(2, nil) Expect(err).NotTo(HaveOccurred()) server.Start() defer server.Stop() config, err := os.CreateTemp("", "endorsement-only-config-*.yaml") Expect(err).NotTo(HaveOccurred()) paddrs, oaddr := server.Addresses() configValue := e2e.Values{ PrivSk: mtlsKeyFile.Name(), SignCert: mtlsCertFile.Name(), Mtls: false, PeersAddrs: paddrs, OrdererAddr: oaddr, CommitThreshold: 1, PolicyFile: PolicyFile.Name(), } e2e.GenerateConfigFile(config.Name(), configValue) cmd0 := exec.Command(tapeBin, "traffic", "-c", config.Name()) cmd1 := exec.Command(tapeBin, "observer", "-c", config.Name()) tapeSession, err = gexec.Start(cmd1, nil, nil) Expect(err).NotTo(HaveOccurred()) _, err = gexec.Start(cmd0, nil, nil) Expect(err).NotTo(HaveOccurred()) Eventually(tapeSession.Out).Should(Say("Time.*Tx.*")) }) }) }) })
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/e2e/mock/peer.go
e2e/mock/peer.go
package mock import ( "context" "net" "github.com/hyperledger/fabric-protos-go-apiv2/peer" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ) type Peer struct { Listener net.Listener GrpcServer *grpc.Server BlkSize, txCnt uint64 TxC chan struct{} ctlCh chan bool } func (p *Peer) ProcessProposal(context.Context, *peer.SignedProposal) (*peer.ProposalResponse, error) { return &peer.ProposalResponse{Response: &peer.Response{Status: 200}}, nil } func (p *Peer) Deliver(peer.Deliver_DeliverServer) error { panic("Not implemented") } func (p *Peer) DeliverFiltered(srv peer.Deliver_DeliverFilteredServer) error { _, err := srv.Recv() if err != nil { panic("expect no recv error") } _ = srv.Send(&peer.DeliverResponse{}) txc := p.TxC for { select { case <-txc: p.txCnt++ if p.txCnt%p.BlkSize == 0 { _ = srv.Send(&peer.DeliverResponse{Type: &peer.DeliverResponse_FilteredBlock{ FilteredBlock: &peer.FilteredBlock{ Number: p.txCnt / p.BlkSize, FilteredTransactions: make([]*peer.FilteredTransaction, p.BlkSize)}}}) } case pause := <-p.ctlCh: if pause { txc = nil } else { txc = p.TxC } } } } func (p *Peer) DeliverWithPrivateData(peer.Deliver_DeliverWithPrivateDataServer) error { panic("Not implemented") } func (p *Peer) Stop() { p.GrpcServer.Stop() p.Listener.Close() } func (p *Peer) Start() { _ = p.GrpcServer.Serve(p.Listener) } func (p *Peer) Addrs() string { return p.Listener.Addr().String() } func NewPeer(TxC chan struct{}, credentials credentials.TransportCredentials) (*Peer, error) { lis, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { return nil, err } ctlCh := make(chan bool) instance := &Peer{ Listener: lis, GrpcServer: grpc.NewServer(grpc.Creds(credentials)), BlkSize: 10, TxC: TxC, ctlCh: ctlCh, } peer.RegisterEndorserServer(instance.GrpcServer, instance) peer.RegisterDeliverServer(instance.GrpcServer, instance) return instance, nil } func (p *Peer) Pause() { p.ctlCh <- true } func (p *Peer) Unpause() { p.ctlCh <- false }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/e2e/mock/orderer.go
e2e/mock/orderer.go
package mock import ( "fmt" "io" "net" "github.com/hyperledger/fabric-protos-go-apiv2/common" "github.com/hyperledger/fabric-protos-go-apiv2/orderer" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ) type Orderer struct { Listener net.Listener GrpcServer *grpc.Server cnt uint64 TxCs []chan struct{} SelfC chan struct{} } func (o *Orderer) Deliver(srv orderer.AtomicBroadcast_DeliverServer) error { _, err := srv.Recv() if err != nil { panic("expect no recv error") } _ = srv.Send(&orderer.DeliverResponse{}) for range o.SelfC { o.cnt++ if o.cnt%10 == 0 { _ = srv.Send(&orderer.DeliverResponse{ Type: &orderer.DeliverResponse_Block{Block: NewBlock(10, nil)}, }) } } return nil } func (o *Orderer) Broadcast(srv orderer.AtomicBroadcast_BroadcastServer) error { for { _, err := srv.Recv() if err == io.EOF { return nil } if err != nil { fmt.Println(err) return err } for _, c := range o.TxCs { c <- struct{}{} } o.SelfC <- struct{}{} err = srv.Send(&orderer.BroadcastResponse{Status: common.Status_SUCCESS}) if err != nil { return err } } } func NewOrderer(txCs []chan struct{}, credentials credentials.TransportCredentials) (*Orderer, error) { lis, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { return nil, err } instance := &Orderer{ Listener: lis, GrpcServer: grpc.NewServer(grpc.Creds(credentials)), TxCs: txCs, SelfC: make(chan struct{}), } orderer.RegisterAtomicBroadcastServer(instance.GrpcServer, instance) return instance, nil } func (o *Orderer) Stop() { o.GrpcServer.Stop() o.Listener.Close() } func (o *Orderer) Addrs() string { return o.Listener.Addr().String() } func (o *Orderer) Start() { _ = o.GrpcServer.Serve(o.Listener) } // NewBlock constructs a block with no data and no metadata. func NewBlock(seqNum uint64, previousHash []byte) *common.Block { block := &common.Block{} block.Header = &common.BlockHeader{} block.Header.Number = seqNum block.Header.PreviousHash = previousHash block.Header.DataHash = []byte{} block.Data = &common.BlockData{} var metadataContents [][]byte for i := 0; i < len(common.BlockMetadataIndex_name); i++ { metadataContents = append(metadataContents, []byte{}) } block.Metadata = &common.BlockMetadata{Metadata: metadataContents} return block }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/e2e/mock/server.go
e2e/mock/server.go
package mock import ( "google.golang.org/grpc/credentials" ) type Server struct { peers []*Peer orderer *Orderer } // this is the channel size for mock server, peer and orderer // when use or send tx to mock server/peer/orderer // try not over this size to avoid hang up or over size const MockTxSize = 1000 func NewServer(peerN int, credentials credentials.TransportCredentials) (*Server, error) { var txCs []chan struct{} var peers []*Peer for i := 0; i < peerN; i++ { txC := make(chan struct{}, MockTxSize) peer, err := NewPeer(txC, credentials) if err != nil { return nil, err } peers = append(peers, peer) txCs = append(txCs, txC) } orderer, err := NewOrderer(txCs, credentials) if err != nil { return nil, err } return &Server{peers: peers, orderer: orderer}, nil } func (s *Server) Start() { for _, v := range s.peers { go v.Start() } go s.orderer.Start() } func (s *Server) Stop() { for _, v := range s.peers { v.Stop() } s.orderer.Stop() } func (s *Server) PeersAddresses() (peersAddrs []string) { peersAddrs = make([]string, len(s.peers)) for k, v := range s.peers { peersAddrs[k] = v.Addrs() } return } func (s *Server) OrderAddr() string { return s.orderer.Addrs() } func (s *Server) Addresses() ([]string, string) { return s.PeersAddresses(), s.OrderAddr() }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/internal/fabric/bccsp/utils/ecdsa.go
internal/fabric/bccsp/utils/ecdsa.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package utils import ( "crypto/ecdsa" "crypto/elliptic" "encoding/asn1" "errors" "fmt" "math/big" ) type ECDSASignature struct { R, S *big.Int } var ( // curveHalfOrders contains the precomputed curve group orders halved. // It is used to ensure that signature' S value is lower or equal to the // curve group order halved. We accept only low-S signatures. // They are precomputed for efficiency reasons. curveHalfOrders = map[elliptic.Curve]*big.Int{ elliptic.P224(): new(big.Int).Rsh(elliptic.P224().Params().N, 1), elliptic.P256(): new(big.Int).Rsh(elliptic.P256().Params().N, 1), elliptic.P384(): new(big.Int).Rsh(elliptic.P384().Params().N, 1), elliptic.P521(): new(big.Int).Rsh(elliptic.P521().Params().N, 1), } ) func UnmarshalECDSASignature(raw []byte) (*big.Int, *big.Int, error) { // Unmarshal sig := new(ECDSASignature) _, err := asn1.Unmarshal(raw, sig) if err != nil { return nil, nil, fmt.Errorf("failed unmashalling signature [%s]", err) } // Validate sig if sig.R == nil { return nil, nil, errors.New("invalid signature, R must be different from nil") } if sig.S == nil { return nil, nil, errors.New("invalid signature, S must be different from nil") } if sig.R.Sign() != 1 { return nil, nil, errors.New("invalid signature, R must be larger than zero") } if sig.S.Sign() != 1 { return nil, nil, errors.New("invalid signature, S must be larger than zero") } return sig.R, sig.S, nil } // IsLow checks that s is a low-S func IsLowS(k *ecdsa.PublicKey, s *big.Int) (bool, error) { halfOrder, ok := curveHalfOrders[k.Curve] if !ok { return false, fmt.Errorf("curve not recognized [%s]", k.Curve) } return s.Cmp(halfOrder) != 1, nil } func ToLowS(k *ecdsa.PublicKey, s *big.Int) (*big.Int, bool, error) { lowS, err := IsLowS(k, s) if err != nil { return nil, false, err } if !lowS { // Set s to N - s that will be then in the lower part of signature space // less or equal to half order s.Sub(k.Params().N, s) return s, true, nil } return s, false, nil }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/internal/fabric/bccsp/utils/keys.go
internal/fabric/bccsp/utils/keys.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package utils import ( "crypto/ecdsa" "crypto/x509" "encoding/pem" "errors" "fmt" ) // DERToPrivateKey unmarshals a der to private key func DERToPrivateKey(der []byte) (key interface{}, err error) { if key, err = x509.ParsePKCS1PrivateKey(der); err == nil { return key, nil } if key, err = x509.ParsePKCS8PrivateKey(der); err == nil { switch key.(type) { case *ecdsa.PrivateKey: return default: return nil, errors.New("Found unknown private key type in PKCS#8 wrapping") } } if key, err = x509.ParseECPrivateKey(der); err == nil { return } return nil, errors.New("Invalid key type. The DER must contain an ecdsa.PrivateKey") } // PEMtoPrivateKey unmarshals a pem to private key func PEMtoPrivateKey(raw []byte, pwd []byte) (interface{}, error) { if len(raw) == 0 { return nil, errors.New("Invalid PEM. It must be different from nil.") } block, _ := pem.Decode(raw) if block == nil { return nil, fmt.Errorf("Failed decoding PEM. Block must be different from nil. [% x]", raw) } // TODO: derive from header the type of the key if x509.IsEncryptedPEMBlock(block) { if len(pwd) == 0 { return nil, errors.New("Encrypted Key. Need a password") } decrypted, err := x509.DecryptPEMBlock(block, pwd) if err != nil { return nil, fmt.Errorf("Failed PEM decryption [%s]", err) } key, err := DERToPrivateKey(decrypted) if err != nil { return nil, err } return key, err } cert, err := DERToPrivateKey(block.Bytes) if err != nil { return nil, err } return cert, err }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/internal/fabric/common/crypto/random.go
internal/fabric/common/crypto/random.go
/* Copyright IBM Corp. 2016 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package crypto import ( "crypto/rand" "github.com/pkg/errors" ) const ( // NonceSize is the default NonceSize NonceSize = 24 ) // GetRandomBytes returns len random looking bytes func GetRandomBytes(len int) ([]byte, error) { key := make([]byte, len) // TODO: rand could fill less bytes then len _, err := rand.Read(key) if err != nil { return nil, errors.Wrap(err, "error getting random bytes") } return key, nil } // GetRandomNonce returns a random byte array of length NonceSize func GetRandomNonce() ([]byte, error) { return GetRandomBytes(NonceSize) }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/internal/fabric/core/comm/creds.go
internal/fabric/core/comm/creds.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package comm import ( "context" "crypto/tls" "net" "github.com/pkg/errors" "google.golang.org/grpc/credentials" ) var ErrServerHandshakeNotImplemented = errors.New("core/comm: server handshakes are not implemented with clientCreds") type DynamicClientCredentials struct { TLSConfig *tls.Config TLSOptions []TLSOption } func (dtc *DynamicClientCredentials) latestConfig() *tls.Config { tlsConfigCopy := dtc.TLSConfig.Clone() for _, tlsOption := range dtc.TLSOptions { tlsOption(tlsConfigCopy) } return tlsConfigCopy } func (dtc *DynamicClientCredentials) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { return credentials.NewTLS(dtc.latestConfig()).ClientHandshake(ctx, authority, rawConn) } func (dtc *DynamicClientCredentials) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { return nil, nil, ErrServerHandshakeNotImplemented } func (dtc *DynamicClientCredentials) Info() credentials.ProtocolInfo { return credentials.NewTLS(dtc.latestConfig()).Info() } func (dtc *DynamicClientCredentials) Clone() credentials.TransportCredentials { return credentials.NewTLS(dtc.latestConfig()) } func (dtc *DynamicClientCredentials) OverrideServerName(name string) error { dtc.TLSConfig.ServerName = name return nil }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/internal/fabric/core/comm/client.go
internal/fabric/core/comm/client.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package comm import ( "crypto/tls" "crypto/x509" "time" grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing" opentracing "github.com/opentracing/opentracing-go" "github.com/pkg/errors" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/keepalive" ) type GRPCClient struct { // TLS configuration used by the grpc.ClientConn tlsConfig *tls.Config // Options for setting up new connections dialOpts []grpc.DialOption // Maximum message size the client can receive maxRecvMsgSize int // Maximum message size the client can send maxSendMsgSize int } // NewGRPCClient creates a new implementation of GRPCClient given an address // and client configuration func NewGRPCClient(config ClientConfig) (*GRPCClient, error) { client := &GRPCClient{} // parse secure options err := client.parseSecureOptions(config.SecOpts) if err != nil { return client, err } // keepalive options kap := keepalive.ClientParameters{ Time: config.KaOpts.ClientInterval, PermitWithoutStream: true, } // set keepalive client.dialOpts = append(client.dialOpts, grpc.WithKeepaliveParams(kap)) // Unless asynchronous connect is set, make connection establishment blocking. /*if !config.AsyncConnect { client.dialOpts = append(client.dialOpts, grpc.WithBlock()) client.dialOpts = append(client.dialOpts, grpc.FailOnNonTempDialError(true)) }*/ // set send/recv message size to package defaults client.maxRecvMsgSize = MaxRecvMsgSize client.maxSendMsgSize = MaxSendMsgSize return client, nil } func (client *GRPCClient) parseSecureOptions(opts SecureOptions) error { // if TLS is not enabled, return if !opts.UseTLS { return nil } client.tlsConfig = &tls.Config{ VerifyPeerCertificate: opts.VerifyCertificate, MinVersion: tls.VersionTLS12} // TLS 1.2 only if len(opts.ServerRootCAs) > 0 { client.tlsConfig.RootCAs = x509.NewCertPool() for _, certBytes := range opts.ServerRootCAs { err := AddPemToCertPool(certBytes, client.tlsConfig.RootCAs) if err != nil { //commLogger.Debugf("error adding root certificate: %v", err) return errors.WithMessage(err, "error adding root certificate") } } } if opts.RequireClientCert { // make sure we have both Key and Certificate if opts.Key != nil && opts.Certificate != nil { cert, err := tls.X509KeyPair(opts.Certificate, opts.Key) if err != nil { return errors.WithMessage(err, "failed to "+ "load client certificate") } client.tlsConfig.Certificates = append( client.tlsConfig.Certificates, cert) } else { return errors.New("both Key and Certificate " + "are required when using mutual TLS") } } if opts.TimeShift > 0 { client.tlsConfig.Time = func() time.Time { return time.Now().Add((-1) * opts.TimeShift) } } return nil } type TLSOption func(tlsConfig *tls.Config) // NewConnection returns a grpc.ClientConn for the target address and // overrides the server name used to verify the hostname on the // certificate returned by a server when using TLS func (client *GRPCClient) NewConnection(address string, tlsOptions ...TLSOption) (*grpc.ClientConn, error) { var dialOpts []grpc.DialOption dialOpts = append(dialOpts, client.dialOpts...) // set transport credentials and max send/recv message sizes // immediately before creating a connection in order to allow // SetServerRootCAs / SetMaxRecvMsgSize / SetMaxSendMsgSize // to take effect on a per connection basis if client.tlsConfig != nil { dialOpts = append(dialOpts, grpc.WithTransportCredentials( &DynamicClientCredentials{ TLSConfig: client.tlsConfig, TLSOptions: tlsOptions, }, )) } else { dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials())) } dialOpts = append(dialOpts, grpc.WithDefaultCallOptions( grpc.MaxCallRecvMsgSize(client.maxRecvMsgSize), grpc.MaxCallSendMsgSize(client.maxSendMsgSize), )) tracer := opentracing.GlobalTracer() opts := []grpc_opentracing.Option{ grpc_opentracing.WithTracer(tracer), } dialOpts = append(dialOpts, grpc.WithUnaryInterceptor(grpc_opentracing.UnaryClientInterceptor(opts...)), grpc.WithStreamInterceptor(grpc_opentracing.StreamClientInterceptor(opts...)), ) conn, err := grpc.NewClient(address, dialOpts...) if err != nil { return nil, errors.WithMessage(errors.WithStack(err), "failed to create new connection") } return conn, nil }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/internal/fabric/core/comm/config.go
internal/fabric/core/comm/config.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package comm import ( "crypto/x509" "time" "google.golang.org/grpc" ) // Configuration defaults var ( // Max send and receive bytes for grpc clients and servers MaxRecvMsgSize = 100 * 1024 * 1024 MaxSendMsgSize = 100 * 1024 * 1024 // Default peer keepalive options DefaultKeepaliveOptions = KeepaliveOptions{ ClientInterval: time.Duration(1) * time.Minute, // 1 min ClientTimeout: time.Duration(20) * time.Second, // 20 sec - gRPC default ServerInterval: time.Duration(2) * time.Hour, // 2 hours - gRPC default ServerTimeout: time.Duration(20) * time.Second, // 20 sec - gRPC default ServerMinInterval: time.Duration(1) * time.Minute, // match ClientInterval } ) // ServerConfig defines the parameters for configuring a GRPCServer instance type ServerConfig struct { // ConnectionTimeout specifies the timeout for connection establishment // for all new connections ConnectionTimeout time.Duration // SecOpts defines the security parameters SecOpts SecureOptions // KaOpts defines the keepalive parameters KaOpts KeepaliveOptions // StreamInterceptors specifies a list of interceptors to apply to // streaming RPCs. They are executed in order. StreamInterceptors []grpc.StreamServerInterceptor // UnaryInterceptors specifies a list of interceptors to apply to unary // RPCs. They are executed in order. UnaryInterceptors []grpc.UnaryServerInterceptor // HealthCheckEnabled enables the gRPC Health Checking Protocol for the server HealthCheckEnabled bool } // ClientConfig defines the parameters for configuring a GRPCClient instance type ClientConfig struct { // SecOpts defines the security parameters SecOpts SecureOptions // KaOpts defines the keepalive parameters KaOpts KeepaliveOptions // Timeout specifies how long the client will block when attempting to // establish a connection Timeout time.Duration // AsyncConnect makes connection creation non blocking AsyncConnect bool } // Clone clones this ClientConfig func (cc ClientConfig) Clone() ClientConfig { shallowClone := cc return shallowClone } // SecureOptions defines the security parameters (e.g. TLS) for a // GRPCServer or GRPCClient instance type SecureOptions struct { // VerifyCertificate, if not nil, is called after normal // certificate verification by either a TLS client or server. // If it returns a non-nil error, the handshake is aborted and that error results. VerifyCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error // PEM-encoded X509 public key to be used for TLS communication Certificate []byte // PEM-encoded private key to be used for TLS communication Key []byte // Set of PEM-encoded X509 certificate authorities used by clients to // verify server certificates ServerRootCAs [][]byte // Set of PEM-encoded X509 certificate authorities used by servers to // verify client certificates ClientRootCAs [][]byte // Whether or not to use TLS for communication UseTLS bool // Whether or not TLS client must present certificates for authentication RequireClientCert bool // CipherSuites is a list of supported cipher suites for TLS CipherSuites []uint16 // TimeShift makes TLS handshakes time sampling shift to the past by a given duration TimeShift time.Duration } // KeepaliveOptions is used to set the gRPC keepalive settings for both // clients and servers type KeepaliveOptions struct { // ClientInterval is the duration after which if the client does not see // any activity from the server it pings the server to see if it is alive ClientInterval time.Duration // ClientTimeout is the duration the client waits for a response // from the server after sending a ping before closing the connection ClientTimeout time.Duration // ServerInterval is the duration after which if the server does not see // any activity from the client it pings the client to see if it is alive ServerInterval time.Duration // ServerTimeout is the duration the server waits for a response // from the client after sending a ping before closing the connection ServerTimeout time.Duration // ServerMinInterval is the minimum permitted time between client pings. // If clients send pings more frequently, the server will disconnect them ServerMinInterval time.Duration }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/internal/fabric/core/comm/util.go
internal/fabric/core/comm/util.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package comm import ( "crypto/x509" "encoding/pem" ) // AddPemToCertPool adds PEM-encoded certs to a cert pool func AddPemToCertPool(pemCerts []byte, pool *x509.CertPool) error { certs, _, err := pemToX509Certs(pemCerts) if err != nil { return err } for _, cert := range certs { pool.AddCert(cert) } return nil } // parse PEM-encoded certs func pemToX509Certs(pemCerts []byte) ([]*x509.Certificate, []string, error) { var certs []*x509.Certificate var subjects []string // it's possible that multiple certs are encoded for len(pemCerts) > 0 { var block *pem.Block block, pemCerts = pem.Decode(pemCerts) if block == nil { break } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, []string{}, err } certs = append(certs, cert) subjects = append(subjects, string(cert.RawSubject)) } return certs, subjects, nil }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/internal/fabric/protoutil/commonutils.go
internal/fabric/protoutil/commonutils.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package protoutil import ( "crypto/rand" "time" "github.com/golang/protobuf/ptypes/timestamp" cb "github.com/hyperledger/fabric-protos-go-apiv2/common" "github.com/pkg/errors" "google.golang.org/protobuf/proto" ) // MarshalOrPanic serializes a protobuf message and panics if this // operation fails func MarshalOrPanic(pb proto.Message) []byte { data, err := proto.Marshal(pb) if err != nil { panic(err) } return data } // Marshal serializes a protobuf message. func Marshal(pb proto.Message) ([]byte, error) { return proto.Marshal(pb) } // CreateNonce generates a nonce using the common/crypto package. func CreateNonce() ([]byte, error) { nonce, err := getRandomNonce() return nonce, errors.WithMessage(err, "error generating random nonce") } // ExtractEnvelope retrieves the requested envelope from a given block and // unmarshals it func ExtractEnvelope(block *cb.Block, index int) (*cb.Envelope, error) { if block.Data == nil { return nil, errors.New("block data is nil") } envelopeCount := len(block.Data.Data) if index < 0 || index >= envelopeCount { return nil, errors.New("envelope index out of bounds") } marshaledEnvelope := block.Data.Data[index] envelope, err := GetEnvelopeFromBlock(marshaledEnvelope) err = errors.WithMessagef(err, "block data does not carry an envelope at index %d", index) return envelope, err } // MakeChannelHeader creates a ChannelHeader. func MakeChannelHeader(headerType cb.HeaderType, version int32, chainID string, epoch uint64) *cb.ChannelHeader { return &cb.ChannelHeader{ Type: int32(headerType), Version: version, Timestamp: &timestamp.Timestamp{ Seconds: time.Now().Unix(), Nanos: 0, }, ChannelId: chainID, Epoch: epoch, } } // MakePayloadHeader creates a Payload Header. func MakePayloadHeader(ch *cb.ChannelHeader, sh *cb.SignatureHeader) *cb.Header { return &cb.Header{ ChannelHeader: MarshalOrPanic(ch), SignatureHeader: MarshalOrPanic(sh), } } // NewSignatureHeader returns a SignatureHeader with a valid nonce. func NewSignatureHeader(id Signer) (*cb.SignatureHeader, error) { creator, err := id.Serialize() if err != nil { return nil, err } nonce, err := CreateNonce() if err != nil { return nil, err } return &cb.SignatureHeader{ Creator: creator, Nonce: nonce, }, nil } // ChannelHeader returns the *cb.ChannelHeader for a given *cb.Envelope. func ChannelHeader(env *cb.Envelope) (*cb.ChannelHeader, error) { envPayload, err := UnmarshalPayload(env.Payload) if err != nil { return nil, err } if envPayload.Header == nil { return nil, errors.New("header not set") } if envPayload.Header.ChannelHeader == nil { return nil, errors.New("channel header not set") } chdr, err := UnmarshalChannelHeader(envPayload.Header.ChannelHeader) if err != nil { return nil, errors.WithMessage(err, "error unmarshaling channel header") } return chdr, nil } // ChannelID returns the Channel ID for a given *cb.Envelope. func ChannelID(env *cb.Envelope) (string, error) { chdr, err := ChannelHeader(env) if err != nil { return "", errors.WithMessage(err, "error retrieving channel header") } return chdr.ChannelId, nil } func getRandomNonce() ([]byte, error) { key := make([]byte, 24) _, err := rand.Read(key) if err != nil { return nil, errors.Wrap(err, "error getting random bytes") } return key, nil }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/internal/fabric/protoutil/txutils.go
internal/fabric/protoutil/txutils.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package protoutil import ( "bytes" "crypto/sha256" "github.com/hyperledger/fabric-protos-go-apiv2/common" "github.com/hyperledger/fabric-protos-go-apiv2/peer" "github.com/pkg/errors" "google.golang.org/protobuf/proto" ) // GetEnvelopeFromBlock gets an envelope from a block's Data field. func GetEnvelopeFromBlock(data []byte) (*common.Envelope, error) { // Block always begins with an envelope var err error env := &common.Envelope{} if err = proto.Unmarshal(data, env); err != nil { return nil, errors.Wrap(err, "error unmarshaling Envelope") } return env, nil } // CreateSignedEnvelope creates a signed envelope of the desired type, with // marshaled dataMsg and signs it func CreateSignedEnvelope( txType common.HeaderType, channelID string, signer Signer, dataMsg proto.Message, msgVersion int32, epoch uint64, ) (*common.Envelope, error) { return CreateSignedEnvelopeWithTLSBinding(txType, channelID, signer, dataMsg, msgVersion, epoch, nil) } // CreateSignedEnvelopeWithTLSBinding creates a signed envelope of the desired // type, with marshaled dataMsg and signs it. It also includes a TLS cert hash // into the channel header func CreateSignedEnvelopeWithTLSBinding( txType common.HeaderType, channelID string, signer Signer, dataMsg proto.Message, msgVersion int32, epoch uint64, tlsCertHash []byte, ) (*common.Envelope, error) { payloadChannelHeader := MakeChannelHeader(txType, msgVersion, channelID, epoch) payloadChannelHeader.TlsCertHash = tlsCertHash var err error payloadSignatureHeader := &common.SignatureHeader{} if signer != nil { payloadSignatureHeader, err = NewSignatureHeader(signer) if err != nil { return nil, err } } data, err := proto.Marshal(dataMsg) if err != nil { return nil, errors.Wrap(err, "error marshaling") } paylBytes := MarshalOrPanic( &common.Payload{ Header: MakePayloadHeader(payloadChannelHeader, payloadSignatureHeader), Data: data, }, ) var sig []byte if signer != nil { sig, err = signer.Sign(paylBytes) if err != nil { return nil, err } } env := &common.Envelope{ Payload: paylBytes, Signature: sig, } return env, nil } // Signer is the interface needed to sign a transaction type Signer interface { Sign(msg []byte) ([]byte, error) Serialize() ([]byte, error) } // CreateSignedTx assembles an Envelope message from proposal, endorsements, // and a signer. This function should be called by a client when it has // collected enough endorsements for a proposal to create a transaction and // submit it to peers for ordering func CreateSignedTx( proposal *peer.Proposal, signer Signer, resps ...*peer.ProposalResponse, ) (*common.Envelope, error) { if len(resps) == 0 { return nil, errors.New("at least one proposal response is required") } // the original header hdr, err := UnmarshalHeader(proposal.Header) if err != nil { return nil, err } // the original payload pPayl, err := UnmarshalChaincodeProposalPayload(proposal.Payload) if err != nil { return nil, err } // check that the signer is the same that is referenced in the header // TODO: maybe worth removing? signerBytes, err := signer.Serialize() if err != nil { return nil, err } shdr, err := UnmarshalSignatureHeader(hdr.SignatureHeader) if err != nil { return nil, err } if !bytes.Equal(signerBytes, shdr.Creator) { return nil, errors.New("signer must be the same as the one referenced in the header") } // ensure that all actions are bitwise equal and that they are successful var a1 []byte for n, r := range resps { if r.Response.Status < 200 || r.Response.Status >= 400 { return nil, errors.Errorf("proposal response was not successful, error code %d, msg %s", r.Response.Status, r.Response.Message) } if n == 0 { a1 = r.Payload continue } if !bytes.Equal(a1, r.Payload) { return nil, errors.New("ProposalResponsePayloads do not match") } } // fill endorsements endorsements := make([]*peer.Endorsement, len(resps)) for n, r := range resps { endorsements[n] = r.Endorsement } // create ChaincodeEndorsedAction cea := &peer.ChaincodeEndorsedAction{ProposalResponsePayload: resps[0].Payload, Endorsements: endorsements} // obtain the bytes of the proposal payload that will go to the transaction propPayloadBytes, err := GetBytesProposalPayloadForTx(pPayl) if err != nil { return nil, err } // serialize the chaincode action payload cap := &peer.ChaincodeActionPayload{ChaincodeProposalPayload: propPayloadBytes, Action: cea} capBytes, err := GetBytesChaincodeActionPayload(cap) if err != nil { return nil, err } // create a transaction taa := &peer.TransactionAction{Header: hdr.SignatureHeader, Payload: capBytes} taas := make([]*peer.TransactionAction, 1) taas[0] = taa tx := &peer.Transaction{Actions: taas} // serialize the tx txBytes, err := GetBytesTransaction(tx) if err != nil { return nil, err } // create the payload payl := &common.Payload{Header: hdr, Data: txBytes} paylBytes, err := GetBytesPayload(payl) if err != nil { return nil, err } // sign the payload sig, err := signer.Sign(paylBytes) if err != nil { return nil, err } // here's the envelope return &common.Envelope{Payload: paylBytes, Signature: sig}, nil } // CreateProposalResponse creates a proposal response. func CreateProposalResponse( hdrbytes []byte, payl []byte, response *peer.Response, results []byte, events []byte, ccid *peer.ChaincodeID, signingEndorser Signer, ) (*peer.ProposalResponse, error) { hdr, err := UnmarshalHeader(hdrbytes) if err != nil { return nil, err } // obtain the proposal hash given proposal header, payload and the // requested visibility pHashBytes, err := GetProposalHash1(hdr, payl) if err != nil { return nil, errors.WithMessage(err, "error computing proposal hash") } // get the bytes of the proposal response payload - we need to sign them prpBytes, err := GetBytesProposalResponsePayload(pHashBytes, response, results, events, ccid) if err != nil { return nil, err } // serialize the signing identity endorser, err := signingEndorser.Serialize() if err != nil { return nil, errors.WithMessage(err, "error serializing signing identity") } // sign the concatenation of the proposal response and the serialized // endorser identity with this endorser's key signature, err := signingEndorser.Sign(append(prpBytes, endorser...)) if err != nil { return nil, errors.WithMessage(err, "could not sign the proposal response payload") } resp := &peer.ProposalResponse{ // Timestamp: TODO! Version: 1, // TODO: pick right version number Endorsement: &peer.Endorsement{ Signature: signature, Endorser: endorser, }, Payload: prpBytes, Response: &peer.Response{ Status: 200, Message: "OK", }, } return resp, nil } // GetSignedProposal returns a signed proposal given a Proposal message and a // signing identity func GetSignedProposal(prop *peer.Proposal, signer Signer) (*peer.SignedProposal, error) { // check for nil argument if prop == nil || signer == nil { return nil, errors.New("nil arguments") } propBytes, err := proto.Marshal(prop) if err != nil { return nil, err } signature, err := signer.Sign(propBytes) if err != nil { return nil, err } return &peer.SignedProposal{ProposalBytes: propBytes, Signature: signature}, nil } // GetBytesProposalPayloadForTx takes a ChaincodeProposalPayload and returns // its serialized version according to the visibility field func GetBytesProposalPayloadForTx( payload *peer.ChaincodeProposalPayload, ) ([]byte, error) { // check for nil argument if payload == nil { return nil, errors.New("nil arguments") } // strip the transient bytes off the payload cppNoTransient := &peer.ChaincodeProposalPayload{Input: payload.Input, TransientMap: nil} cppBytes, err := GetBytesChaincodeProposalPayload(cppNoTransient) if err != nil { return nil, err } return cppBytes, nil } // GetProposalHash1 gets the proposal hash bytes after sanitizing the // chaincode proposal payload according to the rules of visibility func GetProposalHash1(header *common.Header, ccPropPayl []byte) ([]byte, error) { // check for nil argument if header == nil || header.ChannelHeader == nil || header.SignatureHeader == nil || ccPropPayl == nil { return nil, errors.New("nil arguments") } // unmarshal the chaincode proposal payload cpp, err := UnmarshalChaincodeProposalPayload(ccPropPayl) if err != nil { return nil, err } ppBytes, err := GetBytesProposalPayloadForTx(cpp) if err != nil { return nil, err } hash2 := sha256.New() // hash the serialized Channel Header object hash2.Write(header.ChannelHeader) // hash the serialized Signature Header object hash2.Write(header.SignatureHeader) // hash of the part of the chaincode proposal payload that will go to the tx hash2.Write(ppBytes) return hash2.Sum(nil), nil }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/internal/fabric/protoutil/proputils.go
internal/fabric/protoutil/proputils.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package protoutil import ( "crypto/sha256" "encoding/hex" "time" "github.com/hyperledger/fabric-protos-go-apiv2/common" "github.com/hyperledger/fabric-protos-go-apiv2/peer" "github.com/pkg/errors" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) // CreateChaincodeProposal creates a proposal from given input. // It returns the proposal and the transaction id associated to the proposal func CreateChaincodeProposal(typ common.HeaderType, channelID string, cis *peer.ChaincodeInvocationSpec, creator []byte) (*peer.Proposal, string, error) { return CreateChaincodeProposalWithTransient(typ, channelID, cis, creator, nil) } // CreateChaincodeProposalWithTransient creates a proposal from given input // It returns the proposal and the transaction id associated to the proposal func CreateChaincodeProposalWithTransient(typ common.HeaderType, channelID string, cis *peer.ChaincodeInvocationSpec, creator []byte, transientMap map[string][]byte) (*peer.Proposal, string, error) { // generate a random nonce nonce, err := getRandomNonce() if err != nil { return nil, "", err } // compute txid txid := ComputeTxID(nonce, creator) return CreateChaincodeProposalWithTxIDNonceAndTransient(txid, typ, channelID, cis, nonce, creator, transientMap) } // CreateChaincodeProposalWithTxIDNonceAndTransient creates a proposal from // given input func CreateChaincodeProposalWithTxIDNonceAndTransient(txid string, typ common.HeaderType, channelID string, cis *peer.ChaincodeInvocationSpec, nonce, creator []byte, transientMap map[string][]byte) (*peer.Proposal, string, error) { ccHdrExt := &peer.ChaincodeHeaderExtension{ChaincodeId: cis.ChaincodeSpec.ChaincodeId} ccHdrExtBytes, err := proto.Marshal(ccHdrExt) if err != nil { return nil, "", errors.Wrap(err, "error marshaling ChaincodeHeaderExtension") } cisBytes, err := proto.Marshal(cis) if err != nil { return nil, "", errors.Wrap(err, "error marshaling ChaincodeInvocationSpec") } ccPropPayload := &peer.ChaincodeProposalPayload{Input: cisBytes, TransientMap: transientMap} ccPropPayloadBytes, err := proto.Marshal(ccPropPayload) if err != nil { return nil, "", errors.Wrap(err, "error marshaling ChaincodeProposalPayload") } // TODO: epoch is now set to zero. This must be changed once we // get a more appropriate mechanism to handle it in. var epoch uint64 timestamp := timestamppb.New(time.Now().UTC()) hdr := &common.Header{ ChannelHeader: MarshalOrPanic( &common.ChannelHeader{ Type: int32(typ), TxId: txid, Timestamp: timestamp, ChannelId: channelID, Extension: ccHdrExtBytes, Epoch: epoch, }, ), SignatureHeader: MarshalOrPanic( &common.SignatureHeader{ Nonce: nonce, Creator: creator, }, ), } hdrBytes, err := proto.Marshal(hdr) if err != nil { return nil, "", err } prop := &peer.Proposal{ Header: hdrBytes, Payload: ccPropPayloadBytes, } return prop, txid, nil } // GetBytesProposalResponsePayload gets proposal response payload func GetBytesProposalResponsePayload(hash []byte, response *peer.Response, result []byte, event []byte, ccid *peer.ChaincodeID) ([]byte, error) { cAct := &peer.ChaincodeAction{ Events: event, Results: result, Response: response, ChaincodeId: ccid, } cActBytes, err := proto.Marshal(cAct) if err != nil { return nil, errors.Wrap(err, "error marshaling ChaincodeAction") } prp := &peer.ProposalResponsePayload{ Extension: cActBytes, ProposalHash: hash, } prpBytes, err := proto.Marshal(prp) return prpBytes, errors.Wrap(err, "error marshaling ProposalResponsePayload") } // GetBytesChaincodeProposalPayload gets the chaincode proposal payload func GetBytesChaincodeProposalPayload(cpp *peer.ChaincodeProposalPayload) ([]byte, error) { cppBytes, err := proto.Marshal(cpp) return cppBytes, errors.Wrap(err, "error marshaling ChaincodeProposalPayload") } // GetBytesChaincodeActionPayload get the bytes of ChaincodeActionPayload from // the message func GetBytesChaincodeActionPayload(cap *peer.ChaincodeActionPayload) ([]byte, error) { capBytes, err := proto.Marshal(cap) return capBytes, errors.Wrap(err, "error marshaling ChaincodeActionPayload") } // GetBytesTransaction get the bytes of Transaction from the message func GetBytesTransaction(tx *peer.Transaction) ([]byte, error) { bytes, err := proto.Marshal(tx) return bytes, errors.Wrap(err, "error unmarshaling Transaction") } // GetBytesPayload get the bytes of Payload from the message func GetBytesPayload(payl *common.Payload) ([]byte, error) { bytes, err := proto.Marshal(payl) return bytes, errors.Wrap(err, "error marshaling Payload") } // CreateProposalFromCIS returns a proposal given a serialized identity and a // ChaincodeInvocationSpec func CreateProposalFromCIS(typ common.HeaderType, channelID string, cis *peer.ChaincodeInvocationSpec, creator []byte) (*peer.Proposal, string, error) { return CreateChaincodeProposal(typ, channelID, cis, creator) } // ComputeTxID computes TxID as the Hash computed // over the concatenation of nonce and creator. func ComputeTxID(nonce, creator []byte) string { // TODO: Get the Hash function to be used from // channel configuration hasher := sha256.New() hasher.Write(nonce) hasher.Write(creator) return hex.EncodeToString(hasher.Sum(nil)) }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
Hyperledger-TWGC/tape
https://github.com/Hyperledger-TWGC/tape/blob/ef65cc6c14e3fdf5d47d919d2be880c1817efb56/internal/fabric/protoutil/unmarshalers.go
internal/fabric/protoutil/unmarshalers.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package protoutil import ( "github.com/hyperledger/fabric-protos-go-apiv2/common" cb "github.com/hyperledger/fabric-protos-go-apiv2/common" "github.com/hyperledger/fabric-protos-go-apiv2/peer" "github.com/pkg/errors" "google.golang.org/protobuf/proto" ) // UnmarshalPayload unmarshals bytes to a Payload func UnmarshalPayload(encoded []byte) (*cb.Payload, error) { payload := &cb.Payload{} err := proto.Unmarshal(encoded, payload) return payload, errors.Wrap(err, "error unmarshaling Payload") } // UnmarshalEnvelope unmarshals bytes to a Envelope func UnmarshalEnvelope(encoded []byte) (*cb.Envelope, error) { envelope := &cb.Envelope{} err := proto.Unmarshal(encoded, envelope) return envelope, errors.Wrap(err, "error unmarshaling Envelope") } // UnmarshalChannelHeader unmarshals bytes to a ChannelHeader func UnmarshalChannelHeader(bytes []byte) (*cb.ChannelHeader, error) { chdr := &cb.ChannelHeader{} err := proto.Unmarshal(bytes, chdr) return chdr, errors.Wrap(err, "error unmarshaling ChannelHeader") } // UnmarshalSignatureHeader unmarshals bytes to a SignatureHeader func UnmarshalSignatureHeader(bytes []byte) (*cb.SignatureHeader, error) { sh := &common.SignatureHeader{} err := proto.Unmarshal(bytes, sh) return sh, errors.Wrap(err, "error unmarshaling SignatureHeader") } // UnmarshalHeader unmarshals bytes to a Header func UnmarshalHeader(bytes []byte) (*common.Header, error) { hdr := &common.Header{} err := proto.Unmarshal(bytes, hdr) return hdr, errors.Wrap(err, "error unmarshaling Header") } // UnmarshalChaincodeAction unmarshals bytes to a ChaincodeAction func UnmarshalChaincodeAction(caBytes []byte) (*peer.ChaincodeAction, error) { chaincodeAction := &peer.ChaincodeAction{} err := proto.Unmarshal(caBytes, chaincodeAction) return chaincodeAction, errors.Wrap(err, "error unmarshaling ChaincodeAction") } // UnmarshalProposalResponsePayload unmarshals bytes to a ProposalResponsePayload func UnmarshalProposalResponsePayload(prpBytes []byte) (*peer.ProposalResponsePayload, error) { prp := &peer.ProposalResponsePayload{} err := proto.Unmarshal(prpBytes, prp) return prp, errors.Wrap(err, "error unmarshaling ProposalResponsePayload") } // UnmarshalTransaction unmarshals bytes to a Transaction func UnmarshalTransaction(txBytes []byte) (*peer.Transaction, error) { tx := &peer.Transaction{} err := proto.Unmarshal(txBytes, tx) return tx, errors.Wrap(err, "error unmarshaling Transaction") } // UnmarshalChaincodeActionPayload unmarshals bytes to a ChaincodeActionPayload func UnmarshalChaincodeActionPayload(capBytes []byte) (*peer.ChaincodeActionPayload, error) { cap := &peer.ChaincodeActionPayload{} err := proto.Unmarshal(capBytes, cap) return cap, errors.Wrap(err, "error unmarshaling ChaincodeActionPayload") } // UnmarshalChaincodeProposalPayload unmarshals bytes to a ChaincodeProposalPayload func UnmarshalChaincodeProposalPayload(bytes []byte) (*peer.ChaincodeProposalPayload, error) { cpp := &peer.ChaincodeProposalPayload{} err := proto.Unmarshal(bytes, cpp) return cpp, errors.Wrap(err, "error unmarshaling ChaincodeProposalPayload") }
go
Apache-2.0
ef65cc6c14e3fdf5d47d919d2be880c1817efb56
2026-01-07T10:05:21.922186Z
false
mactat/framed
https://github.com/mactat/framed/blob/4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7/framed.go
framed.go
/* Copyright © 2023 Maciej Tatarski maciektatarski@gmail.com */ package main import "framed/cmd" func main() { cmd.Execute() }
go
MIT
4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7
2026-01-07T10:05:21.947025Z
false
mactat/framed
https://github.com/mactat/framed/blob/4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7/pkg/ext/network.go
pkg/ext/network.go
package ext import ( "io" "net/http" "os" ) func ExampleToUrl(example string) string { return "https://raw.githubusercontent.com/mactat/framed/master/examples/" + example + ".yaml" } func ImportFromUrl(path string, url string) error { // Get the data resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() // Create the file out, err := os.Create(path) if err != nil { return err } defer out.Close() // Write the body to file _, err = io.Copy(out, resp.Body) return err }
go
MIT
4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7
2026-01-07T10:05:21.947025Z
false
mactat/framed
https://github.com/mactat/framed/blob/4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7/pkg/ext/printer.go
pkg/ext/printer.go
package ext import ( "fmt" "os" "strings" "github.com/TwiN/go-color" ) func PrintOut(prompt string, text string) { fmt.Printf("%-35s %-35s\n", prompt, text) } // This is ugly but it works, it needs to be refactored. It also has some bugs in case of out of order directories. func VisualizeTemplate(template []SingleDir) { for dirNum, dir := range template { connectorDir := "├──" initString := "" depth := strings.Count(dir.Path, string(os.PathSeparator)) + 1 name := strings.Split(dir.Path, string(os.PathSeparator))[depth-1] dirDepth := depth if depth <= 2 { dirDepth = 1 } else { initString = "│" } if dirNum == len(template)-1 { connectorDir = "└──" } printDirectory(initString, dirDepth, connectorDir, name) if dir.Files == nil { continue } for num, file := range *dir.Files { connector := "├──" if depth > 1 { initString = "│" } if num == len(*dir.Files)-1 { connector = "└──" } printFile(initString, depth, connector, file) } } } func printDirectory(initString string, dirDepth int, connectorDir string, name string) { output := initString + strings.Repeat(" ", dirDepth-1) + connectorDir + " 📂 " + color.Ize(color.Blue, name) println(output) } func printFile(initString string, depth int, connector string, file string) { output := initString + strings.Repeat(" ", depth-1) + connector + " 📄 " + color.Ize(color.Green, file) println(output) }
go
MIT
4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7
2026-01-07T10:05:21.947025Z
false
mactat/framed
https://github.com/mactat/framed/blob/4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7/pkg/ext/decoder.go
pkg/ext/decoder.go
package ext import ( "fmt" "os" "github.com/creasty/defaults" "gopkg.in/yaml.v3" ) // SingleDir struct type SingleDir struct { Name string `yaml:"name"` Path string `yaml:"path"` Files *[]string `yaml:"files"` Dirs *[]SingleDir `yaml:"dirs"` AllowedPatterns *[]string `yaml:"allowedPatterns"` ForbiddenPatterns *[]string `yaml:"forbiddenPatterns"` MinCount int `default:"0" yaml:"minCount"` MaxCount int `default:"1000" yaml:"maxCount"` MaxDepth int `default:"1000" yaml:"maxDepth"` AllowChildren bool `default:"true" yaml:"allowChildren"` } // UnmarshalYAML implements yaml.Unmarshaler interface // Meant for initializing default values func (s *SingleDir) UnmarshalYAML(unmarshal func(interface{}) error) error { err := defaults.Set(s) if err != nil { fmt.Println("Cannot set defaults!") os.Exit(1) } type plain SingleDir if err := unmarshal((*plain)(s)); err != nil { return err } return nil } type config struct { Name string `yaml:"name"` Structure *SingleDir `yaml:"structure"` } func ReadConfig(path string) (config, []SingleDir) { yamlFile, err := os.ReadFile(path) if err != nil { // add emoji PrintOut("☠️ Can not read file ==>", path) os.Exit(1) } PrintOut("✅ Loaded template from ==>", path) // Map to store the parsed YAML data var curConfig config // Unmarshal the YAML string into the data map err = yaml.Unmarshal([]byte(yamlFile), &curConfig) if err != nil { PrintOut("☠️ Can not decode file ==>", path) os.Exit(1) } if curConfig.Structure == nil { PrintOut("☠️ Can not find correct structure in ==>", path) os.Exit(1) } else { PrintOut("✅ Read structure for ==>", curConfig.Name) } dirList := []SingleDir{} traverseStructure(curConfig.Structure, ".", &dirList) return curConfig, dirList } func traverseStructure(dir *SingleDir, path string, dirsList *[]SingleDir) { // Change path if dir == nil { PrintOut("☠️ Can't traverse nil dir ==>", path) os.Exit(1) } dir.Path = path // add current dir to dirsList *dirsList = append(*dirsList, *dir) if dir.Dirs == nil { return } // traverse children for _, child := range *dir.Dirs { traverseStructure(&child, path+"/"+child.Name, dirsList) } }
go
MIT
4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7
2026-01-07T10:05:21.947025Z
false
mactat/framed
https://github.com/mactat/framed/blob/4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7/pkg/ext/system.go
pkg/ext/system.go
package ext import ( "errors" "fmt" "log" "os" "path/filepath" "regexp" "strings" ) func CreateDir(path string) { // Create directory if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { err := os.Mkdir(path, os.ModePerm) fmt.Printf("%-35s %-35s\n", "📂 Creating directory ==> ", path) if err != nil { log.Println(err) } } } func CreateAllDirs(dirList []SingleDir) { for _, dir := range dirList { CreateDir(dir.Path) } } func CreateFile(path string, name string) { // Check if file exists if _, err := os.Stat(path + "/" + name); errors.Is(err, os.ErrNotExist) { // Create file fmt.Printf("%-35s %-35s\n", "📄 Creating file ==> ", path+"/"+name) file, err := os.Create(path + "/" + name) if err != nil { log.Println(err) } defer file.Close() } } func CreateAllFiles(dirList []SingleDir) { for _, dir := range dirList { if dir.Files == nil { continue } for _, file := range *dir.Files { CreateFile(dir.Path, file) } } } // Check if directory exists on given path and is type dir func DirExists(path string) bool { if path == "." { return true } info, err := os.Stat(path) if os.IsNotExist(err) { return false } return info.IsDir() } // Check if file exists on given path and is type file func FileExists(path string) bool { info, err := os.Stat(path) if os.IsNotExist(err) { return false } return !info.IsDir() } // Count files in given directory func CountFiles(path string) int { files, err := os.ReadDir(path) if err != nil { log.Fatal(err) } filesCount := 0 for _, file := range files { if !file.IsDir() { filesCount++ } } return filesCount } func HasDirs(path string) bool { files, err := os.ReadDir(path) if err != nil { log.Fatal(err) } for _, file := range files { if file.IsDir() { return true } } return false } // Check depth of folder tree, exclude .git folder func CheckDepth(path string) int { maxDepth := 0 var depth int err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if info.IsDir() && info.Name() == ".git" { return filepath.SkipDir } else if info.IsDir() { depth = strings.Count(path, string(os.PathSeparator)) + 1 if depth > maxDepth { maxDepth = depth } } return nil }) if err != nil { log.Println(err) } return maxDepth } func MatchPatternInDir(path string, pattern string) []string { if pattern == "" { pattern = ".*" } // List all files in directory files, err := os.ReadDir(path) if err != nil { log.Fatal(err) } matched := []string{} for _, file := range files { if !file.IsDir() { match, err := regexp.MatchString(pattern, file.Name()) if err != nil { log.Fatal(err) } if match { matched = append(matched, file.Name()) } } } return matched } // Capture all subdirectories in given directory func CaptureSubDirs(path string, depth int) []string { var dirs []string err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if info.IsDir() && info.Name() == ".git" { return filepath.SkipDir } else if info.IsDir() && depth > 0 && strings.Count(path, string(os.PathSeparator)) >= depth { return filepath.SkipDir } else if info.IsDir() && info.Name() != "." { dirs = append(dirs, path) } return nil }) if err != nil { fmt.Printf("Cannot traverse dirs!") os.Exit(1) } return dirs } // Capture all files in given directory func CaptureAllFiles(path string, depth int) []string { var files []string err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if info.IsDir() && info.Name() == ".git" { return filepath.SkipDir } else if !info.IsDir() && depth > 0 && strings.Count(path, string(os.PathSeparator)) >= depth { return filepath.SkipDir } else if !info.IsDir() { files = append(files, path) } return nil }) if err != nil { fmt.Printf("Cannot traverse dirs!") os.Exit(1) } return files } // Capture rules for files with same extension in given directory. If all files in subdirectory have the same extension, save the extension to map with directory path as key. // It should return map path -> extension func CaptureRequiredPatterns(path string, depth int) map[string]string { var rules = make(map[string]string) var dirs []string err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if info.IsDir() && info.Name() == ".git" { return filepath.SkipDir } else if info.IsDir() && depth > 0 && strings.Count(path, string(os.PathSeparator)) >= depth { return filepath.SkipDir } else if info.IsDir() && info.Name() != "." { dirs = append(dirs, path) } return nil }) if err != nil { fmt.Printf("Cannot traverse dirs!") os.Exit(1) } // Check files in dir, if all extensions are the same, save extension to map with dir path as key for _, dir := range dirs { files, err := os.ReadDir(dir) if err != nil { log.Fatal(err) } ext := "" for _, file := range files { if !file.IsDir() { extension := filepath.Ext(file.Name()) if ext == "" { ext = extension } else if ext != extension { ext = "" break } } } if ext != "" { rules[dir] = ext } } return rules } func VerifyFiles(dir SingleDir, allGood *bool) { for _, file := range *dir.Files { if !FileExists(dir.Path + "/" + file) { PrintOut("❌ File not found ==>", dir.Path+"/"+file) *allGood = false } } } func VerifyForbiddenPatterns(dir SingleDir, allGood *bool) { for _, pattern := range *dir.ForbiddenPatterns { matched := MatchPatternInDir(dir.Path, pattern) for _, match := range matched { PrintOut("❌ Forbidden pattern ("+pattern+") matched under ==>", dir.Path+"/"+match) *allGood = false } } } func VerifyAllowedPatterns(dir SingleDir, allGood *bool) { matchedCount := 0 for _, pattern := range *dir.AllowedPatterns { matched := MatchPatternInDir(dir.Path, pattern) matchedCount += len(matched) } if matchedCount != CountFiles(dir.Path) && len(*dir.AllowedPatterns) > 0 { patternsString := strings.Join(*dir.AllowedPatterns, " ") PrintOut("❌ Not all files match required pattern ("+patternsString+") under ==>", dir.Path) *allGood = false } }
go
MIT
4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7
2026-01-07T10:05:21.947025Z
false
mactat/framed
https://github.com/mactat/framed/blob/4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7/pkg/ext/encoder.go
pkg/ext/encoder.go
package ext import ( "fmt" "os" "strings" "gopkg.in/yaml.v3" ) // Consider implementing a custom Unmarshaler for SingleDirOut type SingleDirOut struct { Name string `yaml:"name"` Path string `yaml:"-"` Files *[]string `yaml:"files,omitempty"` Dirs *[]SingleDirOut `yaml:"dirs,omitempty"` AllowedPatterns *[]string `yaml:"allowedPatterns,omitempty"` ForbiddenPatterns *[]string `yaml:"forbiddenPatterns,omitempty"` MinCount int `yaml:"minCount,omitempty"` MaxCount int `yaml:"maxCount,omitempty"` MaxDepth int `yaml:"maxDepth,omitempty"` AllowChildren bool `yaml:"allowChildren,omitempty"` } type configOut struct { Name string `yaml:"name"` Structure *SingleDirOut `yaml:"structure"` } func ExportConfig(name string, path string, subdirs []string, files []string, patterns map[string]string) { // create config, files and dirs are empty config := configOut{ Name: name, Structure: &SingleDirOut{ Name: "root", Files: &[]string{}, Dirs: &[]SingleDirOut{}, }, } // add subdirs insertSubdirs(config.Structure.Dirs, subdirs) // add files insertFiles(config.Structure, files) // add patterns insertPatterns(config.Structure, patterns) // export config yamlFile, err := yaml.Marshal(config) if err != nil { fmt.Printf("Error while Marshaling. %v", err) } // Save to file err = os.WriteFile(path, yamlFile, 0644) if err != nil { fmt.Printf("Error while writing file. %v", err) } } func insertSubdirs(dirs *[]SingleDirOut, subdirs []string) { for subdir := range subdirs { insertSingleDir(dirs, subdirs[subdir]) } } func insertSingleDir(dirs *[]SingleDirOut, dir string) { subdirPath := strings.Split(dir, "/") curDirs := dirs for i := range subdirPath { if !containsDir(*curDirs, subdirPath[i]) { *curDirs = append(*curDirs, SingleDirOut{ Name: subdirPath[i], Files: &[]string{}, Dirs: &[]SingleDirOut{}, AllowedPatterns: &[]string{}, }) } // go deeper curDirs = getDir(*curDirs, subdirPath[i]).Dirs } } func containsDir(dirs []SingleDirOut, name string) bool { for _, dir := range dirs { if dir.Name == name { return true } } return false } func getDir(dirs []SingleDirOut, name string) *SingleDirOut { for _, dir := range dirs { if dir.Name == name { return &dir } } return nil } func insertFiles(root *SingleDirOut, files []string) { for file := range files { insertSingleFile(root, files[file]) } } func insertSingleFile(root *SingleDirOut, file string) { subdirPath := strings.Split(file, "/") if len(subdirPath) == 1 { *root.Files = append(*root.Files, subdirPath[0]) return } curDirs := root.Dirs curDir := root for i := 0; i < len(subdirPath)-1; i++ { curDir = getDir(*curDirs, subdirPath[i]) curDirs = curDir.Dirs } *curDir.Files = append(*curDir.Files, subdirPath[len(subdirPath)-1]) } func insertPatterns(root *SingleDirOut, patterns map[string]string) { for dir, pattern := range patterns { insertSinglePattern(root, dir, pattern) } } func insertSinglePattern(root *SingleDirOut, dir string, pattern string) { subdirPath := strings.Split(dir, "/") curDirs := root.Dirs curDir := root for i := range subdirPath { // go deeper curDir = getDir(*curDirs, subdirPath[i]) curDirs = curDir.Dirs } // insert pattern *curDir.AllowedPatterns = append(*curDir.AllowedPatterns, pattern) }
go
MIT
4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7
2026-01-07T10:05:21.947025Z
false
mactat/framed
https://github.com/mactat/framed/blob/4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7/cmd/verify.go
cmd/verify.go
/* Copyright © 2023 Maciej Tatarski maciektatarski@gmail.com */ // Package cmd represents the command line interface of the application package cmd import ( "fmt" "framed/pkg/ext" "os" "github.com/spf13/cobra" ) // testCmd represents the test command var testCmd = &cobra.Command{ Use: "verify", Short: "Verify the project rules and structure", Long: `This command is verifying the project structure for consistency and compliance with the YAML template. Example: framed verify --template ./framed.yaml `, Run: func(cmd *cobra.Command, args []string) { path := cmd.Flag("template").Value.String() // read config _, dirList := ext.ReadConfig(path) allGood := true // verify directories for _, dir := range dirList { if !ext.DirExists(dir.Path) { ext.PrintOut("❌ Directory not found ==>", dir.Path) allGood = false } // verify files if dir.Files != nil { ext.VerifyFiles(dir, &allGood) } // verify minCount numFiles := ext.CountFiles(dir.Path) if numFiles < dir.MinCount { ext.PrintOut("❌ Min count ("+fmt.Sprint(dir.MinCount)+") not met ==>", dir.Path) allGood = false } // verify maxCount if numFiles > dir.MaxCount { ext.PrintOut("❌ Max count ("+fmt.Sprint(dir.MaxCount)+") exceeded ==>", dir.Path) allGood = false } // verify childrenAllowed if !dir.AllowChildren { if ext.HasDirs(dir.Path) { ext.PrintOut("❌ Children not allowed ==>", dir.Path) allGood = false } } // verify maxDepth if ext.CheckDepth(dir.Path) > dir.MaxDepth { ext.PrintOut("❌ Max depth exceeded ("+fmt.Sprint(dir.MaxDepth)+") ==>", dir.Path) allGood = false } // Verify forbidden if dir.ForbiddenPatterns != nil { ext.VerifyForbiddenPatterns(dir, &allGood) } // Verify allowed patterns if dir.AllowedPatterns != nil { ext.VerifyAllowedPatterns(dir, &allGood) } } if allGood { fmt.Println("✅ Verified successfully!") } else { os.Exit(1) } }, } func init() { rootCmd.AddCommand(testCmd) testCmd.PersistentFlags().String("template", "./framed.yaml", "path to template file") }
go
MIT
4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7
2026-01-07T10:05:21.947025Z
false
mactat/framed
https://github.com/mactat/framed/blob/4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7/cmd/root.go
cmd/root.go
/* Copyright © 2023 Maciej Tatarski maciektatarski@gmail.com */ // Package cmd represents the command line interface of the application package cmd import ( "os" "github.com/spf13/cobra" ) // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "framed", Short: "CLI tool for managing folder and files structures", Long: `FRAMED (Files and Directories Reusability, Architecture, and Management) is a powerful CLI tool written in Go that simplifies the organization and management of files and directories in a reusable and architectural manner. It provides YAML templates for defining project structures and ensures that your projects adhere to the defined structure, enabling consistency and reusability. `, } func Execute() { err := rootCmd.Execute() if err != nil { os.Exit(1) } } func init() {}
go
MIT
4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7
2026-01-07T10:05:21.947025Z
false
mactat/framed
https://github.com/mactat/framed/blob/4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7/cmd/create.go
cmd/create.go
/* Copyright © 2023 Maciej Tatarski maciektatarski@gmail.com */ // Package cmd represents the command line interface of the application package cmd import ( "framed/pkg/ext" "github.com/spf13/cobra" ) // createCmd represents the create command var createCmd = &cobra.Command{ Use: "create", Short: "Create a new project structure using a YAML template", Long: `This command is creating a new project structure from a YAML template. Example: framed create --template ./framed.yaml --files true `, Run: func(cmd *cobra.Command, args []string) { path := cmd.Flag("template").Value.String() createFiles := cmd.Flag("files").Value.String() == "true" // read config _, dirList := ext.ReadConfig(path) // create directories ext.CreateAllDirs(dirList) // create files if createFiles { ext.CreateAllFiles(dirList) } }, } func init() { rootCmd.AddCommand(createCmd) createCmd.PersistentFlags().String("template", "./framed.yaml", "path to template file default") createCmd.PersistentFlags().Bool("files", false, "create required files") }
go
MIT
4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7
2026-01-07T10:05:21.947025Z
false
mactat/framed
https://github.com/mactat/framed/blob/4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7/cmd/visualize.go
cmd/visualize.go
/* Copyright © 2023 Maciej Tatarski maciektatarski@gmail.com */ // Package cmd represents the command line interface of the application package cmd import ( "framed/pkg/ext" "github.com/spf13/cobra" ) // visualizeCmd represents the visualize command var visualizeCmd = &cobra.Command{ Use: "visualize", Short: "Visualize the project structure", Long: `This command is visualizing the project structure from a YAML template. Example: framed visualize --template ./framed.yaml`, Run: func(cmd *cobra.Command, args []string) { path := cmd.Flag("template").Value.String() // read config _, dirList := ext.ReadConfig(path) // visualize template ext.VisualizeTemplate(dirList) }, } func init() { rootCmd.AddCommand(visualizeCmd) visualizeCmd.PersistentFlags().String("template", "./framed.yaml", "Path to template file default is ./framed.yaml") }
go
MIT
4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7
2026-01-07T10:05:21.947025Z
false
mactat/framed
https://github.com/mactat/framed/blob/4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7/cmd/capture.go
cmd/capture.go
/* Copyright © 2023 Maciej Tatarski maciektatarski@gmail.com */ // Package cmd represents the command line interface of the application package cmd import ( "fmt" "framed/pkg/ext" "os" "strconv" "github.com/spf13/cobra" ) // captureCmd represents the capture command var captureCmd = &cobra.Command{ Use: "capture", Short: "Capture the current project structure as a YAML template", Long: `This command is capturing the current project structure as a YAML template. Example: framed capture --output ./framed.yaml --name my-project `, Run: func(cmd *cobra.Command, args []string) { output := cmd.Flag("output").Value.String() name := cmd.Flag("name").Value.String() depthStr := cmd.Flag("depth").Value.String() depth, err := strconv.Atoi(depthStr) if err != nil { ext.PrintOut("🚨 Invalid depth value: ", depthStr) os.Exit(1) } ext.PrintOut("📝 Name:", name+"\n") // capture subdirectories subdirs := ext.CaptureSubDirs(".", depth) ext.PrintOut("📂 Directories:", fmt.Sprintf("%v", len(subdirs))) // capture files files := ext.CaptureAllFiles(".", depth) ext.PrintOut("📄 Files:", fmt.Sprintf("%v", len(files))) // capture patterns patterns := ext.CaptureRequiredPatterns(".", depth) ext.PrintOut("🔁 Patterns:", fmt.Sprintf("%v", len(patterns))) // export config ext.ExportConfig(name, output, subdirs, files, patterns) ext.PrintOut("\n✅ Exported to file: ", output) }, } func init() { rootCmd.AddCommand(captureCmd) captureCmd.PersistentFlags().String("output", "./framed.yaml", "path to output file") captureCmd.PersistentFlags().String("name", "default", "name of the project") captureCmd.PersistentFlags().String("depth", "-1", "depth of the directory tree to capture") }
go
MIT
4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7
2026-01-07T10:05:21.947025Z
false
mactat/framed
https://github.com/mactat/framed/blob/4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7/cmd/import.go
cmd/import.go
/* Copyright © 2023 Maciej Tatarski maciektatarski@gmail.com */ // Package cmd represents the command line interface of the application package cmd import ( "framed/pkg/ext" "os" "github.com/spf13/cobra" ) // importCmd represents the import command var importCmd = &cobra.Command{ Use: "import", Short: "Import the project structure", Long: `This command is importing the project structure from a YAML template. It can be imported from a template or from a remote URL. Example: framed import https://raw.githubusercontent.com/username/repo/master/framed.yaml or framed import --example python --output ./python.yaml `, Run: func(cmd *cobra.Command, args []string) { url := cmd.Flag("url").Value.String() example := cmd.Flag("example").Value.String() output := cmd.Flag("output").Value.String() if url != "" { err := ext.ImportFromUrl(output, url) if err != nil { ext.PrintOut("☠️ Failed to import from url ==>", url) os.Exit(1) } } if example != "" { err := ext.ImportFromUrl(output, ext.ExampleToUrl(example)) if err != nil { ext.PrintOut("☠️ Failed to import from example ==>", example) os.Exit(1) } } ext.PrintOut("✅ Saved to ==>", output) // try to load configTree, _ := ext.ReadConfig(output) ext.PrintOut("✅ Imported successfully ==>", configTree.Name) }, } func init() { rootCmd.AddCommand(importCmd) // Here you will define your flags and configuration settings. importCmd.PersistentFlags().String("url", "", "url to template file") importCmd.PersistentFlags().String("example", "", "example template file from github") importCmd.MarkFlagsMutuallyExclusive("url", "example") // path to file importCmd.PersistentFlags().String("output", "./framed.yaml", "path to template file") }
go
MIT
4f18db334ce43b065a4e82dd04ccbbe3fbb7f3f7
2026-01-07T10:05:21.947025Z
false
nafey/minimalytics
https://github.com/nafey/minimalytics/blob/d6447eaff2caadf94db1fd7225acb6707f9a9405/main.go
main.go
package main import ( "minim/cmd" "github.com/jxskiss/mcli" _ "github.com/mattn/go-sqlite3" ) func main() { // cmd.Setup() cmd.Init() mcli.Add("version", cmd.CmdVersion, "View the version details") mcli.Add("status", cmd.CmdStatus, "View the status") mcli.AddGroup("server", "Commands for managing Minimalytics server") mcli.Add("server start", cmd.CmdServerStart, "Start the server") mcli.Add("server stop", cmd.CmdServerStop, "Stop the server") mcli.Add("server restart", cmd.CmdServerRestart, "Restart the server") mcli.AddGroup("web", "Commands for managing the web UI for Minimalytics") mcli.Add("web enable", cmd.CmdUiEnable, "Enable the Minim UI") mcli.Add("web disable", cmd.CmdUiDisable, "Disable the Minim UI") mcli.AddHidden("execserver", cmd.CmdExecServer, "") mcli.Run() }
go
MIT
d6447eaff2caadf94db1fd7225acb6707f9a9405
2026-01-07T10:05:21.899121Z
false
nafey/minimalytics
https://github.com/nafey/minimalytics/blob/d6447eaff2caadf94db1fd7225acb6707f9a9405/cmd/cmd.go
cmd/cmd.go
package cmd import ( "errors" "fmt" "io/fs" "log" "minim/model" "os" "os/exec" "path/filepath" "strconv" "strings" _ "github.com/mattn/go-sqlite3" ) type Message struct { Event string } type Response struct { Status string `json:"status"` Message string `json:"message"` Data any `json:"data,omitempty"` } type StatRequest struct { Event string `json:"event"` } func exists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if errors.Is(err, fs.ErrNotExist) { return false, nil } return false, err } func getMinimDir() (string, error) { homeDir, err := os.UserHomeDir() if err != nil { fmt.Println("Error:", err) return "", err } minimDir := filepath.Join(homeDir, ".minim") isDir, err := exists(minimDir) if err != nil { fmt.Println("Error:", err) return "", err } if isDir { return minimDir, nil } err = os.MkdirAll(minimDir, 0755) if err != nil { return "", err } return minimDir, nil } func Init() { _, err := getMinimDir() if err != nil { fmt.Println(err) } err = model.Init() if err != nil { fmt.Println(err) } } func readPID() (int, error) { minimDir, err := getMinimDir() if err != nil { return -1, err } pidFile := filepath.Join(minimDir, "minim.pid") exists, err := exists(pidFile) if err != nil { return -1, err } if !exists { _, err := os.Create(pidFile) if err != nil { return -1, err } } pidBytes, err := os.ReadFile(pidFile) if err != nil { return -1, err } pidStr := strings.TrimSpace(string(pidBytes)) if pidStr == "" { return -1, nil } pid, err := strconv.Atoi(pidStr) return pid, err } func execserver() error { exepath := os.Args[0] cmd := exec.Command(exepath, "execserver") err := cmd.Start() return err } func GetVersion() (string, error) { data, err := os.ReadFile("VERSION") return string(data), err } func CmdServerStart() { out, err := isServerRunning() if err != nil { fmt.Println(err) return } if out { fmt.Println("Server is already running") return } err = execserver() if err != nil { fmt.Println(err) } } func CmdServerStop() { out, err := isServerRunning() if err != nil { fmt.Println(err) return } if !out { fmt.Println("Server is not running") return } stopServer() } func CmdServerRestart() { running, err := isServerRunning() if err != nil { fmt.Println(err) return } if running { CmdServerStop() } execserver() fmt.Println("Restarted the server") } func CmdExecServer() { err := startServer() if err != nil { log.Print(err) } } func CmdStatus() { out, err := isServerRunning() if err != nil { fmt.Println("Error encountered: ", err) } port, err := model.GetConfigValue("PORT") if err != nil { fmt.Println(err) return } if out { fmt.Println("Server is running on Port:", port) } else { fmt.Println("Server is not running") } minimDir, err := getMinimDir() if err != nil { fmt.Println("Unable to access minim dir at.", minimDir) } else { fmt.Println("Minimalytics directory location:", minimDir) } } func CmdUiEnable() { err := model.SetConfig("UI_ENABLE", "1") if err != nil { fmt.Println(err) } } func CmdUiDisable() { err := model.SetConfig("UI_ENABLE", "0") if err != nil { fmt.Println(err) } } func CmdVersion() { data, err := GetVersion() if err != nil { fmt.Println("Error reading file:", err) return } fmt.Print("Minimalytics version: ") fmt.Println(string(data)) }
go
MIT
d6447eaff2caadf94db1fd7225acb6707f9a9405
2026-01-07T10:05:21.899121Z
false
nafey/minimalytics
https://github.com/nafey/minimalytics/blob/d6447eaff2caadf94db1fd7225acb6707f9a9405/cmd/server.go
cmd/server.go
package cmd import ( "encoding/json" "errors" "fmt" "io" "log" "minim/api" "minim/model" "net/http" "os" "path/filepath" "strconv" "syscall" "time" "github.com/gorilla/mux" "github.com/natefinch/lumberjack" ) func isServerRunning() (bool, error) { pid, err := readPID() if err != nil { return false, err } if pid < 1 { return false, nil } process, err := os.FindProcess(pid) if err != nil { if err.Error() == "os: process already finished" { return false, nil } return false, err } if process == nil { return false, nil } err = process.Signal(syscall.Signal(0)) if err != nil { if err.Error() == "os: process already finished" { return false, nil } return false, err } client := &http.Client{ Timeout: 10 * time.Second, } port, err := model.GetConfigValue("PORT") if err != nil { return false, err } resp, err := client.Get("http://localhost:" + port + "/api/") if err != nil { return false, err } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return false, err } var apiResp Response if err := json.Unmarshal(body, &apiResp); err != nil { return false, err } if apiResp.Status != "OK" || apiResp.Message != "Success" { return false, err } return true, nil } func stopServer() error { pid, err := readPID() if err != nil { return err } process, err := os.FindProcess(pid) if err != nil { fmt.Printf("Failed to find process with PID %d: %v\n", pid, err) return err } err = process.Kill() if err != nil { fmt.Printf("Failed to kill process %d: %v\n", pid, err) return err } _, err = process.Wait() if err != nil { if err.Error() == "wait: no child processes" { fmt.Println("Server has been stopped") return nil } fmt.Printf("Error waiting for process to terminate: %v\n", err) return err } fmt.Println("Server has been stopped") return nil } func isUiEnabled() (bool, error) { ui_enable_row, err := model.GetConfig("UI_ENABLE") if err != nil { log.Println("Unable to read UI config") return false, err } ui_enable, err := strconv.Atoi(ui_enable_row.Value) if err != nil { log.Println("Invalid UI config value") return false, err } if ui_enable != 1 { log.Println("UI has been disabled") return false, err } return true, nil } func uiMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ui_enabled, err := isUiEnabled() if err != nil { log.Println(err) } if !ui_enabled { return } next.ServeHTTP(w, r) }) } func middleware(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ui_enabled, err := isUiEnabled() if err != nil { log.Println(err) } if !ui_enabled { return } next(w, r) } } type spaHandler struct { staticPath string indexPath string } func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { path := filepath.Join(h.staticPath, r.URL.Path) fi, err := os.Stat(path) if os.IsNotExist(err) || fi.IsDir() { http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath)) return } if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r) } func startServer() error { minimDir, err := getMinimDir() if err != nil { fmt.Println("Error accessing minim directory") return err } pidFile := filepath.Join(minimDir, "minim.pid") logFile := filepath.Join(minimDir, "minim.log") pid := os.Getpid() pidStr := strconv.Itoa(pid) err = os.WriteFile(pidFile, []byte(pidStr), 0644) if err != nil { fmt.Println("Error writing to file:", err) return err } log.SetOutput(&lumberjack.Logger{ Filename: logFile, MaxSize: 20, // megabytes MaxBackups: 3, }) log.Println("-------------- Starting Server ---------------") // model.Init() model.DeleteEvents() ticker := time.NewTicker(60 * time.Second) defer ticker.Stop() go func() { for range ticker.C { model.DeleteEvents() } }() r := mux.NewRouter() r.PathPrefix("/api/event/").HandlerFunc((api.Middleware(api.HandleEvent))) r.PathPrefix("/api/stat/").HandlerFunc(middleware(api.Middleware(api.HandleStat))) r.PathPrefix("/api/events/").HandlerFunc(middleware(api.Middleware(api.HandleEventDefsApi))) r.PathPrefix("/api/graphs/").HandlerFunc(middleware(api.Middleware(api.HandleGraphs))) r.PathPrefix("/api/dashboards/").HandlerFunc(middleware(api.Middleware(api.HandleDashboard))) r.PathPrefix("/api/").HandlerFunc(middleware(api.Middleware(api.HandleAPIBase))) spa := spaHandler{staticPath: "static", indexPath: "index.html"} r.PathPrefix("/").Handler(spa) http.Handle("/", r) port, err := model.GetConfigValue("PORT") if err != nil { return err } log.Println("Starting server on port " + port) err = http.ListenAndServe(":"+port, nil) if errors.Is(err, http.ErrServerClosed) { fmt.Printf("server closed\n") return err } else if err != nil { fmt.Printf("error starting server: %s\n", err) os.Exit(1) return err } return nil }
go
MIT
d6447eaff2caadf94db1fd7225acb6707f9a9405
2026-01-07T10:05:21.899121Z
false
nafey/minimalytics
https://github.com/nafey/minimalytics/blob/d6447eaff2caadf94db1fd7225acb6707f9a9405/model/graphs.go
model/graphs.go
package model import ( "database/sql" "errors" "time" // "minimalytics/model" ) type Graph struct { Id int64 `json:"id"` DashboardId int64 `json:"dashboardId"` Name string `json:"name"` Event string `json:"event"` Period string `json:"period"` Length int64 `json:"length"` CreatedOn string `json:"createdOn"` } type GraphUpdate struct { Name string `json:"name"` Event string `json:"event"` Period string `json:"period"` Length int64 `json:"length"` } type GraphCreate struct { DashboardId int64 `json:"dashboardId"` Name string `json:"name"` Event string `json:"event"` Period string `json:"period"` Length int64 `json:"length"` } func InitGraphs() error { query := ` CREATE TABLE IF NOT EXISTS graphs ( id INTEGER PRIMARY KEY AUTOINCREMENT, dashboardId INTEGER NOT NULL, name TEXT, event TEXT, period TEXT, length INTEGER, createdOn TEXT );` _, err := db.Exec(query) return err } func IsValidGraphId(graphId int64) (bool, error) { var exists bool query := `SELECT EXISTS ( SELECT 1 FROM graphs WHERE id = ? );` err := db.QueryRow(query, graphId).Scan(&exists) if err != nil { return false, err } return exists, nil } func GetDashboardGraphs(dashboardId int64) ([]Graph, error) { var graphs []Graph exists, _ := IsValidDashboardId(dashboardId) if !exists { return graphs, errors.New("Invalid DashboardId") } rows, err := db.Query("select * from graphs where dashboardId = ?", dashboardId) if err != nil { return graphs, err } defer rows.Close() for rows.Next() { var graph Graph err := rows.Scan(&graph.Id, &graph.DashboardId, &graph.Name, &graph.Event, &graph.Period, &graph.Length, &graph.CreatedOn) if err != nil { return graphs, err } graphs = append(graphs, graph) } return graphs, err } func GetGraph(graphId int64) (Graph, error) { row := db.QueryRow("select * from graphs where id = ?", graphId) var graph Graph err := row.Scan(&graph.Id, &graph.DashboardId, &graph.Name, &graph.Event, &graph.Period, &graph.Length, &graph.CreatedOn) if err != nil { if errors.Is(err, sql.ErrNoRows) { return graph, errors.New("Invalid graphId") } } return graph, err } func UpdateGraph(graphId int64, updateGraph GraphUpdate) error { _, err := GetGraph(graphId) if err != nil { return err } name := updateGraph.Name event := updateGraph.Event period := updateGraph.Period length := updateGraph.Length if name != "" { // Add validation if needed } if event != "" { exists, _ := IsValidEvent(event) if !exists { return errors.New("Invalid event value") } } if period != "" { if period != "DAILY" && period != "HOURLY" && period != "MINUTELY" { return errors.New("Invalid period value") } } if length == 0 { return errors.New("Invalid length value") } _, err = db.Exec(` UPDATE graphs set name = coalesce(NULLIF(?, ''), name), event = coalesce(NULLIF(?, ''), event), period = coalesce(NULLIF(?, ''), period), length = coalesce(NULLIF(?, 0), length) where id = ?`, name, event, period, length, graphId) return err } func DeleteGraph(graphId int64) error { exists, err := IsValidGraphId(graphId) if !exists { return errors.New("Invalid graphId") } if err != nil { return err } _, err = db.Exec( ` DELETE FROM graphs where id = ? `, graphId) return err } func CreateGraph(createGraph GraphCreate) (Graph, error) { var graph Graph dashboardId := createGraph.DashboardId name := createGraph.Name event := createGraph.Event period := createGraph.Period length := createGraph.Length if dashboardId <= 0 { return graph, errors.New("Invalid dashboardId") } else { exists, _ := IsValidDashboard(dashboardId) if !exists { return graph, errors.New("Invalid dashboardId") } } if name == "" { return graph, errors.New("Invalid name") } if event != "" { exists, _ := IsValidEvent(event) if !exists { return graph, errors.New("Invalid event value") } } else { return graph, errors.New("Event value cannot be empty") } if period != "" { if period != "DAILY" && period != "HOURLY" && period != "MINUTELY" { return graph, errors.New("Invalid period value") } } else { return graph, errors.New("Period cannot be empty") } if length <= 0 { return graph, errors.New("Invalid length value") } currentTime := time.Now() formattedTime := currentTime.Format("2006-01-02 15:04:05") result, err := db.Exec( ` INSERT INTO graphs (dashboardId, name, event, period, length, createdOn) values (?, ?, ?, ?, ?, ?) `, dashboardId, name, event, period, length, formattedTime) if err != nil { return graph, err } graphId, err := result.LastInsertId() if err != nil { return graph, err } graph, err = GetGraph(graphId) return graph, err } func GetGraphData(graphId int64) ([]TimeStat, error) { var statsArray []TimeStat graph, err := GetGraph(graphId) if err != nil { return statsArray, err } event := graph.Event period := graph.Period length := graph.Length return GetEventData(event, period, length) }
go
MIT
d6447eaff2caadf94db1fd7225acb6707f9a9405
2026-01-07T10:05:21.899121Z
false
nafey/minimalytics
https://github.com/nafey/minimalytics/blob/d6447eaff2caadf94db1fd7225acb6707f9a9405/model/config.go
model/config.go
package model import ( "time" ) type Config struct { Id int64 Key string Value string CreatedOn string } func InitConfig() error { query := ` CREATE TABLE IF NOT EXISTS config ( id INTEGER PRIMARY KEY AUTOINCREMENT, key TEXT, value TEXT, createdOn TEXT );` _, err := db.Exec(query) if err != nil { return err } currentTime := time.Now() formattedTime := currentTime.Format("2006-01-02 15:04:05") _, err = GetConfig("PORT") if err != nil { _, err = db.Exec("insert into config (key, value, createdOn) values (?, ?, ?)", "PORT", "3333", formattedTime) if err != nil { return err } } _, err = GetConfig("UI_ENABLE") if err != nil { _, err = db.Exec("insert into config (key, value, createdOn) values (?, ?, ?)", "UI_ENABLE", "1", formattedTime) if err != nil { return err } } return nil } func GetConfig(key string) (Config, error) { row := db.QueryRow("select * from config where key = ?", key) var configItem Config err := row.Scan(&configItem.Id, &configItem.Key, &configItem.Value, &configItem.CreatedOn) return configItem, err } func GetConfigValue(key string) (string, error) { configItem, err := GetConfig(key) return configItem.Value, err } func SetConfig(key string, val string) error { _, err := db.Exec("update config set value = ? where key = ?", val, key) return err }
go
MIT
d6447eaff2caadf94db1fd7225acb6707f9a9405
2026-01-07T10:05:21.899121Z
false
nafey/minimalytics
https://github.com/nafey/minimalytics/blob/d6447eaff2caadf94db1fd7225acb6707f9a9405/model/dash.go
model/dash.go
package model import ( "database/sql" "errors" "time" ) type Dashboard struct { Id int64 `json:"id"` Name string `json:"name"` CreatedOn string `json:"createdOn"` } type DashboardGet struct { Id int64 `json:"id"` Name string `json:"name"` CreatedOn string `json:"createdOn"` Graphs []Graph `json:"graphs"` } type DashboardUpdate struct { Name string `json:"name"` } type DashboardCreate struct { Name string `json:"name"` } func InitDashboards() error { query := ` CREATE TABLE IF NOT EXISTS dashboards ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, createdOn TEXT );` _, err := db.Exec(query) if err != nil { return err } _, err = CreateDashboard(DashboardCreate{ Name: "Example Dashboard", }) return err } func IsValidDashboardId(dashboardId int64) (bool, error) { var exists bool query := `SELECT EXISTS ( SELECT 1 FROM dashboards WHERE id = ? );` err := db.QueryRow(query, dashboardId).Scan(&exists) if err != nil { return false, err } return exists, nil } func GetDashboards() ([]Dashboard, error) { var dashboards []Dashboard rows, err := db.Query("select * from dashboards") if err != nil { return dashboards, err } defer rows.Close() for rows.Next() { var dash Dashboard err := rows.Scan(&dash.Id, &dash.Name, &dash.CreatedOn) // Replace with actual fields if err != nil { return dashboards, err } dashboards = append(dashboards, dash) } return dashboards, nil } func GetDashboard(dashboardId int64) (DashboardGet, error) { row := db.QueryRow("select * from dashboards where id = ?", dashboardId) var dashboard DashboardGet err := row.Scan(&dashboard.Id, &dashboard.Name, &dashboard.CreatedOn) if err != nil { if errors.Is(err, sql.ErrNoRows) { return dashboard, errors.New("Invalid dashboardId") } } var graphs []Graph graphs, err = GetDashboardGraphs(dashboardId) dashboard.Graphs = graphs return dashboard, err } func UpdateDashboard(dashboardId int64, updateDashboard DashboardUpdate) error { _, err := GetDashboard(dashboardId) if err != nil { return err } name := updateDashboard.Name if name != "" { // Add validation if needed } _, err = db.Exec(` UPDATE dashboards set name = coalesce(NULLIF(?, ''), name) where id = ?`, name, dashboardId) if err != nil { return (err) } return nil } func CreateDashboard(createDashboard DashboardCreate) (DashboardGet, error) { name := createDashboard.Name var dash DashboardGet if name == "" { return dash, errors.New("Invalid name for Dashboard") } currentTime := time.Now() formattedTime := currentTime.Format("2006-01-02 15:04:05") result, err := db.Exec( ` INSERT INTO dashboards (name, createdOn) values (?, ?) `, name, formattedTime) if err != nil { return dash, err } dashboardId, err := result.LastInsertId() if err != nil { return dash, err } dash, err = GetDashboard(dashboardId) return dash, err } func DeleteDashboard(dashboardId int64) error { _, err := GetDashboard(dashboardId) if err != nil { return err } graphs, err := GetDashboardGraphs(dashboardId) if err != nil { return err } for _, graph := range graphs { graphId := graph.Id DeleteGraph(graphId) } _, err = db.Exec( ` DELETE FROM dashboards where id = ? `, dashboardId) return err } func IsValidDashboard(dashboardId int64) (bool, error) { var exists bool query := `SELECT EXISTS ( SELECT 1 FROM dashboards WHERE id = ? );` err := db.QueryRow(query, dashboardId).Scan(&exists) if err != nil { return false, err } return exists, nil }
go
MIT
d6447eaff2caadf94db1fd7225acb6707f9a9405
2026-01-07T10:05:21.899121Z
false
nafey/minimalytics
https://github.com/nafey/minimalytics/blob/d6447eaff2caadf94db1fd7225acb6707f9a9405/model/events.go
model/events.go
package model import ( "fmt" "log" "time" ) type EventRow struct { Time int64 Count int64 } type TimeStat struct { Time int64 `json:"time"` Count int64 `json:"count"` } type EventDef struct { Id string `json:"id"` Event string `json:"event"` LastSeen *string `json:"lastSeen"` } func InitEventDefs() error { query := ` CREATE TABLE IF NOT EXISTS events ( id INTEGER PRIMARY KEY AUTOINCREMENT, event TEXT, lastSeen TEXT );` _, err := db.Exec(query) return err } func InitDailyEvent(event string) error { query := fmt.Sprintf(` CREATE TABLE IF NOT EXISTS daily_%s ( time INTEGER PRIMARY KEY, count INTEGER );`, event) _, err := db.Exec(query) if err != nil { log.Println("failed to create table: %w", err) } return err } func InitHourlyEvent(event string) error { query := fmt.Sprintf(` CREATE TABLE IF NOT EXISTS hourly_%s ( time INTEGER PRIMARY KEY, count INTEGER );`, event) _, err := db.Exec(query) if err != nil { log.Println("failed to create table: %w", err) } return err } func InitMinutelyEvent(event string) error { query := fmt.Sprintf(` CREATE TABLE IF NOT EXISTS minutely_%s ( time INTEGER PRIMARY KEY, count INTEGER );`, event) _, err := db.Exec(query) if err != nil { log.Println("failed to create table: %w", err) } return err } func InitEvent(event string) error { row := db.QueryRow("select * from events where event = ?", event) var eventDef EventDef err := row.Scan(&eventDef.Id, &eventDef.Event, &eventDef.LastSeen) if err != nil { log.Print(err) db.Exec("insert into events (event) values (?)", event) InitDailyEvent(event) InitHourlyEvent(event) InitMinutelyEvent(event) } else { // Skip } return err } func GetEventDefs() *[]EventDef { rows, err := db.Query("select * from events") if err != nil { panic(err) } var eventDefs []EventDef for rows.Next() { var eventDef EventDef err := rows.Scan(&eventDef.Id, &eventDef.Event, &eventDef.LastSeen) if err != nil { // Handle scan error panic(err) } eventDefs = append(eventDefs, eventDef) } return &eventDefs } func IsValidEvent(event string) (bool, error) { var exists bool query := `SELECT EXISTS ( SELECT 1 FROM events WHERE event = ? );` err := db.QueryRow(query, event).Scan(&exists) if err != nil { return false, err } return exists, nil } func DeleteEvents() { rows, err := db.Query("select * from events") if err != nil { panic(err) } defer rows.Close() var events []string for rows.Next() { var eventDef EventDef err = rows.Scan(&eventDef.Id, &eventDef.Event, &eventDef.LastSeen) if err != nil { panic(err) } events = append(events, eventDef.Event) } for _, event := range events { // fmt.Printf("%d: %s\n", i+1, event) cutoffTime := time.Now().Unix() - 3600 query := fmt.Sprintf("delete from minutely_%s where time < ?", event) _, err := db.Exec(query, cutoffTime) if err != nil { panic(err) } cutoffTimeH := time.Now().Unix() - 3600*60 query = fmt.Sprintf("delete from hourly_%s where time < ?", event) _, err = db.Exec(query, cutoffTimeH) if err != nil { panic(err) } } } func SubmitDailyEvent(event string) { currentTime := time.Now() dayStart := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 0, 0, 0, 0, currentTime.Location()) time := dayStart.Unix() query := fmt.Sprintf("select * from daily_%s where time = ?", event) row := db.QueryRow(query, time) var eventRow EventRow err := row.Scan(&eventRow.Time, &eventRow.Count) if err != nil { query = fmt.Sprintf("insert into daily_%s (time, count) values (?, ?)", event) db.Exec(query, time, 1) } else { nextCount := eventRow.Count + 1 query = fmt.Sprintf("update daily_%s set count = ? where time = ?", event) db.Exec(query, nextCount, time) } } func SubmitHourlyEvent(event string) { currentTime := time.Now() hourStart := currentTime.Truncate(time.Hour) time := hourStart.Unix() query := fmt.Sprintf("select * from hourly_%s where time = ?", event) row := db.QueryRow(query, time) var eventRow EventRow err := row.Scan(&eventRow.Time, &eventRow.Count) if err != nil { query = fmt.Sprintf("insert into hourly_%s (time, count) values (?, ?)", event) db.Exec(query, time, 1) } else { nextCount := eventRow.Count + 1 query = fmt.Sprintf("update hourly_%s set count = ? where time = ?", event) db.Exec(query, nextCount, time) } } func SubmitMinuteEvent(event string) { currentTime := time.Now() minuteStart := currentTime.Truncate(time.Minute) time := minuteStart.Unix() query := fmt.Sprintf("select * from minutely_%s where time = ?", event) row := db.QueryRow(query, time) var eventRow EventRow err := row.Scan(&eventRow.Time, &eventRow.Count) if err != nil { query = fmt.Sprintf("insert into minutely_%s (time, count) values (?, ?)", event) db.Exec(query, time, 1) } else { nextCount := eventRow.Count + 1 query = fmt.Sprintf("update minutely_%s set count = ? where time = ?", event) db.Exec(query, nextCount, time) } } func GetDailyStat(event string) *[60]TimeStat { currentTime := time.Now() dayStart := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 0, 0, 0, 0, currentTime.Location()) toTimestamp := dayStart.Unix() fromTime := dayStart.AddDate(0, 0, -60) fromTimestamp := time.Date(fromTime.Year(), fromTime.Month(), fromTime.Day(), 0, 0, 0, 0, fromTime.Location()).Unix() query := fmt.Sprintf("select * from daily_%s where time between ? and ?", event) rows, err := db.Query(query, fromTimestamp, toTimestamp) if err != nil { panic(err) } countMap := make(map[int64]int64) for rows.Next() { var eventRow EventRow err = rows.Scan(&eventRow.Time, &eventRow.Count) if err != nil { panic(err) } countMap[eventRow.Time] = eventRow.Count } var statsArray [60]TimeStat for i := 0; i < 60; i++ { iTime := dayStart.AddDate(0, 0, -1*i) iTimestamp := time.Date(iTime.Year(), iTime.Month(), iTime.Day(), 0, 0, 0, 0, iTime.Location()).Unix() iCount := int64(0) foundCount, ok := countMap[iTimestamp] if ok { iCount = foundCount } iStatItem := TimeStat{ Time: iTimestamp, Count: iCount, } statsArray[i] = iStatItem } return &statsArray } func GetHourlyStat(event string) *[60]TimeStat { currentTime := time.Now() hourStart := currentTime.Truncate(time.Hour) toTimestamp := hourStart.Unix() fromTime := hourStart.Add(-60 * time.Hour) fromTimestamp := fromTime.Unix() query := fmt.Sprintf("select * from hourly_%s where time between ? and ?", event) rows, err := db.Query(query, fromTimestamp, toTimestamp) if err != nil { panic(err) } countMap := make(map[int64]int64) for rows.Next() { var eventRow EventRow err = rows.Scan(&eventRow.Time, &eventRow.Count) if err != nil { panic(err) } countMap[eventRow.Time] = eventRow.Count } var statsArray [60]TimeStat for i := 0; i < 60; i++ { iTime := hourStart.Add(time.Duration(-i) * time.Hour) iTimestamp := iTime.Unix() iCount := int64(0) foundCount, ok := countMap[iTimestamp] if ok { iCount = foundCount } iStatItem := TimeStat{ Time: iTimestamp, Count: iCount, } statsArray[i] = iStatItem } return &statsArray } func GetMinuteStat(event string) *[60]TimeStat { currentTime := time.Now() minuteStart := currentTime.Truncate(time.Minute) toTimestamp := minuteStart.Unix() fromTime := minuteStart.Add(-60 * time.Minute) fromTimestamp := fromTime.Unix() query := fmt.Sprintf("select * from minutely_%s where time between ? and ?", event) rows, err := db.Query(query, fromTimestamp, toTimestamp) if err != nil { panic(err) } countMap := make(map[int64]int64) for rows.Next() { var eventRow EventRow err = rows.Scan(&eventRow.Time, &eventRow.Count) if err != nil { panic(err) } countMap[eventRow.Time] = eventRow.Count } var statsArray [60]TimeStat for i := 0; i < 60; i++ { iTime := minuteStart.Add(time.Duration(-i) * time.Minute) iTimestamp := iTime.Unix() iCount := int64(0) foundCount, ok := countMap[iTimestamp] if ok { iCount = foundCount } iStatItem := TimeStat{ Time: iTimestamp, Count: iCount, } statsArray[i] = iStatItem } return &statsArray } func GetEventData(event string, period string, length int64) ([]TimeStat, error) { currentTime := time.Now() var startTime time.Time var fromTime time.Time var toTimestamp int64 var periodPrefix string var intLength int = int(length) statsArray := make([]TimeStat, intLength) if period == "DAILY" { periodPrefix = "daily" startTime = time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 0, 0, 0, 0, currentTime.Location()) fromTime = startTime.AddDate(0, 0, -1*int(length)) } else if period == "HOURLY" { periodPrefix = "hourly" startTime = currentTime.Truncate(time.Hour) fromTime = startTime.Add(-time.Duration(intLength) * time.Hour) } else { periodPrefix = "minutely" startTime = currentTime.Truncate(time.Minute) fromTime = startTime.Add(-time.Duration(intLength) * time.Minute) } toTimestamp = startTime.Unix() fromTimestamp := time.Date(fromTime.Year(), fromTime.Month(), fromTime.Day(), 0, 0, 0, 0, fromTime.Location()).Unix() query := fmt.Sprintf("select * from %s_%s where time between ? and ?", periodPrefix, event) rows, err := db.Query(query, fromTimestamp, toTimestamp) if err != nil { return statsArray, err } countMap := make(map[int64]int64) for rows.Next() { var eventRow EventRow err := rows.Scan(&eventRow.Time, &eventRow.Count) if err != nil { return statsArray, err } countMap[eventRow.Time] = eventRow.Count } for i := 0; i < intLength; i++ { var iTime time.Time if period == "DAILY" { iTime = startTime.Add(time.Duration(-i) * time.Hour * 24) } else if period == "HOURLY" { iTime = startTime.Add(time.Duration(-i) * time.Hour) } else { iTime = startTime.Add(time.Duration(-i) * time.Minute) } iTimestamp := iTime.Unix() iCount := int64(0) foundCount, ok := countMap[iTimestamp] if ok { iCount = foundCount } iStatItem := TimeStat{ Time: iTimestamp, Count: iCount, } statsArray[i] = iStatItem } return statsArray, nil }
go
MIT
d6447eaff2caadf94db1fd7225acb6707f9a9405
2026-01-07T10:05:21.899121Z
false
nafey/minimalytics
https://github.com/nafey/minimalytics/blob/d6447eaff2caadf94db1fd7225acb6707f9a9405/model/common.go
model/common.go
package model import ( "database/sql" "errors" "fmt" "io/fs" "log" "os" "path/filepath" ) var didInit bool = false var db *sql.DB func exists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if errors.Is(err, fs.ErrNotExist) { return false, nil } return false, err } func tableExists(tableName string) (bool, error) { query := `SELECT name FROM sqlite_master WHERE type='table' AND name=?` var name string err := db.QueryRow(query, tableName).Scan(&name) if err == sql.ErrNoRows { return false, nil } if err != nil { return false, fmt.Errorf("error checking table existence: %w", err) } return true, nil } func InitCreateDb() { } func Init() error { if didInit { return nil } var err error homeDir, _ := os.UserHomeDir() dbPath := filepath.Join(homeDir, ".minim", "data.db") exists, err := exists(dbPath) if !exists { } db, err = sql.Open("sqlite3", dbPath) if err != nil { log.Println("Error:", err) } _, err = db.Query("select 1") if err != nil { log.Println("Error:", err) } if err != nil { fmt.Println("Error:", err) panic("Unable to connect to database") } tab, _ := tableExists("config") if !tab { err = InitConfig() if err != nil { return err } } tab, _ = tableExists("graphs") if !tab { err = InitGraphs() if err != nil { return err } } tab, _ = tableExists("dashboards") if !tab { err = InitDashboards() if err != nil { return err } } tab, _ = tableExists("events") if !tab { err = InitEventDefs() if err != nil { return err } } didInit = true return nil }
go
MIT
d6447eaff2caadf94db1fd7225acb6707f9a9405
2026-01-07T10:05:21.899121Z
false
nafey/minimalytics
https://github.com/nafey/minimalytics/blob/d6447eaff2caadf94db1fd7225acb6707f9a9405/api/api.go
api/api.go
package api import ( "bytes" "encoding/json" "errors" "io" "log" "minim/model" "net/http" "strconv" "strings" ) type Message struct { Event string } type Response struct { Status string `json:"status"` Message string `json:"message"` Data any `json:"data,omitempty"` } type StatRequest struct { Event string `json:"event"` Period string `json:"period"` Length int64 `json:"length"` } func isNumber(s string) bool { _, err := strconv.Atoi(s) return err == nil } func writeResponse(w http.ResponseWriter, err error, data any) { w.Header().Set("Content-Type", "application/json") response := Response{ Status: "OK", Message: "Success", Data: data, } if err != nil { w.WriteHeader(http.StatusBadRequest) log.Printf("Error: %v", err) response = Response{ Status: "ERROR", Message: err.Error(), Data: nil, } } if err := json.NewEncoder(w).Encode(response); err != nil { http.Error(w, "Error encoding JSON", http.StatusInternalServerError) } } func Middleware(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") if r.Method == http.MethodOptions { w.WriteHeader(http.StatusOK) return } next(w, r) } } func HandleGraphs(w http.ResponseWriter, r *http.Request) { path := r.URL.Path trimmedPath := strings.Trim(path, "/") parts := strings.Split(trimmedPath, "/") if len(parts) == 2 { switch r.Method { case http.MethodPost: var postData model.GraphCreate if err := json.NewDecoder(r.Body).Decode(&postData); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } graph, err := model.CreateGraph(postData) writeResponse(w, err, graph) default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } } else if len(parts) == 3 { graphId, err := strconv.Atoi(parts[2]) if err != nil { writeResponse(w, err, nil) return } switch r.Method { case http.MethodGet: graph, err := model.GetGraph(int64(graphId)) writeResponse(w, err, graph) case http.MethodPatch: var patchData model.GraphUpdate if err := json.NewDecoder(r.Body).Decode(&patchData); err != nil { http.Error(w, "Invalid request body", http.StatusBadRequest) } err = model.UpdateGraph(int64(graphId), patchData) writeResponse(w, err, nil) case http.MethodDelete: err = model.DeleteGraph(int64(graphId)) writeResponse(w, err, nil) default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } } else if len(parts) == 4 { graphId, err := strconv.Atoi(parts[2]) if err != nil { writeResponse(w, err, nil) return } switch r.Method { case http.MethodGet: graphData, err := model.GetGraphData(int64(graphId)) writeResponse(w, err, graphData) default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } } } func HandleDashboard(w http.ResponseWriter, r *http.Request) { path := r.URL.Path trimmedPath := strings.Trim(path, "/") parts := strings.Split(trimmedPath, "/") if len(parts) == 2 { switch r.Method { case http.MethodGet: dashes, err := model.GetDashboards() if err != nil { writeResponse(w, err, nil) } else { writeResponse(w, err, dashes) } // writeResponse(w, nil, model.GetDashboards()) case http.MethodPost: var postData model.DashboardCreate if err := json.NewDecoder(r.Body).Decode(&postData); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } dash, err := model.CreateDashboard(postData) if err != nil { writeResponse(w, err, nil) } else { writeResponse(w, err, dash) } default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } } else if len(parts) > 2 { dashboardId, err := strconv.Atoi(parts[2]) if err != nil { writeResponse(w, err, nil) return } if len(parts) == 3 { switch r.Method { case http.MethodGet: dash, err := model.GetDashboard(int64(dashboardId)) if err != nil { writeResponse(w, err, nil) } else { writeResponse(w, err, dash) } case http.MethodPatch: var patchData model.DashboardUpdate if err = json.NewDecoder(r.Body).Decode(&patchData); err != nil { http.Error(w, "Invalid request body", http.StatusBadRequest) } err = model.UpdateDashboard(int64(dashboardId), patchData) writeResponse(w, err, nil) case http.MethodDelete: err = model.DeleteDashboard(int64(dashboardId)) writeResponse(w, err, nil) default: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } } else { writeResponse(w, errors.New("Invalid request"), nil) } } } func HandleConfig(w http.ResponseWriter, r *http.Request) { parts := strings.Split(r.URL.Path, "/") if len(parts) < 4 { writeResponse(w, nil, nil) return } key := parts[3] config, _ := model.GetConfig(key) value := config.Value writeResponse(w, nil, value) } func HandleEventDefsApi(w http.ResponseWriter, r *http.Request) { writeResponse(w, nil, model.GetEventDefs()) } func HandleEvent(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) var t Message err := decoder.Decode(&t) if err != nil { log.Println(err) } event := t.Event model.InitEvent(event) model.SubmitDailyEvent(event) model.SubmitHourlyEvent(event) model.SubmitMinuteEvent(event) io.WriteString(w, "OK") } func HandleEvents(w http.ResponseWriter, r *http.Request) { } func HandleStat(w http.ResponseWriter, r *http.Request) { var statRequest StatRequest body, err := io.ReadAll(r.Body) if err != nil { log.Printf("Error reading body: %v", err) writeResponse(w, err, nil) return } defer r.Body.Close() if len(string(body)) <= 2 { writeResponse(w, errors.New("Inavlid body size"), nil) return } decoder := json.NewDecoder(bytes.NewReader(body)) err = decoder.Decode(&statRequest) if err != nil { writeResponse(w, err, nil) } if r.URL.Path == "/api/stat/" { val, err := model.GetEventData(statRequest.Event, statRequest.Period, statRequest.Length) writeResponse(w, err, val) } else if r.URL.Path == "/api/stat/daily/" { writeResponse(w, nil, model.GetDailyStat(statRequest.Event)) } else if r.URL.Path == "/api/stat/hourly/" { writeResponse(w, nil, model.GetHourlyStat(statRequest.Event)) } else if r.URL.Path == "/api/stat/minutes/" { writeResponse(w, nil, model.GetMinuteStat(statRequest.Event)) } else { writeResponse(w, errors.New("Unimplemented"), nil) } } func HandleAPIBase(w http.ResponseWriter, r *http.Request) { writeResponse(w, nil, nil) } func HandleTest(w http.ResponseWriter, r *http.Request) { }
go
MIT
d6447eaff2caadf94db1fd7225acb6707f9a9405
2026-01-07T10:05:21.899121Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/cmd/script/main.go
cmd/script/main.go
package main import ( "flag" "fmt" "github.com/threagile/threagile/pkg/risks/script" "github.com/threagile/threagile/pkg/types" "gopkg.in/yaml.v3" "os" "path/filepath" "strings" ) func main() { var scriptFilename string flag.StringVar(&scriptFilename, "script", "", "script file") flag.Parse() if len(scriptFilename) == 0 { scriptFilename = filepath.Join("pkg", "risks", "scripts", "accidental-secret-leak.yaml") } scriptFilename = filepath.Clean(scriptFilename) ruleData, ruleReadError := os.ReadFile(scriptFilename) if ruleReadError != nil { fmt.Printf("error reading risk category: %v\n", ruleReadError) return } newRule, parseError := new(script.RiskRule).ParseFromData(ruleData) if parseError != nil { fmt.Printf("error parsing scripts from %q: %v\n", scriptFilename, parseError) return } modelFilename := filepath.Clean(filepath.Join("test", "parsed-model.yaml")) modelData, modelReadError := os.ReadFile(modelFilename) if modelReadError != nil { fmt.Printf("error reading model: %v\n", modelReadError) return } parsedModel := new(types.Model) modelUnmarshalError := yaml.Unmarshal(modelData, parsedModel) if modelUnmarshalError != nil { fmt.Printf("error parsing model from %q: %v\n", modelFilename, modelUnmarshalError) return } generatedRisks, riskError := newRule.GenerateRisks(parsedModel) if riskError != nil { fmt.Printf("error generating risks for %q: %v\n", newRule.Category().ID, riskError) return } for n, risk := range generatedRisks { riskExplanation := risk.RiskExplanation ratingExplanation := risk.RatingExplanation risk.RiskExplanation = nil risk.RatingExplanation = nil for _, riskLine := range riskExplanation { fmt.Println(riskLine) } fmt.Println("") for _, ratingLine := range ratingExplanation { fmt.Println(ratingLine) } fmt.Println("") printedRisks, printError := yaml.Marshal(risk) if printError != nil { fmt.Printf("error printing risk #%d for %q: %v\n", n+1, newRule.Category().ID, printError) return } fmt.Printf("generated risk #%d for %q: \n%v\n", n+1, newRule.Category().ID, string(printedRisks)) assets := make([]*types.TechnicalAsset, 0) for _, techAsset := range parsedModel.TechnicalAssets { if strings.EqualFold(techAsset.Id, risk.MostRelevantTechnicalAssetId) { assets = append(assets, techAsset) } } if len(assets) > 0 { fmt.Printf("found %d asset(s) for risk #%d %q\n", len(assets), n+1, risk.SyntheticId) for _, asset := range assets { fmt.Printf(" - %v\n", asset.Title) } } else { fmt.Printf("no assets found for risk #%d %q\n", n+1, risk.SyntheticId) } } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/cmd/threagile/main_test.go
cmd/threagile/main_test.go
package main import ( "encoding/json" "fmt" "github.com/akedrou/textdiff" "github.com/threagile/threagile/pkg/input" "os" "path/filepath" "sort" "strings" "testing" ) func TestParseModelYaml(t *testing.T) { flatModelFile := filepath.Join("..", "..", "test", "all.yaml") flatModel := *new(input.Model).Defaults() flatLoadError := flatModel.Load(flatModelFile) if flatLoadError != nil { t.Errorf("unable to parse model yaml %q: %v", flatModelFile, flatLoadError) return } sort.Strings(flatModel.TagsAvailable) flatModel.TagsAvailable = []string{strings.Join(flatModel.TagsAvailable, ", ")} flatData, flatMarshalError := json.MarshalIndent(flatModel, "", " ") if flatMarshalError != nil { t.Errorf("unable to print model yaml %q: %v", flatModelFile, flatMarshalError) return } splitModelFile := filepath.Join("..", "..", "test", "main.yaml") splitModel := *new(input.Model).Defaults() splitLoadError := splitModel.Load(splitModelFile) if splitLoadError != nil { t.Errorf("unable to parse model yaml %q: %v", splitModelFile, splitLoadError) return } sort.Strings(splitModel.TagsAvailable) splitModel.TagsAvailable = []string{strings.Join(splitModel.TagsAvailable, ", ")} splitModel.Includes = flatModel.Includes splitData, splitMarshalError := json.MarshalIndent(splitModel, "", " ") if splitMarshalError != nil { t.Errorf("unable to print model yaml %q: %v", splitModelFile, splitMarshalError) return } if string(flatData) != string(splitData) { t.Errorf("parsing split model files is broken; diff: %v", textdiff.Unified(flatModelFile, splitModelFile, string(flatData), string(splitData))) return } } func TestParseModelJson(t *testing.T) { modelFile := filepath.Join("..", "..", "test", "all.yaml") model := *new(input.Model).Defaults() flatLoadError := model.Load(modelFile) if flatLoadError != nil { t.Errorf("unable to parse model yaml %q: %v", modelFile, flatLoadError) return } modelJson, marshalError := json.MarshalIndent(model, "", " ") if marshalError != nil { t.Error("Unable to print model json: ", marshalError) return } var modelStruct input.Model unmarshalError := json.Unmarshal(modelJson, &modelStruct) if unmarshalError != nil { jsonFile := "test.json" _ = os.WriteFile(jsonFile, modelJson, 0644) fmt.Printf("Yaml file: %v\n", modelFile) fmt.Printf("Json file: %v\n", jsonFile) t.Error("Unable to parse model json: ", unmarshalError) return } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/cmd/threagile/main.go
cmd/threagile/main.go
package main import ( "github.com/threagile/threagile/internal/threagile" ) var ( buildTimestamp = "" ) func main() { new(threagile.Threagile).Init(buildTimestamp).Execute() }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/cmd/risk_demo/main.go
cmd/risk_demo/main.go
package main import ( "bufio" "flag" "fmt" "gopkg.in/yaml.v3" "io" "os" "github.com/threagile/threagile/pkg/model" "github.com/threagile/threagile/pkg/types" ) type customRiskRule string func main() { getInfo := flag.Bool("get-info", false, "get rule info") generateRisks := flag.Bool("generate-risks", false, "generate risks") flag.Parse() if *getInfo { rule := new(customRiskRule) riskData, marshalError := yaml.Marshal(new(model.CustomRiskCategory).Init(rule.Category(), rule.SupportedTags())) if marshalError != nil { _, _ = fmt.Fprintf(os.Stderr, "failed to print risk data: %v", marshalError) os.Exit(-2) } _, _ = os.Stdout.Write(riskData) os.Exit(0) } if *generateRisks { reader := bufio.NewReader(os.Stdin) inData, outError := io.ReadAll(reader) if outError != nil { _, _ = fmt.Fprintf(os.Stderr, "failed to read model data from stdin\n") os.Exit(-2) } var input types.Model inError := yaml.Unmarshal(inData, &input) if inError != nil { _, _ = fmt.Fprintf(os.Stderr, "failed to parse model: %v\n", inError) os.Exit(-2) } generatedRisks, riskError := new(customRiskRule).GenerateRisks(&input) if riskError != nil { _, _ = fmt.Fprintf(os.Stderr, "failed to generate risks: %v\n", riskError) os.Exit(-2) } outData, marshalError := yaml.Marshal(generatedRisks) if marshalError != nil { _, _ = fmt.Fprintf(os.Stderr, "failed to print generated risks: %v\n", marshalError) os.Exit(-2) } _, _ = os.Stdout.Write(outData) os.Exit(0) } flag.Usage() os.Exit(-2) } func (r customRiskRule) Category() *types.RiskCategory { return &types.RiskCategory{ ID: "demo", Title: "Just a Demo", Description: "Demo Description", Impact: "Demo Impact", ASVS: "Demo ASVS", CheatSheet: "https://example.com", Action: "Demo Action", Mitigation: "Demo Mitigation", Check: "Demo Check", Function: types.Development, STRIDE: types.Tampering, DetectionLogic: "Demo Detection", RiskAssessment: "Demo Risk Assessment", FalsePositives: "Demo False Positive.", ModelFailurePossibleReason: false, CWE: 0, } } func (r customRiskRule) SupportedTags() []string { return []string{"demo tag"} } func (r customRiskRule) GenerateRisks(parsedModel *types.Model) ([]*types.Risk, error) { generatedRisks := make([]*types.Risk, 0) for _, techAsset := range parsedModel.TechnicalAssets { generatedRisks = append(generatedRisks, createRisk(techAsset)) } return generatedRisks, nil } func createRisk(technicalAsset *types.TechnicalAsset) *types.Risk { category := new(customRiskRule).Category() risk := &types.Risk{ CategoryId: category.ID, Severity: types.CalculateSeverity(types.VeryLikely, types.MediumImpact), ExploitationLikelihood: types.VeryLikely, ExploitationImpact: types.MediumImpact, Title: "<b>Demo</b> risk at <b>" + technicalAsset.Title + "</b>", MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: types.Possible, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.CategoryId + "@" + technicalAsset.Id return risk }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/server.go
internal/threagile/server.go
package threagile import ( "github.com/spf13/cobra" "github.com/threagile/threagile/pkg/risks" "github.com/threagile/threagile/pkg/server" ) func (what *Threagile) initServer() *Threagile { serverCmd := &cobra.Command{ Use: "server", Short: "Run server", RunE: func(cmd *cobra.Command, args []string) error { what.processArgs(cmd, args) return what.runServer() }, } serverCmd.PersistentFlags().IntVar(&what.flags.ServerPortValue, serverPortFlagName, what.config.GetServerPort(), "server port") serverCmd.PersistentFlags().StringVar(&what.flags.ServerFolderValue, serverDirFlagName, what.config.GetDataFolder(), "base folder for server mode (default: "+DataDir+")") what.rootCmd.AddCommand(serverCmd) return what } func (what *Threagile) runServer() error { what.config.SetServerMode(true) serverError := what.config.CheckServerFolder() if serverError != nil { return serverError } server.RunServer(what.config, risks.GetBuiltInRiskRules()) return nil }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/print.go
internal/threagile/print.go
package threagile import ( "fmt" "os" "path/filepath" "github.com/spf13/cobra" ) func (what *Threagile) initPrint() *Threagile { what.rootCmd.AddCommand(&cobra.Command{ Use: Print3rdPartyCommand, Short: "Print 3rd-party license information", Long: "\n" + Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp) + "\n\n" + ThirdPartyLicenses, }) what.rootCmd.AddCommand(&cobra.Command{ Use: PrintLicenseCommand, Short: "Print license information", RunE: func(cmd *cobra.Command, args []string) error { what.processArgs(cmd, args) appDir, err := cmd.Flags().GetString(appDirFlagName) if err != nil { cmd.Printf("Unable to read app-dir flag: %v", err) return err } cmd.Println(Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp)) if appDir != filepath.Clean(appDir) { // TODO: do we need this check here? cmd.Printf("weird app folder %v", appDir) return fmt.Errorf("weird app folder") } content, err := os.ReadFile(filepath.Clean(filepath.Join(appDir, "LICENSE.txt"))) if err != nil { cmd.Printf("Unable to read license file: %v", err) return err } cmd.Print(string(content)) cmd.Println() return nil }, }) return what }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/analyze.go
internal/threagile/analyze.go
package threagile import ( "fmt" "github.com/spf13/cobra" "github.com/threagile/threagile/pkg/model" "github.com/threagile/threagile/pkg/report" "github.com/threagile/threagile/pkg/risks" ) func (what *Threagile) initAnalyze() *Threagile { analyze := &cobra.Command{ Use: AnalyzeModelCommand, Short: "Analyze model", Aliases: []string{"analyze", "analyse", "run", "analyse-model"}, RunE: func(cmd *cobra.Command, args []string) error { what.processArgs(cmd, args) commands := what.readCommands() progressReporter := DefaultProgressReporter{Verbose: what.config.GetVerbose()} r, err := model.ReadAndAnalyzeModel(what.config, risks.GetBuiltInRiskRules(), progressReporter) if err != nil { return fmt.Errorf("failed to read and analyze model: %w", err) } err = report.Generate(what.config, r, commands, risks.GetBuiltInRiskRules(), progressReporter) if err != nil { return fmt.Errorf("failed to generate reports: %w", err) } return nil }, CompletionOptions: cobra.CompletionOptions{ DisableDefaultCmd: true, }, } what.rootCmd.AddCommand(analyze) return what }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/version.go
internal/threagile/version.go
package threagile import ( "fmt" "github.com/spf13/cobra" ) func (what *Threagile) initVersion() *Threagile { what.rootCmd.AddCommand(&cobra.Command{ Use: PrintVersionCommand, Short: "Get version information", Long: "\n" + Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp), }) return what }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/attractiveness.go
internal/threagile/attractiveness.go
package threagile type Attractiveness struct { Quantity int `json:"quantity,omitempty" yaml:"quantity"` Confidentiality AttackerFocus `json:"confidentiality" yaml:"confidentiality"` Integrity AttackerFocus `json:"integrity" yaml:"integrity"` Availability AttackerFocus `json:"availability" yaml:"availability"` }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/import.go
internal/threagile/import.go
package threagile import ( "fmt" "github.com/spf13/cobra" "github.com/threagile/threagile/pkg/model" "github.com/threagile/threagile/pkg/report" "github.com/threagile/threagile/pkg/risks" ) func (what *Threagile) initImport() *Threagile { analyze := &cobra.Command{ Use: ImportModelCommand, Short: "Import model (convert to internal representation)", Aliases: []string{"import"}, RunE: func(cmd *cobra.Command, args []string) error { what.processArgs(cmd, args) commands := what.readCommands() progressReporter := DefaultProgressReporter{Verbose: what.config.GetVerbose()} r, err := model.ReadAndAnalyzeModel(what.config, risks.GetBuiltInRiskRules(), progressReporter) if err != nil { return fmt.Errorf("failed to read and analyze model: %w", err) } err = report.Generate(what.config, r, commands, risks.GetBuiltInRiskRules(), progressReporter) if err != nil { return fmt.Errorf("failed to generate reports: %w", err) } return nil }, CompletionOptions: cobra.CompletionOptions{ DisableDefaultCmd: true, }, } what.rootCmd.AddCommand(analyze) return what }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/consts.go
internal/threagile/consts.go
package threagile const ( TempDir = "/dev/shm" AppDir = "/app" PluginDir = "/app" DataDir = "/data" OutputDir = "." ServerDir = "/app/server" KeyDir = "keys" DefaultServerPort = 8080 InputFile = "threagile.yaml" ReportFilename = "report.pdf" ExcelRisksFilename = "risks.xlsx" ExcelTagsFilename = "tags.xlsx" JsonRisksFilename = "risks.json" JsonTechnicalAssetsFilename = "technical-assets.json" JsonStatsFilename = "stats.json" TemplateFilename = "background.pdf" ReportLogoImagePath = "report/threagile-logo.png" DataFlowDiagramFilenameDOT = "data-flow-diagram.gv" DataFlowDiagramFilenamePNG = "data-flow-diagram.png" DataAssetDiagramFilenameDOT = "data-asset-diagram.gv" DataAssetDiagramFilenamePNG = "data-asset-diagram.png" DefaultDiagramDPI = 100 DefaultGraphvizDPI = 120 MinGraphvizDPI = 20 MaxGraphvizDPI = 300 DefaultBackupHistoryFilesToKeep = 50 ) const ( AnalyzeModelCommand = "analyze-model" CreateExampleModelCommand = "create-example-model" CreateStubModelCommand = "create-stub-model" CreateEditingSupportCommand = "create-editing-support" ImportModelCommand = "import-model" ListTypesCommand = "list-types" ListRiskRulesCommand = "list-risk-rules" ListModelMacrosCommand = "list-model-macros" Print3rdPartyCommand = "print-3rd-party-licenses" PrintLicenseCommand = "print-license" CreateCommand = "create" ExplainCommand = "explain" ListCommand = "list" PrintCommand = "print" QuitCommand = "quit" RunCommand = "run" PrintVersionCommand = "version" ) const ( EditingSupportItem = "editing-support" ExampleItem = "example" LicenseItem = "license" MacrosItem = "macros" ModelItem = "model" RiskItem = "risk" RulesItem = "rules" StubItem = "stub" TypesItem = "types" ) const ( ThreagileVersion = "1.0.0" // Also update into example and stub model files and openapi.yaml Logo = " _____ _ _ _ \n |_ _| |__ _ __ ___ __ _ __ _(_) | ___ \n | | | '_ \\| '__/ _ \\/ _` |/ _` | | |/ _ \\\n | | | | | | | | __/ (_| | (_| | | | __/\n |_| |_| |_|_| \\___|\\__,_|\\__, |_|_|\\___|\n |___/ " + "\nThreagile - Agile Threat Modeling" VersionText = "Documentation: https://threagile.io\n" + "Docker Images: https://hub.docker.com/r/threagile/threagile\n" + "Sourcecode: https://github.com/threagile\n" + "License: Open-Source (MIT License)\n" + "Version: " + ThreagileVersion + " (%v)" Examples = "Examples:\n\n" + "If you want to create an example model (via docker) as a starting point to learn about Threagile just run: \n" + " docker run --rm -it -v \"$(pwd)\":app/work threagile/threagile " + CreateExampleModelCommand + " --output app/work \n\n" + "If you want to create a minimal stub model (via docker) as a starting point for your own model just run: \n" + " docker run --rm -it -v \"$(pwd)\":app/work threagile/threagile " + CreateStubModelCommand + " --output app/work \n\n" + "If you want to execute Threagile on a model yaml file (via docker): \n" + " docker run --rm -it -v \"$(pwd)\":app/work threagile/threagile analyze-model --verbose --model --output app/work \n\n" + "If you want to execute Threagile in interactive mode (via docker): \n" + " docker run --rm -it -v \"$(pwd)\":app/work threagile/threagile -i --verbose --model --output app/work \n\n" + "If you want to run Threagile as a server (REST API) on some port (here 8080): \n" + " docker run --rm -it --shm-size=256m -p 8080:8080 --mount 'type=volume,src=threagile-storage,dst=/data,readonly=false' threagile/threagile server --server-port 8080 \n\n" + "If you want to find out about the different enum values usable in the model yaml file: \n" + " docker run --rm -it threagile/threagile " + ListTypesCommand + "\n\n" + "If you want to use some nice editing help (syntax validation, autocompletion, and live templates) in your favourite IDE: \n" + " docker run --rm -it -v \"$(pwd)\":app/work threagile/threagile " + CreateEditingSupportCommand + " --output app/work\n\n" + "If you want to list all available model macros (which are macros capable of reading a model yaml file, asking you questions in a wizard-style and then update the model yaml file accordingly): \n" + " docker run --rm -it threagile/threagile " + ListModelMacrosCommand + " \n\n" + "If you want to execute a certain model macro on the model yaml file (here the macro add-build-pipeline): \n" + " docker run --rm -it -v \"$(pwd)\":app/work threagile/threagile --model app/work/threagile.yaml --output app/work execute-model-macro add-build-pipeline" ThirdPartyLicenses = " - golang (Google Go License): https://golang.org/LICENSE\n" + " - go-yaml (MIT License): https://github.com/go-yaml/yaml/blob/v3/LICENSE\n" + " - graphviz (CPL License): https://graphviz.gitlab.io/license/\n" + " - gofpdf (MIT License): https://github.com/jung-kurt/gofpdf/blob/master/LICENSE\n" + " - go-chart (MIT License): https://github.com/wcharczuk/go-chart/blob/master/LICENSE\n" + " - excelize (BSD License): https://github.com/qax-os/excelize/blob/master/LICENSE\n" + " - graphics-go (BSD License): https://github.com/BurntSushi/graphics-go/blob/master/LICENSE\n" + " - google-uuid (BSD License): https://github.com/google/uuid/blob/master/LICENSE\n" + " - gin-gonic (MIT License): https://github.com/gin-gonic/gin/blob/master/LICENSE\n" + " - cobra-cli (Apache License): https://github.com/spf13/cobra-cli/blob/main/LICENSE.txt\n" )
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/create.go
internal/threagile/create.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package threagile import ( "fmt" "github.com/spf13/cobra" "github.com/threagile/threagile/pkg/examples" ) func (what *Threagile) initCreate() *Threagile { what.rootCmd.AddCommand(&cobra.Command{ Use: CreateExampleModelCommand, Short: "Create example threagile model", Long: "\n" + Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp) + "\n\njust create an example model named threagile-example-model.yaml in the output directory", RunE: func(cmd *cobra.Command, args []string) error { what.processArgs(cmd, args) appDir, err := cmd.Flags().GetString(appDirFlagName) if err != nil { cmd.Printf("Unable to read app-dir flag: %v", err) return err } outDir, err := cmd.Flags().GetString(outputFlagName) if err != nil { cmd.Printf("Unable to read output flag: %v", err) return err } err = examples.CreateExampleModelFile(appDir, outDir, InputFile) if err != nil { cmd.Printf("Unable to copy example model: %v", err) return err } cmd.Println(Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp)) cmd.Println("An example model was created named threagile-example-model.yaml in the output directory.") cmd.Println() cmd.Println(Examples) cmd.Println() return nil }, }) what.rootCmd.AddCommand(&cobra.Command{ Use: CreateStubModelCommand, Short: "Create stub threagile model", Long: "\n" + Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp) + "\n\njust create a minimal stub model named threagile-stub-model.yaml in the output directory", RunE: func(cmd *cobra.Command, args []string) error { what.processArgs(cmd, args) err := examples.CreateStubModelFile(what.config.GetAppFolder(), what.config.GetOutputFolder(), InputFile) if err != nil { cmd.Printf("Unable to copy stub model: %v", err) return err } if !what.config.GetInteractive() { cmd.Println(Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp)) } cmd.Printf("A minimal stub model was created named threagile-stub-model.yaml in %q.\n", what.config.GetOutputFolder()) if !what.config.GetInteractive() { cmd.Println() cmd.Println(Examples) cmd.Println() } return nil }, }) what.rootCmd.AddCommand(&cobra.Command{ Use: CreateEditingSupportCommand, Short: "Create editing support", Long: "\n" + Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp) + "\n\njust create some editing support stuff in the output directory", RunE: func(cmd *cobra.Command, args []string) error { what.processArgs(cmd, args) appDir, err := cmd.Flags().GetString(appDirFlagName) if err != nil { cmd.Printf("Unable to read app-dir flag: %v", err) return err } outDir, err := cmd.Flags().GetString(outputFlagName) if err != nil { cmd.Printf("Unable to read output flag: %v", err) return err } err = examples.CreateEditingSupportFiles(appDir, outDir) if err != nil { cmd.Printf("Unable to copy editing support files: %v", err) return err } cmd.Println(Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp)) cmd.Println("The following files were created in the output directory:") cmd.Println(" - schema.json") cmd.Println(" - live-templates.txt") cmd.Println() cmd.Println("For a perfect editing experience within your IDE of choice you can easily get " + "model syntax validation and autocompletion (very handy for enum values) as well as live templates: " + "Just import the schema.json into your IDE and assign it as \"schema\" to each Threagile YAML file. " + "Also try to import individual parts from the live-templates.txt file into your IDE as live editing templates.") cmd.Println() return nil }, }) return what }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/flags.go
internal/threagile/flags.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package threagile const ( configFlagName = "config" verboseFlagName = "verbose" verboseFlagShorthand = "v" interactiveFlagName = "interactive" interactiveFlagShorthand = "i" appDirFlagName = "app-dir" pluginDirFlagName = "plugin-dir" dataDirFlagName = "data-dir" outputFlagName = "output" serverDirFlagName = "server-dir" tempDirFlagName = "temp-dir" keyDirFlagName = "key-dir" inputFileFlagName = "model" importedFileFlagName = "imported-model" dataFlowDiagramPNGFileFlagName = "data-flow-diagram-png" dataAssetDiagramPNGFileFlagName = "data-asset-diagram-png" dataFlowDiagramDOTFileFlagName = "data-flow-diagram-dot" dataAssetDiagramDOTFileFlagName = "data-asset-diagram-dot" reportFileFlagName = "report" risksExcelFileFlagName = "risks-excel" tagsExcelFileFlagName = "tags-excel" risksJsonFileFlagName = "risks-json" technicalAssetsJsonFileFlagName = "technical-assets-json" statsJsonFileFlagName = "stats-json" templateFileNameFlagName = "background" reportLogoImagePathFlagName = "reportLogoImagePath" technologyFileFlagName = "technology" customRiskRulesPluginFlagName = "custom-risk-rules-plugin" skipRiskRulesFlagName = "skip-risk-rules" executeModelMacroFlagName = "execute-model-macro" serverModeFlagName = "server-mode" serverPortFlagName = "server-port" diagramDpiFlagName = "diagram-dpi" graphvizDpiFlagName = "graphviz-dpi" backupHistoryFilesToKeepFlagName = "backup-history-files-to-keep" addModelTitleFlagName = "add-model-title" keepDiagramSourceFilesFlagName = "keep-diagram-source-files" ignoreOrphanedRiskTrackingFlagName = "ignore-orphaned-risk-tracking" skipDataFlowDiagramFlagName = "skip-data-flow-diagram" skipDataAssetDiagramFlagName = "skip-data-asset-diagram" skipRisksJSONFlagName = "skip-risks-json" skipTechnicalAssetsJSONFlagName = "skip-technical-assets-json" skipStatsJSONFlagName = "skip-stats-json" skipRisksExcelFlagName = "skip-risks-excel" skipTagsExcelFlagName = "skip-tags-excel" skipReportPDFFlagName = "skip-report-pdf" skipReportADOCFlagName = "skip-report-adoc" generateDataFlowDiagramFlagName = "generate-data-flow-diagram" generateDataAssetDiagramFlagName = "generate-data-asset-diagram" generateRisksJSONFlagName = "generate-risks-json" generateTechnicalAssetsJSONFlagName = "generate-technical-assets-json" generateStatsJSONFlagName = "generate-stats-json" generateRisksExcelFlagName = "generate-risks-excel" generateTagsExcelFlagName = "generate-tags-excel" generateReportPDFFlagName = "generate-report-pdf" generateReportADOCFlagName = "generate-report-adoc" ) type Flags struct { Config configFlag string riskRulePluginsValue string skipRiskRulesValue string generateDataFlowDiagramFlag bool // deprecated generateDataAssetDiagramFlag bool // deprecated generateRisksJSONFlag bool // deprecated generateTechnicalAssetsJSONFlag bool // deprecated generateStatsJSONFlag bool // deprecated generateRisksExcelFlag bool // deprecated generateTagsExcelFlag bool // deprecated generateReportPDFFlag bool // deprecated generateReportADOCFlag bool // deprecated }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/risk-excel-config.go
internal/threagile/risk-excel-config.go
package threagile type RiskExcelConfig struct { HideColumns []string `json:"HideColumns,omitempty" yaml:"HideColumns"` SortByColumns []string `json:"SortByColumns,omitempty" yaml:"SortByColumns"` WidthOfColumns map[string]float64 `json:"WidthOfColumns,omitempty" yaml:"WidthOfColumns"` ShrinkColumnsToFit bool `json:"ShrinkColumnsToFit,omitempty" yaml:"ShrinkColumnsToFit"` WrapText bool `json:"WrapText,omitempty" yaml:"WrapText"` ColorText bool `json:"ColorText,omitempty" yaml:"ColorText"` }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/quit.go
internal/threagile/quit.go
package threagile import ( "os" "github.com/spf13/cobra" ) func (what *Threagile) initQuit() *Threagile { quit := &cobra.Command{ Use: QuitCommand, Short: "quit client", Aliases: []string{"exit", "bye", "x", "q"}, Run: func(cmd *cobra.Command, args []string) { what.processArgs(cmd, args) os.Exit(0) }, CompletionOptions: cobra.CompletionOptions{ DisableDefaultCmd: true, }, } what.rootCmd.AddCommand(quit) return what }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/explain.go
internal/threagile/explain.go
package threagile import ( "fmt" "github.com/spf13/cobra" "github.com/threagile/threagile/pkg/macros" "github.com/threagile/threagile/pkg/model" "github.com/threagile/threagile/pkg/risks" "github.com/threagile/threagile/pkg/types" ) func (what *Threagile) initExplain() *Threagile { return what.initExplainNew() } func (what *Threagile) initExplainNew() *Threagile { explainCmd := &cobra.Command{ Use: ExplainCommand, Short: "Explain an item", } what.rootCmd.AddCommand(explainCmd) explainCmd.AddCommand( &cobra.Command{ Use: RiskItem, Short: "Detailed explanation of why a risk was flagged", Args: cobra.MinimumNArgs(1), ArgAliases: []string{"risk_id", "..."}, RunE: what.explainRisk, }, &cobra.Command{ Use: RulesItem, Short: "Detailed explanation of all the risk rules", RunE: what.explainRules, }, &cobra.Command{ Use: MacrosItem, Short: "Explain model macros", Run: what.explainMacros, }, &cobra.Command{ Use: TypesItem, Short: "Print type information (enum values to be used in models)", Run: what.explainTypes, }) return what } func (what *Threagile) explainRisk(cmd *cobra.Command, args []string) error { what.processArgs(cmd, args) progressReporter := DefaultProgressReporter{Verbose: what.config.GetVerbose()} // todo: reuse model if already loaded result, runError := model.ReadAndAnalyzeModel(what.config, risks.GetBuiltInRiskRules(), progressReporter) if runError != nil { cmd.Printf("Failed to read and analyze model: %v", runError) return runError } // todo: implement this _ = result return fmt.Errorf("not implemented yet") } func (what *Threagile) explainRules(cmd *cobra.Command, args []string) error { what.processArgs(cmd, args) cmd.Println(Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp)) cmd.Println("Explanation for risk rules:") cmd.Println() cmd.Println("----------------------") cmd.Println("Custom risk rules:") cmd.Println("----------------------") customRiskRules := model.LoadCustomRiskRules(what.config.GetPluginFolder(), what.config.GetRiskRulePlugins(), DefaultProgressReporter{Verbose: what.config.GetVerbose()}) for _, rule := range customRiskRules { cmd.Printf("%v: %v\n", rule.Category().ID, rule.Category().Description) } cmd.Println() cmd.Println("--------------------") cmd.Println("Built-in risk rules:") cmd.Println("--------------------") cmd.Println() for _, rule := range risks.GetBuiltInRiskRules() { cmd.Printf("%v: %v\n", rule.Category().ID, rule.Category().Description) } cmd.Println() return nil } func (what *Threagile) explainMacros(cmd *cobra.Command, args []string) { what.processArgs(cmd, args) cmd.Println(Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp)) cmd.Println("Explanation for the model macros:") cmd.Println() /* TODO finish plugin stuff cmd.Println("Custom model macros:") for _, macros := range macros.ListCustomMacros() { details := macros.GetMacroDetails() cmd.Println(details.ID, "-->", details.Title) } cmd.Println() */ cmd.Println("----------------------") cmd.Println("Built-in model macros:") cmd.Println("----------------------") for _, macroList := range macros.ListBuiltInMacros() { details := macroList.GetMacroDetails() cmd.Printf("%v: %v\n", details.ID, details.Title) } cmd.Println() } func (what *Threagile) explainTypes(cmd *cobra.Command, args []string) { what.processArgs(cmd, args) cmd.Println(Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp)) fmt.Println("Explanation for the types:") cmd.Println() cmd.Println("The following types are available (can be extended for custom rules):") cmd.Println() for name, values := range types.GetBuiltinTypeValues(what.config) { cmd.Println(name) for _, candidate := range values { cmd.Printf("\t %v: %v\n", candidate, candidate.Explain()) } } }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/execute.go
internal/threagile/execute.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package threagile import ( "fmt" "github.com/spf13/cobra" "github.com/threagile/threagile/pkg/macros" "github.com/threagile/threagile/pkg/model" "github.com/threagile/threagile/pkg/risks" ) func (what *Threagile) initExecute() *Threagile { what.rootCmd.AddCommand(&cobra.Command{ Use: "execute-model-macro", Short: "Execute model macro", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { what.processArgs(cmd, args) progressReporter := DefaultProgressReporter{Verbose: what.config.GetVerbose()} r, err := model.ReadAndAnalyzeModel(what.config, risks.GetBuiltInRiskRules(), progressReporter) if err != nil { return fmt.Errorf("unable to read and analyze model: %w", err) } macrosId := args[0] err = macros.ExecuteModelMacro(r.ModelInput, what.config.GetInputFile(), r.ParsedModel, macrosId) if err != nil { return fmt.Errorf("unable to execute model macro: %w", err) } return nil }, }) return what }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/config.go
internal/threagile/config.go
package threagile import ( "encoding/json" "errors" "fmt" "log" "os" "path/filepath" "runtime" "strings" "gopkg.in/yaml.v3" "github.com/threagile/threagile/pkg/report" "github.com/threagile/threagile/pkg/types" ) type Config struct { ConfigGetter ConfigSetter BuildTimestampValue string `json:"BuildTimestamp,omitempty" yaml:"BuildTimestamp"` VerboseValue bool `json:"Verbose,omitempty" yaml:"Verbose"` InteractiveValue bool `json:"Interactive,omitempty" yaml:"Interactive"` AppFolderValue string `json:"AppFolder,omitempty" yaml:"AppFolder"` PluginFolderValue string `json:"PluginFolder,omitempty" yaml:"PluginFolder"` DataFolderValue string `json:"DataFolder,omitempty" yaml:"DataFolder"` OutputFolderValue string `json:"OutputFolder,omitempty" yaml:"OutputFolder"` ServerFolderValue string `json:"ServerFolder,omitempty" yaml:"ServerFolder"` TempFolderValue string `json:"TempFolder,omitempty" yaml:"TempFolder"` KeyFolderValue string `json:"KeyFolder,omitempty" yaml:"KeyFolder"` InputFileValue string `json:"InputFile,omitempty" yaml:"InputFile"` ImportedInputFileValue string `json:"ImportedInputFile,omitempty" yaml:"ImportedInputFile"` DataFlowDiagramFilenamePNGValue string `json:"DataFlowDiagramFilenamePNG,omitempty" yaml:"DataFlowDiagramFilenamePNG"` DataAssetDiagramFilenamePNGValue string `json:"DataAssetDiagramFilenamePNG,omitempty" yaml:"DataAssetDiagramFilenamePNG"` DataFlowDiagramFilenameDOTValue string `json:"DataFlowDiagramFilenameDOT,omitempty" yaml:"DataFlowDiagramFilenameDOT"` DataAssetDiagramFilenameDOTValue string `json:"DataAssetDiagramFilenameDOT,omitempty" yaml:"DataAssetDiagramFilenameDOT"` ReportFilenameValue string `json:"ReportFilename,omitempty" yaml:"ReportFilename"` ExcelRisksFilenameValue string `json:"ExcelRisksFilename,omitempty" yaml:"ExcelRisksFilename"` ExcelTagsFilenameValue string `json:"ExcelTagsFilename,omitempty" yaml:"ExcelTagsFilename"` JsonRisksFilenameValue string `json:"JsonRisksFilename,omitempty" yaml:"JsonRisksFilename"` JsonTechnicalAssetsFilenameValue string `json:"JsonTechnicalAssetsFilename,omitempty" yaml:"JsonTechnicalAssetsFilename"` JsonStatsFilenameValue string `json:"JsonStatsFilename,omitempty" yaml:"JsonStatsFilename"` TemplateFilenameValue string `json:"TemplateFilename,omitempty" yaml:"TemplateFilename"` ReportLogoImagePathValue string `json:"ReportLogoImagePath,omitempty" yaml:"ReportLogoImagePath"` TechnologyFilenameValue string `json:"TechnologyFilename,omitempty" yaml:"TechnologyFilename"` HideEmptyChaptersValue bool `json:"HideEmptyChapters,omitempty" yaml:"HideEmptyChapters"` RiskRulePluginsValue []string `json:"RiskRulePlugins,omitempty" yaml:"RiskRulePlugins"` SkipRiskRulesValue []string `json:"SkipRiskRules,omitempty" yaml:"SkipRiskRules"` ExecuteModelMacroValue string `json:"ExecuteModelMacro,omitempty" yaml:"ExecuteModelMacro"` RiskExcelValue RiskExcelConfig `json:"RiskExcel" yaml:"RiskExcel"` ServerModeValue bool `json:"ServerMode,omitempty" yaml:"ServerMode"` ServerPortValue int `json:"ServerPort,omitempty" yaml:"ServerPort"` DiagramDPIValue int `json:"DiagramDPI,omitempty" yaml:"DiagramDPI"` GraphvizDPIValue int `json:"GraphvizDPI,omitempty" yaml:"GraphvizDPI"` MaxGraphvizDPIValue int `json:"MaxGraphvizDPI,omitempty" yaml:"MaxGraphvizDPI"` BackupHistoryFilesToKeepValue int `json:"BackupHistoryFilesToKeep,omitempty" yaml:"BackupHistoryFilesToKeep"` AddModelTitleValue bool `json:"AddModelTitle,omitempty" yaml:"AddModelTitle"` AddLegendValue bool `json:"AddLegend,omitempty" yaml:"AddLegend"` KeepDiagramSourceFilesValue bool `json:"KeepDiagramSourceFiles,omitempty" yaml:"KeepDiagramSourceFiles"` IgnoreOrphanedRiskTrackingValue bool `json:"IgnoreOrphanedRiskTracking,omitempty" yaml:"IgnoreOrphanedRiskTracking"` SkipDataFlowDiagramValue bool `json:"SkipDataFlowDiagram,omitempty" yaml:"SkipDataFlowDiagram"` SkipDataAssetDiagramValue bool `json:"SkipDataAssetDiagram,omitempty" yaml:"SkipDataAssetDiagram"` SkipRisksJSONValue bool `json:"SkipRisksJSON,omitempty" yaml:"SkipRisksJSON"` SkipTechnicalAssetsJSONValue bool `json:"SkipTechnicalAssetsJSON,omitempty" yaml:"SkipTechnicalAssetsJSON"` SkipStatsJSONValue bool `json:"SkipStatsJSON,omitempty" yaml:"SkipStatsJSON"` SkipRisksExcelValue bool `json:"SkipRisksExcel,omitempty" yaml:"SkipRisksExcel"` SkipTagsExcelValue bool `json:"SkipTagsExcel,omitempty" yaml:"SkipTagsExcel"` SkipReportPDFValue bool `json:"SkipReportPDF,omitempty" yaml:"SkipReportPDF"` SkipReportADOCValue bool `json:"SkipReportADOC,omitempty" yaml:"SkipReportADOC"` AttractivenessValue Attractiveness `json:"Attractiveness" yaml:"Attractiveness"` ReportConfigurationValue report.ReportConfiguation `json:"ReportConfiguration" yaml:"ReportConfiguration"` } type ConfigGetter interface { GetBuildTimestamp() string GetVerbose() bool GetInteractive() bool GetAppFolder() string GetPluginFolder() string GetDataFolder() string GetOutputFolder() string GetServerFolder() string GetTempFolder() string GetKeyFolder() string GetTechnologyFilename() string GetInputFile() string GetDataFlowDiagramFilenamePNG() string GetDataAssetDiagramFilenamePNG() string GetDataFlowDiagramFilenameDOT() string GetDataAssetDiagramFilenameDOT() string GetReportFilename() string GetExcelRisksFilename() string GetExcelTagsFilename() string GetJsonRisksFilename() string GetJsonTechnicalAssetsFilename() string GetJsonStatsFilename() string GetReportLogoImagePath() string GetTemplateFilename() string GetRiskRulePlugins() []string GetSkipRiskRules() []string GetExecuteModelMacro() string GetRiskExcelConfigHideColumns() []string GetRiskExcelConfigSortByColumns() []string GetRiskExcelConfigWidthOfColumns() map[string]float64 GetRiskExcelWrapText() bool GetRiskExcelShrinkColumnsToFit() bool GetRiskExcelColorText() bool GetServerMode() bool GetServerPort() int GetDiagramDPI() int GetGraphvizDPI() int GetMinGraphvizDPI() int GetMaxGraphvizDPI() int GetBackupHistoryFilesToKeep() int GetAddModelTitle() bool GetAddLegend() bool GetKeepDiagramSourceFiles() bool GetIgnoreOrphanedRiskTracking() bool GetSkipDataFlowDiagram() bool GetSkipDataAssetDiagram() bool GetSkipRisksJSON() bool GetSkipTechnicalAssetsJSON() bool GetSkipStatsJSON() bool GetSkipRisksExcel() bool GetSkipTagsExcel() bool GetSkipReportPDF() bool GetSkipReportADOC() bool GetAttractiveness() Attractiveness GetReportConfiguration() report.ReportConfiguation GetThreagileVersion() string GetProgressReporter() types.ProgressReporter GetReportConfigurationHideChapters() map[report.ChaptersToShowHide]bool } type ConfigSetter interface { SetVerbose(verbose bool) SetInteractive(interactive bool) SetAppFolder(appFolder string) SetPluginFolder(pluginFolder string) SetOutputFolder(outputFolder string) SetServerFolder(serverFolder string) SetTempFolder(tempFolder string) SetInputFile(inputFile string) SetTemplateFilename(templateFilename string) SetRiskRulePlugins(riskRulePlugins []string) SetSkipRiskRules(skipRiskRules []string) SetServerMode(serverMode bool) SetServerPort(serverPort int) SetDiagramDPI(diagramDPI int) SetIgnoreOrphanedRiskTracking(ignoreOrphanedRiskTracking bool) } func (c *Config) Defaults(buildTimestamp string) *Config { *c = Config{ BuildTimestampValue: buildTimestamp, VerboseValue: false, InteractiveValue: false, AppFolderValue: AppDir, PluginFolderValue: PluginDir, DataFolderValue: DataDir, OutputFolderValue: OutputDir, ServerFolderValue: ServerDir, TempFolderValue: TempDir, KeyFolderValue: KeyDir, InputFileValue: InputFile, DataFlowDiagramFilenamePNGValue: DataFlowDiagramFilenamePNG, DataAssetDiagramFilenamePNGValue: DataAssetDiagramFilenamePNG, DataFlowDiagramFilenameDOTValue: DataFlowDiagramFilenameDOT, DataAssetDiagramFilenameDOTValue: DataAssetDiagramFilenameDOT, ReportFilenameValue: ReportFilename, ExcelRisksFilenameValue: ExcelRisksFilename, ExcelTagsFilenameValue: ExcelTagsFilename, JsonRisksFilenameValue: JsonRisksFilename, JsonTechnicalAssetsFilenameValue: JsonTechnicalAssetsFilename, JsonStatsFilenameValue: JsonStatsFilename, TemplateFilenameValue: TemplateFilename, ReportLogoImagePathValue: ReportLogoImagePath, TechnologyFilenameValue: "", HideEmptyChaptersValue: false, RiskRulePluginsValue: make([]string, 0), SkipRiskRulesValue: make([]string, 0), ExecuteModelMacroValue: "", RiskExcelValue: RiskExcelConfig{ HideColumns: make([]string, 0), SortByColumns: make([]string, 0), WidthOfColumns: make(map[string]float64), ShrinkColumnsToFit: true, WrapText: false, ColorText: true, }, ServerModeValue: false, DiagramDPIValue: DefaultDiagramDPI, ServerPortValue: DefaultServerPort, GraphvizDPIValue: DefaultGraphvizDPI, MaxGraphvizDPIValue: MaxGraphvizDPI, BackupHistoryFilesToKeepValue: DefaultBackupHistoryFilesToKeep, AddModelTitleValue: false, AddLegendValue: false, KeepDiagramSourceFilesValue: false, IgnoreOrphanedRiskTrackingValue: false, AttractivenessValue: Attractiveness{ Quantity: 0, Confidentiality: AttackerFocus{ Asset: 0, ProcessedOrStoredData: 0, TransferredData: 0, }, Integrity: AttackerFocus{ Asset: 0, ProcessedOrStoredData: 0, TransferredData: 0, }, Availability: AttackerFocus{ Asset: 0, ProcessedOrStoredData: 0, TransferredData: 0, }, }, ReportConfigurationValue: report.ReportConfiguation{ HideChapter: make(map[report.ChaptersToShowHide]bool), }, } return c } func (c *Config) Load(configFilename string) error { if len(configFilename) == 0 { return nil } data, readError := os.ReadFile(filepath.Clean(configFilename)) if readError != nil { return readError } values := make(map[string]any) var config Config if strings.HasSuffix(configFilename, ".yaml") { parseError := yaml.Unmarshal(data, &values) if parseError != nil { return fmt.Errorf("failed to parse keys of yaml config file %q: %w", configFilename, parseError) } unmarshalError := yaml.Unmarshal(data, &config) if unmarshalError != nil { return fmt.Errorf("failed to parse yaml config file %q: %w", configFilename, unmarshalError) } } else { parseError := json.Unmarshal(data, &values) if parseError != nil { return fmt.Errorf("failed to parse keys of json config file %q: %w", configFilename, parseError) } unmarshalError := json.Unmarshal(data, &config) if unmarshalError != nil { return fmt.Errorf("failed to parse json config file %q: %w", configFilename, unmarshalError) } } c.Merge(config, values) errorList := make([]error, 0) c.TempFolderValue = c.CleanPath(c.TempFolderValue) tempDirError := os.MkdirAll(c.TempFolderValue, 0700) if tempDirError != nil { errorList = append(errorList, fmt.Errorf("failed to create temp dir %q: %w", c.TempFolderValue, tempDirError)) } c.OutputFolderValue = c.CleanPath(c.OutputFolderValue) outDirError := os.MkdirAll(c.OutputFolderValue, 0700) if outDirError != nil { errorList = append(errorList, fmt.Errorf("failed to create output dir %q: %w", c.OutputFolderValue, outDirError)) } c.AppFolderValue = c.CleanPath(c.AppFolderValue) appDirError := c.checkDir(c.AppFolderValue, "app") if appDirError != nil { errorList = append(errorList, appDirError) } c.PluginFolderValue = c.CleanPath(c.PluginFolderValue) pluginDirError := c.checkDir(c.PluginFolderValue, "plugin") if pluginDirError != nil { errorList = append(errorList, pluginDirError) } c.DataFolderValue = c.CleanPath(c.DataFolderValue) dataDirError := c.checkDir(c.DataFolderValue, "data") if dataDirError != nil { errorList = append(errorList, dataDirError) } if c.TechnologyFilenameValue != "" { c.TechnologyFilenameValue = c.CleanPath(c.TechnologyFilenameValue) } serverFolderError := c.CheckServerFolder() if serverFolderError != nil { errorList = append(errorList, serverFolderError) } if len(errorList) > 0 { return errors.Join(errorList...) } return nil } func (c *Config) CheckServerFolder() error { if c.ServerModeValue { c.ServerFolderValue = c.CleanPath(c.ServerFolderValue) serverDirError := c.checkDir(c.ServerFolderValue, "server") if serverDirError != nil { return serverDirError } keyDirError := os.MkdirAll(filepath.Join(c.ServerFolderValue, c.KeyFolderValue), 0700) if keyDirError != nil { return fmt.Errorf("failed to create key dir %q: %w", filepath.Join(c.ServerFolderValue, c.KeyFolderValue), keyDirError) } } return nil } func (c *Config) Merge(config Config, values map[string]any) { for key := range values { switch strings.ToLower(key) { case strings.ToLower("BuildTimestamp"): c.BuildTimestampValue = config.BuildTimestampValue case strings.ToLower("Verbose"): c.VerboseValue = config.VerboseValue case strings.ToLower("Interactive"): c.InteractiveValue = config.InteractiveValue case strings.ToLower("AppFolder"): c.AppFolderValue = config.AppFolderValue case strings.ToLower("PluginFolder"): c.PluginFolderValue = config.PluginFolderValue case strings.ToLower("DataFolder"): c.DataFolderValue = config.DataFolderValue case strings.ToLower("OutputFolder"): c.OutputFolderValue = config.OutputFolderValue case strings.ToLower("ServerFolder"): c.ServerFolderValue = config.ServerFolderValue case strings.ToLower("TempFolder"): c.TempFolderValue = config.TempFolderValue case strings.ToLower("KeyFolder"): c.KeyFolderValue = config.KeyFolderValue case strings.ToLower("InputFile"): c.InputFileValue = config.InputFileValue case strings.ToLower("ImportedInputFile"): c.ImportedInputFileValue = config.ImportedInputFileValue case strings.ToLower("DataFlowDiagramFilenamePNG"): c.DataFlowDiagramFilenamePNGValue = config.DataFlowDiagramFilenamePNGValue case strings.ToLower("DataAssetDiagramFilenamePNG"): c.DataAssetDiagramFilenamePNGValue = config.DataAssetDiagramFilenamePNGValue case strings.ToLower("DataFlowDiagramFilenameDOT"): c.DataFlowDiagramFilenameDOTValue = config.DataFlowDiagramFilenameDOTValue case strings.ToLower("DataAssetDiagramFilenameDOT"): c.DataAssetDiagramFilenameDOTValue = config.DataAssetDiagramFilenameDOTValue case strings.ToLower("ReportFilename"): c.ReportFilenameValue = config.ReportFilenameValue case strings.ToLower("ExcelRisksFilename"): c.ExcelRisksFilenameValue = config.ExcelRisksFilenameValue case strings.ToLower("ExcelTagsFilename"): c.ExcelTagsFilenameValue = config.ExcelTagsFilenameValue case strings.ToLower("JsonRisksFilename"): c.JsonRisksFilenameValue = config.JsonRisksFilenameValue case strings.ToLower("JsonTechnicalAssetsFilename"): c.JsonTechnicalAssetsFilenameValue = config.JsonTechnicalAssetsFilenameValue case strings.ToLower("JsonStatsFilename"): c.JsonStatsFilenameValue = config.JsonStatsFilenameValue case strings.ToLower("TemplateFilename"): c.TemplateFilenameValue = config.TemplateFilenameValue case strings.ToLower("ReportLogoImagePath"): c.ReportLogoImagePathValue = config.ReportLogoImagePathValue case strings.ToLower("TechnologyFilename"): c.TechnologyFilenameValue = config.TechnologyFilenameValue case strings.ToLower("HideEmptyChapters"): c.HideEmptyChaptersValue = config.HideEmptyChaptersValue case strings.ToLower("RiskRulePlugins"): c.RiskRulePluginsValue = config.RiskRulePluginsValue case strings.ToLower("SkipRiskRules"): c.SkipRiskRulesValue = config.SkipRiskRulesValue case strings.ToLower("ExecuteModelMacro"): c.ExecuteModelMacroValue = config.ExecuteModelMacroValue case strings.ToLower("RiskExcel"): configMap, mapOk := values[key].(map[string]any) if !mapOk { continue } for valueName := range configMap { switch strings.ToLower(valueName) { case strings.ToLower("HideColumns"): c.RiskExcelValue.HideColumns = append(c.RiskExcelValue.HideColumns, config.RiskExcelValue.HideColumns...) case strings.ToLower("SortByColumns"): c.RiskExcelValue.SortByColumns = append(c.RiskExcelValue.SortByColumns, config.RiskExcelValue.SortByColumns...) case strings.ToLower("WidthOfColumns"): if c.RiskExcelValue.WidthOfColumns == nil { c.RiskExcelValue.WidthOfColumns = make(map[string]float64) } for name, value := range config.RiskExcelValue.WidthOfColumns { c.RiskExcelValue.WidthOfColumns[name] = value } case strings.ToLower("ShrinkColumnsToFit"): c.RiskExcelValue.ShrinkColumnsToFit = config.RiskExcelValue.ShrinkColumnsToFit case strings.ToLower("WrapText"): c.RiskExcelValue.WrapText = config.RiskExcelValue.WrapText case strings.ToLower("ColorText"): c.RiskExcelValue.ColorText = config.RiskExcelValue.ColorText } } case strings.ToLower("ServerMode"): c.ServerModeValue = config.ServerModeValue case strings.ToLower("DiagramDPI"): c.DiagramDPIValue = config.DiagramDPIValue case strings.ToLower("ServerPort"): c.ServerPortValue = config.ServerPortValue case strings.ToLower("GraphvizDPI"): c.GraphvizDPIValue = config.GraphvizDPIValue case strings.ToLower("MaxGraphvizDPI"): c.MaxGraphvizDPIValue = config.MaxGraphvizDPIValue case strings.ToLower("BackupHistoryFilesToKeep"): c.BackupHistoryFilesToKeepValue = config.BackupHistoryFilesToKeepValue case strings.ToLower("AddModelTitle"): c.AddModelTitleValue = config.AddModelTitleValue case strings.ToLower("AddLegend"): c.AddLegendValue = config.AddLegendValue case strings.ToLower("KeepDiagramSourceFiles"): c.KeepDiagramSourceFilesValue = config.KeepDiagramSourceFilesValue case strings.ToLower("IgnoreOrphanedRiskTracking"): c.IgnoreOrphanedRiskTrackingValue = config.IgnoreOrphanedRiskTrackingValue case strings.ToLower("Attractiveness"): c.AttractivenessValue = config.AttractivenessValue case strings.ToLower("ReportConfiguration"): configMap, mapOk := values[key].(map[string]any) if !mapOk { continue } for valueName := range configMap { switch strings.ToLower(valueName) { case strings.ToLower("HideChapter"): if c.ReportConfigurationValue.HideChapter == nil { c.ReportConfigurationValue.HideChapter = make(map[report.ChaptersToShowHide]bool) } for chapter, value := range config.ReportConfigurationValue.HideChapter { c.ReportConfigurationValue.HideChapter[chapter] = value if value { log.Println("Hiding chapter: ", chapter) } } } } } } } func (c *Config) CleanPath(path string) string { return filepath.Clean(c.ExpandPath(path)) } func (c *Config) checkDir(dir string, name string) error { dirInfo, dirError := os.Stat(dir) if dirError != nil { return fmt.Errorf("%v folder %q not good: %w", name, dir, dirError) } if !dirInfo.IsDir() { return fmt.Errorf("%v folder %q is not a folder", name, dir) } return nil } func (c *Config) ExpandPath(path string) string { home := c.UserHomeDir() if strings.HasPrefix(path, "~") { path = strings.Replace(path, "~", home, 1) } if strings.HasPrefix(path, "$HOME") { path = strings.ReplaceAll(path, "$HOME", home) } return path } func (c *Config) UserHomeDir() string { switch runtime.GOOS { case "windows": home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") if home == "" { home = os.Getenv("USERPROFILE") } return home default: return os.Getenv("HOME") } } func (c *Config) GetBuildTimestamp() string { return c.BuildTimestampValue } func (c *Config) GetVerbose() bool { return c.VerboseValue } func (c *Config) SetVerbose(verbose bool) { c.VerboseValue = verbose } func (c *Config) GetInteractive() bool { return c.InteractiveValue } func (c *Config) SetInteractive(interactive bool) { c.InteractiveValue = interactive } func (c *Config) GetAppFolder() string { return c.AppFolderValue } func (c *Config) SetAppFolder(appFolder string) { c.AppFolderValue = appFolder } func (c *Config) GetPluginFolder() string { return c.PluginFolderValue } func (c *Config) SetPluginFolder(pluginFolder string) { c.PluginFolderValue = pluginFolder } func (c *Config) GetDataFolder() string { return c.DataFolderValue } func (c *Config) GetOutputFolder() string { return c.OutputFolderValue } func (c *Config) SetOutputFolder(outputFolder string) { c.OutputFolderValue = outputFolder } func (c *Config) GetServerFolder() string { return c.ServerFolderValue } func (c *Config) SetServerFolder(serverFolder string) { c.ServerFolderValue = serverFolder } func (c *Config) GetTempFolder() string { return c.TempFolderValue } func (c *Config) SetTempFolder(tempFolder string) { c.TempFolderValue = tempFolder } func (c *Config) GetKeyFolder() string { return c.KeyFolderValue } func (c *Config) GetTechnologyFilename() string { return c.TechnologyFilenameValue } func (c *Config) GetHideEmptyChapters() bool { return c.HideEmptyChaptersValue } func (c *Config) GetInputFile() string { return c.InputFileValue } func (c *Config) SetInputFile(inputFile string) { c.InputFileValue = inputFile } func (c *Config) GetImportedInputFile() string { return c.ImportedInputFileValue } func (c *Config) SetImportedInputFile(inputFile string) { c.ImportedInputFileValue = inputFile } func (c *Config) GetDataFlowDiagramFilenamePNG() string { return c.DataFlowDiagramFilenamePNGValue } func (c *Config) GetDataAssetDiagramFilenamePNG() string { return c.DataAssetDiagramFilenamePNGValue } func (c *Config) GetDataFlowDiagramFilenameDOT() string { return c.DataFlowDiagramFilenameDOTValue } func (c *Config) GetDataAssetDiagramFilenameDOT() string { return c.DataAssetDiagramFilenameDOTValue } func (c *Config) GetReportFilename() string { return c.ReportFilenameValue } func (c *Config) GetExcelRisksFilename() string { return c.ExcelRisksFilenameValue } func (c *Config) GetExcelTagsFilename() string { return c.ExcelTagsFilenameValue } func (c *Config) GetJsonRisksFilename() string { return c.JsonRisksFilenameValue } func (c *Config) GetJsonTechnicalAssetsFilename() string { return c.JsonTechnicalAssetsFilenameValue } func (c *Config) GetJsonStatsFilename() string { return c.JsonStatsFilenameValue } func (c *Config) GetReportLogoImagePath() string { return c.ReportLogoImagePathValue } func (c *Config) GetTemplateFilename() string { return c.TemplateFilenameValue } func (c *Config) SetTemplateFilename(templateFilename string) { c.TemplateFilenameValue = templateFilename } func (c *Config) GetRiskRulePlugins() []string { return c.RiskRulePluginsValue } func (c *Config) SetRiskRulePlugins(riskRulePlugins []string) { c.RiskRulePluginsValue = riskRulePlugins } func (c *Config) GetSkipRiskRules() []string { return c.SkipRiskRulesValue } func (c *Config) SetSkipRiskRules(skipRiskRules []string) { c.SkipRiskRulesValue = skipRiskRules } func (c *Config) GetExecuteModelMacro() string { return c.ExecuteModelMacroValue } func (c *Config) GetRiskExcelConfigHideColumns() []string { return c.RiskExcelValue.HideColumns } func (c *Config) GetRiskExcelConfigSortByColumns() []string { return c.RiskExcelValue.SortByColumns } func (c *Config) GetRiskExcelConfigWidthOfColumns() map[string]float64 { return c.RiskExcelValue.WidthOfColumns } func (c *Config) GetRiskExcelWrapText() bool { return c.RiskExcelValue.WrapText } func (c *Config) GetRiskExcelShrinkColumnsToFit() bool { return c.RiskExcelValue.ShrinkColumnsToFit } func (c *Config) GetRiskExcelColorText() bool { return c.RiskExcelValue.ColorText } func (c *Config) GetServerMode() bool { return c.ServerModeValue } func (c *Config) SetServerMode(serverMode bool) { c.ServerModeValue = serverMode } func (c *Config) GetServerPort() int { return c.ServerPortValue } func (c *Config) SetServerPort(serverPort int) { c.ServerPortValue = serverPort } func (c *Config) GetDiagramDPI() int { return c.DiagramDPIValue } func (c *Config) SetDiagramDPI(diagramDPI int) { c.DiagramDPIValue = diagramDPI } func (c *Config) GetGraphvizDPI() int { return c.GraphvizDPIValue } func (c *Config) GetMinGraphvizDPI() int { return MinGraphvizDPI } func (c *Config) GetMaxGraphvizDPI() int { return c.MaxGraphvizDPIValue } func (c *Config) GetBackupHistoryFilesToKeep() int { return c.BackupHistoryFilesToKeepValue } func (c *Config) GetAddModelTitle() bool { return c.AddModelTitleValue } func (c *Config) GetAddLegend() bool { return c.AddLegendValue } func (c *Config) GetKeepDiagramSourceFiles() bool { return c.KeepDiagramSourceFilesValue } func (c *Config) GetIgnoreOrphanedRiskTracking() bool { return c.IgnoreOrphanedRiskTrackingValue } func (c *Config) SetIgnoreOrphanedRiskTracking(ignoreOrphanedRiskTracking bool) { c.IgnoreOrphanedRiskTrackingValue = ignoreOrphanedRiskTracking } func (c *Config) GetSkipDataFlowDiagram() bool { return c.SkipDataFlowDiagramValue } func (c *Config) GetSkipDataAssetDiagram() bool { return c.SkipDataAssetDiagramValue } func (c *Config) GetSkipRisksJSON() bool { return c.SkipRisksJSONValue } func (c *Config) GetSkipTechnicalAssetsJSON() bool { return c.SkipTechnicalAssetsJSONValue } func (c *Config) GetSkipStatsJSON() bool { return c.SkipStatsJSONValue } func (c *Config) GetSkipRisksExcel() bool { return c.SkipRisksExcelValue } func (c *Config) GetSkipTagsExcel() bool { return c.SkipTagsExcelValue } func (c *Config) GetSkipReportPDF() bool { return c.SkipReportPDFValue } func (c *Config) GetSkipReportADOC() bool { return c.SkipReportADOCValue } func (c *Config) GetAttractiveness() Attractiveness { return c.AttractivenessValue } func (c *Config) GetReportConfiguration() report.ReportConfiguation { return c.ReportConfigurationValue } func (c *Config) GetThreagileVersion() string { return ThreagileVersion } func (c *Config) GetProgressReporter() types.ProgressReporter { return DefaultProgressReporter{Verbose: c.VerboseValue} } func (c *Config) GetReportConfigurationHideChapters() map[report.ChaptersToShowHide]bool { return c.ReportConfigurationValue.HideChapter }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/attacker-focus.go
internal/threagile/attacker-focus.go
package threagile type AttackerFocus struct { Asset int // fibonacci sequence base index ProcessedOrStoredData int // fibonacci sequence base index TransferredData int // fibonacci sequence base index }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/list.go
internal/threagile/list.go
package threagile import ( "fmt" "github.com/spf13/cobra" "github.com/threagile/threagile/pkg/macros" "github.com/threagile/threagile/pkg/model" "github.com/threagile/threagile/pkg/risks" "github.com/threagile/threagile/pkg/types" ) func (what *Threagile) initList() *Threagile { what.rootCmd.AddCommand(&cobra.Command{ Use: ListRiskRulesCommand, Short: "Print available risk rules", RunE: func(cmd *cobra.Command, args []string) error { what.processArgs(cmd, args) cmd.Println(Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp)) cmd.Println("The following risk rules are available (can be extended via custom risk rules):") cmd.Println() cmd.Println("----------------------") cmd.Println("Custom risk rules:") cmd.Println("----------------------") customRiskRules := model.LoadCustomRiskRules(what.config.GetPluginFolder(), what.config.GetRiskRulePlugins(), DefaultProgressReporter{Verbose: what.config.GetVerbose()}) for id, customRule := range customRiskRules { cmd.Println(id, "-->", customRule.Category().Title, "--> with tags:", customRule.SupportedTags()) } cmd.Println() cmd.Println("--------------------") cmd.Println("Built-in risk rules:") cmd.Println("--------------------") cmd.Println() for _, rule := range risks.GetBuiltInRiskRules() { cmd.Println(rule.Category().ID, "-->", rule.Category().Title, "--> with tags:", rule.SupportedTags()) } return nil }, }) what.rootCmd.AddCommand(&cobra.Command{ Use: ListModelMacrosCommand, Short: "Print model macros", Run: func(cmd *cobra.Command, args []string) { what.processArgs(cmd, args) cmd.Println(Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp)) cmd.Println("The following model macros are available (can be extended via custom model macros):") cmd.Println() /* TODO finish plugin stuff cmd.Println("Custom model macros:") for _, macros := range macros.ListCustomMacros() { details := macros.GetMacroDetails() cmd.Println(details.ID, "-->", details.Title) } cmd.Println() */ cmd.Println("----------------------") cmd.Println("Built-in model macros:") cmd.Println("----------------------") for _, macroList := range macros.ListBuiltInMacros() { details := macroList.GetMacroDetails() cmd.Println(details.ID, "-->", details.Title) } cmd.Println() }, }) what.rootCmd.AddCommand(&cobra.Command{ Use: ListTypesCommand, Short: "Print type information (enum values to be used in models)", Run: func(cmd *cobra.Command, args []string) { what.processArgs(cmd, args) cmd.Println(Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp)) cmd.Println() cmd.Println() cmd.Println("The following types are available (can be extended for custom rules):") cmd.Println() for name, values := range types.GetBuiltinTypeValues(what.config) { cmd.Println(fmt.Sprintf(" %v: %v", name, values)) } }, }) return what }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/progress-reporter.go
internal/threagile/progress-reporter.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package threagile import ( "fmt" "log" ) type DefaultProgressReporter struct { Verbose bool SuppressError bool } func (r DefaultProgressReporter) Info(a ...any) { if r.Verbose { fmt.Println(a...) } } func (DefaultProgressReporter) Warn(a ...any) { fmt.Println(a...) } func (r DefaultProgressReporter) Error(v ...any) { if r.SuppressError { r.Warn(v...) return } log.Fatal(v...) } func (r DefaultProgressReporter) Infof(format string, a ...any) { if r.Verbose { fmt.Printf(format, a...) fmt.Println() } } func (DefaultProgressReporter) Warnf(format string, a ...any) { fmt.Print("WARNING: ") fmt.Printf(format, a...) fmt.Println() } func (r DefaultProgressReporter) Errorf(format string, v ...any) { if r.SuppressError { r.Warnf(format, v...) return } log.Fatalf(format, v...) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/threagile.go
internal/threagile/threagile.go
package threagile import ( "os" "github.com/spf13/cobra" ) type Threagile struct { flags Flags config *Config rootCmd *cobra.Command buildTimestamp string } func (what *Threagile) Execute() { err := what.rootCmd.Execute() if err != nil { what.rootCmd.Println(err) os.Exit(1) } if what.config.GetServerMode() { serverError := what.runServer() what.rootCmd.Println(serverError) } else if what.config.GetInteractive() { what.run(what.rootCmd, nil) } } func (what *Threagile) Init(buildTimestamp string) *Threagile { what.buildTimestamp = buildTimestamp return what.initRoot().initImport().initAnalyze().initCreate().initExecute().initExplain().initList().initPrint().initQuit().initServer().initVersion().processSystemArgs(what.rootCmd) }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/internal/threagile/root.go
internal/threagile/root.go
/* Copyright © 2023 NAME HERE <EMAIL ADDRESS> */ package threagile import ( "errors" "fmt" "os" "path/filepath" "strings" "github.com/chzyer/readline" "github.com/mattn/go-shellwords" "github.com/spf13/cobra" "github.com/threagile/threagile/pkg/report" ) const ( UsageTemplate = `Usage:{{if .Runnable}} {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} Aliases: {{.NameAndAliases}}{{end}}{{if .HasExample}} Examples: {{.Example}}{{end}}{{if .HasAvailableSubCommands}} Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Title "help"))}} {{rpad .Title .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasHelpSubCommands}} Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}} ` ) func (what *Threagile) initRoot() *Threagile { what.rootCmd = &cobra.Command{ Use: "threagile", Version: ThreagileVersion, Short: "\n" + Logo, Long: "\n" + Logo + "\n\n" + fmt.Sprintf(VersionText, what.buildTimestamp) + "\n\n" + Examples, SilenceErrors: true, SilenceUsage: true, Run: what.run, CompletionOptions: cobra.CompletionOptions{ DisableDefaultCmd: true, }, } what.config = new(Config).Defaults(what.buildTimestamp) return what.initFlags() } func (what *Threagile) initFlags() *Threagile { what.rootCmd.ResetFlags() what.rootCmd.PersistentFlags().StringVar(&what.flags.configFlag, configFlagName, "", "config file") what.rootCmd.PersistentFlags().BoolVarP(&what.flags.VerboseValue, verboseFlagName, verboseFlagShorthand, what.config.GetVerbose(), "Verbose output") what.rootCmd.PersistentFlags().BoolVarP(&what.flags.InteractiveValue, interactiveFlagName, interactiveFlagShorthand, what.config.GetInteractive(), "interactive mode") what.rootCmd.PersistentFlags().StringVar(&what.flags.AppFolderValue, appDirFlagName, what.config.GetAppFolder(), "app folder") what.rootCmd.PersistentFlags().StringVar(&what.flags.PluginFolderValue, pluginDirFlagName, what.config.GetPluginFolder(), "plugin directory") what.rootCmd.PersistentFlags().StringVar(&what.flags.DataFolderValue, dataDirFlagName, what.config.GetDataFolder(), "data directory") what.rootCmd.PersistentFlags().StringVar(&what.flags.OutputFolderValue, outputFlagName, what.config.GetOutputFolder(), "output directory") what.rootCmd.PersistentFlags().StringVar(&what.flags.TempFolderValue, tempDirFlagName, what.config.GetTempFolder(), "temporary folder location") what.rootCmd.PersistentFlags().StringVar(&what.flags.KeyFolderValue, keyDirFlagName, what.config.GetKeyFolder(), "key folder location") what.rootCmd.PersistentFlags().StringVar(&what.flags.InputFileValue, inputFileFlagName, what.config.GetInputFile(), "input model yaml file") what.rootCmd.PersistentFlags().StringVar(&what.flags.ImportedInputFileValue, importedFileFlagName, what.config.GetImportedInputFile(), "imported input model yaml file") what.rootCmd.PersistentFlags().StringVar(&what.flags.DataFlowDiagramFilenamePNGValue, dataFlowDiagramPNGFileFlagName, what.config.GetDataFlowDiagramFilenamePNG(), "data flow diagram PNG file") what.rootCmd.PersistentFlags().StringVar(&what.flags.DataAssetDiagramFilenamePNGValue, dataAssetDiagramPNGFileFlagName, what.config.GetDataAssetDiagramFilenamePNG(), "data asset diagram PNG file") what.rootCmd.PersistentFlags().StringVar(&what.flags.DataFlowDiagramFilenameDOTValue, dataFlowDiagramDOTFileFlagName, what.config.GetDataFlowDiagramFilenameDOT(), "data flow diagram DOT file") what.rootCmd.PersistentFlags().StringVar(&what.flags.DataAssetDiagramFilenameDOTValue, dataAssetDiagramDOTFileFlagName, what.config.GetDataAssetDiagramFilenameDOT(), "data asset diagram DOT file") what.rootCmd.PersistentFlags().StringVar(&what.flags.ReportFilenameValue, reportFileFlagName, what.config.GetReportFilename(), "report file") what.rootCmd.PersistentFlags().StringVar(&what.flags.ExcelRisksFilenameValue, risksExcelFileFlagName, what.config.GetExcelRisksFilename(), "risks Excel file") what.rootCmd.PersistentFlags().StringVar(&what.flags.ExcelTagsFilenameValue, tagsExcelFileFlagName, what.config.GetExcelTagsFilename(), "tags Excel file") what.rootCmd.PersistentFlags().StringVar(&what.flags.JsonRisksFilenameValue, risksJsonFileFlagName, what.config.GetJsonRisksFilename(), "risks JSON file") what.rootCmd.PersistentFlags().StringVar(&what.flags.JsonTechnicalAssetsFilenameValue, technicalAssetsJsonFileFlagName, what.config.GetJsonTechnicalAssetsFilename(), "technical assets JSON file") what.rootCmd.PersistentFlags().StringVar(&what.flags.JsonStatsFilenameValue, statsJsonFileFlagName, what.config.GetJsonStatsFilename(), "stats JSON file") what.rootCmd.PersistentFlags().StringVar(&what.flags.TemplateFilenameValue, templateFileNameFlagName, what.config.GetTemplateFilename(), "template pdf file") what.rootCmd.PersistentFlags().StringVar(&what.flags.ReportLogoImagePathValue, reportLogoImagePathFlagName, what.config.GetReportLogoImagePath(), "report logo image") what.rootCmd.PersistentFlags().StringVar(&what.flags.TechnologyFilenameValue, technologyFileFlagName, what.config.GetTechnologyFilename(), "file name of additional technologies") what.rootCmd.PersistentFlags().StringVar(&what.flags.riskRulePluginsValue, customRiskRulesPluginFlagName, strings.Join(what.config.GetRiskRulePlugins(), ","), "comma-separated list of plugins file names with custom risk rules to load") what.rootCmd.PersistentFlags().StringVar(&what.flags.skipRiskRulesValue, skipRiskRulesFlagName, strings.Join(what.config.GetSkipRiskRules(), ","), "comma-separated list of risk rules (by their ID) to skip") what.rootCmd.PersistentFlags().StringVar(&what.flags.ExecuteModelMacroValue, executeModelMacroFlagName, what.config.GetExecuteModelMacro(), "macro to execute") // RiskExcelValue not available as flags what.rootCmd.PersistentFlags().IntVar(&what.flags.ServerPortValue, serverPortFlagName, what.config.GetServerPort(), "server port") what.rootCmd.PersistentFlags().StringVar(&what.flags.ServerFolderValue, serverDirFlagName, what.config.GetDataFolder(), "base folder for server mode (default: "+DataDir+")") what.rootCmd.PersistentFlags().IntVar(&what.flags.DiagramDPIValue, diagramDpiFlagName, what.config.GetDiagramDPI(), "DPI used to render: maximum is "+fmt.Sprintf("%d", what.config.GetMaxGraphvizDPI())+"") // MaxGraphvizDPIValue not available as flags what.rootCmd.PersistentFlags().IntVar(&what.flags.BackupHistoryFilesToKeepValue, backupHistoryFilesToKeepFlagName, what.config.GetBackupHistoryFilesToKeep(), "number of backup history files to keep") what.rootCmd.PersistentFlags().BoolVar(&what.flags.AddModelTitleValue, addModelTitleFlagName, what.config.GetAddModelTitle(), "add model title") what.rootCmd.PersistentFlags().BoolVar(&what.flags.KeepDiagramSourceFilesValue, keepDiagramSourceFilesFlagName, what.config.GetKeepDiagramSourceFiles(), "keep diagram source files") what.rootCmd.PersistentFlags().BoolVar(&what.flags.IgnoreOrphanedRiskTrackingValue, ignoreOrphanedRiskTrackingFlagName, what.config.GetIgnoreOrphanedRiskTracking(), "ignore orphaned risk tracking (just log them) not matching a concrete risk") what.rootCmd.PersistentFlags().BoolVar(&what.flags.SkipDataFlowDiagramValue, skipDataFlowDiagramFlagName, what.config.GetSkipDataFlowDiagram(), "skip generating data flow diagram") what.rootCmd.PersistentFlags().BoolVar(&what.flags.SkipDataAssetDiagramValue, skipDataAssetDiagramFlagName, what.config.GetSkipDataAssetDiagram(), "skip generating data asset diagram") what.rootCmd.PersistentFlags().BoolVar(&what.flags.SkipRisksJSONValue, skipRisksJSONFlagName, what.config.GetSkipRisksJSON(), "skip generating risks json") what.rootCmd.PersistentFlags().BoolVar(&what.flags.SkipTechnicalAssetsJSONValue, skipTechnicalAssetsJSONFlagName, what.config.GetSkipTechnicalAssetsJSON(), "skip generating technical assets json") what.rootCmd.PersistentFlags().BoolVar(&what.flags.SkipStatsJSONValue, skipStatsJSONFlagName, what.config.GetSkipStatsJSON(), "skip generating stats json") what.rootCmd.PersistentFlags().BoolVar(&what.flags.SkipRisksExcelValue, skipRisksExcelFlagName, what.config.GetSkipRisksExcel(), "skip generating risks excel") what.rootCmd.PersistentFlags().BoolVar(&what.flags.SkipTagsExcelValue, skipTagsExcelFlagName, what.config.GetSkipTagsExcel(), "skip generating tags excel") what.rootCmd.PersistentFlags().BoolVar(&what.flags.SkipReportPDFValue, skipReportPDFFlagName, what.config.GetSkipReportPDF(), "skip generating report pdf, including diagrams") what.rootCmd.PersistentFlags().BoolVar(&what.flags.SkipReportADOCValue, skipReportADOCFlagName, what.config.GetSkipReportADOC(), "skip generating report adoc, including diagrams") what.rootCmd.PersistentFlags().BoolVar(&what.flags.generateDataFlowDiagramFlag, generateDataFlowDiagramFlagName, !what.config.GetSkipDataFlowDiagram(), "(deprecated) generate generating data flow diagram") what.rootCmd.PersistentFlags().BoolVar(&what.flags.generateDataAssetDiagramFlag, generateDataAssetDiagramFlagName, !what.config.GetSkipDataAssetDiagram(), "(deprecated) generate generating data asset diagram") what.rootCmd.PersistentFlags().BoolVar(&what.flags.generateRisksJSONFlag, generateRisksJSONFlagName, !what.config.GetSkipRisksJSON(), "(deprecated) generate generating risks json") what.rootCmd.PersistentFlags().BoolVar(&what.flags.generateTechnicalAssetsJSONFlag, generateTechnicalAssetsJSONFlagName, !what.config.GetSkipTechnicalAssetsJSON(), "(deprecated) generate generating technical assets json") what.rootCmd.PersistentFlags().BoolVar(&what.flags.generateStatsJSONFlag, generateStatsJSONFlagName, !what.config.GetSkipStatsJSON(), "(deprecated) generate generating stats json") what.rootCmd.PersistentFlags().BoolVar(&what.flags.generateRisksExcelFlag, generateRisksExcelFlagName, !what.config.GetSkipRisksExcel(), "(deprecated) generate generating risks excel") what.rootCmd.PersistentFlags().BoolVar(&what.flags.generateTagsExcelFlag, generateTagsExcelFlagName, !what.config.GetSkipTagsExcel(), "(deprecated) generate generating tags excel") what.rootCmd.PersistentFlags().BoolVar(&what.flags.generateReportPDFFlag, generateReportPDFFlagName, !what.config.GetSkipReportPDF(), "(deprecated) generate generating report pdf, including diagrams") what.rootCmd.PersistentFlags().BoolVar(&what.flags.generateReportADOCFlag, generateReportADOCFlagName, !what.config.GetSkipReportADOC(), "(deprecated) generate generating report adoc, including diagrams") // AttractivenessValue not available as flags // ReportConfigurationValue not available as flags return what } func (what *Threagile) run(thisCmd *cobra.Command, args []string) { what.processArgs(thisCmd, args) if !what.config.GetInteractive() { what.rootCmd.Println("Please add the --interactive flag to run in interactive mode.") return } completer := readline.NewPrefixCompleter() for _, child := range what.rootCmd.Commands() { what.cobraToReadline(completer, child) } dir, homeError := os.UserHomeDir() if homeError != nil { what.rootCmd.Println("Error, please report bug at https://github.com/Threagile/threagile. Unable to find home directory: " + homeError.Error()) return } shell, readlineError := readline.NewEx(&readline.Config{ Prompt: "\033[31m>>\033[0m ", HistoryFile: filepath.Join(dir, ".threagile_history"), HistoryLimit: 1000, AutoComplete: completer, InterruptPrompt: "^C", EOFPrompt: "quit", HistorySearchFold: true, }) if readlineError != nil { what.rootCmd.Println("Error, please report bug at https://github.com/Threagile/threagile. Unable to initialize readline: " + readlineError.Error()) return } defer func() { _ = shell.Close() }() for { line, readError := shell.Readline() if errors.Is(readError, readline.ErrInterrupt) { return } if readError != nil { what.rootCmd.Println("Error, please report bug at https://github.com/Threagile/threagile. Unable to read line: " + readError.Error()) return } if len(strings.TrimSpace(line)) == 0 { continue } params, parseError := shellwords.Parse(line) if parseError != nil { what.rootCmd.Printf("failed to parse command line: %s", parseError.Error()) continue } cmd, args, findError := what.rootCmd.Find(params) if findError != nil { what.rootCmd.Printf("failed to find command: %s", findError.Error()) continue } if cmd == nil || cmd == what.rootCmd { what.rootCmd.Println("failed to find command") continue } flagsError := cmd.ParseFlags(args) if flagsError != nil { what.rootCmd.Printf("invalid flags: %s", flagsError.Error()) continue } if !cmd.DisableFlagParsing { args = cmd.Flags().Args() } argsError := cmd.ValidateArgs(args) if argsError != nil { _ = cmd.Help() continue } if cmd.Run != nil { cmd.Run(cmd, args) continue } if cmd.RunE != nil { runError := cmd.RunE(cmd, args) if runError != nil { what.rootCmd.Printf("error: %v \n", runError) } continue } _ = cmd.Help() } } func (what *Threagile) cobraToReadline(node readline.PrefixCompleterInterface, cmd *cobra.Command) { cmd.SetUsageTemplate(UsageTemplate) cmd.Use = what.usage(cmd) pcItem := readline.PcItem(cmd.Use) node.SetChildren(append(node.GetChildren(), pcItem)) for _, child := range cmd.Commands() { what.cobraToReadline(pcItem, child) } } func (what *Threagile) usage(cmd *cobra.Command) string { words := make([]string, 0, len(cmd.ArgAliases)+1) words = append(words, cmd.Use) for _, name := range cmd.ArgAliases { words = append(words, "["+name+"]") } return strings.Join(words, " ") } func (what *Threagile) readCommands() *report.GenerateCommands { commands := new(report.GenerateCommands).Defaults() commands.DataFlowDiagram = !what.flags.SkipDataFlowDiagramValue commands.DataAssetDiagram = !what.flags.SkipDataAssetDiagramValue commands.RisksJSON = !what.flags.SkipRisksJSONValue commands.StatsJSON = !what.flags.SkipStatsJSONValue commands.TechnicalAssetsJSON = !what.flags.SkipTechnicalAssetsJSONValue commands.RisksExcel = !what.flags.SkipRisksExcelValue commands.TagsExcel = !what.flags.SkipTagsExcelValue commands.ReportPDF = !what.flags.SkipReportPDFValue commands.ReportADOC = !what.flags.SkipReportADOCValue return commands } func (what *Threagile) processSystemArgs(cmd *cobra.Command) *Threagile { what.config.InteractiveValue = what.processArgs(cmd, os.Args[1:]) return what } func (what *Threagile) processArgs(cmd *cobra.Command, args []string) bool { _ = cmd.PersistentFlags().Parse(args) if what.isFlagOverridden(cmd, configFlagName) { configError := what.config.Load(what.flags.configFlag) if configError != nil { what.rootCmd.Printf("WARNING: failed to load config file %q: %v\n", what.flags.configFlag, configError) } } if what.isFlagOverridden(cmd, verboseFlagName) { what.config.VerboseValue = what.flags.VerboseValue } interactive := what.config.GetInteractive() if what.isFlagOverridden(cmd, interactiveFlagName) { interactive = what.flags.InteractiveValue } if what.isFlagOverridden(cmd, appDirFlagName) { what.config.AppFolderValue = what.config.CleanPath(what.flags.AppFolderValue) } if what.isFlagOverridden(cmd, pluginDirFlagName) { what.config.PluginFolderValue = what.config.CleanPath(what.flags.PluginFolderValue) } if what.isFlagOverridden(cmd, dataDirFlagName) { what.config.DataFolderValue = what.config.CleanPath(what.flags.DataFolderValue) } if what.isFlagOverridden(cmd, outputFlagName) { what.config.OutputFolderValue = what.config.CleanPath(what.flags.OutputFolderValue) } if what.isFlagOverridden(cmd, serverDirFlagName) { what.config.ServerFolderValue = what.config.CleanPath(what.flags.ServerFolderValue) } if what.isFlagOverridden(cmd, tempDirFlagName) { what.config.TempFolderValue = what.config.CleanPath(what.flags.TempFolderValue) } if what.isFlagOverridden(cmd, keyDirFlagName) { what.config.KeyFolderValue = what.config.CleanPath(what.flags.KeyFolderValue) } if what.isFlagOverridden(cmd, importedFileFlagName) { what.config.ImportedInputFileValue = what.config.CleanPath(what.flags.ImportedInputFileValue) } if what.isFlagOverridden(cmd, inputFileFlagName) { what.config.InputFileValue = what.config.CleanPath(what.flags.InputFileValue) } if what.isFlagOverridden(cmd, dataFlowDiagramPNGFileFlagName) { what.config.DataFlowDiagramFilenamePNGValue = what.config.CleanPath(what.flags.DataFlowDiagramFilenamePNGValue) } if what.isFlagOverridden(cmd, dataAssetDiagramPNGFileFlagName) { what.config.DataAssetDiagramFilenamePNGValue = what.config.CleanPath(what.flags.DataAssetDiagramFilenamePNGValue) } if what.isFlagOverridden(cmd, dataFlowDiagramDOTFileFlagName) { what.config.DataFlowDiagramFilenameDOTValue = what.config.CleanPath(what.flags.DataFlowDiagramFilenameDOTValue) } if what.isFlagOverridden(cmd, dataAssetDiagramDOTFileFlagName) { what.config.DataAssetDiagramFilenameDOTValue = what.config.CleanPath(what.flags.DataAssetDiagramFilenameDOTValue) } if what.isFlagOverridden(cmd, reportFileFlagName) { what.config.ReportFilenameValue = what.config.CleanPath(what.flags.ReportFilenameValue) } if what.isFlagOverridden(cmd, risksExcelFileFlagName) { what.config.ExcelRisksFilenameValue = what.config.CleanPath(what.flags.ExcelRisksFilenameValue) } if what.isFlagOverridden(cmd, tagsExcelFileFlagName) { what.config.ExcelTagsFilenameValue = what.config.CleanPath(what.flags.ExcelTagsFilenameValue) } if what.isFlagOverridden(cmd, risksJsonFileFlagName) { what.config.JsonRisksFilenameValue = what.config.CleanPath(what.flags.JsonRisksFilenameValue) } if what.isFlagOverridden(cmd, technicalAssetsJsonFileFlagName) { what.config.JsonTechnicalAssetsFilenameValue = what.config.CleanPath(what.flags.JsonTechnicalAssetsFilenameValue) } if what.isFlagOverridden(cmd, statsJsonFileFlagName) { what.config.JsonStatsFilenameValue = what.config.CleanPath(what.flags.JsonStatsFilenameValue) } if what.isFlagOverridden(cmd, templateFileNameFlagName) { what.config.TemplateFilenameValue = what.flags.TemplateFilenameValue } if what.isFlagOverridden(cmd, reportLogoImagePathFlagName) { what.config.ReportLogoImagePathValue = what.flags.ReportLogoImagePathValue } if what.isFlagOverridden(cmd, technologyFileFlagName) { what.config.TechnologyFilenameValue = what.flags.TechnologyFilenameValue } if what.isFlagOverridden(cmd, customRiskRulesPluginFlagName) { what.config.RiskRulePluginsValue = strings.Split(what.flags.riskRulePluginsValue, ",") } if what.isFlagOverridden(cmd, skipRiskRulesFlagName) { what.config.SkipRiskRulesValue = strings.Split(what.flags.skipRiskRulesValue, ",") } if what.isFlagOverridden(cmd, executeModelMacroFlagName) { what.config.ExecuteModelMacroValue = what.flags.ExecuteModelMacroValue } // RiskExcelValue not available as flags if what.isFlagOverridden(cmd, serverModeFlagName) { what.config.ServerModeValue = what.flags.ServerModeValue } if what.isFlagOverridden(cmd, serverPortFlagName) { what.config.ServerPortValue = what.flags.ServerPortValue } if what.isFlagOverridden(cmd, diagramDpiFlagName) { what.config.DiagramDPIValue = what.flags.DiagramDPIValue } if what.isFlagOverridden(cmd, graphvizDpiFlagName) { what.config.GraphvizDPIValue = what.flags.GraphvizDPIValue } // MaxGraphvizDPIValue not available as flags if what.isFlagOverridden(cmd, backupHistoryFilesToKeepFlagName) { what.config.BackupHistoryFilesToKeepValue = what.flags.BackupHistoryFilesToKeepValue } if what.isFlagOverridden(cmd, addModelTitleFlagName) { what.config.AddModelTitleValue = what.flags.AddModelTitleValue } if what.isFlagOverridden(cmd, keepDiagramSourceFilesFlagName) { what.config.KeepDiagramSourceFilesValue = what.flags.KeepDiagramSourceFilesValue } if what.isFlagOverridden(cmd, ignoreOrphanedRiskTrackingFlagName) { what.config.IgnoreOrphanedRiskTrackingValue = what.flags.IgnoreOrphanedRiskTrackingValue } if what.isFlagOverridden(cmd, skipDataFlowDiagramFlagName) { what.config.SkipDataFlowDiagramValue = what.flags.SkipDataFlowDiagramValue } if what.isFlagOverridden(cmd, skipDataAssetDiagramFlagName) { what.config.SkipDataAssetDiagramValue = what.flags.SkipDataAssetDiagramValue } if what.isFlagOverridden(cmd, skipRisksJSONFlagName) { what.config.SkipRisksJSONValue = what.flags.SkipRisksJSONValue } if what.isFlagOverridden(cmd, skipTechnicalAssetsJSONFlagName) { what.config.SkipTechnicalAssetsJSONValue = what.flags.SkipTechnicalAssetsJSONValue } if what.isFlagOverridden(cmd, skipStatsJSONFlagName) { what.config.SkipStatsJSONValue = what.flags.SkipStatsJSONValue } if what.isFlagOverridden(cmd, skipRisksExcelFlagName) { what.config.SkipRisksExcelValue = what.flags.SkipRisksExcelValue } if what.isFlagOverridden(cmd, skipTagsExcelFlagName) { what.config.SkipTagsExcelValue = what.flags.SkipTagsExcelValue } if what.isFlagOverridden(cmd, skipReportPDFFlagName) { what.config.SkipReportPDFValue = what.flags.SkipReportPDFValue } if what.isFlagOverridden(cmd, skipReportADOCFlagName) { what.config.SkipReportADOCValue = what.flags.SkipReportADOCValue } if what.isFlagOverridden(cmd, generateDataFlowDiagramFlagName) { what.config.SkipDataFlowDiagramValue = !what.flags.generateDataFlowDiagramFlag } if what.isFlagOverridden(cmd, generateDataAssetDiagramFlagName) { what.config.SkipDataAssetDiagramValue = !what.flags.generateDataAssetDiagramFlag } if what.isFlagOverridden(cmd, generateRisksJSONFlagName) { what.config.SkipRisksJSONValue = !what.flags.generateRisksJSONFlag } if what.isFlagOverridden(cmd, generateTechnicalAssetsJSONFlagName) { what.config.SkipTechnicalAssetsJSONValue = !what.flags.generateTechnicalAssetsJSONFlag } if what.isFlagOverridden(cmd, generateStatsJSONFlagName) { what.config.SkipStatsJSONValue = !what.flags.generateStatsJSONFlag } if what.isFlagOverridden(cmd, generateRisksExcelFlagName) { what.config.SkipRisksExcelValue = !what.flags.generateRisksExcelFlag } if what.isFlagOverridden(cmd, generateTagsExcelFlagName) { what.config.SkipTagsExcelValue = !what.flags.generateTagsExcelFlag } if what.isFlagOverridden(cmd, generateReportPDFFlagName) { what.config.SkipReportPDFValue = !what.flags.generateReportPDFFlag } if what.isFlagOverridden(cmd, generateReportADOCFlagName) { what.config.SkipReportADOCValue = !what.flags.generateReportADOCFlag } // AttractivenessValue not available as flags // ReportConfigurationValue not available as flags what.initFlags() return interactive } func (what *Threagile) isFlagOverridden(cmd *cobra.Command, flagName string) bool { if cmd == nil { return false } flag := cmd.PersistentFlags().Lookup(flagName) if flag == nil { return false } return flag.Changed }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/graphviz.go
pkg/report/graphviz.go
package report import ( "fmt" "hash/fnv" "os" "os/exec" "path/filepath" "regexp" "sort" "strconv" "strings" "github.com/threagile/threagile/pkg/types" ) func WriteDataFlowDiagramGraphvizDOT(parsedModel *types.Model, diagramFilenameDOT string, dpi int, addModelTitle bool, addLegend bool, progressReporter progressReporter) (*os.File, error) { progressReporter.Info("Writing data flow diagram input") var dotContent strings.Builder dotContent.WriteString("digraph generatedModel { concentrate=false \n") if addLegend { dotContent.WriteString("subgraph cluster_shape_legend { \n") dotContent.WriteString(" label=\"Shape legend\"; \n") dotContent.WriteString(" color=\"lightgrey\"; \n") dotContent.WriteString(" style=\"dashed\"; \n") dotContent.WriteString(makeLegendNode("external_entity_item", "External Entity", "0", "black", "box", "solid", "filled", "2.0", VeryLightGray, "1", Black)) dotContent.WriteString(makeLegendNode("process_item", "Process", "0", "black", "ellipse", "solid", "filled", "2.0", VeryLightGray, "1", Black)) dotContent.WriteString(makeLegendNode("datastore_item", "Datastore", "0", "black", "cylinder", "solid", "filled", "2.0", VeryLightGray, "1", Black)) dotContent.WriteString(makeLegendNode("used_as_client_item", "Used as client", "0", "black", "octagon", "solid", "filled", "2.0", VeryLightGray, "1", Black)) dotContent.WriteString("} \n") dotContent.WriteString("subgraph cluster_tenant_legend { \n") dotContent.WriteString(" label=\"Tenant legend\"; \n") dotContent.WriteString(" color=\"lightgrey\"; \n") dotContent.WriteString(" style=\"dashed\"; \n") dotContent.WriteString(makeLegendNode("single_tenant", "Single tenant", "0", "black", "box", "solid", "filled", "2.0", VeryLightGray, "1", Black)) dotContent.WriteString(makeLegendNode("multi_tenant", "Multitenant", "1", "black", "box", "solid", "filled", "2.0", VeryLightGray, "1", Black)) dotContent.WriteString("} \n") dotContent.WriteString("subgraph cluster_label_legend { \n") dotContent.WriteString(" label=\"Label color legend\"; \n") dotContent.WriteString(" color=\"lightgrey\"; \n") dotContent.WriteString(" style=\"dashed\"; \n") dotContent.WriteString(makeLegendNode("mission_critical", "Mission Critical Asset", "0", Red, "box", "solid", "filled", "3.0", VeryLightGray, "1", Red)) dotContent.WriteString(makeLegendNode("critical", "Critical Asset", "0", Amber, "box", "solid", "filled", "3.0", VeryLightGray, "1", Amber)) dotContent.WriteString(makeLegendNode("other", "Important and Other Assets", "0", Black, "box", "solid", "filled", "2.0", VeryLightGray, "1", Black)) dotContent.WriteString("} \n") dotContent.WriteString("subgraph cluster_border_line_legend { \n") dotContent.WriteString(" label=\"Label color legend\"; \n") dotContent.WriteString(" color=\"lightgrey\"; \n") dotContent.WriteString(" style=\"dashed\"; \n") dotContent.WriteString(makeLegendNode("dotted", "Model forgery attempt", "0", Black, "box", "dotted ", "filled", "2.0", VeryLightGray, "1", Black)) dotContent.WriteString(makeLegendNode("solid", "Normal", "0", Black, "box", "solid", "filled", "2.0", VeryLightGray, "1", Black)) dotContent.WriteString("} \n") dotContent.WriteString("subgraph cluster_fill_legend { \n") dotContent.WriteString(" label=\"Shape fill legend (darker for physical machines, brighter for container and even more brighter for serverless\"; \n") dotContent.WriteString(" color=\"lightgrey\"; \n") dotContent.WriteString(" style=\"dashed\"; \n") dotContent.WriteString(makeLegendNode("invalid_item", "No data processed or stored, or using unknown technology, or no communication links", "0", "black", "box", "solid", "filled", "2.0", LightPink, "1", Black)) dotContent.WriteString(makeLegendNode("internet", "Asset used over the internet", "0", "black", "box", "solid", "filled", "2.0", ExtremeLightBlue, "1", Black)) dotContent.WriteString(makeLegendNode("out_of_scope", "Out of scope", "0", "black", "box", "solid", "filled", "2.0", OutOfScopeFancy, "1", Black)) dotContent.WriteString(makeLegendNode("custom_developed_part", "Custom developed part", "0", "black", "box", "solid", "filled", "2.0", CustomDevelopedParts, "1", Black)) dotContent.WriteString(makeLegendNode("other_assets", "Other assets", "0", "black", "box", "solid", "filled", "2.0", VeryLightGray, "1", Black)) dotContent.WriteString("} \n") } // Metadata init =============================================================================== tweaks := "" if parsedModel.DiagramTweakNodesep > 0 { tweaks += "\n nodesep=\"" + strconv.Itoa(parsedModel.DiagramTweakNodesep) + "\"" } if parsedModel.DiagramTweakRanksep > 0 { tweaks += "\n ranksep=\"" + strconv.Itoa(parsedModel.DiagramTweakRanksep) + "\"" } suppressBidirectionalArrows := true drawSpaceLinesForLayoutUnfortunatelyFurtherSeparatesAllRanks := true splines := "ortho" if len(parsedModel.DiagramTweakEdgeLayout) > 0 { switch parsedModel.DiagramTweakEdgeLayout { case "spline": splines = "spline" drawSpaceLinesForLayoutUnfortunatelyFurtherSeparatesAllRanks = false case "polyline": splines = "polyline" drawSpaceLinesForLayoutUnfortunatelyFurtherSeparatesAllRanks = false case "ortho": splines = "ortho" suppressBidirectionalArrows = true case "curved": splines = "curved" drawSpaceLinesForLayoutUnfortunatelyFurtherSeparatesAllRanks = false case "false": splines = "false" drawSpaceLinesForLayoutUnfortunatelyFurtherSeparatesAllRanks = false default: return nil, fmt.Errorf("unknown value for diagram_tweak_suppress_edge_labels (spline, polyline, ortho, curved, false): %s", parsedModel.DiagramTweakEdgeLayout) } } rankdir := "TB" if parsedModel.DiagramTweakLayoutLeftToRight { rankdir = "LR" } modelTitle := "" if addModelTitle { modelTitle = `label="` + parsedModel.Title + `"` } dotContent.WriteString(` graph [ ` + modelTitle + ` labelloc=t fontname="Verdana" fontsize=40 outputorder="nodesfirst" dpi=` + strconv.Itoa(dpi) + ` splines=` + splines + ` rankdir="` + rankdir + `" ` + tweaks + ` ]; node [ fontname="Verdana" fontsize="20" ]; edge [ shape="none" fontname="Verdana" fontsize="18" ]; `) // Trust Boundaries =============================================================================== var subgraphSnippetsById = make(map[string]string) // first create them in memory (see the link replacement below for nested trust boundaries) - otherwise in Go ranging over map is random order // range over them in sorted (hence re-producible) way: keys := make([]string, 0) for k := range parsedModel.TrustBoundaries { keys = append(keys, k) } sort.Strings(keys) for _, key := range keys { trustBoundary := parsedModel.TrustBoundaries[key] var snippet strings.Builder if len(trustBoundary.TechnicalAssetsInside) > 0 || len(trustBoundary.TrustBoundariesNested) > 0 { if drawSpaceLinesForLayoutUnfortunatelyFurtherSeparatesAllRanks { // see https://stackoverflow.com/questions/17247455/how-do-i-add-extra-space-between-clusters?noredirect=1&lq=1 snippet.WriteString("\n subgraph cluster_space_boundary_for_layout_only_1" + hash(trustBoundary.Id) + " {\n") snippet.WriteString(` graph [ dpi=` + strconv.Itoa(dpi) + ` label=<<table border="0" cellborder="0" cellpadding="0" bgcolor="#FFFFFF55"><tr><td><b> </b></td></tr></table>> fontsize="21" style="invis" color="green" fontcolor="green" margin="50.0" penwidth="6.5" outputorder="nodesfirst" ];`) } snippet.WriteString("\n subgraph cluster_" + hash(trustBoundary.Id) + " {\n") color, fontColor, bgColor, style, fontname := rgbHexColorTwilight(), rgbHexColorTwilight() /*"#550E0C"*/, "#FAFAFA", "dashed", "Verdana" penWidth := 4.5 if len(trustBoundary.TrustBoundariesNested) > 0 { //color, fontColor, style, fontname = Blue, Blue, "dashed", "Verdana" penWidth = 5.5 } if parsedModel.FindParentTrustBoundary(trustBoundary) != nil { bgColor = "#F1F1F1" } if trustBoundary.Type == types.NetworkPolicyNamespaceIsolation { fontColor, bgColor = "#222222", "#DFF4FF" } if trustBoundary.Type == types.ExecutionEnvironment { fontColor, bgColor, style = "#555555", "#FFFFF0", "dotted" } snippet.WriteString(` graph [ dpi=` + strconv.Itoa(dpi) + ` label=<<table border="0" cellborder="0" cellpadding="0"><tr><td><b>` + trustBoundary.Title + `</b> (` + trustBoundary.Type.String() + `)</td></tr></table>> fontsize="21" style="` + style + `" color="` + color + `" bgcolor="` + bgColor + `" fontcolor="` + fontColor + `" fontname="` + fontname + `" penwidth="` + fmt.Sprintf("%f", penWidth) + `" forcelabels=true outputorder="nodesfirst" margin="50.0" ];`) snippet.WriteString("\n") keys := trustBoundary.TechnicalAssetsInside sort.Strings(keys) for _, technicalAssetInside := range keys { //log.Println("About to add technical asset link to trust boundary: ", technicalAssetInside) technicalAsset := parsedModel.TechnicalAssets[technicalAssetInside] snippet.WriteString(hash(technicalAsset.Id)) snippet.WriteString(";\n") } keys = trustBoundary.TrustBoundariesNested sort.Strings(keys) for _, trustBoundaryNested := range keys { //log.Println("About to add nested trust boundary to trust boundary: ", trustBoundaryNested) trustBoundaryNested := parsedModel.TrustBoundaries[trustBoundaryNested] snippet.WriteString("LINK-NEEDS-REPLACED-BY-cluster_" + hash(trustBoundaryNested.Id)) snippet.WriteString(";\n") } snippet.WriteString(" }\n\n") if drawSpaceLinesForLayoutUnfortunatelyFurtherSeparatesAllRanks { snippet.WriteString(" }\n\n") } } subgraphSnippetsById[hash(trustBoundary.Id)] = snippet.String() } // here replace links and remove from map after replacement (i.e. move snippet into nested) for i := range subgraphSnippetsById { re := regexp.MustCompile(`LINK-NEEDS-REPLACED-BY-cluster_([0-9]*);`) for { matches := re.FindStringSubmatch(subgraphSnippetsById[i]) if len(matches) > 0 { embeddedSnippet := " //nested:" + subgraphSnippetsById[matches[1]] subgraphSnippetsById[i] = strings.ReplaceAll(subgraphSnippetsById[i], matches[0], embeddedSnippet) subgraphSnippetsById[matches[1]] = "" // to something like remove it } else { break } } } // now write them all keys = make([]string, 0) for k := range subgraphSnippetsById { keys = append(keys, k) } sort.Strings(keys) for _, key := range keys { snippet := subgraphSnippetsById[key] dotContent.WriteString(snippet) } // Technical Assets =============================================================================== // first create them in memory (see the link replacement below for nested trust boundaries) - otherwise in Go ranging over map is random order // range over them in sorted (hence re-producible) way: // Convert map to slice of values: var techAssets []*types.TechnicalAsset for _, techAsset := range parsedModel.TechnicalAssets { techAssets = append(techAssets, techAsset) } sort.Sort(types.ByOrderAndIdSort(techAssets)) for _, technicalAsset := range techAssets { dotContent.WriteString(makeTechAssetNode(parsedModel, technicalAsset, false)) dotContent.WriteString("\n") } // Data Flows (Technical Communication Links) =============================================================================== for _, technicalAsset := range techAssets { for _, dataFlow := range technicalAsset.CommunicationLinks { sourceId := technicalAsset.Id targetId := dataFlow.TargetId //log.Println("About to add link from", sourceId, "to", targetId, "with id", dataFlow.ID) var arrowStyle, arrowColor, readOrWriteHead, readOrWriteTail string if dataFlow.Readonly { readOrWriteHead = "empty" readOrWriteTail = "odot" } else { readOrWriteHead = "normal" readOrWriteTail = "dot" } dir := "forward" if dataFlow.IsBidirectional() { if !suppressBidirectionalArrows { // as it does not work as bug in graphviz with ortho: https://gitlab.com/graphviz/graphviz/issues/144 dir = "both" } } arrowStyle = ` style="` + determineArrowLineStyle(dataFlow) + `" penwidth="` + determineArrowPenWidth(dataFlow, parsedModel) + `" arrowtail="` + readOrWriteTail + `" arrowhead="` + readOrWriteHead + `" dir="` + dir + `" arrowsize="2.0" ` arrowColor = ` color="` + determineArrowColor(dataFlow, parsedModel) + `"` tweaks := "" if dataFlow.DiagramTweakWeight > 0 { tweaks += " weight=\"" + strconv.Itoa(dataFlow.DiagramTweakWeight) + "\" " } dotContent.WriteString("\n") dotContent.WriteString(" " + hash(sourceId) + " -> " + hash(targetId) + ` [` + arrowColor + ` ` + arrowStyle + tweaks + ` constraint=` + strconv.FormatBool(dataFlow.DiagramTweakConstraint) + ` `) if !parsedModel.DiagramTweakSuppressEdgeLabels { dotContent.WriteString(` xlabel="` + encode(dataFlow.Protocol.String()) + `" fontcolor="` + determineLabelColor(dataFlow, parsedModel) + `" `) } dotContent.WriteString(" ];\n") } } diagramInvisibleConnectionsTweaks, err := makeDiagramInvisibleConnectionsTweaks(parsedModel) if err != nil { return nil, fmt.Errorf("error while making diagram invisible connections tweaks: %w", err) } dotContent.WriteString(diagramInvisibleConnectionsTweaks) diagramSameRankNodeTweaks, err := makeDiagramSameRankNodeTweaks(parsedModel) if err != nil { return nil, fmt.Errorf("error while making diagram same-rank node tweaks: %w", err) } dotContent.WriteString(diagramSameRankNodeTweaks) dotContent.WriteString("}") // Write the DOT file file, err := os.Create(filepath.Clean(diagramFilenameDOT)) if err != nil { return nil, fmt.Errorf("error creating %s: %w", diagramFilenameDOT, err) } defer func() { _ = file.Close() }() _, err = fmt.Fprintln(file, dotContent.String()) if err != nil { return nil, fmt.Errorf("error writing %s: %w", diagramFilenameDOT, err) } return file, nil } func makeLegendNode(id, title, compartmentBorder, labelColor, shape, borderLineStyle, shapeStyle, borderPenWidth, shapeFillColor, shapePeripheries, shapeBorderColor string) string { return " " + id + ` [ label=<<table border="0" cellborder="` + compartmentBorder + `" cellpadding="2" cellspacing="0"><tr><td><font point-size="15" color="` + DarkBlue + `">list of technologies` + `</font><br/><font point-size="15" color="` + LightGray + `">technical asset size</font></td></tr><tr><td><b><font color="` + labelColor + `">` + encode(title) + `</font></b><br/></td></tr><tr><td>attacker attractiveness level</td></tr></table>> shape=` + shape + ` style="` + borderLineStyle + `,` + shapeStyle + `" penwidth="` + borderPenWidth + `" fillcolor="` + shapeFillColor + `" peripheries=` + shapePeripheries + ` color="` + shapeBorderColor + "\"\n ]; " } // Pen Widths: func determineArrowPenWidth(cl *types.CommunicationLink, parsedModel *types.Model) string { if determineArrowColor(cl, parsedModel) == Pink { return fmt.Sprintf("%f", 3.0) } if determineArrowColor(cl, parsedModel) != Black { return fmt.Sprintf("%f", 2.5) } return fmt.Sprintf("%f", 1.5) } func determineLabelColor(cl *types.CommunicationLink, parsedModel *types.Model) string { // TODO: Just move into main.go and let the generated risk determine the color, don't duplicate the logic here /* if dataFlow.Protocol.IsEncrypted() { return Gray } else {*/ // check for red for _, sentDataAsset := range cl.DataAssetsSent { if parsedModel.DataAssets[sentDataAsset].Integrity == types.MissionCritical { return Red } } for _, receivedDataAsset := range cl.DataAssetsReceived { if parsedModel.DataAssets[receivedDataAsset].Integrity == types.MissionCritical { return Red } } // check for amber for _, sentDataAsset := range cl.DataAssetsSent { if parsedModel.DataAssets[sentDataAsset].Integrity == types.Critical { return Amber } } for _, receivedDataAsset := range cl.DataAssetsReceived { if parsedModel.DataAssets[receivedDataAsset].Integrity == types.Critical { return Amber } } // default return Gray } func determineArrowLineStyle(cl *types.CommunicationLink) string { if len(cl.DataAssetsSent) == 0 && len(cl.DataAssetsReceived) == 0 { return "dotted" // dotted, because it's strange when too many technical communication links transfer no data... some ok, but many in a diagram ist a sign of model forgery... } if cl.Usage == types.DevOps { return "dashed" } return "solid" } // pink when model forgery attempt (i.e. nothing being sent and received) func determineArrowColor(cl *types.CommunicationLink, parsedModel *types.Model) string { // TODO: Just move into main.go and let the generated risk determine the color, don't duplicate the logic here if len(cl.DataAssetsSent) == 0 && len(cl.DataAssetsReceived) == 0 || cl.Protocol == types.UnknownProtocol { return Pink // pink, because it's strange when too many technical communication links transfer no data... some ok, but many in a diagram ist a sign of model forgery... } if cl.Usage == types.DevOps { return MiddleLightGray } else if cl.VPN { return DarkBlue } else if cl.IpFiltered { return Brown } // check for red for _, sentDataAsset := range cl.DataAssetsSent { if parsedModel.DataAssets[sentDataAsset].Confidentiality == types.StrictlyConfidential { return Red } } for _, receivedDataAsset := range cl.DataAssetsReceived { if parsedModel.DataAssets[receivedDataAsset].Confidentiality == types.StrictlyConfidential { return Red } } // check for amber for _, sentDataAsset := range cl.DataAssetsSent { if parsedModel.DataAssets[sentDataAsset].Confidentiality == types.Confidential { return Amber } } for _, receivedDataAsset := range cl.DataAssetsReceived { if parsedModel.DataAssets[receivedDataAsset].Confidentiality == types.Confidential { return Amber } } // default return Black } func GenerateDataFlowDiagramGraphvizImage(dotFile *os.File, targetDir string, tempFolder, dataFlowDiagramFilenamePNG string, progressReporter progressReporter, keepGraphVizDataFile bool) error { progressReporter.Info("Rendering data flow diagram input") // tmp files tmpFileDOT, err := os.CreateTemp(tempFolder, "diagram-*-.gv") if err != nil { return fmt.Errorf("error creating temp file: %w", err) } if !keepGraphVizDataFile { defer func() { _ = os.Remove(tmpFileDOT.Name()) }() } tmpFilePNG, err := os.CreateTemp(tempFolder, "diagram-*-.png") if err != nil { return fmt.Errorf("error creating temp file: %w", err) } if !keepGraphVizDataFile { defer func() { _ = os.Remove(tmpFilePNG.Name()) }() } // copy into tmp file as input inputDOT, err := os.ReadFile(dotFile.Name()) if err != nil { return fmt.Errorf("error reading %s: %w", dotFile.Name(), err) } err = os.WriteFile(tmpFileDOT.Name(), inputDOT, 0600) if err != nil { return fmt.Errorf("error creating %s: %w", tmpFileDOT.Name(), err) } // exec cmd := exec.Command("dot", "-Tpng", tmpFileDOT.Name(), "-o", tmpFilePNG.Name()) // #nosec G204 cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err = cmd.Run() if err != nil { return fmt.Errorf("graph rendering call failed with error: %w", err) } // copy into resulting file inputPNG, err := os.ReadFile(tmpFilePNG.Name()) if err != nil { return fmt.Errorf("failed to copy to file %s: %w", tmpFilePNG.Name(), err) } err = os.WriteFile(filepath.Join(targetDir, dataFlowDiagramFilenamePNG), inputPNG, 0600) if err != nil { return fmt.Errorf("failed to create %s: %w", filepath.Join(targetDir, dataFlowDiagramFilenamePNG), err) } return nil } func makeDiagramSameRankNodeTweaks(parsedModel *types.Model) (string, error) { // see https://stackoverflow.com/questions/25734244/how-do-i-place-nodes-on-the-same-level-in-dot tweak := "" if len(parsedModel.DiagramTweakSameRankAssets) > 0 { for _, sameRank := range parsedModel.DiagramTweakSameRankAssets { assetIDs := strings.Split(sameRank, ":") if len(assetIDs) > 0 { tweak += "{ rank=same; " for _, id := range assetIDs { err := parsedModel.CheckTechnicalAssetExists(id, "diagram tweak same-rank", true) if err != nil { return "", fmt.Errorf("error while checking technical asset existence: %w", err) } if len(parsedModel.GetTechnicalAssetTrustBoundaryId(parsedModel.TechnicalAssets[id])) > 0 { return "", fmt.Errorf("technical assets (referenced in same rank diagram tweak) are inside trust boundaries: %v", parsedModel.DiagramTweakSameRankAssets) } tweak += " " + hash(id) + "; " } tweak += " }" } } } return tweak, nil } func makeDiagramInvisibleConnectionsTweaks(parsedModel *types.Model) (string, error) { // see https://stackoverflow.com/questions/2476575/how-to-control-node-placement-in-graphviz-i-e-avoid-edge-crossings tweak := "" if len(parsedModel.DiagramTweakInvisibleConnectionsBetweenAssets) > 0 { for _, invisibleConnections := range parsedModel.DiagramTweakInvisibleConnectionsBetweenAssets { assetIDs := strings.Split(invisibleConnections, ":") if len(assetIDs) == 2 { err := parsedModel.CheckTechnicalAssetExists(assetIDs[0], "diagram tweak connections", true) if err != nil { return "", fmt.Errorf("error while checking technical asset existence: %w", err) } err = parsedModel.CheckTechnicalAssetExists(assetIDs[1], "diagram tweak connections", true) if err != nil { return "", fmt.Errorf("error while checking technical asset existence: %w", err) } tweak += "\n" + hash(assetIDs[0]) + " -> " + hash(assetIDs[1]) + " [style=invis]; \n" } } } return tweak, nil } func WriteDataAssetDiagramGraphvizDOT(parsedModel *types.Model, diagramFilenameDOT string, dpi int, progressReporter progressReporter) (*os.File, error) { progressReporter.Info("Writing data asset diagram input") var dotContent strings.Builder dotContent.WriteString("digraph generatedModel { concentrate=true \n") // Metadata init =============================================================================== dotContent.WriteString(` graph [ dpi=` + strconv.Itoa(dpi) + ` fontname="Verdana" labelloc="c" fontsize="20" splines=false rankdir="LR" nodesep=1.0 ranksep=3.0 outputorder="nodesfirst" ]; node [ fontcolor="white" fontname="Verdana" fontsize="20" ]; edge [ shape="none" fontname="Verdana" fontsize="18" ]; `) // Technical Assets =============================================================================== techAssets := make([]*types.TechnicalAsset, 0) for _, techAsset := range parsedModel.TechnicalAssets { techAssets = append(techAssets, techAsset) } sort.Sort(types.ByOrderAndIdSort(techAssets)) for _, technicalAsset := range techAssets { if len(technicalAsset.DataAssetsStored) > 0 || len(technicalAsset.DataAssetsProcessed) > 0 { dotContent.WriteString(makeTechAssetNode(parsedModel, technicalAsset, true)) dotContent.WriteString("\n") } } // Data Assets =============================================================================== dataAssets := make([]*types.DataAsset, 0) for _, dataAsset := range parsedModel.DataAssets { dataAssets = append(dataAssets, dataAsset) } sortByDataAssetDataBreachProbabilityAndTitle(parsedModel, dataAssets) for _, dataAsset := range dataAssets { dotContent.WriteString(makeDataAssetNode(parsedModel, dataAsset)) dotContent.WriteString("\n") } // Data Asset to Tech Asset links =============================================================================== for _, technicalAsset := range techAssets { for _, sourceId := range technicalAsset.DataAssetsStored { targetId := technicalAsset.Id dotContent.WriteString("\n") dotContent.WriteString(hash(sourceId) + " -> " + hash(targetId) + ` [ color="blue" style="solid" ];`) dotContent.WriteString("\n") } for _, sourceId := range technicalAsset.DataAssetsProcessed { if !contains(technicalAsset.DataAssetsStored, sourceId) { // here only if not already drawn above targetId := technicalAsset.Id dotContent.WriteString("\n") dotContent.WriteString(hash(sourceId) + " -> " + hash(targetId) + ` [ color="#666666" style="dashed" ];`) dotContent.WriteString("\n") } } } dotContent.WriteString("}") // Write the DOT file file, err := os.Create(filepath.Clean(diagramFilenameDOT)) if err != nil { return nil, fmt.Errorf("error creating %s: %w", diagramFilenameDOT, err) } defer func() { _ = file.Close() }() _, err = fmt.Fprintln(file, dotContent.String()) if err != nil { return nil, fmt.Errorf("error writing %s: %w", diagramFilenameDOT, err) } return file, nil } func sortByDataAssetDataBreachProbabilityAndTitle(parsedModel *types.Model, assets []*types.DataAsset) { sort.Slice(assets, func(i, j int) bool { highestDataBreachProbabilityLeft := parsedModel.IdentifiedDataBreachProbability(assets[i]) highestDataBreachProbabilityRight := parsedModel.IdentifiedDataBreachProbability(assets[j]) if highestDataBreachProbabilityLeft == highestDataBreachProbabilityRight { return assets[i].Title < assets[j].Title } return highestDataBreachProbabilityLeft > highestDataBreachProbabilityRight }) } func makeDataAssetNode(parsedModel *types.Model, dataAsset *types.DataAsset) string { var color string switch identifiedDataBreachProbabilityStillAtRisk(parsedModel, dataAsset) { case types.Probable: color = rgbHexColorHighRisk() case types.Possible: color = rgbHexColorMediumRisk() case types.Improbable: color = rgbHexColorLowRisk() default: color = "#444444" // since black is too dark here as fill color } if !isDataBreachPotentialStillAtRisk(parsedModel, dataAsset) { color = "#444444" // since black is too dark here as fill color } return " " + hash(dataAsset.Id) + ` [ label=<<b>` + encode(dataAsset.Title) + `</b>> penwidth="3.0" style="filled" fillcolor="` + color + `" color="` + color + "\"\n ]; " } func makeTechAssetNode(parsedModel *types.Model, technicalAsset *types.TechnicalAsset, simplified bool) string { if simplified { color := rgbHexColorOutOfScope() if !technicalAsset.OutOfScope { generatedRisks := parsedModel.GeneratedRisks(technicalAsset) switch types.HighestSeverityStillAtRisk(generatedRisks) { case types.CriticalSeverity: color = rgbHexColorCriticalRisk() case types.HighSeverity: color = rgbHexColorHighRisk() case types.ElevatedSeverity: color = rgbHexColorElevatedRisk() case types.MediumSeverity: color = rgbHexColorMediumRisk() case types.LowSeverity: color = rgbHexColorLowRisk() default: color = "#444444" // since black is too dark here as fill color } if len(types.ReduceToOnlyStillAtRisk(generatedRisks)) == 0 { color = "#444444" // since black is too dark here as fill color } } return " " + hash(technicalAsset.Id) + ` [ shape="box" style="filled" fillcolor="` + color + `" label=<<b>` + encode(technicalAsset.Title) + `</b>> penwidth="3.0" color="` + color + `" ]; ` } var shape, title string var lineBreak = "" switch technicalAsset.Type { case types.ExternalEntity: shape = "box" title = technicalAsset.Title case types.Process: shape = "ellipse" title = technicalAsset.Title case types.Datastore: shape = "cylinder" title = technicalAsset.Title if technicalAsset.Redundant { lineBreak = "<br/>" } } if technicalAsset.UsedAsClientByHuman { shape = "octagon" } // RAA = Relative Attacker Attractiveness raa := technicalAsset.RAA var attackerAttractivenessLabel string if technicalAsset.OutOfScope { attackerAttractivenessLabel = "<font point-size=\"15\" color=\"#603112\">RAA: out of scope</font>" } else { attackerAttractivenessLabel = "<font point-size=\"15\" color=\"#603112\">RAA: " + fmt.Sprintf("%.0f", raa) + " %</font>" } compartmentBorder := "0" if technicalAsset.MultiTenant { compartmentBorder = "1" } return " " + hash(technicalAsset.Id) + ` [ label=<<table border="0" cellborder="` + compartmentBorder + `" cellpadding="2" cellspacing="0"><tr><td><font point-size="15" color="` + DarkBlue + `">` + lineBreak + technicalAsset.Technologies.String() + `</font><br/><font point-size="15" color="` + LightGray + `">` + technicalAsset.Size.String() + `</font></td></tr><tr><td><b><font color="` + determineTechnicalAssetLabelColor(technicalAsset, parsedModel) + `">` + encode(title) + `</font></b><br/></td></tr><tr><td>` + attackerAttractivenessLabel + `</td></tr></table>> shape=` + shape + ` style="` + determineShapeBorderLineStyle(technicalAsset) + `,` + determineShapeStyle(technicalAsset) + `" penwidth="` + determineShapeBorderPenWidth(technicalAsset, parsedModel) + `" fillcolor="` + determineShapeFillColor(technicalAsset, parsedModel) + `" peripheries=` + strconv.Itoa(determineShapePeripheries(technicalAsset)) + ` color="` + determineShapeBorderColor(technicalAsset, parsedModel) + "\"\n ]; " } func determineShapeStyle(ta *types.TechnicalAsset) string { return "filled" } func determineShapeFillColor(ta *types.TechnicalAsset, parsedModel *types.Model) string { fillColor := VeryLightGray if (len(ta.DataAssetsProcessed) == 0 && len(ta.DataAssetsStored) == 0) || ta.Technologies.IsUnknown() { fillColor = LightPink // lightPink, because it's strange when too many technical assets process no data... some ok, but many in a diagram ist a sign of model forgery... } else if len(ta.CommunicationLinks) == 0 && len(parsedModel.IncomingTechnicalCommunicationLinksMappedByTargetId[ta.Id]) == 0 { fillColor = LightPink } else if ta.Internet { fillColor = ExtremeLightBlue } else if ta.OutOfScope { fillColor = OutOfScopeFancy } else if ta.CustomDevelopedParts { fillColor = CustomDevelopedParts } switch ta.Machine { case types.Physical: fillColor = darkenHexColor(fillColor) case types.Container: fillColor = brightenHexColor(fillColor) case types.Serverless: fillColor = brightenHexColor(brightenHexColor(fillColor)) case types.Virtual: } return fillColor } func determineShapeBorderPenWidth(ta *types.TechnicalAsset, parsedModel *types.Model) string { if determineShapeBorderColor(ta, parsedModel) == Pink { return fmt.Sprintf("%f", 3.5) } if determineShapeBorderColor(ta, parsedModel) != Black { return fmt.Sprintf("%f", 3.0) } return fmt.Sprintf("%f", 2.0) } // red when mission-critical integrity, but still unauthenticated (non-readonly) channels access it // amber when critical integrity, but still unauthenticated (non-readonly) channels access it // pink when model forgery attempt (i.e. nothing being processed) func determineShapeBorderColor(ta *types.TechnicalAsset, parsedModel *types.Model) string { // Check for red if ta.Confidentiality == types.StrictlyConfidential { return Red } for _, processedDataAsset := range ta.DataAssetsProcessed { if parsedModel.DataAssets[processedDataAsset].Confidentiality == types.StrictlyConfidential { return Red } } // Check for amber if ta.Confidentiality == types.Confidential { return Amber } for _, processedDataAsset := range ta.DataAssetsProcessed { if parsedModel.DataAssets[processedDataAsset].Confidentiality == types.Confidential { return Amber } } return Black } func determineShapePeripheries(ta *types.TechnicalAsset) int { if ta.Redundant { return 2 } return 1 } // dotted when model forgery attempt (i.e. nothing being processed or stored) func determineShapeBorderLineStyle(ta *types.TechnicalAsset) string { if len(ta.DataAssetsProcessed) == 0 || ta.OutOfScope { return "dotted" // dotted, because it's strange when too many technical communication links transfer no data... some ok, but many in a diagram ist a sign of model forgery... } return "solid" } // red when >= confidential data stored in unencrypted technical asset func determineTechnicalAssetLabelColor(ta *types.TechnicalAsset, model *types.Model) string { // Check for red if ta.Integrity == types.MissionCritical { return Red } for _, storedDataAsset := range ta.DataAssetsStored { if model.DataAssets[storedDataAsset].Integrity == types.MissionCritical { return Red } } for _, processedDataAsset := range ta.DataAssetsProcessed { if model.DataAssets[processedDataAsset].Integrity == types.MissionCritical { return Red } } // Check for amber if ta.Integrity == types.Critical { return Amber } for _, storedDataAsset := range ta.DataAssetsStored { if model.DataAssets[storedDataAsset].Integrity == types.Critical {
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
true
Threagile/threagile
https://github.com/Threagile/threagile/blob/293892c9c3a6bb287f66b4b048d2fb1fae2d3676/pkg/report/excel-column.go
pkg/report/excel-column.go
package report import ( "github.com/xuri/excelize/v2" "strings" ) type ExcelColumns map[string]ExcelColumn func (what *ExcelColumns) GetColumns() ExcelColumns { *what = map[string]ExcelColumn{ "A": {Title: "Severity", Width: 12}, "B": {Title: "Likelihood", Width: 15}, "C": {Title: "Impact", Width: 15}, "D": {Title: "STRIDE", Width: 22}, "E": {Title: "Function", Width: 16}, "F": {Title: "CWE", Width: 12}, "G": {Title: "Risk Category", Width: 50}, "H": {Title: "Technical Asset", Width: 50}, "I": {Title: "Communication Link", Width: 50}, "J": {Title: "RAA %", Width: 10}, "K": {Title: "Identified Risk", Width: 75}, "L": {Title: "Action", Width: 45}, "M": {Title: "Mitigation", Width: 75}, "N": {Title: "Check", Width: 40}, "O": {Title: "ID", Width: 10}, "P": {Title: "Status", Width: 18}, "Q": {Title: "Justification", Width: 80}, "R": {Title: "Date", Width: 18}, "S": {Title: "Checked by", Width: 20}, "T": {Title: "Ticket", Width: 20}, } return *what } func (what *ExcelColumns) FindColumnNameByTitle(title string) string { for column, excelColumn := range *what { if strings.EqualFold(excelColumn.Title, title) { return column } } return "" } func (what *ExcelColumns) FindColumnIndexByTitle(title string) int { for column, excelColumn := range *what { if strings.EqualFold(excelColumn.Title, title) { columnNumber, columnNumberError := excelize.ColumnNameToNumber(column) if columnNumberError != nil { return -1 } return columnNumber - 1 } } return -1 } type ExcelColumn struct { Title string Width float64 }
go
MIT
293892c9c3a6bb287f66b4b048d2fb1fae2d3676
2026-01-07T10:38:05.901794Z
false