feat: autogénérer certificat TLS si non-fourni

This commit is contained in:
Victor Lacasse-Beaudoin 2025-05-13 16:43:27 -04:00
parent 940c6d8a25
commit 47b8c2b766
3 changed files with 102 additions and 3 deletions

View file

@ -4,7 +4,7 @@ LABEL author="vlbeaudoin"
WORKDIR /go/src/app WORKDIR /go/src/app
COPY LICENSE cmd.go config.go db.go entity.go flag.go go.mod go.sum handler.go server.go ./ COPY LICENSE cmd.go config.go db.go entity.go flag.go go.mod go.sum handler.go server.go x509.go ./
ADD cmd/ cmd/ ADD cmd/ cmd/
ADD queries/ queries/ ADD queries/ queries/

View file

@ -3,7 +3,9 @@ package presences
import ( import (
"context" "context"
"crypto/subtle" "crypto/subtle"
"crypto/tls"
"fmt" "fmt"
"log"
"net/http" "net/http"
"git.agecem.com/bottin/bottin/v11" "git.agecem.com/bottin/bottin/v11"
@ -69,7 +71,30 @@ func RunUIServer(ctx context.Context, cfg Config, bottinClient *bottin.APIClient
address := fmt.Sprintf(":%d", cfg.Port) address := fmt.Sprintf(":%d", cfg.Port)
return e.StartTLS(address, cfg.TLS.Cert, cfg.TLS.Key) switch {
} case cfg.TLS.Cert != "" && cfg.TLS.Key != "":
return e.StartTLS(address, cfg.TLS.Cert, cfg.TLS.Key)
case cfg.TLS.Cert != "" && cfg.TLS.Key == "":
return fmt.Errorf("found TLS certificate but missing associated TLS private key")
case cfg.TLS.Cert == "" && cfg.TLS.Key != "":
return fmt.Errorf("found TLS private key but missing associated TLS certificate")
default:
log.Println("No TLS pair was provided. Generating self-signed pair.")
tlsPair, err := newTLSPair()
if err != nil {
return err
}
server := &http.Server{
Addr: address,
Handler: e,
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{tlsPair},
},
}
return server.ListenAndServeTLS("", "")
}
}
} }

74
x509.go Normal file
View file

@ -0,0 +1,74 @@
package presences
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"time"
)
func newTLSPair() (tls.Certificate, error) {
//TODO revise this code to make sure it is satisfying
// Generate an ECDSA private key using P256.
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return tls.Certificate{}, fmt.Errorf("Failed to generate private key: %v", err)
}
// Generate a random serial number.
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
return tls.Certificate{}, fmt.Errorf("Failed to generate serial number: %v", err)
}
// Create a certificate template.
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"AGECEM-bottin-presences"},
CommonName: "localhost", // common name localhost for local development
},
NotBefore: time.Now().Add(-time.Hour), // valid from 1 hour ago
NotAfter: time.Now().Add(365 * 24 * time.Hour), // valid for 1 year
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
IsCA: true, // self-signed, so we can mark it as CA (optional)
}
// Self-sign the certificate.
derCert, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return tls.Certificate{}, fmt.Errorf("Failed to create certificate: %v", err)
}
// Encode the certificate PEM block.
certPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: derCert,
})
// Encode the private key PEM block.
keyBytes, err := x509.MarshalECPrivateKey(priv)
if err != nil {
return tls.Certificate{}, fmt.Errorf("Unable to marshal ECDSA private key: %v", err)
}
keyPEM := pem.EncodeToMemory(&pem.Block{
Type: "EC PRIVATE KEY",
Bytes: keyBytes,
})
// Load the generated certificate into a tls.Certificate.
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
return tls.Certificate{}, fmt.Errorf("failed to load X509 key pair: %v", err)
}
return tlsCert, nil
}