package main import ( "context" "encoding/json" "net/http" "net/http/httptest" "strings" "testing" ) func newTestBroker() *broker { return &broker{cfg: loadConfig(), sshSigner: mockSSHSigner{}} } func TestHandleSSHHostCert_OK(t *testing.T) { b := newTestBroker() body, _ := json.Marshal(sshHostCertRequest{ PublicKey: "ecdsa-sha2-nistp256 AAAAB3Nz root@fleet", Principals: []string{"host01", "host01.fleet.lab"}, KeyID: "host01.fleet.lab", }) req := httptest.NewRequest(http.MethodPost, "/ssh/hostcert", strings.NewReader(string(body))) rec := httptest.NewRecorder() b.handleSSHHostCert(rec, req) if rec.Code != http.StatusOK { t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String()) } var resp sshHostCertResponse if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatal(err) } if !strings.HasPrefix(resp.Cert, "ecdsa-sha2-nistp256-cert-v01@openssh.com ") { t.Errorf("cert line = %q", resp.Cert) } if !strings.Contains(resp.Cert, "host01.fleet.lab") { t.Errorf("cert should carry keyID/principals: %q", resp.Cert) } } func TestHandleSSHHostCert_NoPrincipals(t *testing.T) { b := newTestBroker() body, _ := json.Marshal(sshHostCertRequest{PublicKey: "ecdsa-sha2-nistp256 AAAA x", KeyID: "h"}) req := httptest.NewRequest(http.MethodPost, "/ssh/hostcert", strings.NewReader(string(body))) rec := httptest.NewRecorder() b.handleSSHHostCert(rec, req) if rec.Code != http.StatusBadRequest { t.Fatalf("want 400 for missing principals, got %d", rec.Code) } } func TestHandleSSHHostCert_BadJSON(t *testing.T) { b := newTestBroker() req := httptest.NewRequest(http.MethodPost, "/ssh/hostcert", strings.NewReader("{not json")) rec := httptest.NewRecorder() b.handleSSHHostCert(rec, req) if rec.Code != http.StatusBadRequest { t.Fatalf("want 400 for bad JSON, got %d", rec.Code) } } func TestMockSSHSignerRejectsEmptyKey(t *testing.T) { if _, err := (mockSSHSigner{}).SignHost(context.Background(), "", "h", []string{"h"}); err == nil { t.Error("expected error on malformed public key") } }