package main import ( "os" "path/filepath" "strings" "testing" ) // The password comes from a file, because that is how the mesh delivers one. // // A provisioner told to take a superuser password from an environment variable needs somebody to // read the sealed file and pass it in — a person in the middle of the one path that exists so // there is not one. It is also the difference between a credential in a file and one in a process // listing: `docker inspect` prints environment. func TestTheSuperuserPasswordComesFromTheFileTheMeshWrote(t *testing.T) { path := filepath.Join(t.TempDir(), "superuser") if err := os.WriteFile(path, []byte("the-sealed-one\n"), 0o600); err != nil { t.Fatal(err) } t.Setenv("MESH_PROVISION_POSTGRES", "postgres://postgres@127.0.0.1:5433/postgres?sslmode=disable") t.Setenv("MESH_PROVISION_PASSWORD_FILE", path) where, err := connectionString() if err != nil { t.Fatal(err) } if !strings.Contains(where, "the-sealed-one") { t.Fatalf("the password the mesh wrote is not in the connection: %s", where) } if !strings.Contains(where, "127.0.0.1:5433") || !strings.Contains(where, "sslmode=disable") { t.Fatalf("the rest of the connection was lost: %s", where) } } // An empty file connects as nobody and is refused by the database three layers away, as an // authentication problem with no cause anybody changed. func TestAnEmptyPasswordFileIsRefusedHere(t *testing.T) { path := filepath.Join(t.TempDir(), "superuser") if err := os.WriteFile(path, []byte("\n"), 0o600); err != nil { t.Fatal(err) } t.Setenv("MESH_PROVISION_POSTGRES", "postgres://postgres@127.0.0.1:5433/postgres") t.Setenv("MESH_PROVISION_PASSWORD_FILE", path) if _, err := connectionString(); err == nil { t.Fatal("a provisioner with no password reported one") } } // And a provisioner somebody runs by hand still works with the URL alone. func TestAConnectionWithNoPasswordFileIsLeftAlone(t *testing.T) { t.Setenv("MESH_PROVISION_POSTGRES", "postgres://postgres:typed@127.0.0.1:5433/postgres") t.Setenv("MESH_PROVISION_PASSWORD_FILE", "") where, err := connectionString() if err != nil { t.Fatal(err) } if where != "postgres://postgres:typed@127.0.0.1:5433/postgres" { t.Fatalf("the connection was rewritten when it should have been left alone: %s", where) } } func TestAProvisionerWithNoDatabaseSaysSo(t *testing.T) { t.Setenv("MESH_PROVISION_POSTGRES", "") t.Setenv("MESH_PROVISION_PASSWORD_FILE", "") if _, err := connectionString(); err == nil { t.Fatal("a provisioner that does not know which database it owns reported one") } }