package main import ( "fmt" "os" "path/filepath" "strings" "testing" "github.com/carlosframework/platform/internal/console" ) func TestClaimAdministrativeDBIsGated(t *testing.T) { for _, flag := range []string{"", "1"} { t.Run("flag="+flag, func(t *testing.T) { t.Setenv("CARLOS_HOST_CLAIM", flag) path := filepath.Join(t.TempDir(), "console.db") if flag != "" { // The console package's test probe is not linked into this package. // Exercise the production UUID ioctl on persistent storage while // leaving TMPDIR short for this package's Unix socket tests. path = claimAdministrativeDBPath(t) } t.Setenv("CONSOLE_DB", path) st := openConsoleDB() defer st.Close() err := st.Grant("operator@example.com", "demo") if flag == "" && err != nil { t.Fatal(err) } if flag != "" && (err == nil || !strings.Contains(err.Error(), "claim: app write not permitted")) { t.Fatalf("unguarded legacy grant: %v", err) } }) } } func claimAdministrativeDBPath(t *testing.T) string { t.Helper() t.Cleanup(console.UseSQLInstanceIdentityForTest("i-claim-admin-test")) roots := []struct { name, path string err error }{ {name: "CARLOS_TEST_DB_ROOT", path: os.Getenv("CARLOS_TEST_DB_ROOT")}, {name: "t.TempDir()", path: t.TempDir()}, } cwd, cwdErr := os.Getwd() cache, cacheErr := os.UserCacheDir() roots = append(roots, struct { name, path string err error }{"package working directory", cwd, cwdErr}, struct { name, path string err error }{"os.UserCacheDir()", cache, cacheErr}) var failures []string for _, root := range roots { err := root.err if err == nil && root.path == "" { err = fmt.Errorf("not configured") } var dir string if err == nil { err = os.MkdirAll(root.path, 0700) } if err == nil { dir, err = os.MkdirTemp(root.path, "carlos-claim-sql-") } path := filepath.Join(dir, "console.db") if err == nil { var st *console.Store st, err = console.OpenGated(path) if err == nil { err = st.Close() } } if err == nil { t.Cleanup(func() { if err := os.RemoveAll(dir); err != nil { t.Errorf("remove claim SQL fixture: %v", err) } }) return path } if dir != "" { if cleanupErr := os.RemoveAll(dir); cleanupErr != nil { t.Errorf("remove failed claim SQL fixture: %v", cleanupErr) } } failures = append(failures, fmt.Sprintf("%s (%q): %v", root.name, root.path, err)) } t.Skipf("no supported writable claim SQL fixture: %s", strings.Join(failures, "; ")) return "" } func TestClaimAdministrativeDBFallsBackFromUnusableOverride(t *testing.T) { t.Setenv("CARLOS_TEST_DB_ROOT", "/proc/carlos-test-db-root") path := claimAdministrativeDBPath(t) st, err := console.OpenGated(path) if err != nil { t.Fatal(err) } if err := st.Close(); err != nil { t.Fatal(err) } }