Initial QSfera import

This commit is contained in:
Курнат Андрей
2026-06-07 10:20:04 +03:00
commit 2315f25754
16485 changed files with 4826827 additions and 0 deletions
+28
View File
@@ -0,0 +1,28 @@
// Package crypto implements utility functions for handling crypto related files.
package crypto
import (
"bytes"
"crypto/x509"
"errors"
"io"
)
// NewCertPoolFromPEM reads certificates from io.Reader and returns a x509.CertPool
// containing those certificates.
func NewCertPoolFromPEM(crts ...io.Reader) (*x509.CertPool, error) {
certPool := x509.NewCertPool()
var buf bytes.Buffer
for _, c := range crts {
if _, err := io.Copy(&buf, c); err != nil {
return nil, err
}
if !certPool.AppendCertsFromPEM(buf.Bytes()) {
return nil, errors.New("failed to append cert from PEM")
}
buf.Reset()
}
return certPool, nil
}
+13
View File
@@ -0,0 +1,13 @@
package crypto_test
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestCrypto(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Crypto Suite")
}
+103
View File
@@ -0,0 +1,103 @@
package crypto_test
import (
"fmt"
"os"
"path/filepath"
"github.com/qsfera/server/pkg/crypto"
"github.com/qsfera/server/pkg/log"
. "github.com/onsi/ginkgo/v2"
cfg "github.com/qsfera/server/pkg/config"
)
var _ = Describe("Crypto", func() {
var (
userConfigDir string
err error
config = cfg.DefaultConfig()
)
BeforeEach(func() {
userConfigDir, err = os.UserConfigDir()
if err != nil {
Fail(err.Error())
}
config.Proxy.HTTP.TLSKey = filepath.Join(userConfigDir, "qsfera", "server.key")
config.Proxy.HTTP.TLSCert = filepath.Join(userConfigDir, "qsfera", "server.cert")
})
AfterEach(func() {
if err := os.RemoveAll(filepath.Join(userConfigDir, "qsfera")); err != nil {
Fail(err.Error())
}
})
// This little test should nail down the main functionality of this package, which is providing with a default location
// for the key / certificate pair in case none is configured. Regardless of how the values ended in the configuration,
// the side effects of GenCert is what we want to test.
Describe("Creating key / certificate pair", func() {
Context("For the proxy service in the location of the user config directory", func() {
It(fmt.Sprintf("Creates the cert / key tuple in: %s", filepath.Join(userConfigDir, "qsfera")), func() {
if err := crypto.GenCert(config.Proxy.HTTP.TLSCert, config.Proxy.HTTP.TLSKey, log.NopLogger()); err != nil {
Fail(err.Error())
}
if _, err := os.Stat(filepath.Join(userConfigDir, "qsfera", "server.key")); err != nil {
Fail("key not found at the expected location")
}
if _, err := os.Stat(filepath.Join(userConfigDir, "qsfera", "server.cert")); err != nil {
Fail("certificate not found at the expected location")
}
})
})
})
Describe("Creating a new cert pool", func() {
var (
crtOne string
keyOne string
crtTwo string
keyTwo string
)
BeforeEach(func() {
crtOne = filepath.Join(userConfigDir, "qsfera/one.cert")
keyOne = filepath.Join(userConfigDir, "qsfera/one.key")
crtTwo = filepath.Join(userConfigDir, "qsfera/two.cert")
keyTwo = filepath.Join(userConfigDir, "qsfera/two.key")
if err := crypto.GenCert(crtOne, keyOne, log.NopLogger()); err != nil {
Fail(err.Error())
}
if err := crypto.GenCert(crtTwo, keyTwo, log.NopLogger()); err != nil {
Fail(err.Error())
}
})
It("handles one certificate", func() {
f1, _ := os.Open(crtOne)
defer f1.Close()
c, err := crypto.NewCertPoolFromPEM(f1)
if err != nil {
Fail(err.Error())
}
if len(c.Subjects()) != 1 {
Fail("expected 1 certificate in the cert pool")
}
})
It("handles multiple certificates", func() {
f1, _ := os.Open(crtOne)
f2, _ := os.Open(crtTwo)
defer f1.Close()
defer f2.Close()
c, err := crypto.NewCertPoolFromPEM(f1, f2)
if err != nil {
Fail(err.Error())
}
if len(c.Subjects()) != 2 {
Fail("expected 2 certificates in the cert pool")
}
})
})
})
+167
View File
@@ -0,0 +1,167 @@
package crypto
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"net"
"os"
"path/filepath"
"github.com/qsfera/server/pkg/log"
mtls "go-micro.dev/v4/util/tls"
)
var (
defaultHosts = []string{"127.0.0.1", "localhost"}
)
// GenCert generates TLS-Certificates. This function has side effects: it creates the respective certificate / key pair at
// the destination locations unless the tuple already exists, if that is the case, this is a noop.
func GenCert(certName string, keyName string, l log.Logger) error {
var pk *rsa.PrivateKey
var err error
pk, err = rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
_, certErr := os.Stat(certName)
_, keyErr := os.Stat(keyName)
if certErr == nil || keyErr == nil {
l.Info().Msg(
fmt.Sprintf("%v certificate / key pair already present. skipping acme certificate generation",
filepath.Base(certName)))
return nil
}
if err := persistCertificate(certName, l, pk); err != nil {
l.Fatal().Err(err).Msg("failed to store certificate")
}
if err := persistKey(keyName, l, pk); err != nil {
l.Fatal().Err(err).Msg("failed to store key")
}
return nil
}
// GenTempCertForAddr generates temporary TLS-Certificates in memory.
func GenTempCertForAddr(addr string) (tls.Certificate, error) {
subjects := defaultHosts
if host, _, err := net.SplitHostPort(addr); err == nil && host != "" {
subjects = []string{host}
}
return mtls.Certificate(subjects...)
}
// persistCertificate generates a certificate using pk as private key and proceeds to store it into a file named certName.
func persistCertificate(certName string, l log.Logger, pk any) error {
if err := ensureExistsDir(certName); err != nil {
return fmt.Errorf("creating certificate destination: %s", certName)
}
certificate, err := generateCertificate(pk)
if err != nil {
return fmt.Errorf("creating certificate: %s", filepath.Dir(certName))
}
certOut, err := os.Create(certName)
if err != nil {
return fmt.Errorf("failed to open `%v` for writing", certName)
}
err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certificate})
if err != nil {
return fmt.Errorf("failed to encode certificate")
}
err = certOut.Close()
if err != nil {
return fmt.Errorf("failed to write cert")
}
l.Info().Msg(fmt.Sprintf("written certificate to %v", certName))
return nil
}
// genCert generates a self signed certificate using a random rsa key.
func generateCertificate(pk any) ([]byte, error) {
for _, h := range defaultHosts {
if ip := net.ParseIP(h); ip != nil {
acmeTemplate.IPAddresses = append(acmeTemplate.IPAddresses, ip)
} else {
acmeTemplate.DNSNames = append(acmeTemplate.DNSNames, h)
}
}
return x509.CreateCertificate(rand.Reader, &acmeTemplate, &acmeTemplate, publicKey(pk), pk)
}
// persistKey persists the private key used to generate the certificate at the configured location.
func persistKey(destination string, l log.Logger, pk any) error {
if err := ensureExistsDir(destination); err != nil {
return fmt.Errorf("creating key destination: %s", destination)
}
keyOut, err := os.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return fmt.Errorf("failed to open %v for writing", destination)
}
err = pem.Encode(keyOut, pemBlockForKey(pk, l))
if err != nil {
return fmt.Errorf("failed to encode key")
}
err = keyOut.Close()
if err != nil {
return fmt.Errorf("failed to write key")
}
l.Info().Msg(fmt.Sprintf("written key to %v", destination))
return nil
}
func publicKey(pk any) any {
switch k := pk.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
default:
return nil
}
}
func pemBlockForKey(pk any, l log.Logger) *pem.Block {
switch k := pk.(type) {
case *rsa.PrivateKey:
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
case *ecdsa.PrivateKey:
b, err := x509.MarshalECPrivateKey(k)
if err != nil {
l.Fatal().Err(err).Msg("Unable to marshal ECDSA private key")
}
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
default:
return nil
}
}
func ensureExistsDir(uri string) error {
certPath := filepath.Dir(uri)
if _, err := os.Stat(certPath); os.IsNotExist(err) {
err = os.MkdirAll(certPath, 0700)
if err != nil {
return err
}
}
return nil
}
+155
View File
@@ -0,0 +1,155 @@
package crypto
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"os"
"path/filepath"
"testing"
"github.com/qsfera/server/pkg/log"
)
func TestEnsureExistsDir(t *testing.T) {
var tmpDir = t.TempDir()
type args struct {
uri string
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "creates a dir if it does not exist",
args: args{
uri: filepath.Join(tmpDir, "example"),
},
wantErr: false,
},
{
name: "noop if the target directory exists",
args: args{
uri: filepath.Join(tmpDir, "example"),
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := ensureExistsDir(tt.args.uri); (err != nil) != tt.wantErr {
t.Errorf("ensureExistsDir() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestPersistKey(t *testing.T) {
p256 := elliptic.P256()
var (
tmpDir = t.TempDir()
keyPath = filepath.Join(tmpDir, "qsfera", "testKey")
rsaPk, _ = rsa.GenerateKey(rand.Reader, 2048)
ecdsaPk, _ = ecdsa.GenerateKey(p256, rand.Reader)
)
type args struct {
keyName string
pk any
}
tests := []struct {
name string
args args
}{
{
name: "writes a private key (rsa) to the specified location",
args: args{
keyName: keyPath,
pk: rsaPk,
},
},
{
name: "writes a private key (ecdsa) to the specified location",
args: args{
keyName: keyPath,
pk: ecdsaPk,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := persistKey(tt.args.keyName, log.NopLogger(), tt.args.pk); err != nil {
t.Error(err)
}
})
// side effect: tt.args.keyName is created
if _, err := os.Stat(tt.args.keyName); err != nil {
t.Errorf("persistKey() error = %v", err)
}
}
}
func TestPersistCertificate(t *testing.T) {
p256 := elliptic.P256()
var (
tmpDir = t.TempDir()
certPath = filepath.Join(tmpDir, "qsfera", "testCert")
rsaPk, _ = rsa.GenerateKey(rand.Reader, 2048)
ecdsaPk, _ = ecdsa.GenerateKey(p256, rand.Reader)
)
type args struct {
certName string
pk any
}
tests := []struct {
name string
args args
wantErr bool
}{
{
name: "store a certificate with an rsa private key",
args: args{
certName: certPath,
pk: rsaPk,
},
wantErr: false,
},
{
name: "store a certificate with an ecdsa private key",
args: args{
certName: certPath,
pk: ecdsaPk,
},
wantErr: false,
},
{
name: "should fail",
args: args{
certName: certPath,
pk: 42,
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
if err := persistCertificate(tt.args.certName, log.NopLogger(), tt.args.pk); err != nil {
if !tt.wantErr {
t.Error(err)
}
}
})
// side effect: tt.args.keyName is created
if _, err := os.Stat(tt.args.certName); err != nil {
t.Errorf("persistCertificate() error = %v", err)
}
})
}
}
+25
View File
@@ -0,0 +1,25 @@
package crypto
import (
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"math/big"
"time"
)
var serialNumber, _ = rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
var acmeTemplate = x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Acme Corp"},
CommonName: "КуСфера",
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(24 * time.Hour * 365),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}