Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Cover SSO conversion, TrueNAS app mapping and config store round-trips

rcourtmanb5d30649eebe
diff --git a/internal/api/router_routes_auth_security_branchcov0722pm_test.go b/internal/api/router_routes_auth_security_branchcov0722pm_test.go
new file mode 100644
index 0000000000..f0665eb270
--- /dev/null
+++ b/internal/api/router_routes_auth_security_branchcov0722pm_test.go
@@ -0,0 +1,783 @@
+package api
+
+import (
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/extensions"
+)
+
+// These tests target the small pure converter functions in
+// router_routes_auth_security.go that translate between the internal/api SSO
+// DTOs and the config/extensions types. Each converter has a nil-input arm and
+// a fully-populated arm; both are exercised with concrete inputs and asserted
+// field-by-field. Slice/map clone independence is asserted where the converter
+// performs a copy, and aliasing (where the converter assigns by reference) is
+// documented via characterization assertions plus a note in the report.
+
+// --- shared fixture helpers ---
+
+func branchcov0722PMCertInfo(subject string) CertificateInfo {
+ return CertificateInfo{
+ Subject: subject,
+ Issuer: "issuer-" + subject,
+ NotBefore: time.Date(2024, time.January, 1, 0, 0, 0, 0, time.UTC),
+ NotAfter: time.Date(2025, time.January, 1, 0, 0, 0, 0, time.UTC),
+ IsExpired: subject == "expired",
+ }
+}
+
+func branchcov0722PMExtCertInfo(subject string) extensions.CertificateInfo {
+ return extensions.CertificateInfo{
+ Subject: subject,
+ Issuer: "issuer-" + subject,
+ NotBefore: time.Date(2024, time.January, 1, 0, 0, 0, 0, time.UTC),
+ NotAfter: time.Date(2025, time.January, 1, 0, 0, 0, 0, time.UTC),
+ IsExpired: subject == "expired",
+ }
+}
+
+// branchcov0722PMPopulatedSAML builds a fully-populated config.SAMLProviderConfig
+// with a distinct value in every field so that a missing or misplaced copy is
+// detectable.
+func branchcov0722PMPopulatedCoreSAML() *config.SAMLProviderConfig {
+ return &config.SAMLProviderConfig{
+ IDPMetadataURL: "https://idp.example.com/metadata",
+ IDPMetadataXML: "<EntityDescriptor>core</EntityDescriptor>",
+ IDPSSOURL: "https://idp.example.com/sso",
+ IDPSLOURL: "https://idp.example.com/slo",
+ IDPCertificate: "core-idp-cert",
+ IDPCertFile: "/etc/pulse/core-idp-cert.pem",
+ IDPEntityID: "core-entity-id",
+ IDPIssuer: "core-issuer",
+ SPEntityID: "core-sp-entity-id",
+ SPACSPath: "/api/saml/core/acs",
+ SPMetadataPath: "/api/saml/core/metadata",
+ SPCertificate: "core-sp-cert",
+ SPPrivateKey: "core-sp-key",
+ SPCertFile: "/etc/pulse/core-sp-cert.pem",
+ SPKeyFile: "/etc/pulse/core-sp-key.pem",
+ SignRequests: true,
+ WantAssertionsSigned: true,
+ AllowUnencrypted: true,
+ UsernameAttr: "core-username",
+ EmailAttr: "core-email",
+ GroupsAttr: "core-groups",
+ FirstNameAttr: "core-first",
+ LastNameAttr: "core-last",
+ NameIDFormat: "core-nameid",
+ ForceAuthn: true,
+ AllowIDPInitiated: true,
+ RelayStateTemplate: "core-relay",
+ }
+}
+
+func branchcov0722PMPopulatedExtSAML() *extensions.SAMLProviderConfig {
+ return &extensions.SAMLProviderConfig{
+ IDPMetadataURL: "https://idp.example.com/metadata",
+ IDPMetadataXML: "<EntityDescriptor>ext</EntityDescriptor>",
+ IDPSSOURL: "https://idp.example.com/sso",
+ IDPSLOURL: "https://idp.example.com/slo",
+ IDPCertificate: "ext-idp-cert",
+ IDPCertFile: "/etc/pulse/ext-idp-cert.pem",
+ IDPEntityID: "ext-entity-id",
+ IDPIssuer: "ext-issuer",
+ SPEntityID: "ext-sp-entity-id",
+ SPACSPath: "/api/saml/ext/acs",
+ SPMetadataPath: "/api/saml/ext/metadata",
+ SPCertificate: "ext-sp-cert",
+ SPPrivateKey: "ext-sp-key",
+ SPCertFile: "/etc/pulse/ext-sp-cert.pem",
+ SPKeyFile: "/etc/pulse/ext-sp-key.pem",
+ SignRequests: true,
+ WantAssertionsSigned: true,
+ AllowUnencrypted: true,
+ UsernameAttr: "ext-username",
+ EmailAttr: "ext-email",
+ GroupsAttr: "ext-groups",
+ FirstNameAttr: "ext-first",
+ LastNameAttr: "ext-last",
+ NameIDFormat: "ext-nameid",
+ ForceAuthn: true,
+ AllowIDPInitiated: true,
+ RelayStateTemplate: "ext-relay",
+ }
+}
+
+func branchcov0722PMPopulatedCoreOIDC() *config.OIDCProviderConfig {
+ return &config.OIDCProviderConfig{
+ IssuerURL: "https://issuer.example.com",
+ ClientID: "core-client-id",
+ ClientSecret: "core-secret",
+ RedirectURL: "https://pulse.example.com/api/oidc/callback",
+ LogoutURL: "https://issuer.example.com/logout",
+ Scopes: []string{"openid", "profile", "email"},
+ UsernameClaim: "preferred_username",
+ EmailClaim: "email",
+ CABundle: "/etc/pulse/core-ca.pem",
+ ClientSecretSet: true,
+ }
+}
+
+func branchcov0722PMPopulatedCoreProvider() config.SSOProvider {
+ return config.SSOProvider{
+ ID: "provider-1",
+ Name: "Corporate SSO",
+ Type: config.SSOProviderTypeSAML,
+ Enabled: true,
+ DisplayName: "Login with Corp",
+ IconURL: "https://example.com/icon.png",
+ Priority: 3,
+ AllowedGroups: []string{"admins", "users"},
+ AllowedDomains: []string{"example.com"},
+ AllowedEmails: []string{"[email protected]"},
+ GroupsClaim: "groups",
+ GroupRoleMappings: map[string]string{"admins": "admin", "users": "viewer"},
+ OIDC: branchcov0722PMPopulatedCoreOIDC(),
+ SAML: branchcov0722PMPopulatedCoreSAML(),
+ }
+}
+
+// ----------------------------------------------------------------------------
+// toAPISAMLTestConfig
+// ----------------------------------------------------------------------------
+
+func TestBranchcov0722PM_ToAPISAMLTestConfig(t *testing.T) {
+ t.Run("nil_returns_nil", func(t *testing.T) {
+ if got := toAPISAMLTestConfig(nil); got != nil {
+ t.Fatalf("toAPISAMLTestConfig(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("populated_copies_fields", func(t *testing.T) {
+ src := &extensions.SAMLTestConfig{
+ IDPMetadataURL: "https://idp.example.com/metadata",
+ IDPMetadataXML: "<EntityDescriptor>",
+ IDPSSOURL: "https://idp.example.com/sso",
+ IDPCertificate: "idp-cert-pem",
+ }
+ got := toAPISAMLTestConfig(src)
+ if got == nil {
+ t.Fatal("toAPISAMLTestConfig(populated) returned nil, want non-nil")
+ }
+ if got.IDPMetadataURL != src.IDPMetadataURL {
+ t.Errorf("IDPMetadataURL = %q, want %q", got.IDPMetadataURL, src.IDPMetadataURL)
+ }
+ if got.IDPMetadataXML != src.IDPMetadataXML {
+ t.Errorf("IDPMetadataXML = %q, want %q", got.IDPMetadataXML, src.IDPMetadataXML)
+ }
+ if got.IDPSSOURL != src.IDPSSOURL {
+ t.Errorf("IDPSSOURL = %q, want %q", got.IDPSSOURL, src.IDPSSOURL)
+ }
+ if got.IDPCertificate != src.IDPCertificate {
+ t.Errorf("IDPCertificate = %q, want %q", got.IDPCertificate, src.IDPCertificate)
+ }
+ // The api DTO has IDPSLOURL but the extensions DTO does not; the
+ // converter must leave it as the zero value.
+ if got.IDPSLOURL != "" {
+ t.Errorf("IDPSLOURL = %q, want empty (not present on source type)", got.IDPSLOURL)
+ }
+ // Strings are copied by value; mutating the source after conversion must
+ // not affect the converted result.
+ src.IDPMetadataURL = "https://mutated.example.com/metadata"
+ src.IDPCertificate = "mutated-cert"
+ if got.IDPMetadataURL != "https://idp.example.com/metadata" {
+ t.Errorf("IDPMetadataURL mutated after conversion to %q, expected independence", got.IDPMetadataURL)
+ }
+ if got.IDPCertificate != "idp-cert-pem" {
+ t.Errorf("IDPCertificate mutated after conversion to %q, expected independence", got.IDPCertificate)
+ }
+ })
+}
+
+// ----------------------------------------------------------------------------
+// toAPIOIDCTestConfig
+// ----------------------------------------------------------------------------
+
+func TestBranchcov0722PM_ToAPIOIDCTestConfig(t *testing.T) {
+ t.Run("nil_returns_nil", func(t *testing.T) {
+ if got := toAPIOIDCTestConfig(nil); got != nil {
+ t.Fatalf("toAPIOIDCTestConfig(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("populated_copies_fields", func(t *testing.T) {
+ src := &extensions.OIDCTestConfig{
+ IssuerURL: "https://issuer.example.com",
+ ClientID: "client-123",
+ }
+ got := toAPIOIDCTestConfig(src)
+ if got == nil {
+ t.Fatal("toAPIOIDCTestConfig(populated) returned nil, want non-nil")
+ }
+ if got.IssuerURL != src.IssuerURL {
+ t.Errorf("IssuerURL = %q, want %q", got.IssuerURL, src.IssuerURL)
+ }
+ if got.ClientID != src.ClientID {
+ t.Errorf("ClientID = %q, want %q", got.ClientID, src.ClientID)
+ }
+ src.IssuerURL = "https://mutated.example.com"
+ if got.IssuerURL != "https://issuer.example.com" {
+ t.Errorf("IssuerURL mutated after conversion to %q, expected independence", got.IssuerURL)
+ }
+ })
+}
+
+// ----------------------------------------------------------------------------
+// toExtensionSSOTestResponse
+// ----------------------------------------------------------------------------
+
+func TestBranchcov0722PM_ToExtensionSSOTestResponse(t *testing.T) {
+ t.Run("details_nil_propagates", func(t *testing.T) {
+ resp := SSOTestResponse{
+ Success: true,
+ Message: "connection ok",
+ Error: "",
+ Details: nil,
+ }
+ got := toExtensionSSOTestResponse(resp)
+ if !got.Success {
+ t.Errorf("Success = false, want true")
+ }
+ if got.Message != "connection ok" {
+ t.Errorf("Message = %q, want %q", got.Message, "connection ok")
+ }
+ if got.Error != "" {
+ t.Errorf("Error = %q, want empty", got.Error)
+ }
+ if got.Details != nil {
+ t.Fatalf("Details = %#v, want nil", got.Details)
+ }
+ })
+
+ t.Run("with_error_message", func(t *testing.T) {
+ resp := SSOTestResponse{
+ Success: false,
+ Message: "failed",
+ Error: "dial tcp: connection refused",
+ }
+ got := toExtensionSSOTestResponse(resp)
+ if got.Success {
+ t.Errorf("Success = true, want false")
+ }
+ if got.Error != "dial tcp: connection refused" {
+ t.Errorf("Error = %q, want the connection-refused error", got.Error)
+ }
+ })
+
+ t.Run("details_populated_copies_fields", func(t *testing.T) {
+ resp := SSOTestResponse{
+ Success: true,
+ Message: "ok",
+ Details: &SSOTestDetails{
+ Type: "oidc",
+ EntityID: "entity-1",
+ SSOURL: "https://idp/sso",
+ SLOURL: "https://idp/slo",
+ TokenEndpoint: "https://idp/token",
+ UserinfoEndpoint: "https://idp/userinfo",
+ JWKSURI: "https://idp/jwks",
+ SupportedScopes: []string{"openid", "email"},
+ Certificates: []CertificateInfo{branchcov0722PMCertInfo("subject-a")},
+ },
+ }
+ got := toExtensionSSOTestResponse(resp)
+ if got.Details == nil {
+ t.Fatal("Details = nil, want non-nil")
+ }
+ d := got.Details
+ if d.Type != "oidc" {
+ t.Errorf("Details.Type = %q, want oidc", d.Type)
+ }
+ if d.EntityID != "entity-1" {
+ t.Errorf("Details.EntityID = %q, want entity-1", d.EntityID)
+ }
+ if d.SSOURL != "https://idp/sso" {
+ t.Errorf("Details.SSOURL = %q, want https://idp/sso", d.SSOURL)
+ }
+ if d.SLOURL != "https://idp/slo" {
+ t.Errorf("Details.SLOURL = %q, want https://idp/slo", d.SLOURL)
+ }
+ if d.TokenEndpoint != "https://idp/token" {
+ t.Errorf("Details.TokenEndpoint = %q, want https://idp/token", d.TokenEndpoint)
+ }
+ if d.UserinfoEndpoint != "https://idp/userinfo" {
+ t.Errorf("Details.UserinfoEndpoint = %q, want https://idp/userinfo", d.UserinfoEndpoint)
+ }
+ if d.JWKSURI != "https://idp/jwks" {
+ t.Errorf("Details.JWKSURI = %q, want https://idp/jwks", d.JWKSURI)
+ }
+ if len(d.SupportedScopes) != 2 || d.SupportedScopes[0] != "openid" || d.SupportedScopes[1] != "email" {
+ t.Errorf("Details.SupportedScopes = %#v, want [openid email]", d.SupportedScopes)
+ }
+ if !reflect.DeepEqual(d.Certificates, []extensions.CertificateInfo{branchcov0722PMExtCertInfo("subject-a")}) {
+ t.Errorf("Details.Certificates = %#v, want single subject-a cert", d.Certificates)
+ }
+ })
+}
+
+// ----------------------------------------------------------------------------
+// toExtensionSSOTestDetails
+// ----------------------------------------------------------------------------
+
+func TestBranchcov0722PM_ToExtensionSSOTestDetails(t *testing.T) {
+ t.Run("nil_returns_nil", func(t *testing.T) {
+ if got := toExtensionSSOTestDetails(nil); got != nil {
+ t.Fatalf("toExtensionSSOTestDetails(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("populated_without_certificates", func(t *testing.T) {
+ src := &SSOTestDetails{
+ Type: "saml",
+ EntityID: "saml-entity",
+ SSOURL: "https://saml/sso",
+ SupportedScopes: nil,
+ }
+ got := toExtensionSSOTestDetails(src)
+ if got == nil {
+ t.Fatal("returned nil, want non-nil")
+ }
+ if got.Type != "saml" {
+ t.Errorf("Type = %q, want saml", got.Type)
+ }
+ if got.EntityID != "saml-entity" {
+ t.Errorf("EntityID = %q, want saml-entity", got.EntityID)
+ }
+ if got.SSOURL != "https://saml/sso" {
+ t.Errorf("SSOURL = %q, want https://saml/sso", got.SSOURL)
+ }
+ if got.Certificates != nil {
+ t.Errorf("Certificates = %#v, want nil when source empty", got.Certificates)
+ }
+ })
+
+ t.Run("certificates_are_independently_copied", func(t *testing.T) {
+ src := &SSOTestDetails{
+ Type: "saml",
+ Certificates: []CertificateInfo{branchcov0722PMCertInfo("subject-a"), branchcov0722PMCertInfo("expired")},
+ }
+ got := toExtensionSSOTestDetails(src)
+ if len(got.Certificates) != 2 {
+ t.Fatalf("len(Certificates) = %d, want 2", len(got.Certificates))
+ }
+ // Field-by-field verification of the first certificate.
+ want := branchcov0722PMExtCertInfo("subject-a")
+ c0 := got.Certificates[0]
+ if c0.Subject != want.Subject || c0.Issuer != want.Issuer || c0.IsExpired != want.IsExpired {
+ t.Errorf("Certificates[0] = %+v, want %+v", c0, want)
+ }
+ if !c0.NotBefore.Equal(want.NotBefore) || !c0.NotAfter.Equal(want.NotAfter) {
+ t.Errorf("Certificates[0] timestamps = %v..%v, want %v..%v", c0.NotBefore, c0.NotAfter, want.NotBefore, want.NotAfter)
+ }
+ if !got.Certificates[1].IsExpired {
+ t.Errorf("Certificates[1].IsExpired = false, want true")
+ }
+
+ // Clone independence: mutate the source slice and elements after
+ // conversion. The converted Certificates must be unaffected (the
+ // converter allocates a fresh slice and copies each CertificateInfo by
+ // value).
+ src.Certificates[0] = branchcov0722PMCertInfo("tampered")
+ src.Certificates = append(src.Certificates, branchcov0722PMCertInfo("extra"))
+ if got.Certificates[0].Subject != "subject-a" {
+ t.Errorf("Certificates[0].Subject mutated to %q after source change; converter must deep-copy", got.Certificates[0].Subject)
+ }
+ if len(got.Certificates) != 2 {
+ t.Errorf("len(Certificates) changed to %d after source append; converter must not alias backing array", len(got.Certificates))
+ }
+ })
+
+ t.Run("supported_scopes_alias_source_backing_array", func(t *testing.T) {
+ // CHARACTERIZATION (not desired behaviour): the converter assigns
+ // SupportedScopes by reference, so element mutation of the source slice
+ // is visible through the converted value. This locks in the current
+ // aliasing and is reported as a suspected source bug (see report).
+ src := &SSOTestDetails{
+ Type: "oidc",
+ SupportedScopes: []string{"openid", "email"},
+ }
+ got := toExtensionSSOTestDetails(src)
+ src.SupportedScopes[0] = "mutated"
+ if got.SupportedScopes[0] != "mutated" {
+ t.Errorf("SupportedScopes[0] = %q, want %q (documents aliasing bug)", got.SupportedScopes[0], "mutated")
+ }
+ // Reassigning the source slice header, however, must NOT affect the
+ // converted slice (different headers).
+ src.SupportedScopes = []string{"entirely", "new"}
+ if len(got.SupportedScopes) != 2 || got.SupportedScopes[0] != "mutated" {
+ t.Errorf("SupportedScopes = %#v, want unchanged [mutated email] after header reassign", got.SupportedScopes)
+ }
+ })
+}
+
+// ----------------------------------------------------------------------------
+// toExtensionSSOConfigSnapshot
+// ----------------------------------------------------------------------------
+
+func TestBranchcov0722PM_ToExtensionSSOConfigSnapshot(t *testing.T) {
+ t.Run("nil_returns_defaulted_empty_snapshot", func(t *testing.T) {
+ got := toExtensionSSOConfigSnapshot(nil)
+ // The nil arm must return a non-nil, empty Providers slice and
+ // AllowMultipleProviders=true (a safe default).
+ if got.Providers == nil {
+ t.Fatal("Providers = nil, want non-nil empty slice")
+ }
+ if len(got.Providers) != 0 {
+ t.Fatalf("len(Providers) = %d, want 0", len(got.Providers))
+ }
+ if !got.AllowMultipleProviders {
+ t.Errorf("AllowMultipleProviders = false, want true (default)")
+ }
+ if got.DefaultProviderID != "" {
+ t.Errorf("DefaultProviderID = %q, want empty", got.DefaultProviderID)
+ }
+ })
+
+ t.Run("populated_maps_providers_and_metadata", func(t *testing.T) {
+ cfg := &config.SSOConfig{
+ DefaultProviderID: "provider-1",
+ AllowMultipleProviders: false,
+ Providers: []config.SSOProvider{
+ branchcov0722PMPopulatedCoreProvider(),
+ {
+ ID: "provider-2",
+ Name: "OIDC Only",
+ Type: config.SSOProviderTypeOIDC,
+ Enabled: false,
+ OIDC: branchcov0722PMPopulatedCoreOIDC(),
+ },
+ },
+ }
+ got := toExtensionSSOConfigSnapshot(cfg)
+ if got.DefaultProviderID != "provider-1" {
+ t.Errorf("DefaultProviderID = %q, want provider-1", got.DefaultProviderID)
+ }
+ if got.AllowMultipleProviders {
+ t.Errorf("AllowMultipleProviders = true, want false")
+ }
+ if len(got.Providers) != 2 {
+ t.Fatalf("len(Providers) = %d, want 2", len(got.Providers))
+ }
+ if got.Providers[0].ID != "provider-1" {
+ t.Errorf("Providers[0].ID = %q, want provider-1", got.Providers[0].ID)
+ }
+ if got.Providers[1].ID != "provider-2" {
+ t.Errorf("Providers[1].ID = %q, want provider-2", got.Providers[1].ID)
+ }
+ // Provider detail is verified exhaustively in TestBranchcov0722PM_ToExtensionSSOProvider;
+ // here spot-check the type conversion and nested config presence.
+ if got.Providers[0].Type != extensions.SSOProviderTypeSAML {
+ t.Errorf("Providers[0].Type = %q, want %q", got.Providers[0].Type, extensions.SSOProviderTypeSAML)
+ }
+ if got.Providers[0].SAML == nil {
+ t.Errorf("Providers[0].SAML = nil, want populated")
+ }
+ if got.Providers[1].OIDC == nil {
+ t.Errorf("Providers[1].OIDC = nil, want populated")
+ }
+ if got.Providers[1].SAML != nil {
+ t.Errorf("Providers[1].SAML = %#v, want nil (OIDC-only provider)", got.Providers[1].SAML)
+ }
+ })
+
+ t.Run("providers_slice_is_independent_of_source", func(t *testing.T) {
+ cfg := &config.SSOConfig{
+ Providers: []config.SSOProvider{branchcov0722PMPopulatedCoreProvider()},
+ AllowMultipleProviders: true,
+ }
+ got := toExtensionSSOConfigSnapshot(cfg)
+ // Mutate the source slice; the converted snapshot must not change.
+ cfg.Providers[0].ID = "mutated"
+ cfg.Providers = append(cfg.Providers, config.SSOProvider{ID: "extra"})
+ if got.Providers[0].ID != "provider-1" {
+ t.Errorf("Providers[0].ID changed to %q after source mutation; converter must copy the slice", got.Providers[0].ID)
+ }
+ if len(got.Providers) != 1 {
+ t.Errorf("len(Providers) = %d, want 1 after source append (slice must be copied)", len(got.Providers))
+ }
+ })
+
+ t.Run("provider_collection_fields_alias_source", func(t *testing.T) {
+ // CHARACTERIZATION: AllowedGroups and GroupRoleMappings on each
+ // provider are assigned by reference by toExtensionSSOProvider, so the
+ // converted snapshot shares their backing storage with the source. This
+ // documents the aliasing (reported as a suspected source bug).
+ cfg := &config.SSOConfig{
+ Providers: []config.SSOProvider{branchcov0722PMPopulatedCoreProvider()},
+ AllowMultipleProviders: true,
+ }
+ got := toExtensionSSOConfigSnapshot(cfg)
+ cfg.Providers[0].AllowedGroups[0] = "mutated-group"
+ cfg.Providers[0].GroupRoleMappings["admins"] = "mutated-role"
+ if got.Providers[0].AllowedGroups[0] != "mutated-group" {
+ t.Errorf("AllowedGroups[0] = %q, want %q (documents aliasing bug)", got.Providers[0].AllowedGroups[0], "mutated-group")
+ }
+ if got.Providers[0].GroupRoleMappings["admins"] != "mutated-role" {
+ t.Errorf("GroupRoleMappings[admins] = %q, want %q (documents aliasing bug)", got.Providers[0].GroupRoleMappings["admins"], "mutated-role")
+ }
+ })
+}
+
+// ----------------------------------------------------------------------------
+// toExtensionSSOProvider
+// ----------------------------------------------------------------------------
+
+func TestBranchcov0722PM_ToExtensionSSOProvider(t *testing.T) {
+ t.Run("nil_nested_configs_omit_oidc_and_saml", func(t *testing.T) {
+ p := config.SSOProvider{
+ ID: "bare",
+ Name: "Bare",
+ Type: config.SSOProviderTypeOIDC,
+ Enabled: true,
+ }
+ got := toExtensionSSOProvider(p)
+ if got.ID != "bare" {
+ t.Errorf("ID = %q, want bare", got.ID)
+ }
+ if got.Type != extensions.SSOProviderTypeOIDC {
+ t.Errorf("Type = %q, want %q", got.Type, extensions.SSOProviderTypeOIDC)
+ }
+ if !got.Enabled {
+ t.Errorf("Enabled = false, want true")
+ }
+ if got.OIDC != nil {
+ t.Errorf("OIDC = %#v, want nil when source OIDC is nil", got.OIDC)
+ }
+ if got.SAML != nil {
+ t.Errorf("SAML = %#v, want nil when source SAML is nil", got.SAML)
+ }
+ })
+
+ t.Run("populated_copies_all_fields", func(t *testing.T) {
+ p := branchcov0722PMPopulatedCoreProvider()
+ got := toExtensionSSOProvider(p)
+
+ // Top-level scalar fields.
+ if got.ID != "provider-1" {
+ t.Errorf("ID = %q, want provider-1", got.ID)
+ }
+ if got.Name != "Corporate SSO" {
+ t.Errorf("Name = %q, want Corporate SSO", got.Name)
+ }
+ if got.Type != extensions.SSOProviderTypeSAML {
+ t.Errorf("Type = %q, want %q", got.Type, extensions.SSOProviderTypeSAML)
+ }
+ if !got.Enabled {
+ t.Errorf("Enabled = false, want true")
+ }
+ if got.DisplayName != "Login with Corp" {
+ t.Errorf("DisplayName = %q, want Login with Corp", got.DisplayName)
+ }
+ if got.IconURL != "https://example.com/icon.png" {
+ t.Errorf("IconURL = %q, want icon url", got.IconURL)
+ }
+ if got.Priority != 3 {
+ t.Errorf("Priority = %d, want 3", got.Priority)
+ }
+ if got.GroupsClaim != "groups" {
+ t.Errorf("GroupsClaim = %q, want groups", got.GroupsClaim)
+ }
+
+ // Top-level collection fields.
+ if !reflect.DeepEqual(got.AllowedGroups, []string{"admins", "users"}) {
+ t.Errorf("AllowedGroups = %#v, want [admins users]", got.AllowedGroups)
+ }
+ if !reflect.DeepEqual(got.AllowedDomains, []string{"example.com"}) {
+ t.Errorf("AllowedDomains = %#v, want [example.com]", got.AllowedDomains)
+ }
+ if !reflect.DeepEqual(got.AllowedEmails, []string{"[email protected]"}) {
+ t.Errorf("AllowedEmails = %#v, want [[email protected]]", got.AllowedEmails)
+ }
+ wantMappings := map[string]string{"admins": "admin", "users": "viewer"}
+ if !reflect.DeepEqual(got.GroupRoleMappings, wantMappings) {
+ t.Errorf("GroupRoleMappings = %#v, want %#v", got.GroupRoleMappings, wantMappings)
+ }
+
+ // OIDC nested config, field by field.
+ if got.OIDC == nil {
+ t.Fatal("OIDC = nil, want populated")
+ }
+ oidc := got.OIDC
+ srcOIDC := p.OIDC
+ if oidc.IssuerURL != srcOIDC.IssuerURL {
+ t.Errorf("OIDC.IssuerURL = %q, want %q", oidc.IssuerURL, srcOIDC.IssuerURL)
+ }
+ if oidc.ClientID != srcOIDC.ClientID {
+ t.Errorf("OIDC.ClientID = %q, want %q", oidc.ClientID, srcOIDC.ClientID)
+ }
+ if oidc.ClientSecret != srcOIDC.ClientSecret {
+ t.Errorf("OIDC.ClientSecret = %q, want %q", oidc.ClientSecret, srcOIDC.ClientSecret)
+ }
+ if oidc.RedirectURL != srcOIDC.RedirectURL {
+ t.Errorf("OIDC.RedirectURL = %q, want %q", oidc.RedirectURL, srcOIDC.RedirectURL)
+ }
+ if oidc.LogoutURL != srcOIDC.LogoutURL {
+ t.Errorf("OIDC.LogoutURL = %q, want %q", oidc.LogoutURL, srcOIDC.LogoutURL)
+ }
+ if !reflect.DeepEqual(oidc.Scopes, srcOIDC.Scopes) {
+ t.Errorf("OIDC.Scopes = %#v, want %#v", oidc.Scopes, srcOIDC.Scopes)
+ }
+ if oidc.UsernameClaim != srcOIDC.UsernameClaim {
+ t.Errorf("OIDC.UsernameClaim = %q, want %q", oidc.UsernameClaim, srcOIDC.UsernameClaim)
+ }
+ if oidc.EmailClaim != srcOIDC.EmailClaim {
+ t.Errorf("OIDC.EmailClaim = %q, want %q", oidc.EmailClaim, srcOIDC.EmailClaim)
+ }
+ if oidc.CABundle != srcOIDC.CABundle {
+ t.Errorf("OIDC.CABundle = %q, want %q", oidc.CABundle, srcOIDC.CABundle)
+ }
+ if !oidc.ClientSecretSet {
+ t.Errorf("OIDC.ClientSecretSet = false, want true")
+ }
+
+ // SAML nested config: verify every copied field via DeepEqual against a
+ // hand-built expected value (built from the same source fixture).
+ if got.SAML == nil {
+ t.Fatal("SAML = nil, want populated")
+ }
+ srcSAML := p.SAML
+ wantSAML := &extensions.SAMLProviderConfig{
+ IDPMetadataURL: srcSAML.IDPMetadataURL,
+ IDPMetadataXML: srcSAML.IDPMetadataXML,
+ IDPSSOURL: srcSAML.IDPSSOURL,
+ IDPSLOURL: srcSAML.IDPSLOURL,
+ IDPCertificate: srcSAML.IDPCertificate,
+ IDPCertFile: srcSAML.IDPCertFile,
+ IDPEntityID: srcSAML.IDPEntityID,
+ IDPIssuer: srcSAML.IDPIssuer,
+ SPEntityID: srcSAML.SPEntityID,
+ SPACSPath: srcSAML.SPACSPath,
+ SPMetadataPath: srcSAML.SPMetadataPath,
+ SPCertificate: srcSAML.SPCertificate,
+ SPPrivateKey: srcSAML.SPPrivateKey,
+ SPCertFile: srcSAML.SPCertFile,
+ SPKeyFile: srcSAML.SPKeyFile,
+ SignRequests: srcSAML.SignRequests,
+ WantAssertionsSigned: srcSAML.WantAssertionsSigned,
+ AllowUnencrypted: srcSAML.AllowUnencrypted,
+ UsernameAttr: srcSAML.UsernameAttr,
+ EmailAttr: srcSAML.EmailAttr,
+ GroupsAttr: srcSAML.GroupsAttr,
+ FirstNameAttr: srcSAML.FirstNameAttr,
+ LastNameAttr: srcSAML.LastNameAttr,
+ NameIDFormat: srcSAML.NameIDFormat,
+ ForceAuthn: srcSAML.ForceAuthn,
+ AllowIDPInitiated: srcSAML.AllowIDPInitiated,
+ RelayStateTemplate: srcSAML.RelayStateTemplate,
+ }
+ if !reflect.DeepEqual(got.SAML, wantSAML) {
+ t.Errorf("SAML = %+v, want %+v", got.SAML, wantSAML)
+ }
+ })
+
+ t.Run("collections_alias_source_backing_storage", func(t *testing.T) {
+ // CHARACTERIZATION: AllowedGroups, AllowedDomains, AllowedEmails,
+ // GroupRoleMappings and OIDC.Scopes are assigned by reference, so the
+ // converted provider shares backing storage with the source. Reported
+ // as a suspected source bug.
+ p := branchcov0722PMPopulatedCoreProvider()
+ got := toExtensionSSOProvider(p)
+
+ p.AllowedGroups[0] = "mutated-group"
+ if got.AllowedGroups[0] != "mutated-group" {
+ t.Errorf("AllowedGroups[0] = %q, want %q (documents aliasing bug)", got.AllowedGroups[0], "mutated-group")
+ }
+
+ p.GroupRoleMappings["admins"] = "mutated-role"
+ if got.GroupRoleMappings["admins"] != "mutated-role" {
+ t.Errorf("GroupRoleMappings[admins] = %q, want %q (documents aliasing bug)", got.GroupRoleMappings["admins"], "mutated-role")
+ }
+
+ if got.OIDC != nil {
+ p.OIDC.Scopes[0] = "mutated-scope"
+ if got.OIDC.Scopes[0] != "mutated-scope" {
+ t.Errorf("OIDC.Scopes[0] = %q, want %q (documents aliasing bug)", got.OIDC.Scopes[0], "mutated-scope")
+ }
+ }
+ })
+}
+
+// ----------------------------------------------------------------------------
+// toCoreSAMLProviderConfig
+// ----------------------------------------------------------------------------
+
+func TestBranchcov0722PM_ToCoreSAMLProviderConfig(t *testing.T) {
+ t.Run("nil_returns_nil", func(t *testing.T) {
+ if got := toCoreSAMLProviderConfig(nil); got != nil {
+ t.Fatalf("toCoreSAMLProviderConfig(nil) = %#v, want nil", got)
+ }
+ })
+
+ t.Run("populated_copies_all_fields", func(t *testing.T) {
+ src := branchcov0722PMPopulatedExtSAML()
+ got := toCoreSAMLProviderConfig(src)
+ if got == nil {
+ t.Fatal("returned nil, want non-nil")
+ }
+
+ want := &config.SAMLProviderConfig{
+ IDPMetadataURL: src.IDPMetadataURL,
+ IDPMetadataXML: src.IDPMetadataXML,
+ IDPSSOURL: src.IDPSSOURL,
+ IDPSLOURL: src.IDPSLOURL,
+ IDPCertificate: src.IDPCertificate,
+ IDPCertFile: src.IDPCertFile,
+ IDPEntityID: src.IDPEntityID,
+ IDPIssuer: src.IDPIssuer,
+ SPEntityID: src.SPEntityID,
+ SPACSPath: src.SPACSPath,
+ SPMetadataPath: src.SPMetadataPath,
+ SPCertificate: src.SPCertificate,
+ SPPrivateKey: src.SPPrivateKey,
+ SPCertFile: src.SPCertFile,
+ SPKeyFile: src.SPKeyFile,
+ SignRequests: src.SignRequests,
+ WantAssertionsSigned: src.WantAssertionsSigned,
+ AllowUnencrypted: src.AllowUnencrypted,
+ UsernameAttr: src.UsernameAttr,
+ EmailAttr: src.EmailAttr,
+ GroupsAttr: src.GroupsAttr,
+ FirstNameAttr: src.FirstNameAttr,
+ LastNameAttr: src.LastNameAttr,
+ NameIDFormat: src.NameIDFormat,
+ ForceAuthn: src.ForceAuthn,
+ AllowIDPInitiated: src.AllowIDPInitiated,
+ RelayStateTemplate: src.RelayStateTemplate,
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("converted config = %+v\nwant %+v", got, want)
+ }
+
+ // Explicit checks on representative boolean and string fields to keep
+ // the assertions readable in failure output.
+ if got.IDPMetadataURL != "https://idp.example.com/metadata" {
+ t.Errorf("IDPMetadataURL = %q, want metadata url", got.IDPMetadataURL)
+ }
+ if got.IDPSLOURL != "https://idp.example.com/slo" {
+ t.Errorf("IDPSLOURL = %q, want slo url", got.IDPSLOURL)
+ }
+ if !got.SignRequests {
+ t.Errorf("SignRequests = false, want true")
+ }
+ if !got.AllowIDPInitiated {
+ t.Errorf("AllowIDPInitiated = false, want true")
+ }
+ if got.RelayStateTemplate != "ext-relay" {
+ t.Errorf("RelayStateTemplate = %q, want ext-relay", got.RelayStateTemplate)
+ }
+
+ // The result is an independent copy: mutating the source must not
+ // affect the converted value (all fields are value types here).
+ src.IDPMetadataURL = "https://mutated.example.com/metadata"
+ src.SignRequests = false
+ if got.IDPMetadataURL != "https://idp.example.com/metadata" {
+ t.Errorf("IDPMetadataURL mutated to %q after source change; converter must copy", got.IDPMetadataURL)
+ }
+ if !got.SignRequests {
+ t.Errorf("SignRequests mutated to false after source change; converter must copy")
+ }
+ })
+}
diff --git a/internal/api/truenas_app_providers_branchcov0722pm_test.go b/internal/api/truenas_app_providers_branchcov0722pm_test.go
new file mode 100644
index 0000000000..4885308621
--- /dev/null
+++ b/internal/api/truenas_app_providers_branchcov0722pm_test.go
@@ -0,0 +1,407 @@
+package api
+
+import (
+ "reflect"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/truenas"
+)
+
+// TestBranchcov0722PM_Ports exercises every branch of
+// mapTrueNASAppPortsToToolPorts: empty/nil input, the no-HostPorts arm, the
+// per-HostPort arm (including multiple host ports and trimmed/uppercased
+// protocol and host IP), and a mixed slice that hits both arms in one call.
+func TestBranchcov0722PM_Ports(t *testing.T) {
+ cases := []struct {
+ name string
+ ports []truenas.AppPort
+ expect []tools.PortInfo
+ }{
+ {
+ name: "nil_slice_returns_nil",
+ ports: nil,
+ expect: nil,
+ },
+ {
+ name: "empty_slice_returns_nil",
+ ports: []truenas.AppPort{},
+ expect: nil,
+ },
+ {
+ name: "no_host_ports_emits_private_and_protocol_only",
+ ports: []truenas.AppPort{
+ {ContainerPort: 8080, Protocol: " TCP "},
+ },
+ expect: []tools.PortInfo{
+ {Private: 8080, Public: 0, Protocol: "tcp", IP: ""},
+ },
+ },
+ {
+ name: "no_host_ports_with_blank_protocol_normalizes_to_empty",
+ ports: []truenas.AppPort{
+ {ContainerPort: 53, Protocol: " "},
+ },
+ expect: []tools.PortInfo{
+ {Private: 53, Public: 0, Protocol: "", IP: ""},
+ },
+ },
+ {
+ name: "host_ports_emit_one_entry_each_with_trimmed_ip",
+ ports: []truenas.AppPort{
+ {
+ ContainerPort: 443,
+ Protocol: "tcp",
+ HostPorts: []truenas.AppHostPort{
+ {HostPort: 8443, HostIP: " 10.0.0.1 "},
+ {HostPort: 9443, HostIP: ""},
+ },
+ },
+ },
+ expect: []tools.PortInfo{
+ {Private: 443, Public: 8443, Protocol: "tcp", IP: "10.0.0.1"},
+ {Private: 443, Public: 9443, Protocol: "tcp", IP: ""},
+ },
+ },
+ {
+ name: "mixed_slice_hits_both_arms_in_order",
+ ports: []truenas.AppPort{
+ {ContainerPort: 8080, Protocol: "TCP"},
+ {ContainerPort: 5432, Protocol: "tcp", HostPorts: []truenas.AppHostPort{{HostPort: 15432, HostIP: "172.16.0.1"}}},
+ },
+ expect: []tools.PortInfo{
+ {Private: 8080, Public: 0, Protocol: "tcp", IP: ""},
+ {Private: 5432, Public: 15432, Protocol: "tcp", IP: "172.16.0.1"},
+ },
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := mapTrueNASAppPortsToToolPorts(tc.ports)
+ if tc.expect == nil {
+ if got != nil {
+ t.Fatalf("expected nil result, got %#v", got)
+ }
+ return
+ }
+ if len(got) != len(tc.expect) {
+ t.Fatalf("expected %d entries, got %d: %#v", len(tc.expect), len(got), got)
+ }
+ if !reflect.DeepEqual(got, tc.expect) {
+ t.Fatalf("expected %#v, got %#v", tc.expect, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0722PM_Networks exercises every branch of
+// mapTrueNASAppNetworksToToolNetworks: empty/nil input, name-from-Name,
+// fallback to ID when Name is blank, and both-blank.
+func TestBranchcov0722PM_Networks(t *testing.T) {
+ cases := []struct {
+ name string
+ networks []truenas.AppNetwork
+ expect []tools.NetworkInfo
+ }{
+ {
+ name: "nil_slice_returns_nil",
+ networks: nil,
+ expect: nil,
+ },
+ {
+ name: "empty_slice_returns_nil",
+ networks: []truenas.AppNetwork{},
+ expect: nil,
+ },
+ {
+ name: "uses_trimmed_name_when_present",
+ networks: []truenas.AppNetwork{
+ {Name: " frontend ", ID: "net-1"},
+ },
+ expect: []tools.NetworkInfo{{Name: "frontend"}},
+ },
+ {
+ name: "falls_back_to_trimmed_id_when_name_blank",
+ networks: []truenas.AppNetwork{
+ {Name: " ", ID: " net-2 "},
+ },
+ expect: []tools.NetworkInfo{{Name: "net-2"}},
+ },
+ {
+ name: "both_blank_yields_empty_name",
+ networks: []truenas.AppNetwork{
+ {Name: "", ID: ""},
+ },
+ expect: []tools.NetworkInfo{{Name: ""}},
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := mapTrueNASAppNetworksToToolNetworks(tc.networks)
+ if tc.expect == nil {
+ if got != nil {
+ t.Fatalf("expected nil result, got %#v", got)
+ }
+ return
+ }
+ if len(got) != len(tc.expect) {
+ t.Fatalf("expected %d entries, got %d: %#v", len(tc.expect), len(got), got)
+ }
+ if !reflect.DeepEqual(got, tc.expect) {
+ t.Fatalf("expected %#v, got %#v", tc.expect, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0722PM_Volumes exercises every branch of
+// mapTrueNASAppVolumesToToolMounts: empty/nil input, read-only detection
+// (case-insensitive "ro"), read-write default, and field trimming.
+func TestBranchcov0722PM_Volumes(t *testing.T) {
+ cases := []struct {
+ name string
+ volumes []truenas.AppVolume
+ expect []tools.MountInfo
+ }{
+ {
+ name: "nil_slice_returns_nil",
+ volumes: nil,
+ expect: nil,
+ },
+ {
+ name: "empty_slice_returns_nil",
+ volumes: []truenas.AppVolume{},
+ expect: nil,
+ },
+ {
+ name: "ro_mode_lowercase_is_read_only",
+ volumes: []truenas.AppVolume{
+ {Source: "/host/path", Destination: "/container/path", Mode: "ro"},
+ },
+ expect: []tools.MountInfo{
+ {Source: "/host/path", Destination: "/container/path", ReadWrite: false},
+ },
+ },
+ {
+ name: "RO_mode_uppercase_is_read_only",
+ volumes: []truenas.AppVolume{
+ {Source: " /host/ro ", Destination: " /data ", Mode: " RO "},
+ },
+ expect: []tools.MountInfo{
+ {Source: "/host/ro", Destination: "/data", ReadWrite: false},
+ },
+ },
+ {
+ name: "rw_mode_is_read_write",
+ volumes: []truenas.AppVolume{
+ {Source: "/host/rw", Destination: "/data", Mode: "rw"},
+ },
+ expect: []tools.MountInfo{
+ {Source: "/host/rw", Destination: "/data", ReadWrite: true},
+ },
+ },
+ {
+ name: "empty_mode_defaults_to_read_write",
+ volumes: []truenas.AppVolume{
+ {Source: "/host/empty", Destination: "/data", Mode: ""},
+ },
+ expect: []tools.MountInfo{
+ {Source: "/host/empty", Destination: "/data", ReadWrite: true},
+ },
+ },
+ {
+ name: "unknown_mode_defaults_to_read_write",
+ volumes: []truenas.AppVolume{
+ {Source: "/host/zfs", Destination: "/data", Mode: "zfs"},
+ },
+ expect: []tools.MountInfo{
+ {Source: "/host/zfs", Destination: "/data", ReadWrite: true},
+ },
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := mapTrueNASAppVolumesToToolMounts(tc.volumes)
+ if tc.expect == nil {
+ if got != nil {
+ t.Fatalf("expected nil result, got %#v", got)
+ }
+ return
+ }
+ if len(got) != len(tc.expect) {
+ t.Fatalf("expected %d entries, got %d: %#v", len(tc.expect), len(got), got)
+ }
+ if !reflect.DeepEqual(got, tc.expect) {
+ t.Fatalf("expected %#v, got %#v", tc.expect, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0722PM_Containers exercises every branch of
+// mapTrueNASAppContainersToToolContainers: empty/nil input, a fully-populated
+// container (trimmed/lowercased fields with nested ports and mounts), and a
+// container whose PortConfig/VolumeMounts are nil so the nested mappers return
+// nil.
+func TestBranchcov0722PM_Containers(t *testing.T) {
+ cases := []struct {
+ name string
+ containers []truenas.AppContainer
+ expect []tools.AppContainerConfigContainer
+ }{
+ {
+ name: "nil_slice_returns_nil",
+ containers: nil,
+ expect: nil,
+ },
+ {
+ name: "empty_slice_returns_nil",
+ containers: []truenas.AppContainer{},
+ expect: nil,
+ },
+ {
+ name: "fully_populated_trims_and_maps_nested_ports_and_mounts",
+ containers: []truenas.AppContainer{
+ {
+ ID: " c1 ",
+ ServiceName: " plex ",
+ Image: " plexinc/pms:1.2 ",
+ State: " RUNNING ",
+ PortConfig: []truenas.AppPort{
+ {ContainerPort: 32400, Protocol: "TCP"},
+ {ContainerPort: 3005, Protocol: "tcp", HostPorts: []truenas.AppHostPort{{HostPort: 13240, HostIP: "1.2.3.4"}}},
+ },
+ VolumeMounts: []truenas.AppVolume{
+ {Source: "/mnt/media", Destination: "/data", Mode: "ro"},
+ },
+ },
+ },
+ expect: []tools.AppContainerConfigContainer{
+ {
+ ID: "c1",
+ Service: "plex",
+ Image: "plexinc/pms:1.2",
+ State: "running",
+ Ports: []tools.PortInfo{
+ {Private: 32400, Public: 0, Protocol: "tcp", IP: ""},
+ {Private: 3005, Public: 13240, Protocol: "tcp", IP: "1.2.3.4"},
+ },
+ Mounts: []tools.MountInfo{
+ {Source: "/mnt/media", Destination: "/data", ReadWrite: false},
+ },
+ },
+ },
+ },
+ {
+ name: "container_without_ports_or_mounts_has_nil_nested_slices",
+ containers: []truenas.AppContainer{
+ {
+ ID: "c2",
+ ServiceName: "bare",
+ Image: "alpine",
+ State: "EXITED",
+ PortConfig: nil,
+ VolumeMounts: nil,
+ },
+ },
+ expect: []tools.AppContainerConfigContainer{
+ {
+ ID: "c2",
+ Service: "bare",
+ Image: "alpine",
+ State: "exited",
+ Ports: nil,
+ Mounts: nil,
+ },
+ },
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := mapTrueNASAppContainersToToolContainers(tc.containers)
+ if tc.expect == nil {
+ if got != nil {
+ t.Fatalf("expected nil result, got %#v", got)
+ }
+ return
+ }
+ if len(got) != len(tc.expect) {
+ t.Fatalf("expected %d entries, got %d: %#v", len(tc.expect), len(got), got)
+ }
+ if !reflect.DeepEqual(got, tc.expect) {
+ t.Fatalf("expected %#v, got %#v", tc.expect, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0722PM_LogOutput exercises every branch of
+// formatTrueNASAppLogOutput: empty/nil input, timestamp-less line, timestamped
+// line (with trimming), ordering across multiple lines, and skipping of blank
+// Data entries (including the all-blank case that yields "").
+func TestBranchcov0722PM_LogOutput(t *testing.T) {
+ cases := []struct {
+ name string
+ lines []truenas.AppLogLine
+ expect string
+ }{
+ {
+ name: "nil_input_returns_empty",
+ lines: nil,
+ expect: "",
+ },
+ {
+ name: "empty_input_returns_empty",
+ lines: []truenas.AppLogLine{},
+ expect: "",
+ },
+ {
+ name: "single_line_without_timestamp_emits_text_only",
+ lines: []truenas.AppLogLine{{Data: " started ok "}},
+ expect: "started ok",
+ },
+ {
+ name: "single_line_with_timestamp_prefixes_and_trims_both",
+ lines: []truenas.AppLogLine{{Timestamp: " 2024-01-02T03:04:05Z ", Data: " boot "}},
+ expect: "2024-01-02T03:04:05Z boot",
+ },
+ {
+ name: "multiline_preserves_order_and_joins_with_newline",
+ lines: []truenas.AppLogLine{
+ {Data: "first"},
+ {Timestamp: "2024-01-02", Data: "second"},
+ },
+ expect: "first\n2024-01-02 second",
+ },
+ {
+ name: "blank_data_lines_are_skipped_but_order_preserved",
+ lines: []truenas.AppLogLine{
+ {Timestamp: "2024-01-02", Data: " "},
+ {Data: "kept"},
+ {Data: ""},
+ },
+ expect: "kept",
+ },
+ {
+ name: "all_blank_data_yields_empty_string",
+ lines: []truenas.AppLogLine{
+ {Data: " "},
+ {Timestamp: "2024-01-02", Data: ""},
+ },
+ expect: "",
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := formatTrueNASAppLogOutput(tc.lines)
+ if got != tc.expect {
+ t.Fatalf("expected %q, got %q", tc.expect, got)
+ }
+ })
+ }
+}
diff --git a/internal/config/multi_tenant_branchcov0722pm_test.go b/internal/config/multi_tenant_branchcov0722pm_test.go
new file mode 100644
index 0000000000..ef60263bea
--- /dev/null
+++ b/internal/config/multi_tenant_branchcov0722pm_test.go
@@ -0,0 +1,331 @@
+package config
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "sort"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// Test functions use the TestBranchcov0722PM prefix so the scoped run
+// `go test ./internal/config/ -run '^TestBranchcov0722PM'` selects only them.
+//
+// This file raises branch coverage for the five MultiTenantPersistence
+// organization lifecycle methods in multi_tenant.go:
+// - LoadOrganization
+// - LoadOrganizationStrict
+// - SaveOrganization
+// - ListOrganizations
+// - DeleteOrganization
+//
+// Each MultiTenantPersistence is built over an isolated t.TempDir(), mirroring
+// the pattern in multi_tenant_test.go. No writes escape the temp dir.
+
+// newTestMultiTenantPersistence returns a MultiTenantPersistence rooted at a
+// fresh temp directory along with the base directory path.
+func newTestMultiTenantPersistence(t *testing.T) (*MultiTenantPersistence, string) {
+ t.Helper()
+ baseDir := t.TempDir()
+ return NewMultiTenantPersistence(baseDir), baseDir
+}
+
+// TestBranchcov0722PM_LoadOrganization exercises every return path of
+// (*MultiTenantPersistence).LoadOrganization.
+func TestBranchcov0722PM_LoadOrganization(t *testing.T) {
+ t.Run("missing non-default org yields default org", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ // No org.json exists: persistence.LoadOrganization returns os.ErrNotExist,
+ // which LoadOrganization translates into a synthetic default org.
+ org, err := mtp.LoadOrganization("ghost")
+ require.NoError(t, err)
+ require.NotNil(t, org)
+ assert.Equal(t, "ghost", org.ID)
+ assert.Equal(t, "ghost", org.DisplayName)
+ assert.Empty(t, org.Members, "synthetic default org has no members")
+ })
+
+ t.Run("missing default org yields default org", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ org, err := mtp.LoadOrganization("default")
+ require.NoError(t, err)
+ require.NotNil(t, org)
+ assert.Equal(t, "default", org.ID)
+ assert.Equal(t, "default", org.DisplayName)
+ })
+
+ t.Run("invalid org id surfaces get-persistence error", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ org, err := mtp.LoadOrganization("../escape")
+ require.Error(t, err)
+ assert.Nil(t, org)
+ assert.Contains(t, err.Error(), "invalid organization ID")
+ })
+
+ t.Run("malformed org.json surfaces non-notExist error", func(t *testing.T) {
+ mtp, baseDir := newTestMultiTenantPersistence(t)
+ require.NoError(t, mtp.SaveOrganization(&models.Organization{ID: "acme", DisplayName: "Acme"}))
+ // Corrupt the persisted org.json so persistence.LoadOrganization fails with
+ // a parse error (distinct from os.ErrNotExist).
+ orgFile := filepath.Join(baseDir, "orgs", "acme", "org.json")
+ require.NoError(t, os.WriteFile(orgFile, []byte("{not valid json"), 0o600))
+ org, err := mtp.LoadOrganization("acme")
+ require.Error(t, err)
+ assert.Nil(t, org)
+ assert.False(t, errors.Is(err, os.ErrNotExist), "parse error must not be classified as not-exist")
+ assert.Contains(t, err.Error(), "failed to parse org file")
+ })
+}
+
+// TestBranchcov0722PM_LoadOrganizationStrict exercises every return path of
+// (*MultiTenantPersistence).LoadOrganizationStrict, and asserts the contrast
+// with LoadOrganization on a missing org.
+func TestBranchcov0722PM_LoadOrganizationStrict(t *testing.T) {
+ t.Run("missing non-default org returns os.ErrNotExist and does not create dir", func(t *testing.T) {
+ mtp, baseDir := newTestMultiTenantPersistence(t)
+ org, err := mtp.LoadOrganizationStrict("ghost")
+ require.Error(t, err)
+ assert.Nil(t, org)
+ assert.True(t, errors.Is(err, os.ErrNotExist),
+ "strict load of a missing org must return os.ErrNotExist, got %v", err)
+ // Strict short-circuits at OrgExists before GetPersistence, so it must not
+ // materialize the organization directory.
+ _, statErr := os.Stat(filepath.Join(baseDir, "orgs", "ghost"))
+ assert.True(t, os.IsNotExist(statErr),
+ "strict load of a missing org must not create its directory")
+ })
+
+ t.Run("nil receiver returns no-persistence error", func(t *testing.T) {
+ var mtp *MultiTenantPersistence
+ org, err := mtp.LoadOrganizationStrict("default")
+ require.Error(t, err)
+ assert.Nil(t, org)
+ assert.Contains(t, err.Error(), "no persistence configured")
+ })
+
+ t.Run("default with no org.json errors with wrapped not-exist", func(t *testing.T) {
+ // "default" always passes OrgExists, so strict reaches persistence.LoadOrganization
+ // which returns os.ErrNotExist for the absent org.json; strict wraps and returns it.
+ mtp, _ := newTestMultiTenantPersistence(t)
+ org, err := mtp.LoadOrganizationStrict("default")
+ require.Error(t, err)
+ assert.Nil(t, org)
+ assert.True(t, errors.Is(err, os.ErrNotExist))
+ })
+
+ t.Run("existing org loads via strict", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ require.NoError(t, mtp.SaveOrganization(&models.Organization{ID: "acme", DisplayName: "Acme"}))
+ org, err := mtp.LoadOrganizationStrict("acme")
+ require.NoError(t, err)
+ require.NotNil(t, org)
+ assert.Equal(t, "Acme", org.DisplayName)
+ })
+}
+
+// TestBranchcov0722PM_LoadVsLoadStrictMissing is the explicit contrast: on the
+// same missing-org condition the lenient loader returns a synthetic default org
+// while the strict loader returns os.ErrNotExist.
+func TestBranchcov0722PM_LoadVsLoadStrictMissing(t *testing.T) {
+ // Lenient: returns synthetic default org, nil error.
+ mtpLenient, _ := newTestMultiTenantPersistence(t)
+ lenient, lenientErr := mtpLenient.LoadOrganization("ghost")
+ require.NoError(t, lenientErr)
+ require.NotNil(t, lenient)
+ assert.Equal(t, &models.Organization{ID: "ghost", DisplayName: "ghost"}, lenient)
+
+ // Strict: same missing org, different store so no dir was pre-created.
+ mtpStrict, _ := newTestMultiTenantPersistence(t)
+ strict, strictErr := mtpStrict.LoadOrganizationStrict("ghost")
+ require.Error(t, strictErr)
+ assert.Nil(t, strict)
+ assert.True(t, errors.Is(strictErr, os.ErrNotExist))
+}
+
+// TestBranchcov0722PM_SaveOrganization exercises every return path of
+// (*MultiTenantPersistence).SaveOrganization plus a save->load round trip.
+func TestBranchcov0722PM_SaveOrganization(t *testing.T) {
+ t.Run("nil org rejected", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ err := mtp.SaveOrganization(nil)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "organization is required")
+ })
+
+ t.Run("invalid org id rejected", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ err := mtp.SaveOrganization(&models.Organization{ID: "../evil", DisplayName: "x"})
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "invalid organization ID")
+ })
+
+ t.Run("save then load round trip", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ saved := &models.Organization{
+ ID: "acme",
+ DisplayName: "Acme Corporation",
+ OwnerUserID: "owner-1",
+ OwnerEmail: "[email protected]",
+ }
+ require.NoError(t, mtp.SaveOrganization(saved))
+
+ loaded, err := mtp.LoadOrganization("acme")
+ require.NoError(t, err)
+ require.NotNil(t, loaded)
+ assert.Equal(t, "acme", loaded.ID)
+ assert.Equal(t, "Acme Corporation", loaded.DisplayName)
+ assert.Equal(t, "owner-1", loaded.OwnerUserID)
+ assert.Equal(t, "[email protected]", loaded.OwnerEmail)
+ })
+}
+
+// TestBranchcov0722PM_ListOrganizations exercises the list path over zero, one,
+// and several organizations, plus the skip and error branches.
+func TestBranchcov0722PM_ListOrganizations(t *testing.T) {
+ t.Run("only default present", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ orgs, err := mtp.ListOrganizations()
+ require.NoError(t, err)
+ require.Len(t, orgs, 1)
+ assert.Equal(t, "default", orgs[0].ID)
+ assert.Equal(t, "default", orgs[0].DisplayName)
+ })
+
+ t.Run("one extra org", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ require.NoError(t, mtp.SaveOrganization(&models.Organization{ID: "acme", DisplayName: "Acme"}))
+ orgs, err := mtp.ListOrganizations()
+ require.NoError(t, err)
+ require.Len(t, orgs, 2)
+ byID := map[string]*models.Organization{}
+ for _, o := range orgs {
+ byID[o.ID] = o
+ }
+ assert.Contains(t, byID, "default")
+ require.Contains(t, byID, "acme")
+ assert.Equal(t, "Acme", byID["acme"].DisplayName)
+ })
+
+ t.Run("several extra orgs returned sorted by id", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ for _, id := range []string{"zeta", "alpha", "mid"} {
+ require.NoError(t, mtp.SaveOrganization(&models.Organization{ID: id, DisplayName: id + "-display"}))
+ }
+ orgs, err := mtp.ListOrganizations()
+ require.NoError(t, err)
+ require.Len(t, orgs, 4, "default plus three extras")
+
+ // The implementation sorts IDs before loading, so ordering is guaranteed.
+ gotIDs := make([]string, len(orgs))
+ for i, o := range orgs {
+ gotIDs[i] = o.ID
+ }
+ assert.Equal(t, []string{"alpha", "default", "mid", "zeta"}, gotIDs,
+ "ListOrganizations must return orgs sorted by ID")
+
+ for _, o := range orgs {
+ if o.ID == "default" {
+ assert.Equal(t, "default", o.DisplayName)
+ } else {
+ assert.Equal(t, o.ID+"-display", o.DisplayName)
+ }
+ }
+ })
+
+ t.Run("skips non-dir entries and invalid directory names", func(t *testing.T) {
+ mtp, baseDir := newTestMultiTenantPersistence(t)
+ require.NoError(t, mtp.SaveOrganization(&models.Organization{ID: "acme", DisplayName: "Acme"}))
+ orgsDir := filepath.Join(baseDir, "orgs")
+
+ // A stray regular file must be skipped by the IsDir check.
+ require.NoError(t, os.WriteFile(filepath.Join(orgsDir, "stray.txt"), []byte("x"), 0o600))
+ // A directory whose name fails the org-ID regex (space is invalid) must be
+ // skipped by the isValidOrgID check.
+ require.NoError(t, os.MkdirAll(filepath.Join(orgsDir, "bad name"), 0o700))
+
+ orgs, err := mtp.ListOrganizations()
+ require.NoError(t, err)
+ gotIDs := make([]string, 0, len(orgs))
+ for _, o := range orgs {
+ gotIDs = append(gotIDs, o.ID)
+ }
+ sort.Strings(gotIDs)
+ assert.Equal(t, []string{"acme", "default"}, gotIDs,
+ "stray file and invalid-named directory must be excluded")
+ })
+
+ t.Run("unreadable orgs dir surfaces non-NotExist error", func(t *testing.T) {
+ mtp, baseDir := newTestMultiTenantPersistence(t)
+ // Make "orgs" a regular file so os.ReadDir fails with a non-IsNotExist error.
+ require.NoError(t, os.WriteFile(filepath.Join(baseDir, "orgs"), []byte("x"), 0o600))
+ orgs, err := mtp.ListOrganizations()
+ require.Error(t, err)
+ assert.Nil(t, orgs)
+ assert.Contains(t, err.Error(), "failed to read organizations directory")
+ })
+
+ t.Run("load failure inside list is propagated", func(t *testing.T) {
+ mtp, baseDir := newTestMultiTenantPersistence(t)
+ // Manually create an org directory with a malformed org.json so that
+ // LoadOrganization (called per org) returns a non-not-exist error, which
+ // ListOrganizations must wrap and return.
+ acmeDir := filepath.Join(baseDir, "orgs", "acme")
+ require.NoError(t, os.MkdirAll(acmeDir, 0o700))
+ require.NoError(t, os.WriteFile(filepath.Join(acmeDir, "org.json"), []byte("{broken"), 0o600))
+ orgs, err := mtp.ListOrganizations()
+ require.Error(t, err)
+ assert.Nil(t, orgs)
+ assert.Contains(t, err.Error(), "acme")
+ })
+}
+
+// TestBranchcov0722PM_DeleteOrganization exercises every return path of
+// (*MultiTenantPersistence).DeleteOrganization.
+func TestBranchcov0722PM_DeleteOrganization(t *testing.T) {
+ t.Run("existing org removed and subsequent load falls back to default", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ require.NoError(t, mtp.SaveOrganization(&models.Organization{ID: "acme", DisplayName: "Acme Corp"}))
+ loaded, err := mtp.LoadOrganization("acme")
+ require.NoError(t, err)
+ assert.Equal(t, "Acme Corp", loaded.DisplayName)
+
+ require.NoError(t, mtp.DeleteOrganization("acme"))
+
+ // After deletion org.json is gone, so Load returns the synthetic default org.
+ after, err := mtp.LoadOrganization("acme")
+ require.NoError(t, err)
+ require.NotNil(t, after)
+ assert.Equal(t, "acme", after.ID)
+ assert.Equal(t, "acme", after.DisplayName,
+ "deleted org's DisplayName must not survive")
+ // Strict must report it as missing again.
+ _, strictErr := mtp.LoadOrganizationStrict("acme")
+ require.Error(t, strictErr)
+ assert.True(t, errors.Is(strictErr, os.ErrNotExist))
+ })
+
+ t.Run("non-existent org returns os.ErrNotExist", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ err := mtp.DeleteOrganization("ghost")
+ require.Error(t, err)
+ assert.True(t, errors.Is(err, os.ErrNotExist))
+ })
+
+ t.Run("default cannot be deleted", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ err := mtp.DeleteOrganization("default")
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "default organization cannot be deleted")
+ })
+
+ t.Run("invalid id rejected", func(t *testing.T) {
+ mtp, _ := newTestMultiTenantPersistence(t)
+ err := mtp.DeleteOrganization("../evil")
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "invalid organization ID")
+ })
+}
diff --git a/internal/config/report_schedules_branchcov0722pm_test.go b/internal/config/report_schedules_branchcov0722pm_test.go
new file mode 100644
index 0000000000..0cd8f401fc
--- /dev/null
+++ b/internal/config/report_schedules_branchcov0722pm_test.go
@@ -0,0 +1,295 @@
+package config
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// This file raises branch/function coverage for the three ConfigPersistence
+// methods on report_schedules.go that were previously 0.0% covered:
+// - (*ConfigPersistence).ReportSchedulesPath()
+// - (*ConfigPersistence).LoadReportScheduleStore()
+// - (*ConfigPersistence).SaveReportScheduleStore()
+//
+// Conventions (table-driven subtests, NewConfigPersistence(t.TempDir())
+// constructor, testify assert/require, package-level mockFSError for
+// FileSystem error injection) are copied from availability_test.go and
+// persistence_coverage_test.go in this directory.
+//
+// Test functions use the TestBranchcov0722PM prefix so the scoped run
+// `go test ./internal/config/ -run '^TestBranchcov0722PM'` selects only them.
+
+// newPlainReportSchedulePersistence builds a ConfigPersistence whose crypto is
+// nil and whose reportSchedulesFile lives under dir. With crypto disabled we
+// can (a) read the persisted bytes back as plaintext JSON to assert exactly
+// what Save wrote, and (b) reach the parse-only error branch of Load that is
+// shadowed by decryption when crypto is enabled. It writes only under dir.
+func newPlainReportSchedulePersistence(dir string) *ConfigPersistence {
+ return &ConfigPersistence{
+ configDir: dir,
+ reportSchedulesFile: filepath.Join(dir, "report_schedules.json"),
+ fs: defaultFileSystem{},
+ }
+}
+
+// TestBranchcov0722PM_ReportSchedulesPath covers both arms of the nil-receiver
+// guard in (*ConfigPersistence).ReportSchedulesPath and asserts the exact
+// joined path against the persistence's configured directory.
+func TestBranchcov0722PM_ReportSchedulesPath(t *testing.T) {
+ t.Run("nil receiver returns empty string", func(t *testing.T) {
+ var cp *ConfigPersistence
+ assert.Equal(t, "", cp.ReportSchedulesPath())
+ })
+
+ t.Run("populated receiver returns joined path equal to internal field", func(t *testing.T) {
+ dir := t.TempDir()
+ cp := NewConfigPersistence(dir)
+
+ got := cp.ReportSchedulesPath()
+ want := filepath.Join(dir, "report_schedules.json")
+ assert.Equal(t, want, got, "ReportSchedulesPath must be dir/report_schedules.json")
+ assert.Equal(t, cp.reportSchedulesFile, got, "ReportSchedulesPath must mirror the configured field")
+ assert.True(t, filepath.IsAbs(got), "path should be absolute under a temp dir")
+ assert.True(t, strings.HasSuffix(got, "report_schedules.json"))
+ })
+}
+
+// TestBranchcov0722PM_LoadReportScheduleStore covers every return path of
+// (*ConfigPersistence).LoadReportScheduleStore: nil-receiver short-circuit,
+// missing-file (os.ErrNotExist) default, plain-parse error (crypto nil),
+// decrypt error (crypto non-nil, corrupt ciphertext), generic read error, and
+// the success path round-tripped through Save.
+func TestBranchcov0722PM_LoadReportScheduleStore(t *testing.T) {
+ t.Run("nil receiver returns empty store and nil error", func(t *testing.T) {
+ var cp *ConfigPersistence
+ store, err := cp.LoadReportScheduleStore()
+ require.NoError(t, err)
+ require.NotNil(t, store, "nil receiver must still yield a usable empty store")
+ require.NotNil(t, store.Schedules, "Schedules must be non-nil so it serializes as [] not null")
+ assert.Empty(t, store.Schedules)
+ })
+
+ t.Run("missing file yields default empty store with no error", func(t *testing.T) {
+ cp := NewConfigPersistence(t.TempDir())
+ require.NoFileExists(t, cp.ReportSchedulesPath())
+
+ store, err := cp.LoadReportScheduleStore()
+ require.NoError(t, err)
+ require.NotNil(t, store)
+ require.NotNil(t, store.Schedules, "missing file must normalize to non-nil empty slice")
+ assert.Empty(t, store.Schedules)
+ })
+
+ t.Run("corrupt file with crypto disabled surfaces parse error", func(t *testing.T) {
+ dir := t.TempDir()
+ cp := newPlainReportSchedulePersistence(dir)
+ require.NoError(t, os.WriteFile(cp.ReportSchedulesPath(), []byte("{not valid json"), 0600))
+
+ store, err := cp.LoadReportScheduleStore()
+ require.Error(t, err)
+ assert.Nil(t, store)
+ assert.Contains(t, err.Error(), "parse report schedules",
+ "with crypto nil the parse-error path must be taken (not the decrypt path)")
+ })
+
+ t.Run("corrupt file with crypto enabled surfaces decrypt error", func(t *testing.T) {
+ cp := NewConfigPersistence(t.TempDir())
+ // Write plaintext garbage; with crypto enabled, parsing fails first,
+ // then Decrypt also fails on the non-ciphertext bytes.
+ require.NoError(t, os.WriteFile(cp.ReportSchedulesPath(), []byte("{not valid json"), 0600))
+
+ store, err := cp.LoadReportScheduleStore()
+ require.Error(t, err)
+ assert.Nil(t, store)
+ assert.Contains(t, err.Error(), "decrypt report schedules",
+ "with crypto enabled the decrypt-error path must be taken")
+ })
+
+ t.Run("non-ErrNotExist read error is wrapped as read report schedules", func(t *testing.T) {
+ cp := NewConfigPersistence(t.TempDir())
+ // Reuse the package-level mockFSError helper (see persistence_coverage_test.go)
+ // to inject a read failure that is NOT os.ErrNotExist, exercising the
+ // non-not-found error arm of Load.
+ cp.SetFileSystem(&mockFSError{
+ FileSystem: defaultFileSystem{},
+ readError: errors.New("disk read failed"),
+ })
+
+ store, err := cp.LoadReportScheduleStore()
+ require.Error(t, err)
+ assert.Nil(t, store)
+ assert.Contains(t, err.Error(), "read report schedules")
+ assert.Contains(t, err.Error(), "disk read failed")
+ })
+
+ t.Run("save then load round-trips every field through encryption", func(t *testing.T) {
+ cp := NewConfigPersistence(t.TempDir())
+
+ created := time.Date(2024, time.March, 15, 8, 30, 0, 0, time.UTC)
+ lastRun := created.Add(-24 * time.Hour)
+ nextRun := created.Add(7 * 24 * time.Hour)
+ want := ReportScheduleStore{Schedules: []ReportSchedule{
+ {
+ ID: "sched-1",
+ Name: "Monthly Uptime Report",
+ Enabled: true,
+ Cadence: ReportScheduleCadence{
+ Type: ReportScheduleCadenceMonthly,
+ DayOfMonth: 15,
+ Time: "08:00",
+ Timezone: "UTC",
+ },
+ Window: "last_month",
+ // Deliberately uppercase to prove Save normalizes before persisting.
+ Format: "PDF",
+ RetentionCount: 7,
+ Scope: ReportScheduleScope{
+ Resources: []ReportScheduleResource{
+ {ResourceType: "HOST", ResourceID: "h-1", Name: "Host One"},
+ },
+ Tags: []string{"prod"},
+ },
+ Delivery: ReportScheduleDelivery{
+ Method: ReportScheduleDeliveryEmail,
+ To: []string{"[email protected]"},
+ Attach: true,
+ SaveToDisk: true,
+ },
+ LastRunAt: &lastRun,
+ LastRunStatus: ReportScheduleLastRunOK,
+ NextRunAt: &nextRun,
+ LastOccurrenceKey: "2024-03",
+ CreatedAt: created,
+ UpdatedAt: created,
+ },
+ }}
+
+ require.NoError(t, cp.SaveReportScheduleStore(want))
+
+ // Sanity: with crypto enabled, the persisted bytes must not leak the
+ // plaintext schedule identifier (i.e. the Encrypt branch ran).
+ raw, err := os.ReadFile(cp.ReportSchedulesPath())
+ require.NoError(t, err)
+ assert.NotContains(t, string(raw), "Monthly Uptime Report",
+ "encrypted store must not contain plaintext schedule name")
+
+ got, err := cp.LoadReportScheduleStore()
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ require.Len(t, got.Schedules, 1)
+
+ s := got.Schedules[0]
+ assert.Equal(t, "sched-1", s.ID)
+ assert.Equal(t, "Monthly Uptime Report", s.Name)
+ assert.True(t, s.Enabled)
+ assert.Equal(t, ReportScheduleCadenceMonthly, s.Cadence.Type)
+ assert.Equal(t, 15, s.Cadence.DayOfMonth)
+ assert.Equal(t, "08:00", s.Cadence.Time)
+ assert.Equal(t, "UTC", s.Cadence.Timezone)
+ assert.Equal(t, "last_month", s.Window)
+ // Normalized (lowercased) by Save.
+ assert.Equal(t, "pdf", s.Format)
+ assert.Equal(t, 7, s.RetentionCount, "non-zero retention is preserved verbatim")
+ require.Len(t, s.Scope.Resources, 1)
+ assert.Equal(t, "host", s.Scope.Resources[0].ResourceType, "resource type lowercased by Save normalize")
+ assert.Equal(t, "h-1", s.Scope.Resources[0].ResourceID)
+ assert.Equal(t, "Host One", s.Scope.Resources[0].Name)
+ assert.Equal(t, []string{"prod"}, s.Scope.Tags)
+ assert.Equal(t, ReportScheduleDeliveryEmail, s.Delivery.Method)
+ assert.Equal(t, []string{"[email protected]"}, s.Delivery.To)
+ assert.True(t, s.Delivery.Attach)
+ assert.True(t, s.Delivery.SaveToDisk)
+ // Pointer fields round-trip through JSON.
+ require.NotNil(t, s.LastRunAt)
+ assert.True(t, s.LastRunAt.Equal(lastRun), "LastRunAt round-tripped: got %v want %v", *s.LastRunAt, lastRun)
+ require.NotNil(t, s.NextRunAt)
+ assert.True(t, s.NextRunAt.Equal(nextRun), "NextRunAt round-tripped: got %v want %v", *s.NextRunAt, nextRun)
+ assert.Equal(t, ReportScheduleLastRunOK, s.LastRunStatus)
+ assert.Equal(t, "2024-03", s.LastOccurrenceKey)
+ assert.True(t, s.CreatedAt.Equal(created), "CreatedAt round-tripped")
+ assert.True(t, s.UpdatedAt.Equal(created), "UpdatedAt round-tripped")
+ })
+}
+
+// TestBranchcov0722PM_SaveReportScheduleStore covers every return path of
+// (*ConfigPersistence).SaveReportScheduleStore: nil-receiver guard, successful
+// write (with normalization observable on disk), the generic write-error wrap,
+// and the missing-parent-directory error arm.
+func TestBranchcov0722PM_SaveReportScheduleStore(t *testing.T) {
+ t.Run("nil receiver returns not-configured error", func(t *testing.T) {
+ var cp *ConfigPersistence
+ err := cp.SaveReportScheduleStore(EmptyReportScheduleStore())
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "config persistence is not configured")
+ })
+
+ t.Run("successful save writes normalized plaintext JSON when crypto is nil", func(t *testing.T) {
+ dir := t.TempDir()
+ cp := newPlainReportSchedulePersistence(dir)
+
+ store := ReportScheduleStore{Schedules: []ReportSchedule{
+ {
+ ID: " s1 ",
+ Name: " Weekly CSV ",
+ Format: "CSV",
+ RetentionCount: 0, // expect default applied by normalize
+ Scope: ReportScheduleScope{Tags: []string{" Prod ", "prod", "staging"}},
+ },
+ }}
+ require.NoError(t, cp.SaveReportScheduleStore(store))
+
+ raw, err := os.ReadFile(cp.ReportSchedulesPath())
+ require.NoError(t, err)
+ body := string(raw)
+
+ // Save normalizes before marshaling: trimmed IDs, lowercased format,
+ // default retention, and de-duplicated/lowercased tag slice.
+ assert.Contains(t, body, `"id": "s1"`)
+ assert.Contains(t, body, `"name": "Weekly CSV"`)
+ assert.Contains(t, body, `"format": "csv"`)
+ assert.Contains(t, body, `"retention_count": 12`)
+ assert.Contains(t, body, `"tags": [`)
+
+ // File is created with the restrictive perm passed by Save (0600).
+ info, err := os.Stat(cp.ReportSchedulesPath())
+ require.NoError(t, err)
+ assert.Equal(t, os.FileMode(0600), info.Mode().Perm())
+ })
+
+ t.Run("write error is wrapped as write report schedules", func(t *testing.T) {
+ cp := NewConfigPersistence(t.TempDir())
+ cp.SetFileSystem(&mockFSError{
+ FileSystem: defaultFileSystem{},
+ writeError: errors.New("disk full"),
+ })
+
+ err := cp.SaveReportScheduleStore(EmptyReportScheduleStore())
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "write report schedules")
+ assert.Contains(t, err.Error(), "disk full")
+ })
+
+ t.Run("missing parent directory yields a write error", func(t *testing.T) {
+ // writeConfigFileLocked does not create parent dirs (callers are
+ // expected to EnsureConfigDir first); saving into a path whose parent
+ // does not exist therefore surfaces the wrapped write error.
+ dir := t.TempDir()
+ cp := &ConfigPersistence{
+ configDir: dir,
+ reportSchedulesFile: filepath.Join(dir, "does_not_exist", "report_schedules.json"),
+ fs: defaultFileSystem{},
+ }
+
+ err := cp.SaveReportScheduleStore(EmptyReportScheduleStore())
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "write report schedules")
+ assert.NoFileExists(t, cp.ReportSchedulesPath())
+ })
+}