//go:build linux

package landlock_test

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"testing"

	"github.com/alexfalkowski/go-linux/v2/internal/test"
	"github.com/alexfalkowski/go-linux/v2/landlock"
	"github.com/stretchr/testify/require"
)

// After Linux accepts both allow rules, the builder reports the configured access.
//
//	rules added for /usr and TCP port 443
func ExampleNew() {
	ruleset, err := landlock.New(landlock.Config{
		HandledFS:  landlock.ReadFile | landlock.ReadDir,
		HandledNet: landlock.ConnectTCP,
	})
	if err != nil {
		panic(err)
	}
	defer ruleset.Close()

	if err := ruleset.AddPath("/usr", landlock.ReadFile|landlock.ReadDir); err != nil {
		panic(err)
	}
	if err := ruleset.AddPort(443, landlock.ConnectTCP); err != nil {
		panic(err)
	}
	// Building a ruleset does not restrict this process. Restrict is explicit.
	fmt.Println("rules added for /usr and TCP port 443")
}

// The restricted thread reports the outcome of opening the file for writing.
//
//	write denied
func ExampleRuleset_Restrict() {
	// Execute on a dedicated goroutine in a disposable child during development.
	runtime.LockOSThread() // Intentionally never unlocked, even on failure.
	directory, err := os.MkdirTemp("", "landlock-example-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(directory)
	path := filepath.Join(directory, "read-only")
	if err := os.WriteFile(path, []byte("hello"), 0o600); err != nil {
		panic(err)
	}
	ruleset, err := landlock.New(landlock.Config{HandledFS: landlock.WriteFile})
	if err != nil {
		panic(err)
	}
	defer ruleset.Close()

	if err := ruleset.Restrict(landlock.Options{
		Synchronization: landlock.CallingThread,
		Privileges:      landlock.SetNoNewPrivileges,
	}); err != nil {
		panic(err)
	}

	// Opening for writing is denied on this thread. Reads stay unhandled.
	writer, err := os.OpenFile(path, os.O_WRONLY, 0)
	if err != nil {
		if !errors.Is(err, os.ErrPermission) {
			panic(err)
		}
		fmt.Println("write denied")
		return
	}
	writer.Close()
	panic("expected Landlock write denial")
}

func TestConstructionExample(t *testing.T) {
	test.LandlockAvailable(t, 8)
	require.Equal(t, "rules added for /usr and TCP port 443\n", test.ExampleOutput(t, ExampleNew))
}

func TestRestrictionExample(t *testing.T) {
	test.LandlockAvailable(t, 8)
	if !test.LandlockProcess(t) {
		return
	}
	require.Equal(t, "write denied\n", test.ExampleOutput(t, ExampleRuleset_Restrict))
}
