SPB Git

Repository Public

pki_test.go 5.6 KB 164 lines go

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Command Center (MCC)8 * File             : services/internal/pki/pki_test.go9 * Module           : services10 * Repository       : https://git.spboucher.ai/maclustr-command-center11 * Project Website  : https://clustr.spboucher.ai12 * Created          : 2026-11-1813 * Last Modified    : 2026-11-1814 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142package pki4344import (45	"crypto/ecdsa"46	"crypto/elliptic"47	"crypto/rand"48	"crypto/rsa"49	"crypto/x509"50	"crypto/x509/pkix"51	"encoding/pem"52	"os"53	"path/filepath"54	"sync"55	"testing"56	"time"5758	"github.com/google/uuid"59)6061func csr(t *testing.T, key any) []byte {62	der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{Subject: pkix.Name{CommonName: "evil-cn"}, DNSNames: []string{"ingest.mcc.internal"}}, key)63	if err != nil {64		t.Fatal(err)65	}66	return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE REQUEST", Bytes: der})67}6869func TestCAAndCertificates(t *testing.T) {70	dir := filepath.Join(t.TempDir(), "secrets")71	// Concurrent first start: everyone ends with the same CA.72	var wg sync.WaitGroup73	fps := make([]string, 6)74	for i := range fps {75		wg.Add(1)76		go func() {77			defer wg.Done()78			ca, err := LoadOrCreate(dir)79			if err != nil {80				t.Error(err)81				return82			}83			fps[i] = ca.Fingerprint()84		}()85	}86	wg.Wait()87	for _, f := range fps {88		if f != fps[0] || len(f) != 7+64 {89			t.Fatalf("CA creation race: %v", fps)90		}91	}92	if st, _ := os.Stat(dir); st.Mode().Perm() != 0o700 {93		t.Errorf("dir mode %o", st.Mode().Perm())94	}95	for _, f := range []string{caKeyFile, caCertFile} {96		if st, err := os.Stat(filepath.Join(dir, f)); err != nil || st.Mode().Perm() != 0o600 {97			t.Errorf("%s: %v", f, err)98		}99	}100	ca, _ := LoadOrCreate(dir)101	if b, err := ParseFingerprint(ca.Fingerprint()); err != nil || len(b) != 32 {102		t.Error(err)103	}104	if _, err := ParseFingerprint("sha256:abcd"); err == nil {105		t.Error("short fingerprint accepted")106	}107108	now := time.Now()109	srv, err := ca.IssueServer("ingest.mcc.internal", now)110	if err != nil {111		t.Fatal(err)112	}113	if _, err := srv.Leaf.Verify(x509.VerifyOptions{Roots: ca.Pool(), DNSName: "ingest.mcc.internal", KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}); err != nil {114		t.Errorf("server certificate: %v", err)115	}116	if len(srv.Certificate) != 2 || srv.Leaf.NotAfter.Sub(now) > ServerCertTTL+time.Minute {117		t.Error("server chain must carry the CA and be short-lived")118	}119120	key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)121	req, err := ParseCSR(csr(t, key))122	if err != nil {123		t.Fatal(err)124	}125	id := uuid.New()126	_, cert, err := ca.SignAgent(req, id, now)127	if err != nil {128		t.Fatal(err)129	}130	// Identity comes from the CA, never from the request.131	if cert.Subject.CommonName != id.String() || len(cert.DNSNames) != 0 || len(cert.URIs) != 1 || cert.URIs[0].String() != "mcc://agent/"+id.String() {132		t.Errorf("agent certificate identity: %v %v %v", cert.Subject, cert.DNSNames, cert.URIs)133	}134	if got, err := AgentIDFromCert(cert); err != nil || got != id {135		t.Error(err)136	}137	if d := cert.NotAfter.Sub(now); d < 30*24*time.Hour-time.Minute || d > 30*24*time.Hour+time.Minute {138		t.Errorf("agent certificate lifetime %s", d)139	}140	if len(cert.ExtKeyUsage) != 1 || cert.ExtKeyUsage[0] != x509.ExtKeyUsageClientAuth || cert.IsCA {141		t.Error("agent certificate must be clientAuth only and not a CA")142	}143	// An agent certificate cannot impersonate the server, nor the reverse.144	if _, err := cert.Verify(x509.VerifyOptions{Roots: ca.Pool(), KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}); err == nil {145		t.Error("agent certificate accepted as a server")146	}147	if _, err := srv.Leaf.Verify(x509.VerifyOptions{Roots: ca.Pool(), KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}); err == nil {148		t.Error("server certificate accepted as a client")149	}150	// Refused requests.151	rsaKey, _ := rsa.GenerateKey(rand.Reader, 2048)152	p384, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)153	for name, b := range map[string][]byte{"rsa": csr(t, rsaKey), "p384": csr(t, p384), "garbage": []byte("x"), "wrong pem": pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})} {154		if _, err := ParseCSR(b); err == nil {155			t.Errorf("%s CSR accepted", name)156		}157	}158	// A key readable by others is refused.159	os.Chmod(filepath.Join(dir, caKeyFile), 0o644)160	if _, err := LoadOrCreate(dir); err == nil {161		t.Error("world-readable CA key accepted")162	}163}164
Files main
Menu

Theme