1 Commits

Author SHA1 Message Date
userAdityaa 732f9b6209 feat(blossom): optional S3-compatible blob storage 2026-05-12 16:50:09 +05:45
14 changed files with 551 additions and 492 deletions
+4 -5
View File
@@ -5,8 +5,8 @@ on:
branches: [master]
env:
REGISTRY: gitea.coracle.social
IMAGE_NAME: coracle/zooid
REGISTRY: ghcr.io
IMAGE_NAME: coracle-social/zooid
jobs:
build-and-push-image:
@@ -23,8 +23,8 @@ jobs:
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: hodlbod
password: ${{ secrets.PACKAGE_TOKEN }}
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
- name: Extract metadata (tags, labels) for Docker
id: meta
@@ -48,4 +48,3 @@ jobs:
platforms: linux/amd64,linux/arm64
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+1 -13
View File
@@ -32,7 +32,7 @@ docker run -it \
-v ./config:/app/config \
-v ./media:/app/media \
-v ./data:/app/data \
gitea.coracle.social/coracle/zooid
ghcr.io/coracle-social/zooid
```
Drop a TOML config file into `./config/` (see [Configuration](#configuration)) and the relay will be available at `ws://<host>:3334`.
@@ -96,18 +96,6 @@ Configures blossom support.
- `enabled` - whether blossom is enabled.
- `authenticated_read` - whether users must perform NIP 98 AUTH in order to fetch a file.
- `adapter` - where to store blobs. Either `local` (the default, stores files under `MEDIA`) or `s3` (stores files in an S3-compatible bucket).
#### `[blossom.s3]`
Configures S3-compatible object storage, used when `blossom.adapter` is `s3`.
- `endpoint` - the S3 endpoint URL. Optional; leave unset to use AWS S3.
- `region` - the bucket region. Required when `adapter` is `s3`.
- `bucket` - the bucket name. Required when `adapter` is `s3`.
- `access_key` - the access key ID. Required when `adapter` is `s3`.
- `secret_key` - the secret access key. Required when `adapter` is `s3`.
- `key_prefix` - an optional prefix prepended to every object key.
### `[push]`
+4 -4
View File
@@ -25,11 +25,11 @@ func main() {
os.Exit(1)
}
name := zooid.ConfigNameFromId(*relay)
path := zooid.ConfigPathFromName(name)
config, err := zooid.LoadConfigFromPath(path)
// Load config for the specified relay
filename := fmt.Sprintf("%s.toml", *relay)
config, err := zooid.LoadConfig(filename)
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, "No such config file", filename)
os.Exit(1)
}
+4 -4
View File
@@ -39,11 +39,11 @@ func main() {
os.Exit(1)
}
name := zooid.ConfigNameFromId(*relay)
path := zooid.ConfigPathFromName(name)
config, err := zooid.LoadConfigFromPath(path)
// Load config for the specified relay
filename := fmt.Sprintf("%s.toml", *relay)
config, err := zooid.LoadConfig(filename)
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, "No such config file", filename)
os.Exit(1)
}
+4 -2
View File
@@ -21,6 +21,8 @@ func main() {
port := zooid.Env("PORT")
apiHost := zooid.Env("API_HOST")
apiWhitelist := zooid.Env("API_WHITELIST")
configDir := zooid.Env("CONFIG")
pprofAddr := zooid.Env("PPROF_ADDR")
// pprof server — only starts when PPROF_ADDR is set. Bind to
@@ -48,8 +50,8 @@ func main() {
// Wrap with API handler if API_HOST is configured
var handler http.Handler = mainHandler
if apiHost != "" {
apiHandler := zooid.NewAPIHandler()
if apiHost != "" && apiWhitelist != "" {
apiHandler := zooid.NewAPIHandler(apiWhitelist, configDir)
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if this request is for the API host
if r.Host == apiHost {
+273 -154
View File
@@ -2,44 +2,52 @@ package zooid
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"fiatjaf.com/nostr"
"github.com/BurntSushi/toml"
"github.com/gosimple/slug"
)
// APIHandler handles REST API requests for managing virtual relays
type APIHandler struct {
whitelist map[string]bool
configDir string
mux http.Handler
}
func NewAPIHandler() *APIHandler {
whitelist := make(map[string]bool)
for _, pubkey := range Split(Env("API_WHITELIST"), ",") {
// NewAPIHandler creates a new API handler with the given whitelist
func NewAPIHandler(whitelist string, configDir string) *APIHandler {
w := make(map[string]bool)
for _, pubkey := range Split(whitelist, ",") {
pubkey = strings.TrimSpace(pubkey)
if pubkey != "" {
whitelist[pubkey] = true
w[pubkey] = true
}
}
api := &APIHandler{
whitelist: whitelist,
whitelist: w,
configDir: configDir,
}
api.mux = api.buildMux()
return api
}
func (api *APIHandler) buildMux() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /relay/{id}", api.auth(api.createRelay))
mux.HandleFunc("PUT /relay/{id}", api.auth(api.putRelay))
mux.HandleFunc("PUT /relay/{id}", api.auth(api.updateRelay))
mux.HandleFunc("PATCH /relay/{id}", api.auth(api.patchRelay))
mux.HandleFunc("DELETE /relay/{id}", api.auth(api.deleteRelay))
mux.HandleFunc("GET /relay/{id}/members", api.auth(api.listRelayMembers))
api.mux = mux
return api
return mux
}
func (api *APIHandler) auth(next http.HandlerFunc) http.HandlerFunc {
@@ -57,89 +65,108 @@ func (api *APIHandler) auth(next http.HandlerFunc) http.HandlerFunc {
}
}
// ServeHTTP implements the http.Handler interface
func (api *APIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
api.mux.ServeHTTP(w, r)
}
// listRelayMembers returns members for a relay as an array of pubkeys.
func (api *APIHandler) listRelayMembers(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
members, err := api.resolveRelayMembers(id)
if err != nil {
if os.IsNotExist(err) {
writeError(w, http.StatusNotFound, "relay not found")
} else {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to load relay members: %v", err))
}
return
}
writeJSON(w, http.StatusOK, map[string][]string{"members": members})
}
func (api *APIHandler) resolveRelayMembers(id string) ([]string, error) {
if members, ok := api.getMembersFromLoadedInstance(id); ok {
return members, nil
}
config, err := api.loadConfigFromPath(api.configPath(id))
if err != nil {
return nil, err
}
events := &EventStore{
Config: config,
Schema: &Schema{Name: slug.Make(config.Schema)},
}
if err := events.Init(); err != nil {
return nil, fmt.Errorf("failed to init event store: %w", err)
}
management := &ManagementStore{
Config: config,
Events: events,
}
return collectMembers(management), nil
}
func (api *APIHandler) getMembersFromLoadedInstance(id string) ([]string, bool) {
instancesMux.RLock()
instance, exists := instancesByName[id+".toml"]
instancesMux.RUnlock()
if !exists || instance == nil || instance.Config == nil || instance.Management == nil {
return nil, false
}
return collectMembers(instance.Management), true
}
func collectMembers(management *ManagementStore) []string {
memberSet := make(map[string]struct{})
for _, pubkey := range management.GetMembers() {
memberSet[pubkey.Hex()] = struct{}{}
}
members := Keys(memberSet)
sort.Strings(members)
return members
}
// writeError writes a JSON error response
func writeError(w http.ResponseWriter, status int, message string) {
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]string{"error": message})
}
// writeJSON writes a JSON success response
func writeJSON(w http.ResponseWriter, status int, v any) {
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}
// Relay CRUD
func (api *APIHandler) configFromRequest(path string, r *http.Request) (*Config, error) {
r.Body = http.MaxBytesReader(nil, r.Body, 1024*1024)
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body: %w", err)
// scheme returns the URL scheme based on the request
func scheme(r *http.Request) string {
if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
return "https"
}
return LoadConfigFromJson(path, body)
return "http"
}
func (api *APIHandler) patchFromRequest(r *http.Request) (map[string]interface{}, error) {
r.Body = http.MaxBytesReader(nil, r.Body, 1024*1024)
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body: %w", err)
}
var patch map[string]interface{}
if err := json.Unmarshal(body, &patch); err != nil {
return nil, fmt.Errorf("invalid json config: %w", err)
}
return patch, nil
}
func (api *APIHandler) checkDuplicateSchemaOrHost(config *Config, excludeFilename string) error {
entries, err := os.ReadDir(Env("CONFIG"))
if err != nil {
return fmt.Errorf("failed to read config directory: %w", err)
}
for _, entry := range entries {
if entry.IsDir() || entry.Name() == excludeFilename || !strings.HasSuffix(entry.Name(), ".toml") {
continue
}
path := ConfigPathFromName(entry.Name())
if existing, err := LoadConfigFromPath(path); err == nil {
if existing.Schema == config.Schema {
return fmt.Errorf("schema %q is already in use", config.Schema)
}
if existing.Host == config.Host {
return fmt.Errorf("host %q is already in use", config.Host)
}
}
}
return nil
}
// Create relay
// createRelay creates a new relay config file
func (api *APIHandler) createRelay(w http.ResponseWriter, r *http.Request) {
name := ConfigNameFromId(r.PathValue("id"))
path := ConfigPathFromName(name)
if _, err := os.Stat(path); err == nil {
id := r.PathValue("id")
configPath := api.configPath(id)
if _, err := os.Stat(configPath); err == nil {
writeError(w, http.StatusConflict, "relay with this id already exists")
return
}
config, err := api.configFromRequest(path, r)
config, err := api.parseAndValidateConfig(r)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
@@ -150,7 +177,7 @@ func (api *APIHandler) createRelay(w http.ResponseWriter, r *http.Request) {
return
}
if err := config.Save(); err != nil {
if err := api.saveConfig(configPath, config); err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to write config: %v", err))
return
}
@@ -158,29 +185,32 @@ func (api *APIHandler) createRelay(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, map[string]string{"message": "relay created successfully"})
}
// Put relay
func (api *APIHandler) putRelay(w http.ResponseWriter, r *http.Request) {
// updateRelay updates an existing relay config file
func (api *APIHandler) updateRelay(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
name := ConfigNameFromId(id)
path := ConfigPathFromName(name)
if _, err := os.Stat(path); err != nil {
writeError(w, http.StatusNotFound, "relay not found")
configPath := api.configPath(id)
if err := api.checkConfigExists(configPath); err != nil {
if os.IsNotExist(err) {
writeError(w, http.StatusNotFound, "relay not found")
} else {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to check config: %v", err))
}
return
}
config, err := api.configFromRequest(path, r)
config, err := api.parseAndValidateConfig(r)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := api.checkDuplicateSchemaOrHost(config, name); err != nil {
if err := api.checkDuplicateSchemaOrHost(config, id+".toml"); err != nil {
writeError(w, http.StatusConflict, err.Error())
return
}
if err := config.Save(); err != nil {
if err := api.saveConfig(configPath, config); err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to write config: %v", err))
return
}
@@ -188,45 +218,52 @@ func (api *APIHandler) putRelay(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"message": "relay updated successfully"})
}
// Patch relay
// patchRelay partially updates an existing relay config
func (api *APIHandler) patchRelay(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
name := ConfigNameFromId(id)
path := ConfigPathFromName(name)
if _, err := os.Stat(path); err != nil {
writeError(w, http.StatusNotFound, "relay not found")
configPath := api.configPath(id)
if err := api.checkConfigExists(configPath); err != nil {
if os.IsNotExist(err) {
writeError(w, http.StatusNotFound, "relay not found")
} else {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to check config: %v", err))
}
return
}
config, err := LoadConfigFromPath(path)
// Load existing config
existing, err := api.loadConfigFromPath(configPath)
if err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to read existing config: %v", err))
return
}
patch, err := api.patchFromRequest(r)
// Parse patch
patch, err := api.readPatch(r)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := api.applyPatch(config, patch); err != nil {
// Apply patch to existing config
if err := api.applyPatch(existing, patch); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := config.Validate(); err != nil {
// Validate the patched config
if err := api.validateConfig(existing); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := api.checkDuplicateSchemaOrHost(config, name); err != nil {
if err := api.checkDuplicateSchemaOrHost(existing, id+".toml"); err != nil {
writeError(w, http.StatusConflict, err.Error())
return
}
if err := config.Save(); err != nil {
if err := api.saveConfig(configPath, existing); err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to write config: %v", err))
return
}
@@ -234,6 +271,25 @@ func (api *APIHandler) patchRelay(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"message": "relay patched successfully"})
}
// readPatch reads and parses the patch JSON from the request
func (api *APIHandler) readPatch(r *http.Request) (map[string]interface{}, error) {
r.Body = http.MaxBytesReader(nil, r.Body, 1024*1024)
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body: %w", err)
}
var patch map[string]interface{}
if err := json.Unmarshal(body, &patch); err != nil {
return nil, fmt.Errorf("invalid json: %w", err)
}
return patch, nil
}
// applyPatch applies a JSON patch to a config using reflection via JSON marshaling
func (api *APIHandler) applyPatch(config *Config, patch map[string]interface{}) error {
// Convert config to map for merging
configJSON, _ := json.Marshal(config)
@@ -250,15 +306,12 @@ func (api *APIHandler) applyPatch(config *Config, patch map[string]interface{})
return err
}
// Preserve unexported fields, which don't survive the JSON round-trip
patched.path = config.path
patched.secret = config.secret
// Copy patched values to original config
*config = patched
return nil
}
// deepMerge recursively merges patch into base
func deepMerge(base, patch map[string]interface{}) map[string]interface{} {
result := make(map[string]interface{})
@@ -283,18 +336,50 @@ func deepMerge(base, patch map[string]interface{}) map[string]interface{} {
return result
}
// Delete relay
// validateConfig validates a config
func (api *APIHandler) validateConfig(config *Config) error {
if config.Host == "" {
return fmt.Errorf("host is required")
}
if config.Schema == "" {
return fmt.Errorf("schema is required")
}
if !regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`).MatchString(config.Schema) {
return fmt.Errorf("schema must contain only letters, numbers, and underscores")
}
if config.Secret == "" {
return fmt.Errorf("secret is required")
}
if _, err := nostr.SecretKeyFromHex(config.Secret); err != nil {
return fmt.Errorf("invalid secret key: %w", err)
}
if config.Info.Pubkey != "" {
if _, err := nostr.PubKeyFromHex(config.Info.Pubkey); err != nil {
return fmt.Errorf("invalid info.pubkey: %w", err)
}
}
normalizeBlossomConfig(config)
if err := validateBlossomFileStorage(config); err != nil {
return err
}
return nil
}
// deleteRelay deletes a relay config file
func (api *APIHandler) deleteRelay(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
name := ConfigNameFromId(id)
path := ConfigPathFromName(name)
if _, err := os.Stat(path); err != nil {
writeError(w, http.StatusNotFound, "relay not found")
configPath := api.configPath(id)
if err := api.checkConfigExists(configPath); err != nil {
if os.IsNotExist(err) {
writeError(w, http.StatusNotFound, "relay not found")
} else {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to check config: %v", err))
}
return
}
if err := os.Remove(path); err != nil {
if err := os.Remove(configPath); err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to delete config: %v", err))
return
}
@@ -302,62 +387,96 @@ func (api *APIHandler) deleteRelay(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"message": "relay deleted successfully"})
}
// Relay members endpoint
func (api *APIHandler) listRelayMembers(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
name := ConfigNameFromId(id)
members, err := api.resolveRelayMembers(name)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
writeError(w, http.StatusNotFound, "relay not found")
} else {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to load relay members: %v", err))
}
return
}
writeJSON(w, http.StatusOK, map[string][]string{"members": members})
// configName returns the config file name
func (api *APIHandler) configName(id string) string {
return id+".toml"
}
func (api *APIHandler) resolveRelayMembers(name string) ([]string, error) {
instancesMux.RLock()
instance, exists := instancesByName[name]
instancesMux.RUnlock()
// configPath returns the full path for a config file
func (api *APIHandler) configPath(id string) string {
return filepath.Join(api.configDir, api.configName(id))
}
if exists {
return collectMembers(instance.Management), nil
}
// checkConfigExists checks if a config file exists
func (api *APIHandler) checkConfigExists(path string) error {
_, err := os.Stat(path)
return err
}
path := ConfigPathFromName(name)
config, err := LoadConfigFromPath(path)
// loadConfigFromPath loads a config from a file path
func (api *APIHandler) loadConfigFromPath(path string) (*Config, error) {
var config Config
_, err := toml.DecodeFile(path, &config)
if err != nil {
return nil, err
}
events := &EventStore{
Config: config,
Schema: &Schema{Name: config.Schema},
}
if err := events.Init(); err != nil {
return nil, fmt.Errorf("failed to init event store: %w", err)
}
management := &ManagementStore{
Config: config,
Events: events,
}
return collectMembers(management), nil
normalizeBlossomConfig(&config)
return &config, nil
}
func collectMembers(management *ManagementStore) []string {
memberSet := make(map[string]struct{})
for _, pubkey := range management.GetMembers() {
memberSet[pubkey.Hex()] = struct{}{}
// parseAndValidateConfig parses and validates the JSON config from the request body
func (api *APIHandler) parseAndValidateConfig(r *http.Request) (*Config, error) {
r.Body = http.MaxBytesReader(nil, r.Body, 1024*1024)
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body: %w", err)
}
members := Keys(memberSet)
sort.Strings(members)
return members
var config Config
if err := json.Unmarshal(body, &config); err != nil {
return nil, fmt.Errorf("invalid json config: %w", err)
}
if err := api.validateConfig(&config); err != nil {
return nil, err
}
return &config, nil
}
// saveConfig saves a config to a file as TOML
func (api *APIHandler) saveConfig(path string, config *Config) error {
file, err := os.Create(path)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
defer file.Close()
encoder := toml.NewEncoder(file)
if err := encoder.Encode(config); err != nil {
return fmt.Errorf("failed to encode toml: %w", err)
}
return nil
}
// checkDuplicateSchemaOrHost checks if the schema or host is already in use by another config
func (api *APIHandler) checkDuplicateSchemaOrHost(config *Config, excludeFilename string) error {
entries, err := os.ReadDir(api.configDir)
if err != nil {
return fmt.Errorf("failed to read config directory: %w", err)
}
for _, entry := range entries {
if entry.IsDir() || entry.Name() == excludeFilename || !strings.HasSuffix(entry.Name(), ".toml") {
continue
}
path := filepath.Join(api.configDir, entry.Name())
var existing Config
if _, err := toml.DecodeFile(path, &existing); err != nil {
continue
}
if existing.Schema == config.Schema {
return fmt.Errorf("schema %q is already in use", config.Schema)
}
if existing.Host == config.Host {
return fmt.Errorf("host %q is already in use", config.Host)
}
}
return nil
}
+38 -68
View File
@@ -13,17 +13,20 @@ import (
"testing"
"fiatjaf.com/nostr"
"github.com/gosimple/slug"
)
func TestAPIHandler_Authentication(t *testing.T) {
useTestConfigDir(t)
// Create a temporary config directory
configDir := t.TempDir()
// Create a test keypair for authentication
secretKey := nostr.Generate()
pubkey := secretKey.Public()
// Create API handler with whitelist containing our test pubkey
api := newTestAPIHandler(t, pubkey.Hex())
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
t.Run("missing authorization header", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/relay/test", strings.NewReader("{}"))
@@ -171,11 +174,12 @@ func TestAPIHandler_Authentication(t *testing.T) {
}
func TestAPIHandler_CreateRelay(t *testing.T) {
configDir := useTestConfigDir(t)
configDir := t.TempDir()
secretKey := nostr.Generate()
pubkey := secretKey.Public()
api := newTestAPIHandler(t, pubkey.Hex())
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
validConfig := map[string]interface{}{
"host": "relay.example.com",
@@ -223,9 +227,6 @@ func TestAPIHandler_CreateRelay(t *testing.T) {
"host": "other.example.com",
"schema": "testrelay", // Same schema as existing
"secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
}
body, _ := json.Marshal(config)
req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/other", secretKey, body)
@@ -243,9 +244,6 @@ func TestAPIHandler_CreateRelay(t *testing.T) {
"host": "relay.example.com", // Same host as existing
"schema": "otherschema",
"secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
}
body, _ := json.Marshal(config)
req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/other2", secretKey, body)
@@ -304,11 +302,12 @@ func TestAPIHandler_CreateRelay(t *testing.T) {
}
func TestAPIHandler_UpdateRelay(t *testing.T) {
useTestConfigDir(t)
configDir := t.TempDir()
secretKey := nostr.Generate()
pubkey := secretKey.Public()
api := newTestAPIHandler(t, pubkey.Hex())
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
// Create initial relay
initialConfig := map[string]interface{}{
@@ -373,9 +372,6 @@ func TestAPIHandler_UpdateRelay(t *testing.T) {
"host": "other.example.com",
"schema": "otherrelay",
"secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
}
body, _ := json.Marshal(otherConfig)
req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/otherrelay", secretKey, body)
@@ -390,9 +386,6 @@ func TestAPIHandler_UpdateRelay(t *testing.T) {
"host": "relay.example.com",
"schema": "otherrelay", // Duplicate
"secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
}
body, _ = json.Marshal(updateConfig)
req = createAuthenticatedRequest(http.MethodPut, "http://api.example.com/relay/testrelay", secretKey, body)
@@ -407,11 +400,12 @@ func TestAPIHandler_UpdateRelay(t *testing.T) {
}
func TestAPIHandler_PatchRelay(t *testing.T) {
useTestConfigDir(t)
configDir := t.TempDir()
secretKey := nostr.Generate()
pubkey := secretKey.Public()
api := newTestAPIHandler(t, pubkey.Hex())
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
// Create initial relay with full config
initialConfig := map[string]interface{}{
@@ -501,9 +495,6 @@ func TestAPIHandler_PatchRelay(t *testing.T) {
"host": "other.example.com",
"schema": "anotherrelay",
"secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
}
body, _ := json.Marshal(otherConfig)
req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/anotherrelay", secretKey, body)
@@ -560,11 +551,12 @@ func TestAPIHandler_PatchRelay(t *testing.T) {
}
func TestAPIHandler_DeleteRelay(t *testing.T) {
configDir := useTestConfigDir(t)
configDir := t.TempDir()
secretKey := nostr.Generate()
pubkey := secretKey.Public()
api := newTestAPIHandler(t, pubkey.Hex())
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
// Create a relay to delete
config := map[string]interface{}{
@@ -614,11 +606,12 @@ func TestAPIHandler_DeleteRelay(t *testing.T) {
}
func TestAPIHandler_ListRelayMembers(t *testing.T) {
useTestConfigDir(t)
configDir := t.TempDir()
secretKey := nostr.Generate()
pubkey := secretKey.Public()
api := newTestAPIHandler(t, pubkey.Hex())
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
t.Run("list members from loaded relay instance", func(t *testing.T) {
member1 := nostr.Generate().Public()
@@ -689,20 +682,18 @@ func TestAPIHandler_ListRelayMembers(t *testing.T) {
config := &Config{
Host: "members.example.com",
Schema: "members_" + strings.ToLower(RandomString(8)),
Schema: "members_" + RandomString(8),
Secret: relaySecret.Hex(),
}
config.Info.Pubkey = nostr.Generate().Public().Hex()
config.path = ConfigPathFromName(ConfigNameFromId("fallback"))
if err := config.Save(); err != nil {
if err := api.saveConfig(api.configPath("fallback"), config); err != nil {
t.Fatalf("failed to save config: %v", err)
}
// Seed DB with RELAY_MEMBERS to simulate a prior relay load.
seedEvents := &EventStore{
Config: &Config{secret: relaySecret},
Schema: &Schema{Name: config.Schema},
Schema: &Schema{Name: slug.Make(config.Schema)},
}
if err := seedEvents.Init(); err != nil {
t.Fatalf("failed to init seed events: %v", err)
@@ -789,11 +780,12 @@ func TestAPIHandler_ListRelayMembers(t *testing.T) {
}
func TestAPIHandler_MethodNotAllowed(t *testing.T) {
useTestConfigDir(t)
configDir := t.TempDir()
secretKey := nostr.Generate()
pubkey := secretKey.Public()
api := newTestAPIHandler(t, pubkey.Hex())
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
t.Run("GET method not allowed", func(t *testing.T) {
req := createAuthenticatedRequest(http.MethodGet, "http://api.example.com/relay/test", secretKey, nil)
@@ -808,11 +800,12 @@ func TestAPIHandler_MethodNotAllowed(t *testing.T) {
}
func TestAPIHandler_InvalidPath(t *testing.T) {
useTestConfigDir(t)
configDir := t.TempDir()
secretKey := nostr.Generate()
pubkey := secretKey.Public()
api := newTestAPIHandler(t, pubkey.Hex())
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
t.Run("invalid path returns not found", func(t *testing.T) {
req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/invalid/path", secretKey, []byte("{}"))
@@ -838,11 +831,12 @@ func TestAPIHandler_InvalidPath(t *testing.T) {
}
func TestAPIHandler_ConfigValidation(t *testing.T) {
configDir := useTestConfigDir(t)
configDir := t.TempDir()
secretKey := nostr.Generate()
pubkey := secretKey.Public()
api := newTestAPIHandler(t, pubkey.Hex())
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
t.Run("invalid info.pubkey", func(t *testing.T) {
config := map[string]interface{}{
@@ -983,33 +977,9 @@ func createAuthenticatedRequest(method, url string, secretKey nostr.SecretKey, b
return req
}
// setTestEnv overrides a value in the package-level env map. Env memoizes
// os.Environ via sync.Once, so once the test binary has started, os.Setenv is
// ignored — mutating the cached map directly is the only way to change config
// for an individual test. Safe because tests in this package run sequentially.
func setTestEnv(key, value string) {
_ = Env("DATA") // ensure the env map has been initialized
env[key] = value
}
// useTestConfigDir points Env("CONFIG") at a fresh temp dir for this test.
func useTestConfigDir(t *testing.T) string {
t.Helper()
dir := t.TempDir()
setTestEnv("CONFIG", dir)
return dir
}
// newTestAPIHandler builds a handler whose whitelist contains the given pubkeys.
func newTestAPIHandler(t *testing.T, whitelist ...string) *APIHandler {
t.Helper()
setTestEnv("API_WHITELIST", strings.Join(whitelist, ","))
return NewAPIHandler()
}
func TestNewAPIHandler(t *testing.T) {
t.Run("empty whitelist", func(t *testing.T) {
api := newTestAPIHandler(t)
api := NewAPIHandler("", "/tmp")
if len(api.whitelist) != 0 {
t.Error("expected empty whitelist")
}
@@ -1017,7 +987,7 @@ func TestNewAPIHandler(t *testing.T) {
t.Run("single pubkey", func(t *testing.T) {
pubkey := nostr.Generate().Public().Hex()
api := newTestAPIHandler(t, pubkey)
api := NewAPIHandler(pubkey, "/tmp")
if len(api.whitelist) != 1 {
t.Error("expected 1 entry in whitelist")
}
@@ -1029,8 +999,8 @@ func TestNewAPIHandler(t *testing.T) {
t.Run("multiple pubkeys", func(t *testing.T) {
pubkey1 := nostr.Generate().Public().Hex()
pubkey2 := nostr.Generate().Public().Hex()
setTestEnv("API_WHITELIST", fmt.Sprintf("%s, %s", pubkey1, pubkey2))
api := NewAPIHandler()
whitelist := fmt.Sprintf("%s, %s", pubkey1, pubkey2)
api := NewAPIHandler(whitelist, "/tmp")
if len(api.whitelist) != 2 {
t.Error("expected 2 entries in whitelist")
}
@@ -1041,8 +1011,8 @@ func TestNewAPIHandler(t *testing.T) {
t.Run("whitespace trimming", func(t *testing.T) {
pubkey := nostr.Generate().Public().Hex()
setTestEnv("API_WHITELIST", " "+pubkey+" ")
api := NewAPIHandler()
whitelist := " " + pubkey + " "
api := NewAPIHandler(whitelist, "/tmp")
if len(api.whitelist) != 1 {
t.Error("expected 1 entry in whitelist after trimming")
}
+115 -118
View File
@@ -16,6 +16,7 @@ import (
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/gosimple/slug"
"github.com/spf13/afero"
)
@@ -24,24 +25,131 @@ type BlossomStore struct {
Events eventstore.Store
}
func loadAWSConfigForBlossomS3(ctx context.Context, s *BlossomS3Settings) (aws.Config, error) {
return awsconfig.LoadDefaultConfig(ctx,
awsconfig.WithRegion(s.Region),
awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(s.AccessKey, s.SecretKey, "")),
)
}
func s3APIClientForBlossomSettings(awsCfg aws.Config, s *BlossomS3Settings) *s3.Client {
customEndpoint := s.Endpoint != ""
return s3.NewFromConfig(awsCfg, func(o *s3.Options) {
if customEndpoint {
o.BaseEndpoint = aws.String(s.Endpoint)
// Custom endpoints (e.g. MinIO) expect path-style addressing.
o.UsePathStyle = true
}
})
}
func blossomS3ObjectKey(slugName, sha256, keyPrefix string) string {
rel := slugName + "/" + sha256
if keyPrefix != "" {
return keyPrefix + "/" + rel
}
return rel
}
func attachBlossomLocalBlobs(bs *blossom.BlossomServer, slugName string) {
dir := filepath.Join(Env("MEDIA"), slugName)
osfs := afero.NewOsFs()
_ = osfs.MkdirAll(dir, 0755)
bs.StoreBlob = func(ctx context.Context, sha256 string, ext string, body []byte) error {
file, err := osfs.Create(filepath.Join(dir, sha256))
if err != nil {
return err
}
if _, err := io.Copy(file, bytes.NewReader(body)); err != nil {
return err
}
return nil
}
bs.LoadBlob = func(ctx context.Context, sha256 string, ext string) (io.ReadSeeker, *url.URL, error) {
file, err := osfs.Open(filepath.Join(dir, sha256))
if err != nil {
return nil, nil, err
}
return file, nil, nil
}
bs.DeleteBlob = func(ctx context.Context, sha256 string, ext string) error {
return osfs.Remove(filepath.Join(dir, sha256))
}
}
func attachBlossomS3Blobs(bs *blossom.BlossomServer, cfg *Config, slugName string) error {
s := &cfg.Blossom.S3
ctx := context.Background()
awsCfg, err := loadAWSConfigForBlossomS3(ctx, s)
if err != nil {
return fmt.Errorf("aws config: %w", err)
}
client := s3APIClientForBlossomSettings(awsCfg, s)
bucket := s.Bucket
bs.StoreBlob = func(ctx context.Context, sha256 string, ext string, body []byte) error {
_, err := client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(blossomS3ObjectKey(slugName, sha256, s.KeyPrefix)),
Body: bytes.NewReader(body),
})
return err
}
bs.LoadBlob = func(ctx context.Context, sha256 string, ext string) (io.ReadSeeker, *url.URL, error) {
out, err := client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(blossomS3ObjectKey(slugName, sha256, s.KeyPrefix)),
})
if err != nil {
return nil, nil, err
}
defer out.Body.Close()
data, err := io.ReadAll(out.Body)
if err != nil {
return nil, nil, err
}
return bytes.NewReader(data), nil, nil
}
bs.DeleteBlob = func(ctx context.Context, sha256 string, ext string) error {
_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(blossomS3ObjectKey(slugName, sha256, s.KeyPrefix)),
})
return err
}
return nil
}
func (bl *BlossomStore) Enable(instance *Instance) {
slugName := slug.Make(bl.Config.Schema)
backend := blossom.New(instance.Relay, "https://"+bl.Config.Host)
backend.Store = blossom.EventStoreBlobIndexWrapper{
Store: bl.Events,
ServiceURL: "https://" + bl.Config.Host,
}
switch bl.Config.Blossom.Adapter {
switch bl.Config.Blossom.Backend {
case "local":
if err := bl.UseLocalAdapter(backend); err != nil {
log.Fatalf("blossom: failed to use local adapter %q", err)
}
attachBlossomLocalBlobs(backend, slugName)
case "s3":
if err := bl.UseS3Adapter(backend); err != nil {
log.Fatalf("blossom: failed to use s3 adapter %q", err)
if err := attachBlossomS3Blobs(backend, bl.Config, slugName); err != nil {
log.Fatalf("blossom: s3: %v", err)
}
default:
log.Fatalf("blossom: unknown backend %q", bl.Config.Blossom.Adapter)
log.Fatalf("blossom: unknown backend %q (use local or s3)", bl.Config.Blossom.Backend)
}
backend.RejectUpload = func(ctx context.Context, auth *nostr.Event, size int, ext string) (bool, string, int) {
@@ -89,114 +197,3 @@ func (bl *BlossomStore) Enable(instance *Instance) {
instance.Relay.Info.SupportedNIPs = append(instance.Relay.Info.SupportedNIPs, "BUD-02")
instance.Relay.Info.SupportedNIPs = append(instance.Relay.Info.SupportedNIPs, "BUD-11")
}
// Local adapter
func (bl *BlossomStore) UseLocalAdapter(backend *blossom.BlossomServer) error {
dir := filepath.Join(Env("MEDIA"), bl.Config.Schema)
osfs := afero.NewOsFs()
_ = osfs.MkdirAll(dir, 0755)
backend.StoreBlob = func(ctx context.Context, sha256 string, ext string, body []byte) error {
file, err := osfs.Create(filepath.Join(dir, sha256))
if err != nil {
return err
}
if _, err := io.Copy(file, bytes.NewReader(body)); err != nil {
return err
}
return nil
}
backend.LoadBlob = func(ctx context.Context, sha256 string, ext string) (io.ReadSeeker, *url.URL, error) {
file, err := osfs.Open(filepath.Join(dir, sha256))
if err != nil {
return nil, nil, err
}
return file, nil, nil
}
backend.DeleteBlob = func(ctx context.Context, sha256 string, ext string) error {
return osfs.Remove(filepath.Join(dir, sha256))
}
return nil
}
// S3 adapter
func (bl *BlossomStore) S3Key(sha256 string) string {
key := bl.Config.Schema + "/" + sha256
if bl.Config.Blossom.S3.KeyPrefix != "" {
key = bl.Config.Blossom.S3.KeyPrefix + "/" + key
}
return key
}
func (bl *BlossomStore) UseS3Adapter(backend *blossom.BlossomServer) error {
ctx := context.Background()
awsConfig, err := awsconfig.LoadDefaultConfig(ctx,
awsconfig.WithRegion(bl.Config.Blossom.S3.Region),
awsconfig.WithCredentialsProvider(
credentials.NewStaticCredentialsProvider(
bl.Config.Blossom.S3.AccessKey,
bl.Config.Blossom.S3.SecretKey,
"",
),
),
)
if err != nil {
return fmt.Errorf("aws config: %w", err)
}
client := s3.NewFromConfig(awsConfig, func(o *s3.Options) {
if bl.Config.Blossom.S3.Endpoint != "" {
o.BaseEndpoint = aws.String(bl.Config.Blossom.S3.Endpoint)
o.UsePathStyle = true
}
})
backend.StoreBlob = func(ctx context.Context, sha256 string, ext string, body []byte) error {
_, err := client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(bl.Config.Blossom.S3.Bucket),
Key: aws.String(bl.S3Key(sha256)),
Body: bytes.NewReader(body),
})
return err
}
backend.LoadBlob = func(ctx context.Context, sha256 string, ext string) (io.ReadSeeker, *url.URL, error) {
out, err := client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(bl.Config.Blossom.S3.Bucket),
Key: aws.String(bl.S3Key(sha256)),
})
if err != nil {
return nil, nil, err
}
defer out.Body.Close()
data, err := io.ReadAll(out.Body)
if err != nil {
return nil, nil, err
}
return bytes.NewReader(data), nil, nil
}
backend.DeleteBlob = func(ctx context.Context, sha256 string, ext string) error {
_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(bl.Config.Blossom.S3.Bucket),
Key: aws.String(bl.S3Key(sha256)),
})
return err
}
return nil
}
+71 -65
View File
@@ -1,14 +1,13 @@
package zooid
import (
"encoding/json"
"fiatjaf.com/nostr"
"fmt"
"github.com/BurntSushi/toml"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
)
type Role struct {
@@ -47,10 +46,10 @@ type Config struct {
} `toml:"management" json:"management"`
Blossom struct {
Enabled bool `toml:"enabled" json:"enabled"`
AuthenticatedRead bool `toml:"authenticated_read" json:"authenticated_read"`
Adapter string `toml:"adapter" json:"adapter"`
S3 BlossomS3Settings `toml:"s3" json:"s3"`
Enabled bool `toml:"enabled" json:"enabled"`
AuthenticatedRead bool `toml:"authenticated_read" json:"authenticated_read"`
Backend string `toml:"backend" json:"backend"`
S3 BlossomS3Settings `toml:"s3" json:"s3"`
} `toml:"blossom" json:"blossom"`
Livekit struct {
@@ -61,13 +60,13 @@ type Config struct {
Roles map[string]Role `toml:"roles" json:"roles"`
// Parsed values
// Private/parsed values
path string
secret nostr.SecretKey
}
// BlossomS3Settings configures S3-compatible object storage for Blossom blobs
// when [blossom] adapter is "s3".
// when [blossom] backend is "s3".
type BlossomS3Settings struct {
Endpoint string `toml:"endpoint" json:"endpoint"`
Region string `toml:"region" json:"region"`
@@ -77,12 +76,10 @@ type BlossomS3Settings struct {
KeyPrefix string `toml:"key_prefix" json:"key_prefix"`
}
func ConfigNameFromId(id string) string {
return id + ".toml"
}
func LoadConfig(filename string) (*Config, error) {
path := filepath.Join(Env("CONFIG"), filename)
func ConfigPathFromName(name string) string {
return filepath.Join(Env("CONFIG"), name)
return LoadConfigFromPath(path)
}
func LoadConfigFromPath(path string) (*Config, error) {
@@ -91,80 +88,86 @@ func LoadConfigFromPath(path string) (*Config, error) {
return nil, fmt.Errorf("Failed to parse config file %s: %w", path, err)
}
config.path = path
if err := config.Validate(); err != nil {
return nil, err
}
return &config, nil
}
func LoadConfigFromJson(path string, body []byte) (*Config, error) {
var config Config
if err := json.Unmarshal(body, &config); err != nil {
return nil, fmt.Errorf("invalid json config: %w", err)
}
config.path = path
if err := config.Validate(); err != nil {
return nil, err
}
return &config, nil
}
func (config *Config) Validate() error {
if config.Blossom.Adapter == "" {
config.Blossom.Adapter = "local"
}
normalizeBlossomConfig(&config)
if config.Host == "" {
return fmt.Errorf("host is required")
return nil, fmt.Errorf("host is required")
}
if config.Schema == "" {
return fmt.Errorf("schema is required")
return nil, fmt.Errorf("schema is required")
}
if !regexp.MustCompile(`^[a-z_][a-z0-9_]*$`).MatchString(config.Schema) {
return fmt.Errorf("schema must contain only lowercase letters, numbers, and underscores")
if config.Info.Pubkey == "" {
return nil, fmt.Errorf("info.pubkey is required")
}
secret, err := nostr.SecretKeyFromHex(config.Secret)
if err != nil {
return fmt.Errorf("invalid secret key: %w", err)
return nil, err
}
// Save the path for later
config.path = path
// Make the secret... secret
config.Secret = ""
config.secret = secret
if _, err := nostr.PubKeyFromHex(config.Info.Pubkey); err != nil {
return fmt.Errorf("invalid info.pubkey: %w", err)
if err := validateBlossomFileStorage(&config); err != nil {
return nil, err
}
if config.Blossom.Adapter == "s3" {
if config.Blossom.S3.Bucket == "" {
return fmt.Errorf("blossom.s3.bucket is required when blossom.adapter is s3")
}
if config.Blossom.S3.Region == "" {
return fmt.Errorf("blossom.s3.region is required when blossom.adapter is s3")
}
if config.Blossom.S3.AccessKey == "" {
return fmt.Errorf("blossom.s3.access_key is required when blossom.adapter is s3")
}
if config.Blossom.S3.SecretKey == "" {
return fmt.Errorf("blossom.s3.secret_key is required when blossom.adapter is s3")
}
} else if config.Blossom.Adapter != "local" {
return fmt.Errorf("invalid blossom adapter")
}
return &config, nil
}
func normalizeBlossomConfig(c *Config) {
s := &c.Blossom.S3
s.Region = strings.TrimSpace(s.Region)
s.Bucket = strings.TrimSpace(s.Bucket)
s.AccessKey = strings.TrimSpace(s.AccessKey)
s.SecretKey = strings.TrimSpace(s.SecretKey)
s.Endpoint = strings.TrimRight(strings.TrimSpace(s.Endpoint), "/")
s.KeyPrefix = strings.Trim(strings.TrimSpace(s.KeyPrefix), "/")
c.Blossom.Backend = strings.ToLower(strings.TrimSpace(c.Blossom.Backend))
if c.Blossom.Backend == "" {
c.Blossom.Backend = "local"
}
}
func validateBlossomFileStorage(c *Config) error {
if !c.Blossom.Enabled {
return nil
}
switch c.Blossom.Backend {
case "local":
return nil
case "s3":
// fall through
default:
return fmt.Errorf(`blossom.backend must be "local", "s3", or empty (defaults to local)`)
}
s := c.Blossom.S3
if s.Bucket == "" {
return fmt.Errorf("blossom.s3.bucket is required when blossom.backend is s3")
}
if s.Region == "" {
return fmt.Errorf("blossom.s3.region is required when blossom.backend is s3")
}
if s.AccessKey == "" {
return fmt.Errorf("blossom.s3.access_key is required when blossom.backend is s3")
}
if s.SecretKey == "" {
return fmt.Errorf("blossom.s3.secret_key is required when blossom.backend is s3")
}
return nil
}
func (config *Config) Save() error {
// Restore the secret key to the public field for saving
config.Secret = config.secret.Hex()
file, err := os.Create(config.path)
if err != nil {
return fmt.Errorf("Failed to open config file %s: %w", config.path, err)
@@ -176,6 +179,9 @@ func (config *Config) Save() error {
return fmt.Errorf("Failed to encode config file %s: %w", config.path, err)
}
// Clear the secret again
config.Secret = ""
return nil
}
+25 -36
View File
@@ -157,64 +157,53 @@ func TestConfig_MemberRole(t *testing.T) {
}
}
// validBlossomTestConfig returns a config that passes Validate except for any
// Blossom settings the caller overrides, so blossom validation can be exercised
// in isolation.
func validBlossomTestConfig() *Config {
sk := nostr.Generate()
c := &Config{
Host: "r.example.com",
Schema: "myrelay",
Secret: sk.Hex(),
}
c.Info.Pubkey = sk.Public().Hex()
return c
}
func TestValidateBlossomFileStorage(t *testing.T) {
t.Run("empty adapter defaults to local", func(t *testing.T) {
c := validBlossomTestConfig()
c.Blossom.Enabled = true
if err := c.Validate(); err != nil {
t.Run("blossom disabled skips validation", func(t *testing.T) {
c := &Config{}
c.Blossom.Enabled = false
c.Blossom.Backend = "s3"
normalizeBlossomConfig(c)
if err := validateBlossomFileStorage(c); err != nil {
t.Fatalf("expected nil, got %v", err)
}
if c.Blossom.Adapter != "local" {
t.Errorf("expected adapter normalized to local, got %q", c.Blossom.Adapter)
}
})
t.Run("local storage needs no s3 fields", func(t *testing.T) {
c := validBlossomTestConfig()
c := &Config{}
c.Blossom.Enabled = true
c.Blossom.Adapter = "local"
if err := c.Validate(); err != nil {
c.Blossom.Backend = "local"
normalizeBlossomConfig(c)
if err := validateBlossomFileStorage(c); err != nil {
t.Fatalf("expected nil, got %v", err)
}
})
t.Run("s3 requires bucket region keys and secret", func(t *testing.T) {
c := validBlossomTestConfig()
c := &Config{}
c.Blossom.Enabled = true
c.Blossom.Adapter = "s3"
c.Blossom.Backend = "s3"
c.Blossom.S3.Region = "us-east-1"
if err := c.Validate(); err == nil {
normalizeBlossomConfig(c)
if err := validateBlossomFileStorage(c); err == nil {
t.Fatal("expected error for missing bucket and credentials")
}
c.Blossom.S3.Bucket = "b"
c.Blossom.S3.AccessKey = "k"
c.Blossom.S3.SecretKey = "s"
if err := c.Validate(); err != nil {
normalizeBlossomConfig(c)
if err := validateBlossomFileStorage(c); err != nil {
t.Fatalf("expected nil with all s3 fields set, got %v", err)
}
})
t.Run("invalid adapter value", func(t *testing.T) {
c := validBlossomTestConfig()
t.Run("invalid backend value", func(t *testing.T) {
c := &Config{}
c.Blossom.Enabled = true
c.Blossom.Adapter = "nfs"
if err := c.Validate(); err == nil {
t.Fatal("expected error for unknown adapter")
c.Blossom.Backend = "nfs"
normalizeBlossomConfig(c)
if err := validateBlossomFileStorage(c); err == nil {
t.Fatal("expected error for unknown backend")
}
})
}
@@ -234,7 +223,7 @@ pubkey = "` + sk.Public().Hex() + `"
[blossom]
enabled = true
adapter = "s3"
backend = "s3"
[blossom.s3]
region = "auto"
@@ -254,7 +243,7 @@ endpoint = "http://127.0.0.1:9000"
if cfg.Blossom.S3.SecretKey != "topsecret" {
t.Errorf("expected s3 secret_key retained in struct, got %q", cfg.Blossom.S3.SecretKey)
}
if cfg.Blossom.Adapter != "s3" {
t.Errorf("adapter: got %q", cfg.Blossom.Adapter)
if cfg.Blossom.Backend != "s3" {
t.Errorf("backend: got %q", cfg.Blossom.Backend)
}
}
+5 -5
View File
@@ -9,6 +9,7 @@ import (
"fiatjaf.com/nostr"
"fiatjaf.com/nostr/khatru"
"github.com/gosimple/slug"
)
type Instance struct {
@@ -21,14 +22,13 @@ type Instance struct {
Push *PushManager
}
func MakeInstance(name string) (*Instance, error) {
path := ConfigPathFromName(name)
config, err := LoadConfigFromPath(path)
func MakeInstance(filename string) (*Instance, error) {
config, err := LoadConfig(filename)
if err != nil {
return nil, err
}
return makeInstance(config, name)
return makeInstance(config, filename)
}
func makeInstance(config *Config, source string) (*Instance, error) {
@@ -38,7 +38,7 @@ func makeInstance(config *Config, source string) (*Instance, error) {
Relay: relay,
Config: config,
Schema: &Schema{
Name: config.Schema,
Name: slug.Make(config.Schema),
},
}
+2 -2
View File
@@ -64,7 +64,7 @@ func Start() {
if err != nil {
log.Printf("Failed to make instance for %s: %v", entry.Name(), err)
} else if instance.Config.Inactive {
instance.Cleanup()
instance.Cleanup()
log.Printf("Skipped inactive %s", entry.Name())
} else {
instancesByHost[instance.Config.Host] = instance
@@ -112,7 +112,7 @@ func Start() {
if err != nil {
log.Printf("Failed to reload %s: %v", filename, err)
} else if instance.Config.Inactive {
instance.Cleanup()
instance.Cleanup()
log.Printf("Skipped inactive %s", filename)
} else {
instancesByHost[instance.Config.Host] = instance
+4 -10
View File
@@ -1,9 +1,7 @@
package zooid
import (
"slices"
"context"
"errors"
"fiatjaf.com/nostr"
"fiatjaf.com/nostr/khatru"
"fiatjaf.com/nostr/nip86"
@@ -129,6 +127,10 @@ func (m *ManagementStore) PubkeyIsBanned(pubkey nostr.PubKey) bool {
// Admins
func (m *ManagementStore) IsAdmin(pubkey nostr.PubKey) bool {
return m.Config.IsOwner(pubkey) || m.Config.IsSelf(pubkey)
}
func (m *ManagementStore) GetAdmins() []nostr.PubKey {
members := make([]nostr.PubKey, 0)
@@ -145,10 +147,6 @@ func (m *ManagementStore) GetAdmins() []nostr.PubKey {
return members
}
func (m *ManagementStore) IsAdmin(pubkey nostr.PubKey) bool {
return slices.Contains(m.GetAdmins(), pubkey)
}
// Membership
func (m *ManagementStore) GetMembers() []nostr.PubKey {
@@ -197,10 +195,6 @@ func (m *ManagementStore) AddMember(pubkey nostr.PubKey) error {
}
func (m *ManagementStore) RemoveMember(pubkey nostr.PubKey) error {
if m.IsAdmin(pubkey) {
return errors.New("Can't remove permanent admins from relay.")
}
membersEvent := m.Events.GetOrCreateRelayMembersList()
if membersEvent.Tags.FindWithValue("member", pubkey.Hex()) != nil {
+1 -6
View File
@@ -183,12 +183,7 @@ func validateNIP98Auth(r *http.Request) (nostr.PubKey, error) {
return nostr.PubKey{}, fmt.Errorf("invalid event signature")
}
scheme := "http"
if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
scheme = scheme + "s"
}
expectedURL := fmt.Sprintf("%s://%s%s", scheme, r.Host, r.URL.Path)
expectedURL := fmt.Sprintf("%s://%s%s", scheme(r), r.Host, r.URL.Path)
var hasURL, hasMethod bool
for _, tag := range event.Tags {