package securityevents

import (
	"bytes"
	"context"
	"errors"
	"os"
	"path/filepath"
	"testing"
)

func TestFileSecretStoreCreatesProtectedFilesAndNeverAcceptsTraversal(t *testing.T) {
	directory := filepath.Join(t.TempDir(), "ssf")
	secrets, err := NewFileSecretStore(directory)
	if err != nil {
		t.Fatal(err)
	}
	value := bytes.Repeat([]byte{0x41}, 32)
	if err := secrets.Put(context.Background(), "ssf-push-connection", value); err != nil {
		t.Fatal(err)
	}
	info, err := os.Stat(filepath.Join(directory, "ssf-push-connection"))
	if err != nil || info.Mode().Perm() != 0o600 {
		t.Fatalf("secret mode=%v err=%v", info.Mode().Perm(), err)
	}
	loaded, err := secrets.Get(context.Background(), "ssf-push-connection")
	if err != nil || !bytes.Equal(loaded, value) {
		t.Fatalf("secret mismatch err=%v", err)
	}
	clear(loaded)
	if err := secrets.Put(context.Background(), "../escape", value); err == nil {
		t.Fatal("path traversal reference was accepted")
	}
	if err := secrets.Delete(context.Background(), "ssf-push-connection"); err != nil {
		t.Fatal(err)
	}
	if _, err := secrets.Get(context.Background(), "ssf-push-connection"); !errors.Is(err, ErrSecretNotFound) {
		t.Fatalf("deleted secret error=%v", err)
	}
}
