mirror of
https://github.com/ultravioletrs/cocos.git
synced 2026-06-23 04:10:25 +00:00
8eb1fac9ad
* Refactor and update dependencies in the project - Updated go.sum to replace `github.com/absmach/magistrala` with `github.com/absmach/supermq` across various modules. - Removed VSock configuration from environment variables and QEMU arguments. - Updated QEMU configuration and related tests to remove references to guest CID and VSock. - Added new HTTP transport layer for API endpoints in the manager. - Introduced Prometheus monitoring configuration with alert rules and Alertmanager setup. - Updated service and VM interfaces to remove unused methods and references. - Refactored tests to align with the new structure and dependencies. Signed-off-by: Sammy Oina <sammyoina@gmail.com> * Add MaxVMs configuration and enforce limit on VM creation Signed-off-by: Sammy Oina <sammyoina@gmail.com> * Add comprehensive tests for HTTP transport handlers and endpoints Signed-off-by: Sammy Oina <sammyoina@gmail.com> * Add test case for exceeding maximum number of VMs in TestRun Signed-off-by: Sammy Oina <sammyoina@gmail.com> * Improve error handling in TestHandlerWithCustomRouter to ensure response writing is checked Signed-off-by: Sammy Oina <sammyoina@gmail.com> * Update dependencies to latest versions - Upgrade cel.dev/expr from v0.23.0 to v0.24.0 - Upgrade github.com/absmach/supermq from v0.16.0 to v0.17.0 - Upgrade github.com/cenkalti/backoff from v4.3.0 to v5.0.2 - Upgrade github.com/cncf/xds/go to v0.0.0-20250501225837-2ac532fd4443 - Upgrade github.com/go-chi/chi/v5 from v5.2.1 to v5.2.2 - Upgrade github.com/go-jose/go-jose/v3 from v3.0.3 to v3.0.4 - Upgrade github.com/gofrs/uuid/v5 from v5.3.0 to v5.3.2 - Upgrade github.com/prometheus/client_golang from v1.22.0 to v1.23.0 - Upgrade github.com/prometheus/client_model from v0.6.1 to v0.6.2 - Upgrade github.com/prometheus/common from v0.62.0 to v0.65.0 - Upgrade github.com/prometheus/procfs from v0.15.1 to v0.16.1 - Upgrade go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp from v0.60.0 to v0.62.0 - Upgrade go.opentelemetry.io/otel/exporters/otlp/otlptrace from v1.36.0 to v1.37.0 - Upgrade golang.org/x/crypto from v0.39.0 to v0.40.0 - Upgrade golang.org/x/sys from v0.33.0 to v0.34.0 - Upgrade golang.org/x/text from v0.26.0 to v0.27.0 - Upgrade golang.org/x/time from v0.11.0 to v0.12.0 - Upgrade google.golang.org/grpc from v1.73.0 to v1.74.2 Signed-off-by: Sammy Oina <sammyoina@gmail.com> --------- Signed-off-by: Sammy Oina <sammyoina@gmail.com>
410 lines
9.9 KiB
Go
410 lines
9.9 KiB
Go
// Copyright (c) Ultraviolet
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
package grpc
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/rsa"
|
|
"crypto/x509"
|
|
"crypto/x509/pkix"
|
|
"encoding/pem"
|
|
"fmt"
|
|
"math/big"
|
|
"os"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/absmach/supermq/pkg/errors"
|
|
"github.com/google/go-sev-guest/proto/check"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
"github.com/ultravioletrs/cocos/pkg/attestation"
|
|
"github.com/ultravioletrs/cocos/pkg/attestation/vtpm"
|
|
)
|
|
|
|
func TestNewClient(t *testing.T) {
|
|
caCertFile, clientCertFile, clientKeyFile, err := createCertificatesFiles()
|
|
require.NoError(t, err)
|
|
|
|
t.Cleanup(func() {
|
|
os.Remove(caCertFile)
|
|
os.Remove(clientCertFile)
|
|
os.Remove(clientKeyFile)
|
|
})
|
|
|
|
tests := []struct {
|
|
name string
|
|
cfg BaseConfig
|
|
agentCfg AgentClientConfig
|
|
wantErr bool
|
|
err error
|
|
}{
|
|
{
|
|
name: "Success without TLS",
|
|
cfg: BaseConfig{
|
|
URL: "localhost:7001",
|
|
},
|
|
wantErr: false,
|
|
err: nil,
|
|
},
|
|
{
|
|
name: "Success with TLS",
|
|
cfg: BaseConfig{
|
|
URL: "localhost:7001",
|
|
ServerCAFile: caCertFile,
|
|
},
|
|
wantErr: false,
|
|
err: nil,
|
|
},
|
|
{
|
|
name: "Success with mTLS",
|
|
cfg: BaseConfig{
|
|
URL: "localhost:7001",
|
|
ServerCAFile: caCertFile,
|
|
ClientCert: clientCertFile,
|
|
ClientKey: clientKeyFile,
|
|
},
|
|
wantErr: false,
|
|
err: nil,
|
|
},
|
|
{
|
|
name: "Success agent client with mTLS",
|
|
agentCfg: AgentClientConfig{
|
|
BaseConfig: BaseConfig{
|
|
URL: "localhost:7001",
|
|
ServerCAFile: caCertFile,
|
|
ClientCert: clientCertFile,
|
|
ClientKey: clientKeyFile,
|
|
},
|
|
},
|
|
wantErr: false,
|
|
err: nil,
|
|
},
|
|
{
|
|
name: "Success agent client with aTLS",
|
|
agentCfg: AgentClientConfig{
|
|
BaseConfig: BaseConfig{
|
|
URL: "localhost:7001",
|
|
ServerCAFile: caCertFile,
|
|
ClientCert: clientCertFile,
|
|
ClientKey: clientKeyFile,
|
|
},
|
|
AttestedTLS: true,
|
|
AttestationPolicy: "../../../scripts/attestation_policy/attestation_policy.json",
|
|
},
|
|
wantErr: false,
|
|
err: nil,
|
|
},
|
|
{
|
|
name: "Failed agent client with aTLS",
|
|
agentCfg: AgentClientConfig{
|
|
BaseConfig: BaseConfig{
|
|
URL: "localhost:7001",
|
|
ServerCAFile: caCertFile,
|
|
ClientCert: clientCertFile,
|
|
ClientKey: clientKeyFile,
|
|
},
|
|
AttestedTLS: true,
|
|
AttestationPolicy: "no such file",
|
|
},
|
|
wantErr: true,
|
|
err: fmt.Errorf("failed to stat attestation policy file"),
|
|
},
|
|
{
|
|
name: "Fail with invalid ServerCAFile",
|
|
cfg: BaseConfig{
|
|
URL: "localhost:7001",
|
|
ServerCAFile: "nonexistent.pem",
|
|
},
|
|
wantErr: true,
|
|
err: errFailedToLoadRootCA,
|
|
},
|
|
{
|
|
name: "Fail with invalid ClientCert",
|
|
cfg: BaseConfig{
|
|
URL: "localhost:7001",
|
|
ServerCAFile: caCertFile,
|
|
ClientCert: "nonexistent.pem",
|
|
ClientKey: clientKeyFile,
|
|
},
|
|
wantErr: true,
|
|
err: errFailedToLoadClientCertKey,
|
|
},
|
|
{
|
|
name: "Fail with invalid ClientKey",
|
|
cfg: BaseConfig{
|
|
URL: "localhost:7001",
|
|
ServerCAFile: caCertFile,
|
|
ClientCert: clientCertFile,
|
|
ClientKey: "nonexistent.pem",
|
|
},
|
|
wantErr: true,
|
|
err: errFailedToLoadClientCertKey,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
var client Client
|
|
if strings.Contains(tt.name, "agent client") {
|
|
client, err = NewClient(tt.agentCfg)
|
|
} else {
|
|
client, err = NewClient(tt.cfg)
|
|
}
|
|
assert.True(t, errors.Contains(err, tt.err), fmt.Sprintf("expected error %v, got %v", tt.err, err))
|
|
if tt.wantErr {
|
|
assert.Error(t, err)
|
|
assert.Nil(t, client)
|
|
} else {
|
|
assert.NoError(t, err)
|
|
assert.NotNil(t, client)
|
|
assert.NoError(t, client.Close())
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestClientSecure(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
secure security
|
|
expected string
|
|
}{
|
|
{
|
|
name: "Without TLS",
|
|
secure: withoutTLS,
|
|
expected: "without TLS",
|
|
},
|
|
{
|
|
name: "With TLS",
|
|
secure: withTLS,
|
|
expected: "with TLS",
|
|
},
|
|
{
|
|
name: "With mTLS",
|
|
secure: withmTLS,
|
|
expected: "with mTLS",
|
|
},
|
|
{
|
|
name: "With aTLS",
|
|
secure: withaTLS,
|
|
expected: "with aTLS",
|
|
},
|
|
{
|
|
name: "With maTLS",
|
|
secure: withmaTLS,
|
|
expected: WithMATLS,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
c := &client{secure: tt.secure}
|
|
assert.Equal(t, tt.expected, c.Secure())
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestReadAttestationPolicy(t *testing.T) {
|
|
validJSON := `{"pcr_values":{"sha256":{"0":"123"},"sha384":{"0":"123"}},"policy":{"report_data":"AAAA"},"root_of_trust":{"product_line":"Milan"}}`
|
|
invalidJSON := `{"invalid_json"`
|
|
invalidJSONPCR := `{"pcr_values":{"sha256":{"0":true},"sha384":{"0":"123"}},"policy":{"report_data":"AAAA"},"root_of_trust":{"product_line":"Milan"}}`
|
|
|
|
cases := []struct {
|
|
name string
|
|
manifestPath string
|
|
fileContent string
|
|
err error
|
|
}{
|
|
{
|
|
name: "Valid manifest",
|
|
manifestPath: "valid_manifest.json",
|
|
fileContent: validJSON,
|
|
err: nil,
|
|
},
|
|
{
|
|
name: "Invalid JSON",
|
|
manifestPath: "invalid_manifest.json",
|
|
fileContent: invalidJSON,
|
|
err: vtpm.ErrAttestationPolicyDecode,
|
|
},
|
|
{
|
|
name: "Non-existent file",
|
|
manifestPath: "nonexistent.json",
|
|
fileContent: "",
|
|
err: vtpm.ErrAttestationPolicyOpen,
|
|
},
|
|
{
|
|
name: "Empty manifest path",
|
|
manifestPath: "",
|
|
fileContent: "",
|
|
err: vtpm.ErrAttestationPolicyMissing,
|
|
},
|
|
{
|
|
name: "Invalid JSON PCR",
|
|
manifestPath: "invalid_manifest.json",
|
|
fileContent: invalidJSONPCR,
|
|
err: vtpm.ErrAttestationPolicyDecode,
|
|
},
|
|
}
|
|
|
|
for _, tt := range cases {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if tt.manifestPath != "" && tt.fileContent != "" {
|
|
err := os.WriteFile(tt.manifestPath, []byte(tt.fileContent), 0o644)
|
|
require.NoError(t, err)
|
|
defer os.Remove(tt.manifestPath)
|
|
}
|
|
|
|
config := attestation.Config{Config: &check.Config{}, PcrConfig: &attestation.PcrConfig{}}
|
|
err := vtpm.ReadPolicy(tt.manifestPath, &config)
|
|
|
|
assert.True(t, errors.Contains(err, tt.err), fmt.Sprintf("expected error %v, got %v", tt.err, err))
|
|
if tt.err == nil {
|
|
assert.NotNil(t, config.Config.Policy)
|
|
assert.NotNil(t, config.Config.RootOfTrust)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func createCertificatesFiles() (string, string, string, error) {
|
|
caKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
if err != nil {
|
|
return "", "", "", err
|
|
}
|
|
|
|
caTemplate := x509.Certificate{
|
|
SerialNumber: big.NewInt(1),
|
|
Subject: pkix.Name{
|
|
Organization: []string{"Test Org"},
|
|
},
|
|
NotBefore: time.Now(),
|
|
NotAfter: time.Now().Add(time.Hour * 24),
|
|
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
|
|
BasicConstraintsValid: true,
|
|
IsCA: true,
|
|
}
|
|
|
|
caCertDER, err := x509.CreateCertificate(rand.Reader, &caTemplate, &caTemplate, &caKey.PublicKey, caKey)
|
|
if err != nil {
|
|
return "", "", "", err
|
|
}
|
|
|
|
caCertFile, err := createTempFile(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caCertDER}))
|
|
if err != nil {
|
|
return "", "", "", err
|
|
}
|
|
|
|
clientKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
if err != nil {
|
|
return "", "", "", err
|
|
}
|
|
|
|
clientTemplate := x509.Certificate{
|
|
SerialNumber: big.NewInt(2),
|
|
Subject: pkix.Name{
|
|
Organization: []string{"Test Org"},
|
|
},
|
|
NotBefore: time.Now(),
|
|
NotAfter: time.Now().Add(time.Hour * 24),
|
|
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth},
|
|
BasicConstraintsValid: true,
|
|
}
|
|
|
|
clientCertDER, err := x509.CreateCertificate(rand.Reader, &clientTemplate, &caTemplate, &clientKey.PublicKey, caKey)
|
|
if err != nil {
|
|
return "", "", "", err
|
|
}
|
|
|
|
clientCertFile, err := createTempFile(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: clientCertDER}))
|
|
if err != nil {
|
|
return "", "", "", err
|
|
}
|
|
|
|
clientKeyFile, err := createTempFile(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(clientKey)}))
|
|
if err != nil {
|
|
return "", "", "", err
|
|
}
|
|
|
|
return caCertFile, clientCertFile, clientKeyFile, nil
|
|
}
|
|
|
|
func createTempFile(data []byte) (string, error) {
|
|
file, err := createTempFileHandle()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
_, err = file.Write(data)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
err = file.Close()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return file.Name(), nil
|
|
}
|
|
|
|
func createTempFileHandle() (*os.File, error) {
|
|
return os.CreateTemp("", "test")
|
|
}
|
|
|
|
func TestCheckIfCertificateSelfSigned(t *testing.T) {
|
|
selfSignedCert := createSelfSignedCert(t)
|
|
|
|
tests := []struct {
|
|
name string
|
|
cert *x509.Certificate
|
|
err error
|
|
}{
|
|
{
|
|
name: "Self-signed certificate",
|
|
cert: selfSignedCert,
|
|
err: nil,
|
|
},
|
|
{
|
|
name: "missing certificate contents",
|
|
cert: &x509.Certificate{},
|
|
err: errors.New("x509: missing ASN.1 contents; use ParseCertificate"),
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
err := checkIfCertificateSigned(tt.cert, nil)
|
|
assert.True(t, errors.Contains(err, tt.err), fmt.Sprintf("expected error %v, got %v", tt.err, err))
|
|
})
|
|
}
|
|
}
|
|
|
|
func createSelfSignedCert(t *testing.T) *x509.Certificate {
|
|
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
require.NoError(t, err)
|
|
|
|
template := x509.Certificate{
|
|
SerialNumber: big.NewInt(1),
|
|
Subject: pkix.Name{
|
|
Organization: []string{"Test Org"},
|
|
},
|
|
NotBefore: time.Now(),
|
|
NotAfter: time.Now().Add(time.Hour * 24),
|
|
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
BasicConstraintsValid: true,
|
|
}
|
|
|
|
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
|
|
require.NoError(t, err)
|
|
|
|
cert, err := x509.ParseCertificate(certDER)
|
|
require.NoError(t, err)
|
|
|
|
return cert
|
|
}
|