Files
vHost/backend/internal/panel/certificate_inline_test.go
T

70 lines
2.4 KiB
Go

package panel
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"math/big"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestSynchronousHTTPCertificateIsValidatedAndInstalledWithoutOrderIndex(t *testing.T) {
key, e := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if e != nil {
t.Fatal(e)
}
cert := &x509.Certificate{SerialNumber: big.NewInt(42), Subject: pkix.Name{CommonName: "host.example.com"}, DNSNames: []string{"host.example.com"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(90 * 24 * time.Hour), KeyUsage: x509.KeyUsageDigitalSignature}
der, e := x509.CreateCertificate(rand.Reader, cert, cert, &key.PublicKey, key)
if e != nil {
t.Fatal(e)
}
rawKey, e := x509.MarshalPKCS8PrivateKey(key)
if e != nil {
t.Fatal(e)
}
chain := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
private := string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: rawKey}))
installed := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
switch r.Form.Get("action") {
case "apply_cert_api":
if r.Form.Get("auth_to") != "7" {
t.Error("issuance must resolve the site's current run directory")
}
_ = json.NewEncoder(w).Encode(map[string]any{"status": true, "msg": "申请成功", "cert": chain, "root": "", "private_key": private})
case "SetSSL":
installed++
if r.Form.Get("siteName") != "host.example.com" || r.Form.Get("key") != private || r.Form.Get("csr") == "" {
t.Error("invalid fixed-site installation")
}
_ = json.NewEncoder(w).Encode(map[string]any{"status": true})
default:
t.Error("unexpected certificate operation", r.Form.Get("action"))
w.WriteHeader(404)
}
}))
defer server.Close()
client := NewClient(server.URL, "test-key", false, 5*time.Second)
if e = client.RequestCertificate(context.Background(), 7, "/www/example", []string{"host.example.com"}); e != nil {
t.Fatal(e)
}
if installed != 1 {
t.Fatal("inline certificate was not installed")
}
if e = client.RequestCertificate(context.Background(), 7, "/www/example", []string{"outside.example.net"}); e == nil {
t.Fatal("certificate outside requested domains accepted")
}
if installed != 1 {
t.Fatal("invalid certificate reached panel installation")
}
}