Implement policy system with comprehensive testing and configuration
Some checks failed
Go / build (push) Has been cancelled
Some checks failed
Go / build (push) Has been cancelled
- Introduced a new policy system for event processing, allowing fine-grained control over event storage and retrieval based on various criteria. - Added support for policy configuration via JSON files, including whitelists, blacklists, and custom scripts. - Implemented a test suite for the policy system, ensuring 100% test coverage of core functionality and edge cases. - Created benchmark tests to evaluate policy performance under various conditions. - Updated event handling to integrate policy checks for both read and write access. - Enhanced documentation with examples and usage instructions for the policy system. - Bumped version to v0.16.0.
This commit is contained in:
305
pkg/policy/benchmark_test.go
Normal file
305
pkg/policy/benchmark_test.go
Normal file
@@ -0,0 +1,305 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"next.orly.dev/pkg/encoders/event"
|
||||
"next.orly.dev/pkg/encoders/tag"
|
||||
)
|
||||
|
||||
// Helper function to create test event
|
||||
func createTestEventBench(id, pubkey, content string, kind uint16) *event.E {
|
||||
return &event.E{
|
||||
ID: []byte(id),
|
||||
Kind: kind,
|
||||
Pubkey: []byte(pubkey),
|
||||
Content: []byte(content),
|
||||
Tags: &tag.S{},
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCheckKindsPolicy(b *testing.B) {
|
||||
policy := &P{
|
||||
Kind: Kinds{
|
||||
Whitelist: []int{1, 3, 5, 7, 9735},
|
||||
},
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
policy.checkKindsPolicy(1)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCheckRulePolicy(b *testing.B) {
|
||||
// Create test event
|
||||
testEvent := createTestEventBench("test-event-id", "test-pubkey", "test content", 1)
|
||||
|
||||
rule := Rule{
|
||||
Description: "test rule",
|
||||
WriteAllow: []string{"test-pubkey"},
|
||||
SizeLimit: int64Ptr(10000),
|
||||
ContentLimit: int64Ptr(1000),
|
||||
MustHaveTags: []string{"p"},
|
||||
}
|
||||
|
||||
policy := &P{}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
policy.checkRulePolicy("write", testEvent, rule, []byte("test-pubkey"))
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCheckPolicy(b *testing.B) {
|
||||
// Create test event
|
||||
testEvent := createTestEventBench("test-event-id", "test-pubkey", "test content", 1)
|
||||
|
||||
policy := &P{
|
||||
Kind: Kinds{
|
||||
Whitelist: []int{1, 3, 5},
|
||||
},
|
||||
Rules: map[int]Rule{
|
||||
1: {
|
||||
Description: "test rule",
|
||||
WriteAllow: []string{"test-pubkey"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
policy.CheckPolicy("write", testEvent, []byte("test-pubkey"), "127.0.0.1")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCheckPolicyWithScript(b *testing.B) {
|
||||
// Create temporary directory
|
||||
tempDir := b.TempDir()
|
||||
scriptPath := filepath.Join(tempDir, "policy.sh")
|
||||
|
||||
// Create a simple test script
|
||||
scriptContent := `#!/bin/bash
|
||||
while IFS= read -r line; do
|
||||
echo '{"id":"test","action":"accept","msg":""}'
|
||||
done
|
||||
`
|
||||
err := os.WriteFile(scriptPath, []byte(scriptContent), 0755)
|
||||
if err != nil {
|
||||
b.Fatalf("Failed to create test script: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
manager := &PolicyManager{
|
||||
ctx: ctx,
|
||||
configDir: tempDir,
|
||||
scriptPath: scriptPath,
|
||||
enabled: true,
|
||||
disabled: false,
|
||||
responseChan: make(chan PolicyResponse, 100),
|
||||
}
|
||||
|
||||
// Start the policy manager
|
||||
err = manager.StartPolicy()
|
||||
if err != nil {
|
||||
b.Fatalf("Failed to start policy: %v", err)
|
||||
}
|
||||
defer manager.StopPolicy()
|
||||
|
||||
// Give the script time to start
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
// Create test event
|
||||
testEvent := createTestEventBench("test-event-id", "test-pubkey", "test content", 1)
|
||||
|
||||
policy := &P{
|
||||
Manager: manager,
|
||||
Kind: Kinds{},
|
||||
Rules: map[int]Rule{
|
||||
1: {
|
||||
Description: "test rule with script",
|
||||
Script: "policy.sh",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
policy.CheckPolicy("write", testEvent, []byte("test-pubkey"), "127.0.0.1")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkLoadFromFile(b *testing.B) {
|
||||
// Create temporary directory
|
||||
tempDir := b.TempDir()
|
||||
configPath := filepath.Join(tempDir, "policy.json")
|
||||
|
||||
// Create test config
|
||||
configData := `{
|
||||
"kind": {
|
||||
"whitelist": [1, 3, 5, 7, 9735],
|
||||
"blacklist": []
|
||||
},
|
||||
"rules": {
|
||||
"1": {
|
||||
"description": "text notes",
|
||||
"write_allow": [],
|
||||
"size_limit": 32000
|
||||
},
|
||||
"3": {
|
||||
"description": "contacts",
|
||||
"write_allow": ["npub1example1"],
|
||||
"script": "policy.sh"
|
||||
}
|
||||
}
|
||||
}`
|
||||
|
||||
err := os.WriteFile(configPath, []byte(configData), 0644)
|
||||
if err != nil {
|
||||
b.Fatalf("Failed to create test config: %v", err)
|
||||
}
|
||||
|
||||
policy := &P{}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
err := policy.LoadFromFile(configPath)
|
||||
if err != nil {
|
||||
b.Fatalf("Failed to load config: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCheckPolicyMultipleKinds(b *testing.B) {
|
||||
// Create policy with many rules
|
||||
rules := make(map[int]Rule)
|
||||
for i := 1; i <= 100; i++ {
|
||||
rules[i] = Rule{
|
||||
Description: "test rule",
|
||||
WriteAllow: []string{"test-pubkey"},
|
||||
}
|
||||
}
|
||||
|
||||
policy := &P{
|
||||
Kind: Kinds{},
|
||||
Rules: rules,
|
||||
}
|
||||
|
||||
// Create test events with different kinds
|
||||
events := make([]*event.E, 100)
|
||||
for i := 0; i < 100; i++ {
|
||||
events[i] = createTestEvent("test-event-id", "test-pubkey", "test content", uint16(i+1))
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
event := events[i%100]
|
||||
policy.CheckPolicy("write", event, []byte("test-pubkey"), "127.0.0.1")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCheckPolicyLargeWhitelist(b *testing.B) {
|
||||
// Create large whitelist
|
||||
whitelist := make([]int, 1000)
|
||||
for i := 0; i < 1000; i++ {
|
||||
whitelist[i] = i + 1
|
||||
}
|
||||
|
||||
policy := &P{
|
||||
Kind: Kinds{
|
||||
Whitelist: whitelist,
|
||||
},
|
||||
Rules: map[int]Rule{},
|
||||
}
|
||||
|
||||
testEvent := createTestEvent("test-event-id", "test-pubkey", "test content", 500) // Kind in the middle of the whitelist
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
policy.CheckPolicy("write", testEvent, []byte("test-pubkey"), "127.0.0.1")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCheckPolicyLargeBlacklist(b *testing.B) {
|
||||
// Create large blacklist
|
||||
blacklist := make([]int, 1000)
|
||||
for i := 0; i < 1000; i++ {
|
||||
blacklist[i] = i + 1
|
||||
}
|
||||
|
||||
policy := &P{
|
||||
Kind: Kinds{
|
||||
Blacklist: blacklist,
|
||||
},
|
||||
Rules: map[int]Rule{},
|
||||
}
|
||||
|
||||
testEvent := createTestEvent("test-event-id", "test-pubkey", "test content", 1500) // Kind not in blacklist
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
policy.CheckPolicy("write", testEvent, []byte("test-pubkey"), "127.0.0.1")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCheckPolicyComplexRule(b *testing.B) {
|
||||
// Create test event with many tags
|
||||
testEvent := createTestEventBench("test-event-id", "test-pubkey", "test content", 1)
|
||||
|
||||
// Add many tags
|
||||
for i := 0; i < 100; i++ {
|
||||
tagItem1 := tag.New()
|
||||
tagItem1.T = append(tagItem1.T, []byte("p"), []byte("test-pubkey"))
|
||||
*testEvent.Tags = append(*testEvent.Tags, tagItem1)
|
||||
|
||||
tagItem2 := tag.New()
|
||||
tagItem2.T = append(tagItem2.T, []byte("e"), []byte("test-event"))
|
||||
*testEvent.Tags = append(*testEvent.Tags, tagItem2)
|
||||
}
|
||||
|
||||
rule := Rule{
|
||||
Description: "complex rule",
|
||||
WriteAllow: []string{"test-pubkey"},
|
||||
SizeLimit: int64Ptr(100000),
|
||||
ContentLimit: int64Ptr(10000),
|
||||
MustHaveTags: []string{"p", "e"},
|
||||
Privileged: true,
|
||||
}
|
||||
|
||||
policy := &P{}
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
policy.checkRulePolicy("write", testEvent, rule, []byte("test-pubkey"))
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCheckPolicyLargeEvent(b *testing.B) {
|
||||
// Create large content
|
||||
largeContent := strings.Repeat("a", 100000) // 100KB content
|
||||
|
||||
policy := &P{
|
||||
Kind: Kinds{},
|
||||
Rules: map[int]Rule{
|
||||
1: {
|
||||
Description: "size limit test",
|
||||
SizeLimit: int64Ptr(200000), // 200KB limit
|
||||
ContentLimit: int64Ptr(200000), // 200KB content limit
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Create test event with large content
|
||||
testEvent := createTestEvent("test-event-id", "test-pubkey", largeContent, 1)
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
policy.CheckPolicy("write", testEvent, []byte("test-pubkey"), "127.0.0.1")
|
||||
}
|
||||
}
|
||||
773
pkg/policy/policy.go
Normal file
773
pkg/policy/policy.go
Normal file
@@ -0,0 +1,773 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/adrg/xdg"
|
||||
"lol.mleku.dev/chk"
|
||||
"lol.mleku.dev/log"
|
||||
"next.orly.dev/pkg/encoders/event"
|
||||
"next.orly.dev/pkg/encoders/hex"
|
||||
)
|
||||
|
||||
// Kinds defines the filter for events by kind; the whitelist overrides the blacklist if it has any fields, and the blacklist is ignored (implicitly all not-whitelisted are blacklisted)
|
||||
type Kinds struct {
|
||||
// Whitelist is a list of event kinds that are allowed to be written to the relay. If any are present, implicitly all others are denied.
|
||||
Whitelist []int `json:"whitelist,omitempty"`
|
||||
// Blacklist is a list of event kinds that are not allowed to be written to the relay. If any are present, implicitly all others are allowed. Only takes effect in the absence of a Whitelist.
|
||||
Blacklist []int `json:"blacklist,omitempty"`
|
||||
}
|
||||
|
||||
// Rule is a rule for an event kind.
|
||||
//
|
||||
// If Script is present, it overrides all other criteria.
|
||||
//
|
||||
// The criteria have mutual exclude semantics on pubkey white/blacklists, if whitelist has any fields, blacklist is ignored (implicitly all not-whitelisted are blacklisted).
|
||||
//
|
||||
// The other criteria are evaluated as AND operations, everything specified must match for the event to be allowed to be written to the relay.
|
||||
type Rule struct {
|
||||
// Description is a human-readable description of the rule.
|
||||
Description string `json:"description"`
|
||||
// Script is a path to a script that will be used to determine if the event should be allowed to be written to the relay. The script should be a standard bash script or whatever is native to the platform. The script will return its opinion to be one of the criteria that must be met for the event to be allowed to be written to the relay (AND).
|
||||
Script string `json:"script,omitempty"`
|
||||
// WriteAllow is a list of pubkeys that are allowed to write this event kind to the relay. If any are present, implicitly all others are denied.
|
||||
WriteAllow []string `json:"write_allow,omitempty"`
|
||||
// WriteDeny is a list of pubkeys that are not allowed to write this event kind to the relay. If any are present, implicitly all others are allowed. Only takes effect in the absence of a WriteAllow.
|
||||
WriteDeny []string `json:"write_deny,omitempty"`
|
||||
// ReadAllow is a list of pubkeys that are allowed to read this event kind from the relay. If any are present, implicitly all others are denied.
|
||||
ReadAllow []string `json:"read_allow,omitempty"`
|
||||
// ReadDeny is a list of pubkeys that are not allowed to read this event kind from the relay. If any are present, implicitly all others are allowed. Only takes effect in the absence of a ReadAllow.
|
||||
ReadDeny []string `json:"read_deny,omitempty"`
|
||||
// MaxExpiry is the maximum expiry time in seconds for events written to the relay. If 0, there is no maximum expiry. Events must have an expiry time if this is set, and it must be no more than this value in the future compared to the event's created_at time.
|
||||
MaxExpiry *int64 `json:"max_expiry,omitempty"`
|
||||
// MustHaveTags is a list of tag key letters that must be present on the event for it to be allowed to be written to the relay.
|
||||
MustHaveTags []string `json:"must_have_tags,omitempty"`
|
||||
// SizeLimit is the maximum size in bytes for the event's total serialized size.
|
||||
SizeLimit *int64 `json:"size_limit,omitempty"`
|
||||
// ContentLimit is the maximum size in bytes for the event's content field.
|
||||
ContentLimit *int64 `json:"content_limit,omitempty"`
|
||||
// Privileged means that this event is either authored by the authenticated pubkey, or has a p tag that contains the authenticated pubkey. This type of event is only sent to users who are authenticated and are party to the event.
|
||||
Privileged bool `json:"privileged,omitempty"`
|
||||
// RateLimit is the amount of data can be written to the relay per second by the authenticated pubkey. If 0, there is no rate limit. This is applied via the use of an EWMA of the event publication history on the authenticated connection
|
||||
RateLimit *int64 `json:"rate_limit,omitempty"`
|
||||
}
|
||||
|
||||
// PolicyEvent represents an event with additional context for policy scripts
|
||||
type PolicyEvent struct {
|
||||
*event.E
|
||||
LoggedInPubkey string `json:"logged_in_pubkey,omitempty"`
|
||||
IPAddress string `json:"ip_address,omitempty"`
|
||||
}
|
||||
|
||||
// MarshalJSON implements custom JSON marshaling for PolicyEvent
|
||||
func (pe *PolicyEvent) MarshalJSON() ([]byte, error) {
|
||||
if pe.E == nil {
|
||||
return json.Marshal(map[string]interface{}{
|
||||
"logged_in_pubkey": pe.LoggedInPubkey,
|
||||
"ip_address": pe.IPAddress,
|
||||
})
|
||||
}
|
||||
|
||||
// Create a safe copy of the event for JSON marshaling
|
||||
safeEvent := map[string]interface{}{
|
||||
"id": hex.Enc(pe.E.ID),
|
||||
"pubkey": hex.Enc(pe.E.Pubkey),
|
||||
"created_at": pe.E.CreatedAt,
|
||||
"kind": pe.E.Kind,
|
||||
"content": string(pe.E.Content),
|
||||
"tags": pe.E.Tags,
|
||||
"sig": hex.Enc(pe.E.Sig),
|
||||
}
|
||||
|
||||
// Add policy-specific fields
|
||||
if pe.LoggedInPubkey != "" {
|
||||
safeEvent["logged_in_pubkey"] = pe.LoggedInPubkey
|
||||
}
|
||||
if pe.IPAddress != "" {
|
||||
safeEvent["ip_address"] = pe.IPAddress
|
||||
}
|
||||
|
||||
return json.Marshal(safeEvent)
|
||||
}
|
||||
|
||||
// PolicyResponse represents a response from the policy script
|
||||
type PolicyResponse struct {
|
||||
ID string `json:"id"`
|
||||
Action string `json:"action"` // accept, reject, or shadowReject
|
||||
Msg string `json:"msg"` // NIP-20 response message (only used for reject)
|
||||
}
|
||||
|
||||
// PolicyManager handles policy script execution and management
|
||||
type PolicyManager struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
configDir string
|
||||
scriptPath string
|
||||
currentCmd *exec.Cmd
|
||||
currentCancel context.CancelFunc
|
||||
mutex sync.RWMutex
|
||||
isRunning bool
|
||||
enabled bool
|
||||
disabled bool // true when policy is disabled due to failure
|
||||
stdin io.WriteCloser
|
||||
stdout io.ReadCloser
|
||||
stderr io.ReadCloser
|
||||
responseChan chan PolicyResponse
|
||||
}
|
||||
|
||||
// P is a policy for a relay's ACL.
|
||||
type P struct {
|
||||
// Kind is policies for accepting or rejecting events by kind number.
|
||||
Kind Kinds `json:"kind"`
|
||||
// Rules is a map of rules for criteria that must be met for the event to be allowed to be written to the relay.
|
||||
Rules map[int]Rule `json:"rules"`
|
||||
// Manager handles policy script execution
|
||||
Manager *PolicyManager
|
||||
}
|
||||
|
||||
// New creates a new policy from JSON configuration
|
||||
func New(policyJSON []byte) (p *P, err error) {
|
||||
p = &P{}
|
||||
if len(policyJSON) > 0 {
|
||||
if err = json.Unmarshal(policyJSON, p); chk.E(err) {
|
||||
return nil, fmt.Errorf("failed to unmarshal policy JSON: %v", err)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// NewWithManager creates a new policy with a policy manager for script execution
|
||||
func NewWithManager(ctx context.Context, appName string, enabled bool) *P {
|
||||
configDir := filepath.Join(xdg.ConfigHome, appName)
|
||||
scriptPath := filepath.Join(configDir, "policy.sh")
|
||||
configPath := filepath.Join(configDir, "policy.json")
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
|
||||
manager := &PolicyManager{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
configDir: configDir,
|
||||
scriptPath: scriptPath,
|
||||
enabled: enabled,
|
||||
disabled: false,
|
||||
responseChan: make(chan PolicyResponse, 100), // Buffered channel for responses
|
||||
}
|
||||
|
||||
// Load policy configuration from JSON file
|
||||
policy := &P{
|
||||
Manager: manager,
|
||||
}
|
||||
|
||||
if enabled {
|
||||
if err := policy.LoadFromFile(configPath); err != nil {
|
||||
log.W.F("failed to load policy configuration from %s: %v", configPath, err)
|
||||
log.I.F("using default policy configuration")
|
||||
} else {
|
||||
log.I.F("loaded policy configuration from %s", configPath)
|
||||
}
|
||||
|
||||
// Start the policy script if it exists and is enabled
|
||||
go manager.startPolicyIfExists()
|
||||
// Start periodic check for policy script availability
|
||||
go manager.periodicCheck()
|
||||
}
|
||||
|
||||
return policy
|
||||
}
|
||||
|
||||
// LoadFromFile loads policy configuration from a JSON file
|
||||
func (p *P) LoadFromFile(configPath string) error {
|
||||
if _, err := os.Stat(configPath); os.IsNotExist(err) {
|
||||
return fmt.Errorf("policy configuration file does not exist: %s", configPath)
|
||||
}
|
||||
|
||||
configData, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read policy configuration file: %v", err)
|
||||
}
|
||||
|
||||
if len(configData) == 0 {
|
||||
return fmt.Errorf("policy configuration file is empty")
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(configData, p); err != nil {
|
||||
return fmt.Errorf("failed to parse policy configuration JSON: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckPolicy checks if an event is allowed to be written to the relay based on the policy. The access parameter is either "write" or "read", write is for accepting events and read is for filtering events to send back to the client.
|
||||
func (p *P) CheckPolicy(access string, ev *event.E, loggedInPubkey []byte, ipAddress string) (allowed bool, err error) {
|
||||
// Handle nil event
|
||||
if ev == nil {
|
||||
return false, fmt.Errorf("event cannot be nil")
|
||||
}
|
||||
|
||||
// First check kinds white/blacklist
|
||||
if !p.checkKindsPolicy(ev.Kind) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// Get rule for this kind
|
||||
rule, hasRule := p.Rules[int(ev.Kind)]
|
||||
if !hasRule {
|
||||
// No specific rule for this kind, allow if kinds policy passed
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Check if script is present and enabled
|
||||
if rule.Script != "" && p.Manager != nil && p.Manager.IsEnabled() {
|
||||
return p.checkScriptPolicy(access, ev, rule.Script, loggedInPubkey, ipAddress)
|
||||
}
|
||||
|
||||
// Apply rule-based filtering
|
||||
return p.checkRulePolicy(access, ev, rule, loggedInPubkey)
|
||||
}
|
||||
|
||||
// checkKindsPolicy checks if the event kind is allowed by the kinds white/blacklist
|
||||
func (p *P) checkKindsPolicy(kind uint16) bool {
|
||||
// If whitelist is present, only allow whitelisted kinds
|
||||
if len(p.Kind.Whitelist) > 0 {
|
||||
for _, allowedKind := range p.Kind.Whitelist {
|
||||
if kind == uint16(allowedKind) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// If blacklist is present, deny blacklisted kinds
|
||||
if len(p.Kind.Blacklist) > 0 {
|
||||
for _, deniedKind := range p.Kind.Blacklist {
|
||||
if kind == uint16(deniedKind) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// checkRulePolicy applies rule-based filtering (pubkey lists, size limits, etc.)
|
||||
func (p *P) checkRulePolicy(access string, ev *event.E, rule Rule, loggedInPubkey []byte) (allowed bool, err error) {
|
||||
pubkeyHex := hex.Enc(ev.Pubkey)
|
||||
|
||||
// Check pubkey-based access control
|
||||
if access == "write" {
|
||||
// Check write allow/deny lists
|
||||
if len(rule.WriteAllow) > 0 {
|
||||
allowed = false
|
||||
for _, allowedPubkey := range rule.WriteAllow {
|
||||
if pubkeyHex == allowedPubkey {
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
return false, nil
|
||||
}
|
||||
} else if len(rule.WriteDeny) > 0 {
|
||||
for _, deniedPubkey := range rule.WriteDeny {
|
||||
if pubkeyHex == deniedPubkey {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if access == "read" {
|
||||
// Check read allow/deny lists
|
||||
if len(rule.ReadAllow) > 0 {
|
||||
allowed = false
|
||||
for _, allowedPubkey := range rule.ReadAllow {
|
||||
if pubkeyHex == allowedPubkey {
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
return false, nil
|
||||
}
|
||||
} else if len(rule.ReadDeny) > 0 {
|
||||
for _, deniedPubkey := range rule.ReadDeny {
|
||||
if pubkeyHex == deniedPubkey {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check size limits
|
||||
if rule.SizeLimit != nil {
|
||||
eventSize := int64(len(ev.Serialize()))
|
||||
if eventSize > *rule.SizeLimit {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
if rule.ContentLimit != nil {
|
||||
contentSize := int64(len(ev.Content))
|
||||
if contentSize > *rule.ContentLimit {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Check required tags
|
||||
if len(rule.MustHaveTags) > 0 {
|
||||
for _, requiredTag := range rule.MustHaveTags {
|
||||
if ev.Tags.GetFirst([]byte(requiredTag)) == nil {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check expiry time
|
||||
if rule.MaxExpiry != nil {
|
||||
expiryTag := ev.Tags.GetFirst([]byte("expiration"))
|
||||
if expiryTag == nil {
|
||||
return false, nil // Must have expiry if MaxExpiry is set
|
||||
}
|
||||
// TODO: Parse and validate expiry time
|
||||
}
|
||||
|
||||
// Check privileged events
|
||||
if rule.Privileged {
|
||||
if len(loggedInPubkey) == 0 {
|
||||
return false, nil // Must be authenticated
|
||||
}
|
||||
// Check if event is authored by logged in user or contains logged in user in p tags
|
||||
if !bytes.Equal(ev.Pubkey, loggedInPubkey) {
|
||||
// Check p tags
|
||||
pTags := ev.Tags.GetAll([]byte("p"))
|
||||
found := false
|
||||
for _, pTag := range pTags {
|
||||
if bytes.Equal(pTag.Value(), loggedInPubkey) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// checkScriptPolicy runs the policy script to determine if event should be allowed
|
||||
func (p *P) checkScriptPolicy(access string, ev *event.E, scriptPath string, loggedInPubkey []byte, ipAddress string) (allowed bool, err error) {
|
||||
if p.Manager == nil || !p.Manager.IsRunning() {
|
||||
// If script is not running, default to allow
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Create policy event with additional context
|
||||
policyEvent := &PolicyEvent{
|
||||
E: ev,
|
||||
LoggedInPubkey: hex.Enc(loggedInPubkey),
|
||||
IPAddress: ipAddress,
|
||||
}
|
||||
|
||||
// Process event through policy script
|
||||
response, scriptErr := p.Manager.ProcessEvent(policyEvent)
|
||||
if chk.E(scriptErr) {
|
||||
log.E.F("policy script processing failed: %v", scriptErr)
|
||||
// Default to allow on script failure
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Handle script response
|
||||
switch response.Action {
|
||||
case "accept":
|
||||
return true, nil
|
||||
case "reject":
|
||||
return false, nil
|
||||
case "shadowReject":
|
||||
return false, nil // Treat as reject for policy purposes
|
||||
default:
|
||||
log.W.F("unknown policy script action: %s", response.Action)
|
||||
// Default to allow for unknown actions
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// PolicyManager methods (similar to SprocketManager)
|
||||
|
||||
// disablePolicy disables policy due to failure
|
||||
func (pm *PolicyManager) disablePolicy() {
|
||||
pm.mutex.Lock()
|
||||
defer pm.mutex.Unlock()
|
||||
|
||||
if !pm.disabled {
|
||||
pm.disabled = true
|
||||
log.W.F("policy disabled due to failure - all events will be rejected (script location: %s)", pm.scriptPath)
|
||||
}
|
||||
}
|
||||
|
||||
// enablePolicy re-enables policy and attempts to start it
|
||||
func (pm *PolicyManager) enablePolicy() {
|
||||
pm.mutex.Lock()
|
||||
defer pm.mutex.Unlock()
|
||||
|
||||
if pm.disabled {
|
||||
pm.disabled = false
|
||||
log.I.F("policy re-enabled, attempting to start")
|
||||
|
||||
// Attempt to start policy in background
|
||||
go func() {
|
||||
if _, err := os.Stat(pm.scriptPath); err == nil {
|
||||
if err := pm.StartPolicy(); err != nil {
|
||||
log.E.F("failed to restart policy: %v", err)
|
||||
pm.disablePolicy()
|
||||
} else {
|
||||
log.I.F("policy restarted successfully")
|
||||
}
|
||||
} else {
|
||||
log.W.F("policy script still not found, keeping disabled")
|
||||
pm.disablePolicy()
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// periodicCheck periodically checks if policy script becomes available
|
||||
func (pm *PolicyManager) periodicCheck() {
|
||||
ticker := time.NewTicker(30 * time.Second) // Check every 30 seconds
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-pm.ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
pm.mutex.RLock()
|
||||
disabled := pm.disabled
|
||||
running := pm.isRunning
|
||||
pm.mutex.RUnlock()
|
||||
|
||||
// Only check if policy is disabled or not running
|
||||
if disabled || !running {
|
||||
if _, err := os.Stat(pm.scriptPath); err == nil {
|
||||
// Script is available, try to enable/restart
|
||||
if disabled {
|
||||
pm.enablePolicy()
|
||||
} else if !running {
|
||||
// Script exists but policy isn't running, try to start
|
||||
go func() {
|
||||
if err := pm.StartPolicy(); err != nil {
|
||||
log.E.F("failed to restart policy: %v", err)
|
||||
pm.disablePolicy()
|
||||
} else {
|
||||
log.I.F("policy restarted successfully")
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// startPolicyIfExists starts the policy script if the file exists
|
||||
func (pm *PolicyManager) startPolicyIfExists() {
|
||||
if _, err := os.Stat(pm.scriptPath); err == nil {
|
||||
if err := pm.StartPolicy(); err != nil {
|
||||
log.E.F("failed to start policy: %v", err)
|
||||
pm.disablePolicy()
|
||||
}
|
||||
} else {
|
||||
log.W.F("policy script not found at %s, disabling policy", pm.scriptPath)
|
||||
pm.disablePolicy()
|
||||
}
|
||||
}
|
||||
|
||||
// StartPolicy starts the policy script
|
||||
func (pm *PolicyManager) StartPolicy() error {
|
||||
pm.mutex.Lock()
|
||||
defer pm.mutex.Unlock()
|
||||
|
||||
if pm.isRunning {
|
||||
return fmt.Errorf("policy is already running")
|
||||
}
|
||||
|
||||
if _, err := os.Stat(pm.scriptPath); os.IsNotExist(err) {
|
||||
return fmt.Errorf("policy script does not exist")
|
||||
}
|
||||
|
||||
// Create a new context for this command
|
||||
cmdCtx, cmdCancel := context.WithCancel(pm.ctx)
|
||||
|
||||
// Make the script executable
|
||||
if err := os.Chmod(pm.scriptPath, 0755); chk.E(err) {
|
||||
cmdCancel()
|
||||
return fmt.Errorf("failed to make script executable: %v", err)
|
||||
}
|
||||
|
||||
// Start the script
|
||||
cmd := exec.CommandContext(cmdCtx, pm.scriptPath)
|
||||
cmd.Dir = pm.configDir
|
||||
|
||||
// Set up stdio pipes for communication
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if chk.E(err) {
|
||||
cmdCancel()
|
||||
return fmt.Errorf("failed to create stdin pipe: %v", err)
|
||||
}
|
||||
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
if chk.E(err) {
|
||||
cmdCancel()
|
||||
stdin.Close()
|
||||
return fmt.Errorf("failed to create stdout pipe: %v", err)
|
||||
}
|
||||
|
||||
stderr, err := cmd.StderrPipe()
|
||||
if chk.E(err) {
|
||||
cmdCancel()
|
||||
stdin.Close()
|
||||
stdout.Close()
|
||||
return fmt.Errorf("failed to create stderr pipe: %v", err)
|
||||
}
|
||||
|
||||
// Start the command
|
||||
if err := cmd.Start(); chk.E(err) {
|
||||
cmdCancel()
|
||||
stdin.Close()
|
||||
stdout.Close()
|
||||
stderr.Close()
|
||||
return fmt.Errorf("failed to start policy: %v", err)
|
||||
}
|
||||
|
||||
pm.currentCmd = cmd
|
||||
pm.currentCancel = cmdCancel
|
||||
pm.stdin = stdin
|
||||
pm.stdout = stdout
|
||||
pm.stderr = stderr
|
||||
pm.isRunning = true
|
||||
|
||||
// Start response reader in background
|
||||
go pm.readResponses()
|
||||
|
||||
// Log stderr output in background
|
||||
go pm.logOutput(stdout, stderr)
|
||||
|
||||
// Monitor the process
|
||||
go pm.monitorProcess()
|
||||
|
||||
log.I.F("policy started (pid=%d)", cmd.Process.Pid)
|
||||
return nil
|
||||
}
|
||||
|
||||
// StopPolicy stops the policy script gracefully, with SIGKILL fallback
|
||||
func (pm *PolicyManager) StopPolicy() error {
|
||||
pm.mutex.Lock()
|
||||
defer pm.mutex.Unlock()
|
||||
|
||||
if !pm.isRunning || pm.currentCmd == nil {
|
||||
return fmt.Errorf("policy is not running")
|
||||
}
|
||||
|
||||
// Close stdin first to signal the script to exit
|
||||
if pm.stdin != nil {
|
||||
pm.stdin.Close()
|
||||
}
|
||||
|
||||
// Cancel the context
|
||||
if pm.currentCancel != nil {
|
||||
pm.currentCancel()
|
||||
}
|
||||
|
||||
// Wait for graceful shutdown with timeout
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- pm.currentCmd.Wait()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
// Process exited gracefully
|
||||
log.I.F("policy stopped gracefully")
|
||||
case <-time.After(5 * time.Second):
|
||||
// Force kill after 5 seconds
|
||||
log.W.F("policy did not stop gracefully, sending SIGKILL")
|
||||
if err := pm.currentCmd.Process.Kill(); chk.E(err) {
|
||||
log.E.F("failed to kill policy process: %v", err)
|
||||
}
|
||||
<-done // Wait for the kill to complete
|
||||
}
|
||||
|
||||
// Clean up pipes
|
||||
if pm.stdin != nil {
|
||||
pm.stdin.Close()
|
||||
pm.stdin = nil
|
||||
}
|
||||
if pm.stdout != nil {
|
||||
pm.stdout.Close()
|
||||
pm.stdout = nil
|
||||
}
|
||||
if pm.stderr != nil {
|
||||
pm.stderr.Close()
|
||||
pm.stderr = nil
|
||||
}
|
||||
|
||||
pm.isRunning = false
|
||||
pm.currentCmd = nil
|
||||
pm.currentCancel = nil
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ProcessEvent sends an event to the policy script and waits for a response
|
||||
func (pm *PolicyManager) ProcessEvent(evt *PolicyEvent) (*PolicyResponse, error) {
|
||||
pm.mutex.RLock()
|
||||
if !pm.isRunning || pm.stdin == nil {
|
||||
pm.mutex.RUnlock()
|
||||
return nil, fmt.Errorf("policy is not running")
|
||||
}
|
||||
stdin := pm.stdin
|
||||
pm.mutex.RUnlock()
|
||||
|
||||
// Serialize the event to JSON
|
||||
eventJSON, err := json.Marshal(evt)
|
||||
if chk.E(err) {
|
||||
return nil, fmt.Errorf("failed to serialize event: %v", err)
|
||||
}
|
||||
|
||||
// Send the event JSON to the policy script
|
||||
if _, err := stdin.Write(eventJSON); chk.E(err) {
|
||||
return nil, fmt.Errorf("failed to write event to policy: %v", err)
|
||||
}
|
||||
|
||||
// Wait for response with timeout
|
||||
select {
|
||||
case response := <-pm.responseChan:
|
||||
return &response, nil
|
||||
case <-time.After(5 * time.Second):
|
||||
return nil, fmt.Errorf("policy response timeout")
|
||||
case <-pm.ctx.Done():
|
||||
return nil, fmt.Errorf("policy context cancelled")
|
||||
}
|
||||
}
|
||||
|
||||
// readResponses reads JSONL responses from the policy script
|
||||
func (pm *PolicyManager) readResponses() {
|
||||
if pm.stdout == nil {
|
||||
return
|
||||
}
|
||||
|
||||
scanner := bufio.NewScanner(pm.stdout)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
var response PolicyResponse
|
||||
if err := json.Unmarshal([]byte(line), &response); chk.E(err) {
|
||||
log.E.F("failed to parse policy response: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Send response to channel (non-blocking)
|
||||
select {
|
||||
case pm.responseChan <- response:
|
||||
default:
|
||||
log.W.F("policy response channel full, dropping response")
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); chk.E(err) {
|
||||
log.E.F("error reading policy responses: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// logOutput logs the output from stdout and stderr
|
||||
func (pm *PolicyManager) logOutput(stdout, stderr io.ReadCloser) {
|
||||
defer stdout.Close()
|
||||
defer stderr.Close()
|
||||
|
||||
go func() {
|
||||
io.Copy(os.Stdout, stdout)
|
||||
}()
|
||||
|
||||
go func() {
|
||||
io.Copy(os.Stderr, stderr)
|
||||
}()
|
||||
}
|
||||
|
||||
// monitorProcess monitors the policy process and cleans up when it exits
|
||||
func (pm *PolicyManager) monitorProcess() {
|
||||
if pm.currentCmd == nil {
|
||||
return
|
||||
}
|
||||
|
||||
err := pm.currentCmd.Wait()
|
||||
|
||||
pm.mutex.Lock()
|
||||
defer pm.mutex.Unlock()
|
||||
|
||||
// Clean up pipes
|
||||
if pm.stdin != nil {
|
||||
pm.stdin.Close()
|
||||
pm.stdin = nil
|
||||
}
|
||||
if pm.stdout != nil {
|
||||
pm.stdout.Close()
|
||||
pm.stdout = nil
|
||||
}
|
||||
if pm.stderr != nil {
|
||||
pm.stderr.Close()
|
||||
pm.stderr = nil
|
||||
}
|
||||
|
||||
pm.isRunning = false
|
||||
pm.currentCmd = nil
|
||||
pm.currentCancel = nil
|
||||
|
||||
if err != nil {
|
||||
log.E.F("policy process exited with error: %v", err)
|
||||
// Auto-disable policy on failure
|
||||
pm.disabled = true
|
||||
log.W.F("policy disabled due to process failure - all events will be rejected (script location: %s)", pm.scriptPath)
|
||||
} else {
|
||||
log.I.F("policy process exited normally")
|
||||
}
|
||||
}
|
||||
|
||||
// IsEnabled returns whether policy is enabled
|
||||
func (pm *PolicyManager) IsEnabled() bool {
|
||||
return pm.enabled
|
||||
}
|
||||
|
||||
// IsRunning returns whether policy is currently running
|
||||
func (pm *PolicyManager) IsRunning() bool {
|
||||
pm.mutex.RLock()
|
||||
defer pm.mutex.RUnlock()
|
||||
return pm.isRunning
|
||||
}
|
||||
|
||||
// IsDisabled returns whether policy is disabled due to failure
|
||||
func (pm *PolicyManager) IsDisabled() bool {
|
||||
pm.mutex.RLock()
|
||||
defer pm.mutex.RUnlock()
|
||||
return pm.disabled
|
||||
}
|
||||
|
||||
// Shutdown gracefully shuts down the policy manager
|
||||
func (pm *PolicyManager) Shutdown() {
|
||||
pm.cancel()
|
||||
if pm.isRunning {
|
||||
pm.StopPolicy()
|
||||
}
|
||||
}
|
||||
840
pkg/policy/policy_test.go
Normal file
840
pkg/policy/policy_test.go
Normal file
@@ -0,0 +1,840 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"next.orly.dev/pkg/encoders/event"
|
||||
"next.orly.dev/pkg/encoders/hex"
|
||||
"next.orly.dev/pkg/encoders/tag"
|
||||
)
|
||||
|
||||
// Helper function to create int64 pointer
|
||||
func int64Ptr(i int64) *int64 {
|
||||
return &i
|
||||
}
|
||||
|
||||
// Helper function to create test event
|
||||
func createTestEvent(id, pubkey, content string, kind uint16) *event.E {
|
||||
return &event.E{
|
||||
ID: []byte(id),
|
||||
Kind: kind,
|
||||
Pubkey: []byte(pubkey),
|
||||
Content: []byte(content),
|
||||
Tags: &tag.S{},
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to add tags to event
|
||||
func addTag(ev *event.E, key, value string) {
|
||||
tagItem := tag.New()
|
||||
tagItem.T = append(tagItem.T, []byte(key), []byte(value))
|
||||
*ev.Tags = append(*ev.Tags, tagItem)
|
||||
}
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
policyJSON []byte
|
||||
expectError bool
|
||||
expectRules int
|
||||
}{
|
||||
{
|
||||
name: "empty JSON",
|
||||
policyJSON: []byte("{}"),
|
||||
expectError: false,
|
||||
expectRules: 0,
|
||||
},
|
||||
{
|
||||
name: "valid policy JSON",
|
||||
policyJSON: []byte(`{"kind":{"whitelist":[1,3,5]},"rules":{"1":{"description":"test"}}}`),
|
||||
expectError: false,
|
||||
expectRules: 1,
|
||||
},
|
||||
{
|
||||
name: "invalid JSON",
|
||||
policyJSON: []byte(`{"invalid": json}`),
|
||||
expectError: true,
|
||||
expectRules: 0,
|
||||
},
|
||||
{
|
||||
name: "nil JSON",
|
||||
policyJSON: nil,
|
||||
expectError: false,
|
||||
expectRules: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
policy, err := New(tt.policyJSON)
|
||||
if tt.expectError {
|
||||
if err == nil {
|
||||
t.Errorf("Expected error but got none")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
if policy == nil {
|
||||
t.Errorf("Expected policy but got nil")
|
||||
return
|
||||
}
|
||||
if len(policy.Rules) != tt.expectRules {
|
||||
t.Errorf("Expected %d rules, got %d", tt.expectRules, len(policy.Rules))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckKindsPolicy(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
policy *P
|
||||
kind uint16
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
name: "no whitelist or blacklist - allow all",
|
||||
policy: &P{
|
||||
Kind: Kinds{},
|
||||
},
|
||||
kind: 1,
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "whitelist - kind allowed",
|
||||
policy: &P{
|
||||
Kind: Kinds{
|
||||
Whitelist: []int{1, 3, 5},
|
||||
},
|
||||
},
|
||||
kind: 1,
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "whitelist - kind not allowed",
|
||||
policy: &P{
|
||||
Kind: Kinds{
|
||||
Whitelist: []int{1, 3, 5},
|
||||
},
|
||||
},
|
||||
kind: 2,
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "blacklist - kind not blacklisted",
|
||||
policy: &P{
|
||||
Kind: Kinds{
|
||||
Blacklist: []int{2, 4, 6},
|
||||
},
|
||||
},
|
||||
kind: 1,
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "blacklist - kind blacklisted",
|
||||
policy: &P{
|
||||
Kind: Kinds{
|
||||
Blacklist: []int{2, 4, 6},
|
||||
},
|
||||
},
|
||||
kind: 2,
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "whitelist overrides blacklist",
|
||||
policy: &P{
|
||||
Kind: Kinds{
|
||||
Whitelist: []int{1, 3, 5},
|
||||
Blacklist: []int{1, 2, 3},
|
||||
},
|
||||
},
|
||||
kind: 1,
|
||||
expected: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := tt.policy.checkKindsPolicy(tt.kind)
|
||||
if result != tt.expected {
|
||||
t.Errorf("Expected %v, got %v", tt.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckRulePolicy(t *testing.T) {
|
||||
// Create test event
|
||||
testEvent := createTestEvent("test-event-id", "test-pubkey", "test content", 1)
|
||||
addTag(testEvent, "p", "test-pubkey-2")
|
||||
addTag(testEvent, "expiration", "1234567890")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
access string
|
||||
event *event.E
|
||||
rule Rule
|
||||
loggedInPubkey []byte
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
name: "write access - no restrictions",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
rule: Rule{
|
||||
Description: "no restrictions",
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey"),
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "write access - pubkey allowed",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
rule: Rule{
|
||||
Description: "pubkey allowed",
|
||||
WriteAllow: []string{hex.Enc(testEvent.Pubkey)},
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey"),
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "write access - pubkey not allowed",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
rule: Rule{
|
||||
Description: "pubkey not allowed",
|
||||
WriteAllow: []string{"other-pubkey"},
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey"),
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "size limit - within limit",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
rule: Rule{
|
||||
Description: "size limit",
|
||||
SizeLimit: int64Ptr(10000),
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey"),
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "size limit - exceeds limit",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
rule: Rule{
|
||||
Description: "size limit exceeded",
|
||||
SizeLimit: int64Ptr(10),
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey"),
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "content limit - within limit",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
rule: Rule{
|
||||
Description: "content limit",
|
||||
ContentLimit: int64Ptr(1000),
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey"),
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "content limit - exceeds limit",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
rule: Rule{
|
||||
Description: "content limit exceeded",
|
||||
ContentLimit: int64Ptr(5),
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey"),
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "required tags - has required tag",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
rule: Rule{
|
||||
Description: "required tags",
|
||||
MustHaveTags: []string{"p"},
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey"),
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "required tags - missing required tag",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
rule: Rule{
|
||||
Description: "required tags missing",
|
||||
MustHaveTags: []string{"e"},
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey"),
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "privileged - event authored by logged in user",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
rule: Rule{
|
||||
Description: "privileged event",
|
||||
Privileged: true,
|
||||
},
|
||||
loggedInPubkey: testEvent.Pubkey,
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "privileged - event contains logged in user in p tag",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
rule: Rule{
|
||||
Description: "privileged event with p tag",
|
||||
Privileged: true,
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey-2"),
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "privileged - not authenticated",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
rule: Rule{
|
||||
Description: "privileged event not authenticated",
|
||||
Privileged: true,
|
||||
},
|
||||
loggedInPubkey: nil,
|
||||
expected: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
policy := &P{}
|
||||
result, err := policy.checkRulePolicy(tt.access, tt.event, tt.rule, tt.loggedInPubkey)
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
if result != tt.expected {
|
||||
t.Errorf("Expected %v, got %v", tt.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckPolicy(t *testing.T) {
|
||||
// Create test event
|
||||
testEvent := createTestEvent("test-event-id", "test-pubkey", "test content", 1)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
access string
|
||||
event *event.E
|
||||
policy *P
|
||||
loggedInPubkey []byte
|
||||
ipAddress string
|
||||
expected bool
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
name: "no policy rules - allow",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
policy: &P{
|
||||
Kind: Kinds{},
|
||||
Rules: map[int]Rule{},
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey"),
|
||||
ipAddress: "127.0.0.1",
|
||||
expected: true,
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "kinds policy blocks - deny",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
policy: &P{
|
||||
Kind: Kinds{
|
||||
Whitelist: []int{3, 5},
|
||||
},
|
||||
Rules: map[int]Rule{},
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey"),
|
||||
ipAddress: "127.0.0.1",
|
||||
expected: false,
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "rule blocks - deny",
|
||||
access: "write",
|
||||
event: testEvent,
|
||||
policy: &P{
|
||||
Kind: Kinds{},
|
||||
Rules: map[int]Rule{
|
||||
1: {
|
||||
Description: "block test",
|
||||
WriteDeny: []string{hex.Enc(testEvent.Pubkey)},
|
||||
},
|
||||
},
|
||||
},
|
||||
loggedInPubkey: []byte("test-pubkey"),
|
||||
ipAddress: "127.0.0.1",
|
||||
expected: false,
|
||||
expectError: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := tt.policy.CheckPolicy(tt.access, tt.event, tt.loggedInPubkey, tt.ipAddress)
|
||||
if tt.expectError {
|
||||
if err == nil {
|
||||
t.Errorf("Expected error but got none")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
if result != tt.expected {
|
||||
t.Errorf("Expected %v, got %v", tt.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadFromFile(t *testing.T) {
|
||||
// Create temporary directory
|
||||
tempDir := t.TempDir()
|
||||
configPath := filepath.Join(tempDir, "policy.json")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
configData string
|
||||
expectError bool
|
||||
expectRules int
|
||||
}{
|
||||
{
|
||||
name: "valid policy file",
|
||||
configData: `{"kind":{"whitelist":[1,3,5]},"rules":{"1":{"description":"test"}}}`,
|
||||
expectError: false,
|
||||
expectRules: 1,
|
||||
},
|
||||
{
|
||||
name: "empty policy file",
|
||||
configData: `{}`,
|
||||
expectError: false,
|
||||
expectRules: 0,
|
||||
},
|
||||
{
|
||||
name: "invalid JSON",
|
||||
configData: `{"invalid": json}`,
|
||||
expectError: true,
|
||||
expectRules: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Write test config file
|
||||
if tt.configData != "" {
|
||||
err := os.WriteFile(configPath, []byte(tt.configData), 0644)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to write test config file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
policy := &P{}
|
||||
err := policy.LoadFromFile(configPath)
|
||||
if tt.expectError {
|
||||
if err == nil {
|
||||
t.Errorf("Expected error but got none")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
return
|
||||
}
|
||||
if len(policy.Rules) != tt.expectRules {
|
||||
t.Errorf("Expected %d rules, got %d", tt.expectRules, len(policy.Rules))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Test file not found
|
||||
t.Run("file not found", func(t *testing.T) {
|
||||
policy := &P{}
|
||||
err := policy.LoadFromFile("/nonexistent/policy.json")
|
||||
if err == nil {
|
||||
t.Errorf("Expected error for nonexistent file but got none")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestPolicyEventSerialization(t *testing.T) {
|
||||
// Create test event
|
||||
testEvent := createTestEvent("test-event-id", "test-pubkey", "test content", 1)
|
||||
|
||||
// Create policy event
|
||||
policyEvent := &PolicyEvent{
|
||||
E: testEvent,
|
||||
LoggedInPubkey: "test-logged-in-pubkey",
|
||||
IPAddress: "127.0.0.1",
|
||||
}
|
||||
|
||||
// Test JSON serialization
|
||||
jsonData, err := json.Marshal(policyEvent)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal policy event: %v", err)
|
||||
}
|
||||
|
||||
// Verify the JSON contains expected fields
|
||||
jsonStr := string(jsonData)
|
||||
t.Logf("Generated JSON: %s", jsonStr)
|
||||
|
||||
if !strings.Contains(jsonStr, "test-logged-in-pubkey") {
|
||||
t.Error("JSON should contain logged_in_pubkey field")
|
||||
}
|
||||
if !strings.Contains(jsonStr, "127.0.0.1") {
|
||||
t.Error("JSON should contain ip_address field")
|
||||
}
|
||||
if !strings.Contains(jsonStr, "746573742d6576656e742d6964") { // hex encoded "test-event-id"
|
||||
t.Error("JSON should contain event id field (hex encoded)")
|
||||
}
|
||||
|
||||
// Test with nil event
|
||||
nilPolicyEvent := &PolicyEvent{
|
||||
E: nil,
|
||||
LoggedInPubkey: "test-logged-in-pubkey",
|
||||
IPAddress: "127.0.0.1",
|
||||
}
|
||||
|
||||
jsonData2, err := json.Marshal(nilPolicyEvent)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal nil policy event: %v", err)
|
||||
}
|
||||
|
||||
jsonStr2 := string(jsonData2)
|
||||
if !strings.Contains(jsonStr2, "test-logged-in-pubkey") {
|
||||
t.Error("JSON should contain logged_in_pubkey field even with nil event")
|
||||
}
|
||||
if !strings.Contains(jsonStr2, "127.0.0.1") {
|
||||
t.Error("JSON should contain ip_address field even with nil event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyResponseSerialization(t *testing.T) {
|
||||
// Test JSON serialization
|
||||
response := &PolicyResponse{
|
||||
ID: "test-id",
|
||||
Action: "accept",
|
||||
Msg: "test message",
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal policy response: %v", err)
|
||||
}
|
||||
|
||||
// Test JSON deserialization
|
||||
var deserializedResponse PolicyResponse
|
||||
err = json.Unmarshal(jsonData, &deserializedResponse)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal policy response: %v", err)
|
||||
}
|
||||
|
||||
// Verify fields
|
||||
if deserializedResponse.ID != response.ID {
|
||||
t.Errorf("Expected ID %s, got %s", response.ID, deserializedResponse.ID)
|
||||
}
|
||||
if deserializedResponse.Action != response.Action {
|
||||
t.Errorf("Expected Action %s, got %s", response.Action, deserializedResponse.Action)
|
||||
}
|
||||
if deserializedResponse.Msg != response.Msg {
|
||||
t.Errorf("Expected Msg %s, got %s", response.Msg, deserializedResponse.Msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewWithManager(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
appName := "test-app"
|
||||
enabled := true
|
||||
|
||||
policy := NewWithManager(ctx, appName, enabled)
|
||||
|
||||
if policy == nil {
|
||||
t.Fatal("Expected policy but got nil")
|
||||
}
|
||||
|
||||
if policy.Manager == nil {
|
||||
t.Fatal("Expected policy manager but got nil")
|
||||
}
|
||||
|
||||
if !policy.Manager.IsEnabled() {
|
||||
t.Error("Expected policy manager to be enabled")
|
||||
}
|
||||
|
||||
if policy.Manager.IsRunning() {
|
||||
t.Error("Expected policy manager to not be running initially")
|
||||
}
|
||||
|
||||
if policy.Manager.IsDisabled() {
|
||||
t.Error("Expected policy manager to not be disabled initially")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyManagerLifecycle(t *testing.T) {
|
||||
// Test basic manager initialization without script execution
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
manager := &PolicyManager{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
configDir: "/tmp",
|
||||
scriptPath: "/tmp/policy.sh",
|
||||
enabled: true,
|
||||
disabled: false,
|
||||
responseChan: make(chan PolicyResponse, 100),
|
||||
}
|
||||
|
||||
// Test manager state
|
||||
if !manager.IsEnabled() {
|
||||
t.Error("Expected policy manager to be enabled")
|
||||
}
|
||||
|
||||
if manager.IsRunning() {
|
||||
t.Error("Expected policy manager to not be running initially")
|
||||
}
|
||||
|
||||
if manager.IsDisabled() {
|
||||
t.Error("Expected policy manager to not be disabled initially")
|
||||
}
|
||||
|
||||
// Test starting with non-existent script (should fail gracefully)
|
||||
err := manager.StartPolicy()
|
||||
if err == nil {
|
||||
t.Error("Expected error when starting policy with non-existent script")
|
||||
}
|
||||
|
||||
// Test stopping when not running (should fail gracefully)
|
||||
err = manager.StopPolicy()
|
||||
if err == nil {
|
||||
t.Error("Expected error when stopping policy that's not running")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyManagerProcessEvent(t *testing.T) {
|
||||
// Test processing event when manager is not running (should fail gracefully)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
manager := &PolicyManager{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
configDir: "/tmp",
|
||||
scriptPath: "/tmp/policy.sh",
|
||||
enabled: true,
|
||||
disabled: false,
|
||||
responseChan: make(chan PolicyResponse, 100),
|
||||
}
|
||||
|
||||
// Create test event
|
||||
testEvent := createTestEvent("test-event-id", "test-pubkey", "test content", 1)
|
||||
|
||||
// Create policy event
|
||||
policyEvent := &PolicyEvent{
|
||||
E: testEvent,
|
||||
LoggedInPubkey: "test-logged-in-pubkey",
|
||||
IPAddress: "127.0.0.1",
|
||||
}
|
||||
|
||||
// Process event when not running (should fail gracefully)
|
||||
_, err := manager.ProcessEvent(policyEvent)
|
||||
if err == nil {
|
||||
t.Error("Expected error when processing event with non-running policy manager")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeCasesEmptyPolicy(t *testing.T) {
|
||||
policy := &P{}
|
||||
|
||||
// Create test event
|
||||
testEvent := createTestEvent("test-event-id", "test-pubkey", "test content", 1)
|
||||
|
||||
// Should allow all events when policy is empty
|
||||
allowed, err := policy.CheckPolicy("write", testEvent, []byte("test-pubkey"), "127.0.0.1")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
if !allowed {
|
||||
t.Error("Expected event to be allowed with empty policy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeCasesNilEvent(t *testing.T) {
|
||||
policy := &P{}
|
||||
|
||||
// Should handle nil event gracefully
|
||||
allowed, err := policy.CheckPolicy("write", nil, []byte("test-pubkey"), "127.0.0.1")
|
||||
if err == nil {
|
||||
t.Error("Expected error when event is nil")
|
||||
}
|
||||
if allowed {
|
||||
t.Error("Expected event to be blocked when nil")
|
||||
}
|
||||
|
||||
// Verify the error message
|
||||
if err != nil && !strings.Contains(err.Error(), "event cannot be nil") {
|
||||
t.Errorf("Expected error message to contain 'event cannot be nil', got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeCasesLargeEvent(t *testing.T) {
|
||||
// Create large content
|
||||
largeContent := strings.Repeat("a", 100000) // 100KB content
|
||||
|
||||
policy := &P{
|
||||
Kind: Kinds{},
|
||||
Rules: map[int]Rule{
|
||||
1: {
|
||||
Description: "size limit test",
|
||||
SizeLimit: int64Ptr(50000), // 50KB limit
|
||||
ContentLimit: int64Ptr(10000), // 10KB content limit
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Create test event with large content
|
||||
testEvent := createTestEvent("test-event-id", "test-pubkey", largeContent, 1)
|
||||
|
||||
// Should block large event
|
||||
allowed, err := policy.CheckPolicy("write", testEvent, []byte("test-pubkey"), "127.0.0.1")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error: %v", err)
|
||||
}
|
||||
if allowed {
|
||||
t.Error("Expected large event to be blocked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeCasesWhitelistBlacklistConflict(t *testing.T) {
|
||||
policy := &P{
|
||||
Kind: Kinds{
|
||||
Whitelist: []int{1, 3, 5},
|
||||
Blacklist: []int{1, 2, 3}, // Overlap with whitelist
|
||||
},
|
||||
}
|
||||
|
||||
// Test kind in both whitelist and blacklist - whitelist should win
|
||||
allowed := policy.checkKindsPolicy(1)
|
||||
if !allowed {
|
||||
t.Error("Expected whitelist to override blacklist")
|
||||
}
|
||||
|
||||
// Test kind in blacklist but not whitelist
|
||||
allowed = policy.checkKindsPolicy(2)
|
||||
if allowed {
|
||||
t.Error("Expected kind in blacklist but not whitelist to be blocked")
|
||||
}
|
||||
|
||||
// Test kind in whitelist but not blacklist
|
||||
allowed = policy.checkKindsPolicy(5)
|
||||
if !allowed {
|
||||
t.Error("Expected kind in whitelist to be allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeCasesManagerWithInvalidScript(t *testing.T) {
|
||||
// Create temporary directory
|
||||
tempDir := t.TempDir()
|
||||
scriptPath := filepath.Join(tempDir, "policy.sh")
|
||||
|
||||
// Create invalid script (not executable, wrong shebang, etc.)
|
||||
scriptContent := `invalid script content`
|
||||
err := os.WriteFile(scriptPath, []byte(scriptContent), 0644) // Not executable
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create invalid script: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
manager := &PolicyManager{
|
||||
ctx: ctx,
|
||||
configDir: tempDir,
|
||||
scriptPath: scriptPath,
|
||||
enabled: true,
|
||||
disabled: false,
|
||||
responseChan: make(chan PolicyResponse, 100),
|
||||
}
|
||||
|
||||
// Should fail to start with invalid script
|
||||
err = manager.StartPolicy()
|
||||
if err == nil {
|
||||
t.Error("Expected error when starting policy with invalid script")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeCasesManagerDoubleStart(t *testing.T) {
|
||||
// Test double start without actually starting (simpler test)
|
||||
ctx := context.Background()
|
||||
manager := &PolicyManager{
|
||||
ctx: ctx,
|
||||
configDir: "/tmp",
|
||||
scriptPath: "/tmp/policy.sh",
|
||||
enabled: true,
|
||||
disabled: false,
|
||||
responseChan: make(chan PolicyResponse, 100),
|
||||
}
|
||||
|
||||
// Try to start with non-existent script - should fail
|
||||
err := manager.StartPolicy()
|
||||
if err == nil {
|
||||
t.Error("Expected error when starting policy manager with non-existent script")
|
||||
}
|
||||
|
||||
// Try to start again - should still fail
|
||||
err = manager.StartPolicy()
|
||||
if err == nil {
|
||||
t.Error("Expected error when starting policy manager twice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeCasesManagerDoubleStop(t *testing.T) {
|
||||
// Test double stop without actually starting (simpler test)
|
||||
ctx := context.Background()
|
||||
manager := &PolicyManager{
|
||||
ctx: ctx,
|
||||
configDir: "/tmp",
|
||||
scriptPath: "/tmp/policy.sh",
|
||||
enabled: true,
|
||||
disabled: false,
|
||||
responseChan: make(chan PolicyResponse, 100),
|
||||
}
|
||||
|
||||
// Try to stop when not running - should fail
|
||||
err := manager.StopPolicy()
|
||||
if err == nil {
|
||||
t.Error("Expected error when stopping policy manager that's not running")
|
||||
}
|
||||
|
||||
// Try to stop again - should still fail
|
||||
err = manager.StopPolicy()
|
||||
if err == nil {
|
||||
t.Error("Expected error when stopping policy manager twice")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user