//go:build windows

package credentiallease

import (
	"bytes"
	"encoding/base64"
	"errors"
	"os"
	"path/filepath"
	"testing"

	"golang.org/x/sys/windows"
)

func secureTestKeyFile(t *testing.T, path string) {
	t.Helper()
	current, err := windows.GetCurrentProcessToken().GetTokenUser()
	if err != nil {
		t.Fatal(err)
	}
	setTestKeyFileDACL(t, path, "D:P(A;;FA;;;"+current.User.Sid.String()+")(A;;FA;;;SY)(A;;FA;;;BA)")
}

func TestLoadPrivateKeyFileRejectsUntrustedWindowsReader(t *testing.T) {
	path := filepath.Join(t.TempDir(), "recipient.key")
	encoded := base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{0x5a}, 32))
	if err := os.WriteFile(path, []byte(encoded), 0o600); err != nil {
		t.Fatal(err)
	}
	current, err := windows.GetCurrentProcessToken().GetTokenUser()
	if err != nil {
		t.Fatal(err)
	}
	setTestKeyFileDACL(t, path, "D:P(A;;FA;;;"+current.User.Sid.String()+")(A;;FR;;;WD)")

	_, err = LoadPrivateKeyFile(path, 32)
	if !errors.Is(err, ErrKey) {
		t.Fatalf("LoadPrivateKeyFile() error = %v, want ErrKey", err)
	}
}

func setTestKeyFileDACL(t *testing.T, path, sddl string) {
	t.Helper()
	sd, err := windows.SecurityDescriptorFromString(sddl)
	if err != nil {
		t.Fatal(err)
	}
	dacl, _, err := sd.DACL()
	if err != nil {
		t.Fatal(err)
	}
	if err := windows.SetNamedSecurityInfo(
		path,
		windows.SE_FILE_OBJECT,
		windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION,
		nil,
		nil,
		dacl,
		nil,
	); err != nil {
		t.Fatal(err)
	}
}
