mirror of
https://github.com/DeBrosOfficial/orama.git
synced 2026-03-27 10:44:13 +00:00
commit
4b7c342c77
91
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
91
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
@ -0,0 +1,91 @@
|
||||
name: Bug Report
|
||||
description: Report a bug in Orama Network
|
||||
labels: ["bug"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for reporting a bug! Please fill out the sections below.
|
||||
|
||||
**Security issues:** If this is a security vulnerability, do NOT open an issue. Email security@orama.io instead.
|
||||
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Orama version
|
||||
description: "Run `orama version` to find this"
|
||||
placeholder: "v0.18.0-beta"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: component
|
||||
attributes:
|
||||
label: Component
|
||||
options:
|
||||
- Gateway / API
|
||||
- CLI (orama command)
|
||||
- WireGuard / Networking
|
||||
- RQLite / Storage
|
||||
- Olric / Caching
|
||||
- IPFS / Pinning
|
||||
- CoreDNS
|
||||
- OramaOS
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Description
|
||||
description: A clear description of the bug
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
description: Minimal steps to reproduce the behavior
|
||||
placeholder: |
|
||||
1. Run `orama ...`
|
||||
2. See error
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: Expected behavior
|
||||
description: What you expected to happen
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: Actual behavior
|
||||
description: What actually happened (include error messages and logs if any)
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: Environment
|
||||
description: OS, Go version, deployment environment, etc.
|
||||
placeholder: |
|
||||
- OS: Ubuntu 22.04
|
||||
- Go: 1.23
|
||||
- Environment: sandbox
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: context
|
||||
attributes:
|
||||
label: Additional context
|
||||
description: Logs, screenshots, monitor reports, or anything else that might help
|
||||
validations:
|
||||
required: false
|
||||
49
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
49
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@ -0,0 +1,49 @@
|
||||
name: Feature Request
|
||||
description: Suggest a new feature or improvement
|
||||
labels: ["enhancement"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for the suggestion! Please describe what you'd like to see.
|
||||
|
||||
- type: dropdown
|
||||
id: component
|
||||
attributes:
|
||||
label: Component
|
||||
options:
|
||||
- Gateway / API
|
||||
- CLI (orama command)
|
||||
- WireGuard / Networking
|
||||
- RQLite / Storage
|
||||
- Olric / Caching
|
||||
- IPFS / Pinning
|
||||
- CoreDNS
|
||||
- OramaOS
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem
|
||||
description: What problem does this solve? Why do you need it?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: solution
|
||||
attributes:
|
||||
label: Proposed solution
|
||||
description: How do you think this should work?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives considered
|
||||
description: Any workarounds or alternative approaches you've thought of
|
||||
validations:
|
||||
required: false
|
||||
31
.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
31
.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
@ -0,0 +1,31 @@
|
||||
## Summary
|
||||
|
||||
<!-- What does this PR do? Keep it to 1-3 bullet points. -->
|
||||
|
||||
## Motivation
|
||||
|
||||
<!-- Why is this change needed? Link to an issue if applicable. -->
|
||||
|
||||
## Test plan
|
||||
|
||||
<!-- How did you verify this works? -->
|
||||
|
||||
- [ ] `make test` passes
|
||||
- [ ] Tested on sandbox/staging environment
|
||||
|
||||
## Distributed system impact
|
||||
|
||||
<!-- Does this change affect any of the following? If yes, explain. -->
|
||||
|
||||
- [ ] Raft quorum / RQLite
|
||||
- [ ] WireGuard mesh / networking
|
||||
- [ ] Olric gossip / caching
|
||||
- [ ] Service startup ordering
|
||||
- [ ] Rolling upgrade compatibility
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Tests added for new functionality or bug fix
|
||||
- [ ] No debug code (`fmt.Println`, `log.Println`) left behind
|
||||
- [ ] Docs updated (if user-facing behavior changed)
|
||||
- [ ] Errors wrapped with context (`fmt.Errorf("...: %w", err)`)
|
||||
80
.github/workflows/publish-sdk.yml
vendored
Normal file
80
.github/workflows/publish-sdk.yml
vendored
Normal file
@ -0,0 +1,80 @@
|
||||
name: Publish SDK to npm
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Version to publish (e.g., 1.0.0). Leave empty to use package.json version."
|
||||
required: false
|
||||
dry-run:
|
||||
description: "Dry run (don't actually publish)"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Build & Publish @debros/orama
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: sdk
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Bump version
|
||||
if: inputs.version != ''
|
||||
run: npm version ${{ inputs.version }} --no-git-tag-version
|
||||
|
||||
- name: Typecheck
|
||||
run: pnpm typecheck
|
||||
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
|
||||
- name: Run tests
|
||||
run: pnpm test -- --run
|
||||
|
||||
- name: Publish (dry run)
|
||||
if: inputs.dry-run == true
|
||||
run: npm publish --access public --dry-run
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
- name: Publish
|
||||
if: inputs.dry-run == false
|
||||
run: npm publish --access public
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
- name: Get published version
|
||||
if: inputs.dry-run == false
|
||||
id: version
|
||||
run: echo "version=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Create git tag
|
||||
if: inputs.dry-run == false
|
||||
working-directory: .
|
||||
run: |
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git tag "sdk/v${{ steps.version.outputs.version }}"
|
||||
git push origin "sdk/v${{ steps.version.outputs.version }}"
|
||||
9
.github/workflows/release-apt.yml
vendored
9
.github/workflows/release-apt.yml
vendored
@ -46,6 +46,7 @@ jobs:
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Build binary
|
||||
working-directory: core
|
||||
env:
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
CGO_ENABLED: 0
|
||||
@ -57,9 +58,9 @@ jobs:
|
||||
|
||||
mkdir -p build/usr/local/bin
|
||||
go build -ldflags "$LDFLAGS" -o build/usr/local/bin/orama cmd/cli/main.go
|
||||
go build -ldflags "$LDFLAGS" -o build/usr/local/bin/debros-node cmd/node/main.go
|
||||
go build -ldflags "$LDFLAGS" -o build/usr/local/bin/orama-node cmd/node/main.go
|
||||
# Build the entire gateway package so helper files (e.g., config parsing) are included
|
||||
go build -ldflags "$LDFLAGS" -o build/usr/local/bin/debros-gateway ./cmd/gateway
|
||||
go build -ldflags "$LDFLAGS" -o build/usr/local/bin/orama-gateway ./cmd/gateway
|
||||
|
||||
- name: Create Debian package structure
|
||||
run: |
|
||||
@ -71,7 +72,7 @@ jobs:
|
||||
mkdir -p ${PKG_NAME}/usr/local/bin
|
||||
|
||||
# Copy binaries
|
||||
cp build/usr/local/bin/* ${PKG_NAME}/usr/local/bin/
|
||||
cp core/build/usr/local/bin/* ${PKG_NAME}/usr/local/bin/
|
||||
chmod 755 ${PKG_NAME}/usr/local/bin/*
|
||||
|
||||
# Create control file
|
||||
@ -82,7 +83,7 @@ jobs:
|
||||
Priority: optional
|
||||
Architecture: ${ARCH}
|
||||
Depends: libc6
|
||||
Maintainer: DeBros Team <team@debros.network>
|
||||
Maintainer: DeBros Team <team@orama.network>
|
||||
Description: Orama Network - Distributed P2P Database System
|
||||
Orama is a distributed peer-to-peer network that combines
|
||||
RQLite for distributed SQL, IPFS for content-addressed storage,
|
||||
|
||||
35
.github/workflows/release.yaml
vendored
35
.github/workflows/release.yaml
vendored
@ -23,7 +23,7 @@ jobs:
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v4
|
||||
with:
|
||||
go-version: '1.21'
|
||||
go-version: '1.24'
|
||||
cache: true
|
||||
|
||||
- name: Run GoReleaser
|
||||
@ -34,6 +34,7 @@ jobs:
|
||||
args: release --clean
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
@ -42,32 +43,26 @@ jobs:
|
||||
path: dist/
|
||||
retention-days: 5
|
||||
|
||||
# Optional: Publish to GitHub Packages (requires additional setup)
|
||||
publish-packages:
|
||||
# Verify release artifacts
|
||||
verify-release:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-release
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-artifacts
|
||||
path: dist/
|
||||
|
||||
- name: Publish to GitHub Packages
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: List release artifacts
|
||||
run: |
|
||||
echo "Publishing Debian packages to GitHub Packages..."
|
||||
for deb in dist/*.deb; do
|
||||
if [ -f "$deb" ]; then
|
||||
curl -H "Authorization: token $GITHUB_TOKEN" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @"$deb" \
|
||||
"https://uploads.github.com/repos/${{ github.repository }}/releases/upload?name=$(basename "$deb")"
|
||||
fi
|
||||
done
|
||||
echo "=== Release Artifacts ==="
|
||||
ls -la dist/
|
||||
echo ""
|
||||
echo "=== .deb packages ==="
|
||||
ls -la dist/*.deb 2>/dev/null || echo "No .deb files found"
|
||||
echo ""
|
||||
echo "=== Archives ==="
|
||||
ls -la dist/*.tar.gz 2>/dev/null || echo "No .tar.gz files found"
|
||||
|
||||
135
.gitignore
vendored
135
.gitignore
vendored
@ -1,34 +1,4 @@
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
# vendor/
|
||||
|
||||
# Go workspace file
|
||||
go.work
|
||||
|
||||
# Built binaries
|
||||
bin/
|
||||
dist/
|
||||
|
||||
# IDE and editor files
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS generated files
|
||||
# === Global ===
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
@ -36,48 +6,85 @@ dist/
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# Log files
|
||||
*.log
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
.cursor/
|
||||
|
||||
# Environment variables
|
||||
# Environment & credentials
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
.env.*
|
||||
!.env.example
|
||||
.mcp.json
|
||||
.claude/
|
||||
.codex/
|
||||
|
||||
# Temporary files
|
||||
tmp/
|
||||
temp/
|
||||
*.tmp
|
||||
# === Core (Go) ===
|
||||
core/phantom-auth/
|
||||
core/bin/
|
||||
core/bin-linux/
|
||||
core/dist/
|
||||
core/orama-cli-linux
|
||||
core/keys_backup/
|
||||
core/.gocache/
|
||||
core/configs/
|
||||
core/data/*
|
||||
core/tmp/
|
||||
core/temp/
|
||||
core/results/
|
||||
core/rnd/
|
||||
core/vps.txt
|
||||
core/coverage.txt
|
||||
core/coverage.html
|
||||
core/profile.out
|
||||
core/e2e/config.yaml
|
||||
core/scripts/remote-nodes.conf
|
||||
|
||||
# Coverage reports
|
||||
coverage.txt
|
||||
coverage.html
|
||||
profile.out
|
||||
|
||||
# Build artifacts
|
||||
# Go build artifacts
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
*.test
|
||||
*.out
|
||||
*.deb
|
||||
*.rpm
|
||||
*.tar.gz
|
||||
*.zip
|
||||
go.work
|
||||
|
||||
# Local development files
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Databases
|
||||
*.db
|
||||
|
||||
# === Website ===
|
||||
website/node_modules/
|
||||
website/dist/
|
||||
website/invest-api/invest-api
|
||||
website/invest-api/*.db
|
||||
website/invest-api/*.db-shm
|
||||
website/invest-api/*.db-wal
|
||||
|
||||
# === SDK (TypeScript) ===
|
||||
sdk/node_modules/
|
||||
sdk/dist/
|
||||
sdk/coverage/
|
||||
|
||||
# === Vault (Zig) ===
|
||||
vault/.zig-cache/
|
||||
vault/zig-out/
|
||||
|
||||
# === OS ===
|
||||
os/output/
|
||||
|
||||
# === Local development ===
|
||||
.dev/
|
||||
.local/
|
||||
local/
|
||||
|
||||
data/*
|
||||
./bootstrap
|
||||
./node
|
||||
data/bootstrap/rqlite/
|
||||
|
||||
.env.*
|
||||
|
||||
configs/
|
||||
|
||||
.dev/
|
||||
|
||||
.gocache/
|
||||
|
||||
.claude/
|
||||
.mcp.json
|
||||
.cursor/
|
||||
121
.goreleaser.yaml
121
.goreleaser.yaml
@ -1,17 +1,23 @@
|
||||
# GoReleaser Configuration for DeBros Network
|
||||
# Builds and releases the dbn binary for multiple platforms
|
||||
# Other binaries (node, gateway, identity) are installed via: dbn setup
|
||||
# Builds and releases orama (CLI) and orama-node binaries
|
||||
# Publishes to: GitHub Releases, Homebrew, and apt (.deb packages)
|
||||
|
||||
project_name: debros-network
|
||||
project_name: orama-network
|
||||
|
||||
env:
|
||||
- GO111MODULE=on
|
||||
|
||||
before:
|
||||
hooks:
|
||||
- cmd: go mod tidy
|
||||
dir: core
|
||||
|
||||
builds:
|
||||
# dbn binary - only build the CLI
|
||||
- id: dbn
|
||||
# orama CLI binary
|
||||
- id: orama
|
||||
dir: core
|
||||
main: ./cmd/cli
|
||||
binary: dbn
|
||||
binary: orama
|
||||
goos:
|
||||
- linux
|
||||
- darwin
|
||||
@ -25,18 +31,107 @@ builds:
|
||||
- -X main.date={{.Date}}
|
||||
mod_timestamp: "{{ .CommitTimestamp }}"
|
||||
|
||||
# orama-node binary (Linux only for apt)
|
||||
- id: orama-node
|
||||
dir: core
|
||||
main: ./cmd/node
|
||||
binary: orama-node
|
||||
goos:
|
||||
- linux
|
||||
goarch:
|
||||
- amd64
|
||||
- arm64
|
||||
ldflags:
|
||||
- -s -w
|
||||
- -X main.version={{.Version}}
|
||||
- -X main.commit={{.ShortCommit}}
|
||||
- -X main.date={{.Date}}
|
||||
mod_timestamp: "{{ .CommitTimestamp }}"
|
||||
|
||||
archives:
|
||||
# Tar.gz archives for dbn
|
||||
- id: binaries
|
||||
# Tar.gz archives for orama CLI
|
||||
- id: orama-archives
|
||||
builds:
|
||||
- orama
|
||||
format: tar.gz
|
||||
name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}"
|
||||
name_template: "orama_{{ .Version }}_{{ .Os }}_{{ .Arch }}"
|
||||
files:
|
||||
- README.md
|
||||
- LICENSE
|
||||
- CHANGELOG.md
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
format: zip
|
||||
|
||||
# Tar.gz archives for orama-node
|
||||
- id: orama-node-archives
|
||||
builds:
|
||||
- orama-node
|
||||
format: tar.gz
|
||||
name_template: "orama-node_{{ .Version }}_{{ .Os }}_{{ .Arch }}"
|
||||
files:
|
||||
- README.md
|
||||
- LICENSE
|
||||
|
||||
# Debian packages for apt
|
||||
nfpms:
|
||||
# orama CLI .deb package
|
||||
- id: orama-deb
|
||||
package_name: orama
|
||||
builds:
|
||||
- orama
|
||||
vendor: DeBros
|
||||
homepage: https://github.com/DeBrosOfficial/network
|
||||
maintainer: DeBros <dev@debros.io>
|
||||
description: CLI tool for the Orama decentralized network
|
||||
license: MIT
|
||||
formats:
|
||||
- deb
|
||||
bindir: /usr/bin
|
||||
section: utils
|
||||
priority: optional
|
||||
contents:
|
||||
- src: ./core/README.md
|
||||
dst: /usr/share/doc/orama/README.md
|
||||
deb:
|
||||
lintian_overrides:
|
||||
- statically-linked-binary
|
||||
|
||||
# orama-node .deb package
|
||||
- id: orama-node-deb
|
||||
package_name: orama-node
|
||||
builds:
|
||||
- orama-node
|
||||
vendor: DeBros
|
||||
homepage: https://github.com/DeBrosOfficial/network
|
||||
maintainer: DeBros <dev@debros.io>
|
||||
description: Node daemon for the Orama decentralized network
|
||||
license: MIT
|
||||
formats:
|
||||
- deb
|
||||
bindir: /usr/bin
|
||||
section: net
|
||||
priority: optional
|
||||
contents:
|
||||
- src: ./core/README.md
|
||||
dst: /usr/share/doc/orama-node/README.md
|
||||
deb:
|
||||
lintian_overrides:
|
||||
- statically-linked-binary
|
||||
|
||||
# Homebrew tap for macOS (orama CLI only)
|
||||
brews:
|
||||
- name: orama
|
||||
ids:
|
||||
- orama-archives
|
||||
repository:
|
||||
owner: DeBrosOfficial
|
||||
name: homebrew-tap
|
||||
token: "{{ .Env.HOMEBREW_TAP_TOKEN }}"
|
||||
folder: Formula
|
||||
homepage: https://github.com/DeBrosOfficial/network
|
||||
description: CLI tool for the Orama decentralized network
|
||||
license: MIT
|
||||
install: |
|
||||
bin.install "orama"
|
||||
test: |
|
||||
system "#{bin}/orama", "--version"
|
||||
|
||||
checksum:
|
||||
name_template: "checksums.txt"
|
||||
|
||||
@ -32,7 +32,7 @@ This Code applies within all project spaces and when an individual is officially
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the maintainers at: security@debros.io
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the maintainers at: security@orama.io
|
||||
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
|
||||
@ -1,47 +1,78 @@
|
||||
# Contributing to DeBros Network
|
||||
# Contributing to Orama Network
|
||||
|
||||
Thanks for helping improve the network! This guide covers setup, local dev, tests, and PR guidelines.
|
||||
Thanks for helping improve the network! This monorepo contains multiple projects — pick the one relevant to your contribution.
|
||||
|
||||
## Requirements
|
||||
## Repository Structure
|
||||
|
||||
- Go 1.22+ (1.23 recommended)
|
||||
- RQLite (optional for local runs; the Makefile starts nodes with embedded setup)
|
||||
- Make (optional)
|
||||
| Package | Language | Build |
|
||||
|---------|----------|-------|
|
||||
| `core/` | Go 1.24+ | `make core-build` |
|
||||
| `website/` | TypeScript (pnpm) | `make website-build` |
|
||||
| `vault/` | Zig 0.14+ | `make vault-build` |
|
||||
| `os/` | Go + Buildroot | `make os-build` |
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
git clone https://github.com/DeBrosOfficial/network.git
|
||||
cd network
|
||||
make deps
|
||||
```
|
||||
|
||||
## Build, Test, Lint
|
||||
|
||||
- Build: `make build`
|
||||
- Test: `make test`
|
||||
- Format/Vet: `make fmt vet` (or `make lint`)
|
||||
|
||||
````
|
||||
|
||||
Useful CLI commands:
|
||||
### Core (Go)
|
||||
|
||||
```bash
|
||||
./bin/orama health
|
||||
./bin/orama peers
|
||||
./bin/orama status
|
||||
````
|
||||
cd core
|
||||
make deps
|
||||
make build
|
||||
make test
|
||||
```
|
||||
|
||||
## Versioning
|
||||
### Website
|
||||
|
||||
- The CLI reports its version via `orama version`.
|
||||
- Releases are tagged (e.g., `v0.18.0-beta`) and published via GoReleaser.
|
||||
```bash
|
||||
cd website
|
||||
pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
### Vault (Zig)
|
||||
|
||||
```bash
|
||||
cd vault
|
||||
zig build
|
||||
zig build test
|
||||
```
|
||||
|
||||
## Pull Requests
|
||||
|
||||
1. Fork and create a topic branch.
|
||||
2. Ensure `make build test` passes; include tests for new functionality.
|
||||
3. Keep PRs focused and well-described (motivation, approach, testing).
|
||||
4. Update README/docs for behavior changes.
|
||||
1. Fork and create a topic branch from `main`.
|
||||
2. Ensure `make test` passes for affected packages.
|
||||
3. Include tests for new functionality or bug fixes.
|
||||
4. Keep PRs focused — one concern per PR.
|
||||
5. Write a clear description: motivation, approach, and how you tested it.
|
||||
6. Update docs if you're changing user-facing behavior.
|
||||
|
||||
## Code Style
|
||||
|
||||
### Go (core/, os/)
|
||||
|
||||
- Follow standard Go conventions
|
||||
- Run `make lint` before submitting
|
||||
- Wrap errors with context: `fmt.Errorf("failed to X: %w", err)`
|
||||
- No magic values — use named constants
|
||||
|
||||
### TypeScript (website/)
|
||||
|
||||
- TypeScript strict mode
|
||||
- Follow existing patterns in the codebase
|
||||
|
||||
### Zig (vault/)
|
||||
|
||||
- Follow standard Zig conventions
|
||||
- Run `zig build test` before submitting
|
||||
|
||||
## Security
|
||||
|
||||
If you find a security vulnerability, **do not open a public issue**. Email security@debros.io instead.
|
||||
|
||||
Thank you for contributing!
|
||||
|
||||
150
Makefile
150
Makefile
@ -1,122 +1,66 @@
|
||||
TEST?=./...
|
||||
# Orama Monorepo
|
||||
# Delegates to sub-project Makefiles
|
||||
|
||||
.PHONY: test
|
||||
test:
|
||||
@echo Running tests...
|
||||
go test -v $(TEST)
|
||||
.PHONY: help build test clean
|
||||
|
||||
# Gateway-focused E2E tests assume gateway and nodes are already running
|
||||
# Auto-discovers configuration from ~/.orama and queries database for API key
|
||||
# No environment variables required
|
||||
.PHONY: test-e2e
|
||||
test-e2e:
|
||||
@echo "Running comprehensive E2E tests..."
|
||||
@echo "Auto-discovering configuration from ~/.orama..."
|
||||
go test -v -tags e2e ./e2e
|
||||
# === Core (Go network) ===
|
||||
.PHONY: core core-build core-test core-clean core-lint
|
||||
core: core-build
|
||||
|
||||
# Network - Distributed P2P Database System
|
||||
# Makefile for development and build tasks
|
||||
core-build:
|
||||
$(MAKE) -C core build
|
||||
|
||||
.PHONY: build clean test run-node run-node2 run-node3 run-example deps tidy fmt vet lint clear-ports install-hooks kill
|
||||
core-test:
|
||||
$(MAKE) -C core test
|
||||
|
||||
VERSION := 0.90.0
|
||||
COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo unknown)
|
||||
DATE ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
LDFLAGS := -X 'main.version=$(VERSION)' -X 'main.commit=$(COMMIT)' -X 'main.date=$(DATE)'
|
||||
core-lint:
|
||||
$(MAKE) -C core lint
|
||||
|
||||
# Build targets
|
||||
build: deps
|
||||
@echo "Building network executables (version=$(VERSION))..."
|
||||
@mkdir -p bin
|
||||
go build -ldflags "$(LDFLAGS)" -o bin/identity ./cmd/identity
|
||||
go build -ldflags "$(LDFLAGS)" -o bin/orama-node ./cmd/node
|
||||
go build -ldflags "$(LDFLAGS)" -o bin/orama cmd/cli/main.go
|
||||
go build -ldflags "$(LDFLAGS)" -o bin/rqlite-mcp ./cmd/rqlite-mcp
|
||||
# Inject gateway build metadata via pkg path variables
|
||||
go build -ldflags "$(LDFLAGS) -X 'github.com/DeBrosOfficial/network/pkg/gateway.BuildVersion=$(VERSION)' -X 'github.com/DeBrosOfficial/network/pkg/gateway.BuildCommit=$(COMMIT)' -X 'github.com/DeBrosOfficial/network/pkg/gateway.BuildTime=$(DATE)'" -o bin/gateway ./cmd/gateway
|
||||
@echo "Build complete! Run ./bin/orama version"
|
||||
core-clean:
|
||||
$(MAKE) -C core clean
|
||||
|
||||
# Install git hooks
|
||||
install-hooks:
|
||||
@echo "Installing git hooks..."
|
||||
@bash scripts/install-hooks.sh
|
||||
# === Website ===
|
||||
.PHONY: website website-dev website-build
|
||||
website-dev:
|
||||
cd website && pnpm dev
|
||||
|
||||
# Clean build artifacts
|
||||
clean:
|
||||
@echo "Cleaning build artifacts..."
|
||||
rm -rf bin/
|
||||
rm -rf data/
|
||||
@echo "Clean complete!"
|
||||
website-build:
|
||||
cd website && pnpm build
|
||||
|
||||
# Run bootstrap node (auto-selects identity and data dir)
|
||||
run-node:
|
||||
@echo "Starting node..."
|
||||
@echo "Config: ~/.orama/node.yaml"
|
||||
go run ./cmd/orama-node --config node.yaml
|
||||
# === SDK (TypeScript) ===
|
||||
.PHONY: sdk sdk-build sdk-test
|
||||
sdk: sdk-build
|
||||
|
||||
# Run second node - requires join address
|
||||
run-node2:
|
||||
@echo "Starting second node..."
|
||||
@echo "Config: ~/.orama/node2.yaml"
|
||||
go run ./cmd/orama-node --config node2.yaml
|
||||
sdk-build:
|
||||
cd sdk && pnpm install && pnpm build
|
||||
|
||||
# Run third node - requires join address
|
||||
run-node3:
|
||||
@echo "Starting third node..."
|
||||
@echo "Config: ~/.orama/node3.yaml"
|
||||
go run ./cmd/orama-node --config node3.yaml
|
||||
sdk-test:
|
||||
cd sdk && pnpm test
|
||||
|
||||
# Run gateway HTTP server
|
||||
run-gateway:
|
||||
@echo "Starting gateway HTTP server..."
|
||||
@echo "Note: Config must be in ~/.orama/data/gateway.yaml"
|
||||
go run ./cmd/orama-gateway
|
||||
# === Vault (Zig) ===
|
||||
.PHONY: vault vault-build vault-test
|
||||
vault-build:
|
||||
cd vault && zig build
|
||||
|
||||
# Development environment target
|
||||
# Uses orama dev up to start full stack with dependency and port checking
|
||||
dev: build
|
||||
@./bin/orama dev up
|
||||
vault-test:
|
||||
cd vault && zig build test
|
||||
|
||||
# Graceful shutdown of all dev services
|
||||
stop:
|
||||
@if [ -f ./bin/orama ]; then \
|
||||
./bin/orama dev down || true; \
|
||||
fi
|
||||
@bash scripts/dev-kill-all.sh
|
||||
# === OS ===
|
||||
.PHONY: os os-build
|
||||
os-build:
|
||||
$(MAKE) -C os
|
||||
|
||||
# Force kill all processes (immediate termination)
|
||||
kill:
|
||||
@bash scripts/dev-kill-all.sh
|
||||
# === Aggregate ===
|
||||
build: core-build
|
||||
test: core-test
|
||||
clean: core-clean
|
||||
|
||||
# Help
|
||||
help:
|
||||
@echo "Available targets:"
|
||||
@echo " build - Build all executables"
|
||||
@echo " clean - Clean build artifacts"
|
||||
@echo " test - Run tests"
|
||||
@echo "Orama Monorepo"
|
||||
@echo ""
|
||||
@echo "Local Development (Recommended):"
|
||||
@echo " make dev - Start full development stack with one command"
|
||||
@echo " - Checks dependencies and available ports"
|
||||
@echo " - Generates configs and starts all services"
|
||||
@echo " - Validates cluster health"
|
||||
@echo " make stop - Gracefully stop all development services"
|
||||
@echo " make kill - Force kill all development services (use if stop fails)"
|
||||
@echo " Core (Go): make core-build | core-test | core-lint | core-clean"
|
||||
@echo " Website: make website-dev | website-build"
|
||||
@echo " Vault (Zig): make vault-build | vault-test"
|
||||
@echo " OS: make os-build"
|
||||
@echo ""
|
||||
@echo "Development Management (via orama):"
|
||||
@echo " ./bin/orama dev status - Show status of all dev services"
|
||||
@echo " ./bin/orama dev logs <component> [--follow]"
|
||||
@echo ""
|
||||
@echo "Individual Node Targets (advanced):"
|
||||
@echo " run-node - Start first node directly"
|
||||
@echo " run-node2 - Start second node directly"
|
||||
@echo " run-node3 - Start third node directly"
|
||||
@echo " run-gateway - Start HTTP gateway directly"
|
||||
@echo ""
|
||||
@echo "Maintenance:"
|
||||
@echo " deps - Download dependencies"
|
||||
@echo " tidy - Tidy dependencies"
|
||||
@echo " fmt - Format code"
|
||||
@echo " vet - Vet code"
|
||||
@echo " lint - Lint code (fmt + vet)"
|
||||
@echo " help - Show this help"
|
||||
@echo " Aggregate: make build | test | clean (delegates to core)"
|
||||
|
||||
397
README.md
397
README.md
@ -1,379 +1,50 @@
|
||||
# Orama Network - Distributed P2P Platform
|
||||
# Orama Network
|
||||
|
||||
A high-performance API Gateway and distributed platform built in Go. Provides a unified HTTP/HTTPS API for distributed SQL (RQLite), distributed caching (Olric), decentralized storage (IPFS), pub/sub messaging, and serverless WebAssembly execution.
|
||||
A decentralized infrastructure platform combining distributed SQL, IPFS storage, caching, serverless WASM execution, and privacy relay — all managed through a unified API gateway.
|
||||
|
||||
**Architecture:** Modular Gateway / Edge Proxy following SOLID principles
|
||||
## Packages
|
||||
|
||||
## Features
|
||||
|
||||
- **🔐 Authentication** - Wallet signatures, API keys, JWT tokens
|
||||
- **💾 Storage** - IPFS-based decentralized file storage with encryption
|
||||
- **⚡ Cache** - Distributed cache with Olric (in-memory key-value)
|
||||
- **🗄️ Database** - RQLite distributed SQL with Raft consensus
|
||||
- **📡 Pub/Sub** - Real-time messaging via LibP2P and WebSocket
|
||||
- **⚙️ Serverless** - WebAssembly function execution with host functions
|
||||
- **🌐 HTTP Gateway** - Unified REST API with automatic HTTPS (Let's Encrypt)
|
||||
- **📦 Client SDK** - Type-safe Go SDK for all services
|
||||
| Package | Language | Description |
|
||||
|---------|----------|-------------|
|
||||
| [core/](core/) | Go | API gateway, distributed node, CLI, and client SDK |
|
||||
| [sdk/](sdk/) | TypeScript | `@debros/orama` — JavaScript/TypeScript SDK ([npm](https://www.npmjs.com/package/@debros/orama)) |
|
||||
| [website/](website/) | TypeScript | Marketing website and invest portal |
|
||||
| [vault/](vault/) | Zig | Distributed secrets vault (Shamir's Secret Sharing) |
|
||||
| [os/](os/) | Go + Buildroot | OramaOS — hardened minimal Linux for network nodes |
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Local Development
|
||||
|
||||
```bash
|
||||
# Build the project
|
||||
make build
|
||||
# Build the core network binaries
|
||||
make core-build
|
||||
|
||||
# Start 5-node development cluster
|
||||
make dev
|
||||
# Run tests
|
||||
make core-test
|
||||
|
||||
# Start website dev server
|
||||
make website-dev
|
||||
|
||||
# Build vault
|
||||
make vault-build
|
||||
```
|
||||
|
||||
The cluster automatically performs health checks before declaring success.
|
||||
|
||||
### Stop Development Environment
|
||||
|
||||
```bash
|
||||
make stop
|
||||
```
|
||||
|
||||
## Testing Services
|
||||
|
||||
After running `make dev`, test service health using these curl requests:
|
||||
|
||||
### Node Unified Gateways
|
||||
|
||||
Each node is accessible via a single unified gateway port:
|
||||
|
||||
```bash
|
||||
# Node-1 (port 6001)
|
||||
curl http://localhost:6001/health
|
||||
|
||||
# Node-2 (port 6002)
|
||||
curl http://localhost:6002/health
|
||||
|
||||
# Node-3 (port 6003)
|
||||
curl http://localhost:6003/health
|
||||
|
||||
# Node-4 (port 6004)
|
||||
curl http://localhost:6004/health
|
||||
|
||||
# Node-5 (port 6005)
|
||||
curl http://localhost:6005/health
|
||||
```
|
||||
|
||||
## Network Architecture
|
||||
|
||||
### Unified Gateway Ports
|
||||
|
||||
```
|
||||
Node-1: localhost:6001 → /rqlite/http, /rqlite/raft, /cluster, /ipfs/api
|
||||
Node-2: localhost:6002 → Same routes
|
||||
Node-3: localhost:6003 → Same routes
|
||||
Node-4: localhost:6004 → Same routes
|
||||
Node-5: localhost:6005 → Same routes
|
||||
```
|
||||
|
||||
### Direct Service Ports (for debugging)
|
||||
|
||||
```
|
||||
RQLite HTTP: 5001, 5002, 5003, 5004, 5005 (one per node)
|
||||
RQLite Raft: 7001, 7002, 7003, 7004, 7005
|
||||
IPFS API: 4501, 4502, 4503, 4504, 4505
|
||||
IPFS Swarm: 4101, 4102, 4103, 4104, 4105
|
||||
Cluster API: 9094, 9104, 9114, 9124, 9134
|
||||
Internal Gateway: 6000
|
||||
Olric Cache: 3320
|
||||
Anon SOCKS: 9050
|
||||
```
|
||||
|
||||
## Development Commands
|
||||
|
||||
```bash
|
||||
# Start full cluster (5 nodes + gateway)
|
||||
make dev
|
||||
|
||||
# Check service status
|
||||
orama dev status
|
||||
|
||||
# View logs
|
||||
orama dev logs node-1 # Node-1 logs
|
||||
orama dev logs node-1 --follow # Follow logs in real-time
|
||||
orama dev logs gateway --follow # Gateway logs
|
||||
|
||||
# Stop all services
|
||||
orama stop
|
||||
|
||||
# Build binaries
|
||||
make build
|
||||
```
|
||||
|
||||
## CLI Commands
|
||||
|
||||
### Network Status
|
||||
|
||||
```bash
|
||||
./bin/orama health # Cluster health check
|
||||
./bin/orama peers # List connected peers
|
||||
./bin/orama status # Network status
|
||||
```
|
||||
|
||||
### Database Operations
|
||||
|
||||
```bash
|
||||
./bin/orama query "SELECT * FROM users"
|
||||
./bin/orama query "CREATE TABLE users (id INTEGER PRIMARY KEY)"
|
||||
./bin/orama transaction --file ops.json
|
||||
```
|
||||
|
||||
### Pub/Sub
|
||||
|
||||
```bash
|
||||
./bin/orama pubsub publish <topic> <message>
|
||||
./bin/orama pubsub subscribe <topic> 30s
|
||||
./bin/orama pubsub topics
|
||||
```
|
||||
|
||||
### Authentication
|
||||
|
||||
```bash
|
||||
./bin/orama auth login
|
||||
./bin/orama auth status
|
||||
./bin/orama auth logout
|
||||
```
|
||||
|
||||
## Serverless Functions (WASM)
|
||||
|
||||
Orama supports high-performance serverless function execution using WebAssembly (WASM). Functions are isolated, secure, and can interact with network services like the distributed cache.
|
||||
|
||||
### 1. Build Functions
|
||||
|
||||
Functions must be compiled to WASM. We recommend using [TinyGo](https://tinygo.org/).
|
||||
|
||||
```bash
|
||||
# Build example functions to examples/functions/bin/
|
||||
./examples/functions/build.sh
|
||||
```
|
||||
|
||||
### 2. Deployment
|
||||
|
||||
Deploy your compiled `.wasm` file to the network via the Gateway.
|
||||
|
||||
```bash
|
||||
# Deploy a function
|
||||
curl -X POST http://localhost:6001/v1/functions \
|
||||
-H "Authorization: Bearer <your_api_key>" \
|
||||
-F "name=hello-world" \
|
||||
-F "namespace=default" \
|
||||
-F "wasm=@./examples/functions/bin/hello.wasm"
|
||||
```
|
||||
|
||||
### 3. Invocation
|
||||
|
||||
Trigger your function with a JSON payload. The function receives the payload via `stdin` and returns its response via `stdout`.
|
||||
|
||||
```bash
|
||||
# Invoke via HTTP
|
||||
curl -X POST http://localhost:6001/v1/functions/hello-world/invoke \
|
||||
-H "Authorization: Bearer <your_api_key>" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"name": "Developer"}'
|
||||
```
|
||||
|
||||
### 4. Management
|
||||
|
||||
```bash
|
||||
# List all functions in a namespace
|
||||
curl http://localhost:6001/v1/functions?namespace=default
|
||||
|
||||
# Delete a function
|
||||
curl -X DELETE http://localhost:6001/v1/functions/hello-world?namespace=default
|
||||
```
|
||||
|
||||
## Production Deployment
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Ubuntu 22.04+ or Debian 12+
|
||||
- `amd64` or `arm64` architecture
|
||||
- 4GB RAM, 50GB SSD, 2 CPU cores
|
||||
|
||||
### Required Ports
|
||||
|
||||
**External (must be open in firewall):**
|
||||
|
||||
- **80** - HTTP (ACME/Let's Encrypt certificate challenges)
|
||||
- **443** - HTTPS (Main gateway API endpoint)
|
||||
- **4101** - IPFS Swarm (peer connections)
|
||||
- **7001** - RQLite Raft (cluster consensus)
|
||||
|
||||
**Internal (bound to localhost, no firewall needed):**
|
||||
|
||||
- 4501 - IPFS API
|
||||
- 5001 - RQLite HTTP API
|
||||
- 6001 - Unified Gateway
|
||||
- 8080 - IPFS Gateway
|
||||
- 9050 - Anyone Client SOCKS5 proxy
|
||||
- 9094 - IPFS Cluster API
|
||||
- 3320/3322 - Olric Cache
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# Install via APT
|
||||
echo "deb https://debrosficial.github.io/network/apt stable main" | sudo tee /etc/apt/sources.list.d/debros.list
|
||||
|
||||
sudo apt update && sudo apt install orama
|
||||
|
||||
sudo orama install --interactive
|
||||
```
|
||||
|
||||
### Service Management
|
||||
|
||||
```bash
|
||||
# Status
|
||||
orama status
|
||||
|
||||
# Control services
|
||||
sudo orama start
|
||||
sudo orama stop
|
||||
sudo orama restart
|
||||
|
||||
# View logs
|
||||
orama logs node --follow
|
||||
orama logs gateway --follow
|
||||
orama logs ipfs --follow
|
||||
```
|
||||
|
||||
### Upgrade
|
||||
|
||||
```bash
|
||||
# Upgrade to latest version
|
||||
sudo orama upgrade --interactive
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
All configuration lives in `~/.orama/`:
|
||||
|
||||
- `configs/node.yaml` - Node configuration
|
||||
- `configs/gateway.yaml` - Gateway configuration
|
||||
- `configs/olric.yaml` - Cache configuration
|
||||
- `secrets/` - Keys and certificates
|
||||
- `data/` - Service data directories
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Services Not Starting
|
||||
|
||||
```bash
|
||||
# Check status
|
||||
systemctl status debros-node
|
||||
|
||||
# View logs
|
||||
journalctl -u debros-node -f
|
||||
|
||||
# Check log files
|
||||
tail -f /home/debros/.orama/logs/node.log
|
||||
```
|
||||
|
||||
### Port Conflicts
|
||||
|
||||
```bash
|
||||
# Check what's using specific ports
|
||||
sudo lsof -i :443 # HTTPS Gateway
|
||||
sudo lsof -i :7001 # TCP/SNI Gateway
|
||||
sudo lsof -i :6001 # Internal Gateway
|
||||
```
|
||||
|
||||
### RQLite Cluster Issues
|
||||
|
||||
```bash
|
||||
# Connect to RQLite CLI
|
||||
rqlite -H localhost -p 5001
|
||||
|
||||
# Check cluster status
|
||||
.nodes
|
||||
.status
|
||||
.ready
|
||||
|
||||
# Check consistency level
|
||||
.consistency
|
||||
```
|
||||
|
||||
### Reset Installation
|
||||
|
||||
```bash
|
||||
# Production reset (⚠️ DESTROYS DATA)
|
||||
sudo orama uninstall
|
||||
sudo rm -rf /home/debros/.orama
|
||||
sudo orama install
|
||||
```
|
||||
|
||||
## HTTP Gateway API
|
||||
|
||||
### Main Gateway Endpoints
|
||||
|
||||
- `GET /health` - Health status
|
||||
- `GET /v1/status` - Full status
|
||||
- `GET /v1/version` - Version info
|
||||
- `POST /v1/rqlite/exec` - Execute SQL
|
||||
- `POST /v1/rqlite/query` - Query database
|
||||
- `GET /v1/rqlite/schema` - Get schema
|
||||
- `POST /v1/pubsub/publish` - Publish message
|
||||
- `GET /v1/pubsub/topics` - List topics
|
||||
- `GET /v1/pubsub/ws?topic=<name>` - WebSocket subscribe
|
||||
- `POST /v1/functions` - Deploy function (multipart/form-data)
|
||||
- `POST /v1/functions/{name}/invoke` - Invoke function
|
||||
- `GET /v1/functions` - List functions
|
||||
- `DELETE /v1/functions/{name}` - Delete function
|
||||
- `GET /v1/functions/{name}/logs` - Get function logs
|
||||
|
||||
See `openapi/gateway.yaml` for complete API specification.
|
||||
|
||||
## Documentation
|
||||
|
||||
- **[Architecture Guide](docs/ARCHITECTURE.md)** - System architecture and design patterns
|
||||
- **[Client SDK](docs/CLIENT_SDK.md)** - Go SDK documentation and examples
|
||||
- **[Gateway API](docs/GATEWAY_API.md)** - Complete HTTP API reference
|
||||
- **[Security Deployment](docs/SECURITY_DEPLOYMENT_GUIDE.md)** - Production security hardening
|
||||
|
||||
## Resources
|
||||
|
||||
- [RQLite Documentation](https://rqlite.io/docs/)
|
||||
- [IPFS Documentation](https://docs.ipfs.tech/)
|
||||
- [LibP2P Documentation](https://docs.libp2p.io/)
|
||||
- [WebAssembly](https://webassembly.org/)
|
||||
- [GitHub Repository](https://github.com/DeBrosOfficial/network)
|
||||
- [Issue Tracker](https://github.com/DeBrosOfficial/network/issues)
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
network/
|
||||
├── cmd/ # Binary entry points
|
||||
│ ├── cli/ # CLI tool
|
||||
│ ├── gateway/ # HTTP Gateway
|
||||
│ ├── node/ # P2P Node
|
||||
│ └── rqlite-mcp/ # RQLite MCP server
|
||||
├── pkg/ # Core packages
|
||||
│ ├── gateway/ # Gateway implementation
|
||||
│ │ └── handlers/ # HTTP handlers by domain
|
||||
│ ├── client/ # Go SDK
|
||||
│ ├── serverless/ # WASM engine
|
||||
│ ├── rqlite/ # Database ORM
|
||||
│ ├── contracts/ # Interface definitions
|
||||
│ ├── httputil/ # HTTP utilities
|
||||
│ └── errors/ # Error handling
|
||||
├── docs/ # Documentation
|
||||
├── e2e/ # End-to-end tests
|
||||
└── examples/ # Example code
|
||||
```
|
||||
| Document | Description |
|
||||
|----------|-------------|
|
||||
| [Architecture](core/docs/ARCHITECTURE.md) | System architecture and design patterns |
|
||||
| [Deployment Guide](core/docs/DEPLOYMENT_GUIDE.md) | Deploy apps, databases, and domains |
|
||||
| [Dev & Deploy](core/docs/DEV_DEPLOY.md) | Building, deploying to VPS, rolling upgrades |
|
||||
| [Security](core/docs/SECURITY.md) | Security hardening and threat model |
|
||||
| [Monitoring](core/docs/MONITORING.md) | Cluster health monitoring |
|
||||
| [Client SDK](core/docs/CLIENT_SDK.md) | Go SDK documentation |
|
||||
| [Serverless](core/docs/SERVERLESS.md) | WASM serverless functions |
|
||||
| [Common Problems](core/docs/COMMON_PROBLEMS.md) | Troubleshooting known issues |
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome! This project follows:
|
||||
- **SOLID Principles** - Single responsibility, open/closed, etc.
|
||||
- **DRY Principle** - Don't repeat yourself
|
||||
- **Clean Architecture** - Clear separation of concerns
|
||||
- **Test Coverage** - Unit and E2E tests required
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, development, and PR guidelines.
|
||||
|
||||
See our architecture docs for design patterns and guidelines.
|
||||
## License
|
||||
|
||||
[AGPL-3.0](LICENSE)
|
||||
|
||||
151
cmd/cli/main.go
151
cmd/cli/main.go
@ -1,151 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/pkg/cli"
|
||||
)
|
||||
|
||||
var (
|
||||
timeout = 30 * time.Second
|
||||
format = "table"
|
||||
)
|
||||
|
||||
// version metadata populated via -ldflags at build time
|
||||
var (
|
||||
version = "dev"
|
||||
commit = ""
|
||||
date = ""
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
showHelp()
|
||||
return
|
||||
}
|
||||
|
||||
command := os.Args[1]
|
||||
args := os.Args[2:]
|
||||
|
||||
// Parse global flags
|
||||
parseGlobalFlags(args)
|
||||
|
||||
switch command {
|
||||
case "version":
|
||||
fmt.Printf("orama %s", version)
|
||||
if commit != "" {
|
||||
fmt.Printf(" (commit %s)", commit)
|
||||
}
|
||||
if date != "" {
|
||||
fmt.Printf(" built %s", date)
|
||||
}
|
||||
fmt.Println()
|
||||
return
|
||||
|
||||
// Development environment commands
|
||||
case "dev":
|
||||
cli.HandleDevCommand(args)
|
||||
|
||||
// Production environment commands (legacy with 'prod' prefix)
|
||||
case "prod":
|
||||
cli.HandleProdCommand(args)
|
||||
|
||||
// Direct production commands (new simplified interface)
|
||||
case "install":
|
||||
cli.HandleProdCommand(append([]string{"install"}, args...))
|
||||
case "upgrade":
|
||||
cli.HandleProdCommand(append([]string{"upgrade"}, args...))
|
||||
case "migrate":
|
||||
cli.HandleProdCommand(append([]string{"migrate"}, args...))
|
||||
case "status":
|
||||
cli.HandleProdCommand(append([]string{"status"}, args...))
|
||||
case "start":
|
||||
cli.HandleProdCommand(append([]string{"start"}, args...))
|
||||
case "stop":
|
||||
cli.HandleProdCommand(append([]string{"stop"}, args...))
|
||||
case "restart":
|
||||
cli.HandleProdCommand(append([]string{"restart"}, args...))
|
||||
case "logs":
|
||||
cli.HandleProdCommand(append([]string{"logs"}, args...))
|
||||
case "uninstall":
|
||||
cli.HandleProdCommand(append([]string{"uninstall"}, args...))
|
||||
|
||||
// Authentication commands
|
||||
case "auth":
|
||||
cli.HandleAuthCommand(args)
|
||||
|
||||
// Help
|
||||
case "help", "--help", "-h":
|
||||
showHelp()
|
||||
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "Unknown command: %s\n", command)
|
||||
showHelp()
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func parseGlobalFlags(args []string) {
|
||||
for i, arg := range args {
|
||||
switch arg {
|
||||
case "-f", "--format":
|
||||
if i+1 < len(args) {
|
||||
format = args[i+1]
|
||||
}
|
||||
case "-t", "--timeout":
|
||||
if i+1 < len(args) {
|
||||
if d, err := time.ParseDuration(args[i+1]); err == nil {
|
||||
timeout = d
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func showHelp() {
|
||||
fmt.Printf("Orama CLI - Distributed P2P Network Management Tool\n\n")
|
||||
fmt.Printf("Usage: orama <command> [args...]\n\n")
|
||||
|
||||
fmt.Printf("💻 Local Development:\n")
|
||||
fmt.Printf(" dev up - Start full local dev environment\n")
|
||||
fmt.Printf(" dev down - Stop all dev services\n")
|
||||
fmt.Printf(" dev status - Show status of dev services\n")
|
||||
fmt.Printf(" dev logs <component> - View dev component logs\n")
|
||||
fmt.Printf(" dev help - Show dev command help\n\n")
|
||||
|
||||
fmt.Printf("🚀 Production Deployment:\n")
|
||||
fmt.Printf(" install - Install production node (requires root/sudo)\n")
|
||||
fmt.Printf(" upgrade - Upgrade existing installation\n")
|
||||
fmt.Printf(" status - Show production service status\n")
|
||||
fmt.Printf(" start - Start all production services (requires root/sudo)\n")
|
||||
fmt.Printf(" stop - Stop all production services (requires root/sudo)\n")
|
||||
fmt.Printf(" restart - Restart all production services (requires root/sudo)\n")
|
||||
fmt.Printf(" logs <service> - View production service logs\n")
|
||||
fmt.Printf(" uninstall - Remove production services (requires root/sudo)\n\n")
|
||||
|
||||
fmt.Printf("🔐 Authentication:\n")
|
||||
fmt.Printf(" auth login - Authenticate with wallet\n")
|
||||
fmt.Printf(" auth logout - Clear stored credentials\n")
|
||||
fmt.Printf(" auth whoami - Show current authentication\n")
|
||||
fmt.Printf(" auth status - Show detailed auth info\n")
|
||||
fmt.Printf(" auth help - Show auth command help\n\n")
|
||||
|
||||
fmt.Printf("Global Flags:\n")
|
||||
fmt.Printf(" -f, --format <format> - Output format: table, json (default: table)\n")
|
||||
fmt.Printf(" -t, --timeout <duration> - Operation timeout (default: 30s)\n")
|
||||
fmt.Printf(" --help, -h - Show this help message\n\n")
|
||||
|
||||
fmt.Printf("Examples:\n")
|
||||
fmt.Printf(" # First node (creates new cluster)\n")
|
||||
fmt.Printf(" sudo orama install --vps-ip 203.0.113.1 --domain node-1.orama.network\n\n")
|
||||
|
||||
fmt.Printf(" # Join existing cluster\n")
|
||||
fmt.Printf(" sudo orama install --vps-ip 203.0.113.2 --domain node-2.orama.network \\\n")
|
||||
fmt.Printf(" --peers /ip4/203.0.113.1/tcp/4001/p2p/12D3KooW... --cluster-secret <hex>\n\n")
|
||||
|
||||
fmt.Printf(" # Service management\n")
|
||||
fmt.Printf(" orama status\n")
|
||||
fmt.Printf(" orama logs node --follow\n")
|
||||
}
|
||||
@ -1,320 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/rqlite/gorqlite"
|
||||
)
|
||||
|
||||
// MCP JSON-RPC types
|
||||
type JSONRPCRequest struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID any `json:"id,omitempty"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
type JSONRPCResponse struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID any `json:"id"`
|
||||
Result any `json:"result,omitempty"`
|
||||
Error *ResponseError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type ResponseError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// Tool definition
|
||||
type Tool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema any `json:"inputSchema"`
|
||||
}
|
||||
|
||||
// Tool call types
|
||||
type CallToolRequest struct {
|
||||
Name string `json:"name"`
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
}
|
||||
|
||||
type TextContent struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type CallToolResult struct {
|
||||
Content []TextContent `json:"content"`
|
||||
IsError bool `json:"isError,omitempty"`
|
||||
}
|
||||
|
||||
type MCPServer struct {
|
||||
conn *gorqlite.Connection
|
||||
}
|
||||
|
||||
func NewMCPServer(rqliteURL string) (*MCPServer, error) {
|
||||
conn, err := gorqlite.Open(rqliteURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &MCPServer{
|
||||
conn: conn,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *MCPServer) handleRequest(req JSONRPCRequest) JSONRPCResponse {
|
||||
var resp JSONRPCResponse
|
||||
resp.JSONRPC = "2.0"
|
||||
resp.ID = req.ID
|
||||
|
||||
// Debug logging disabled to prevent excessive disk writes
|
||||
// log.Printf("Received method: %s", req.Method)
|
||||
|
||||
switch req.Method {
|
||||
case "initialize":
|
||||
resp.Result = map[string]any{
|
||||
"protocolVersion": "2024-11-05",
|
||||
"capabilities": map[string]any{
|
||||
"tools": map[string]any{},
|
||||
},
|
||||
"serverInfo": map[string]any{
|
||||
"name": "rqlite-mcp",
|
||||
"version": "0.1.0",
|
||||
},
|
||||
}
|
||||
|
||||
case "notifications/initialized":
|
||||
// This is a notification, no response needed
|
||||
return JSONRPCResponse{}
|
||||
|
||||
case "tools/list":
|
||||
// Debug logging disabled to prevent excessive disk writes
|
||||
tools := []Tool{
|
||||
{
|
||||
Name: "list_tables",
|
||||
Description: "List all tables in the Rqlite database",
|
||||
InputSchema: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "query",
|
||||
Description: "Run a SELECT query on the Rqlite database",
|
||||
InputSchema: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"sql": map[string]any{
|
||||
"type": "string",
|
||||
"description": "The SQL SELECT query to run",
|
||||
},
|
||||
},
|
||||
"required": []string{"sql"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "execute",
|
||||
Description: "Run an INSERT, UPDATE, or DELETE statement on the Rqlite database",
|
||||
InputSchema: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"sql": map[string]any{
|
||||
"type": "string",
|
||||
"description": "The SQL statement (INSERT, UPDATE, DELETE) to run",
|
||||
},
|
||||
},
|
||||
"required": []string{"sql"},
|
||||
},
|
||||
},
|
||||
}
|
||||
resp.Result = map[string]any{"tools": tools}
|
||||
|
||||
case "tools/call":
|
||||
var callReq CallToolRequest
|
||||
if err := json.Unmarshal(req.Params, &callReq); err != nil {
|
||||
resp.Error = &ResponseError{Code: -32700, Message: "Parse error"}
|
||||
return resp
|
||||
}
|
||||
resp.Result = s.handleToolCall(callReq)
|
||||
|
||||
default:
|
||||
// Debug logging disabled to prevent excessive disk writes
|
||||
resp.Error = &ResponseError{Code: -32601, Message: "Method not found"}
|
||||
}
|
||||
|
||||
return resp
|
||||
}
|
||||
|
||||
func (s *MCPServer) handleToolCall(req CallToolRequest) CallToolResult {
|
||||
// Debug logging disabled to prevent excessive disk writes
|
||||
// log.Printf("Tool call: %s", req.Name)
|
||||
|
||||
switch req.Name {
|
||||
case "list_tables":
|
||||
rows, err := s.conn.QueryOne("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
|
||||
if err != nil {
|
||||
return errorResult(fmt.Sprintf("Error listing tables: %v", err))
|
||||
}
|
||||
var tables []string
|
||||
for rows.Next() {
|
||||
slice, err := rows.Slice()
|
||||
if err == nil && len(slice) > 0 {
|
||||
tables = append(tables, fmt.Sprint(slice[0]))
|
||||
}
|
||||
}
|
||||
if len(tables) == 0 {
|
||||
return textResult("No tables found")
|
||||
}
|
||||
return textResult(strings.Join(tables, "\n"))
|
||||
|
||||
case "query":
|
||||
var args struct {
|
||||
SQL string `json:"sql"`
|
||||
}
|
||||
if err := json.Unmarshal(req.Arguments, &args); err != nil {
|
||||
return errorResult(fmt.Sprintf("Invalid arguments: %v", err))
|
||||
}
|
||||
// Debug logging disabled to prevent excessive disk writes
|
||||
rows, err := s.conn.QueryOne(args.SQL)
|
||||
if err != nil {
|
||||
return errorResult(fmt.Sprintf("Query error: %v", err))
|
||||
}
|
||||
|
||||
var result strings.Builder
|
||||
cols := rows.Columns()
|
||||
result.WriteString(strings.Join(cols, " | ") + "\n")
|
||||
result.WriteString(strings.Repeat("-", len(cols)*10) + "\n")
|
||||
|
||||
rowCount := 0
|
||||
for rows.Next() {
|
||||
vals, err := rows.Slice()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
rowCount++
|
||||
for i, v := range vals {
|
||||
if i > 0 {
|
||||
result.WriteString(" | ")
|
||||
}
|
||||
result.WriteString(fmt.Sprint(v))
|
||||
}
|
||||
result.WriteString("\n")
|
||||
}
|
||||
result.WriteString(fmt.Sprintf("\n(%d rows)", rowCount))
|
||||
return textResult(result.String())
|
||||
|
||||
case "execute":
|
||||
var args struct {
|
||||
SQL string `json:"sql"`
|
||||
}
|
||||
if err := json.Unmarshal(req.Arguments, &args); err != nil {
|
||||
return errorResult(fmt.Sprintf("Invalid arguments: %v", err))
|
||||
}
|
||||
// Debug logging disabled to prevent excessive disk writes
|
||||
res, err := s.conn.WriteOne(args.SQL)
|
||||
if err != nil {
|
||||
return errorResult(fmt.Sprintf("Execution error: %v", err))
|
||||
}
|
||||
return textResult(fmt.Sprintf("Rows affected: %d", res.RowsAffected))
|
||||
|
||||
default:
|
||||
return errorResult(fmt.Sprintf("Unknown tool: %s", req.Name))
|
||||
}
|
||||
}
|
||||
|
||||
func textResult(text string) CallToolResult {
|
||||
return CallToolResult{
|
||||
Content: []TextContent{
|
||||
{
|
||||
Type: "text",
|
||||
Text: text,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func errorResult(text string) CallToolResult {
|
||||
return CallToolResult{
|
||||
Content: []TextContent{
|
||||
{
|
||||
Type: "text",
|
||||
Text: text,
|
||||
},
|
||||
},
|
||||
IsError: true,
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Log to stderr so stdout is clean for JSON-RPC
|
||||
log.SetOutput(os.Stderr)
|
||||
|
||||
rqliteURL := "http://localhost:5001"
|
||||
if u := os.Getenv("RQLITE_URL"); u != "" {
|
||||
rqliteURL = u
|
||||
}
|
||||
|
||||
var server *MCPServer
|
||||
var err error
|
||||
|
||||
// Retry connecting to rqlite
|
||||
maxRetries := 30
|
||||
for i := 0; i < maxRetries; i++ {
|
||||
server, err = NewMCPServer(rqliteURL)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if i%5 == 0 {
|
||||
log.Printf("Waiting for Rqlite at %s... (%d/%d)", rqliteURL, i+1, maxRetries)
|
||||
}
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect to Rqlite after %d retries: %v", maxRetries, err)
|
||||
}
|
||||
|
||||
log.Printf("MCP Rqlite server started (stdio transport)")
|
||||
log.Printf("Connected to Rqlite at %s", rqliteURL)
|
||||
|
||||
// Read JSON-RPC requests from stdin, write responses to stdout
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
var req JSONRPCRequest
|
||||
if err := json.Unmarshal([]byte(line), &req); err != nil {
|
||||
// Debug logging disabled to prevent excessive disk writes
|
||||
continue
|
||||
}
|
||||
|
||||
resp := server.handleRequest(req)
|
||||
|
||||
// Don't send response for notifications (no ID)
|
||||
if req.ID == nil && strings.HasPrefix(req.Method, "notifications/") {
|
||||
continue
|
||||
}
|
||||
|
||||
respData, err := json.Marshal(resp)
|
||||
if err != nil {
|
||||
// Debug logging disabled to prevent excessive disk writes
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Println(string(respData))
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
// Debug logging disabled to prevent excessive disk writes
|
||||
}
|
||||
}
|
||||
8
core/.env.example
Normal file
8
core/.env.example
Normal file
@ -0,0 +1,8 @@
|
||||
# OpenRouter API Key for changelog generation
|
||||
# Get your API key from https://openrouter.ai/keys
|
||||
OPENROUTER_API_KEY=your-api-key-here
|
||||
|
||||
# ZeroSSL API Key for TLS certificates (alternative to Let's Encrypt)
|
||||
# Get your free API key from https://app.zerossl.com/developer
|
||||
# If not set, Caddy will use Let's Encrypt as the default CA
|
||||
ZEROSSL_API_KEY=
|
||||
@ -8,7 +8,7 @@ NOCOLOR='\033[0m'
|
||||
|
||||
# Run tests before push
|
||||
echo -e "\n${CYAN}Running tests...${NOCOLOR}"
|
||||
go test ./... # Runs all tests in your repo
|
||||
cd "$(git rev-parse --show-toplevel)/core" && go test ./...
|
||||
status=$?
|
||||
if [ $status -ne 0 ]; then
|
||||
echo -e "${RED}Push aborted: some tests failed.${NOCOLOR}"
|
||||
181
core/Makefile
Normal file
181
core/Makefile
Normal file
@ -0,0 +1,181 @@
|
||||
TEST?=./...
|
||||
|
||||
.PHONY: test
|
||||
test:
|
||||
@echo Running tests...
|
||||
go test -v $(TEST)
|
||||
|
||||
# Gateway-focused E2E tests assume gateway and nodes are already running
|
||||
# Auto-discovers configuration from ~/.orama and queries database for API key
|
||||
# No environment variables required
|
||||
.PHONY: test-e2e test-e2e-deployments test-e2e-fullstack test-e2e-https test-e2e-quick test-e2e-prod test-e2e-shared test-e2e-cluster test-e2e-integration test-e2e-production
|
||||
|
||||
# Production E2E tests - includes production-only tests
|
||||
test-e2e-prod:
|
||||
@if [ -z "$$ORAMA_GATEWAY_URL" ]; then \
|
||||
echo "❌ ORAMA_GATEWAY_URL not set"; \
|
||||
echo "Usage: ORAMA_GATEWAY_URL=https://dbrs.space make test-e2e-prod"; \
|
||||
exit 1; \
|
||||
fi
|
||||
@echo "Running E2E tests (including production-only) against $$ORAMA_GATEWAY_URL..."
|
||||
go test -v -tags "e2e production" -timeout 30m ./e2e/...
|
||||
|
||||
# Generic e2e target
|
||||
test-e2e:
|
||||
@echo "Running comprehensive E2E tests..."
|
||||
@echo "Auto-discovering configuration from ~/.orama..."
|
||||
go test -v -tags e2e -timeout 30m ./e2e/...
|
||||
|
||||
test-e2e-deployments:
|
||||
@echo "Running deployment E2E tests..."
|
||||
go test -v -tags e2e -timeout 15m ./e2e/deployments/...
|
||||
|
||||
test-e2e-fullstack:
|
||||
@echo "Running fullstack E2E tests..."
|
||||
go test -v -tags e2e -timeout 20m -run "TestFullStack" ./e2e/...
|
||||
|
||||
test-e2e-https:
|
||||
@echo "Running HTTPS/external access E2E tests..."
|
||||
go test -v -tags e2e -timeout 10m -run "TestHTTPS" ./e2e/...
|
||||
|
||||
test-e2e-shared:
|
||||
@echo "Running shared E2E tests..."
|
||||
go test -v -tags e2e -timeout 10m ./e2e/shared/...
|
||||
|
||||
test-e2e-cluster:
|
||||
@echo "Running cluster E2E tests..."
|
||||
go test -v -tags e2e -timeout 15m ./e2e/cluster/...
|
||||
|
||||
test-e2e-integration:
|
||||
@echo "Running integration E2E tests..."
|
||||
go test -v -tags e2e -timeout 20m ./e2e/integration/...
|
||||
|
||||
test-e2e-production:
|
||||
@echo "Running production-only E2E tests..."
|
||||
go test -v -tags "e2e production" -timeout 15m ./e2e/production/...
|
||||
|
||||
test-e2e-quick:
|
||||
@echo "Running quick E2E smoke tests..."
|
||||
go test -v -tags e2e -timeout 5m -run "TestStatic|TestHealth" ./e2e/...
|
||||
|
||||
# Network - Distributed P2P Database System
|
||||
# Makefile for development and build tasks
|
||||
|
||||
.PHONY: build clean test deps tidy fmt vet lint install-hooks push-devnet push-testnet rollout-devnet rollout-testnet release
|
||||
|
||||
VERSION := 0.120.0
|
||||
COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo unknown)
|
||||
DATE ?= $(shell date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
LDFLAGS := -X 'main.version=$(VERSION)' -X 'main.commit=$(COMMIT)' -X 'main.date=$(DATE)'
|
||||
LDFLAGS_LINUX := -s -w $(LDFLAGS)
|
||||
|
||||
# Build targets
|
||||
build: deps
|
||||
@echo "Building network executables (version=$(VERSION))..."
|
||||
@mkdir -p bin
|
||||
go build -ldflags "$(LDFLAGS)" -o bin/identity ./cmd/identity
|
||||
go build -ldflags "$(LDFLAGS)" -o bin/orama-node ./cmd/node
|
||||
go build -ldflags "$(LDFLAGS)" -o bin/orama ./cmd/cli/
|
||||
# Inject gateway build metadata via pkg path variables
|
||||
go build -ldflags "$(LDFLAGS) -X 'github.com/DeBrosOfficial/network/pkg/gateway.BuildVersion=$(VERSION)' -X 'github.com/DeBrosOfficial/network/pkg/gateway.BuildCommit=$(COMMIT)' -X 'github.com/DeBrosOfficial/network/pkg/gateway.BuildTime=$(DATE)'" -o bin/gateway ./cmd/gateway
|
||||
go build -ldflags "$(LDFLAGS)" -o bin/sfu ./cmd/sfu
|
||||
go build -ldflags "$(LDFLAGS)" -o bin/turn ./cmd/turn
|
||||
@echo "Build complete! Run ./bin/orama version"
|
||||
|
||||
# Cross-compile CLI for Linux (only binary needed locally; VPS builds everything else from source)
|
||||
build-linux: deps
|
||||
@echo "Cross-compiling CLI for linux/amd64 (version=$(VERSION))..."
|
||||
@mkdir -p bin-linux
|
||||
GOOS=linux GOARCH=amd64 go build -ldflags "$(LDFLAGS_LINUX)" -trimpath -o bin-linux/orama ./cmd/cli/
|
||||
@echo "✓ CLI built at bin-linux/orama"
|
||||
@echo ""
|
||||
@echo "Prefer 'make build-archive' for full pre-built binary archive."
|
||||
|
||||
# Build pre-compiled binary archive for deployment (all binaries + deps)
|
||||
build-archive: deps
|
||||
@echo "Building binary archive (version=$(VERSION))..."
|
||||
go build -ldflags "$(LDFLAGS)" -o bin/orama ./cmd/cli/
|
||||
./bin/orama build --output /tmp/orama-$(VERSION)-linux-amd64.tar.gz
|
||||
|
||||
# Install git hooks
|
||||
install-hooks:
|
||||
@echo "Installing git hooks..."
|
||||
@bash scripts/install-hooks.sh
|
||||
|
||||
# Install orama CLI to ~/.local/bin and configure PATH
|
||||
install: build
|
||||
@bash scripts/install.sh
|
||||
|
||||
# Clean build artifacts
|
||||
clean:
|
||||
@echo "Cleaning build artifacts..."
|
||||
rm -rf bin/
|
||||
rm -rf data/
|
||||
@echo "Clean complete!"
|
||||
|
||||
# Push binary archive to devnet nodes (fanout distribution)
|
||||
push-devnet:
|
||||
./bin/orama node push --env devnet
|
||||
|
||||
# Push binary archive to testnet nodes (fanout distribution)
|
||||
push-testnet:
|
||||
./bin/orama node push --env testnet
|
||||
|
||||
# Full rollout to devnet (build + push + rolling upgrade)
|
||||
rollout-devnet:
|
||||
./bin/orama node rollout --env devnet --yes
|
||||
|
||||
# Full rollout to testnet (build + push + rolling upgrade)
|
||||
rollout-testnet:
|
||||
./bin/orama node rollout --env testnet --yes
|
||||
|
||||
# Interactive release workflow (tag + push)
|
||||
release:
|
||||
@bash scripts/release.sh
|
||||
|
||||
# Check health of all nodes in an environment
|
||||
# Usage: make health ENV=devnet
|
||||
health:
|
||||
@if [ -z "$(ENV)" ]; then \
|
||||
echo "Usage: make health ENV=devnet|testnet"; \
|
||||
exit 1; \
|
||||
fi
|
||||
./bin/orama monitor report --env $(ENV)
|
||||
|
||||
# Help
|
||||
help:
|
||||
@echo "Available targets:"
|
||||
@echo " build - Build all executables"
|
||||
@echo " install - Build and install 'orama' CLI to ~/.local/bin"
|
||||
@echo " clean - Clean build artifacts"
|
||||
@echo " test - Run unit tests"
|
||||
@echo ""
|
||||
@echo "E2E Testing:"
|
||||
@echo " make test-e2e-prod - Run all E2E tests incl. production-only (needs ORAMA_GATEWAY_URL)"
|
||||
@echo " make test-e2e-shared - Run shared E2E tests (cache, storage, pubsub, auth)"
|
||||
@echo " make test-e2e-cluster - Run cluster E2E tests (libp2p, olric, rqlite, namespace)"
|
||||
@echo " make test-e2e-integration - Run integration E2E tests (fullstack, persistence, concurrency)"
|
||||
@echo " make test-e2e-deployments - Run deployment E2E tests"
|
||||
@echo " make test-e2e-production - Run production-only E2E tests (DNS, HTTPS, cross-node)"
|
||||
@echo " make test-e2e-quick - Quick smoke tests (static deploys, health checks)"
|
||||
@echo " make test-e2e - Generic E2E tests (auto-discovers config)"
|
||||
@echo ""
|
||||
@echo " Example:"
|
||||
@echo " ORAMA_GATEWAY_URL=https://orama-devnet.network make test-e2e-prod"
|
||||
@echo ""
|
||||
@echo "Deployment:"
|
||||
@echo " make build-archive - Build pre-compiled binary archive for deployment"
|
||||
@echo " make push-devnet - Push binary archive to devnet nodes"
|
||||
@echo " make push-testnet - Push binary archive to testnet nodes"
|
||||
@echo " make rollout-devnet - Full rollout: build + push + rolling upgrade (devnet)"
|
||||
@echo " make rollout-testnet - Full rollout: build + push + rolling upgrade (testnet)"
|
||||
@echo " make health ENV=devnet - Check health of all nodes in an environment"
|
||||
@echo " make release - Interactive release workflow (tag + push)"
|
||||
@echo ""
|
||||
@echo "Maintenance:"
|
||||
@echo " deps - Download dependencies"
|
||||
@echo " tidy - Tidy dependencies"
|
||||
@echo " fmt - Format code"
|
||||
@echo " vet - Vet code"
|
||||
@echo " lint - Lint code (fmt + vet)"
|
||||
@echo " help - Show this help"
|
||||
5
core/cmd/cli/main.go
Normal file
5
core/cmd/cli/main.go
Normal file
@ -0,0 +1,5 @@
|
||||
package main
|
||||
|
||||
func main() {
|
||||
runCLI()
|
||||
}
|
||||
103
core/cmd/cli/root.go
Normal file
103
core/cmd/cli/root.go
Normal file
@ -0,0 +1,103 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
// Command groups
|
||||
"github.com/DeBrosOfficial/network/pkg/cli/cmd/app"
|
||||
"github.com/DeBrosOfficial/network/pkg/cli/cmd/authcmd"
|
||||
"github.com/DeBrosOfficial/network/pkg/cli/cmd/buildcmd"
|
||||
"github.com/DeBrosOfficial/network/pkg/cli/cmd/dbcmd"
|
||||
deploycmd "github.com/DeBrosOfficial/network/pkg/cli/cmd/deploy"
|
||||
"github.com/DeBrosOfficial/network/pkg/cli/cmd/envcmd"
|
||||
"github.com/DeBrosOfficial/network/pkg/cli/cmd/functioncmd"
|
||||
"github.com/DeBrosOfficial/network/pkg/cli/cmd/inspectcmd"
|
||||
"github.com/DeBrosOfficial/network/pkg/cli/cmd/monitorcmd"
|
||||
"github.com/DeBrosOfficial/network/pkg/cli/cmd/namespacecmd"
|
||||
"github.com/DeBrosOfficial/network/pkg/cli/cmd/node"
|
||||
"github.com/DeBrosOfficial/network/pkg/cli/cmd/sandboxcmd"
|
||||
)
|
||||
|
||||
// version metadata populated via -ldflags at build time
|
||||
// Must match Makefile: -X 'main.version=...' -X 'main.commit=...' -X 'main.date=...'
|
||||
var (
|
||||
version = "dev"
|
||||
commit = ""
|
||||
date = ""
|
||||
)
|
||||
|
||||
func newRootCmd() *cobra.Command {
|
||||
rootCmd := &cobra.Command{
|
||||
Use: "orama",
|
||||
Short: "Orama CLI - Distributed P2P Network Management Tool",
|
||||
Long: `Orama CLI is a tool for managing nodes, deploying applications,
|
||||
and interacting with the Orama distributed network.`,
|
||||
SilenceUsage: true,
|
||||
SilenceErrors: true,
|
||||
}
|
||||
|
||||
// Version command
|
||||
rootCmd.AddCommand(&cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Show version information",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("orama %s", version)
|
||||
if commit != "" {
|
||||
fmt.Printf(" (commit %s)", commit)
|
||||
}
|
||||
if date != "" {
|
||||
fmt.Printf(" built %s", date)
|
||||
}
|
||||
fmt.Println()
|
||||
},
|
||||
})
|
||||
|
||||
// Node operator commands (was "prod")
|
||||
rootCmd.AddCommand(node.Cmd)
|
||||
|
||||
// Deploy command (top-level, upsert)
|
||||
rootCmd.AddCommand(deploycmd.Cmd)
|
||||
|
||||
// App management (was "deployments")
|
||||
rootCmd.AddCommand(app.Cmd)
|
||||
|
||||
// Database commands
|
||||
rootCmd.AddCommand(dbcmd.Cmd)
|
||||
|
||||
// Namespace commands
|
||||
rootCmd.AddCommand(namespacecmd.Cmd)
|
||||
|
||||
// Environment commands
|
||||
rootCmd.AddCommand(envcmd.Cmd)
|
||||
|
||||
// Auth commands
|
||||
rootCmd.AddCommand(authcmd.Cmd)
|
||||
|
||||
// Inspect command
|
||||
rootCmd.AddCommand(inspectcmd.Cmd)
|
||||
|
||||
// Monitor command
|
||||
rootCmd.AddCommand(monitorcmd.Cmd)
|
||||
|
||||
// Serverless function commands
|
||||
rootCmd.AddCommand(functioncmd.Cmd)
|
||||
|
||||
// Build command (cross-compile binary archive)
|
||||
rootCmd.AddCommand(buildcmd.Cmd)
|
||||
|
||||
// Sandbox command (ephemeral Hetzner Cloud clusters)
|
||||
rootCmd.AddCommand(sandboxcmd.Cmd)
|
||||
|
||||
return rootCmd
|
||||
}
|
||||
|
||||
func runCLI() {
|
||||
rootCmd := newRootCmd()
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@ -14,10 +14,6 @@ import (
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// For transition, alias main.GatewayConfig to pkg/gateway.Config
|
||||
// server.go will be removed; this keeps compatibility until then.
|
||||
type GatewayConfig = gateway.Config
|
||||
|
||||
func getEnvDefault(key, def string) string {
|
||||
if v := os.Getenv(key); strings.TrimSpace(v) != "" {
|
||||
return v
|
||||
@ -73,10 +69,18 @@ func parseGatewayConfig(logger *logging.ColoredLogger) *gateway.Config {
|
||||
}
|
||||
|
||||
// Load YAML
|
||||
type yamlWebRTCCfg struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
SFUPort int `yaml:"sfu_port"`
|
||||
TURNDomain string `yaml:"turn_domain"`
|
||||
TURNSecret string `yaml:"turn_secret"`
|
||||
}
|
||||
|
||||
type yamlCfg struct {
|
||||
ListenAddr string `yaml:"listen_addr"`
|
||||
ClientNamespace string `yaml:"client_namespace"`
|
||||
RQLiteDSN string `yaml:"rqlite_dsn"`
|
||||
GlobalRQLiteDSN string `yaml:"global_rqlite_dsn"`
|
||||
Peers []string `yaml:"bootstrap_peers"`
|
||||
EnableHTTPS bool `yaml:"enable_https"`
|
||||
DomainName string `yaml:"domain_name"`
|
||||
@ -87,6 +91,7 @@ func parseGatewayConfig(logger *logging.ColoredLogger) *gateway.Config {
|
||||
IPFSAPIURL string `yaml:"ipfs_api_url"`
|
||||
IPFSTimeout string `yaml:"ipfs_timeout"`
|
||||
IPFSReplicationFactor int `yaml:"ipfs_replication_factor"`
|
||||
WebRTC yamlWebRTCCfg `yaml:"webrtc"`
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(configPath)
|
||||
@ -95,7 +100,7 @@ func parseGatewayConfig(logger *logging.ColoredLogger) *gateway.Config {
|
||||
zap.String("path", configPath),
|
||||
zap.Error(err))
|
||||
fmt.Fprintf(os.Stderr, "\nConfig file not found at %s\n", configPath)
|
||||
fmt.Fprintf(os.Stderr, "Generate it using: dbn config init --type gateway\n")
|
||||
fmt.Fprintf(os.Stderr, "Generate it using: orama config init --type gateway\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
@ -113,6 +118,7 @@ func parseGatewayConfig(logger *logging.ColoredLogger) *gateway.Config {
|
||||
ClientNamespace: "default",
|
||||
BootstrapPeers: nil,
|
||||
RQLiteDSN: "",
|
||||
GlobalRQLiteDSN: "",
|
||||
EnableHTTPS: false,
|
||||
DomainName: "",
|
||||
TLSCacheDir: "",
|
||||
@ -133,6 +139,9 @@ func parseGatewayConfig(logger *logging.ColoredLogger) *gateway.Config {
|
||||
if v := strings.TrimSpace(y.RQLiteDSN); v != "" {
|
||||
cfg.RQLiteDSN = v
|
||||
}
|
||||
if v := strings.TrimSpace(y.GlobalRQLiteDSN); v != "" {
|
||||
cfg.GlobalRQLiteDSN = v
|
||||
}
|
||||
if len(y.Peers) > 0 {
|
||||
var peers []string
|
||||
for _, p := range y.Peers {
|
||||
@ -191,6 +200,18 @@ func parseGatewayConfig(logger *logging.ColoredLogger) *gateway.Config {
|
||||
cfg.IPFSReplicationFactor = y.IPFSReplicationFactor
|
||||
}
|
||||
|
||||
// WebRTC configuration
|
||||
cfg.WebRTCEnabled = y.WebRTC.Enabled
|
||||
if y.WebRTC.SFUPort > 0 {
|
||||
cfg.SFUPort = y.WebRTC.SFUPort
|
||||
}
|
||||
if v := strings.TrimSpace(y.WebRTC.TURNDomain); v != "" {
|
||||
cfg.TURNDomain = v
|
||||
}
|
||||
if v := strings.TrimSpace(y.WebRTC.TURNSecret); v != "" {
|
||||
cfg.TURNSecret = v
|
||||
}
|
||||
|
||||
// Validate configuration
|
||||
if errs := cfg.ValidateConfig(); len(errs) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "\nGateway configuration errors (%d):\n", len(errs))
|
||||
@ -66,15 +66,25 @@ func main() {
|
||||
|
||||
// Create HTTP server for ACME challenge (port 80)
|
||||
httpServer := &http.Server{
|
||||
Addr: ":80",
|
||||
Handler: manager.HTTPHandler(nil), // Redirects all HTTP traffic to HTTPS except ACME challenge
|
||||
Addr: ":80",
|
||||
Handler: manager.HTTPHandler(nil), // Redirects all HTTP traffic to HTTPS except ACME challenge
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 120 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20, // 1MB
|
||||
}
|
||||
|
||||
// Create HTTPS server (port 443)
|
||||
httpsServer := &http.Server{
|
||||
Addr: ":443",
|
||||
Handler: gw.Routes(),
|
||||
TLSConfig: manager.TLSConfig(),
|
||||
Addr: ":443",
|
||||
Handler: gw.Routes(),
|
||||
TLSConfig: manager.TLSConfig(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 120 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20, // 1MB
|
||||
}
|
||||
|
||||
// Start HTTP server for ACME challenge
|
||||
@ -161,8 +171,13 @@ func main() {
|
||||
|
||||
// Standard HTTP server (no HTTPS)
|
||||
server := &http.Server{
|
||||
Addr: cfg.ListenAddr,
|
||||
Handler: gw.Routes(),
|
||||
Addr: cfg.ListenAddr,
|
||||
Handler: gw.Routes(),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 120 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20, // 1MB
|
||||
}
|
||||
|
||||
// Try to bind listener explicitly so binding failures are visible immediately.
|
||||
11
core/cmd/inspector/main.go
Normal file
11
core/cmd/inspector/main.go
Normal file
@ -0,0 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/DeBrosOfficial/network/pkg/cli"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cli.HandleInspectCommand(os.Args[1:])
|
||||
}
|
||||
118
core/cmd/sfu/config.go
Normal file
118
core/cmd/sfu/config.go
Normal file
@ -0,0 +1,118 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/DeBrosOfficial/network/pkg/config"
|
||||
"github.com/DeBrosOfficial/network/pkg/logging"
|
||||
"github.com/DeBrosOfficial/network/pkg/sfu"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// newSFUServer creates a new SFU server from config and logger.
|
||||
// Wrapper to keep main.go clean and avoid importing sfu in main.
|
||||
func newSFUServer(cfg *sfu.Config, logger *zap.Logger) (*sfu.Server, error) {
|
||||
return sfu.NewServer(cfg, logger)
|
||||
}
|
||||
|
||||
func parseSFUConfig(logger *logging.ColoredLogger) *sfu.Config {
|
||||
configFlag := flag.String("config", "", "Config file path (absolute path or filename in ~/.orama)")
|
||||
flag.Parse()
|
||||
|
||||
var configPath string
|
||||
var err error
|
||||
if *configFlag != "" {
|
||||
if filepath.IsAbs(*configFlag) {
|
||||
configPath = *configFlag
|
||||
} else {
|
||||
configPath, err = config.DefaultPath(*configFlag)
|
||||
if err != nil {
|
||||
logger.ComponentError(logging.ComponentSFU, "Failed to determine config path", zap.Error(err))
|
||||
fmt.Fprintf(os.Stderr, "Configuration error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
configPath, err = config.DefaultPath("sfu.yaml")
|
||||
if err != nil {
|
||||
logger.ComponentError(logging.ComponentSFU, "Failed to determine config path", zap.Error(err))
|
||||
fmt.Fprintf(os.Stderr, "Configuration error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
type yamlTURNServer struct {
|
||||
Host string `yaml:"host"`
|
||||
Port int `yaml:"port"`
|
||||
Secure bool `yaml:"secure"`
|
||||
}
|
||||
|
||||
type yamlCfg struct {
|
||||
ListenAddr string `yaml:"listen_addr"`
|
||||
Namespace string `yaml:"namespace"`
|
||||
MediaPortStart int `yaml:"media_port_start"`
|
||||
MediaPortEnd int `yaml:"media_port_end"`
|
||||
TURNServers []yamlTURNServer `yaml:"turn_servers"`
|
||||
TURNSecret string `yaml:"turn_secret"`
|
||||
TURNCredentialTTL int `yaml:"turn_credential_ttl"`
|
||||
RQLiteDSN string `yaml:"rqlite_dsn"`
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
logger.ComponentError(logging.ComponentSFU, "Config file not found",
|
||||
zap.String("path", configPath), zap.Error(err))
|
||||
fmt.Fprintf(os.Stderr, "\nConfig file not found at %s\n", configPath)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
var y yamlCfg
|
||||
if err := config.DecodeStrict(strings.NewReader(string(data)), &y); err != nil {
|
||||
logger.ComponentError(logging.ComponentSFU, "Failed to parse SFU config", zap.Error(err))
|
||||
fmt.Fprintf(os.Stderr, "Configuration parse error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
var turnServers []sfu.TURNServerConfig
|
||||
for _, ts := range y.TURNServers {
|
||||
turnServers = append(turnServers, sfu.TURNServerConfig{
|
||||
Host: ts.Host,
|
||||
Port: ts.Port,
|
||||
Secure: ts.Secure,
|
||||
})
|
||||
}
|
||||
|
||||
cfg := &sfu.Config{
|
||||
ListenAddr: y.ListenAddr,
|
||||
Namespace: y.Namespace,
|
||||
MediaPortStart: y.MediaPortStart,
|
||||
MediaPortEnd: y.MediaPortEnd,
|
||||
TURNServers: turnServers,
|
||||
TURNSecret: y.TURNSecret,
|
||||
TURNCredentialTTL: y.TURNCredentialTTL,
|
||||
RQLiteDSN: y.RQLiteDSN,
|
||||
}
|
||||
|
||||
if errs := cfg.Validate(); len(errs) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "\nSFU configuration errors (%d):\n", len(errs))
|
||||
for _, e := range errs {
|
||||
fmt.Fprintf(os.Stderr, " - %s\n", e)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "\nPlease fix the configuration and try again.\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
logger.ComponentInfo(logging.ComponentSFU, "Loaded SFU configuration",
|
||||
zap.String("path", configPath),
|
||||
zap.String("listen_addr", cfg.ListenAddr),
|
||||
zap.String("namespace", cfg.Namespace),
|
||||
zap.Int("media_ports", cfg.MediaPortEnd-cfg.MediaPortStart),
|
||||
zap.Int("turn_servers", len(cfg.TURNServers)),
|
||||
)
|
||||
|
||||
return cfg
|
||||
}
|
||||
61
core/cmd/sfu/main.go
Normal file
61
core/cmd/sfu/main.go
Normal file
@ -0,0 +1,61 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/pkg/logging"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
var (
|
||||
version = "dev"
|
||||
commit = "unknown"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger, err := logging.NewColoredLogger(logging.ComponentSFU, true)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
logger.ComponentInfo(logging.ComponentSFU, "Starting SFU server",
|
||||
zap.String("version", version),
|
||||
zap.String("commit", commit))
|
||||
|
||||
cfg := parseSFUConfig(logger)
|
||||
|
||||
server, err := newSFUServer(cfg, logger.Logger)
|
||||
if err != nil {
|
||||
logger.ComponentError(logging.ComponentSFU, "Failed to create SFU server", zap.Error(err))
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Start HTTP server in background
|
||||
go func() {
|
||||
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
logger.ComponentError(logging.ComponentSFU, "SFU server error", zap.Error(err))
|
||||
os.Exit(1)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for termination signal
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
|
||||
sig := <-quit
|
||||
|
||||
logger.ComponentInfo(logging.ComponentSFU, "Shutdown signal received", zap.String("signal", sig.String()))
|
||||
|
||||
// Graceful drain: notify peers and wait
|
||||
server.Drain(30 * time.Second)
|
||||
|
||||
if err := server.Close(); err != nil {
|
||||
logger.ComponentError(logging.ComponentSFU, "Error during shutdown", zap.Error(err))
|
||||
}
|
||||
|
||||
logger.ComponentInfo(logging.ComponentSFU, "SFU server shutdown complete")
|
||||
}
|
||||
100
core/cmd/turn/config.go
Normal file
100
core/cmd/turn/config.go
Normal file
@ -0,0 +1,100 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/DeBrosOfficial/network/pkg/config"
|
||||
"github.com/DeBrosOfficial/network/pkg/logging"
|
||||
"github.com/DeBrosOfficial/network/pkg/turn"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func parseTURNConfig(logger *logging.ColoredLogger) *turn.Config {
|
||||
configFlag := flag.String("config", "", "Config file path (absolute path or filename in ~/.orama)")
|
||||
flag.Parse()
|
||||
|
||||
var configPath string
|
||||
var err error
|
||||
if *configFlag != "" {
|
||||
if filepath.IsAbs(*configFlag) {
|
||||
configPath = *configFlag
|
||||
} else {
|
||||
configPath, err = config.DefaultPath(*configFlag)
|
||||
if err != nil {
|
||||
logger.ComponentError(logging.ComponentTURN, "Failed to determine config path", zap.Error(err))
|
||||
fmt.Fprintf(os.Stderr, "Configuration error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
configPath, err = config.DefaultPath("turn.yaml")
|
||||
if err != nil {
|
||||
logger.ComponentError(logging.ComponentTURN, "Failed to determine config path", zap.Error(err))
|
||||
fmt.Fprintf(os.Stderr, "Configuration error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
type yamlCfg struct {
|
||||
ListenAddr string `yaml:"listen_addr"`
|
||||
TURNSListenAddr string `yaml:"turns_listen_addr"`
|
||||
PublicIP string `yaml:"public_ip"`
|
||||
Realm string `yaml:"realm"`
|
||||
AuthSecret string `yaml:"auth_secret"`
|
||||
RelayPortStart int `yaml:"relay_port_start"`
|
||||
RelayPortEnd int `yaml:"relay_port_end"`
|
||||
Namespace string `yaml:"namespace"`
|
||||
TLSCertPath string `yaml:"tls_cert_path"`
|
||||
TLSKeyPath string `yaml:"tls_key_path"`
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
logger.ComponentError(logging.ComponentTURN, "Config file not found",
|
||||
zap.String("path", configPath), zap.Error(err))
|
||||
fmt.Fprintf(os.Stderr, "\nConfig file not found at %s\n", configPath)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
var y yamlCfg
|
||||
if err := config.DecodeStrict(strings.NewReader(string(data)), &y); err != nil {
|
||||
logger.ComponentError(logging.ComponentTURN, "Failed to parse TURN config", zap.Error(err))
|
||||
fmt.Fprintf(os.Stderr, "Configuration parse error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
cfg := &turn.Config{
|
||||
ListenAddr: y.ListenAddr,
|
||||
TURNSListenAddr: y.TURNSListenAddr,
|
||||
PublicIP: y.PublicIP,
|
||||
Realm: y.Realm,
|
||||
AuthSecret: y.AuthSecret,
|
||||
RelayPortStart: y.RelayPortStart,
|
||||
RelayPortEnd: y.RelayPortEnd,
|
||||
Namespace: y.Namespace,
|
||||
TLSCertPath: y.TLSCertPath,
|
||||
TLSKeyPath: y.TLSKeyPath,
|
||||
}
|
||||
|
||||
if errs := cfg.Validate(); len(errs) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "\nTURN configuration errors (%d):\n", len(errs))
|
||||
for _, e := range errs {
|
||||
fmt.Fprintf(os.Stderr, " - %s\n", e)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "\nPlease fix the configuration and try again.\n")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
logger.ComponentInfo(logging.ComponentTURN, "Loaded TURN configuration",
|
||||
zap.String("path", configPath),
|
||||
zap.String("listen_addr", cfg.ListenAddr),
|
||||
zap.String("namespace", cfg.Namespace),
|
||||
zap.String("realm", cfg.Realm),
|
||||
)
|
||||
|
||||
return cfg
|
||||
}
|
||||
48
core/cmd/turn/main.go
Normal file
48
core/cmd/turn/main.go
Normal file
@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/DeBrosOfficial/network/pkg/logging"
|
||||
"github.com/DeBrosOfficial/network/pkg/turn"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
var (
|
||||
version = "dev"
|
||||
commit = "unknown"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger, err := logging.NewColoredLogger(logging.ComponentTURN, true)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
logger.ComponentInfo(logging.ComponentTURN, "Starting TURN server",
|
||||
zap.String("version", version),
|
||||
zap.String("commit", commit))
|
||||
|
||||
cfg := parseTURNConfig(logger)
|
||||
|
||||
server, err := turn.NewServer(cfg, logger.Logger)
|
||||
if err != nil {
|
||||
logger.ComponentError(logging.ComponentTURN, "Failed to start TURN server", zap.Error(err))
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Wait for termination signal
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
|
||||
sig := <-quit
|
||||
|
||||
logger.ComponentInfo(logging.ComponentTURN, "Shutdown signal received", zap.String("signal", sig.String()))
|
||||
|
||||
if err := server.Close(); err != nil {
|
||||
logger.ComponentError(logging.ComponentTURN, "Error during shutdown", zap.Error(err))
|
||||
}
|
||||
|
||||
logger.ComponentInfo(logging.ComponentTURN, "TURN server shutdown complete")
|
||||
}
|
||||
@ -4,7 +4,7 @@ Section: net
|
||||
Priority: optional
|
||||
Architecture: amd64
|
||||
Depends: libc6
|
||||
Maintainer: DeBros Team <dev@debros.io>
|
||||
Maintainer: DeBros Team <dev@orama.io>
|
||||
Description: Orama Network - Distributed P2P Database System
|
||||
Orama is a distributed peer-to-peer network that combines
|
||||
RQLite for distributed SQL, IPFS for content-addressed storage,
|
||||
@ -52,6 +52,13 @@ The system follows a clean, layered architecture with clear separation of concer
|
||||
│ │ │ │
|
||||
│ Port 9094 │ │ In-Process │
|
||||
└─────────────────┘ └──────────────┘
|
||||
|
||||
┌─────────────────┐
|
||||
│ Anyone │
|
||||
│ (Anonymity) │
|
||||
│ │
|
||||
│ Port 9050 │
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
## Core Components
|
||||
@ -226,7 +233,38 @@ pkg/config/
|
||||
└── gateway.go
|
||||
```
|
||||
|
||||
### 6. Shared Utilities
|
||||
### 6. Anyone Integration (`pkg/anyoneproxy/`)
|
||||
|
||||
Integration with the Anyone Protocol for anonymous routing.
|
||||
|
||||
**Modes:**
|
||||
|
||||
| Mode | Purpose | Port | Rewards |
|
||||
|------|---------|------|---------|
|
||||
| Client | Route traffic anonymously | 9050 (SOCKS5) | No |
|
||||
| Relay | Provide bandwidth to network | 9001 (ORPort) + 9050 | Yes ($ANYONE) |
|
||||
|
||||
**Key Files:**
|
||||
- `pkg/anyoneproxy/socks.go` - SOCKS5 proxy client interface
|
||||
- `pkg/gateway/anon_proxy_handler.go` - Anonymous proxy API endpoint
|
||||
- `pkg/environments/production/installers/anyone_relay.go` - Relay installation
|
||||
|
||||
**Features:**
|
||||
- Smart routing (bypasses proxy for local/private addresses)
|
||||
- Automatic detection of existing Anyone installations
|
||||
- Migration support for existing relay operators
|
||||
- Exit relay mode with legal warnings
|
||||
|
||||
**API Endpoint:**
|
||||
- `POST /v1/proxy/anon` - Route HTTP requests through Anyone network
|
||||
|
||||
**Relay Requirements:**
|
||||
- Linux OS (Debian/Ubuntu)
|
||||
- 100 $ANYONE tokens in wallet
|
||||
- ORPort accessible from internet
|
||||
- Registration at dashboard.anyone.io
|
||||
|
||||
### 7. Shared Utilities
|
||||
|
||||
**HTTP Utilities (`pkg/httputil/`):**
|
||||
- Request parsing and validation
|
||||
@ -315,12 +353,47 @@ Function Invocation:
|
||||
- Refresh token support
|
||||
- Claims-based authorization
|
||||
|
||||
### Network Security (WireGuard Mesh)
|
||||
|
||||
All inter-node communication is encrypted via a WireGuard VPN mesh:
|
||||
|
||||
- **WireGuard IPs:** Each node gets a private IP (10.0.0.x/24) used for all cluster traffic
|
||||
- **UFW Firewall:** Only public ports are exposed: 22 (SSH), 53 (DNS, nameservers only), 80/443 (HTTP/HTTPS), 51820 (WireGuard UDP)
|
||||
- **IPv6 disabled:** System-wide via sysctl to prevent bypass of IPv4 firewall rules
|
||||
- **Internal services** (RQLite 5001/7001, IPFS 4001/4501, Olric 3320/3322, Gateway 6001) are only accessible via WireGuard or localhost
|
||||
- **Invite tokens:** Single-use, time-limited tokens for secure node joining. No shared secrets on the CLI
|
||||
- **Join flow:** New nodes authenticate via HTTPS (443) with TOFU certificate pinning, establish WireGuard tunnel, then join all services over the encrypted mesh
|
||||
|
||||
### Service Authentication
|
||||
|
||||
- **RQLite:** HTTP basic auth on all queries/executions — credentials generated at genesis, distributed via join response
|
||||
- **Olric:** Memberlist gossip encrypted with a shared 32-byte key
|
||||
- **IPFS Cluster:** TrustedPeers restricted to known cluster peer IDs (not `*`)
|
||||
- **Internal endpoints:** `/v1/internal/wg/peers` and `/v1/internal/wg/peer/remove` require cluster secret
|
||||
- **Vault:** V1 push/pull endpoints require session token authentication when guardian is configured
|
||||
- **WebSockets:** Origin header validated against the node's configured domain
|
||||
|
||||
### Token & Key Security
|
||||
|
||||
- **Refresh tokens:** Stored as SHA-256 hashes (never plaintext)
|
||||
- **API keys:** Stored as HMAC-SHA256 hashes with a server-side secret
|
||||
- **TURN secrets:** Encrypted at rest with AES-256-GCM (key derived from cluster secret)
|
||||
- **Binary signing:** Build archives signed with rootwallet EVM signature, verified on install
|
||||
|
||||
### Process Isolation
|
||||
|
||||
- **Dedicated user:** All services run as `orama` user (not root)
|
||||
- **systemd hardening:** `ProtectSystem=strict`, `NoNewPrivileges=yes`, `PrivateDevices=yes`, etc.
|
||||
- **Capabilities:** Caddy and CoreDNS get `CAP_NET_BIND_SERVICE` for privileged ports
|
||||
|
||||
See [SECURITY.md](SECURITY.md) for the full security hardening reference.
|
||||
|
||||
### TLS/HTTPS
|
||||
|
||||
- Automatic ACME (Let's Encrypt) certificate management
|
||||
- Automatic ACME (Let's Encrypt) certificate management via Caddy
|
||||
- TLS 1.3 support
|
||||
- HTTP/2 enabled
|
||||
- Certificate caching
|
||||
- On-demand TLS for deployment custom domains
|
||||
|
||||
### Middleware Stack
|
||||
|
||||
@ -391,11 +464,10 @@ Function Invocation:
|
||||
|
||||
## Deployment
|
||||
|
||||
### Development
|
||||
### Building & Testing
|
||||
|
||||
```bash
|
||||
make dev # Start 5-node cluster
|
||||
make stop # Stop all services
|
||||
make build # Build all binaries
|
||||
make test # Run unit tests
|
||||
make test-e2e # Run E2E tests
|
||||
```
|
||||
@ -403,21 +475,85 @@ make test-e2e # Run E2E tests
|
||||
### Production
|
||||
|
||||
```bash
|
||||
# First node (creates cluster)
|
||||
sudo orama install --vps-ip <IP> --domain node1.example.com
|
||||
# First node (genesis — creates cluster)
|
||||
# Nameserver nodes use the base domain as --domain
|
||||
sudo orama install --vps-ip <IP> --domain example.com --base-domain example.com --nameserver
|
||||
|
||||
# Additional nodes (join cluster)
|
||||
sudo orama install --vps-ip <IP> --domain node2.example.com \
|
||||
--peers /dns4/node1.example.com/tcp/4001/p2p/<PEER_ID> \
|
||||
--join <node1-ip>:7002 \
|
||||
--cluster-secret <secret> \
|
||||
--swarm-key <key>
|
||||
# On the genesis node, generate an invite for a new node
|
||||
orama invite
|
||||
# Outputs: sudo orama install --join https://example.com --token <TOKEN> --vps-ip <NEW_IP>
|
||||
|
||||
# Additional nameserver nodes (join via invite token over HTTPS)
|
||||
sudo orama install --join https://example.com --token <TOKEN> \
|
||||
--vps-ip <IP> --domain example.com --base-domain example.com --nameserver
|
||||
```
|
||||
|
||||
**Security:** Nodes join via single-use invite tokens over HTTPS. A WireGuard VPN tunnel
|
||||
is established before any cluster services start. All inter-node traffic (RQLite, IPFS,
|
||||
Olric, LibP2P) flows over the encrypted WireGuard mesh — no cluster ports are exposed
|
||||
publicly. **Never use `http://<ip>:6001`** for joining — port 6001 is internal-only and
|
||||
blocked by UFW. Use the domain (`https://node1.example.com`) or, if DNS is not yet
|
||||
configured, use the IP over HTTP port 80 (`http://<ip>`) which goes through Caddy.
|
||||
|
||||
### Docker (Future)
|
||||
|
||||
Planned containerization with Docker Compose and Kubernetes support.
|
||||
|
||||
## WebRTC (Voice/Video/Data)
|
||||
|
||||
Namespaces can opt in to WebRTC support for real-time voice, video, and data channels.
|
||||
|
||||
### Components
|
||||
|
||||
- **SFU (Selective Forwarding Unit)** — Pion WebRTC server that handles signaling (WebSocket), SDP negotiation, and RTP forwarding. Runs on all 3 cluster nodes, binds only to WireGuard IPs.
|
||||
- **TURN Server** — Pion TURN relay that provides NAT traversal. Runs on 2 of 3 nodes for redundancy. Public-facing (UDP 3478, 443, relay range 49152-65535).
|
||||
|
||||
### Security Model
|
||||
|
||||
- **TURN-shielded**: SFU binds only to WireGuard (10.0.0.x), never 0.0.0.0. All client media flows through TURN relay.
|
||||
- **Forced relay**: `iceTransportPolicy: relay` enforced server-side — no direct peer connections.
|
||||
- **HMAC credentials**: Per-namespace TURN shared secret with 10-minute TTL.
|
||||
- **Namespace isolation**: Each namespace has its own TURN secret, port ranges, and rooms.
|
||||
|
||||
### Port Allocation
|
||||
|
||||
WebRTC uses a separate port allocation system from core namespace services:
|
||||
|
||||
| Service | Port Range |
|
||||
|---------|-----------|
|
||||
| SFU signaling | 30000-30099 |
|
||||
| SFU media (RTP) | 20000-29999 |
|
||||
| TURN listen | 3478/udp (standard) |
|
||||
| TURN TLS | 443/udp |
|
||||
| TURN relay | 49152-65535/udp |
|
||||
|
||||
See [docs/WEBRTC.md](WEBRTC.md) for full details including client integration, API reference, and debugging.
|
||||
|
||||
## OramaOS
|
||||
|
||||
For mainnet, devnet, and testnet environments, nodes run **OramaOS** — a custom minimal Linux image built with Buildroot.
|
||||
|
||||
**Key properties:**
|
||||
- No SSH, no shell — operators cannot access the filesystem
|
||||
- LUKS full-disk encryption with Shamir key distribution across peers
|
||||
- Read-only rootfs (SquashFS + dm-verity)
|
||||
- A/B partition updates with cryptographic signature verification
|
||||
- Service sandboxing via Linux namespaces + seccomp
|
||||
- Single root process: the **orama-agent**
|
||||
|
||||
**The orama-agent manages:**
|
||||
- Boot sequence and LUKS key reconstruction
|
||||
- WireGuard tunnel setup
|
||||
- Service lifecycle in sandboxed namespaces
|
||||
- Command reception from Gateway over WireGuard (port 9998)
|
||||
- OS updates (download, verify, A/B swap, reboot with rollback)
|
||||
|
||||
**Node enrollment:** OramaOS nodes join via `orama node enroll` instead of `orama node install`. The enrollment flow uses a registration code + invite token + wallet verification.
|
||||
|
||||
See [ORAMAOS_DEPLOYMENT.md](ORAMAOS_DEPLOYMENT.md) for the full deployment guide.
|
||||
|
||||
Sandbox clusters remain on Ubuntu for development convenience.
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
1. **GraphQL Support** - GraphQL gateway alongside REST
|
||||
151
core/docs/CLEAN_NODE.md
Normal file
151
core/docs/CLEAN_NODE.md
Normal file
@ -0,0 +1,151 @@
|
||||
# Clean Node — Full Reset Guide
|
||||
|
||||
How to completely remove all Orama Network state from a VPS so it can be reinstalled fresh.
|
||||
|
||||
> **OramaOS nodes:** This guide applies to Ubuntu-based nodes only. OramaOS has no SSH or shell access. To remove an OramaOS node: use `POST /v1/node/leave` via the Gateway API for graceful departure, or reflash the OramaOS image via your VPS provider's dashboard for a factory reset. See [ORAMAOS_DEPLOYMENT.md](ORAMAOS_DEPLOYMENT.md) for details.
|
||||
|
||||
## Quick Clean (Copy-Paste)
|
||||
|
||||
Run this as root or with sudo on the target VPS:
|
||||
|
||||
```bash
|
||||
# 1. Stop and disable all services
|
||||
sudo systemctl stop orama-node orama-ipfs orama-ipfs-cluster orama-olric orama-anyone-relay orama-anyone-client coredns caddy 2>/dev/null
|
||||
sudo systemctl disable orama-node orama-ipfs orama-ipfs-cluster orama-olric orama-anyone-relay orama-anyone-client coredns caddy 2>/dev/null
|
||||
|
||||
# 1b. Kill leftover processes (binaries may run outside systemd)
|
||||
sudo pkill -f orama-node 2>/dev/null; sudo pkill -f ipfs-cluster-service 2>/dev/null
|
||||
sudo pkill -f "ipfs daemon" 2>/dev/null; sudo pkill -f olric-server 2>/dev/null
|
||||
sudo pkill -f rqlited 2>/dev/null; sudo pkill -f coredns 2>/dev/null
|
||||
sleep 1
|
||||
|
||||
# 2. Remove systemd service files
|
||||
sudo rm -f /etc/systemd/system/orama-*.service
|
||||
sudo rm -f /etc/systemd/system/coredns.service
|
||||
sudo rm -f /etc/systemd/system/caddy.service
|
||||
sudo systemctl daemon-reload
|
||||
|
||||
# 3. Tear down WireGuard
|
||||
# Must stop the systemd unit first — wg-quick@wg0 is a oneshot with
|
||||
# RemainAfterExit=yes, so it stays "active (exited)" even after the
|
||||
# interface is removed. Without "stop", a future "systemctl start" is a no-op.
|
||||
sudo systemctl stop wg-quick@wg0 2>/dev/null
|
||||
sudo wg-quick down wg0 2>/dev/null
|
||||
sudo systemctl disable wg-quick@wg0 2>/dev/null
|
||||
sudo rm -f /etc/wireguard/wg0.conf
|
||||
|
||||
# 4. Reset UFW firewall
|
||||
sudo ufw --force reset
|
||||
sudo ufw allow 22/tcp
|
||||
sudo ufw --force enable
|
||||
|
||||
# 5. Remove orama data directory
|
||||
sudo rm -rf /opt/orama
|
||||
|
||||
# 6. Remove legacy orama user (if exists from old installs)
|
||||
sudo userdel -r orama 2>/dev/null
|
||||
sudo rm -rf /home/orama
|
||||
sudo rm -f /etc/sudoers.d/orama-access
|
||||
sudo rm -f /etc/sudoers.d/orama-deployments
|
||||
sudo rm -f /etc/sudoers.d/orama-wireguard
|
||||
|
||||
# 7. Remove CoreDNS config
|
||||
sudo rm -rf /etc/coredns
|
||||
|
||||
# 8. Remove Caddy config and data
|
||||
sudo rm -rf /etc/caddy
|
||||
sudo rm -rf /var/lib/caddy
|
||||
|
||||
# 9. Remove deployment systemd services (dynamic)
|
||||
sudo rm -f /etc/systemd/system/orama-deploy-*.service
|
||||
sudo systemctl daemon-reload
|
||||
|
||||
# 10. Clean temp files
|
||||
sudo rm -f /tmp/orama /tmp/network-source.tar.gz /tmp/network-source.zip
|
||||
sudo rm -rf /tmp/network-extract /tmp/coredns-build /tmp/caddy-build
|
||||
|
||||
echo "Node cleaned. Ready for fresh install."
|
||||
```
|
||||
|
||||
## What This Removes
|
||||
|
||||
| Category | Paths |
|
||||
|----------|-------|
|
||||
| **App data** | `/opt/orama/.orama/` (configs, secrets, logs, IPFS, RQLite, Olric) |
|
||||
| **Source code** | `/opt/orama/src/` |
|
||||
| **Binaries** | `/opt/orama/bin/orama-node`, `/opt/orama/bin/gateway` |
|
||||
| **Systemd** | `orama-*.service`, `coredns.service`, `caddy.service`, `orama-deploy-*.service` |
|
||||
| **WireGuard** | `/etc/wireguard/wg0.conf`, `wg-quick@wg0` systemd unit |
|
||||
| **Firewall** | All UFW rules (reset to default + SSH only) |
|
||||
| **Legacy** | `orama` user, `/etc/sudoers.d/orama-*` (old installs only) |
|
||||
| **CoreDNS** | `/etc/coredns/Corefile` |
|
||||
| **Caddy** | `/etc/caddy/Caddyfile`, `/var/lib/caddy/` (TLS certs) |
|
||||
| **Anyone Relay** | `orama-anyone-relay.service`, `orama-anyone-client.service` |
|
||||
| **Temp files** | `/tmp/orama`, `/tmp/network-source.*`, build dirs |
|
||||
|
||||
## What This Does NOT Remove
|
||||
|
||||
These are shared system tools that may be used by other software. Remove manually if desired:
|
||||
|
||||
| Binary | Path | Remove Command |
|
||||
|--------|------|----------------|
|
||||
| RQLite | `/usr/local/bin/rqlited` | `sudo rm /usr/local/bin/rqlited` |
|
||||
| IPFS | `/usr/local/bin/ipfs` | `sudo rm /usr/local/bin/ipfs` |
|
||||
| IPFS Cluster | `/usr/local/bin/ipfs-cluster-service` | `sudo rm /usr/local/bin/ipfs-cluster-service` |
|
||||
| Olric | `/usr/local/bin/olric-server` | `sudo rm /usr/local/bin/olric-server` |
|
||||
| CoreDNS | `/usr/local/bin/coredns` | `sudo rm /usr/local/bin/coredns` |
|
||||
| Caddy | `/usr/bin/caddy` | `sudo rm /usr/bin/caddy` |
|
||||
| xcaddy | `/usr/local/bin/xcaddy` | `sudo rm /usr/local/bin/xcaddy` |
|
||||
| Go | `/usr/local/go/` | `sudo rm -rf /usr/local/go` |
|
||||
| Orama CLI | `/usr/local/bin/orama` | `sudo rm /usr/local/bin/orama` |
|
||||
|
||||
## Nuclear Clean (Remove Everything Including Binaries)
|
||||
|
||||
```bash
|
||||
# Run quick clean above first, then:
|
||||
sudo rm -f /usr/local/bin/rqlited
|
||||
sudo rm -f /usr/local/bin/ipfs
|
||||
sudo rm -f /usr/local/bin/ipfs-cluster-service
|
||||
sudo rm -f /usr/local/bin/olric-server
|
||||
sudo rm -f /usr/local/bin/coredns
|
||||
sudo rm -f /usr/local/bin/xcaddy
|
||||
sudo rm -f /usr/bin/caddy
|
||||
sudo rm -f /usr/local/bin/orama
|
||||
```
|
||||
|
||||
## Multi-Node Clean
|
||||
|
||||
To clean all nodes at once from your local machine:
|
||||
|
||||
```bash
|
||||
# Define your nodes
|
||||
NODES=(
|
||||
"ubuntu@141.227.165.168:password1"
|
||||
"ubuntu@141.227.165.154:password2"
|
||||
"ubuntu@141.227.156.51:password3"
|
||||
)
|
||||
|
||||
for entry in "${NODES[@]}"; do
|
||||
IFS=: read -r userhost pass <<< "$entry"
|
||||
echo "Cleaning $userhost..."
|
||||
sshpass -p "$pass" ssh -o StrictHostKeyChecking=no "$userhost" 'bash -s' << 'CLEAN'
|
||||
sudo systemctl stop orama-node orama-ipfs orama-ipfs-cluster orama-olric orama-anyone-relay orama-anyone-client coredns caddy 2>/dev/null
|
||||
sudo systemctl disable orama-node orama-ipfs orama-ipfs-cluster orama-olric orama-anyone-relay orama-anyone-client coredns caddy 2>/dev/null
|
||||
sudo rm -f /etc/systemd/system/orama-*.service /etc/systemd/system/coredns.service /etc/systemd/system/caddy.service /etc/systemd/system/orama-deploy-*.service
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl stop wg-quick@wg0 2>/dev/null
|
||||
sudo wg-quick down wg0 2>/dev/null
|
||||
sudo systemctl disable wg-quick@wg0 2>/dev/null
|
||||
sudo rm -f /etc/wireguard/wg0.conf
|
||||
sudo ufw --force reset && sudo ufw allow 22/tcp && sudo ufw --force enable
|
||||
sudo rm -rf /opt/orama
|
||||
sudo userdel -r orama 2>/dev/null
|
||||
sudo rm -rf /home/orama
|
||||
sudo rm -f /etc/sudoers.d/orama-access /etc/sudoers.d/orama-deployments /etc/sudoers.d/orama-wireguard
|
||||
sudo rm -rf /etc/coredns /etc/caddy /var/lib/caddy
|
||||
sudo rm -f /tmp/orama /tmp/network-source.tar.gz
|
||||
sudo rm -rf /tmp/network-extract /tmp/coredns-build /tmp/caddy-build
|
||||
echo "Done"
|
||||
CLEAN
|
||||
done
|
||||
```
|
||||
217
core/docs/COMMON_PROBLEMS.md
Normal file
217
core/docs/COMMON_PROBLEMS.md
Normal file
@ -0,0 +1,217 @@
|
||||
# Common Problems & Solutions
|
||||
|
||||
Troubleshooting guide for known issues in the Orama Network.
|
||||
|
||||
---
|
||||
|
||||
## 1. Namespace Gateway: "Olric unavailable"
|
||||
|
||||
**Symptom:** `ns-<name>.orama-devnet.network/v1/health` returns `"olric": {"status": "unavailable"}`.
|
||||
|
||||
**Cause:** The Olric memberlist gossip between namespace nodes is broken. Olric uses UDP pings for health checks — if those fail, the cluster can't bootstrap and the gateway reports Olric as unavailable.
|
||||
|
||||
### Check 1: WireGuard packet loss between nodes
|
||||
|
||||
SSH into each node and ping the other namespace nodes over WireGuard:
|
||||
|
||||
```bash
|
||||
ping -c 10 -W 2 10.0.0.X # replace with the WG IP of each peer
|
||||
```
|
||||
|
||||
If you see packet loss over WireGuard but **not** over the public IP (`ping <public-ip>`), the WireGuard peer session is corrupted.
|
||||
|
||||
**Fix — Reset the WireGuard peer on both sides:**
|
||||
|
||||
```bash
|
||||
# On Node A — replace <pubkey> and <endpoint> with Node B's values
|
||||
wg set wg0 peer <NodeB-pubkey> remove
|
||||
wg set wg0 peer <NodeB-pubkey> endpoint <NodeB-public-ip>:51820 allowed-ips <NodeB-wg-ip>/32 persistent-keepalive 25
|
||||
|
||||
# On Node B — same but with Node A's values
|
||||
wg set wg0 peer <NodeA-pubkey> remove
|
||||
wg set wg0 peer <NodeA-pubkey> endpoint <NodeA-public-ip>:51820 allowed-ips <NodeA-wg-ip>/32 persistent-keepalive 25
|
||||
```
|
||||
|
||||
Then restart services: `sudo orama node restart`
|
||||
|
||||
You can find peer public keys with `wg show wg0`.
|
||||
|
||||
### Check 2: Olric bound to 0.0.0.0 instead of WireGuard IP
|
||||
|
||||
Check the Olric config on each node:
|
||||
|
||||
```bash
|
||||
cat /opt/orama/.orama/data/namespaces/<name>/configs/olric-*.yaml
|
||||
```
|
||||
|
||||
If `bindAddr` is `0.0.0.0`, the node will try to bind to IPv6 on dual-stack hosts, breaking memberlist gossip.
|
||||
|
||||
**Fix:** Edit the YAML to use the node's WireGuard IP (run `ip addr show wg0` to find it), then restart: `sudo orama node restart`
|
||||
|
||||
This was fixed in code (BindAddr validation in `SpawnOlric`), so new namespaces won't have this issue.
|
||||
|
||||
### Check 3: Olric logs show "Failed UDP ping" constantly
|
||||
|
||||
```bash
|
||||
journalctl -u orama-namespace-olric@<name>.service --no-pager -n 30
|
||||
```
|
||||
|
||||
If every UDP ping fails but TCP stream connections succeed, it's the WireGuard packet loss issue (see Check 1).
|
||||
|
||||
---
|
||||
|
||||
## 2. Namespace Gateway: Missing config fields
|
||||
|
||||
**Symptom:** Gateway config YAML is missing `global_rqlite_dsn`, has `olric_timeout: 0s`, or `olric_servers` only lists `localhost`.
|
||||
|
||||
**Cause:** Before the spawn handler fix, `spawnGatewayRemote()` didn't send `global_rqlite_dsn` or `olric_timeout` to remote nodes.
|
||||
|
||||
**Fix:** Edit the gateway config manually:
|
||||
|
||||
```bash
|
||||
vim /opt/orama/.orama/data/namespaces/<name>/configs/gateway-*.yaml
|
||||
```
|
||||
|
||||
Add/fix:
|
||||
```yaml
|
||||
global_rqlite_dsn: "http://10.0.0.X:10001"
|
||||
olric_timeout: 30s
|
||||
olric_servers:
|
||||
- "10.0.0.X:10002"
|
||||
- "10.0.0.Y:10002"
|
||||
- "10.0.0.Z:10002"
|
||||
```
|
||||
|
||||
Then: `sudo orama node restart`
|
||||
|
||||
This was fixed in code, so new namespaces get the correct config.
|
||||
|
||||
---
|
||||
|
||||
## 3. Namespace not restoring after restart (missing cluster-state.json)
|
||||
|
||||
**Symptom:** After `orama node restart`, the namespace services don't come back because `RestoreLocalClustersFromDisk` has no state file.
|
||||
|
||||
**Check:**
|
||||
|
||||
```bash
|
||||
ls /opt/orama/.orama/data/namespaces/<name>/cluster-state.json
|
||||
```
|
||||
|
||||
If the file doesn't exist, the node can't restore the namespace.
|
||||
|
||||
**Fix:** Create the file manually from another node that has it, or reconstruct it. The format is:
|
||||
|
||||
```json
|
||||
{
|
||||
"namespace": "<name>",
|
||||
"rqlite": { "http_port": 10001, "raft_port": 10000, ... },
|
||||
"olric": { "http_port": 10002, "memberlist_port": 10003, ... },
|
||||
"gateway": { "http_port": 10004, ... }
|
||||
}
|
||||
```
|
||||
|
||||
This was fixed in code — `ProvisionCluster` now saves state to all nodes (including remote ones via the `save-cluster-state` spawn action).
|
||||
|
||||
---
|
||||
|
||||
## 4. Namespace gateway processes not restarting after upgrade
|
||||
|
||||
**Symptom:** After `orama upgrade --restart` or `orama node restart`, namespace gateway/olric/rqlite services don't start.
|
||||
|
||||
**Cause:** `orama node stop` disables systemd template services (`orama-namespace-gateway@<name>.service`). They have `PartOf=orama-node.service`, but that only propagates restart to **enabled** services.
|
||||
|
||||
**Fix:** Re-enable the services before restarting:
|
||||
|
||||
```bash
|
||||
systemctl enable orama-namespace-rqlite@<name>.service
|
||||
systemctl enable orama-namespace-olric@<name>.service
|
||||
systemctl enable orama-namespace-gateway@<name>.service
|
||||
sudo orama node restart
|
||||
```
|
||||
|
||||
This was fixed in code — the upgrade orchestrator now re-enables `@` services before restarting.
|
||||
|
||||
---
|
||||
|
||||
## 5. SSH commands eating stdin inside heredocs
|
||||
|
||||
**Symptom:** When running a script that SSHes into multiple nodes inside a heredoc (`<<'EOS'`), only the first SSH command runs — the rest are silently skipped.
|
||||
|
||||
**Cause:** `ssh` reads from stdin, consuming the rest of the heredoc.
|
||||
|
||||
**Fix:** Add `-n` flag to all `ssh` calls inside heredocs:
|
||||
|
||||
```bash
|
||||
ssh -n user@host 'command'
|
||||
```
|
||||
|
||||
`scp` is not affected (doesn't read stdin).
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 6. RQLite returns 401 Unauthorized
|
||||
|
||||
**Symptom:** RQLite queries fail with HTTP 401 after security hardening.
|
||||
|
||||
**Cause:** RQLite now requires basic auth. The client isn't sending credentials.
|
||||
|
||||
**Fix:** Ensure the RQLite client is configured with the credentials from `/opt/orama/.orama/secrets/rqlite-auth.json`. The central RQLite client wrapper (`pkg/rqlite/client.go`) handles this automatically. If using a standalone client (e.g., CoreDNS plugin), ensure it's also configured.
|
||||
|
||||
---
|
||||
|
||||
## 7. Olric cluster split after upgrade
|
||||
|
||||
**Symptom:** Olric nodes can't gossip after enabling memberlist encryption.
|
||||
|
||||
**Cause:** Olric memberlist encryption is all-or-nothing. Nodes with encryption can't communicate with nodes without it.
|
||||
|
||||
**Fix:** All nodes must be restarted simultaneously when enabling Olric encryption. The cache will be lost (it rebuilds from DB). This is expected — Olric is a cache, not persistent storage.
|
||||
|
||||
---
|
||||
|
||||
## 8. OramaOS: LUKS unlock fails
|
||||
|
||||
**Symptom:** OramaOS node can't reconstruct its LUKS key after reboot.
|
||||
|
||||
**Cause:** Not enough peer vault-guardians are online to meet the Shamir threshold (K = max(3, N/3)).
|
||||
|
||||
**Fix:** Ensure enough cluster nodes are online and reachable over WireGuard. The agent retries with exponential backoff. For genesis nodes before 5+ peers exist, use:
|
||||
|
||||
```bash
|
||||
orama node unlock --genesis --node-ip <wg-ip>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. OramaOS: Enrollment timeout
|
||||
|
||||
**Symptom:** `orama node enroll` hangs or times out.
|
||||
|
||||
**Cause:** The OramaOS node's port 9999 isn't reachable, or the Gateway can't reach the node's WebSocket.
|
||||
|
||||
**Fix:** Check that port 9999 is open in your VPS provider's external firewall (Hetzner firewall, AWS security groups, etc.). OramaOS opens it internally, but provider-level firewalls must be configured separately.
|
||||
|
||||
---
|
||||
|
||||
## 10. Binary signature verification fails
|
||||
|
||||
**Symptom:** `orama node install` rejects the binary archive with a signature error.
|
||||
|
||||
**Cause:** The archive was tampered with, or the manifest.sig file is missing/corrupted.
|
||||
|
||||
**Fix:** Rebuild the archive with `orama build` and re-sign with `make sign` (in the orama-os repo). Ensure you're using the rootwallet that matches the embedded signer address.
|
||||
|
||||
---
|
||||
|
||||
## General Debugging Tips
|
||||
|
||||
- **Always use `sudo orama node restart`** instead of raw `systemctl` commands
|
||||
- **Namespace data lives at:** `/opt/orama/.orama/data/namespaces/<name>/`
|
||||
- **Check service logs:** `journalctl -u orama-namespace-olric@<name>.service --no-pager -n 50`
|
||||
- **Check WireGuard:** `wg show wg0` — look for recent handshakes and transfer bytes
|
||||
- **Check gateway health:** `curl http://localhost:<port>/v1/health` from the node itself
|
||||
- **Node IPs:** Check `scripts/remote-nodes.conf` for credentials, `wg show wg0` for WG IPs
|
||||
- **OramaOS nodes:** No SSH access — use Gateway API endpoints (`/v1/node/status`, `/v1/node/logs`) for diagnostics
|
||||
1041
core/docs/DEPLOYMENT_GUIDE.md
Normal file
1041
core/docs/DEPLOYMENT_GUIDE.md
Normal file
File diff suppressed because it is too large
Load Diff
152
core/docs/DEVNET_INSTALL.md
Normal file
152
core/docs/DEVNET_INSTALL.md
Normal file
@ -0,0 +1,152 @@
|
||||
# Devnet Installation Commands
|
||||
|
||||
This document contains example installation commands for a multi-node devnet cluster.
|
||||
|
||||
**Wallet:** `<YOUR_WALLET_ADDRESS>`
|
||||
**Contact:** `@anon: <YOUR_WALLET_ADDRESS>`
|
||||
|
||||
## Node Configuration
|
||||
|
||||
| Node | Role | Nameserver | Anyone Relay |
|
||||
|------|------|------------|--------------|
|
||||
| ns1 | Genesis | Yes | No |
|
||||
| ns2 | Nameserver | Yes | Yes (relay-1) |
|
||||
| ns3 | Nameserver | Yes | Yes (relay-2) |
|
||||
| node4 | Worker | No | Yes (relay-3) |
|
||||
| node5 | Worker | No | Yes (relay-4) |
|
||||
| node6 | Worker | No | No |
|
||||
|
||||
**Note:** Store credentials securely (not in version control).
|
||||
|
||||
## MyFamily Fingerprints
|
||||
|
||||
If running multiple Anyone relays, configure MyFamily with all your relay fingerprints:
|
||||
```
|
||||
<FINGERPRINT_1>,<FINGERPRINT_2>,<FINGERPRINT_3>,...
|
||||
```
|
||||
|
||||
## Installation Order
|
||||
|
||||
Install nodes **one at a time**, waiting for each to complete before starting the next:
|
||||
|
||||
1. ns1 (genesis, no Anyone relay)
|
||||
2. ns2 (nameserver + relay)
|
||||
3. ns3 (nameserver + relay)
|
||||
4. node4 (non-nameserver + relay)
|
||||
5. node5 (non-nameserver + relay)
|
||||
6. node6 (non-nameserver, no relay)
|
||||
|
||||
## ns1 - Genesis Node (No Anyone Relay)
|
||||
|
||||
```bash
|
||||
# SSH: <user>@<ns1-ip>
|
||||
|
||||
sudo orama node install \
|
||||
--vps-ip <ns1-ip> \
|
||||
--domain <your-domain.com> \
|
||||
--base-domain <your-domain.com> \
|
||||
--nameserver
|
||||
```
|
||||
|
||||
After ns1 is installed, generate invite tokens:
|
||||
```bash
|
||||
sudo orama node invite --expiry 24h
|
||||
```
|
||||
|
||||
## ns2 - Nameserver + Relay
|
||||
|
||||
```bash
|
||||
# SSH: <user>@<ns2-ip>
|
||||
|
||||
sudo orama node install \
|
||||
--join http://<ns1-ip> --token <TOKEN> \
|
||||
--vps-ip <ns2-ip> \
|
||||
--domain <your-domain.com> \
|
||||
--base-domain <your-domain.com> \
|
||||
--nameserver \
|
||||
--anyone-relay --anyone-migrate \
|
||||
--anyone-nickname <relay-name> \
|
||||
--anyone-wallet <wallet-address> \
|
||||
--anyone-contact "<contact-info>" \
|
||||
--anyone-family "<fingerprint1>,<fingerprint2>,..."
|
||||
```
|
||||
|
||||
## ns3 - Nameserver + Relay
|
||||
|
||||
```bash
|
||||
# SSH: <user>@<ns3-ip>
|
||||
|
||||
sudo orama node install \
|
||||
--join http://<ns1-ip> --token <TOKEN> \
|
||||
--vps-ip <ns3-ip> \
|
||||
--domain <your-domain.com> \
|
||||
--base-domain <your-domain.com> \
|
||||
--nameserver \
|
||||
--anyone-relay --anyone-migrate \
|
||||
--anyone-nickname <relay-name> \
|
||||
--anyone-wallet <wallet-address> \
|
||||
--anyone-contact "<contact-info>" \
|
||||
--anyone-family "<fingerprint1>,<fingerprint2>,..."
|
||||
```
|
||||
|
||||
## node4 - Non-Nameserver + Relay
|
||||
|
||||
Domain is auto-generated (e.g., `node-a3f8k2.<your-domain.com>`). No `--domain` flag needed.
|
||||
|
||||
```bash
|
||||
# SSH: <user>@<node4-ip>
|
||||
|
||||
sudo orama node install \
|
||||
--join http://<ns1-ip> --token <TOKEN> \
|
||||
--vps-ip <node4-ip> \
|
||||
--base-domain <your-domain.com> \
|
||||
--anyone-relay --anyone-migrate \
|
||||
--anyone-nickname <relay-name> \
|
||||
--anyone-wallet <wallet-address> \
|
||||
--anyone-contact "<contact-info>" \
|
||||
--anyone-family "<fingerprint1>,<fingerprint2>,..."
|
||||
```
|
||||
|
||||
## node5 - Non-Nameserver + Relay
|
||||
|
||||
```bash
|
||||
# SSH: <user>@<node5-ip>
|
||||
|
||||
sudo orama node install \
|
||||
--join http://<ns1-ip> --token <TOKEN> \
|
||||
--vps-ip <node5-ip> \
|
||||
--base-domain <your-domain.com> \
|
||||
--anyone-relay --anyone-migrate \
|
||||
--anyone-nickname <relay-name> \
|
||||
--anyone-wallet <wallet-address> \
|
||||
--anyone-contact "<contact-info>" \
|
||||
--anyone-family "<fingerprint1>,<fingerprint2>,..."
|
||||
```
|
||||
|
||||
## node6 - Non-Nameserver (No Anyone Relay)
|
||||
|
||||
```bash
|
||||
# SSH: <user>@<node6-ip>
|
||||
|
||||
sudo orama node install \
|
||||
--join http://<ns1-ip> --token <TOKEN> \
|
||||
--vps-ip <node6-ip> \
|
||||
--base-domain <your-domain.com>
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
After all nodes are installed, verify cluster health:
|
||||
|
||||
```bash
|
||||
# Full cluster report (from local machine)
|
||||
./bin/orama monitor report --env devnet
|
||||
|
||||
# Single node health
|
||||
./bin/orama monitor report --env devnet --node <ip>
|
||||
|
||||
# Or manually from any VPS:
|
||||
curl -s http://localhost:5001/status | jq -r '.store.raft.state, .store.raft.num_peers'
|
||||
curl -s http://localhost:6001/health
|
||||
systemctl status orama-anyone-relay
|
||||
```
|
||||
469
core/docs/DEV_DEPLOY.md
Normal file
469
core/docs/DEV_DEPLOY.md
Normal file
@ -0,0 +1,469 @@
|
||||
# Development Guide
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Go 1.21+
|
||||
- Node.js 18+ (for anyone-client in dev mode)
|
||||
- macOS or Linux
|
||||
|
||||
## Building
|
||||
|
||||
```bash
|
||||
# Build all binaries
|
||||
make build
|
||||
|
||||
# Outputs:
|
||||
# bin/orama-node — the node binary
|
||||
# bin/orama — the CLI
|
||||
# bin/gateway — standalone gateway (optional)
|
||||
# bin/identity — identity tool
|
||||
```
|
||||
|
||||
## Running Tests
|
||||
|
||||
```bash
|
||||
make test
|
||||
```
|
||||
|
||||
## Deploying to VPS
|
||||
|
||||
All binaries are pre-compiled locally and shipped as a binary archive. Zero compilation on the VPS.
|
||||
|
||||
### Deploy Workflow
|
||||
|
||||
```bash
|
||||
# One-command: build + push + rolling upgrade
|
||||
orama node rollout --env testnet
|
||||
|
||||
# Or step by step:
|
||||
|
||||
# 1. Build binary archive (cross-compiles all binaries for linux/amd64)
|
||||
orama build
|
||||
# Creates: /tmp/orama-<version>-linux-amd64.tar.gz
|
||||
|
||||
# 2. Push archive to all nodes (fanout via hub node)
|
||||
orama node push --env testnet
|
||||
|
||||
# 3. Rolling upgrade (one node at a time, followers first, leader last)
|
||||
orama node upgrade --env testnet
|
||||
```
|
||||
|
||||
### Fresh Node Install
|
||||
|
||||
```bash
|
||||
# Build the archive first (if not already built)
|
||||
orama build
|
||||
|
||||
# Install on a new VPS (auto-uploads binary archive, zero compilation)
|
||||
orama node install --vps-ip <ip> --nameserver --domain <domain> --base-domain <domain>
|
||||
```
|
||||
|
||||
The installer auto-detects the binary archive at `/opt/orama/manifest.json` and copies pre-built binaries instead of compiling from source.
|
||||
|
||||
### Upgrading a Multi-Node Cluster (CRITICAL)
|
||||
|
||||
**NEVER restart all nodes simultaneously.** RQLite uses Raft consensus and requires a majority (quorum) to function.
|
||||
|
||||
#### Safe Upgrade Procedure
|
||||
|
||||
```bash
|
||||
# Full rollout (build + push + rolling upgrade, one command)
|
||||
orama node rollout --env testnet
|
||||
|
||||
# Or with more control:
|
||||
orama node push --env testnet # Push archive to all nodes
|
||||
orama node upgrade --env testnet # Rolling upgrade (auto-detects leader)
|
||||
orama node upgrade --env testnet --node 1.2.3.4 # Single node only
|
||||
orama node upgrade --env testnet --delay 60 # 60s between nodes
|
||||
```
|
||||
|
||||
The rolling upgrade automatically:
|
||||
1. Upgrades **follower** nodes first
|
||||
2. Upgrades the **leader** last
|
||||
3. Waits a configurable delay between nodes (default: 30s)
|
||||
|
||||
After each node, verify health:
|
||||
```bash
|
||||
orama monitor report --env testnet
|
||||
```
|
||||
|
||||
#### What NOT to Do
|
||||
|
||||
- **DON'T** stop all nodes, replace binaries, then start all nodes
|
||||
- **DON'T** run `orama node upgrade --restart` on multiple nodes in parallel
|
||||
- **DON'T** clear RQLite data directories unless doing a full cluster rebuild
|
||||
- **DON'T** use `systemctl stop orama-node` on multiple nodes simultaneously
|
||||
|
||||
#### Recovery from Cluster Split
|
||||
|
||||
If nodes get stuck in "Candidate" state or show "leader not found" errors:
|
||||
|
||||
```bash
|
||||
# Recover the Raft cluster (specify the node with highest commit index as leader)
|
||||
orama node recover-raft --env testnet --leader 1.2.3.4
|
||||
```
|
||||
|
||||
This will:
|
||||
1. Stop orama-node on ALL nodes
|
||||
2. Backup + delete raft/ on non-leader nodes
|
||||
3. Start the leader, wait for Leader state
|
||||
4. Start remaining nodes in batches
|
||||
5. Verify cluster health
|
||||
|
||||
### Cleaning Nodes for Reinstallation
|
||||
|
||||
```bash
|
||||
# Wipe all data and services (preserves Anyone relay keys)
|
||||
orama node clean --env testnet --force
|
||||
|
||||
# Also remove shared binaries (rqlited, ipfs, caddy, etc.)
|
||||
orama node clean --env testnet --nuclear --force
|
||||
|
||||
# Single node only
|
||||
orama node clean --env testnet --node 1.2.3.4 --force
|
||||
```
|
||||
|
||||
### Push Options
|
||||
|
||||
```bash
|
||||
orama node push --env devnet # Fanout via hub (default, fastest)
|
||||
orama node push --env testnet --node 1.2.3.4 # Single node
|
||||
orama node push --env testnet --direct # Sequential, no fanout
|
||||
```
|
||||
|
||||
### CLI Flags Reference
|
||||
|
||||
#### `orama node install`
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--vps-ip <ip>` | VPS public IP address (required) |
|
||||
| `--domain <domain>` | Domain for HTTPS certificates. Required for nameserver nodes (use the base domain, e.g., `example.com`). Auto-generated for non-nameserver nodes if omitted (e.g., `node-a3f8k2.example.com`) |
|
||||
| `--base-domain <domain>` | Base domain for deployment routing (e.g., example.com) |
|
||||
| `--nameserver` | Configure this node as a nameserver (CoreDNS + Caddy) |
|
||||
| `--join <url>` | Join existing cluster via HTTPS URL (e.g., `https://node1.example.com`) |
|
||||
| `--token <token>` | Invite token for joining (from `orama node invite` on existing node) |
|
||||
| `--force` | Force reconfiguration even if already installed |
|
||||
| `--skip-firewall` | Skip UFW firewall setup |
|
||||
| `--skip-checks` | Skip minimum resource checks (RAM/CPU) |
|
||||
| `--anyone-relay` | Install and configure an Anyone relay on this node |
|
||||
| `--anyone-migrate` | Migrate existing Anyone relay installation (preserves keys/fingerprint) |
|
||||
| `--anyone-nickname <name>` | Relay nickname (required for relay mode) |
|
||||
| `--anyone-wallet <addr>` | Ethereum wallet for relay rewards (required for relay mode) |
|
||||
| `--anyone-contact <info>` | Contact info for relay (required for relay mode) |
|
||||
| `--anyone-family <fps>` | Comma-separated fingerprints of related relays (MyFamily) |
|
||||
| `--anyone-orport <port>` | ORPort for relay (default: 9001) |
|
||||
| `--anyone-exit` | Configure as an exit relay (default: non-exit) |
|
||||
| `--anyone-bandwidth <pct>` | Limit relay to N% of VPS bandwidth (default: 30, 0=unlimited). Runs a speedtest during install to measure available bandwidth |
|
||||
| `--anyone-accounting <GB>` | Monthly data cap for relay in GB (0=unlimited) |
|
||||
|
||||
#### `orama node invite`
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--expiry <duration>` | Token expiry duration (default: 1h, e.g. `--expiry 24h`) |
|
||||
|
||||
**Important notes about invite tokens:**
|
||||
|
||||
- **Tokens are single-use.** Once a node consumes a token during the join handshake, it cannot be reused. Generate a separate token for each node you want to join.
|
||||
- **Expiry is checked in UTC.** RQLite uses `datetime('now')` which is always UTC. If your local timezone differs, account for the offset when choosing expiry durations.
|
||||
- **Use longer expiry for multi-node deployments.** When deploying multiple nodes, use `--expiry 24h` to avoid tokens expiring mid-deployment.
|
||||
|
||||
#### `orama node upgrade`
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--restart` | Restart all services after upgrade (local mode) |
|
||||
| `--env <env>` | Target environment for remote rolling upgrade |
|
||||
| `--node <ip>` | Upgrade a single node only |
|
||||
| `--delay <seconds>` | Delay between nodes during rolling upgrade (default: 30) |
|
||||
| `--anyone-relay` | Enable Anyone relay (same flags as install) |
|
||||
| `--anyone-bandwidth <pct>` | Limit relay to N% of VPS bandwidth (default: 30, 0=unlimited) |
|
||||
| `--anyone-accounting <GB>` | Monthly data cap for relay in GB (0=unlimited) |
|
||||
|
||||
#### `orama build`
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--arch <arch>` | Target architecture (default: amd64) |
|
||||
| `--output <path>` | Output archive path |
|
||||
| `--verbose` | Verbose build output |
|
||||
|
||||
#### `orama node push`
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--env <env>` | Target environment (required) |
|
||||
| `--node <ip>` | Push to a single node only |
|
||||
| `--direct` | Sequential upload (no hub fanout) |
|
||||
|
||||
#### `orama node rollout`
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--env <env>` | Target environment (required) |
|
||||
| `--no-build` | Skip the build step |
|
||||
| `--yes` | Skip confirmation |
|
||||
| `--delay <seconds>` | Delay between nodes (default: 30) |
|
||||
|
||||
#### `orama node clean`
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--env <env>` | Target environment (required) |
|
||||
| `--node <ip>` | Clean a single node only |
|
||||
| `--nuclear` | Also remove shared binaries |
|
||||
| `--force` | Skip confirmation (DESTRUCTIVE) |
|
||||
|
||||
#### `orama node recover-raft`
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--env <env>` | Target environment (required) |
|
||||
| `--leader <ip>` | Leader node IP — highest commit index (required) |
|
||||
| `--force` | Skip confirmation (DESTRUCTIVE) |
|
||||
|
||||
#### `orama node` (Service Management)
|
||||
|
||||
Use these commands to manage services on production nodes:
|
||||
|
||||
```bash
|
||||
# Stop all services (orama-node, coredns, caddy)
|
||||
sudo orama node stop
|
||||
|
||||
# Start all services
|
||||
sudo orama node start
|
||||
|
||||
# Restart all services
|
||||
sudo orama node restart
|
||||
|
||||
# Check service status
|
||||
sudo orama node status
|
||||
|
||||
# Diagnose common issues
|
||||
sudo orama node doctor
|
||||
```
|
||||
|
||||
**Note:** Always use `orama node stop` instead of manually running `systemctl stop`. The CLI ensures all related services (including CoreDNS and Caddy on nameserver nodes) are handled correctly.
|
||||
|
||||
#### `orama node report`
|
||||
|
||||
Outputs comprehensive health data as JSON. Used by `orama monitor` over SSH:
|
||||
|
||||
```bash
|
||||
sudo orama node report --json
|
||||
```
|
||||
|
||||
See [MONITORING.md](MONITORING.md) for full details.
|
||||
|
||||
#### `orama monitor`
|
||||
|
||||
Real-time cluster monitoring from your local machine:
|
||||
|
||||
```bash
|
||||
# Interactive TUI
|
||||
orama monitor --env testnet
|
||||
|
||||
# Cluster overview
|
||||
orama monitor cluster --env testnet
|
||||
|
||||
# Alerts only
|
||||
orama monitor alerts --env testnet
|
||||
|
||||
# Full JSON for LLM analysis
|
||||
orama monitor report --env testnet
|
||||
```
|
||||
|
||||
See [MONITORING.md](MONITORING.md) for all subcommands and flags.
|
||||
|
||||
### Node Join Flow
|
||||
|
||||
```bash
|
||||
# 1. Genesis node (first node, creates cluster)
|
||||
# Nameserver nodes use the base domain as --domain
|
||||
sudo orama node install --vps-ip 1.2.3.4 --domain example.com \
|
||||
--base-domain example.com --nameserver
|
||||
|
||||
# 2. On genesis node, generate an invite
|
||||
orama node invite --expiry 24h
|
||||
# Output: sudo orama node install --join https://example.com --token <TOKEN> --vps-ip <IP>
|
||||
|
||||
# 3a. Join as nameserver (requires --domain set to base domain)
|
||||
sudo orama node install --join http://1.2.3.4 --token abc123... \
|
||||
--vps-ip 5.6.7.8 --domain example.com --base-domain example.com --nameserver
|
||||
|
||||
# 3b. Join as regular node (domain auto-generated, no --domain needed)
|
||||
sudo orama node install --join http://1.2.3.4 --token abc123... \
|
||||
--vps-ip 5.6.7.8 --base-domain example.com
|
||||
```
|
||||
|
||||
The join flow establishes a WireGuard VPN tunnel before starting cluster services.
|
||||
All inter-node communication (RQLite, IPFS, Olric) uses WireGuard IPs (10.0.0.x).
|
||||
No cluster ports are ever exposed publicly.
|
||||
|
||||
#### DNS Prerequisite
|
||||
|
||||
The `--join` URL should use the HTTPS domain of the genesis node (e.g., `https://node1.example.com`).
|
||||
For this to work, the domain registrar for `example.com` must have NS records pointing to the genesis
|
||||
node's IP so that `node1.example.com` resolves publicly.
|
||||
|
||||
**If DNS is not yet configured**, you can use the genesis node's public IP with HTTP as a fallback:
|
||||
|
||||
```bash
|
||||
sudo orama node install --join http://1.2.3.4 --vps-ip 5.6.7.8 --token abc123... --nameserver
|
||||
```
|
||||
|
||||
This works because Caddy's `:80` block proxies all HTTP traffic to the gateway. However, once DNS
|
||||
is properly configured, always use the HTTPS domain URL.
|
||||
|
||||
**Important:** Never use `http://<ip>:6001` — port 6001 is the internal gateway and is blocked by
|
||||
UFW from external access. The join request goes through Caddy on port 80 (HTTP) or 443 (HTTPS),
|
||||
which proxies to the gateway internally.
|
||||
|
||||
## OramaOS Enrollment
|
||||
|
||||
For OramaOS nodes (mainnet, devnet, testnet), use the enrollment flow instead of `orama node install`:
|
||||
|
||||
```bash
|
||||
# 1. Flash OramaOS image to VPS (via provider dashboard)
|
||||
# 2. Generate invite token on existing cluster node
|
||||
orama node invite --expiry 24h
|
||||
|
||||
# 3. Enroll the OramaOS node
|
||||
orama node enroll --node-ip <vps-public-ip> --token <invite-token> --gateway <gateway-url>
|
||||
|
||||
# 4. For genesis node reboots (before 5+ peers exist)
|
||||
orama node unlock --genesis --node-ip <wg-ip>
|
||||
```
|
||||
|
||||
OramaOS nodes have no SSH access. All management happens through the Gateway API:
|
||||
|
||||
```bash
|
||||
# Status, logs, commands — all via Gateway proxy
|
||||
curl "https://gateway.example.com/v1/node/status?node_id=<id>"
|
||||
curl "https://gateway.example.com/v1/node/logs?node_id=<id>&service=gateway"
|
||||
```
|
||||
|
||||
See [ORAMAOS_DEPLOYMENT.md](ORAMAOS_DEPLOYMENT.md) for the full guide.
|
||||
|
||||
**Note:** `orama node clean` does not work on OramaOS nodes (no SSH). Use `orama node leave` for graceful departure, or reflash the image for a factory reset.
|
||||
|
||||
## Pre-Install Checklist (Ubuntu Only)
|
||||
|
||||
Before running `orama node install` on a VPS, ensure:
|
||||
|
||||
1. **Stop Docker if running.** Docker commonly binds ports 4001 and 8080 which conflict with IPFS. The installer checks for port conflicts and shows which process is using each port, but it's easier to stop Docker first:
|
||||
```bash
|
||||
sudo systemctl stop docker docker.socket
|
||||
sudo systemctl disable docker docker.socket
|
||||
```
|
||||
|
||||
2. **Stop any existing IPFS instance.**
|
||||
```bash
|
||||
sudo systemctl stop ipfs
|
||||
```
|
||||
|
||||
3. **Stop any service on port 53** (for nameserver nodes). The installer handles `systemd-resolved` automatically, but other DNS services (like `bind9` or `dnsmasq`) must be stopped manually.
|
||||
|
||||
## Recovering from Failed Joins
|
||||
|
||||
If a node partially joins the cluster (registers in RQLite's Raft but then fails or gets cleaned), the remaining cluster can lose quorum permanently. This happens because RQLite thinks there are N voters but only N-1 are reachable.
|
||||
|
||||
**Symptoms:** RQLite stuck in "Candidate" state, no leader elected, all writes fail.
|
||||
|
||||
**Solution:** Do a full clean reinstall of all affected nodes. Use [CLEAN_NODE.md](CLEAN_NODE.md) to reset each node, then reinstall starting from the genesis node.
|
||||
|
||||
**Prevention:** Always ensure a joining node can complete the full installation before it joins. The installer validates port availability upfront to catch conflicts early.
|
||||
|
||||
## Debugging Production Issues
|
||||
|
||||
Always follow the local-first approach:
|
||||
|
||||
1. **Reproduce locally** — set up the same conditions on your machine
|
||||
2. **Find the root cause** — understand why it's happening
|
||||
3. **Fix in the codebase** — make changes to the source code
|
||||
4. **Test locally** — run `make test` and verify
|
||||
5. **Deploy** — only then deploy the fix to production
|
||||
|
||||
Never fix issues directly on the server — those fixes are lost on next deployment.
|
||||
|
||||
## Trusting the Self-Signed TLS Certificate
|
||||
|
||||
When Let's Encrypt is rate-limited, Caddy falls back to its internal CA (self-signed certificates). Browsers will show security warnings unless you install the root CA certificate.
|
||||
|
||||
### Downloading the Root CA Certificate
|
||||
|
||||
From VPS 1 (or any node), copy the certificate:
|
||||
|
||||
```bash
|
||||
# Copy the cert to an accessible location on the VPS
|
||||
ssh ubuntu@<VPS_IP> "sudo cp /var/lib/caddy/.local/share/caddy/pki/authorities/local/root.crt /tmp/caddy-root-ca.crt && sudo chmod 644 /tmp/caddy-root-ca.crt"
|
||||
|
||||
# Download to your local machine
|
||||
scp ubuntu@<VPS_IP>:/tmp/caddy-root-ca.crt ~/Downloads/caddy-root-ca.crt
|
||||
```
|
||||
|
||||
### macOS
|
||||
|
||||
```bash
|
||||
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ~/Downloads/caddy-root-ca.crt
|
||||
```
|
||||
|
||||
This adds the cert system-wide. All browsers (Safari, Chrome, Arc, etc.) will trust it immediately. Firefox uses its own certificate store — go to **Settings > Privacy & Security > Certificates > View Certificates > Import** and import the `.crt` file there.
|
||||
|
||||
To remove it later:
|
||||
```bash
|
||||
sudo security remove-trusted-cert -d ~/Downloads/caddy-root-ca.crt
|
||||
```
|
||||
|
||||
### iOS (iPhone/iPad)
|
||||
|
||||
1. Transfer `caddy-root-ca.crt` to your device (AirDrop, email attachment, or host it on a URL)
|
||||
2. Open the file — iOS will show "Profile Downloaded"
|
||||
3. Go to **Settings > General > VPN & Device Management** (or "Profiles" on older iOS)
|
||||
4. Tap the "Caddy Local Authority" profile and tap **Install**
|
||||
5. Go to **Settings > General > About > Certificate Trust Settings**
|
||||
6. Enable **full trust** for "Caddy Local Authority - 2026 ECC Root"
|
||||
|
||||
### Android
|
||||
|
||||
1. Transfer `caddy-root-ca.crt` to your device
|
||||
2. Go to **Settings > Security > Encryption & Credentials > Install a certificate > CA certificate**
|
||||
3. Select the `caddy-root-ca.crt` file
|
||||
4. Confirm the installation
|
||||
|
||||
Note: On Android 7+, user-installed CA certificates are only trusted by apps that explicitly opt in. Chrome will trust it, but some apps may not.
|
||||
|
||||
### Windows
|
||||
|
||||
```powershell
|
||||
certutil -addstore -f "ROOT" caddy-root-ca.crt
|
||||
```
|
||||
|
||||
Or double-click the `.crt` file > **Install Certificate** > **Local Machine** > **Place in "Trusted Root Certification Authorities"**.
|
||||
|
||||
### Linux
|
||||
|
||||
```bash
|
||||
sudo cp caddy-root-ca.crt /usr/local/share/ca-certificates/caddy-root-ca.crt
|
||||
sudo update-ca-certificates
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
See [ARCHITECTURE.md](ARCHITECTURE.md) for the full architecture overview.
|
||||
|
||||
Key directories:
|
||||
|
||||
```
|
||||
cmd/
|
||||
cli/ — CLI entry point (orama command)
|
||||
node/ — Node entry point (orama-node)
|
||||
gateway/ — Standalone gateway entry point
|
||||
pkg/
|
||||
cli/ — CLI command implementations
|
||||
gateway/ — HTTP gateway, routes, middleware
|
||||
deployments/ — Deployment types, service, storage
|
||||
environments/ — Production (systemd) and development (direct) modes
|
||||
rqlite/ — Distributed SQLite via RQLite
|
||||
```
|
||||
213
core/docs/INSPECTOR.md
Normal file
213
core/docs/INSPECTOR.md
Normal file
@ -0,0 +1,213 @@
|
||||
# Inspector
|
||||
|
||||
The inspector is a cluster health check tool that SSHs into every node, collects subsystem data in parallel, runs deterministic checks, and optionally sends failures to an AI model for root-cause analysis.
|
||||
|
||||
## Pipeline
|
||||
|
||||
```
|
||||
Collect (parallel SSH) → Check (deterministic Go) → Report (table/JSON) → Analyze (optional AI)
|
||||
```
|
||||
|
||||
1. **Collect** — SSH into every node in parallel, run diagnostic commands, parse results into structured data.
|
||||
2. **Check** — Run pure Go check functions against the collected data. Each check produces a pass/fail/warn/skip result with a severity level.
|
||||
3. **Report** — Print results as a table (default) or JSON. Failures sort first, grouped by subsystem.
|
||||
4. **Analyze** — If `--ai` is enabled and there are failures or warnings, send them to an LLM via OpenRouter for root-cause analysis.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Inspect all subsystems on devnet
|
||||
orama inspect --env devnet
|
||||
|
||||
# Inspect only RQLite
|
||||
orama inspect --env devnet --subsystem rqlite
|
||||
|
||||
# JSON output
|
||||
orama inspect --env devnet --format json
|
||||
|
||||
# With AI analysis
|
||||
orama inspect --env devnet --ai
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
orama inspect [flags]
|
||||
```
|
||||
|
||||
| Flag | Default | Description |
|
||||
|------|---------|-------------|
|
||||
| `--config` | `scripts/remote-nodes.conf` | Path to node configuration file |
|
||||
| `--env` | *(required)* | Environment to inspect (`devnet`, `testnet`) |
|
||||
| `--subsystem` | `all` | Comma-separated subsystems to inspect |
|
||||
| `--format` | `table` | Output format: `table` or `json` |
|
||||
| `--timeout` | `30s` | SSH command timeout per node |
|
||||
| `--verbose` | `false` | Print collection progress |
|
||||
| `--ai` | `false` | Enable AI analysis of failures |
|
||||
| `--model` | `moonshotai/kimi-k2.5` | OpenRouter model for AI analysis |
|
||||
| `--api-key` | `$OPENROUTER_API_KEY` | OpenRouter API key |
|
||||
|
||||
### Subsystem Names
|
||||
|
||||
`rqlite`, `olric`, `ipfs`, `dns`, `wireguard` (alias: `wg`), `system`, `network`, `namespace`
|
||||
|
||||
Multiple subsystems can be combined: `--subsystem rqlite,olric,dns`
|
||||
|
||||
## Subsystems
|
||||
|
||||
| Subsystem | What It Checks |
|
||||
|-----------|---------------|
|
||||
| **rqlite** | Raft state, leader election, readyz, commit/applied gap, FSM pending, strong reads, debug vars (query errors, leader_not_found, snapshots), cross-node leader agreement, term consistency, applied index convergence, quorum, version match |
|
||||
| **olric** | Service active, memberlist up, restart count, memory usage, log analysis (suspects, flapping, errors), cross-node memberlist consistency |
|
||||
| **ipfs** | Daemon active, cluster active, swarm peer count, cluster peer count, cluster errors, repo usage %, swarm key present, bootstrap list empty, cross-node version consistency |
|
||||
| **dns** | CoreDNS active, Caddy active, ports (53/80/443), memory, restart count, log errors, Corefile exists, SOA/NS/wildcard/base-A resolution, TLS cert expiry, cross-node nameserver availability |
|
||||
| **wireguard** | Interface up, service active, correct 10.0.0.x IP, listen port 51820, peer count vs expected, MTU 1420, config exists + permissions 600, peer handshakes (fresh/stale/never), peer traffic, catch-all route detection, cross-node peer count + MTU consistency |
|
||||
| **system** | Core services (orama-node, rqlite, olric, ipfs, ipfs-cluster, wg-quick), nameserver services (coredns, caddy), failed systemd units, memory/disk/inode usage, load average, OOM kills, swap, UFW active, process user (orama), panic count, expected ports |
|
||||
| **network** | Internet reachability, default route, WireGuard route, TCP connection count, TIME_WAIT count, TCP retransmission rate, WireGuard mesh ping (all peers) |
|
||||
| **namespace** | Per-namespace: RQLite up + raft state + readyz, Olric memberlist, Gateway HTTP health. Cross-namespace: all-healthy check, RQLite quorum per namespace |
|
||||
|
||||
## Severity Levels
|
||||
|
||||
| Level | When Used |
|
||||
|-------|-----------|
|
||||
| **CRITICAL** | Service completely down. Raft quorum lost, RQLite unresponsive, no leader. |
|
||||
| **HIGH** | Service degraded. Olric down, gateway not responding, IPFS swarm key missing. |
|
||||
| **MEDIUM** | Non-ideal but functional. Stale handshakes, elevated memory, log suspects. |
|
||||
| **LOW** | Informational. Non-standard MTU, port mismatch, version skew. |
|
||||
|
||||
## Check Statuses
|
||||
|
||||
| Status | Meaning |
|
||||
|--------|---------|
|
||||
| **pass** | Check passed. |
|
||||
| **fail** | Check failed — action needed. |
|
||||
| **warn** | Degraded — monitor or investigate. |
|
||||
| **skip** | Check could not run (insufficient data). |
|
||||
|
||||
## Output Formats
|
||||
|
||||
### Table (default)
|
||||
|
||||
```
|
||||
Inspecting 14 devnet nodes...
|
||||
|
||||
## RQLITE
|
||||
----------------------------------------------------------------------
|
||||
OK [CRITICAL] RQLite responding (ubuntu@10.0.0.1)
|
||||
responsive=true version=v8.36.16
|
||||
FAIL [CRITICAL] Cluster has exactly one leader
|
||||
leaders=0 (NO LEADER)
|
||||
...
|
||||
|
||||
======================================================================
|
||||
Summary: 800 passed, 12 failed, 31 warnings, 0 skipped (4.2s)
|
||||
```
|
||||
|
||||
Failures sort first, then warnings, then passes. Within each group, higher severity checks appear first.
|
||||
|
||||
### JSON (`--format json`)
|
||||
|
||||
```json
|
||||
{
|
||||
"summary": {
|
||||
"passed": 800,
|
||||
"failed": 12,
|
||||
"warned": 31,
|
||||
"skipped": 0,
|
||||
"total": 843,
|
||||
"duration_seconds": 4.2
|
||||
},
|
||||
"checks": [
|
||||
{
|
||||
"id": "rqlite.responsive",
|
||||
"name": "RQLite responding",
|
||||
"subsystem": "rqlite",
|
||||
"severity": 3,
|
||||
"status": "pass",
|
||||
"message": "responsive=true version=v8.36.16",
|
||||
"node": "ubuntu@10.0.0.1"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## AI Analysis
|
||||
|
||||
When `--ai` is enabled, failures and warnings are sent to an LLM via OpenRouter for root-cause analysis.
|
||||
|
||||
```bash
|
||||
# Use default model (kimi-k2.5)
|
||||
orama inspect --env devnet --ai
|
||||
|
||||
# Use a different model
|
||||
orama inspect --env devnet --ai --model openai/gpt-4o
|
||||
|
||||
# Pass API key directly
|
||||
orama inspect --env devnet --ai --api-key sk-or-...
|
||||
```
|
||||
|
||||
The API key can be set via:
|
||||
1. `--api-key` flag
|
||||
2. `OPENROUTER_API_KEY` environment variable
|
||||
3. `.env` file in the current directory
|
||||
|
||||
The AI receives the full check results plus cluster metadata and returns a structured analysis with likely root causes and suggested fixes.
|
||||
|
||||
## Exit Codes
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| `0` | All checks passed (or only warnings). |
|
||||
| `1` | At least one check failed. |
|
||||
|
||||
## Configuration
|
||||
|
||||
The inspector reads node definitions from a pipe-delimited config file (default: `scripts/remote-nodes.conf`).
|
||||
|
||||
### Format
|
||||
|
||||
```
|
||||
# environment|user@host|role
|
||||
devnet|ubuntu@1.2.3.4|node
|
||||
devnet|ubuntu@5.6.7.8|nameserver-ns1
|
||||
```
|
||||
|
||||
| Field | Description |
|
||||
|-------|-------------|
|
||||
| `environment` | Cluster name (`devnet`, `testnet`) |
|
||||
| `user@host` | SSH credentials |
|
||||
| `role` | `node` or `nameserver-ns1`, `nameserver-ns2`, etc. |
|
||||
|
||||
SSH keys are resolved from rootwallet (`rw vault ssh get <host>/<user> --priv`).
|
||||
|
||||
Blank lines and lines starting with `#` are ignored.
|
||||
|
||||
### Node Roles
|
||||
|
||||
- **`node`** — Regular cluster node. Runs RQLite, Olric, IPFS, WireGuard, namespaces.
|
||||
- **`nameserver-*`** — DNS nameserver. Runs CoreDNS + Caddy in addition to base services. System checks verify nameserver-specific services.
|
||||
|
||||
## Examples
|
||||
|
||||
```bash
|
||||
# Full cluster inspection
|
||||
orama inspect --env devnet
|
||||
|
||||
# Check only networking
|
||||
orama inspect --env devnet --subsystem wireguard,network
|
||||
|
||||
# Quick RQLite health check
|
||||
orama inspect --env devnet --subsystem rqlite
|
||||
|
||||
# Verbose mode (shows collection progress)
|
||||
orama inspect --env devnet --verbose
|
||||
|
||||
# JSON for scripting / piping
|
||||
orama inspect --env devnet --format json | jq '.checks[] | select(.status == "fail")'
|
||||
|
||||
# AI-assisted debugging
|
||||
orama inspect --env devnet --ai --model anthropic/claude-sonnet-4
|
||||
|
||||
# Custom config file
|
||||
orama inspect --config /path/to/nodes.conf --env testnet
|
||||
```
|
||||
278
core/docs/MONITORING.md
Normal file
278
core/docs/MONITORING.md
Normal file
@ -0,0 +1,278 @@
|
||||
# Monitoring
|
||||
|
||||
Real-time cluster health monitoring via SSH. The system has two parts:
|
||||
|
||||
1. **`orama node report`** — Runs on each VPS node, collects all local health data, outputs JSON
|
||||
2. **`orama monitor`** — Runs on your local machine, SSHes into nodes, aggregates results, displays via TUI or tables
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Developer Machine VPS Nodes (via SSH)
|
||||
┌──────────────────┐ ┌────────────────────┐
|
||||
│ orama monitor │ ──SSH──────────>│ orama node report │
|
||||
│ (TUI / tables) │ <──JSON─────── │ (local collector) │
|
||||
│ │ └────────────────────┘
|
||||
│ CollectOnce() │ ──SSH──────────>│ orama node report │
|
||||
│ DeriveAlerts() │ <──JSON─────── │ (local collector) │
|
||||
│ Render() │ └────────────────────┘
|
||||
└──────────────────┘
|
||||
```
|
||||
|
||||
Each node runs `orama node report --json` locally (no SSH to other nodes), collecting data via `os/exec` and `net/http` to localhost services. The monitor SSHes into all nodes in parallel, collects reports, then runs cross-node analysis to detect cluster-wide issues.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Interactive TUI (auto-refreshes every 30s)
|
||||
orama monitor --env testnet
|
||||
|
||||
# Cluster overview table
|
||||
orama monitor cluster --env testnet
|
||||
|
||||
# Alerts only
|
||||
orama monitor alerts --env testnet
|
||||
|
||||
# Full JSON report (pipe to jq or feed to LLM)
|
||||
orama monitor report --env testnet
|
||||
```
|
||||
|
||||
## `orama monitor` — Local Orchestrator
|
||||
|
||||
### Usage
|
||||
|
||||
```
|
||||
orama monitor [subcommand] --env <environment> [flags]
|
||||
```
|
||||
|
||||
Without a subcommand, launches the interactive TUI.
|
||||
|
||||
### Global Flags
|
||||
|
||||
| Flag | Default | Description |
|
||||
|------|---------|-------------|
|
||||
| `--env` | *(required)* | Environment: `devnet`, `testnet`, `mainnet` |
|
||||
| `--json` | `false` | Machine-readable JSON output (for one-shot subcommands) |
|
||||
| `--node` | | Filter to a specific node host/IP |
|
||||
| `--config` | `scripts/remote-nodes.conf` | Path to node configuration file |
|
||||
|
||||
### Subcommands
|
||||
|
||||
| Subcommand | Description |
|
||||
|------------|-------------|
|
||||
| `live` | Interactive TUI monitor (default when no subcommand) |
|
||||
| `cluster` | Cluster overview: all nodes, roles, RQLite state, WG peers |
|
||||
| `node` | Per-node health details (system, services, WG, DNS) |
|
||||
| `service` | Service status matrix across all nodes |
|
||||
| `mesh` | WireGuard mesh connectivity and peer details |
|
||||
| `dns` | DNS health: CoreDNS, Caddy, TLS cert expiry, resolution |
|
||||
| `namespaces` | Namespace health across nodes |
|
||||
| `alerts` | Active alerts and warnings sorted by severity |
|
||||
| `report` | Full JSON dump optimized for LLM consumption |
|
||||
|
||||
### Examples
|
||||
|
||||
```bash
|
||||
# Cluster overview
|
||||
orama monitor cluster --env testnet
|
||||
|
||||
# Cluster overview as JSON
|
||||
orama monitor cluster --env testnet --json
|
||||
|
||||
# Alerts for all nodes
|
||||
orama monitor alerts --env testnet
|
||||
|
||||
# Single-node deep dive
|
||||
orama monitor node --env testnet --node 51.195.109.238
|
||||
|
||||
# Services for one node
|
||||
orama monitor service --env testnet --node 51.195.109.238
|
||||
|
||||
# WireGuard mesh details
|
||||
orama monitor mesh --env testnet
|
||||
|
||||
# DNS health
|
||||
orama monitor dns --env testnet
|
||||
|
||||
# Namespace health
|
||||
orama monitor namespaces --env testnet
|
||||
|
||||
# Full report for LLM analysis
|
||||
orama monitor report --env testnet | jq .
|
||||
|
||||
# Single-node report
|
||||
orama monitor report --env testnet --node 51.195.109.238
|
||||
|
||||
# Custom config file
|
||||
orama monitor cluster --config /path/to/nodes.conf --env devnet
|
||||
```
|
||||
|
||||
### Interactive TUI
|
||||
|
||||
The `live` subcommand (default) launches a full-screen terminal UI:
|
||||
|
||||
**Tabs:** Overview | Nodes | Services | WG Mesh | DNS | Namespaces | Alerts
|
||||
|
||||
**Key Bindings:**
|
||||
|
||||
| Key | Action |
|
||||
|-----|--------|
|
||||
| `Tab` / `Shift+Tab` | Switch tabs |
|
||||
| `j` / `k` or `↑` / `↓` | Scroll content |
|
||||
| `r` | Force refresh |
|
||||
| `q` / `Ctrl+C` | Quit |
|
||||
|
||||
The TUI auto-refreshes every 30 seconds. A spinner shows during data collection. Colors indicate health: green = healthy, red = critical, yellow = warning.
|
||||
|
||||
### LLM Report Format
|
||||
|
||||
`orama monitor report` outputs structured JSON designed for AI consumption:
|
||||
|
||||
```json
|
||||
{
|
||||
"meta": {
|
||||
"environment": "testnet",
|
||||
"collected_at": "2026-02-16T12:00:00Z",
|
||||
"duration_seconds": 3.2,
|
||||
"node_count": 3,
|
||||
"healthy_count": 3
|
||||
},
|
||||
"summary": {
|
||||
"rqlite_leader": "10.0.0.1",
|
||||
"rqlite_voters": "3/3",
|
||||
"rqlite_raft_term": 42,
|
||||
"wg_mesh_status": "all connected",
|
||||
"service_health": "all nominal",
|
||||
"critical_alerts": 0,
|
||||
"warning_alerts": 1,
|
||||
"info_alerts": 0
|
||||
},
|
||||
"alerts": [...],
|
||||
"nodes": [
|
||||
{
|
||||
"host": "51.195.109.238",
|
||||
"status": "healthy",
|
||||
"collection_ms": 526,
|
||||
"report": { ... }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## `orama node report` — VPS-Side Collector
|
||||
|
||||
Runs locally on a VPS node. Collects all system and service data in parallel and outputs a single JSON blob. Requires root privileges.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
# On a VPS node
|
||||
sudo orama node report --json
|
||||
```
|
||||
|
||||
### What It Collects
|
||||
|
||||
| Section | Data |
|
||||
|---------|------|
|
||||
| **system** | CPU count, load average, memory/disk/swap usage, OOM kills, kernel version, uptime, clock time |
|
||||
| **services** | Systemd service states (active, restarts, memory, CPU, restart loop detection) for 10 core services |
|
||||
| **rqlite** | Raft state, leader, term, applied/commit index, peers, strong read test, readyz, debug vars |
|
||||
| **olric** | Service state, memberlist, member count, restarts, memory, log analysis |
|
||||
| **ipfs** | Daemon/cluster state, swarm/cluster peers, repo size, versions, swarm key |
|
||||
| **gateway** | HTTP health check, subsystem status |
|
||||
| **wireguard** | Interface state, WG IP, peers, handshake ages, MTU, config permissions |
|
||||
| **dns** | CoreDNS/Caddy state, port bindings, resolution tests, TLS cert expiry |
|
||||
| **anyone** | Relay/client state, bootstrap progress, fingerprint |
|
||||
| **network** | Internet reachability, TCP stats, retransmission rate, listening ports, UFW rules |
|
||||
| **processes** | Zombie count, orphan orama processes, panic/fatal count in logs |
|
||||
| **namespaces** | Per-namespace service probes (RQLite, Olric, Gateway) |
|
||||
|
||||
### Performance
|
||||
|
||||
All 12 collectors run in parallel with goroutines. Typical collection time is **< 1 second** per node. HTTP timeouts are 3 seconds, command timeouts are 4 seconds.
|
||||
|
||||
### Output Schema
|
||||
|
||||
```json
|
||||
{
|
||||
"timestamp": "2026-02-16T12:00:00Z",
|
||||
"hostname": "ns1",
|
||||
"version": "0.107.0",
|
||||
"collect_ms": 526,
|
||||
"errors": [],
|
||||
"system": { "cpu_count": 4, "load_avg_1": 0.1, "mem_total_mb": 7937, ... },
|
||||
"services": { "services": [...], "failed_units": [] },
|
||||
"rqlite": { "responsive": true, "raft_state": "Leader", "term": 42, ... },
|
||||
"olric": { "service_active": true, "memberlist_up": true, ... },
|
||||
"ipfs": { "daemon_active": true, "swarm_peers": 2, ... },
|
||||
"gateway": { "responsive": true, "http_status": 200, ... },
|
||||
"wireguard": { "interface_up": true, "wg_ip": "10.0.0.1", "peers": [...], ... },
|
||||
"dns": { "coredns_active": true, "caddy_active": true, "base_tls_days_left": 88, ... },
|
||||
"anyone": { "relay_active": true, "bootstrapped": true, ... },
|
||||
"network": { "internet_reachable": true, "ufw_active": true, ... },
|
||||
"processes": { "zombie_count": 0, "orphan_count": 0, "panic_count": 0, ... },
|
||||
"namespaces": []
|
||||
}
|
||||
```
|
||||
|
||||
## Alert Detection
|
||||
|
||||
Alerts are derived from cross-node analysis of all collected reports. Each alert has a severity level and identifies the affected subsystem and node.
|
||||
|
||||
### Alert Severities
|
||||
|
||||
| Severity | Examples |
|
||||
|----------|----------|
|
||||
| **critical** | SSH collection failed (node unreachable), no RQLite leader, split brain, RQLite unresponsive, WireGuard interface down, WG peer never handshaked, OOM kills, service failed, UFW inactive |
|
||||
| **warning** | Strong read failed, memory > 90%, disk > 85%, stale WG handshake (> 3min), Raft term inconsistency, applied index lag > 100, restart loop detected, TLS cert < 14 days, DNS down, namespace gateway down, Anyone not bootstrapped, clock skew > 5s, binary version mismatch, internet unreachable, high TCP retransmission |
|
||||
| **info** | Zombie processes, orphan orama processes, swap usage > 30% |
|
||||
|
||||
### Cross-Node Checks
|
||||
|
||||
These checks compare data across all nodes:
|
||||
|
||||
- **RQLite Leader**: Exactly one leader exists (no split brain)
|
||||
- **Leader Agreement**: All nodes agree on the same leader address
|
||||
- **Raft Term Consistency**: Term values within 1 of each other
|
||||
- **Applied Index Lag**: Followers within 100 entries of the leader
|
||||
- **WireGuard Peer Symmetry**: Each node has N-1 peers
|
||||
- **Clock Skew**: Node clocks within 5 seconds of each other
|
||||
- **Binary Version**: All nodes running the same version
|
||||
- **WebRTC SFU Coverage**: SFU running on expected nodes (3/3) per namespace
|
||||
- **WebRTC TURN Redundancy**: TURN running on expected nodes (2/3) per namespace
|
||||
|
||||
### Per-Node Checks
|
||||
|
||||
- **RQLite**: Responsive, ready, strong read
|
||||
- **WireGuard**: Interface up, handshake freshness
|
||||
- **System**: Memory, disk, load, OOM kills, swap
|
||||
- **Services**: Systemd state, restart loops
|
||||
- **DNS**: CoreDNS/Caddy up, TLS cert expiry, SOA resolution
|
||||
- **Anyone**: Bootstrap progress
|
||||
- **Processes**: Zombies, orphans, panics in logs
|
||||
- **Namespaces**: Gateway and RQLite per namespace
|
||||
- **WebRTC**: SFU and TURN service health (when provisioned)
|
||||
- **Network**: UFW, internet reachability, TCP retransmission
|
||||
|
||||
## Monitor vs Inspector
|
||||
|
||||
Both tools check cluster health, but they serve different purposes:
|
||||
|
||||
| | `orama monitor` | `orama inspect` |
|
||||
|---|---|---|
|
||||
| **Data source** | `orama node report --json` (single SSH call per node) | 15+ SSH commands per node per subsystem |
|
||||
| **Speed** | ~3-5s for full cluster | ~4-10s for full cluster |
|
||||
| **Output** | TUI, tables, JSON | Tables, JSON |
|
||||
| **Focus** | Real-time monitoring, alert detection | Deep diagnostic checks with pass/fail/warn |
|
||||
| **AI support** | `report` subcommand for LLM input | `--ai` flag for inline analysis |
|
||||
| **Use case** | "Is anything wrong right now?" | "What exactly is wrong and why?" |
|
||||
|
||||
Use `monitor` for day-to-day health checks and the interactive TUI. Use `inspect` for deep diagnostics when something is already known to be broken.
|
||||
|
||||
## Configuration
|
||||
|
||||
Uses the same `scripts/remote-nodes.conf` as the inspector. See [INSPECTOR.md](INSPECTOR.md#configuration) for format details.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Nodes must have the `orama` CLI installed (via `orama node install` or `upload-source.sh`). The monitor runs `sudo orama node report --json` over SSH, so the binary must be at `/usr/local/bin/orama` on each node.
|
||||
248
core/docs/NAMESERVER_SETUP.md
Normal file
248
core/docs/NAMESERVER_SETUP.md
Normal file
@ -0,0 +1,248 @@
|
||||
# Nameserver Setup Guide
|
||||
|
||||
This guide explains how to configure your domain registrar to use Orama Network nodes as authoritative nameservers.
|
||||
|
||||
## Overview
|
||||
|
||||
When you install Orama with the `--nameserver` flag, the node runs CoreDNS to serve DNS records for your domain. This enables:
|
||||
|
||||
- Dynamic DNS for deployments (e.g., `myapp.node-abc123.dbrs.space`)
|
||||
- Wildcard DNS support for all subdomains
|
||||
- ACME DNS-01 challenges for automatic SSL certificates
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before setting up nameservers, you need:
|
||||
|
||||
1. **Domain ownership** - A domain you control (e.g., `dbrs.space`)
|
||||
2. **3+ VPS nodes** - Recommended for redundancy
|
||||
3. **Static IP addresses** - Each VPS must have a static public IP
|
||||
4. **Access to registrar DNS settings** - Admin access to your domain registrar
|
||||
|
||||
## Understanding DNS Records
|
||||
|
||||
### NS Records (Nameserver Records)
|
||||
NS records tell the internet which servers are authoritative for your domain:
|
||||
```
|
||||
dbrs.space. IN NS ns1.dbrs.space.
|
||||
dbrs.space. IN NS ns2.dbrs.space.
|
||||
dbrs.space. IN NS ns3.dbrs.space.
|
||||
```
|
||||
|
||||
### Glue Records
|
||||
Glue records are A records that provide IP addresses for nameservers that are under the same domain. They're required because:
|
||||
- `ns1.dbrs.space` is under `dbrs.space`
|
||||
- To resolve `ns1.dbrs.space`, you need to query `dbrs.space` nameservers
|
||||
- But those nameservers ARE `ns1.dbrs.space` - circular dependency!
|
||||
- Glue records break this cycle by providing IPs at the registry level
|
||||
|
||||
```
|
||||
ns1.dbrs.space. IN A 141.227.165.168
|
||||
ns2.dbrs.space. IN A 141.227.165.154
|
||||
ns3.dbrs.space. IN A 141.227.156.51
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
### Step 1: Install Orama on Each VPS
|
||||
|
||||
Install Orama with the `--nameserver` flag on each VPS that will serve as a nameserver:
|
||||
|
||||
```bash
|
||||
# On VPS 1 (ns1)
|
||||
sudo orama install \
|
||||
--nameserver \
|
||||
--domain dbrs.space \
|
||||
--vps-ip 141.227.165.168
|
||||
|
||||
# On VPS 2 (ns2)
|
||||
sudo orama install \
|
||||
--nameserver \
|
||||
--domain dbrs.space \
|
||||
--vps-ip 141.227.165.154
|
||||
|
||||
# On VPS 3 (ns3)
|
||||
sudo orama install \
|
||||
--nameserver \
|
||||
--domain dbrs.space \
|
||||
--vps-ip 141.227.156.51
|
||||
```
|
||||
|
||||
### Step 2: Configure Your Registrar
|
||||
|
||||
#### For Namecheap
|
||||
|
||||
1. **Log into Namecheap Dashboard**
|
||||
- Go to https://www.namecheap.com
|
||||
- Navigate to **Domain List** → **Manage** (next to your domain)
|
||||
|
||||
2. **Add Glue Records (Personal DNS Servers)**
|
||||
- Go to **Advanced DNS** tab
|
||||
- Scroll down to **Personal DNS Servers** section
|
||||
- Click **Add Nameserver**
|
||||
- Add each nameserver with its IP:
|
||||
| Nameserver | IP Address |
|
||||
|------------|------------|
|
||||
| ns1.yourdomain.com | 141.227.165.168 |
|
||||
| ns2.yourdomain.com | 141.227.165.154 |
|
||||
| ns3.yourdomain.com | 141.227.156.51 |
|
||||
|
||||
3. **Set Custom Nameservers**
|
||||
- Go back to the **Domain** tab
|
||||
- Under **Nameservers**, select **Custom DNS**
|
||||
- Add your nameserver hostnames:
|
||||
- ns1.yourdomain.com
|
||||
- ns2.yourdomain.com
|
||||
- ns3.yourdomain.com
|
||||
- Click the green checkmark to save
|
||||
|
||||
4. **Wait for Propagation**
|
||||
- DNS changes can take 24-48 hours to propagate globally
|
||||
- Most changes are visible within 1-4 hours
|
||||
|
||||
#### For GoDaddy
|
||||
|
||||
1. Log into GoDaddy account
|
||||
2. Go to **My Products** → **DNS** for your domain
|
||||
3. Under **Nameservers**, click **Change**
|
||||
4. Select **Enter my own nameservers**
|
||||
5. Add your nameserver hostnames
|
||||
6. For glue records, go to **DNS Management** → **Host Names**
|
||||
7. Add A records for ns1, ns2, ns3
|
||||
|
||||
#### For Cloudflare (as Registrar)
|
||||
|
||||
1. Log into Cloudflare Dashboard
|
||||
2. Go to **Domain Registration** → your domain
|
||||
3. Under **Nameservers**, change to custom
|
||||
4. Note: Cloudflare Registrar may require contacting support for glue records
|
||||
|
||||
#### For Google Domains
|
||||
|
||||
1. Log into Google Domains
|
||||
2. Select your domain → **DNS**
|
||||
3. Under **Name servers**, select **Use custom name servers**
|
||||
4. Add your nameserver hostnames
|
||||
5. For glue records, click **Add** under **Glue records**
|
||||
|
||||
## Verification
|
||||
|
||||
### Step 1: Verify NS Records
|
||||
|
||||
After propagation, check that NS records are visible:
|
||||
|
||||
```bash
|
||||
# Check NS records from Google DNS
|
||||
dig NS yourdomain.com @8.8.8.8
|
||||
|
||||
# Expected output should show:
|
||||
# yourdomain.com. IN NS ns1.yourdomain.com.
|
||||
# yourdomain.com. IN NS ns2.yourdomain.com.
|
||||
# yourdomain.com. IN NS ns3.yourdomain.com.
|
||||
```
|
||||
|
||||
### Step 2: Verify Glue Records
|
||||
|
||||
Check that glue records resolve:
|
||||
|
||||
```bash
|
||||
# Check glue records
|
||||
dig A ns1.yourdomain.com @8.8.8.8
|
||||
dig A ns2.yourdomain.com @8.8.8.8
|
||||
dig A ns3.yourdomain.com @8.8.8.8
|
||||
|
||||
# Each should return the correct IP address
|
||||
```
|
||||
|
||||
### Step 3: Test CoreDNS
|
||||
|
||||
Query your nameservers directly:
|
||||
|
||||
```bash
|
||||
# Test a query against ns1
|
||||
dig @ns1.yourdomain.com test.yourdomain.com
|
||||
|
||||
# Test wildcard resolution
|
||||
dig @ns1.yourdomain.com myapp.node-abc123.yourdomain.com
|
||||
```
|
||||
|
||||
### Step 4: Verify from Multiple Locations
|
||||
|
||||
Use online tools to verify global propagation:
|
||||
- https://dnschecker.org
|
||||
- https://www.whatsmydns.net
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### DNS Not Resolving
|
||||
|
||||
1. **Check CoreDNS is running:**
|
||||
```bash
|
||||
sudo systemctl status coredns
|
||||
```
|
||||
|
||||
2. **Check CoreDNS logs:**
|
||||
```bash
|
||||
sudo journalctl -u coredns -f
|
||||
```
|
||||
|
||||
3. **Verify port 53 is open:**
|
||||
```bash
|
||||
sudo ufw status
|
||||
# Port 53 (TCP/UDP) should be allowed
|
||||
```
|
||||
|
||||
4. **Test locally:**
|
||||
```bash
|
||||
dig @localhost yourdomain.com
|
||||
```
|
||||
|
||||
### Glue Records Not Propagating
|
||||
|
||||
- Glue records are stored at the registry level, not DNS level
|
||||
- They can take longer to propagate (up to 48 hours)
|
||||
- Verify at your registrar that they were saved correctly
|
||||
- Some registrars require the domain to be using their nameservers first
|
||||
|
||||
### SERVFAIL Errors
|
||||
|
||||
Usually indicates CoreDNS configuration issues:
|
||||
|
||||
1. Check Corefile syntax
|
||||
2. Verify RQLite connectivity
|
||||
3. Check firewall rules
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Firewall Rules
|
||||
|
||||
Only expose necessary ports:
|
||||
|
||||
```bash
|
||||
# Allow DNS from anywhere
|
||||
sudo ufw allow 53/tcp
|
||||
sudo ufw allow 53/udp
|
||||
|
||||
# Restrict admin ports to internal network
|
||||
sudo ufw allow from 10.0.0.0/8 to any port 8080 # Health
|
||||
sudo ufw allow from 10.0.0.0/8 to any port 9153 # Metrics
|
||||
```
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
Consider adding rate limiting to prevent DNS amplification attacks.
|
||||
This can be configured in the CoreDNS Corefile.
|
||||
|
||||
## Multi-Node Coordination
|
||||
|
||||
When running multiple nameservers:
|
||||
|
||||
1. **All nodes share the same RQLite cluster** - DNS records are automatically synchronized
|
||||
2. **Install in order** - First node bootstraps, others join
|
||||
3. **Same domain configuration** - All nodes must use the same `--domain` value
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [CoreDNS RQLite Plugin](../pkg/coredns/README.md) - Technical details
|
||||
- [Deployment Guide](./DEPLOYMENT_GUIDE.md) - Full deployment instructions
|
||||
- [Architecture](./ARCHITECTURE.md) - System architecture overview
|
||||
233
core/docs/ORAMAOS_DEPLOYMENT.md
Normal file
233
core/docs/ORAMAOS_DEPLOYMENT.md
Normal file
@ -0,0 +1,233 @@
|
||||
# OramaOS Deployment Guide
|
||||
|
||||
OramaOS is a custom minimal Linux image built with Buildroot. It replaces the standard Ubuntu-based node deployment for mainnet, devnet, and testnet environments. Sandbox clusters remain on Ubuntu for development convenience.
|
||||
|
||||
## What is OramaOS?
|
||||
|
||||
OramaOS is a locked-down operating system designed specifically for Orama node operators. Key properties:
|
||||
|
||||
- **No SSH, no shell** — operators cannot access the filesystem or run commands on the machine
|
||||
- **LUKS full-disk encryption** — the data partition is encrypted; the key is split via Shamir's Secret Sharing across peer nodes
|
||||
- **Read-only rootfs** — the OS image uses SquashFS with dm-verity integrity verification
|
||||
- **A/B partition updates** — signed OS images are applied atomically with automatic rollback on failure
|
||||
- **Service sandboxing** — each service runs in its own Linux namespace with seccomp syscall filtering
|
||||
- **Signed binaries** — all updates are cryptographically signed with the Orama rootwallet
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Partition Layout:
|
||||
/dev/sda1 — ESP (EFI System Partition, systemd-boot)
|
||||
/dev/sda2 — rootfs-A (SquashFS, read-only, dm-verity)
|
||||
/dev/sda3 — rootfs-B (standby, for A/B updates)
|
||||
/dev/sda4 — data (LUKS2 encrypted, ext4)
|
||||
|
||||
Boot Flow:
|
||||
systemd-boot → dm-verity rootfs → orama-agent → WireGuard → services
|
||||
```
|
||||
|
||||
The **orama-agent** is the only root process. It manages:
|
||||
- Boot sequence and LUKS key reconstruction
|
||||
- WireGuard tunnel setup
|
||||
- Service lifecycle (start, stop, restart in sandboxed namespaces)
|
||||
- Command reception from the Gateway over WireGuard
|
||||
- OS updates (download, verify signature, A/B swap, reboot)
|
||||
|
||||
## Enrollment Flow
|
||||
|
||||
OramaOS nodes join the cluster through an enrollment process (different from the Ubuntu `orama node install` flow):
|
||||
|
||||
### Step 1: Flash OramaOS to VPS
|
||||
|
||||
Download the OramaOS image and flash it to your VPS:
|
||||
|
||||
```bash
|
||||
# Download image (URL provided upon acceptance)
|
||||
wget https://releases.orama.network/oramaos-v1.0.0-amd64.qcow2
|
||||
|
||||
# Flash to VPS (provider-specific — Hetzner, Vultr, etc.)
|
||||
# Most providers support uploading custom images via their dashboard
|
||||
```
|
||||
|
||||
### Step 2: First Boot — Enrollment Mode
|
||||
|
||||
On first boot, the agent:
|
||||
1. Generates a random 8-character registration code
|
||||
2. Starts a temporary HTTP server on port 9999
|
||||
3. Opens an outbound WebSocket to the Gateway
|
||||
4. Waits for enrollment to complete
|
||||
|
||||
The registration code is displayed on the VPS console (if available) and served at `http://<vps-ip>:9999/`.
|
||||
|
||||
### Step 3: Run Enrollment from CLI
|
||||
|
||||
On your local machine (where you have the `orama` CLI and rootwallet):
|
||||
|
||||
```bash
|
||||
# Generate an invite token on any existing cluster node
|
||||
orama node invite --expiry 24h
|
||||
|
||||
# Enroll the OramaOS node
|
||||
orama node enroll --node-ip <vps-public-ip> --token <invite-token> --gateway <gateway-url>
|
||||
```
|
||||
|
||||
The enrollment command:
|
||||
1. Fetches the registration code from the node (port 9999)
|
||||
2. Sends the code + invite token to the Gateway
|
||||
3. Gateway validates everything, assigns a WireGuard IP, and pushes config to the node
|
||||
4. Node configures WireGuard, formats the LUKS-encrypted data partition
|
||||
5. LUKS key is split via Shamir and distributed to peer vault-guardians
|
||||
6. Services start in sandboxed namespaces
|
||||
7. Port 9999 closes permanently
|
||||
|
||||
### Step 4: Verify
|
||||
|
||||
```bash
|
||||
# Check the node is online and healthy
|
||||
orama monitor report --env <env>
|
||||
```
|
||||
|
||||
## Genesis Node
|
||||
|
||||
The first OramaOS node in a cluster is the **genesis node**. It has a special boot path because there are no peers yet for Shamir key distribution:
|
||||
|
||||
1. Genesis generates a LUKS key and encrypts the data partition
|
||||
2. The LUKS key is encrypted with a rootwallet-derived key and stored on the unencrypted rootfs
|
||||
3. On reboot (before enough peers exist), the operator must manually unlock:
|
||||
|
||||
```bash
|
||||
orama node unlock --genesis --node-ip <wg-ip>
|
||||
```
|
||||
|
||||
This command:
|
||||
1. Fetches the encrypted genesis key from the node
|
||||
2. Decrypts it using the rootwallet (`rw decrypt`)
|
||||
3. Sends the decrypted LUKS key to the agent over WireGuard
|
||||
|
||||
Once 5+ peers have joined, the genesis node distributes Shamir shares to peers, deletes the local encrypted key, and transitions to normal Shamir-based unlock. After this transition, `orama node unlock` is no longer needed.
|
||||
|
||||
## Normal Reboot (Shamir Unlock)
|
||||
|
||||
When an enrolled OramaOS node reboots:
|
||||
|
||||
1. Agent starts, brings up WireGuard
|
||||
2. Contacts peer vault-guardians over WireGuard
|
||||
3. Fetches K Shamir shares (K = threshold, typically `max(3, N/3)`)
|
||||
4. Reconstructs LUKS key via Lagrange interpolation over GF(256)
|
||||
5. Decrypts and mounts data partition
|
||||
6. Starts all services
|
||||
7. Zeros key from memory
|
||||
|
||||
If not enough peers are available, the agent enters a degraded "waiting for peers" state and retries with exponential backoff (1s, 2s, 4s, 8s, 16s, max 5 retries per cycle).
|
||||
|
||||
## Node Management
|
||||
|
||||
Since OramaOS has no SSH, all management happens through the Gateway API:
|
||||
|
||||
```bash
|
||||
# Check node status
|
||||
curl "https://gateway.example.com/v1/node/status?node_id=<id>"
|
||||
|
||||
# Send a command (e.g., restart a service)
|
||||
curl -X POST "https://gateway.example.com/v1/node/command?node_id=<id>" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"action":"restart","service":"rqlite"}'
|
||||
|
||||
# View logs
|
||||
curl "https://gateway.example.com/v1/node/logs?node_id=<id>&service=gateway&lines=100"
|
||||
|
||||
# Graceful node departure
|
||||
curl -X POST "https://gateway.example.com/v1/node/leave" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"node_id":"<id>"}'
|
||||
```
|
||||
|
||||
The Gateway proxies these requests to the agent over WireGuard (port 9998). The agent is never directly accessible from the public internet.
|
||||
|
||||
## OS Updates
|
||||
|
||||
OramaOS uses an A/B partition scheme for atomic, rollback-safe updates:
|
||||
|
||||
1. Agent periodically checks for new versions
|
||||
2. Downloads the signed image (P2P over WireGuard between nodes)
|
||||
3. Verifies the rootwallet EVM signature against the embedded public key
|
||||
4. Writes to the standby partition (if running from A, writes to B)
|
||||
5. Sets systemd-boot to boot from B with `tries_left=3`
|
||||
6. Reboots
|
||||
7. If B boots successfully (agent starts, WG connects, services healthy): marks B as "good"
|
||||
8. If B fails 3 times: systemd-boot automatically falls back to A
|
||||
|
||||
No operator intervention is needed for updates. Failed updates are automatically rolled back.
|
||||
|
||||
## Service Sandboxing
|
||||
|
||||
Each service on OramaOS runs in an isolated environment:
|
||||
|
||||
- **Mount namespace** — each service only sees its own data directory as writable; everything else is read-only
|
||||
- **UTS namespace** — isolated hostname
|
||||
- **Dedicated UID/GID** — each service runs as a different user (not root)
|
||||
- **Seccomp filtering** — per-service syscall allowlist (initially in audit mode, then enforce mode)
|
||||
|
||||
Services and their sandbox profiles:
|
||||
| Service | Writable Path | Extra Syscalls |
|
||||
|---------|--------------|----------------|
|
||||
| RQLite | `/opt/orama/.orama/data/rqlite` | fsync, fdatasync (Raft + SQLite WAL) |
|
||||
| Olric | `/opt/orama/.orama/data/olric` | sendmmsg, recvmmsg (gossip) |
|
||||
| IPFS | `/opt/orama/.orama/data/ipfs` | sendfile, splice (data transfer) |
|
||||
| Gateway | `/opt/orama/.orama/data/gateway` | sendfile, splice (HTTP) |
|
||||
| CoreDNS | `/opt/orama/.orama/data/coredns` | sendmmsg, recvmmsg (DNS) |
|
||||
|
||||
## OramaOS vs Ubuntu Deployment
|
||||
|
||||
| Feature | Ubuntu | OramaOS |
|
||||
|---------|--------|---------|
|
||||
| SSH access | Yes | No |
|
||||
| Shell access | Yes | No |
|
||||
| Disk encryption | No | LUKS2 (Shamir) |
|
||||
| OS updates | Manual (`orama node upgrade`) | Automatic (signed, A/B) |
|
||||
| Service isolation | systemd only | Namespaces + seccomp |
|
||||
| Rootfs integrity | None | dm-verity |
|
||||
| Binary signing | Optional | Required |
|
||||
| Operator data access | Full | None |
|
||||
| Environments | All (including sandbox) | Mainnet, devnet, testnet |
|
||||
|
||||
## Cleaning / Factory Reset
|
||||
|
||||
OramaOS nodes cannot be cleaned with the standard `orama node clean` command (no SSH access). Instead:
|
||||
|
||||
- **Graceful departure:** `orama node leave` via the Gateway API — stops services, redistributes Shamir shares, removes WG peer
|
||||
- **Factory reset:** Reflash the OramaOS image on the VPS via the hosting provider's dashboard
|
||||
- **Data is unrecoverable:** Since the LUKS key is distributed across peers, reflashing destroys all data permanently
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Node stuck in enrollment mode
|
||||
The node boots but enrollment never completes.
|
||||
|
||||
**Check:** Can you reach `http://<vps-ip>:9999/` from your machine? If not, the VPS firewall may be blocking port 9999.
|
||||
|
||||
**Fix:** Ensure port 9999 is open in the VPS provider's firewall. OramaOS opens it automatically via its internal firewall, but external provider firewalls (Hetzner, AWS security groups) must be configured separately.
|
||||
|
||||
### LUKS unlock fails (not enough peers)
|
||||
After reboot, the node can't reconstruct its LUKS key.
|
||||
|
||||
**Check:** How many peer nodes are online? The node needs at least K peers (threshold) to be reachable over WireGuard.
|
||||
|
||||
**Fix:** Ensure enough cluster nodes are online. If this is the genesis node and fewer than 5 peers exist, use:
|
||||
```bash
|
||||
orama node unlock --genesis --node-ip <wg-ip>
|
||||
```
|
||||
|
||||
### Update failed, node rolled back
|
||||
The node applied an update but reverted to the previous version.
|
||||
|
||||
**Check:** The agent logs will show why the new partition failed to boot (accessible via `GET /v1/node/logs?service=agent`).
|
||||
|
||||
**Common causes:** Corrupted download (signature verification should catch this), hardware issue, or incompatible configuration.
|
||||
|
||||
### Services not starting after reboot
|
||||
The node rebooted and LUKS unlocked, but services are unhealthy.
|
||||
|
||||
**Check:** `GET /v1/node/status` — which services are down?
|
||||
|
||||
**Fix:** Try restarting the specific service via `POST /v1/node/command` with `{"action":"restart","service":"<name>"}`. If the issue persists, check service logs.
|
||||
208
core/docs/SANDBOX.md
Normal file
208
core/docs/SANDBOX.md
Normal file
@ -0,0 +1,208 @@
|
||||
# Sandbox: Ephemeral Hetzner Cloud Clusters
|
||||
|
||||
Spin up temporary 5-node Orama clusters on Hetzner Cloud for development and testing. Total cost: ~€0.04/hour.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# One-time setup (API key, domain, floating IPs, SSH key)
|
||||
orama sandbox setup
|
||||
|
||||
# Create a cluster (~5 minutes)
|
||||
orama sandbox create --name my-feature
|
||||
|
||||
# Check health
|
||||
orama sandbox status
|
||||
|
||||
# SSH into a node
|
||||
orama sandbox ssh 1
|
||||
|
||||
# Deploy code changes
|
||||
orama sandbox rollout
|
||||
|
||||
# Tear it down
|
||||
orama sandbox destroy
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### 1. Hetzner Cloud Account
|
||||
|
||||
Create a project at [console.hetzner.cloud](https://console.hetzner.cloud) and generate an API token with read/write permissions under **Security > API Tokens**.
|
||||
|
||||
### 2. Domain with Glue Records
|
||||
|
||||
You need a domain (or subdomain) that points to Hetzner Floating IPs. The `orama sandbox setup` wizard will guide you through this.
|
||||
|
||||
**Example:** Using `sbx.dbrs.space`
|
||||
|
||||
At your domain registrar:
|
||||
1. Create glue records (Personal DNS Servers):
|
||||
- `ns1.sbx.dbrs.space` → `<floating-ip-1>`
|
||||
- `ns2.sbx.dbrs.space` → `<floating-ip-2>`
|
||||
2. Set custom nameservers for `sbx.dbrs.space`:
|
||||
- `ns1.sbx.dbrs.space`
|
||||
- `ns2.sbx.dbrs.space`
|
||||
|
||||
DNS propagation can take up to 48 hours.
|
||||
|
||||
### 3. Binary Archive
|
||||
|
||||
Build the binary archive before creating a cluster:
|
||||
|
||||
```bash
|
||||
orama build
|
||||
```
|
||||
|
||||
This creates `/tmp/orama-<version>-linux-amd64.tar.gz` with all pre-compiled binaries.
|
||||
|
||||
## Setup
|
||||
|
||||
Run the interactive setup wizard:
|
||||
|
||||
```bash
|
||||
orama sandbox setup
|
||||
```
|
||||
|
||||
This will:
|
||||
1. Prompt for your Hetzner API token and validate it
|
||||
2. Ask for your sandbox domain
|
||||
3. Create or reuse 2 Hetzner Floating IPs (~$0.005/hr each)
|
||||
4. Create a firewall with sandbox rules
|
||||
5. Create a rootwallet SSH entry (`sandbox/root`) if it doesn't exist
|
||||
6. Upload the wallet-derived public key to Hetzner
|
||||
7. Display DNS configuration instructions
|
||||
|
||||
Config is saved to `~/.orama/sandbox.yaml`.
|
||||
|
||||
## Commands
|
||||
|
||||
### `orama sandbox create [--name <name>]`
|
||||
|
||||
Creates a new 5-node cluster. If `--name` is omitted, a random name is generated (e.g., "swift-falcon").
|
||||
|
||||
**Cluster layout:**
|
||||
- Nodes 1-2: Nameservers (CoreDNS + Caddy + all services)
|
||||
- Nodes 3-5: Regular nodes (all services except CoreDNS)
|
||||
|
||||
**Phases:**
|
||||
1. Provision 5 CX22 servers on Hetzner (parallel, ~90s)
|
||||
2. Assign floating IPs to nameserver nodes (~10s)
|
||||
3. Upload binary archive to all nodes (parallel, ~60s)
|
||||
4. Install genesis node + generate invite tokens (~120s)
|
||||
5. Join remaining 4 nodes (serial with health checks, ~180s)
|
||||
6. Verify cluster health (~15s)
|
||||
|
||||
**One sandbox at a time.** Since the floating IPs are shared, only one sandbox can own the nameservers. Destroy the active sandbox before creating a new one.
|
||||
|
||||
### `orama sandbox destroy [--name <name>] [--force]`
|
||||
|
||||
Tears down a cluster:
|
||||
1. Unassigns floating IPs
|
||||
2. Deletes all 5 servers (parallel)
|
||||
3. Removes state file
|
||||
|
||||
Use `--force` to skip confirmation.
|
||||
|
||||
### `orama sandbox list`
|
||||
|
||||
Lists all sandboxes with their status. Also checks Hetzner for orphaned servers that don't have a corresponding state file.
|
||||
|
||||
### `orama sandbox status [--name <name>]`
|
||||
|
||||
Shows per-node health including:
|
||||
- Service status (active/inactive)
|
||||
- RQLite role (Leader/Follower)
|
||||
- Cluster summary (commit index, voter count)
|
||||
|
||||
### `orama sandbox rollout [--name <name>]`
|
||||
|
||||
Deploys code changes:
|
||||
1. Uses the latest binary archive from `/tmp/` (run `orama build` first)
|
||||
2. Pushes to all nodes
|
||||
3. Rolling upgrade: followers first, leader last, 15s between nodes
|
||||
|
||||
### `orama sandbox ssh <node-number>`
|
||||
|
||||
Opens an interactive SSH session to a sandbox node (1-5).
|
||||
|
||||
```bash
|
||||
orama sandbox ssh 1 # SSH into node 1 (genesis/ns1)
|
||||
orama sandbox ssh 3 # SSH into node 3 (regular node)
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Floating IPs
|
||||
|
||||
Hetzner Floating IPs are persistent IPv4 addresses that can be reassigned between servers. They solve the DNS chicken-and-egg problem:
|
||||
|
||||
- Glue records at the registrar point to 2 Floating IPs (configured once)
|
||||
- Each new sandbox assigns the Floating IPs to its nameserver nodes
|
||||
- DNS works instantly — no propagation delay between clusters
|
||||
|
||||
### SSH Authentication
|
||||
|
||||
Sandbox uses a rootwallet-derived SSH key (`sandbox/root` vault entry), the same mechanism as production. The wallet must be unlocked (`rw unlock`) before running sandbox commands that use SSH. The public key is uploaded to Hetzner during setup and injected into every server at creation time.
|
||||
|
||||
### Server Naming
|
||||
|
||||
Servers: `sbx-<name>-<N>` (e.g., `sbx-swift-falcon-1` through `sbx-swift-falcon-5`)
|
||||
|
||||
### State Files
|
||||
|
||||
Sandbox state is stored at `~/.orama/sandboxes/<name>.yaml`. This tracks server IDs, IPs, roles, and cluster status.
|
||||
|
||||
## Cost
|
||||
|
||||
| Resource | Cost | Qty | Total |
|
||||
|----------|------|-----|-------|
|
||||
| CX22 (2 vCPU, 4GB) | €0.006/hr | 5 | €0.03/hr |
|
||||
| Floating IPv4 | €0.005/hr | 2 | €0.01/hr |
|
||||
| **Total** | | | **~€0.04/hr** |
|
||||
|
||||
Servers are billed per hour. Floating IPs are billed as long as they exist (even unassigned). Destroy the sandbox when not in use to save on server costs.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "sandbox not configured"
|
||||
|
||||
Run `orama sandbox setup` first.
|
||||
|
||||
### "no binary archive found"
|
||||
|
||||
Run `orama build` to create the binary archive.
|
||||
|
||||
### "sandbox X is already active"
|
||||
|
||||
Only one sandbox can be active at a time. Destroy it first:
|
||||
```bash
|
||||
orama sandbox destroy --name <name>
|
||||
```
|
||||
|
||||
### Server creation fails
|
||||
|
||||
Check:
|
||||
- Hetzner API token is valid and has read/write permissions
|
||||
- You haven't hit Hetzner's server limit (default: 10 per project)
|
||||
- The selected location has CX22 capacity
|
||||
|
||||
### Genesis install fails
|
||||
|
||||
SSH into the node to debug:
|
||||
```bash
|
||||
orama sandbox ssh 1
|
||||
journalctl -u orama-node -f
|
||||
```
|
||||
|
||||
The sandbox will be left in "error" state. You can destroy and recreate it.
|
||||
|
||||
### DNS not resolving
|
||||
|
||||
1. Verify glue records are configured at your registrar
|
||||
2. Check propagation: `dig NS sbx.dbrs.space @8.8.8.8`
|
||||
3. Propagation can take 24-48 hours for new domains
|
||||
|
||||
### Orphaned servers
|
||||
|
||||
If `orama sandbox list` shows orphaned servers, delete them manually at [console.hetzner.cloud](https://console.hetzner.cloud). Sandbox servers are labeled `orama-sandbox=<name>` for easy identification.
|
||||
194
core/docs/SECURITY.md
Normal file
194
core/docs/SECURITY.md
Normal file
@ -0,0 +1,194 @@
|
||||
# Security Hardening
|
||||
|
||||
This document describes all security measures applied to the Orama Network, covering both Phase 1 (service hardening on existing Ubuntu nodes) and Phase 2 (OramaOS locked-down image).
|
||||
|
||||
## Phase 1: Service Hardening
|
||||
|
||||
These measures apply to all nodes (Ubuntu and OramaOS).
|
||||
|
||||
### Network Isolation
|
||||
|
||||
**CIDR Validation (Step 1.1)**
|
||||
- WireGuard subnet restricted to `10.0.0.0/24` across all components: firewall rules, rate limiter, auth module, and WireGuard PostUp/PostDown iptables rules
|
||||
- Prevents other tenants on shared VPS providers from bypassing the firewall via overlapping `10.x.x.x` ranges
|
||||
|
||||
**IPv6 Disabled (Step 1.2)**
|
||||
- IPv6 disabled system-wide via sysctl: `net.ipv6.conf.all.disable_ipv6=1`
|
||||
- Prevents services bound to `0.0.0.0` from being reachable via IPv6 (which had no firewall rules)
|
||||
|
||||
### Authentication
|
||||
|
||||
**Internal Endpoint Auth (Step 1.3)**
|
||||
- `/v1/internal/wg/peers` and `/v1/internal/wg/peer/remove` now require cluster secret validation
|
||||
- Peer removal additionally validates the request originates from a WireGuard subnet IP
|
||||
|
||||
**RQLite Authentication (Step 1.7)**
|
||||
- RQLite runs with `-auth` flag pointing to a credentials file
|
||||
- All RQLite HTTP requests include `Authorization: Basic <base64>` headers
|
||||
- Credentials generated at cluster genesis, distributed to joining nodes via join response
|
||||
- Both the central RQLite client wrapper and the standalone CoreDNS RQLite client send auth
|
||||
|
||||
**Olric Gossip Encryption (Step 1.8)**
|
||||
- Olric memberlist uses a 32-byte encryption key for all gossip traffic
|
||||
- Key generated at genesis, distributed via join response
|
||||
- Prevents rogue nodes from joining the gossip ring and poisoning caches
|
||||
- Note: encryption is all-or-nothing (coordinated restart required when enabling)
|
||||
|
||||
**IPFS Cluster TrustedPeers (Step 1.9)**
|
||||
- IPFS Cluster `TrustedPeers` populated with actual cluster peer IDs (was `["*"]`)
|
||||
- New peers added to TrustedPeers on all existing nodes during join
|
||||
- Prevents unauthorized peers from controlling IPFS pinning
|
||||
|
||||
**Vault V1 Auth Enforcement (Step 1.14)**
|
||||
- V1 push/pull endpoints require a valid session token when vault-guardian is configured
|
||||
- Previously, auth was optional for backward compatibility — any WG peer could read/overwrite Shamir shares
|
||||
|
||||
### Token & Key Storage
|
||||
|
||||
**Refresh Token Hashing (Step 1.5)**
|
||||
- Refresh tokens stored as SHA-256 hashes in RQLite (never plaintext)
|
||||
- On lookup: hash the incoming token, query by hash
|
||||
- On revocation: hash before revoking (both single-token and by-subject)
|
||||
- Existing tokens invalidated on upgrade (users re-authenticate)
|
||||
|
||||
**API Key Hashing (Step 1.6)**
|
||||
- API keys stored as HMAC-SHA256 hashes using a server-side secret
|
||||
- HMAC secret generated at cluster genesis, stored in `~/.orama/secrets/api-key-hmac-secret`
|
||||
- On lookup: compute HMAC, query by hash — fast enough for every request (unlike bcrypt)
|
||||
- In-memory cache uses raw key as cache key (never persisted)
|
||||
- During rolling upgrade: dual lookup (HMAC first, then raw as fallback) until all nodes upgraded
|
||||
|
||||
**TURN Secret Encryption (Step 1.15)**
|
||||
- TURN shared secrets encrypted at rest in RQLite using AES-256-GCM
|
||||
- Encryption key derived via HKDF from the cluster secret with purpose string `"turn-encryption"`
|
||||
|
||||
### TLS & Transport
|
||||
|
||||
**InsecureSkipVerify Fix (Step 1.10)**
|
||||
- During node join, TLS verification uses TOFU (Trust On First Use)
|
||||
- Invite token output includes the CA certificate fingerprint (SHA-256)
|
||||
- Joining node verifies the server cert fingerprint matches before proceeding
|
||||
- After join: CA cert stored locally for future connections
|
||||
|
||||
**WebSocket Origin Validation (Step 1.4)**
|
||||
- All WebSocket upgraders validate the `Origin` header against the node's configured domain
|
||||
- Non-browser clients (no Origin header) are still allowed
|
||||
- Prevents cross-site WebSocket hijacking attacks
|
||||
|
||||
### Process Isolation
|
||||
|
||||
**Dedicated User (Step 1.11)**
|
||||
- All services run as the `orama` user (not root)
|
||||
- Caddy and CoreDNS get `AmbientCapabilities=CAP_NET_BIND_SERVICE` for ports 80/443 and 53
|
||||
- WireGuard stays as root (kernel netlink requires it)
|
||||
- vault-guardian already had proper hardening
|
||||
|
||||
**systemd Hardening (Step 1.12)**
|
||||
- All service units include:
|
||||
```ini
|
||||
ProtectSystem=strict
|
||||
ProtectHome=yes
|
||||
NoNewPrivileges=yes
|
||||
PrivateDevices=yes
|
||||
ProtectKernelTunables=yes
|
||||
ProtectKernelModules=yes
|
||||
RestrictNamespaces=yes
|
||||
ReadWritePaths=/opt/orama/.orama
|
||||
```
|
||||
- Applied to both template files (`pkg/environments/templates/`) and hardcoded unit generators (`pkg/environments/production/services.go`)
|
||||
|
||||
### Supply Chain
|
||||
|
||||
**Binary Signing (Step 1.13)**
|
||||
- Build archives include `manifest.sig` — a rootwallet EVM signature of the manifest hash
|
||||
- During install, the signature is verified against the embedded Orama public key
|
||||
- Unsigned or tampered archives are rejected
|
||||
|
||||
## Phase 2: OramaOS
|
||||
|
||||
These measures apply only to OramaOS nodes (mainnet, devnet, testnet).
|
||||
|
||||
### Immutable OS
|
||||
|
||||
- **Read-only rootfs** — SquashFS with dm-verity integrity verification
|
||||
- **No shell** — `/bin/sh` symlinked to `/bin/false`, no bash/ash/ssh
|
||||
- **No SSH** — OpenSSH not included in the image
|
||||
- **Minimal packages** — only what's needed for systemd, cryptsetup, and the agent
|
||||
|
||||
### Full-Disk Encryption
|
||||
|
||||
- **LUKS2** with AES-XTS-Plain64 on the data partition
|
||||
- **Shamir's Secret Sharing** over GF(256) — LUKS key split across peer vault-guardians
|
||||
- **Adaptive threshold** — K = max(3, N/3) where N is the number of peers
|
||||
- **Key zeroing** — LUKS key wiped from memory immediately after use
|
||||
- **Malicious share detection** — fetch K+1 shares when possible, verify consistency
|
||||
|
||||
### Service Sandboxing
|
||||
|
||||
Each service runs in isolated Linux namespaces:
|
||||
- **CLONE_NEWNS** — mount namespace (filesystem isolation)
|
||||
- **CLONE_NEWUTS** — hostname namespace
|
||||
- **Dedicated UID/GID** — each service has its own user
|
||||
- **Seccomp filtering** — per-service syscall allowlist
|
||||
|
||||
Note: CLONE_NEWPID is intentionally omitted — it makes services PID 1 in their namespace, which changes signal semantics (SIGTERM ignored by default for PID 1).
|
||||
|
||||
### Signed Updates
|
||||
|
||||
- A/B partition scheme with systemd-boot and boot counting (`tries_left=3`)
|
||||
- All updates signed with rootwallet EVM signature (secp256k1 + keccak256)
|
||||
- Signer address: `0xb5d8a496c8b2412990d7D467E17727fdF5954afC`
|
||||
- P2P distribution over WireGuard between nodes
|
||||
- Automatic rollback on 3 consecutive boot failures
|
||||
|
||||
### Zero Operator Access
|
||||
|
||||
- Operators cannot read data on the machine (LUKS encrypted, no shell)
|
||||
- Management only through Gateway API → agent over WireGuard
|
||||
- All commands are logged and auditable
|
||||
- No root access, no console access, no file system access
|
||||
|
||||
## Rollout Strategy
|
||||
|
||||
### Phase 1 Batches
|
||||
|
||||
```
|
||||
Batch 1 (zero-risk, no restart):
|
||||
- CIDR fix
|
||||
- IPv6 disable
|
||||
- Internal endpoint auth
|
||||
- WebSocket origin check
|
||||
|
||||
Batch 2 (medium-risk, restart needed):
|
||||
- Hash refresh tokens
|
||||
- Hash API keys
|
||||
- Binary signing
|
||||
- Vault V1 auth enforcement
|
||||
- TURN secret encryption
|
||||
|
||||
Batch 3 (high-risk, coordinated rollout):
|
||||
- RQLite auth (followers first, leader last)
|
||||
- Olric encryption (simultaneous restart)
|
||||
- IPFS Cluster TrustedPeers
|
||||
|
||||
Batch 4 (infrastructure changes):
|
||||
- InsecureSkipVerify fix
|
||||
- Dedicated user
|
||||
- systemd hardening
|
||||
```
|
||||
|
||||
### Phase 2
|
||||
|
||||
1. Build and test OramaOS image in QEMU
|
||||
2. Deploy to sandbox cluster alongside Ubuntu nodes
|
||||
3. Verify interop and stability
|
||||
4. Gradual migration: testnet → devnet → mainnet (one node at a time, maintaining Raft quorum)
|
||||
|
||||
## Verification
|
||||
|
||||
All changes verified on sandbox cluster before production deployment:
|
||||
|
||||
- `make test` — all unit tests pass
|
||||
- `orama monitor report --env sandbox` — full cluster health
|
||||
- Manual endpoint testing (e.g., curl without auth → 401)
|
||||
- Security-specific checks (IPv6 listeners, RQLite auth, binary signatures)
|
||||
374
core/docs/SERVERLESS.md
Normal file
374
core/docs/SERVERLESS.md
Normal file
@ -0,0 +1,374 @@
|
||||
# Serverless Functions
|
||||
|
||||
Orama Network runs serverless functions as sandboxed WebAssembly (WASM) modules. Functions are written in Go, compiled to WASM with TinyGo, and executed in an isolated wazero runtime with configurable memory limits and timeouts.
|
||||
|
||||
Functions receive input via **stdin** (JSON) and return output via **stdout** (JSON). They can also access Orama services — database, cache, storage, secrets, PubSub, and HTTP — through **host functions** injected by the runtime.
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# 1. Scaffold a new function
|
||||
orama function init my-function
|
||||
|
||||
# 2. Edit your handler
|
||||
cd my-function
|
||||
# edit function.go
|
||||
|
||||
# 3. Build to WASM
|
||||
orama function build
|
||||
|
||||
# 4. Deploy
|
||||
orama function deploy
|
||||
|
||||
# 5. Invoke
|
||||
orama function invoke my-function --data '{"name": "World"}'
|
||||
|
||||
# 6. View logs
|
||||
orama function logs my-function
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
my-function/
|
||||
├── function.go # Handler code
|
||||
└── function.yaml # Configuration
|
||||
```
|
||||
|
||||
### function.yaml
|
||||
|
||||
```yaml
|
||||
name: my-function # Required. Letters, digits, hyphens, underscores.
|
||||
public: false # Allow unauthenticated invocation (default: false)
|
||||
memory: 64 # Memory limit in MB (1-256, default: 64)
|
||||
timeout: 30 # Execution timeout in seconds (1-300, default: 30)
|
||||
retry:
|
||||
count: 0 # Retry attempts on failure (default: 0)
|
||||
delay: 5 # Seconds between retries (default: 5)
|
||||
env: # Environment variables (accessible via get_env)
|
||||
MY_VAR: "value"
|
||||
```
|
||||
|
||||
### function.go (minimal)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Read JSON input from stdin
|
||||
var input []byte
|
||||
buf := make([]byte, 4096)
|
||||
for {
|
||||
n, err := os.Stdin.Read(buf)
|
||||
if n > 0 {
|
||||
input = append(input, buf[:n]...)
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
var payload map[string]interface{}
|
||||
json.Unmarshal(input, &payload)
|
||||
|
||||
// Process and return JSON output via stdout
|
||||
response := map[string]interface{}{
|
||||
"result": "Hello!",
|
||||
}
|
||||
output, _ := json.Marshal(response)
|
||||
os.Stdout.Write(output)
|
||||
}
|
||||
```
|
||||
|
||||
### Building
|
||||
|
||||
Functions are compiled to WASM using [TinyGo](https://tinygo.org/):
|
||||
|
||||
```bash
|
||||
# Using the CLI (recommended)
|
||||
orama function build
|
||||
|
||||
# Or manually
|
||||
tinygo build -o function.wasm -target wasi function.go
|
||||
```
|
||||
|
||||
## Host Functions API
|
||||
|
||||
Host functions let your WASM code interact with Orama services. They are imported from the `"env"` or `"host"` module (both work) and use a pointer/length ABI for string parameters.
|
||||
|
||||
All host functions are registered at runtime by the engine. They are available to every function without additional configuration.
|
||||
|
||||
### Context
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `get_caller_wallet()` → string | Wallet address of the caller (from JWT) |
|
||||
| `get_request_id()` → string | Unique invocation ID |
|
||||
| `get_env(key)` → string | Environment variable from function.yaml |
|
||||
| `get_secret(name)` → string | Decrypted secret value (see [Managing Secrets](#managing-secrets)) |
|
||||
|
||||
### Database (RQLite)
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `db_query(sql, argsJSON)` → JSON | Execute SELECT query. Args as JSON array. Returns JSON array of row objects. |
|
||||
| `db_execute(sql, argsJSON)` → int | Execute INSERT/UPDATE/DELETE. Returns affected row count. |
|
||||
|
||||
Example query from WASM:
|
||||
```
|
||||
db_query("SELECT push_token, device_type FROM devices WHERE user_id = ?", '["user123"]')
|
||||
→ [{"push_token": "abc...", "device_type": "ios"}]
|
||||
```
|
||||
|
||||
### Cache (Olric Distributed Cache)
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `cache_get(key)` → bytes | Get cached value by key. Returns empty on miss. |
|
||||
| `cache_set(key, value, ttl)` | Store value with TTL in seconds. |
|
||||
| `cache_incr(key)` → int64 | Atomically increment by 1 (init to 0 if missing). |
|
||||
| `cache_incr_by(key, delta)` → int64 | Atomically increment by delta. |
|
||||
|
||||
### HTTP
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `http_fetch(method, url, headersJSON, body)` → JSON | Make outbound HTTP request. Headers as JSON object. Returns `{"status": 200, "headers": {...}, "body": "..."}`. Timeout: 30s. |
|
||||
|
||||
### PubSub
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `pubsub_publish(topic, dataJSON)` → bool | Publish message to a PubSub topic. Returns true on success. |
|
||||
|
||||
### Logging
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `log_info(message)` | Log info-level message (captured in invocation logs). |
|
||||
| `log_error(message)` | Log error-level message. |
|
||||
|
||||
## Managing Secrets
|
||||
|
||||
Secrets are encrypted at rest (AES-256-GCM) and scoped to your namespace. Functions read them via `get_secret("name")` at runtime.
|
||||
|
||||
### CLI Commands
|
||||
|
||||
```bash
|
||||
# Set a secret (inline value)
|
||||
orama function secrets set APNS_KEY_ID "ABC123DEF"
|
||||
|
||||
# Set a secret from a file (useful for PEM keys, certificates)
|
||||
orama function secrets set APNS_AUTH_KEY --from-file ./AuthKey_ABC123.p8
|
||||
|
||||
# List all secret names (values are never shown)
|
||||
orama function secrets list
|
||||
|
||||
# Delete a secret
|
||||
orama function secrets delete APNS_KEY_ID
|
||||
|
||||
# Delete without confirmation
|
||||
orama function secrets delete APNS_KEY_ID --force
|
||||
```
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **You set secrets** via the CLI → encrypted and stored in the database
|
||||
2. **Functions read secrets** at runtime via `get_secret("name")` → decrypted on demand
|
||||
3. **Namespace isolation** → each namespace has its own secret store; functions in namespace A cannot read secrets from namespace B
|
||||
|
||||
## PubSub Triggers
|
||||
|
||||
Triggers let functions react to events automatically. When a message is published to a PubSub topic, all functions with a trigger on that topic are invoked asynchronously.
|
||||
|
||||
### CLI Commands
|
||||
|
||||
```bash
|
||||
# Add a trigger: invoke "call-push-handler" when messages hit "calls:invite"
|
||||
orama function triggers add call-push-handler --topic calls:invite
|
||||
|
||||
# List triggers for a function
|
||||
orama function triggers list call-push-handler
|
||||
|
||||
# Delete a trigger
|
||||
orama function triggers delete call-push-handler <trigger-id>
|
||||
```
|
||||
|
||||
### Trigger Event Payload
|
||||
|
||||
When triggered via PubSub, the function receives this JSON via stdin:
|
||||
|
||||
```json
|
||||
{
|
||||
"topic": "calls:invite",
|
||||
"data": { ... },
|
||||
"namespace": "my-namespace",
|
||||
"trigger_depth": 1,
|
||||
"timestamp": 1708972800
|
||||
}
|
||||
```
|
||||
|
||||
### Depth Limiting
|
||||
|
||||
To prevent infinite loops (function A publishes to topic → triggers function A again), trigger depth is tracked. Maximum depth is **5**. If a function's output triggers another function, `trigger_depth` increments. At depth 5, no further triggers fire.
|
||||
|
||||
## Function Lifecycle
|
||||
|
||||
### Versioning
|
||||
|
||||
Each deploy creates a new version. The WASM binary is stored in **IPFS** (content-addressed) and metadata is stored in **RQLite**.
|
||||
|
||||
```bash
|
||||
# List versions
|
||||
orama function versions my-function
|
||||
|
||||
# Invoke a specific version
|
||||
curl -X POST .../v1/functions/my-function@2/invoke
|
||||
```
|
||||
|
||||
### Invocation Logging
|
||||
|
||||
Every invocation is logged with: request ID, duration, status (success/error/timeout), input/output size, and any `log_info`/`log_error` messages.
|
||||
|
||||
```bash
|
||||
orama function logs my-function
|
||||
```
|
||||
|
||||
## CLI Reference
|
||||
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `orama function init <name>` | Scaffold a new function project |
|
||||
| `orama function build [dir]` | Compile Go to WASM |
|
||||
| `orama function deploy [dir]` | Deploy WASM to the network |
|
||||
| `orama function invoke <name> --data <json>` | Invoke a function |
|
||||
| `orama function list` | List deployed functions |
|
||||
| `orama function get <name>` | Get function details |
|
||||
| `orama function delete <name>` | Delete a function |
|
||||
| `orama function logs <name>` | View invocation logs |
|
||||
| `orama function versions <name>` | List function versions |
|
||||
| `orama function secrets set <name> <value>` | Set an encrypted secret |
|
||||
| `orama function secrets list` | List secret names |
|
||||
| `orama function secrets delete <name>` | Delete a secret |
|
||||
| `orama function triggers add <fn> --topic <t>` | Add PubSub trigger |
|
||||
| `orama function triggers list <fn>` | List triggers |
|
||||
| `orama function triggers delete <fn> <id>` | Delete a trigger |
|
||||
|
||||
## HTTP API Reference
|
||||
|
||||
| Method | Endpoint | Description |
|
||||
|--------|----------|-------------|
|
||||
| POST | `/v1/functions` | Deploy function (multipart/form-data) |
|
||||
| GET | `/v1/functions` | List functions |
|
||||
| GET | `/v1/functions/{name}` | Get function info |
|
||||
| DELETE | `/v1/functions/{name}` | Delete function |
|
||||
| POST | `/v1/functions/{name}/invoke` | Invoke function |
|
||||
| GET | `/v1/functions/{name}/versions` | List versions |
|
||||
| GET | `/v1/functions/{name}/logs` | Get logs |
|
||||
| WS | `/v1/functions/{name}/ws` | WebSocket invoke (streaming) |
|
||||
| PUT | `/v1/functions/secrets` | Set a secret |
|
||||
| GET | `/v1/functions/secrets` | List secret names |
|
||||
| DELETE | `/v1/functions/secrets/{name}` | Delete a secret |
|
||||
| POST | `/v1/functions/{name}/triggers` | Add PubSub trigger |
|
||||
| GET | `/v1/functions/{name}/triggers` | List triggers |
|
||||
| DELETE | `/v1/functions/{name}/triggers/{id}` | Delete trigger |
|
||||
| POST | `/v1/invoke/{namespace}/{name}` | Direct invoke (alt endpoint) |
|
||||
|
||||
## Example: Call Push Handler
|
||||
|
||||
A real-world function that sends VoIP push notifications when a call invite is published to PubSub:
|
||||
|
||||
```yaml
|
||||
# function.yaml
|
||||
name: call-push-handler
|
||||
memory: 128
|
||||
timeout: 30
|
||||
```
|
||||
|
||||
```go
|
||||
// function.go — triggered by PubSub on "calls:invite"
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
)
|
||||
|
||||
// This function:
|
||||
// 1. Receives a call invite event from PubSub trigger
|
||||
// 2. Queries the database for the callee's device info
|
||||
// 3. Reads push notification credentials from secrets
|
||||
// 4. Sends a push notification via http_fetch
|
||||
|
||||
func main() {
|
||||
// Read PubSub trigger event from stdin
|
||||
var input []byte
|
||||
buf := make([]byte, 4096)
|
||||
for {
|
||||
n, err := os.Stdin.Read(buf)
|
||||
if n > 0 {
|
||||
input = append(input, buf[:n]...)
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Parse the trigger event wrapper
|
||||
var event struct {
|
||||
Topic string `json:"topic"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
json.Unmarshal(input, &event)
|
||||
|
||||
// Parse the actual call invite data
|
||||
var invite struct {
|
||||
CalleeID string `json:"calleeId"`
|
||||
CallerName string `json:"callerName"`
|
||||
CallType string `json:"callType"`
|
||||
}
|
||||
json.Unmarshal(event.Data, &invite)
|
||||
|
||||
// At this point, the function would use host functions:
|
||||
//
|
||||
// 1. db_query("SELECT push_token, device_type FROM devices WHERE user_id = ?",
|
||||
// json.Marshal([]string{invite.CalleeID}))
|
||||
//
|
||||
// 2. get_secret("FCM_SERVER_KEY") for Android push
|
||||
// get_secret("APNS_KEY_PEM") for iOS push
|
||||
//
|
||||
// 3. http_fetch("POST", "https://fcm.googleapis.com/v1/...", headers, body)
|
||||
//
|
||||
// 4. log_info("Push sent to " + invite.CalleeID)
|
||||
//
|
||||
// Note: Host functions use the WASM ABI (pointer/length).
|
||||
// A Go SDK for ergonomic access is planned.
|
||||
|
||||
response := map[string]interface{}{
|
||||
"status": "sent",
|
||||
"callee": invite.CalleeID,
|
||||
}
|
||||
output, _ := json.Marshal(response)
|
||||
os.Stdout.Write(output)
|
||||
}
|
||||
```
|
||||
|
||||
Deploy and wire the trigger:
|
||||
```bash
|
||||
orama function build
|
||||
orama function deploy
|
||||
|
||||
# Set push notification secrets
|
||||
orama function secrets set FCM_SERVER_KEY "your-fcm-key"
|
||||
orama function secrets set APNS_KEY_PEM --from-file ./AuthKey.p8
|
||||
orama function secrets set APNS_KEY_ID "ABC123"
|
||||
orama function secrets set APNS_TEAM_ID "TEAM456"
|
||||
|
||||
# Wire the PubSub trigger
|
||||
orama function triggers add call-push-handler --topic calls:invite
|
||||
```
|
||||
291
core/docs/WEBRTC.md
Normal file
291
core/docs/WEBRTC.md
Normal file
@ -0,0 +1,291 @@
|
||||
# WebRTC Integration
|
||||
|
||||
Real-time voice, video, and data channels for Orama Network namespaces.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Client A Client B
|
||||
│ │
|
||||
│ 1. Get TURN credentials (REST) │
|
||||
│ 2. Connect WebSocket (signaling) │
|
||||
│ 3. Exchange SDP/ICE via SFU │
|
||||
│ │
|
||||
▼ ▼
|
||||
┌──────────┐ UDP relay ┌──────────┐
|
||||
│ TURN │◄──────────────────►│ TURN │
|
||||
│ Server │ (public IPs) │ Server │
|
||||
│ Node 1 │ │ Node 2 │
|
||||
└────┬─────┘ └────┬─────┘
|
||||
│ WireGuard │ WireGuard
|
||||
▼ ▼
|
||||
┌──────────────────────────────────────────┐
|
||||
│ SFU Servers (3 nodes) │
|
||||
│ - WebSocket signaling (WireGuard only) │
|
||||
│ - Pion WebRTC (RTP forwarding) │
|
||||
│ - Room management │
|
||||
│ - Track publish/subscribe │
|
||||
└──────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Key design decisions:**
|
||||
- **TURN-shielded**: SFU binds only to WireGuard IPs. All client media flows through TURN relay.
|
||||
- **`iceTransportPolicy: relay`** enforced server-side — no direct peer connections.
|
||||
- **Opt-in per namespace** via `orama namespace enable webrtc`.
|
||||
- **SFU on all 3 nodes**, **TURN on 2 of 3 nodes** (redundancy without over-provisioning).
|
||||
- **Separate port allocation** from existing namespace services.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Namespace must be provisioned with a ready cluster (RQLite + Olric + Gateway running).
|
||||
- Command must be run on a cluster node (uses internal gateway endpoint).
|
||||
|
||||
## Enable / Disable
|
||||
|
||||
```bash
|
||||
# Enable WebRTC for a namespace
|
||||
orama namespace enable webrtc --namespace myapp
|
||||
|
||||
# Check status
|
||||
orama namespace webrtc-status --namespace myapp
|
||||
|
||||
# Disable WebRTC (stops services, deallocates ports, removes DNS)
|
||||
orama namespace disable webrtc --namespace myapp
|
||||
```
|
||||
|
||||
### What happens on enable:
|
||||
1. Generates a per-namespace TURN shared secret (32 bytes, crypto/rand)
|
||||
2. Inserts `namespace_webrtc_config` DB record
|
||||
3. Allocates WebRTC port blocks on each node (SFU signaling + media range, TURN relay range)
|
||||
4. Spawns TURN on 2 nodes (selected by capacity)
|
||||
5. Spawns SFU on all 3 nodes
|
||||
6. Creates DNS A records: `turn.ns-{name}.{baseDomain}` pointing to TURN node public IPs
|
||||
7. Updates cluster state on all nodes (for cold-boot restoration)
|
||||
|
||||
### What happens on disable:
|
||||
1. Stops SFU on all 3 nodes
|
||||
2. Stops TURN on 2 nodes
|
||||
3. Deallocates all WebRTC ports
|
||||
4. Deletes TURN DNS records
|
||||
5. Cleans up DB records (`namespace_webrtc_config`, `webrtc_rooms`)
|
||||
6. Updates cluster state
|
||||
|
||||
## Client Integration (JavaScript)
|
||||
|
||||
### Authentication
|
||||
|
||||
All WebRTC endpoints require authentication. Use one of:
|
||||
|
||||
```
|
||||
# Option A: API Key via header (recommended)
|
||||
X-API-Key: <your-namespace-api-key>
|
||||
|
||||
# Option B: API Key via Authorization header
|
||||
Authorization: ApiKey <your-namespace-api-key>
|
||||
|
||||
# Option C: JWT Bearer token
|
||||
Authorization: Bearer <jwt>
|
||||
```
|
||||
|
||||
### 1. Get TURN Credentials
|
||||
|
||||
```javascript
|
||||
const response = await fetch('https://ns-myapp.orama-devnet.network/v1/webrtc/turn/credentials', {
|
||||
method: 'POST',
|
||||
headers: { 'X-API-Key': apiKey }
|
||||
});
|
||||
|
||||
const { uris, username, password, ttl } = await response.json();
|
||||
// uris: [
|
||||
// "turn:turn.ns-myapp.orama-devnet.network:3478?transport=udp",
|
||||
// "turn:turn.ns-myapp.orama-devnet.network:3478?transport=tcp",
|
||||
// "turns:turn.ns-myapp.orama-devnet.network:5349"
|
||||
// ]
|
||||
// username: "{expiry_unix}:{namespace}"
|
||||
// password: HMAC-SHA1 derived (base64)
|
||||
// ttl: 600 (seconds)
|
||||
```
|
||||
|
||||
### 2. Create PeerConnection
|
||||
|
||||
```javascript
|
||||
const pc = new RTCPeerConnection({
|
||||
iceServers: [{ urls: uris, username, credential: password }],
|
||||
iceTransportPolicy: 'relay' // enforced by SFU
|
||||
});
|
||||
```
|
||||
|
||||
### 3. Connect Signaling WebSocket
|
||||
|
||||
```javascript
|
||||
const ws = new WebSocket(
|
||||
`wss://ns-myapp.orama-devnet.network/v1/webrtc/signal?room=${roomId}&api_key=${apiKey}`
|
||||
);
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
const msg = JSON.parse(event.data);
|
||||
switch (msg.type) {
|
||||
case 'offer': handleOffer(msg); break;
|
||||
case 'answer': handleAnswer(msg); break;
|
||||
case 'ice-candidate': handleICE(msg); break;
|
||||
case 'peer-joined': handleJoin(msg); break;
|
||||
case 'peer-left': handleLeave(msg); break;
|
||||
case 'turn-credentials':
|
||||
case 'refresh-credentials':
|
||||
updateTURN(msg); // SFU sends refreshed creds at 80% TTL
|
||||
break;
|
||||
case 'server-draining':
|
||||
reconnect(); // SFU shutting down, reconnect to another node
|
||||
break;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 4. Room Management (REST)
|
||||
|
||||
```javascript
|
||||
const headers = { 'X-API-Key': apiKey, 'Content-Type': 'application/json' };
|
||||
|
||||
// Create room
|
||||
await fetch('/v1/webrtc/rooms', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ room_id: 'my-room' })
|
||||
});
|
||||
|
||||
// List rooms
|
||||
const rooms = await fetch('/v1/webrtc/rooms', { headers });
|
||||
|
||||
// Close room
|
||||
await fetch('/v1/webrtc/rooms?room_id=my-room', {
|
||||
method: 'DELETE',
|
||||
headers
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### REST Endpoints
|
||||
|
||||
| Method | Path | Auth | Description |
|
||||
|--------|------|------|-------------|
|
||||
| POST | `/v1/webrtc/turn/credentials` | JWT/API key | Get TURN relay credentials |
|
||||
| GET/WS | `/v1/webrtc/signal` | JWT/API key | WebSocket signaling |
|
||||
| GET | `/v1/webrtc/rooms` | JWT/API key | List rooms |
|
||||
| POST | `/v1/webrtc/rooms` | JWT/API key (owner) | Create room |
|
||||
| DELETE | `/v1/webrtc/rooms` | JWT/API key (owner) | Close room |
|
||||
|
||||
### Signaling Messages
|
||||
|
||||
| Type | Direction | Description |
|
||||
|------|-----------|-------------|
|
||||
| `join` | Client → SFU | Join room |
|
||||
| `offer` | Client ↔ SFU | SDP offer |
|
||||
| `answer` | Client ↔ SFU | SDP answer |
|
||||
| `ice-candidate` | Client ↔ SFU | ICE candidate |
|
||||
| `leave` | Client → SFU | Leave room |
|
||||
| `peer-joined` | SFU → Client | New peer notification |
|
||||
| `peer-left` | SFU → Client | Peer departure |
|
||||
| `turn-credentials` | SFU → Client | Initial TURN credentials |
|
||||
| `refresh-credentials` | SFU → Client | Refreshed credentials (at 80% TTL) |
|
||||
| `server-draining` | SFU → Client | SFU shutting down |
|
||||
|
||||
## Port Allocation
|
||||
|
||||
WebRTC uses a **separate port allocation system** from the core namespace ports:
|
||||
|
||||
| Service | Port Range | Protocol | Per Namespace |
|
||||
|---------|-----------|----------|---------------|
|
||||
| SFU signaling | 30000-30099 | TCP (WireGuard only) | 1 port |
|
||||
| SFU media (RTP) | 20000-29999 | UDP (WireGuard only) | 500 ports |
|
||||
| TURN listen | 3478 | UDP + TCP | fixed |
|
||||
| TURNS (TLS) | 5349 | TCP | fixed |
|
||||
| TURN relay | 49152-65535 | UDP | 800 ports |
|
||||
|
||||
## TURN Credential Protocol
|
||||
|
||||
- Credentials use HMAC-SHA1 with a per-namespace shared secret
|
||||
- Username format: `{expiry_unix}:{namespace}`
|
||||
- Password: `base64(HMAC-SHA1(shared_secret, username))`
|
||||
- Default TTL: 600 seconds (10 minutes)
|
||||
- SFU proactively sends `refresh-credentials` at 80% of TTL (8 minutes)
|
||||
- Clients should update ICE servers on receiving refresh
|
||||
|
||||
## TURNS TLS Certificate
|
||||
|
||||
TURNS (port 5349) uses TLS. Certificate provisioning:
|
||||
|
||||
1. **Let's Encrypt (primary)**: On TURN spawn, the TURN domain is added to the local Caddy instance's Caddyfile. Caddy provisions a Let's Encrypt cert via DNS-01 ACME challenge (using the orama DNS provider). TURN reads the cert from Caddy's storage.
|
||||
2. **Self-signed (fallback)**: If Caddy cert provisioning fails (timeout, Caddy not running), a self-signed cert is generated with the node's public IP as SAN.
|
||||
|
||||
Caddy auto-renews Let's Encrypt certs at ~60 days. TURN picks up renewed certs on restart.
|
||||
|
||||
## Monitoring
|
||||
|
||||
```bash
|
||||
# Check WebRTC status
|
||||
orama namespace webrtc-status --namespace myapp
|
||||
|
||||
# Monitor report includes SFU/TURN status
|
||||
orama monitor report --env devnet
|
||||
|
||||
# Inspector checks WebRTC health
|
||||
orama inspector --env devnet
|
||||
```
|
||||
|
||||
The monitoring report includes per-namespace `sfu_up` and `turn_up` fields. The inspector runs cross-node checks to verify SFU coverage (3 nodes) and TURN redundancy (2 nodes).
|
||||
|
||||
## Debugging
|
||||
|
||||
```bash
|
||||
# SFU logs
|
||||
journalctl -u orama-namespace-sfu@myapp -f
|
||||
|
||||
# TURN logs
|
||||
journalctl -u orama-namespace-turn@myapp -f
|
||||
|
||||
# Check service status
|
||||
systemctl status orama-namespace-sfu@myapp
|
||||
systemctl status orama-namespace-turn@myapp
|
||||
```
|
||||
|
||||
## Security Model
|
||||
|
||||
- **Forced relay**: `iceTransportPolicy: relay` enforced server-side. Clients cannot bypass TURN.
|
||||
- **HMAC credentials**: Per-namespace TURN shared secret. Credentials expire after 10 minutes.
|
||||
- **Namespace isolation**: Each namespace has its own TURN secret, port ranges, and rooms.
|
||||
- **Authentication required**: All WebRTC endpoints require API key or JWT (`X-API-Key` header, `Authorization: ApiKey`, or `Authorization: Bearer`).
|
||||
- **Room management**: Creating/closing rooms requires namespace ownership.
|
||||
- **SFU on WireGuard only**: SFU binds to 10.0.0.x, never 0.0.0.0. Only reachable via TURN relay.
|
||||
- **Permissions-Policy**: `camera=(self), microphone=(self)` — only same-origin can access media devices.
|
||||
|
||||
## Firewall
|
||||
|
||||
When WebRTC is enabled, the following ports are opened via UFW on TURN nodes:
|
||||
|
||||
| Port | Protocol | Purpose |
|
||||
|------|----------|---------|
|
||||
| 3478 | UDP | TURN standard |
|
||||
| 3478 | TCP | TURN TCP fallback (for clients behind UDP-blocking firewalls) |
|
||||
| 5349 | TCP | TURNS — TURN over TLS (encrypted, works through strict firewalls/DPI) |
|
||||
| 49152-65535 | UDP | TURN relay range (allocated per namespace) |
|
||||
|
||||
SFU ports are NOT opened in the firewall — they are WireGuard-internal only.
|
||||
|
||||
## Database Tables
|
||||
|
||||
| Table | Purpose |
|
||||
|-------|---------|
|
||||
| `namespace_webrtc_config` | Per-namespace WebRTC config (enabled, TURN secret, node counts) |
|
||||
| `webrtc_rooms` | Room-to-SFU-node affinity |
|
||||
| `webrtc_port_allocations` | SFU/TURN port tracking |
|
||||
|
||||
## Cold Boot Recovery
|
||||
|
||||
On node restart, the cluster state file (`cluster_state.json`) includes `has_sfu`, `has_turn`, and port allocation data. The restore process:
|
||||
|
||||
1. Core services restore first: RQLite → Olric → Gateway
|
||||
2. If `has_turn` is set: fetches TURN shared secret from DB, spawns TURN
|
||||
3. If `has_sfu` is set: fetches WebRTC config from DB, spawns SFU with TURN server list
|
||||
|
||||
If the DB is unavailable during restore, SFU/TURN restoration is skipped with a warning log. They will be restored on the next successful DB connection.
|
||||
556
core/e2e/cluster/namespace_cluster_test.go
Normal file
556
core/e2e/cluster/namespace_cluster_test.go
Normal file
@ -0,0 +1,556 @@
|
||||
//go:build e2e
|
||||
|
||||
package cluster_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// STRICT NAMESPACE CLUSTER TESTS
|
||||
// These tests FAIL if things don't work. No t.Skip() for expected functionality.
|
||||
// =============================================================================
|
||||
|
||||
// TestNamespaceCluster_FullProvisioning is a STRICT test that verifies the complete
|
||||
// namespace cluster provisioning flow. This test FAILS if any component doesn't work.
|
||||
func TestNamespaceCluster_FullProvisioning(t *testing.T) {
|
||||
// Generate unique namespace name
|
||||
newNamespace := fmt.Sprintf("e2e-cluster-%d", time.Now().UnixNano())
|
||||
|
||||
env, err := e2e.LoadTestEnvWithNamespace(newNamespace)
|
||||
require.NoError(t, err, "FATAL: Failed to create test environment for namespace %s", newNamespace)
|
||||
require.NotEmpty(t, env.APIKey, "FATAL: No API key received - namespace provisioning failed")
|
||||
|
||||
t.Logf("Created namespace: %s", newNamespace)
|
||||
t.Logf("API Key: %s...", env.APIKey[:min(20, len(env.APIKey))])
|
||||
|
||||
// Get cluster status to verify provisioning
|
||||
t.Run("Cluster status shows ready", func(t *testing.T) {
|
||||
// Query the namespace cluster status
|
||||
req, _ := http.NewRequest("GET", env.GatewayURL+"/v1/namespace/status?name="+newNamespace, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Failed to query cluster status")
|
||||
defer resp.Body.Close()
|
||||
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Logf("Cluster status response: %s", string(bodyBytes))
|
||||
|
||||
// If status endpoint exists and returns cluster info, verify it
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
var result map[string]interface{}
|
||||
if err := json.Unmarshal(bodyBytes, &result); err == nil {
|
||||
status, _ := result["status"].(string)
|
||||
if status != "" && status != "ready" && status != "default" {
|
||||
t.Errorf("FAIL: Cluster status is '%s', expected 'ready'", status)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Verify we can use the namespace for deployments
|
||||
t.Run("Deployments work on namespace", func(t *testing.T) {
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
if _, err := os.Stat(tarballPath); os.IsNotExist(err) {
|
||||
t.Skip("Test tarball not found - skipping deployment test")
|
||||
}
|
||||
|
||||
deploymentName := fmt.Sprintf("cluster-test-%d", time.Now().Unix())
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID, "FAIL: Deployment creation failed on namespace cluster")
|
||||
|
||||
t.Logf("Created deployment %s (ID: %s) on namespace %s", deploymentName, deploymentID, newNamespace)
|
||||
|
||||
// Cleanup
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
// Verify deployment is accessible
|
||||
req, _ := http.NewRequest("GET", env.GatewayURL+"/v1/deployments/get?id="+deploymentID, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Failed to get deployment")
|
||||
defer resp.Body.Close()
|
||||
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, "FAIL: Cannot retrieve deployment from namespace cluster")
|
||||
})
|
||||
}
|
||||
|
||||
// TestNamespaceCluster_RQLiteHealth verifies that namespace RQLite cluster is running
|
||||
// and accepting connections. This test FAILS if RQLite is not accessible.
|
||||
func TestNamespaceCluster_RQLiteHealth(t *testing.T) {
|
||||
t.Run("Check namespace port range for RQLite", func(t *testing.T) {
|
||||
foundRQLite := false
|
||||
var healthyPorts []int
|
||||
var unhealthyPorts []int
|
||||
|
||||
// Check first few port blocks
|
||||
for portStart := 10000; portStart <= 10015; portStart += 5 {
|
||||
rqlitePort := portStart // RQLite HTTP is first port in block
|
||||
if isPortListening("localhost", rqlitePort) {
|
||||
t.Logf("Found RQLite instance on port %d", rqlitePort)
|
||||
foundRQLite = true
|
||||
|
||||
// Verify it responds to health check
|
||||
healthURL := fmt.Sprintf("http://localhost:%d/status", rqlitePort)
|
||||
healthResp, err := http.Get(healthURL)
|
||||
if err == nil {
|
||||
defer healthResp.Body.Close()
|
||||
if healthResp.StatusCode == http.StatusOK {
|
||||
healthyPorts = append(healthyPorts, rqlitePort)
|
||||
t.Logf(" ✓ RQLite on port %d is healthy", rqlitePort)
|
||||
} else {
|
||||
unhealthyPorts = append(unhealthyPorts, rqlitePort)
|
||||
t.Errorf("FAIL: RQLite on port %d returned status %d", rqlitePort, healthResp.StatusCode)
|
||||
}
|
||||
} else {
|
||||
unhealthyPorts = append(unhealthyPorts, rqlitePort)
|
||||
t.Errorf("FAIL: RQLite on port %d health check failed: %v", rqlitePort, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !foundRQLite {
|
||||
t.Log("No namespace RQLite instances found in port range 10000-10015")
|
||||
t.Log("This is expected if no namespaces have been provisioned yet")
|
||||
} else {
|
||||
t.Logf("Summary: %d healthy, %d unhealthy RQLite instances", len(healthyPorts), len(unhealthyPorts))
|
||||
require.Empty(t, unhealthyPorts, "FAIL: Some RQLite instances are unhealthy")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestNamespaceCluster_OlricHealth verifies that namespace Olric cluster is running
|
||||
// and accepting connections.
|
||||
func TestNamespaceCluster_OlricHealth(t *testing.T) {
|
||||
t.Run("Check namespace port range for Olric", func(t *testing.T) {
|
||||
foundOlric := false
|
||||
foundCount := 0
|
||||
|
||||
// Check first few port blocks - Olric memberlist is port_start + 3
|
||||
for portStart := 10000; portStart <= 10015; portStart += 5 {
|
||||
olricMemberlistPort := portStart + 3
|
||||
if isPortListening("localhost", olricMemberlistPort) {
|
||||
t.Logf("Found Olric memberlist on port %d", olricMemberlistPort)
|
||||
foundOlric = true
|
||||
foundCount++
|
||||
}
|
||||
}
|
||||
|
||||
if !foundOlric {
|
||||
t.Log("No namespace Olric instances found in port range 10003-10018")
|
||||
t.Log("This is expected if no namespaces have been provisioned yet")
|
||||
} else {
|
||||
t.Logf("Found %d Olric memberlist ports accepting connections", foundCount)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestNamespaceCluster_GatewayHealth verifies that namespace Gateway instances are running.
|
||||
// This test FAILS if gateway binary exists but gateways don't spawn.
|
||||
func TestNamespaceCluster_GatewayHealth(t *testing.T) {
|
||||
// Check if gateway binary exists
|
||||
gatewayBinaryPaths := []string{
|
||||
"./bin/orama",
|
||||
"../bin/orama",
|
||||
"/usr/local/bin/orama",
|
||||
}
|
||||
|
||||
var gatewayBinaryExists bool
|
||||
var foundPath string
|
||||
for _, path := range gatewayBinaryPaths {
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
gatewayBinaryExists = true
|
||||
foundPath = path
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !gatewayBinaryExists {
|
||||
t.Log("Gateway binary not found - namespace gateways will not spawn")
|
||||
t.Log("Run 'make build' to build the gateway binary")
|
||||
t.Log("Checked paths:", gatewayBinaryPaths)
|
||||
// This is a FAILURE if we expect gateway to work
|
||||
t.Error("FAIL: Gateway binary not found. Run 'make build' first.")
|
||||
return
|
||||
}
|
||||
|
||||
t.Logf("Gateway binary found at: %s", foundPath)
|
||||
|
||||
t.Run("Check namespace port range for Gateway", func(t *testing.T) {
|
||||
foundGateway := false
|
||||
var healthyPorts []int
|
||||
var unhealthyPorts []int
|
||||
|
||||
// Check first few port blocks - Gateway HTTP is port_start + 4
|
||||
for portStart := 10000; portStart <= 10015; portStart += 5 {
|
||||
gatewayPort := portStart + 4
|
||||
if isPortListening("localhost", gatewayPort) {
|
||||
t.Logf("Found Gateway instance on port %d", gatewayPort)
|
||||
foundGateway = true
|
||||
|
||||
// Verify it responds to health check
|
||||
healthURL := fmt.Sprintf("http://localhost:%d/v1/health", gatewayPort)
|
||||
healthResp, err := http.Get(healthURL)
|
||||
if err == nil {
|
||||
defer healthResp.Body.Close()
|
||||
if healthResp.StatusCode == http.StatusOK {
|
||||
healthyPorts = append(healthyPorts, gatewayPort)
|
||||
t.Logf(" ✓ Gateway on port %d is healthy", gatewayPort)
|
||||
} else {
|
||||
unhealthyPorts = append(unhealthyPorts, gatewayPort)
|
||||
t.Errorf("FAIL: Gateway on port %d returned status %d", gatewayPort, healthResp.StatusCode)
|
||||
}
|
||||
} else {
|
||||
unhealthyPorts = append(unhealthyPorts, gatewayPort)
|
||||
t.Errorf("FAIL: Gateway on port %d health check failed: %v", gatewayPort, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !foundGateway {
|
||||
t.Log("No namespace Gateway instances found in port range 10004-10019")
|
||||
t.Log("This is expected if no namespaces have been provisioned yet")
|
||||
} else {
|
||||
t.Logf("Summary: %d healthy, %d unhealthy Gateway instances", len(healthyPorts), len(unhealthyPorts))
|
||||
require.Empty(t, unhealthyPorts, "FAIL: Some Gateway instances are unhealthy")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestNamespaceCluster_ProvisioningCreatesProcesses creates a new namespace and
|
||||
// verifies that actual processes are spawned. This is the STRICTEST test.
|
||||
func TestNamespaceCluster_ProvisioningCreatesProcesses(t *testing.T) {
|
||||
newNamespace := fmt.Sprintf("e2e-strict-%d", time.Now().UnixNano())
|
||||
|
||||
// Record ports before provisioning
|
||||
portsBefore := getListeningPortsInRange(10000, 10099)
|
||||
t.Logf("Ports in use before provisioning: %v", portsBefore)
|
||||
|
||||
// Create namespace
|
||||
env, err := e2e.LoadTestEnvWithNamespace(newNamespace)
|
||||
require.NoError(t, err, "FATAL: Failed to create namespace")
|
||||
require.NotEmpty(t, env.APIKey, "FATAL: No API key - provisioning failed")
|
||||
|
||||
t.Logf("Namespace '%s' created successfully", newNamespace)
|
||||
|
||||
// Wait a moment for processes to fully start
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
// Record ports after provisioning
|
||||
portsAfter := getListeningPortsInRange(10000, 10099)
|
||||
t.Logf("Ports in use after provisioning: %v", portsAfter)
|
||||
|
||||
// Check if new ports were opened
|
||||
newPorts := diffPorts(portsBefore, portsAfter)
|
||||
sort.Ints(newPorts)
|
||||
t.Logf("New ports opened: %v", newPorts)
|
||||
|
||||
t.Run("New ports allocated for namespace cluster", func(t *testing.T) {
|
||||
if len(newPorts) == 0 {
|
||||
// This might be OK for default namespace or if using global cluster
|
||||
t.Log("No new ports detected")
|
||||
t.Log("Possible reasons:")
|
||||
t.Log(" - Namespace uses default cluster (expected for 'default')")
|
||||
t.Log(" - Cluster already existed from previous test")
|
||||
t.Log(" - Provisioning is handled differently in this environment")
|
||||
} else {
|
||||
t.Logf("SUCCESS: %d new ports opened for namespace cluster", len(newPorts))
|
||||
|
||||
// Verify the ports follow expected pattern
|
||||
for _, port := range newPorts {
|
||||
offset := (port - 10000) % 5
|
||||
switch offset {
|
||||
case 0:
|
||||
t.Logf(" Port %d: RQLite HTTP", port)
|
||||
case 1:
|
||||
t.Logf(" Port %d: RQLite Raft", port)
|
||||
case 2:
|
||||
t.Logf(" Port %d: Olric HTTP", port)
|
||||
case 3:
|
||||
t.Logf(" Port %d: Olric Memberlist", port)
|
||||
case 4:
|
||||
t.Logf(" Port %d: Gateway HTTP", port)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("RQLite is accessible on allocated ports", func(t *testing.T) {
|
||||
rqlitePorts := filterPortsByOffset(newPorts, 0) // RQLite HTTP is offset 0
|
||||
if len(rqlitePorts) == 0 {
|
||||
t.Log("No new RQLite ports detected")
|
||||
return
|
||||
}
|
||||
|
||||
for _, port := range rqlitePorts {
|
||||
healthURL := fmt.Sprintf("http://localhost:%d/status", port)
|
||||
resp, err := http.Get(healthURL)
|
||||
require.NoError(t, err, "FAIL: RQLite on port %d is not responding", port)
|
||||
resp.Body.Close()
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"FAIL: RQLite on port %d returned status %d", port, resp.StatusCode)
|
||||
t.Logf("✓ RQLite on port %d is healthy", port)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Olric is accessible on allocated ports", func(t *testing.T) {
|
||||
olricPorts := filterPortsByOffset(newPorts, 3) // Olric Memberlist is offset 3
|
||||
if len(olricPorts) == 0 {
|
||||
t.Log("No new Olric ports detected")
|
||||
return
|
||||
}
|
||||
|
||||
for _, port := range olricPorts {
|
||||
conn, err := net.DialTimeout("tcp", fmt.Sprintf("localhost:%d", port), 2*time.Second)
|
||||
require.NoError(t, err, "FAIL: Olric memberlist on port %d is not responding", port)
|
||||
conn.Close()
|
||||
t.Logf("✓ Olric memberlist on port %d is accepting connections", port)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestNamespaceCluster_StatusEndpoint tests the /v1/namespace/status endpoint
|
||||
func TestNamespaceCluster_StatusEndpoint(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
t.Run("Status endpoint returns 404 for non-existent cluster", func(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", env.GatewayURL+"/v1/namespace/status?id=non-existent-id", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Request should not fail")
|
||||
defer resp.Body.Close()
|
||||
|
||||
require.Equal(t, http.StatusNotFound, resp.StatusCode,
|
||||
"FAIL: Should return 404 for non-existent cluster, got %d", resp.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
// TestNamespaceCluster_CrossNamespaceAccess verifies namespace isolation
|
||||
func TestNamespaceCluster_CrossNamespaceAccess(t *testing.T) {
|
||||
nsA := fmt.Sprintf("ns-a-%d", time.Now().Unix())
|
||||
nsB := fmt.Sprintf("ns-b-%d", time.Now().Unix())
|
||||
|
||||
envA, err := e2e.LoadTestEnvWithNamespace(nsA)
|
||||
require.NoError(t, err, "FAIL: Cannot create namespace A")
|
||||
|
||||
envB, err := e2e.LoadTestEnvWithNamespace(nsB)
|
||||
require.NoError(t, err, "FAIL: Cannot create namespace B")
|
||||
|
||||
// Verify both namespaces have different API keys
|
||||
require.NotEqual(t, envA.APIKey, envB.APIKey, "FAIL: Namespaces should have different API keys")
|
||||
t.Logf("Namespace A API key: %s...", envA.APIKey[:min(10, len(envA.APIKey))])
|
||||
t.Logf("Namespace B API key: %s...", envB.APIKey[:min(10, len(envB.APIKey))])
|
||||
|
||||
t.Run("API keys are namespace-scoped", func(t *testing.T) {
|
||||
// Namespace A should not see namespace B's resources
|
||||
req, _ := http.NewRequest("GET", envA.GatewayURL+"/v1/deployments/list", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+envA.APIKey)
|
||||
|
||||
resp, err := envA.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Request failed")
|
||||
defer resp.Body.Close()
|
||||
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, "Should list deployments")
|
||||
|
||||
var result map[string]interface{}
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
json.Unmarshal(bodyBytes, &result)
|
||||
|
||||
deployments, _ := result["deployments"].([]interface{})
|
||||
for _, d := range deployments {
|
||||
dep, ok := d.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ns, _ := dep["namespace"].(string)
|
||||
require.NotEqual(t, nsB, ns,
|
||||
"FAIL: Namespace A sees Namespace B deployments - isolation broken!")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestDeployment_SubdomainFormat tests deployment subdomain format
|
||||
func TestDeployment_SubdomainFormat(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
if _, err := os.Stat(tarballPath); os.IsNotExist(err) {
|
||||
t.Skip("Test tarball not found")
|
||||
}
|
||||
|
||||
deploymentName := fmt.Sprintf("subdomain-test-%d", time.Now().UnixNano())
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID, "FAIL: Deployment creation failed")
|
||||
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Deployment has subdomain with random suffix", func(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", env.GatewayURL+"/v1/deployments/get?id="+deploymentID, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Failed to get deployment")
|
||||
defer resp.Body.Close()
|
||||
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, "Should get deployment")
|
||||
|
||||
var result map[string]interface{}
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
json.Unmarshal(bodyBytes, &result)
|
||||
|
||||
deployment, ok := result["deployment"].(map[string]interface{})
|
||||
if !ok {
|
||||
deployment = result
|
||||
}
|
||||
|
||||
subdomain, _ := deployment["subdomain"].(string)
|
||||
if subdomain != "" {
|
||||
require.True(t, strings.HasPrefix(subdomain, deploymentName),
|
||||
"FAIL: Subdomain '%s' should start with deployment name '%s'", subdomain, deploymentName)
|
||||
|
||||
suffix := strings.TrimPrefix(subdomain, deploymentName+"-")
|
||||
if suffix != subdomain { // There was a dash separator
|
||||
require.Equal(t, 6, len(suffix),
|
||||
"FAIL: Random suffix should be 6 characters, got %d (%s)", len(suffix), suffix)
|
||||
}
|
||||
t.Logf("Deployment subdomain: %s", subdomain)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestNamespaceCluster_PortAllocation tests port allocation correctness
|
||||
func TestNamespaceCluster_PortAllocation(t *testing.T) {
|
||||
t.Run("Port range is 10000-10099", func(t *testing.T) {
|
||||
const portRangeStart = 10000
|
||||
const portRangeEnd = 10099
|
||||
const portsPerNamespace = 5
|
||||
const maxNamespacesPerNode = 20
|
||||
|
||||
totalPorts := portRangeEnd - portRangeStart + 1
|
||||
require.Equal(t, 100, totalPorts, "Port range should be 100 ports")
|
||||
|
||||
expectedMax := totalPorts / portsPerNamespace
|
||||
require.Equal(t, maxNamespacesPerNode, expectedMax,
|
||||
"Max namespaces per node calculation mismatch")
|
||||
})
|
||||
|
||||
t.Run("Port assignments are sequential within block", func(t *testing.T) {
|
||||
portStart := 10000
|
||||
ports := map[string]int{
|
||||
"rqlite_http": portStart + 0,
|
||||
"rqlite_raft": portStart + 1,
|
||||
"olric_http": portStart + 2,
|
||||
"olric_memberlist": portStart + 3,
|
||||
"gateway_http": portStart + 4,
|
||||
}
|
||||
|
||||
seen := make(map[int]bool)
|
||||
for name, port := range ports {
|
||||
require.False(t, seen[port], "FAIL: Port %d for %s is duplicate", port, name)
|
||||
seen[port] = true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// HELPER FUNCTIONS
|
||||
// =============================================================================
|
||||
|
||||
func isPortListening(host string, port int) bool {
|
||||
conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", host, port), 1*time.Second)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
conn.Close()
|
||||
return true
|
||||
}
|
||||
|
||||
func getListeningPortsInRange(start, end int) []int {
|
||||
var ports []int
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Check ports concurrently for speed
|
||||
results := make(chan int, end-start+1)
|
||||
for port := start; port <= end; port++ {
|
||||
go func(p int) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
results <- 0
|
||||
return
|
||||
default:
|
||||
if isPortListening("localhost", p) {
|
||||
results <- p
|
||||
} else {
|
||||
results <- 0
|
||||
}
|
||||
}
|
||||
}(port)
|
||||
}
|
||||
|
||||
for i := 0; i <= end-start; i++ {
|
||||
if port := <-results; port > 0 {
|
||||
ports = append(ports, port)
|
||||
}
|
||||
}
|
||||
return ports
|
||||
}
|
||||
|
||||
func diffPorts(before, after []int) []int {
|
||||
beforeMap := make(map[int]bool)
|
||||
for _, p := range before {
|
||||
beforeMap[p] = true
|
||||
}
|
||||
|
||||
var newPorts []int
|
||||
for _, p := range after {
|
||||
if !beforeMap[p] {
|
||||
newPorts = append(newPorts, p)
|
||||
}
|
||||
}
|
||||
return newPorts
|
||||
}
|
||||
|
||||
func filterPortsByOffset(ports []int, offset int) []int {
|
||||
var filtered []int
|
||||
for _, p := range ports {
|
||||
if (p-10000)%5 == offset {
|
||||
filtered = append(filtered, p)
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
447
core/e2e/cluster/namespace_isolation_test.go
Normal file
447
core/e2e/cluster/namespace_isolation_test.go
Normal file
@ -0,0 +1,447 @@
|
||||
//go:build e2e
|
||||
|
||||
package cluster_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestNamespaceIsolation creates two namespaces once and runs all isolation
|
||||
// subtests against them. This keeps namespace usage to 2 regardless of how
|
||||
// many isolation scenarios we test.
|
||||
func TestNamespaceIsolation(t *testing.T) {
|
||||
envA, err := e2e.LoadTestEnvWithNamespace("namespace-a-" + fmt.Sprintf("%d", time.Now().Unix()))
|
||||
require.NoError(t, err, "Failed to create namespace A environment")
|
||||
|
||||
envB, err := e2e.LoadTestEnvWithNamespace("namespace-b-" + fmt.Sprintf("%d", time.Now().Unix()))
|
||||
require.NoError(t, err, "Failed to create namespace B environment")
|
||||
|
||||
t.Run("Deployments", func(t *testing.T) {
|
||||
testNamespaceIsolationDeployments(t, envA, envB)
|
||||
})
|
||||
|
||||
t.Run("SQLiteDatabases", func(t *testing.T) {
|
||||
testNamespaceIsolationSQLiteDatabases(t, envA, envB)
|
||||
})
|
||||
|
||||
t.Run("IPFSContent", func(t *testing.T) {
|
||||
testNamespaceIsolationIPFSContent(t, envA, envB)
|
||||
})
|
||||
|
||||
t.Run("OlricCache", func(t *testing.T) {
|
||||
testNamespaceIsolationOlricCache(t, envA, envB)
|
||||
})
|
||||
}
|
||||
|
||||
func testNamespaceIsolationDeployments(t *testing.T, envA, envB *e2e.E2ETestEnv) {
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
// Create deployment in namespace-a
|
||||
deploymentNameA := "test-app-ns-a"
|
||||
deploymentIDA := e2e.CreateTestDeployment(t, envA, deploymentNameA, tarballPath)
|
||||
defer func() {
|
||||
if !envA.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, envA, deploymentIDA)
|
||||
}
|
||||
}()
|
||||
|
||||
// Create deployment in namespace-b
|
||||
deploymentNameB := "test-app-ns-b"
|
||||
deploymentIDB := e2e.CreateTestDeployment(t, envB, deploymentNameB, tarballPath)
|
||||
defer func() {
|
||||
if !envB.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, envB, deploymentIDB)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Namespace-A cannot list Namespace-B deployments", func(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", envA.GatewayURL+"/v1/deployments/list", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+envA.APIKey)
|
||||
|
||||
resp, err := envA.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result map[string]interface{}
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
require.NoError(t, json.Unmarshal(bodyBytes, &result), "Should decode JSON")
|
||||
|
||||
deployments, ok := result["deployments"].([]interface{})
|
||||
require.True(t, ok, "Deployments should be an array")
|
||||
|
||||
// Should only see namespace-a deployments
|
||||
for _, d := range deployments {
|
||||
dep, ok := d.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
assert.NotEqual(t, deploymentNameB, dep["name"], "Should not see namespace-b deployment")
|
||||
}
|
||||
|
||||
t.Logf("✓ Namespace A cannot see Namespace B deployments")
|
||||
})
|
||||
|
||||
t.Run("Namespace-A cannot access Namespace-B deployment by ID", func(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", envA.GatewayURL+"/v1/deployments/get?id="+deploymentIDB, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+envA.APIKey)
|
||||
|
||||
resp, err := envA.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should return 404 or 403
|
||||
assert.Contains(t, []int{http.StatusNotFound, http.StatusForbidden}, resp.StatusCode,
|
||||
"Should block cross-namespace access")
|
||||
|
||||
t.Logf("✓ Namespace A cannot access Namespace B deployment (status: %d)", resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("Namespace-A cannot delete Namespace-B deployment", func(t *testing.T) {
|
||||
req, _ := http.NewRequest("DELETE", envA.GatewayURL+"/v1/deployments/delete?id="+deploymentIDB, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+envA.APIKey)
|
||||
|
||||
resp, err := envA.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Contains(t, []int{http.StatusNotFound, http.StatusForbidden}, resp.StatusCode,
|
||||
"Should block cross-namespace deletion")
|
||||
|
||||
// Verify deployment still exists for namespace-b
|
||||
req2, _ := http.NewRequest("GET", envB.GatewayURL+"/v1/deployments/get?id="+deploymentIDB, nil)
|
||||
req2.Header.Set("Authorization", "Bearer "+envB.APIKey)
|
||||
|
||||
resp2, err := envB.HTTPClient.Do(req2)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp2.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp2.StatusCode, "Deployment should still exist in namespace B")
|
||||
|
||||
t.Logf("✓ Namespace A cannot delete Namespace B deployment")
|
||||
})
|
||||
}
|
||||
|
||||
func testNamespaceIsolationSQLiteDatabases(t *testing.T, envA, envB *e2e.E2ETestEnv) {
|
||||
// Create database in namespace-a
|
||||
dbNameA := "users-db-a"
|
||||
e2e.CreateSQLiteDB(t, envA, dbNameA)
|
||||
defer func() {
|
||||
if !envA.SkipCleanup {
|
||||
e2e.DeleteSQLiteDB(t, envA, dbNameA)
|
||||
}
|
||||
}()
|
||||
|
||||
// Create database in namespace-b
|
||||
dbNameB := "users-db-b"
|
||||
e2e.CreateSQLiteDB(t, envB, dbNameB)
|
||||
defer func() {
|
||||
if !envB.SkipCleanup {
|
||||
e2e.DeleteSQLiteDB(t, envB, dbNameB)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Namespace-A cannot list Namespace-B databases", func(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", envA.GatewayURL+"/v1/db/sqlite/list", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+envA.APIKey)
|
||||
|
||||
resp, err := envA.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result map[string]interface{}
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
require.NoError(t, json.Unmarshal(bodyBytes, &result), "Should decode JSON")
|
||||
|
||||
databases, ok := result["databases"].([]interface{})
|
||||
require.True(t, ok, "Databases should be an array")
|
||||
|
||||
for _, db := range databases {
|
||||
database, ok := db.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
assert.NotEqual(t, dbNameB, database["database_name"], "Should not see namespace-b database")
|
||||
}
|
||||
|
||||
t.Logf("✓ Namespace A cannot see Namespace B databases")
|
||||
})
|
||||
|
||||
t.Run("Namespace-A cannot query Namespace-B database", func(t *testing.T) {
|
||||
reqBody := map[string]interface{}{
|
||||
"database_name": dbNameB,
|
||||
"query": "SELECT * FROM users",
|
||||
}
|
||||
bodyBytes, _ := json.Marshal(reqBody)
|
||||
|
||||
req, _ := http.NewRequest("POST", envA.GatewayURL+"/v1/db/sqlite/query", bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Authorization", "Bearer "+envA.APIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := envA.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusNotFound, resp.StatusCode, "Should block cross-namespace query")
|
||||
|
||||
t.Logf("✓ Namespace A cannot query Namespace B database")
|
||||
})
|
||||
|
||||
t.Run("Namespace-A cannot backup Namespace-B database", func(t *testing.T) {
|
||||
reqBody := map[string]string{"database_name": dbNameB}
|
||||
bodyBytes, _ := json.Marshal(reqBody)
|
||||
|
||||
req, _ := http.NewRequest("POST", envA.GatewayURL+"/v1/db/sqlite/backup", bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Authorization", "Bearer "+envA.APIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := envA.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusNotFound, resp.StatusCode, "Should block cross-namespace backup")
|
||||
|
||||
t.Logf("✓ Namespace A cannot backup Namespace B database")
|
||||
})
|
||||
}
|
||||
|
||||
func testNamespaceIsolationIPFSContent(t *testing.T, envA, envB *e2e.E2ETestEnv) {
|
||||
// Upload file in namespace-a
|
||||
cidA := e2e.UploadTestFile(t, envA, "test-file-a.txt", "Content from namespace A")
|
||||
defer func() {
|
||||
if !envA.SkipCleanup {
|
||||
e2e.UnpinFile(t, envA, cidA)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Namespace-B cannot GET Namespace-A IPFS content", func(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", envB.GatewayURL+"/v1/storage/get/"+cidA, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+envB.APIKey)
|
||||
|
||||
resp, err := envB.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Contains(t, []int{http.StatusNotFound, http.StatusForbidden}, resp.StatusCode,
|
||||
"Should block cross-namespace IPFS GET")
|
||||
|
||||
t.Logf("✓ Namespace B cannot GET Namespace A IPFS content (status: %d)", resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("Namespace-B cannot PIN Namespace-A IPFS content", func(t *testing.T) {
|
||||
reqBody := map[string]string{
|
||||
"cid": cidA,
|
||||
"name": "stolen-content",
|
||||
}
|
||||
bodyBytes, _ := json.Marshal(reqBody)
|
||||
|
||||
req, _ := http.NewRequest("POST", envB.GatewayURL+"/v1/storage/pin", bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Authorization", "Bearer "+envB.APIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := envB.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Contains(t, []int{http.StatusNotFound, http.StatusForbidden}, resp.StatusCode,
|
||||
"Should block cross-namespace PIN")
|
||||
|
||||
t.Logf("✓ Namespace B cannot PIN Namespace A IPFS content (status: %d)", resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("Namespace-B cannot UNPIN Namespace-A IPFS content", func(t *testing.T) {
|
||||
req, _ := http.NewRequest("DELETE", envB.GatewayURL+"/v1/storage/unpin/"+cidA, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+envB.APIKey)
|
||||
|
||||
resp, err := envB.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Contains(t, []int{http.StatusNotFound, http.StatusForbidden}, resp.StatusCode,
|
||||
"Should block cross-namespace UNPIN")
|
||||
|
||||
t.Logf("✓ Namespace B cannot UNPIN Namespace A IPFS content (status: %d)", resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("Namespace-A can list only their own IPFS pins", func(t *testing.T) {
|
||||
t.Skip("List pins endpoint not implemented yet - namespace isolation enforced at GET/PIN/UNPIN levels")
|
||||
})
|
||||
}
|
||||
|
||||
func testNamespaceIsolationOlricCache(t *testing.T, envA, envB *e2e.E2ETestEnv) {
|
||||
dmap := "test-cache"
|
||||
keyA := "user-session-123"
|
||||
valueA := `{"user_id": "alice", "token": "secret-token-a"}`
|
||||
|
||||
t.Run("Namespace-A sets cache key", func(t *testing.T) {
|
||||
reqBody := map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": keyA,
|
||||
"value": valueA,
|
||||
"ttl": "300s",
|
||||
}
|
||||
bodyBytes, _ := json.Marshal(reqBody)
|
||||
|
||||
req, _ := http.NewRequest("POST", envA.GatewayURL+"/v1/cache/put", bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Authorization", "Bearer "+envA.APIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := envA.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "Should set cache key successfully")
|
||||
|
||||
t.Logf("✓ Namespace A set cache key")
|
||||
})
|
||||
|
||||
t.Run("Namespace-B cannot GET Namespace-A cache key", func(t *testing.T) {
|
||||
reqBody := map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": keyA,
|
||||
}
|
||||
bodyBytes, _ := json.Marshal(reqBody)
|
||||
|
||||
req, _ := http.NewRequest("POST", envB.GatewayURL+"/v1/cache/get", bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Authorization", "Bearer "+envB.APIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := envB.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should return 404 (key doesn't exist in namespace-b)
|
||||
assert.Equal(t, http.StatusNotFound, resp.StatusCode, "Should not find key in different namespace")
|
||||
|
||||
t.Logf("✓ Namespace B cannot GET Namespace A cache key")
|
||||
})
|
||||
|
||||
t.Run("Namespace-B cannot DELETE Namespace-A cache key", func(t *testing.T) {
|
||||
reqBody := map[string]string{
|
||||
"dmap": dmap,
|
||||
"key": keyA,
|
||||
}
|
||||
bodyBytes, _ := json.Marshal(reqBody)
|
||||
|
||||
req, _ := http.NewRequest("POST", envB.GatewayURL+"/v1/cache/delete", bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Authorization", "Bearer "+envB.APIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := envB.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Contains(t, []int{http.StatusOK, http.StatusNotFound}, resp.StatusCode)
|
||||
|
||||
// Verify key still exists for namespace-a
|
||||
reqBody2 := map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": keyA,
|
||||
}
|
||||
bodyBytes2, _ := json.Marshal(reqBody2)
|
||||
|
||||
req2, _ := http.NewRequest("POST", envA.GatewayURL+"/v1/cache/get", bytes.NewReader(bodyBytes2))
|
||||
req2.Header.Set("Authorization", "Bearer "+envA.APIKey)
|
||||
req2.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp2, err := envA.HTTPClient.Do(req2)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp2.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp2.StatusCode, "Key should still exist in namespace A")
|
||||
|
||||
var result map[string]interface{}
|
||||
bodyBytes3, _ := io.ReadAll(resp2.Body)
|
||||
require.NoError(t, json.Unmarshal(bodyBytes3, &result), "Should decode result")
|
||||
|
||||
// Parse expected JSON string for comparison
|
||||
var expectedValue map[string]interface{}
|
||||
json.Unmarshal([]byte(valueA), &expectedValue)
|
||||
assert.Equal(t, expectedValue, result["value"], "Value should match")
|
||||
|
||||
t.Logf("✓ Namespace B cannot DELETE Namespace A cache key")
|
||||
})
|
||||
|
||||
t.Run("Namespace-B can set same key name in their namespace", func(t *testing.T) {
|
||||
// Same key name, different namespace should be allowed
|
||||
valueB := `{"user_id": "bob", "token": "secret-token-b"}`
|
||||
|
||||
reqBody := map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": keyA, // Same key name as namespace-a
|
||||
"value": valueB,
|
||||
"ttl": "300s",
|
||||
}
|
||||
bodyBytes, _ := json.Marshal(reqBody)
|
||||
|
||||
req, _ := http.NewRequest("POST", envB.GatewayURL+"/v1/cache/put", bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Authorization", "Bearer "+envB.APIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := envB.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "Should set key in namespace B")
|
||||
|
||||
// Verify namespace-a still has their value
|
||||
reqBody2 := map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": keyA,
|
||||
}
|
||||
bodyBytes2, _ := json.Marshal(reqBody2)
|
||||
|
||||
req2, _ := http.NewRequest("POST", envA.GatewayURL+"/v1/cache/get", bytes.NewReader(bodyBytes2))
|
||||
req2.Header.Set("Authorization", "Bearer "+envA.APIKey)
|
||||
req2.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp2, _ := envA.HTTPClient.Do(req2)
|
||||
defer resp2.Body.Close()
|
||||
|
||||
var resultA map[string]interface{}
|
||||
bodyBytesA, _ := io.ReadAll(resp2.Body)
|
||||
require.NoError(t, json.Unmarshal(bodyBytesA, &resultA), "Should decode result A")
|
||||
|
||||
// Parse expected JSON string for comparison
|
||||
var expectedValueA map[string]interface{}
|
||||
json.Unmarshal([]byte(valueA), &expectedValueA)
|
||||
assert.Equal(t, expectedValueA, resultA["value"], "Namespace A value should be unchanged")
|
||||
|
||||
// Verify namespace-b has their different value
|
||||
reqBody3 := map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": keyA,
|
||||
}
|
||||
bodyBytes3, _ := json.Marshal(reqBody3)
|
||||
|
||||
req3, _ := http.NewRequest("POST", envB.GatewayURL+"/v1/cache/get", bytes.NewReader(bodyBytes3))
|
||||
req3.Header.Set("Authorization", "Bearer "+envB.APIKey)
|
||||
req3.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp3, _ := envB.HTTPClient.Do(req3)
|
||||
defer resp3.Body.Close()
|
||||
|
||||
var resultB map[string]interface{}
|
||||
bodyBytesB, _ := io.ReadAll(resp3.Body)
|
||||
require.NoError(t, json.Unmarshal(bodyBytesB, &resultB), "Should decode result B")
|
||||
|
||||
// Parse expected JSON string for comparison
|
||||
var expectedValueB map[string]interface{}
|
||||
json.Unmarshal([]byte(valueB), &expectedValueB)
|
||||
assert.Equal(t, expectedValueB, resultB["value"], "Namespace B value should be different")
|
||||
|
||||
t.Logf("✓ Namespace B can set same key name independently")
|
||||
t.Logf(" - Namespace A value: %s", valueA)
|
||||
t.Logf(" - Namespace B value: %s", valueB)
|
||||
})
|
||||
}
|
||||
177
core/e2e/cluster/rqlite_failover_test.go
Normal file
177
core/e2e/cluster/rqlite_failover_test.go
Normal file
@ -0,0 +1,177 @@
|
||||
//go:build e2e
|
||||
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestRQLite_ReadConsistencyLevels tests that different consistency levels work.
|
||||
func TestRQLite_ReadConsistencyLevels(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
gatewayURL := e2e.GetGatewayURL()
|
||||
table := e2e.GenerateTableName()
|
||||
|
||||
defer func() {
|
||||
dropReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: gatewayURL + "/v1/rqlite/drop-table",
|
||||
Body: map[string]interface{}{"table": table},
|
||||
}
|
||||
dropReq.Do(context.Background())
|
||||
}()
|
||||
|
||||
// Create table
|
||||
createReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: gatewayURL + "/v1/rqlite/create-table",
|
||||
Body: map[string]interface{}{
|
||||
"schema": fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT)", table),
|
||||
},
|
||||
}
|
||||
_, status, err := createReq.Do(ctx)
|
||||
require.NoError(t, err)
|
||||
require.True(t, status == http.StatusOK || status == http.StatusCreated, "create table got %d", status)
|
||||
|
||||
// Insert data
|
||||
insertReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: gatewayURL + "/v1/rqlite/transaction",
|
||||
Body: map[string]interface{}{
|
||||
"statements": []string{
|
||||
fmt.Sprintf("INSERT INTO %s(val) VALUES ('consistency-test')", table),
|
||||
},
|
||||
},
|
||||
}
|
||||
_, status, err = insertReq.Do(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
|
||||
t.Run("Default consistency read", func(t *testing.T) {
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: gatewayURL + "/v1/rqlite/query",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT * FROM %s", table),
|
||||
},
|
||||
}
|
||||
body, status, err := queryReq.Do(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
t.Logf("Default read: %s", string(body))
|
||||
})
|
||||
|
||||
t.Run("Strong consistency read", func(t *testing.T) {
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: gatewayURL + "/v1/rqlite/query?level=strong",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT * FROM %s", table),
|
||||
},
|
||||
}
|
||||
body, status, err := queryReq.Do(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
t.Logf("Strong read: %s", string(body))
|
||||
})
|
||||
|
||||
t.Run("Weak consistency read", func(t *testing.T) {
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: gatewayURL + "/v1/rqlite/query?level=weak",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT * FROM %s", table),
|
||||
},
|
||||
}
|
||||
body, status, err := queryReq.Do(ctx)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
t.Logf("Weak read: %s", string(body))
|
||||
})
|
||||
}
|
||||
|
||||
// TestRQLite_WriteAfterMultipleReads verifies write-read cycles stay consistent.
|
||||
func TestRQLite_WriteAfterMultipleReads(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
gatewayURL := e2e.GetGatewayURL()
|
||||
table := e2e.GenerateTableName()
|
||||
|
||||
defer func() {
|
||||
dropReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: gatewayURL + "/v1/rqlite/drop-table",
|
||||
Body: map[string]interface{}{"table": table},
|
||||
}
|
||||
dropReq.Do(context.Background())
|
||||
}()
|
||||
|
||||
createReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: gatewayURL + "/v1/rqlite/create-table",
|
||||
Body: map[string]interface{}{
|
||||
"schema": fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY AUTOINCREMENT, counter INTEGER DEFAULT 0)", table),
|
||||
},
|
||||
}
|
||||
_, status, err := createReq.Do(ctx)
|
||||
require.NoError(t, err)
|
||||
require.True(t, status == http.StatusOK || status == http.StatusCreated)
|
||||
|
||||
// Write-read cycle 10 times
|
||||
for i := 1; i <= 10; i++ {
|
||||
insertReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: gatewayURL + "/v1/rqlite/transaction",
|
||||
Body: map[string]interface{}{
|
||||
"statements": []string{
|
||||
fmt.Sprintf("INSERT INTO %s(counter) VALUES (%d)", table, i),
|
||||
},
|
||||
},
|
||||
}
|
||||
_, status, err := insertReq.Do(ctx)
|
||||
require.NoError(t, err, "insert %d failed", i)
|
||||
require.Equal(t, http.StatusOK, status, "insert %d got status %d", i, status)
|
||||
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: gatewayURL + "/v1/rqlite/query",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT COUNT(*) as cnt FROM %s", table),
|
||||
},
|
||||
}
|
||||
body, _, _ := queryReq.Do(ctx)
|
||||
t.Logf("Iteration %d: %s", i, string(body))
|
||||
}
|
||||
|
||||
// Final verification
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: gatewayURL + "/v1/rqlite/query",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT COUNT(*) as cnt FROM %s", table),
|
||||
},
|
||||
}
|
||||
body, status, err := queryReq.Do(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusOK, status)
|
||||
|
||||
var result map[string]interface{}
|
||||
json.Unmarshal(body, &result)
|
||||
t.Logf("Final count result: %s", string(body))
|
||||
}
|
||||
147
core/e2e/config.go
Normal file
147
core/e2e/config.go
Normal file
@ -0,0 +1,147 @@
|
||||
//go:build e2e
|
||||
|
||||
package e2e
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
// E2EConfig holds the configuration for E2E tests
|
||||
type E2EConfig struct {
|
||||
// Mode can be "local" or "production"
|
||||
Mode string `yaml:"mode"`
|
||||
|
||||
// BaseDomain is the domain used for deployment routing (e.g., "dbrs.space" or "orama.network")
|
||||
BaseDomain string `yaml:"base_domain"`
|
||||
|
||||
// Servers is a list of production servers (only used when mode=production)
|
||||
Servers []ServerConfig `yaml:"servers"`
|
||||
|
||||
// Nameservers is a list of nameserver hostnames (e.g., ["ns1.dbrs.space", "ns2.dbrs.space"])
|
||||
Nameservers []string `yaml:"nameservers"`
|
||||
|
||||
// APIKey is the API key for production testing (auto-discovered if empty)
|
||||
APIKey string `yaml:"api_key"`
|
||||
}
|
||||
|
||||
// ServerConfig holds configuration for a single production server
|
||||
type ServerConfig struct {
|
||||
Name string `yaml:"name"`
|
||||
IP string `yaml:"ip"`
|
||||
User string `yaml:"user"`
|
||||
Password string `yaml:"password"`
|
||||
IsNameserver bool `yaml:"is_nameserver"`
|
||||
}
|
||||
|
||||
// DefaultConfig returns the default configuration
|
||||
func DefaultConfig() *E2EConfig {
|
||||
return &E2EConfig{
|
||||
Mode: "production",
|
||||
BaseDomain: "orama.network",
|
||||
Servers: []ServerConfig{},
|
||||
Nameservers: []string{},
|
||||
APIKey: "",
|
||||
}
|
||||
}
|
||||
|
||||
// LoadE2EConfig loads the E2E test configuration from e2e/config.yaml
|
||||
// Falls back to defaults if the file doesn't exist
|
||||
func LoadE2EConfig() (*E2EConfig, error) {
|
||||
// Try multiple locations for the config file
|
||||
configPaths := []string{
|
||||
"config.yaml", // Relative to e2e directory (when running from e2e/)
|
||||
"e2e/config.yaml", // Relative to project root
|
||||
"../e2e/config.yaml", // From subdirectory within e2e/
|
||||
}
|
||||
|
||||
// Also try absolute path based on working directory
|
||||
if cwd, err := os.Getwd(); err == nil {
|
||||
configPaths = append(configPaths, filepath.Join(cwd, "config.yaml"))
|
||||
configPaths = append(configPaths, filepath.Join(cwd, "e2e", "config.yaml"))
|
||||
// Go up one level if we're in a subdirectory
|
||||
configPaths = append(configPaths, filepath.Join(cwd, "..", "config.yaml"))
|
||||
}
|
||||
|
||||
var configData []byte
|
||||
var readErr error
|
||||
|
||||
for _, path := range configPaths {
|
||||
data, err := os.ReadFile(path)
|
||||
if err == nil {
|
||||
configData = data
|
||||
break
|
||||
}
|
||||
readErr = err
|
||||
}
|
||||
|
||||
// If no config file found, return defaults
|
||||
if configData == nil {
|
||||
// Check if running in production mode via environment variable
|
||||
if os.Getenv("E2E_MODE") == "production" {
|
||||
return nil, readErr // Config file required for production mode
|
||||
}
|
||||
return DefaultConfig(), nil
|
||||
}
|
||||
|
||||
var cfg E2EConfig
|
||||
if err := yaml.Unmarshal(configData, &cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Apply defaults for empty values
|
||||
if cfg.Mode == "" {
|
||||
cfg.Mode = "production"
|
||||
}
|
||||
if cfg.BaseDomain == "" {
|
||||
cfg.BaseDomain = "orama.network"
|
||||
}
|
||||
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
// IsProductionMode returns true if running in production mode
|
||||
func IsProductionMode() bool {
|
||||
// Check environment variable first
|
||||
if os.Getenv("E2E_MODE") == "production" {
|
||||
return true
|
||||
}
|
||||
|
||||
cfg, err := LoadE2EConfig()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return cfg.Mode == "production"
|
||||
}
|
||||
|
||||
// GetServerIPs returns a list of all server IP addresses from config
|
||||
func GetServerIPs(cfg *E2EConfig) []string {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
ips := make([]string, 0, len(cfg.Servers))
|
||||
for _, server := range cfg.Servers {
|
||||
if server.IP != "" {
|
||||
ips = append(ips, server.IP)
|
||||
}
|
||||
}
|
||||
return ips
|
||||
}
|
||||
|
||||
// GetNameserverServers returns servers configured as nameservers
|
||||
func GetNameserverServers(cfg *E2EConfig) []ServerConfig {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var nameservers []ServerConfig
|
||||
for _, server := range cfg.Servers {
|
||||
if server.IsNameserver {
|
||||
nameservers = append(nameservers, server)
|
||||
}
|
||||
}
|
||||
return nameservers
|
||||
}
|
||||
45
core/e2e/config.yaml.example
Normal file
45
core/e2e/config.yaml.example
Normal file
@ -0,0 +1,45 @@
|
||||
# E2E Test Configuration
|
||||
#
|
||||
# Copy this file to config.yaml and fill in your values.
|
||||
# config.yaml is git-ignored and should contain your actual credentials.
|
||||
#
|
||||
# Usage:
|
||||
# cp config.yaml.example config.yaml
|
||||
# # Edit config.yaml with your server credentials
|
||||
# go test -v -tags e2e ./e2e/...
|
||||
|
||||
# Test mode: "local" or "production"
|
||||
# - local: Tests run against `make dev` cluster on localhost
|
||||
# - production: Tests run against real VPS servers
|
||||
mode: local
|
||||
|
||||
# Base domain for deployment routing
|
||||
# - Local: orama.network (default)
|
||||
# - Production: dbrs.space (or your custom domain)
|
||||
base_domain: orama.network
|
||||
|
||||
# Production servers (only used when mode=production)
|
||||
# Add your VPS servers here with their credentials
|
||||
servers:
|
||||
# Example:
|
||||
# - name: vps-1
|
||||
# ip: 1.2.3.4
|
||||
# user: ubuntu
|
||||
# password: "your-password-here"
|
||||
# is_nameserver: true
|
||||
# - name: vps-2
|
||||
# ip: 5.6.7.8
|
||||
# user: ubuntu
|
||||
# password: "another-password"
|
||||
# is_nameserver: false
|
||||
|
||||
# Nameserver hostnames (for DNS tests in production)
|
||||
# These should match your NS records
|
||||
nameservers:
|
||||
# Example:
|
||||
# - ns1.yourdomain.com
|
||||
# - ns2.yourdomain.com
|
||||
|
||||
# API key for production testing
|
||||
# Leave empty to auto-discover from RQLite or create fresh key
|
||||
api_key: ""
|
||||
223
core/e2e/deployments/edge_cases_test.go
Normal file
223
core/e2e/deployments/edge_cases_test.go
Normal file
@ -0,0 +1,223 @@
|
||||
//go:build e2e
|
||||
|
||||
package deployments_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestDeploy_InvalidTarball verifies that uploading an invalid/corrupt tarball
|
||||
// returns a clean error (not a 500 or panic).
|
||||
func TestDeploy_InvalidTarball(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err)
|
||||
|
||||
deploymentName := fmt.Sprintf("invalid-tar-%d", time.Now().Unix())
|
||||
|
||||
body := &bytes.Buffer{}
|
||||
boundary := "----WebKitFormBoundary7MA4YWxkTrZu0gW"
|
||||
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"name\"\r\n\r\n")
|
||||
body.WriteString(deploymentName + "\r\n")
|
||||
|
||||
// Write invalid tarball data (random bytes, not a real gzip)
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"tarball\"; filename=\"app.tar.gz\"\r\n")
|
||||
body.WriteString("Content-Type: application/gzip\r\n\r\n")
|
||||
body.WriteString("this is not a valid tarball content at all!!!")
|
||||
body.WriteString("\r\n--" + boundary + "--\r\n")
|
||||
|
||||
req, err := http.NewRequest("POST", env.GatewayURL+"/v1/deployments/static/upload", body)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
t.Logf("Status: %d, Body: %s", resp.StatusCode, string(respBody))
|
||||
|
||||
// Should return an error, not 2xx (ideally 400, but server currently returns 500)
|
||||
assert.True(t, resp.StatusCode >= 400,
|
||||
"Invalid tarball should return error (got %d)", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestDeploy_EmptyTarball verifies that uploading an empty file returns an error.
|
||||
func TestDeploy_EmptyTarball(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err)
|
||||
|
||||
deploymentName := fmt.Sprintf("empty-tar-%d", time.Now().Unix())
|
||||
|
||||
body := &bytes.Buffer{}
|
||||
boundary := "----WebKitFormBoundary7MA4YWxkTrZu0gW"
|
||||
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"name\"\r\n\r\n")
|
||||
body.WriteString(deploymentName + "\r\n")
|
||||
|
||||
// Empty tarball
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"tarball\"; filename=\"app.tar.gz\"\r\n")
|
||||
body.WriteString("Content-Type: application/gzip\r\n\r\n")
|
||||
body.WriteString("\r\n--" + boundary + "--\r\n")
|
||||
|
||||
req, err := http.NewRequest("POST", env.GatewayURL+"/v1/deployments/static/upload", body)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(resp.Body)
|
||||
t.Logf("Status: %d, Body: %s", resp.StatusCode, string(respBody))
|
||||
|
||||
assert.True(t, resp.StatusCode >= 400,
|
||||
"Empty tarball should return error (got %d)", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestDeploy_MissingName verifies that deploying without a name returns an error.
|
||||
func TestDeploy_MissingName(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err)
|
||||
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
body := &bytes.Buffer{}
|
||||
boundary := "----WebKitFormBoundary7MA4YWxkTrZu0gW"
|
||||
|
||||
// No name field
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"tarball\"; filename=\"app.tar.gz\"\r\n")
|
||||
body.WriteString("Content-Type: application/gzip\r\n\r\n")
|
||||
|
||||
// Create tarball from directory for the "no name" test
|
||||
tarData, err := exec.Command("tar", "-czf", "-", "-C", tarballPath, ".").Output()
|
||||
if err != nil {
|
||||
t.Skip("Failed to create tarball from test app")
|
||||
}
|
||||
body.Write(tarData)
|
||||
body.WriteString("\r\n--" + boundary + "--\r\n")
|
||||
|
||||
req, err := http.NewRequest("POST", env.GatewayURL+"/v1/deployments/static/upload", body)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode >= 400,
|
||||
"Missing name should return error (got %d)", resp.StatusCode)
|
||||
}
|
||||
|
||||
// TestDeploy_ConcurrentSameName verifies that deploying two apps with the same
|
||||
// name concurrently doesn't cause data corruption.
|
||||
func TestDeploy_ConcurrentSameName(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err)
|
||||
|
||||
deploymentName := fmt.Sprintf("concurrent-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
var wg sync.WaitGroup
|
||||
results := make([]int, 2)
|
||||
ids := make([]string, 2)
|
||||
|
||||
// Pre-create tarball once for both goroutines
|
||||
tarData, err := exec.Command("tar", "-czf", "-", "-C", tarballPath, ".").Output()
|
||||
if err != nil {
|
||||
t.Skip("Failed to create tarball from test app")
|
||||
}
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
wg.Add(1)
|
||||
go func(idx int) {
|
||||
defer wg.Done()
|
||||
|
||||
body := &bytes.Buffer{}
|
||||
boundary := "----WebKitFormBoundary7MA4YWxkTrZu0gW"
|
||||
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"name\"\r\n\r\n")
|
||||
body.WriteString(deploymentName + "\r\n")
|
||||
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"tarball\"; filename=\"app.tar.gz\"\r\n")
|
||||
body.WriteString("Content-Type: application/gzip\r\n\r\n")
|
||||
body.Write(tarData)
|
||||
body.WriteString("\r\n--" + boundary + "--\r\n")
|
||||
|
||||
req, _ := http.NewRequest("POST", env.GatewayURL+"/v1/deployments/static/upload", body)
|
||||
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
results[idx] = resp.StatusCode
|
||||
|
||||
var result map[string]interface{}
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
if id, ok := result["deployment_id"].(string); ok {
|
||||
ids[idx] = id
|
||||
} else if id, ok := result["id"].(string); ok {
|
||||
ids[idx] = id
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
t.Logf("Concurrent deploy results: status1=%d status2=%d id1=%s id2=%s",
|
||||
results[0], results[1], ids[0], ids[1])
|
||||
|
||||
// At least one should succeed
|
||||
successCount := 0
|
||||
for _, status := range results {
|
||||
if status == http.StatusCreated {
|
||||
successCount++
|
||||
}
|
||||
}
|
||||
assert.GreaterOrEqual(t, successCount, 1,
|
||||
"At least one concurrent deploy should succeed")
|
||||
|
||||
// Cleanup
|
||||
for _, id := range ids {
|
||||
if id != "" {
|
||||
e2e.DeleteDeployment(t, env, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readFileBytes(path string) ([]byte, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
return io.ReadAll(f)
|
||||
}
|
||||
308
core/e2e/deployments/go_sqlite_test.go
Normal file
308
core/e2e/deployments/go_sqlite_test.go
Normal file
@ -0,0 +1,308 @@
|
||||
//go:build e2e
|
||||
|
||||
package deployments_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestGoBackendWithSQLite tests Go backend deployment with hosted SQLite connectivity
|
||||
// 1. Create hosted SQLite database
|
||||
// 2. Deploy Go backend with DATABASE_NAME env var
|
||||
// 3. POST /api/users → verify insert
|
||||
// 4. GET /api/users → verify read
|
||||
// 5. Cleanup
|
||||
func TestGoBackendWithSQLite(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("go-sqlite-test-%d", time.Now().Unix())
|
||||
dbName := fmt.Sprintf("test-db-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/go-api")
|
||||
var deploymentID string
|
||||
|
||||
// Cleanup after test
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
if deploymentID != "" {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
// Delete the test database
|
||||
deleteSQLiteDB(t, env, dbName)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Create SQLite database", func(t *testing.T) {
|
||||
e2e.CreateSQLiteDB(t, env, dbName)
|
||||
t.Logf("Created database: %s", dbName)
|
||||
})
|
||||
|
||||
t.Run("Deploy Go backend with DATABASE_NAME", func(t *testing.T) {
|
||||
deploymentID = createGoDeployment(t, env, deploymentName, tarballPath, map[string]string{
|
||||
"DATABASE_NAME": dbName,
|
||||
"GATEWAY_URL": env.GatewayURL,
|
||||
"API_KEY": env.APIKey,
|
||||
})
|
||||
require.NotEmpty(t, deploymentID, "Deployment ID should not be empty")
|
||||
t.Logf("Created Go deployment: %s (ID: %s)", deploymentName, deploymentID)
|
||||
})
|
||||
|
||||
t.Run("Wait for deployment to become healthy", func(t *testing.T) {
|
||||
healthy := e2e.WaitForHealthy(t, env, deploymentID, 90*time.Second)
|
||||
require.True(t, healthy, "Deployment should become healthy")
|
||||
t.Logf("Deployment is healthy")
|
||||
})
|
||||
|
||||
t.Run("Test health endpoint", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
|
||||
domain := extractDomain(nodeURL)
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/health")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "Health check should return 200")
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
var health map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(body, &health))
|
||||
|
||||
assert.Contains(t, []string{"healthy", "ok"}, health["status"])
|
||||
t.Logf("Health response: %+v", health)
|
||||
})
|
||||
|
||||
t.Run("POST /api/notes - create note", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
|
||||
domain := extractDomain(nodeURL)
|
||||
|
||||
noteData := map[string]string{
|
||||
"title": "Test Note",
|
||||
"content": "This is a test note",
|
||||
}
|
||||
body, _ := json.Marshal(noteData)
|
||||
|
||||
req, err := http.NewRequest("POST", env.GatewayURL+"/api/notes", bytes.NewBuffer(body))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Host = domain
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusCreated, resp.StatusCode, "Should create note successfully")
|
||||
|
||||
var note map[string]interface{}
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(¬e))
|
||||
|
||||
assert.Equal(t, "Test Note", note["title"])
|
||||
assert.Equal(t, "This is a test note", note["content"])
|
||||
t.Logf("Created note: %+v", note)
|
||||
})
|
||||
|
||||
t.Run("GET /api/notes - list notes", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
|
||||
domain := extractDomain(nodeURL)
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/api/notes")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var notes []map[string]interface{}
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(¬es))
|
||||
|
||||
assert.GreaterOrEqual(t, len(notes), 1, "Should have at least one note")
|
||||
|
||||
found := false
|
||||
for _, note := range notes {
|
||||
if note["title"] == "Test Note" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
assert.True(t, found, "Test note should be in the list")
|
||||
t.Logf("Notes count: %d", len(notes))
|
||||
})
|
||||
|
||||
t.Run("DELETE /api/notes - delete note", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
|
||||
domain := extractDomain(nodeURL)
|
||||
|
||||
// First get the note ID
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/api/notes")
|
||||
defer resp.Body.Close()
|
||||
|
||||
var notes []map[string]interface{}
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(¬es))
|
||||
|
||||
var noteID int
|
||||
for _, note := range notes {
|
||||
if note["title"] == "Test Note" {
|
||||
noteID = int(note["id"].(float64))
|
||||
break
|
||||
}
|
||||
}
|
||||
require.NotZero(t, noteID, "Should find test note ID")
|
||||
|
||||
req, err := http.NewRequest("DELETE", fmt.Sprintf("%s/api/notes/%d", env.GatewayURL, noteID), nil)
|
||||
require.NoError(t, err)
|
||||
req.Host = domain
|
||||
|
||||
deleteResp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer deleteResp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, deleteResp.StatusCode, "Should delete note successfully")
|
||||
t.Logf("Deleted note ID: %d", noteID)
|
||||
})
|
||||
}
|
||||
|
||||
// createGoDeployment creates a Go backend deployment with environment variables
|
||||
func createGoDeployment(t *testing.T, env *e2e.E2ETestEnv, name, tarballPath string, envVars map[string]string) string {
|
||||
t.Helper()
|
||||
|
||||
var fileData []byte
|
||||
info, err := os.Stat(tarballPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to stat tarball path: %v", err)
|
||||
}
|
||||
if info.IsDir() {
|
||||
// Build Go binary for linux/amd64, then tar it
|
||||
tmpDir, err := os.MkdirTemp("", "go-deploy-*")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create temp dir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
binaryPath := filepath.Join(tmpDir, "app")
|
||||
buildCmd := exec.Command("go", "build", "-o", binaryPath, ".")
|
||||
buildCmd.Dir = tarballPath
|
||||
buildCmd.Env = append(os.Environ(), "GOOS=linux", "GOARCH=amd64", "CGO_ENABLED=0")
|
||||
if out, err := buildCmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("failed to build Go app: %v\n%s", err, string(out))
|
||||
}
|
||||
|
||||
fileData, err = exec.Command("tar", "-czf", "-", "-C", tmpDir, ".").Output()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create tarball: %v", err)
|
||||
}
|
||||
} else {
|
||||
file, err := os.Open(tarballPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open tarball: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
fileData, _ = io.ReadAll(file)
|
||||
}
|
||||
|
||||
// Create multipart form
|
||||
body := &bytes.Buffer{}
|
||||
boundary := "----WebKitFormBoundary7MA4YWxkTrZu0gW"
|
||||
|
||||
// Write name field
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"name\"\r\n\r\n")
|
||||
body.WriteString(name + "\r\n")
|
||||
|
||||
// Write environment variables
|
||||
for key, value := range envVars {
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString(fmt.Sprintf("Content-Disposition: form-data; name=\"env_%s\"\r\n\r\n", key))
|
||||
body.WriteString(value + "\r\n")
|
||||
}
|
||||
|
||||
// Write tarball file
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"tarball\"; filename=\"app.tar.gz\"\r\n")
|
||||
body.WriteString("Content-Type: application/gzip\r\n\r\n")
|
||||
|
||||
body.Write(fileData)
|
||||
body.WriteString("\r\n--" + boundary + "--\r\n")
|
||||
|
||||
req, err := http.NewRequest("POST", env.GatewayURL+"/v1/deployments/go/upload", body)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to execute request: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("Deployment upload failed with status %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if id, ok := result["deployment_id"].(string); ok {
|
||||
return id
|
||||
}
|
||||
if id, ok := result["id"].(string); ok {
|
||||
return id
|
||||
}
|
||||
t.Fatalf("Deployment response missing id field: %+v", result)
|
||||
return ""
|
||||
}
|
||||
|
||||
// deleteSQLiteDB deletes a SQLite database
|
||||
func deleteSQLiteDB(t *testing.T, env *e2e.E2ETestEnv, dbName string) {
|
||||
t.Helper()
|
||||
|
||||
req, err := http.NewRequest("DELETE", env.GatewayURL+"/v1/db/"+dbName, nil)
|
||||
if err != nil {
|
||||
t.Logf("warning: failed to create delete request: %v", err)
|
||||
return
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
t.Logf("warning: failed to delete database: %v", err)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Logf("warning: delete database returned status %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
264
core/e2e/deployments/nextjs_ssr_test.go
Normal file
264
core/e2e/deployments/nextjs_ssr_test.go
Normal file
@ -0,0 +1,264 @@
|
||||
//go:build e2e
|
||||
|
||||
package deployments_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestNextJSDeployment_SSR tests Next.js deployment with SSR and API routes
|
||||
// 1. Deploy Next.js app
|
||||
// 2. Test SSR page (verify server-rendered HTML)
|
||||
// 3. Test API routes (/api/hello, /api/data)
|
||||
// 4. Test static assets
|
||||
// 5. Cleanup
|
||||
func TestNextJSDeployment_SSR(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("nextjs-ssr-test-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/nextjs-ssr.tar.gz")
|
||||
var deploymentID string
|
||||
|
||||
// Check if tarball exists
|
||||
if _, err := os.Stat(tarballPath); os.IsNotExist(err) {
|
||||
t.Skip("Next.js SSR tarball not found at " + tarballPath)
|
||||
}
|
||||
|
||||
// Cleanup after test
|
||||
defer func() {
|
||||
if !env.SkipCleanup && deploymentID != "" {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Deploy Next.js SSR app", func(t *testing.T) {
|
||||
deploymentID = createNextJSDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID, "Deployment ID should not be empty")
|
||||
t.Logf("Created Next.js deployment: %s (ID: %s)", deploymentName, deploymentID)
|
||||
})
|
||||
|
||||
t.Run("Wait for deployment to become healthy", func(t *testing.T) {
|
||||
healthy := e2e.WaitForHealthy(t, env, deploymentID, 120*time.Second)
|
||||
require.True(t, healthy, "Deployment should become healthy")
|
||||
t.Logf("Deployment is healthy")
|
||||
})
|
||||
|
||||
t.Run("Verify deployment in database", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
|
||||
assert.Equal(t, deploymentName, deployment["name"], "Deployment name should match")
|
||||
|
||||
deploymentType, ok := deployment["type"].(string)
|
||||
require.True(t, ok, "Type should be a string")
|
||||
assert.Contains(t, deploymentType, "nextjs", "Type should be nextjs")
|
||||
|
||||
t.Logf("Deployment type: %s", deploymentType)
|
||||
})
|
||||
|
||||
t.Run("Test SSR page - verify server-rendered HTML", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
|
||||
domain := extractDomain(nodeURL)
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "SSR page should return 200")
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err, "Should read response body")
|
||||
bodyStr := string(body)
|
||||
|
||||
// Verify HTML is server-rendered (contains actual content, not just loading state)
|
||||
assert.Contains(t, bodyStr, "Orama Network Next.js Test", "Should contain app title")
|
||||
assert.Contains(t, bodyStr, "Server-Side Rendering Test", "Should contain SSR test marker")
|
||||
assert.Contains(t, resp.Header.Get("Content-Type"), "text/html", "Should be HTML content")
|
||||
|
||||
t.Logf("SSR page loaded successfully")
|
||||
t.Logf("Content-Type: %s", resp.Header.Get("Content-Type"))
|
||||
})
|
||||
|
||||
t.Run("Test API route - /api/hello", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
|
||||
domain := extractDomain(nodeURL)
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/api/hello")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "API route should return 200")
|
||||
|
||||
var result map[string]interface{}
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&result), "Should decode JSON response")
|
||||
|
||||
assert.Contains(t, result["message"], "Hello", "Should contain hello message")
|
||||
assert.NotEmpty(t, result["timestamp"], "Should have timestamp")
|
||||
|
||||
t.Logf("API /hello response: %+v", result)
|
||||
})
|
||||
|
||||
t.Run("Test API route - /api/data", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
|
||||
domain := extractDomain(nodeURL)
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/api/data")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "API data route should return 200")
|
||||
|
||||
var result map[string]interface{}
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&result), "Should decode JSON response")
|
||||
|
||||
// Just verify it returns valid JSON
|
||||
t.Logf("API /data response: %+v", result)
|
||||
})
|
||||
|
||||
t.Run("Test static asset - _next directory", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
|
||||
domain := extractDomain(nodeURL)
|
||||
|
||||
// First, get the main page to find the actual static asset path
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
bodyStr := string(body)
|
||||
|
||||
// Look for _next/static references in the HTML
|
||||
if strings.Contains(bodyStr, "_next/static") {
|
||||
t.Logf("Found _next/static references in HTML")
|
||||
|
||||
// Try to fetch a common static chunk
|
||||
// The exact path depends on Next.js build output
|
||||
// We'll just verify the _next directory structure is accessible
|
||||
chunkResp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/_next/static/chunks/main.js")
|
||||
defer chunkResp.Body.Close()
|
||||
|
||||
// It's OK if specific files don't exist (they have hashed names)
|
||||
// Just verify we don't get a 500 error
|
||||
assert.NotEqual(t, http.StatusInternalServerError, chunkResp.StatusCode,
|
||||
"Static asset request should not cause server error")
|
||||
|
||||
t.Logf("Static asset request status: %d", chunkResp.StatusCode)
|
||||
} else {
|
||||
t.Logf("No _next/static references found (may be using different bundling)")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Test 404 handling", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
|
||||
domain := extractDomain(nodeURL)
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/nonexistent-page-xyz")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Next.js should handle 404 gracefully
|
||||
// Could be 404 or 200 depending on catch-all routes
|
||||
assert.Contains(t, []int{200, 404}, resp.StatusCode,
|
||||
"Should return either 200 (catch-all) or 404")
|
||||
|
||||
t.Logf("404 handling: status=%d", resp.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
// createNextJSDeployment creates a Next.js deployment
|
||||
func createNextJSDeployment(t *testing.T, env *e2e.E2ETestEnv, name, tarballPath string) string {
|
||||
t.Helper()
|
||||
|
||||
file, err := os.Open(tarballPath)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to open tarball: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// Create multipart form
|
||||
body := &bytes.Buffer{}
|
||||
boundary := "----WebKitFormBoundary7MA4YWxkTrZu0gW"
|
||||
|
||||
// Write name field
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"name\"\r\n\r\n")
|
||||
body.WriteString(name + "\r\n")
|
||||
|
||||
// Write ssr field (enable SSR mode)
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"ssr\"\r\n\r\n")
|
||||
body.WriteString("true\r\n")
|
||||
|
||||
// Write tarball file
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"tarball\"; filename=\"app.tar.gz\"\r\n")
|
||||
body.WriteString("Content-Type: application/gzip\r\n\r\n")
|
||||
|
||||
fileData, _ := io.ReadAll(file)
|
||||
body.Write(fileData)
|
||||
body.WriteString("\r\n--" + boundary + "--\r\n")
|
||||
|
||||
req, err := http.NewRequest("POST", env.GatewayURL+"/v1/deployments/nextjs/upload", body)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
// Use a longer timeout for large Next.js uploads (can be 50MB+)
|
||||
uploadClient := e2e.NewHTTPClient(5 * time.Minute)
|
||||
resp, err := uploadClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to execute request: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("Deployment upload failed with status %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if id, ok := result["deployment_id"].(string); ok {
|
||||
return id
|
||||
}
|
||||
if id, ok := result["id"].(string); ok {
|
||||
return id
|
||||
}
|
||||
t.Fatalf("Deployment response missing id field: %+v", result)
|
||||
return ""
|
||||
}
|
||||
203
core/e2e/deployments/nodejs_deployment_test.go
Normal file
203
core/e2e/deployments/nodejs_deployment_test.go
Normal file
@ -0,0 +1,203 @@
|
||||
//go:build e2e
|
||||
|
||||
package deployments_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNodeJSDeployment_FullFlow(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("test-nodejs-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/node-api")
|
||||
var deploymentID string
|
||||
|
||||
// Cleanup after test
|
||||
defer func() {
|
||||
if !env.SkipCleanup && deploymentID != "" {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Upload Node.js backend", func(t *testing.T) {
|
||||
deploymentID = createNodeJSDeployment(t, env, deploymentName, tarballPath)
|
||||
|
||||
assert.NotEmpty(t, deploymentID, "Deployment ID should not be empty")
|
||||
t.Logf("Created deployment: %s (ID: %s)", deploymentName, deploymentID)
|
||||
})
|
||||
|
||||
t.Run("Wait for deployment to become healthy", func(t *testing.T) {
|
||||
healthy := e2e.WaitForHealthy(t, env, deploymentID, 90*time.Second)
|
||||
assert.True(t, healthy, "Deployment should become healthy within timeout")
|
||||
t.Logf("Deployment is healthy")
|
||||
})
|
||||
|
||||
t.Run("Test health endpoint", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
|
||||
// Get the deployment URLs (can be array of strings or map)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
|
||||
// Test via Host header (localhost testing)
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, extractDomain(nodeURL), "/health")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "Health check should return 200")
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
var health map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(body, &health))
|
||||
|
||||
assert.Contains(t, []string{"healthy", "ok"}, health["status"],
|
||||
"Health status should be 'healthy' or 'ok'")
|
||||
t.Logf("Health check passed: %v", health)
|
||||
})
|
||||
|
||||
t.Run("Test API endpoint", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
|
||||
domain := extractDomain(nodeURL)
|
||||
|
||||
// Test health endpoint (node-api app serves /health)
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/health")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
var result map[string]interface{}
|
||||
require.NoError(t, json.Unmarshal(body, &result))
|
||||
|
||||
assert.NotEmpty(t, result["service"])
|
||||
t.Logf("API endpoint response: %v", result)
|
||||
})
|
||||
}
|
||||
|
||||
func createNodeJSDeployment(t *testing.T, env *e2e.E2ETestEnv, name, tarballPath string) string {
|
||||
t.Helper()
|
||||
|
||||
var fileData []byte
|
||||
|
||||
info, err := os.Stat(tarballPath)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to stat tarball path: %v", err)
|
||||
}
|
||||
|
||||
if info.IsDir() {
|
||||
// Create tarball from directory
|
||||
tarData, err := exec.Command("tar", "-czf", "-", "-C", tarballPath, ".").Output()
|
||||
require.NoError(t, err, "Failed to create tarball from %s", tarballPath)
|
||||
fileData = tarData
|
||||
} else {
|
||||
file, err := os.Open(tarballPath)
|
||||
require.NoError(t, err, "Failed to open tarball: %s", tarballPath)
|
||||
defer file.Close()
|
||||
fileData, _ = io.ReadAll(file)
|
||||
}
|
||||
|
||||
body := &bytes.Buffer{}
|
||||
boundary := "----WebKitFormBoundary7MA4YWxkTrZu0gW"
|
||||
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"name\"\r\n\r\n")
|
||||
body.WriteString(name + "\r\n")
|
||||
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"tarball\"; filename=\"app.tar.gz\"\r\n")
|
||||
body.WriteString("Content-Type: application/gzip\r\n\r\n")
|
||||
|
||||
body.Write(fileData)
|
||||
body.WriteString("\r\n--" + boundary + "--\r\n")
|
||||
|
||||
req, err := http.NewRequest("POST", env.GatewayURL+"/v1/deployments/nodejs/upload", body)
|
||||
require.NoError(t, err)
|
||||
|
||||
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("Deployment upload failed with status %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&result))
|
||||
|
||||
if id, ok := result["deployment_id"].(string); ok {
|
||||
return id
|
||||
}
|
||||
if id, ok := result["id"].(string); ok {
|
||||
return id
|
||||
}
|
||||
t.Fatalf("Deployment response missing id field: %+v", result)
|
||||
return ""
|
||||
}
|
||||
|
||||
// extractNodeURL gets the node URL from deployment response
|
||||
// Handles both array of strings and map formats
|
||||
func extractNodeURL(t *testing.T, deployment map[string]interface{}) string {
|
||||
t.Helper()
|
||||
|
||||
// Try as array of strings first (new format)
|
||||
if urls, ok := deployment["urls"].([]interface{}); ok && len(urls) > 0 {
|
||||
if url, ok := urls[0].(string); ok {
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
// Try as map (legacy format)
|
||||
if urls, ok := deployment["urls"].(map[string]interface{}); ok {
|
||||
if url, ok := urls["node"].(string); ok {
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractDomain(url string) string {
|
||||
// Extract domain from URL like "https://myapp.node-xyz.dbrs.space"
|
||||
// Remove protocol
|
||||
domain := url
|
||||
if len(url) > 8 && url[:8] == "https://" {
|
||||
domain = url[8:]
|
||||
} else if len(url) > 7 && url[:7] == "http://" {
|
||||
domain = url[7:]
|
||||
}
|
||||
// Remove trailing slash
|
||||
if len(domain) > 0 && domain[len(domain)-1] == '/' {
|
||||
domain = domain[:len(domain)-1]
|
||||
}
|
||||
return domain
|
||||
}
|
||||
352
core/e2e/deployments/replica_test.go
Normal file
352
core/e2e/deployments/replica_test.go
Normal file
@ -0,0 +1,352 @@
|
||||
//go:build e2e
|
||||
|
||||
package deployments_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestStaticReplica_CreatedOnDeploy verifies that deploying a static app
|
||||
// creates replica records on a second node.
|
||||
func TestStaticReplica_CreatedOnDeploy(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("replica-static-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
var deploymentID string
|
||||
|
||||
defer func() {
|
||||
if !env.SkipCleanup && deploymentID != "" {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Deploy static app", func(t *testing.T) {
|
||||
deploymentID = e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID)
|
||||
t.Logf("Created deployment: %s (ID: %s)", deploymentName, deploymentID)
|
||||
})
|
||||
|
||||
t.Run("Wait for replica setup", func(t *testing.T) {
|
||||
// Static replicas should set up quickly (IPFS content)
|
||||
time.Sleep(10 * time.Second)
|
||||
})
|
||||
|
||||
t.Run("Deployment has replica records", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
|
||||
// Check that replicas field exists and has entries
|
||||
replicas, ok := deployment["replicas"].([]interface{})
|
||||
if !ok {
|
||||
// Replicas might be in a nested structure or separate endpoint
|
||||
t.Logf("Deployment response: %+v", deployment)
|
||||
// Try querying replicas via the deployment details
|
||||
homeNodeID, _ := deployment["home_node_id"].(string)
|
||||
require.NotEmpty(t, homeNodeID, "Deployment should have a home_node_id")
|
||||
t.Logf("Home node: %s", homeNodeID)
|
||||
// If replicas aren't in the response, that's still okay — we verify
|
||||
// via DNS and cross-node serving below
|
||||
t.Log("Replica records not in deployment response; will verify via DNS/serving")
|
||||
return
|
||||
}
|
||||
|
||||
assert.GreaterOrEqual(t, len(replicas), 1, "Should have at least 1 replica")
|
||||
t.Logf("Found %d replica records", len(replicas))
|
||||
for i, r := range replicas {
|
||||
if replica, ok := r.(map[string]interface{}); ok {
|
||||
t.Logf(" Replica %d: node=%s status=%s", i, replica["node_id"], replica["status"])
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Static content served via gateway", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
domain := extractDomain(nodeURL)
|
||||
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"Static content should be served (got %d: %s)", resp.StatusCode, string(body))
|
||||
t.Logf("Served via gateway: status=%d", resp.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
// TestDynamicReplica_CreatedOnDeploy verifies that deploying a dynamic (Node.js) app
|
||||
// creates a replica process on a second node.
|
||||
func TestDynamicReplica_CreatedOnDeploy(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("replica-nodejs-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/node-api")
|
||||
var deploymentID string
|
||||
|
||||
defer func() {
|
||||
if !env.SkipCleanup && deploymentID != "" {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Deploy Node.js backend", func(t *testing.T) {
|
||||
deploymentID = createNodeJSDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID)
|
||||
t.Logf("Created deployment: %s (ID: %s)", deploymentName, deploymentID)
|
||||
})
|
||||
|
||||
t.Run("Wait for deployment and replica", func(t *testing.T) {
|
||||
healthy := e2e.WaitForHealthy(t, env, deploymentID, 90*time.Second)
|
||||
assert.True(t, healthy, "Deployment should become healthy")
|
||||
// Extra wait for async replica setup
|
||||
time.Sleep(15 * time.Second)
|
||||
})
|
||||
|
||||
t.Run("Dynamic app served from both nodes", func(t *testing.T) {
|
||||
if len(env.Config.Servers) < 2 {
|
||||
t.Skip("Requires at least 2 servers")
|
||||
}
|
||||
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL in deployment")
|
||||
}
|
||||
domain := extractDomain(nodeURL)
|
||||
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/health")
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"Dynamic app should be served via gateway (got %d: %s)", resp.StatusCode, string(body))
|
||||
t.Logf("Served via gateway: status=%d body=%s", resp.StatusCode, string(body))
|
||||
})
|
||||
}
|
||||
|
||||
// TestReplica_UpdatePropagation verifies that updating a deployment propagates to replicas.
|
||||
func TestReplica_UpdatePropagation(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
if len(env.Config.Servers) < 2 {
|
||||
t.Skip("Requires at least 2 servers")
|
||||
}
|
||||
|
||||
deploymentName := fmt.Sprintf("replica-update-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
var deploymentID string
|
||||
|
||||
defer func() {
|
||||
if !env.SkipCleanup && deploymentID != "" {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Deploy v1", func(t *testing.T) {
|
||||
deploymentID = e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID)
|
||||
time.Sleep(10 * time.Second) // Wait for replica
|
||||
})
|
||||
|
||||
var v1CID string
|
||||
t.Run("Record v1 CID", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
v1CID, _ = deployment["content_cid"].(string)
|
||||
require.NotEmpty(t, v1CID)
|
||||
t.Logf("v1 CID: %s", v1CID)
|
||||
})
|
||||
|
||||
t.Run("Update to v2", func(t *testing.T) {
|
||||
updateStaticDeployment(t, env, deploymentName, tarballPath)
|
||||
time.Sleep(10 * time.Second) // Wait for update + replica propagation
|
||||
})
|
||||
|
||||
t.Run("All nodes serve updated version", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
v2CID, _ := deployment["content_cid"].(string)
|
||||
|
||||
// v2 CID might be same (same tarball) but version should increment
|
||||
version, _ := deployment["version"].(float64)
|
||||
assert.Equal(t, float64(2), version, "Should be version 2")
|
||||
t.Logf("v2 CID: %s, version: %v", v2CID, version)
|
||||
|
||||
// Verify via gateway
|
||||
dep := e2e.GetDeployment(t, env, deploymentID)
|
||||
depCID, _ := dep["content_cid"].(string)
|
||||
assert.Equal(t, v2CID, depCID, "CID should match after update")
|
||||
})
|
||||
}
|
||||
|
||||
// TestReplica_RollbackPropagation verifies rollback propagates to replica nodes.
|
||||
func TestReplica_RollbackPropagation(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
if len(env.Config.Servers) < 2 {
|
||||
t.Skip("Requires at least 2 servers")
|
||||
}
|
||||
|
||||
deploymentName := fmt.Sprintf("replica-rollback-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
var deploymentID string
|
||||
|
||||
defer func() {
|
||||
if !env.SkipCleanup && deploymentID != "" {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Deploy v1 and update to v2", func(t *testing.T) {
|
||||
deploymentID = e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID)
|
||||
time.Sleep(10 * time.Second)
|
||||
|
||||
updateStaticDeployment(t, env, deploymentName, tarballPath)
|
||||
time.Sleep(10 * time.Second)
|
||||
})
|
||||
|
||||
var v1CID string
|
||||
t.Run("Get v1 CID from versions", func(t *testing.T) {
|
||||
versions := listVersions(t, env, deploymentName)
|
||||
if len(versions) > 0 {
|
||||
v1CID, _ = versions[0]["content_cid"].(string)
|
||||
}
|
||||
if v1CID == "" {
|
||||
// Fall back: v1 CID from current deployment
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
v1CID, _ = deployment["content_cid"].(string)
|
||||
}
|
||||
t.Logf("v1 CID for rollback comparison: %s", v1CID)
|
||||
})
|
||||
|
||||
t.Run("Rollback to v1", func(t *testing.T) {
|
||||
rollbackDeployment(t, env, deploymentName, 1)
|
||||
time.Sleep(10 * time.Second) // Wait for rollback + replica propagation
|
||||
})
|
||||
|
||||
t.Run("All nodes have rolled-back CID", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
currentCID, _ := deployment["content_cid"].(string)
|
||||
t.Logf("Post-rollback CID: %s", currentCID)
|
||||
|
||||
assert.Equal(t, v1CID, currentCID, "CID should match v1 after rollback")
|
||||
})
|
||||
}
|
||||
|
||||
// TestReplica_TeardownOnDelete verifies that deleting a deployment removes replicas.
|
||||
func TestReplica_TeardownOnDelete(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
if len(env.Config.Servers) < 2 {
|
||||
t.Skip("Requires at least 2 servers")
|
||||
}
|
||||
|
||||
deploymentName := fmt.Sprintf("replica-delete-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID)
|
||||
time.Sleep(10 * time.Second) // Wait for replica
|
||||
|
||||
// Get the domain before deletion
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
domain := ""
|
||||
if nodeURL != "" {
|
||||
domain = extractDomain(nodeURL)
|
||||
}
|
||||
|
||||
t.Run("Delete deployment", func(t *testing.T) {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
time.Sleep(10 * time.Second) // Wait for teardown propagation
|
||||
})
|
||||
|
||||
t.Run("Deployment no longer served on any node", func(t *testing.T) {
|
||||
if domain == "" {
|
||||
t.Skip("No domain to test")
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", env.GatewayURL+"/", nil)
|
||||
require.NoError(t, err)
|
||||
req.Host = domain
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
t.Logf("Connection failed (expected after deletion)")
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
assert.NotContains(t, string(body), "<div id=\"root\">",
|
||||
"Deleted deployment should not be served")
|
||||
}
|
||||
t.Logf("status=%d (expected non-200)", resp.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
// updateStaticDeployment updates an existing static deployment.
|
||||
func updateStaticDeployment(t *testing.T, env *e2e.E2ETestEnv, name, tarballPath string) {
|
||||
t.Helper()
|
||||
|
||||
var fileData []byte
|
||||
info, err := os.Stat(tarballPath)
|
||||
require.NoError(t, err)
|
||||
if info.IsDir() {
|
||||
fileData, err = exec.Command("tar", "-czf", "-", "-C", tarballPath, ".").Output()
|
||||
require.NoError(t, err)
|
||||
} else {
|
||||
file, err := os.Open(tarballPath)
|
||||
require.NoError(t, err)
|
||||
defer file.Close()
|
||||
fileData, _ = io.ReadAll(file)
|
||||
}
|
||||
|
||||
body := &bytes.Buffer{}
|
||||
boundary := "----WebKitFormBoundary7MA4YWxkTrZu0gW"
|
||||
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"name\"\r\n\r\n")
|
||||
body.WriteString(name + "\r\n")
|
||||
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"tarball\"; filename=\"app.tar.gz\"\r\n")
|
||||
body.WriteString("Content-Type: application/gzip\r\n\r\n")
|
||||
|
||||
body.Write(fileData)
|
||||
body.WriteString("\r\n--" + boundary + "--\r\n")
|
||||
|
||||
req, err := http.NewRequest("POST", env.GatewayURL+"/v1/deployments/static/update", body)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("Update failed with status %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
}
|
||||
232
core/e2e/deployments/rollback_test.go
Normal file
232
core/e2e/deployments/rollback_test.go
Normal file
@ -0,0 +1,232 @@
|
||||
//go:build e2e
|
||||
|
||||
package deployments_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestDeploymentRollback_FullFlow tests the complete rollback workflow:
|
||||
// 1. Deploy v1
|
||||
// 2. Update to v2
|
||||
// 3. Verify v2 content
|
||||
// 4. Rollback to v1
|
||||
// 5. Verify v1 content is restored
|
||||
func TestDeploymentRollback_FullFlow(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("rollback-test-%d", time.Now().Unix())
|
||||
tarballPathV1 := filepath.Join("../../testdata/apps/react-app")
|
||||
var deploymentID string
|
||||
|
||||
// Cleanup after test
|
||||
defer func() {
|
||||
if !env.SkipCleanup && deploymentID != "" {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Deploy v1", func(t *testing.T) {
|
||||
deploymentID = e2e.CreateTestDeployment(t, env, deploymentName, tarballPathV1)
|
||||
require.NotEmpty(t, deploymentID, "Deployment ID should not be empty")
|
||||
t.Logf("Created deployment v1: %s (ID: %s)", deploymentName, deploymentID)
|
||||
})
|
||||
|
||||
t.Run("Verify v1 deployment", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
|
||||
version, ok := deployment["version"].(float64)
|
||||
require.True(t, ok, "Version should be a number")
|
||||
assert.Equal(t, float64(1), version, "Initial version should be 1")
|
||||
|
||||
contentCID, ok := deployment["content_cid"].(string)
|
||||
require.True(t, ok, "Content CID should be a string")
|
||||
assert.NotEmpty(t, contentCID, "Content CID should not be empty")
|
||||
|
||||
t.Logf("v1 version: %v, CID: %s", version, contentCID)
|
||||
})
|
||||
|
||||
var v1CID string
|
||||
t.Run("Save v1 CID", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
v1CID = deployment["content_cid"].(string)
|
||||
t.Logf("Saved v1 CID: %s", v1CID)
|
||||
})
|
||||
|
||||
t.Run("Update to v2", func(t *testing.T) {
|
||||
// Update the deployment with the same tarball (simulates a new version)
|
||||
updateDeployment(t, env, deploymentName, tarballPathV1)
|
||||
|
||||
// Wait for update to complete
|
||||
time.Sleep(2 * time.Second)
|
||||
})
|
||||
|
||||
t.Run("Verify v2 deployment", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
|
||||
version, ok := deployment["version"].(float64)
|
||||
require.True(t, ok, "Version should be a number")
|
||||
assert.Equal(t, float64(2), version, "Version should be 2 after update")
|
||||
|
||||
t.Logf("v2 version: %v", version)
|
||||
})
|
||||
|
||||
t.Run("List deployment versions", func(t *testing.T) {
|
||||
versions := listVersions(t, env, deploymentName)
|
||||
t.Logf("Available versions: %+v", versions)
|
||||
|
||||
// Should have at least 2 versions in history
|
||||
assert.GreaterOrEqual(t, len(versions), 1, "Should have version history")
|
||||
})
|
||||
|
||||
t.Run("Rollback to v1", func(t *testing.T) {
|
||||
rollbackDeployment(t, env, deploymentName, 1)
|
||||
|
||||
// Wait for rollback to complete
|
||||
time.Sleep(2 * time.Second)
|
||||
})
|
||||
|
||||
t.Run("Verify rollback succeeded", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
|
||||
version, ok := deployment["version"].(float64)
|
||||
require.True(t, ok, "Version should be a number")
|
||||
// Note: Version number increases even on rollback (it's a new deployment version)
|
||||
// But the content_cid should be the same as v1
|
||||
t.Logf("Post-rollback version: %v", version)
|
||||
|
||||
contentCID, ok := deployment["content_cid"].(string)
|
||||
require.True(t, ok, "Content CID should be a string")
|
||||
assert.Equal(t, v1CID, contentCID, "Content CID should match v1 after rollback")
|
||||
|
||||
t.Logf("Rollback verified - content CID matches v1: %s", contentCID)
|
||||
})
|
||||
}
|
||||
|
||||
// updateDeployment updates an existing static deployment
|
||||
func updateDeployment(t *testing.T, env *e2e.E2ETestEnv, name, tarballPath string) {
|
||||
t.Helper()
|
||||
|
||||
var fileData []byte
|
||||
info, err := os.Stat(tarballPath)
|
||||
require.NoError(t, err)
|
||||
if info.IsDir() {
|
||||
fileData, err = exec.Command("tar", "-czf", "-", "-C", tarballPath, ".").Output()
|
||||
require.NoError(t, err)
|
||||
} else {
|
||||
file, err := os.Open(tarballPath)
|
||||
require.NoError(t, err, "Failed to open tarball")
|
||||
defer file.Close()
|
||||
fileData, _ = io.ReadAll(file)
|
||||
}
|
||||
|
||||
// Create multipart form
|
||||
body := &bytes.Buffer{}
|
||||
boundary := "----WebKitFormBoundary7MA4YWxkTrZu0gW"
|
||||
|
||||
// Write name field
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"name\"\r\n\r\n")
|
||||
body.WriteString(name + "\r\n")
|
||||
|
||||
// Write tarball file
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"tarball\"; filename=\"app.tar.gz\"\r\n")
|
||||
body.WriteString("Content-Type: application/gzip\r\n\r\n")
|
||||
|
||||
body.Write(fileData)
|
||||
body.WriteString("\r\n--" + boundary + "--\r\n")
|
||||
|
||||
req, err := http.NewRequest("POST", env.GatewayURL+"/v1/deployments/static/update", body)
|
||||
require.NoError(t, err, "Failed to create request")
|
||||
|
||||
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Failed to execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("Update failed with status %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&result), "Failed to decode response")
|
||||
t.Logf("Update response: %+v", result)
|
||||
}
|
||||
|
||||
// listVersions lists available versions for a deployment
|
||||
func listVersions(t *testing.T, env *e2e.E2ETestEnv, name string) []map[string]interface{} {
|
||||
t.Helper()
|
||||
|
||||
req, err := http.NewRequest("GET", env.GatewayURL+"/v1/deployments/versions?name="+name, nil)
|
||||
require.NoError(t, err, "Failed to create request")
|
||||
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Failed to execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Logf("List versions returned status %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
return nil
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Versions []map[string]interface{} `json:"versions"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
t.Logf("Failed to decode versions: %v", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return result.Versions
|
||||
}
|
||||
|
||||
// rollbackDeployment triggers a rollback to a specific version
|
||||
func rollbackDeployment(t *testing.T, env *e2e.E2ETestEnv, name string, targetVersion int) {
|
||||
t.Helper()
|
||||
|
||||
reqBody := map[string]interface{}{
|
||||
"name": name,
|
||||
"version": targetVersion,
|
||||
}
|
||||
bodyBytes, _ := json.Marshal(reqBody)
|
||||
|
||||
req, err := http.NewRequest("POST", env.GatewayURL+"/v1/deployments/rollback", bytes.NewBuffer(bodyBytes))
|
||||
require.NoError(t, err, "Failed to create request")
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Failed to execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("Rollback failed with status %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&result), "Failed to decode response")
|
||||
t.Logf("Rollback response: %+v", result)
|
||||
}
|
||||
210
core/e2e/deployments/static_deployment_test.go
Normal file
210
core/e2e/deployments/static_deployment_test.go
Normal file
@ -0,0 +1,210 @@
|
||||
//go:build e2e
|
||||
|
||||
package deployments_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestStaticDeployment_FullFlow(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("test-static-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
var deploymentID string
|
||||
|
||||
// Cleanup after test
|
||||
defer func() {
|
||||
if !env.SkipCleanup && deploymentID != "" {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Upload static tarball", func(t *testing.T) {
|
||||
deploymentID = e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
|
||||
assert.NotEmpty(t, deploymentID, "Deployment ID should not be empty")
|
||||
t.Logf("✓ Created deployment: %s (ID: %s)", deploymentName, deploymentID)
|
||||
})
|
||||
|
||||
t.Run("Verify deployment in database", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
|
||||
assert.Equal(t, deploymentName, deployment["name"], "Deployment name should match")
|
||||
assert.NotEmpty(t, deployment["content_cid"], "Content CID should not be empty")
|
||||
|
||||
// Status might be "deploying" or "active" depending on timing
|
||||
status, ok := deployment["status"].(string)
|
||||
require.True(t, ok, "Status should be a string")
|
||||
assert.Contains(t, []string{"deploying", "active"}, status, "Status should be deploying or active")
|
||||
|
||||
t.Logf("✓ Deployment verified in database")
|
||||
t.Logf(" - Name: %s", deployment["name"])
|
||||
t.Logf(" - Status: %s", status)
|
||||
t.Logf(" - CID: %s", deployment["content_cid"])
|
||||
})
|
||||
|
||||
t.Run("Verify DNS record creation", func(t *testing.T) {
|
||||
// Wait for deployment to become active
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// Get the actual domain from deployment response
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
require.NotEmpty(t, nodeURL, "Deployment should have a URL")
|
||||
expectedDomain := extractDomain(nodeURL)
|
||||
|
||||
// Make request with Host header (localhost testing)
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, expectedDomain, "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should return 200 with React app HTML
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "Should return 200 OK")
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err, "Should read response body")
|
||||
|
||||
bodyStr := string(body)
|
||||
|
||||
// Verify React app content
|
||||
assert.Contains(t, bodyStr, "<div id=\"root\">", "Should contain React root div")
|
||||
assert.Contains(t, resp.Header.Get("Content-Type"), "text/html", "Content-Type should be text/html")
|
||||
|
||||
t.Logf("✓ Domain routing works")
|
||||
t.Logf(" - Domain: %s", expectedDomain)
|
||||
t.Logf(" - Status: %d", resp.StatusCode)
|
||||
t.Logf(" - Content-Type: %s", resp.Header.Get("Content-Type"))
|
||||
})
|
||||
|
||||
t.Run("Verify static assets serve correctly", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
require.NotEmpty(t, nodeURL, "Deployment should have a URL")
|
||||
expectedDomain := extractDomain(nodeURL)
|
||||
|
||||
// Test CSS file (exact path depends on Vite build output)
|
||||
// We'll just test a few common asset paths
|
||||
assetPaths := []struct {
|
||||
path string
|
||||
contentType string
|
||||
}{
|
||||
{"/index.html", "text/html"},
|
||||
// Note: Asset paths with hashes change on each build
|
||||
// We'll test what we can
|
||||
}
|
||||
|
||||
for _, asset := range assetPaths {
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, expectedDomain, asset.path)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
assert.Contains(t, resp.Header.Get("Content-Type"), asset.contentType,
|
||||
"Content-Type should be %s for %s", asset.contentType, asset.path)
|
||||
|
||||
t.Logf("✓ Asset served correctly: %s (%s)", asset.path, asset.contentType)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Verify SPA fallback routing", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
require.NotEmpty(t, nodeURL, "Deployment should have a URL")
|
||||
expectedDomain := extractDomain(nodeURL)
|
||||
|
||||
// Request unknown route (should return index.html for SPA)
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, expectedDomain, "/about/team")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "SPA fallback should return 200")
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err, "Should read response body")
|
||||
|
||||
assert.Contains(t, string(body), "<div id=\"root\">", "Should return index.html for unknown paths")
|
||||
|
||||
t.Logf("✓ SPA fallback routing works")
|
||||
})
|
||||
|
||||
t.Run("List deployments", func(t *testing.T) {
|
||||
req, err := http.NewRequest("GET", env.GatewayURL+"/v1/deployments/list", nil)
|
||||
require.NoError(t, err, "Should create request")
|
||||
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "List deployments should return 200")
|
||||
|
||||
var result map[string]interface{}
|
||||
require.NoError(t, e2e.DecodeJSON(mustReadAll(t, resp.Body), &result), "Should decode JSON")
|
||||
|
||||
deployments, ok := result["deployments"].([]interface{})
|
||||
require.True(t, ok, "Deployments should be an array")
|
||||
|
||||
assert.GreaterOrEqual(t, len(deployments), 1, "Should have at least one deployment")
|
||||
|
||||
// Find our deployment
|
||||
found := false
|
||||
for _, d := range deployments {
|
||||
dep, ok := d.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if dep["name"] == deploymentName {
|
||||
found = true
|
||||
t.Logf("✓ Found deployment in list: %s", deploymentName)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
assert.True(t, found, "Deployment should be in list")
|
||||
})
|
||||
|
||||
t.Run("Delete deployment", func(t *testing.T) {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
|
||||
// Verify deletion - allow time for replication
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
req, _ := http.NewRequest("GET", env.GatewayURL+"/v1/deployments/get?id="+deploymentID, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
t.Logf("Delete verification response: status=%d body=%s", resp.StatusCode, string(body))
|
||||
|
||||
// After deletion, either 404 (not found) or 200 with empty/error response is acceptable
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
// If 200, check if the deployment is actually gone
|
||||
t.Logf("Got 200 - this may indicate soft delete or eventual consistency")
|
||||
}
|
||||
|
||||
t.Logf("✓ Deployment deleted successfully")
|
||||
|
||||
// Clear deploymentID so cleanup doesn't try to delete again
|
||||
deploymentID = ""
|
||||
})
|
||||
}
|
||||
|
||||
func mustReadAll(t *testing.T, r io.Reader) []byte {
|
||||
t.Helper()
|
||||
data, err := io.ReadAll(r)
|
||||
require.NoError(t, err, "Should read all data")
|
||||
return data
|
||||
}
|
||||
1731
core/e2e/env.go
Normal file
1731
core/e2e/env.go
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,6 @@
|
||||
//go:build e2e
|
||||
|
||||
package e2e
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
@ -10,16 +10,18 @@ import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
)
|
||||
|
||||
// TestCache_ConcurrentWrites tests concurrent cache writes
|
||||
func TestCache_ConcurrentWrites(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
numGoroutines := 10
|
||||
var wg sync.WaitGroup
|
||||
var errorCount int32
|
||||
@ -32,9 +34,9 @@ func TestCache_ConcurrentWrites(t *testing.T) {
|
||||
key := fmt.Sprintf("key-%d", idx)
|
||||
value := fmt.Sprintf("value-%d", idx)
|
||||
|
||||
putReq := &HTTPRequest{
|
||||
putReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/put",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/put",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -56,9 +58,9 @@ func TestCache_ConcurrentWrites(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify all values exist
|
||||
scanReq := &HTTPRequest{
|
||||
scanReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/scan",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/scan",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
},
|
||||
@ -70,7 +72,7 @@ func TestCache_ConcurrentWrites(t *testing.T) {
|
||||
}
|
||||
|
||||
var scanResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &scanResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &scanResp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -82,19 +84,19 @@ func TestCache_ConcurrentWrites(t *testing.T) {
|
||||
|
||||
// TestCache_ConcurrentReads tests concurrent cache reads
|
||||
func TestCache_ConcurrentReads(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
key := "shared-key"
|
||||
value := "shared-value"
|
||||
|
||||
// Put value first
|
||||
putReq := &HTTPRequest{
|
||||
putReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/put",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/put",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -117,9 +119,9 @@ func TestCache_ConcurrentReads(t *testing.T) {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
getReq := &HTTPRequest{
|
||||
getReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/get",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/get",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -133,7 +135,7 @@ func TestCache_ConcurrentReads(t *testing.T) {
|
||||
}
|
||||
|
||||
var getResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &getResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &getResp); err != nil {
|
||||
atomic.AddInt32(&errorCount, 1)
|
||||
return
|
||||
}
|
||||
@ -153,12 +155,12 @@ func TestCache_ConcurrentReads(t *testing.T) {
|
||||
|
||||
// TestCache_ConcurrentDeleteAndWrite tests concurrent delete and write
|
||||
func TestCache_ConcurrentDeleteAndWrite(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
var wg sync.WaitGroup
|
||||
var errorCount int32
|
||||
|
||||
@ -174,9 +176,9 @@ func TestCache_ConcurrentDeleteAndWrite(t *testing.T) {
|
||||
key := fmt.Sprintf("key-%d", idx)
|
||||
value := fmt.Sprintf("value-%d", idx)
|
||||
|
||||
putReq := &HTTPRequest{
|
||||
putReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/put",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/put",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -201,9 +203,9 @@ func TestCache_ConcurrentDeleteAndWrite(t *testing.T) {
|
||||
|
||||
key := fmt.Sprintf("key-%d", idx)
|
||||
|
||||
deleteReq := &HTTPRequest{
|
||||
deleteReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/delete",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/delete",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -226,21 +228,32 @@ func TestCache_ConcurrentDeleteAndWrite(t *testing.T) {
|
||||
|
||||
// TestRQLite_ConcurrentInserts tests concurrent database inserts
|
||||
func TestRQLite_ConcurrentInserts(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
table := GenerateTableName()
|
||||
table := e2e.GenerateTableName()
|
||||
|
||||
// Cleanup table after test
|
||||
defer func() {
|
||||
dropReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/drop-table",
|
||||
Body: map[string]interface{}{"table": table},
|
||||
}
|
||||
dropReq.Do(context.Background())
|
||||
}()
|
||||
|
||||
schema := fmt.Sprintf(
|
||||
"CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY AUTOINCREMENT, value INTEGER)",
|
||||
table,
|
||||
)
|
||||
|
||||
// Create table
|
||||
createReq := &HTTPRequest{
|
||||
createReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
Body: map[string]interface{}{
|
||||
"schema": schema,
|
||||
},
|
||||
@ -261,9 +274,9 @@ func TestRQLite_ConcurrentInserts(t *testing.T) {
|
||||
go func(idx int) {
|
||||
defer wg.Done()
|
||||
|
||||
txReq := &HTTPRequest{
|
||||
txReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
Body: map[string]interface{}{
|
||||
"statements": []string{
|
||||
fmt.Sprintf("INSERT INTO %s(value) VALUES (%d)", table, idx),
|
||||
@ -285,9 +298,9 @@ func TestRQLite_ConcurrentInserts(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify count
|
||||
queryReq := &HTTPRequest{
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/query",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/query",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT COUNT(*) as count FROM %s", table),
|
||||
},
|
||||
@ -299,7 +312,7 @@ func TestRQLite_ConcurrentInserts(t *testing.T) {
|
||||
}
|
||||
|
||||
var countResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &countResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &countResp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -314,21 +327,32 @@ func TestRQLite_ConcurrentInserts(t *testing.T) {
|
||||
|
||||
// TestRQLite_LargeBatchTransaction tests a large transaction with many statements
|
||||
func TestRQLite_LargeBatchTransaction(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
table := GenerateTableName()
|
||||
table := e2e.GenerateTableName()
|
||||
|
||||
// Cleanup table after test
|
||||
defer func() {
|
||||
dropReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/drop-table",
|
||||
Body: map[string]interface{}{"table": table},
|
||||
}
|
||||
dropReq.Do(context.Background())
|
||||
}()
|
||||
|
||||
schema := fmt.Sprintf(
|
||||
"CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY AUTOINCREMENT, value TEXT)",
|
||||
table,
|
||||
)
|
||||
|
||||
// Create table
|
||||
createReq := &HTTPRequest{
|
||||
createReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
Body: map[string]interface{}{
|
||||
"schema": schema,
|
||||
},
|
||||
@ -348,9 +372,9 @@ func TestRQLite_LargeBatchTransaction(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
txReq := &HTTPRequest{
|
||||
txReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
Body: map[string]interface{}{
|
||||
"ops": ops,
|
||||
},
|
||||
@ -362,9 +386,9 @@ func TestRQLite_LargeBatchTransaction(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify count
|
||||
queryReq := &HTTPRequest{
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/query",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/query",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT COUNT(*) as count FROM %s", table),
|
||||
},
|
||||
@ -376,7 +400,7 @@ func TestRQLite_LargeBatchTransaction(t *testing.T) {
|
||||
}
|
||||
|
||||
var countResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &countResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &countResp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -390,19 +414,19 @@ func TestRQLite_LargeBatchTransaction(t *testing.T) {
|
||||
|
||||
// TestCache_TTLExpiryWithSleep tests TTL expiry with a controlled sleep
|
||||
func TestCache_TTLExpiryWithSleep(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
key := "ttl-expiry-key"
|
||||
value := "ttl-expiry-value"
|
||||
|
||||
// Put value with 2 second TTL
|
||||
putReq := &HTTPRequest{
|
||||
putReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/put",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/put",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -417,9 +441,9 @@ func TestCache_TTLExpiryWithSleep(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify exists immediately
|
||||
getReq := &HTTPRequest{
|
||||
getReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/get",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/get",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -432,7 +456,7 @@ func TestCache_TTLExpiryWithSleep(t *testing.T) {
|
||||
}
|
||||
|
||||
// Sleep for TTL duration + buffer
|
||||
Delay(2500)
|
||||
e2e.Delay(2500)
|
||||
|
||||
// Try to get after TTL expires
|
||||
_, status, err = getReq.Do(ctx)
|
||||
@ -443,21 +467,21 @@ func TestCache_TTLExpiryWithSleep(t *testing.T) {
|
||||
|
||||
// TestCache_ConcurrentWriteAndDelete tests concurrent writes and deletes on same key
|
||||
func TestCache_ConcurrentWriteAndDelete(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
key := "contested-key"
|
||||
|
||||
// Alternate between writes and deletes
|
||||
numIterations := 5
|
||||
for i := 0; i < numIterations; i++ {
|
||||
// Write
|
||||
putReq := &HTTPRequest{
|
||||
putReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/put",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/put",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -471,9 +495,9 @@ func TestCache_ConcurrentWriteAndDelete(t *testing.T) {
|
||||
}
|
||||
|
||||
// Read
|
||||
getReq := &HTTPRequest{
|
||||
getReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/get",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/get",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -486,9 +510,9 @@ func TestCache_ConcurrentWriteAndDelete(t *testing.T) {
|
||||
}
|
||||
|
||||
// Delete
|
||||
deleteReq := &HTTPRequest{
|
||||
deleteReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/delete",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/delete",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
462
core/e2e/integration/data_persistence_test.go
Normal file
462
core/e2e/integration/data_persistence_test.go
Normal file
@ -0,0 +1,462 @@
|
||||
//go:build e2e
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// STRICT DATA PERSISTENCE TESTS
|
||||
// These tests verify that data is properly persisted and survives operations.
|
||||
// Tests FAIL if data is lost or corrupted.
|
||||
// =============================================================================
|
||||
|
||||
// TestRQLite_DataPersistence verifies that RQLite data is persisted through the gateway.
|
||||
func TestRQLite_DataPersistence(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
tableName := fmt.Sprintf("persist_test_%d", time.Now().UnixNano())
|
||||
|
||||
// Cleanup
|
||||
defer func() {
|
||||
dropReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/drop-table",
|
||||
Body: map[string]interface{}{"table": tableName},
|
||||
}
|
||||
dropReq.Do(context.Background())
|
||||
}()
|
||||
|
||||
// Create table
|
||||
createReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
Body: map[string]interface{}{
|
||||
"schema": fmt.Sprintf(
|
||||
"CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY, value TEXT, version INTEGER)",
|
||||
tableName,
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
_, status, err := createReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Could not create table")
|
||||
require.True(t, status == http.StatusCreated || status == http.StatusOK,
|
||||
"FAIL: Create table returned status %d", status)
|
||||
|
||||
t.Run("Data_survives_multiple_writes", func(t *testing.T) {
|
||||
// Insert initial data
|
||||
var statements []string
|
||||
for i := 1; i <= 10; i++ {
|
||||
statements = append(statements,
|
||||
fmt.Sprintf("INSERT INTO %s (value, version) VALUES ('item_%d', %d)", tableName, i, i))
|
||||
}
|
||||
|
||||
insertReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
Body: map[string]interface{}{"statements": statements},
|
||||
}
|
||||
|
||||
_, status, err := insertReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Could not insert rows")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: Insert returned status %d", status)
|
||||
|
||||
// Verify all data exists
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/query",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT COUNT(*) FROM %s", tableName),
|
||||
},
|
||||
}
|
||||
|
||||
body, status, err := queryReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Could not count rows")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: Count query returned status %d", status)
|
||||
|
||||
var queryResp map[string]interface{}
|
||||
e2e.DecodeJSON(body, &queryResp)
|
||||
|
||||
if rows, ok := queryResp["rows"].([]interface{}); ok && len(rows) > 0 {
|
||||
row := rows[0].([]interface{})
|
||||
count := int(row[0].(float64))
|
||||
require.Equal(t, 10, count, "FAIL: Expected 10 rows, got %d", count)
|
||||
}
|
||||
|
||||
// Update data
|
||||
updateReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
Body: map[string]interface{}{
|
||||
"statements": []string{
|
||||
fmt.Sprintf("UPDATE %s SET version = version + 100 WHERE version <= 5", tableName),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, status, err = updateReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Could not update rows")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: Update returned status %d", status)
|
||||
|
||||
// Verify updates persisted
|
||||
queryUpdatedReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/query",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE version > 100", tableName),
|
||||
},
|
||||
}
|
||||
|
||||
body, status, err = queryUpdatedReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Could not count updated rows")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: Count updated query returned status %d", status)
|
||||
|
||||
e2e.DecodeJSON(body, &queryResp)
|
||||
if rows, ok := queryResp["rows"].([]interface{}); ok && len(rows) > 0 {
|
||||
row := rows[0].([]interface{})
|
||||
count := int(row[0].(float64))
|
||||
require.Equal(t, 5, count, "FAIL: Expected 5 updated rows, got %d", count)
|
||||
}
|
||||
|
||||
t.Logf(" ✓ Data persists through multiple write operations")
|
||||
})
|
||||
|
||||
t.Run("Deletes_are_persisted", func(t *testing.T) {
|
||||
// Delete some rows
|
||||
deleteReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
Body: map[string]interface{}{
|
||||
"statements": []string{
|
||||
fmt.Sprintf("DELETE FROM %s WHERE version > 100", tableName),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, status, err := deleteReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Could not delete rows")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: Delete returned status %d", status)
|
||||
|
||||
// Verify deletes persisted
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/query",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT COUNT(*) FROM %s", tableName),
|
||||
},
|
||||
}
|
||||
|
||||
body, status, err := queryReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Could not count remaining rows")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: Count query returned status %d", status)
|
||||
|
||||
var queryResp map[string]interface{}
|
||||
e2e.DecodeJSON(body, &queryResp)
|
||||
|
||||
if rows, ok := queryResp["rows"].([]interface{}); ok && len(rows) > 0 {
|
||||
row := rows[0].([]interface{})
|
||||
count := int(row[0].(float64))
|
||||
require.Equal(t, 5, count, "FAIL: Expected 5 rows after delete, got %d", count)
|
||||
}
|
||||
|
||||
t.Logf(" ✓ Deletes are properly persisted")
|
||||
})
|
||||
}
|
||||
|
||||
// TestRQLite_DataFilesExist verifies RQLite data files are created on disk.
|
||||
func TestRQLite_DataFilesExist(t *testing.T) {
|
||||
homeDir, err := os.UserHomeDir()
|
||||
require.NoError(t, err, "FAIL: Could not get home directory")
|
||||
|
||||
// Check for RQLite data directories
|
||||
dataLocations := []string{
|
||||
filepath.Join(homeDir, ".orama", "node-1", "rqlite"),
|
||||
filepath.Join(homeDir, ".orama", "node-2", "rqlite"),
|
||||
filepath.Join(homeDir, ".orama", "node-3", "rqlite"),
|
||||
filepath.Join(homeDir, ".orama", "node-4", "rqlite"),
|
||||
filepath.Join(homeDir, ".orama", "node-5", "rqlite"),
|
||||
}
|
||||
|
||||
foundDataDirs := 0
|
||||
for _, dataDir := range dataLocations {
|
||||
if _, err := os.Stat(dataDir); err == nil {
|
||||
foundDataDirs++
|
||||
t.Logf(" ✓ Found RQLite data directory: %s", dataDir)
|
||||
|
||||
// Check for Raft log files
|
||||
entries, _ := os.ReadDir(dataDir)
|
||||
for _, entry := range entries {
|
||||
t.Logf(" - %s", entry.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
require.Greater(t, foundDataDirs, 0,
|
||||
"FAIL: No RQLite data directories found - data may not be persisted")
|
||||
t.Logf(" Found %d RQLite data directories", foundDataDirs)
|
||||
}
|
||||
|
||||
// TestOlric_DataPersistence verifies Olric cache data persistence.
|
||||
// Note: Olric is an in-memory cache, so this tests data survival during runtime.
|
||||
func TestOlric_DataPersistence(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "FAIL: Could not load test environment")
|
||||
|
||||
dmap := fmt.Sprintf("persist_cache_%d", time.Now().UnixNano())
|
||||
|
||||
t.Run("Cache_data_survives_multiple_operations", func(t *testing.T) {
|
||||
// Put multiple keys
|
||||
keys := make(map[string]string)
|
||||
for i := 0; i < 10; i++ {
|
||||
key := fmt.Sprintf("persist_key_%d", i)
|
||||
value := fmt.Sprintf("persist_value_%d", i)
|
||||
keys[key] = value
|
||||
|
||||
err := e2e.PutToOlric(env.GatewayURL, env.APIKey, dmap, key, value)
|
||||
require.NoError(t, err, "FAIL: Could not put key %s", key)
|
||||
}
|
||||
|
||||
// Perform other operations
|
||||
err := e2e.PutToOlric(env.GatewayURL, env.APIKey, dmap, "other_key", "other_value")
|
||||
require.NoError(t, err, "FAIL: Could not put other key")
|
||||
|
||||
// Verify original keys still exist
|
||||
for key, expectedValue := range keys {
|
||||
retrieved, err := e2e.GetFromOlric(env.GatewayURL, env.APIKey, dmap, key)
|
||||
require.NoError(t, err, "FAIL: Key %s not found after other operations", key)
|
||||
require.Equal(t, expectedValue, retrieved, "FAIL: Value mismatch for key %s", key)
|
||||
}
|
||||
|
||||
t.Logf(" ✓ Cache data survives multiple operations")
|
||||
})
|
||||
}
|
||||
|
||||
// TestNamespaceCluster_DataPersistence verifies namespace-specific data is isolated and persisted.
|
||||
func TestNamespaceCluster_DataPersistence(t *testing.T) {
|
||||
// Create namespace
|
||||
namespace := fmt.Sprintf("persist-ns-%d", time.Now().UnixNano())
|
||||
env, err := e2e.LoadTestEnvWithNamespace(namespace)
|
||||
require.NoError(t, err, "FAIL: Could not create namespace")
|
||||
|
||||
t.Logf("Created namespace: %s", namespace)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
t.Run("Namespace_data_is_isolated", func(t *testing.T) {
|
||||
// Create data via gateway API
|
||||
tableName := fmt.Sprintf("ns_data_%d", time.Now().UnixNano())
|
||||
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: env.GatewayURL + "/v1/rqlite/create-table",
|
||||
Headers: map[string]string{
|
||||
"Authorization": "Bearer " + env.APIKey,
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"schema": fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY, value TEXT)", tableName),
|
||||
},
|
||||
}
|
||||
|
||||
_, status, err := req.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Could not create table in namespace")
|
||||
require.True(t, status == http.StatusOK || status == http.StatusCreated,
|
||||
"FAIL: Create table returned status %d", status)
|
||||
|
||||
// Insert data
|
||||
insertReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: env.GatewayURL + "/v1/rqlite/transaction",
|
||||
Headers: map[string]string{
|
||||
"Authorization": "Bearer " + env.APIKey,
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"statements": []string{
|
||||
fmt.Sprintf("INSERT INTO %s (value) VALUES ('ns_test_value')", tableName),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, status, err = insertReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Could not insert into namespace table")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: Insert returned status %d", status)
|
||||
|
||||
// Verify data exists
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: env.GatewayURL + "/v1/rqlite/query",
|
||||
Headers: map[string]string{
|
||||
"Authorization": "Bearer " + env.APIKey,
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT value FROM %s", tableName),
|
||||
},
|
||||
}
|
||||
|
||||
body, status, err := queryReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Could not query namespace table")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: Query returned status %d", status)
|
||||
|
||||
var queryResp map[string]interface{}
|
||||
json.Unmarshal(body, &queryResp)
|
||||
count, _ := queryResp["count"].(float64)
|
||||
require.Equal(t, float64(1), count, "FAIL: Expected 1 row in namespace table")
|
||||
|
||||
t.Logf(" ✓ Namespace data is isolated and persisted")
|
||||
})
|
||||
}
|
||||
|
||||
// TestIPFS_DataPersistence verifies IPFS content is persisted and pinned.
|
||||
// Note: Detailed IPFS tests are in storage_http_test.go. This test uses the helper from env.go.
|
||||
func TestIPFS_DataPersistence(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "FAIL: Could not load test environment")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
t.Run("Uploaded_content_persists", func(t *testing.T) {
|
||||
// Use helper function to upload content via multipart form
|
||||
content := fmt.Sprintf("persistent content %d", time.Now().UnixNano())
|
||||
cid := e2e.UploadTestFile(t, env, "persist_test.txt", content)
|
||||
require.NotEmpty(t, cid, "FAIL: No CID returned from upload")
|
||||
t.Logf(" Uploaded content with CID: %s", cid)
|
||||
|
||||
// Verify content can be retrieved
|
||||
getReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: env.GatewayURL + "/v1/storage/get/" + cid,
|
||||
Headers: map[string]string{
|
||||
"Authorization": "Bearer " + env.APIKey,
|
||||
},
|
||||
}
|
||||
|
||||
respBody, status, err := getReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Get content failed")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: Get returned status %d", status)
|
||||
require.Contains(t, string(respBody), "persistent content",
|
||||
"FAIL: Retrieved content doesn't match uploaded content")
|
||||
|
||||
t.Logf(" ✓ IPFS content persists and is retrievable")
|
||||
})
|
||||
}
|
||||
|
||||
// TestSQLite_DataPersistence verifies per-deployment SQLite databases persist.
|
||||
func TestSQLite_DataPersistence(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "FAIL: Could not load test environment")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dbName := fmt.Sprintf("persist_db_%d", time.Now().UnixNano())
|
||||
|
||||
t.Run("SQLite_database_persists", func(t *testing.T) {
|
||||
// Create database
|
||||
createReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: env.GatewayURL + "/v1/db/sqlite/create",
|
||||
Headers: map[string]string{
|
||||
"Authorization": "Bearer " + env.APIKey,
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"database_name": dbName,
|
||||
},
|
||||
}
|
||||
|
||||
_, status, err := createReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Create database failed")
|
||||
require.True(t, status == http.StatusOK || status == http.StatusCreated,
|
||||
"FAIL: Create returned status %d", status)
|
||||
t.Logf(" Created SQLite database: %s", dbName)
|
||||
|
||||
// Create table and insert data
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: env.GatewayURL + "/v1/db/sqlite/query",
|
||||
Headers: map[string]string{
|
||||
"Authorization": "Bearer " + env.APIKey,
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"database_name": dbName,
|
||||
"query": "CREATE TABLE IF NOT EXISTS test_table (id INTEGER PRIMARY KEY, data TEXT)",
|
||||
},
|
||||
}
|
||||
|
||||
_, status, err = queryReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Create table failed")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: Create table returned status %d", status)
|
||||
|
||||
// Insert data
|
||||
insertReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: env.GatewayURL + "/v1/db/sqlite/query",
|
||||
Headers: map[string]string{
|
||||
"Authorization": "Bearer " + env.APIKey,
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"database_name": dbName,
|
||||
"query": "INSERT INTO test_table (data) VALUES ('persistent_data')",
|
||||
},
|
||||
}
|
||||
|
||||
_, status, err = insertReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Insert failed")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: Insert returned status %d", status)
|
||||
|
||||
// Verify data persists
|
||||
selectReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: env.GatewayURL + "/v1/db/sqlite/query",
|
||||
Headers: map[string]string{
|
||||
"Authorization": "Bearer " + env.APIKey,
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"database_name": dbName,
|
||||
"query": "SELECT data FROM test_table",
|
||||
},
|
||||
}
|
||||
|
||||
body, status, err := selectReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Select failed")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: Select returned status %d", status)
|
||||
require.Contains(t, string(body), "persistent_data",
|
||||
"FAIL: Data not found in SQLite database")
|
||||
|
||||
t.Logf(" ✓ SQLite database data persists")
|
||||
})
|
||||
|
||||
t.Run("SQLite_database_listed", func(t *testing.T) {
|
||||
// List databases to verify it was persisted
|
||||
listReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: env.GatewayURL + "/v1/db/sqlite/list",
|
||||
Headers: map[string]string{
|
||||
"Authorization": "Bearer " + env.APIKey,
|
||||
},
|
||||
}
|
||||
|
||||
body, status, err := listReq.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: List databases failed")
|
||||
require.Equal(t, http.StatusOK, status, "FAIL: List returned status %d", status)
|
||||
require.Contains(t, string(body), dbName,
|
||||
"FAIL: Created database not found in list")
|
||||
|
||||
t.Logf(" ✓ SQLite database appears in list")
|
||||
})
|
||||
}
|
||||
356
core/e2e/integration/domain_routing_test.go
Normal file
356
core/e2e/integration/domain_routing_test.go
Normal file
@ -0,0 +1,356 @@
|
||||
//go:build e2e
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDomainRouting_BasicRouting(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("test-routing-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for deployment to be active
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// Get deployment details for debugging
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
t.Logf("Deployment created: ID=%s, CID=%s, Name=%s, Status=%s",
|
||||
deploymentID, deployment["content_cid"], deployment["name"], deployment["status"])
|
||||
|
||||
t.Run("Standard domain resolves", func(t *testing.T) {
|
||||
// Domain format: {deploymentName}.{baseDomain}
|
||||
domain := env.BuildDeploymentDomain(deploymentName)
|
||||
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "Should return 200 OK")
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err, "Should read response body")
|
||||
|
||||
assert.Contains(t, string(body), "<div id=\"root\">", "Should serve React app")
|
||||
assert.Contains(t, resp.Header.Get("Content-Type"), "text/html", "Content-Type should be HTML")
|
||||
|
||||
t.Logf("✓ Standard domain routing works: %s", domain)
|
||||
})
|
||||
|
||||
t.Run("Non-orama domain passes through", func(t *testing.T) {
|
||||
// Request with non-orama domain should not route to deployment
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, "example.com", "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should either return 404 or pass to default handler
|
||||
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
|
||||
"Non-orama domain should not route to deployment")
|
||||
|
||||
t.Logf("✓ Non-orama domains correctly pass through (status: %d)", resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("API paths bypass domain routing", func(t *testing.T) {
|
||||
// /v1/* paths should bypass domain routing and use API key auth
|
||||
domain := env.BuildDeploymentDomain(deploymentName)
|
||||
|
||||
req, _ := http.NewRequest("GET", env.GatewayURL+"/v1/deployments/list", nil)
|
||||
req.Host = domain
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should return API response, not deployment content
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "API endpoint should work")
|
||||
|
||||
var result map[string]interface{}
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
err = json.Unmarshal(bodyBytes, &result)
|
||||
|
||||
// Should be JSON API response
|
||||
assert.NoError(t, err, "Should decode JSON (API response)")
|
||||
assert.NotNil(t, result["deployments"], "Should have deployments field")
|
||||
|
||||
t.Logf("✓ API paths correctly bypass domain routing")
|
||||
})
|
||||
|
||||
t.Run("Well-known paths bypass domain routing", func(t *testing.T) {
|
||||
domain := env.BuildDeploymentDomain(deploymentName)
|
||||
|
||||
// /.well-known/ paths should bypass (used for ACME challenges, etc.)
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/.well-known/acme-challenge/test")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should not serve deployment content
|
||||
// Exact status depends on implementation, but shouldn't be deployment content
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
bodyStr := string(body)
|
||||
|
||||
// Shouldn't contain React app content
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
assert.NotContains(t, bodyStr, "<div id=\"root\">",
|
||||
"Well-known paths should not serve deployment content")
|
||||
}
|
||||
|
||||
t.Logf("✓ Well-known paths bypass routing (status: %d)", resp.StatusCode)
|
||||
})
|
||||
}
|
||||
|
||||
func TestDomainRouting_MultipleDeployments(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
// Create multiple deployments
|
||||
deployment1Name := fmt.Sprintf("test-multi-1-%d", time.Now().Unix())
|
||||
deployment2Name := fmt.Sprintf("test-multi-2-%d", time.Now().Unix())
|
||||
|
||||
deployment1ID := e2e.CreateTestDeployment(t, env, deployment1Name, tarballPath)
|
||||
time.Sleep(1 * time.Second)
|
||||
deployment2ID := e2e.CreateTestDeployment(t, env, deployment2Name, tarballPath)
|
||||
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deployment1ID)
|
||||
e2e.DeleteDeployment(t, env, deployment2ID)
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
t.Run("Each deployment routes independently", func(t *testing.T) {
|
||||
domain1 := env.BuildDeploymentDomain(deployment1Name)
|
||||
domain2 := env.BuildDeploymentDomain(deployment2Name)
|
||||
|
||||
// Test deployment 1
|
||||
resp1 := e2e.TestDeploymentWithHostHeader(t, env, domain1, "/")
|
||||
defer resp1.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp1.StatusCode, "Deployment 1 should serve")
|
||||
|
||||
// Test deployment 2
|
||||
resp2 := e2e.TestDeploymentWithHostHeader(t, env, domain2, "/")
|
||||
defer resp2.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp2.StatusCode, "Deployment 2 should serve")
|
||||
|
||||
t.Logf("✓ Multiple deployments route independently")
|
||||
t.Logf(" - Domain 1: %s", domain1)
|
||||
t.Logf(" - Domain 2: %s", domain2)
|
||||
})
|
||||
|
||||
t.Run("Wrong domain returns 404", func(t *testing.T) {
|
||||
// Request with non-existent deployment subdomain
|
||||
fakeDeploymentDomain := env.BuildDeploymentDomain(fmt.Sprintf("nonexistent-deployment-%d", time.Now().Unix()))
|
||||
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, fakeDeploymentDomain, "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusNotFound, resp.StatusCode,
|
||||
"Non-existent deployment should return 404")
|
||||
|
||||
t.Logf("✓ Non-existent deployment returns 404")
|
||||
})
|
||||
}
|
||||
|
||||
func TestDomainRouting_ContentTypes(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("test-content-types-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
domain := env.BuildDeploymentDomain(deploymentName)
|
||||
|
||||
contentTypeTests := []struct {
|
||||
path string
|
||||
shouldHave string
|
||||
description string
|
||||
}{
|
||||
{"/", "text/html", "HTML root"},
|
||||
{"/index.html", "text/html", "HTML file"},
|
||||
}
|
||||
|
||||
for _, test := range contentTypeTests {
|
||||
t.Run(test.description, func(t *testing.T) {
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, test.path)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
contentType := resp.Header.Get("Content-Type")
|
||||
assert.Contains(t, contentType, test.shouldHave,
|
||||
"Content-Type for %s should contain %s", test.path, test.shouldHave)
|
||||
|
||||
t.Logf("✓ %s: %s", test.description, contentType)
|
||||
} else {
|
||||
t.Logf("⚠ %s returned status %d", test.path, resp.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDomainRouting_SPAFallback(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("test-spa-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
domain := env.BuildDeploymentDomain(deploymentName)
|
||||
|
||||
t.Run("Unknown paths fall back to index.html", func(t *testing.T) {
|
||||
unknownPaths := []string{
|
||||
"/about",
|
||||
"/users/123",
|
||||
"/settings/profile",
|
||||
"/some/deep/nested/path",
|
||||
}
|
||||
|
||||
for _, path := range unknownPaths {
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, path)
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
// Should return index.html for SPA routing
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"SPA fallback should return 200 for %s", path)
|
||||
|
||||
assert.Contains(t, string(body), "<div id=\"root\">",
|
||||
"SPA fallback should return index.html for %s", path)
|
||||
}
|
||||
|
||||
t.Logf("✓ SPA fallback routing verified for %d paths", len(unknownPaths))
|
||||
})
|
||||
}
|
||||
|
||||
// TestDeployment_DomainFormat verifies that deployment URLs use the correct format:
|
||||
// - CORRECT: {name}-{random}.{baseDomain} (e.g., "myapp-f3o4if.dbrs.space")
|
||||
// - WRONG: {name}.node-{shortID}.{baseDomain} (should NOT exist)
|
||||
func TestDeployment_DomainFormat(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("format-test-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for deployment
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
t.Run("Deployment URL has correct format", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
|
||||
// Get the deployment URLs
|
||||
urls, ok := deployment["urls"].([]interface{})
|
||||
if !ok || len(urls) == 0 {
|
||||
// Fall back to single url field
|
||||
if url, ok := deployment["url"].(string); ok && url != "" {
|
||||
urls = []interface{}{url}
|
||||
}
|
||||
}
|
||||
|
||||
// Get the subdomain from deployment response
|
||||
subdomain, _ := deployment["subdomain"].(string)
|
||||
t.Logf("Deployment subdomain: %s", subdomain)
|
||||
t.Logf("Deployment URLs: %v", urls)
|
||||
|
||||
foundCorrectFormat := false
|
||||
for _, u := range urls {
|
||||
urlStr, ok := u.(string)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
// URL should start with https://{name}-
|
||||
expectedPrefix := fmt.Sprintf("https://%s-", deploymentName)
|
||||
if strings.HasPrefix(urlStr, expectedPrefix) {
|
||||
foundCorrectFormat = true
|
||||
}
|
||||
|
||||
// URL should contain base domain
|
||||
assert.Contains(t, urlStr, env.BaseDomain,
|
||||
"URL should contain base domain %s", env.BaseDomain)
|
||||
|
||||
// URL should NOT contain node identifier pattern
|
||||
assert.NotContains(t, urlStr, ".node-",
|
||||
"URL should NOT have node identifier (got: %s)", urlStr)
|
||||
}
|
||||
|
||||
if len(urls) > 0 {
|
||||
assert.True(t, foundCorrectFormat, "Should find URL with correct domain format (https://{name}-{random}.{baseDomain})")
|
||||
}
|
||||
|
||||
t.Logf("✓ Domain format verification passed")
|
||||
t.Logf(" - Format: {name}-{random}.{baseDomain}")
|
||||
})
|
||||
|
||||
t.Run("Domain resolves via Host header", func(t *testing.T) {
|
||||
// Get the actual subdomain from the deployment
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
subdomain, _ := deployment["subdomain"].(string)
|
||||
if subdomain == "" {
|
||||
t.Skip("No subdomain set, skipping host header test")
|
||||
}
|
||||
domain := subdomain + "." + env.BaseDomain
|
||||
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"Domain %s should resolve successfully", domain)
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Contains(t, string(body), "<div id=\"root\">",
|
||||
"Should serve deployment content")
|
||||
|
||||
t.Logf("✓ Domain %s resolves correctly", domain)
|
||||
})
|
||||
}
|
||||
278
core/e2e/integration/fullstack_integration_test.go
Normal file
278
core/e2e/integration/fullstack_integration_test.go
Normal file
@ -0,0 +1,278 @@
|
||||
//go:build e2e
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestFullStack_GoAPI_SQLite(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
appName := fmt.Sprintf("fullstack-app-%d", time.Now().Unix())
|
||||
backendName := appName + "-backend"
|
||||
dbName := appName + "-db"
|
||||
|
||||
var backendID string
|
||||
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
if backendID != "" {
|
||||
e2e.DeleteDeployment(t, env, backendID)
|
||||
}
|
||||
e2e.DeleteSQLiteDB(t, env, dbName)
|
||||
}
|
||||
}()
|
||||
|
||||
// Step 1: Create SQLite database
|
||||
t.Run("Create SQLite database", func(t *testing.T) {
|
||||
e2e.CreateSQLiteDB(t, env, dbName)
|
||||
|
||||
// Create users table
|
||||
query := `CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
email TEXT UNIQUE NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)`
|
||||
e2e.ExecuteSQLQuery(t, env, dbName, query)
|
||||
|
||||
// Insert test data
|
||||
insertQuery := `INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')`
|
||||
result := e2e.ExecuteSQLQuery(t, env, dbName, insertQuery)
|
||||
|
||||
assert.NotNil(t, result, "Should execute INSERT successfully")
|
||||
t.Logf("✓ Database created with users table")
|
||||
})
|
||||
|
||||
// Step 2: Deploy Go backend (this would normally connect to SQLite)
|
||||
// Note: For now we test the Go backend deployment without actual DB connection
|
||||
// as that requires environment variable injection during deployment
|
||||
t.Run("Deploy Go backend", func(t *testing.T) {
|
||||
tarballPath := filepath.Join("../../testdata/apps/go-api")
|
||||
|
||||
// Note: In a real implementation, we would pass DATABASE_NAME env var
|
||||
// For now, we just test the deployment mechanism
|
||||
backendID = e2e.CreateTestDeployment(t, env, backendName, tarballPath)
|
||||
|
||||
assert.NotEmpty(t, backendID, "Backend deployment ID should not be empty")
|
||||
t.Logf("✓ Go backend deployed: %s", backendName)
|
||||
|
||||
// Wait for deployment to become active
|
||||
time.Sleep(3 * time.Second)
|
||||
})
|
||||
|
||||
// Step 3: Test database operations
|
||||
t.Run("Test database CRUD operations", func(t *testing.T) {
|
||||
// INSERT
|
||||
insertQuery := `INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com')`
|
||||
e2e.ExecuteSQLQuery(t, env, dbName, insertQuery)
|
||||
|
||||
// SELECT
|
||||
users := e2e.QuerySQLite(t, env, dbName, "SELECT * FROM users ORDER BY id")
|
||||
require.GreaterOrEqual(t, len(users), 2, "Should have at least 2 users")
|
||||
|
||||
assert.Equal(t, "Alice", users[0]["name"], "First user should be Alice")
|
||||
assert.Equal(t, "Bob", users[1]["name"], "Second user should be Bob")
|
||||
|
||||
t.Logf("✓ Database CRUD operations work")
|
||||
t.Logf(" - Found %d users", len(users))
|
||||
|
||||
// UPDATE
|
||||
updateQuery := `UPDATE users SET email = 'alice.new@example.com' WHERE name = 'Alice'`
|
||||
result := e2e.ExecuteSQLQuery(t, env, dbName, updateQuery)
|
||||
|
||||
rowsAffected, ok := result["rows_affected"].(float64)
|
||||
require.True(t, ok, "Should have rows_affected")
|
||||
assert.Equal(t, float64(1), rowsAffected, "Should update 1 row")
|
||||
|
||||
// Verify update
|
||||
updated := e2e.QuerySQLite(t, env, dbName, "SELECT email FROM users WHERE name = 'Alice'")
|
||||
require.Len(t, updated, 1, "Should find Alice")
|
||||
assert.Equal(t, "alice.new@example.com", updated[0]["email"], "Email should be updated")
|
||||
|
||||
t.Logf("✓ UPDATE operation verified")
|
||||
|
||||
// DELETE
|
||||
deleteQuery := `DELETE FROM users WHERE name = 'Bob'`
|
||||
result = e2e.ExecuteSQLQuery(t, env, dbName, deleteQuery)
|
||||
|
||||
rowsAffected, ok = result["rows_affected"].(float64)
|
||||
require.True(t, ok, "Should have rows_affected")
|
||||
assert.Equal(t, float64(1), rowsAffected, "Should delete 1 row")
|
||||
|
||||
// Verify deletion
|
||||
remaining := e2e.QuerySQLite(t, env, dbName, "SELECT * FROM users")
|
||||
assert.Equal(t, 1, len(remaining), "Should have 1 user remaining")
|
||||
|
||||
t.Logf("✓ DELETE operation verified")
|
||||
})
|
||||
|
||||
// Step 4: Test backend API endpoints (if deployment is active)
|
||||
t.Run("Test backend API endpoints", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, backendID)
|
||||
|
||||
status, ok := deployment["status"].(string)
|
||||
if !ok || status != "active" {
|
||||
t.Skip("Backend deployment not active, skipping API tests")
|
||||
return
|
||||
}
|
||||
|
||||
backendDomain := env.BuildDeploymentDomain(backendName)
|
||||
|
||||
// Test health endpoint
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, backendDomain, "/health")
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
var health map[string]interface{}
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
require.NoError(t, json.Unmarshal(bodyBytes, &health), "Should decode health response")
|
||||
|
||||
assert.Equal(t, "healthy", health["status"], "Status should be healthy")
|
||||
assert.Equal(t, "go-backend-test", health["service"], "Service name should match")
|
||||
|
||||
t.Logf("✓ Backend health check passed")
|
||||
} else {
|
||||
t.Logf("⚠ Health check returned status %d (deployment may still be starting)", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Test users API endpoint
|
||||
resp2 := e2e.TestDeploymentWithHostHeader(t, env, backendDomain, "/api/users")
|
||||
defer resp2.Body.Close()
|
||||
|
||||
if resp2.StatusCode == http.StatusOK {
|
||||
var usersResp map[string]interface{}
|
||||
bodyBytes, _ := io.ReadAll(resp2.Body)
|
||||
require.NoError(t, json.Unmarshal(bodyBytes, &usersResp), "Should decode users response")
|
||||
|
||||
users, ok := usersResp["users"].([]interface{})
|
||||
require.True(t, ok, "Should have users array")
|
||||
assert.GreaterOrEqual(t, len(users), 3, "Should have test users")
|
||||
|
||||
t.Logf("✓ Backend API endpoint works")
|
||||
t.Logf(" - Users endpoint returned %d users", len(users))
|
||||
} else {
|
||||
t.Logf("⚠ Users API returned status %d (deployment may still be starting)", resp2.StatusCode)
|
||||
}
|
||||
})
|
||||
|
||||
// Step 5: Test database backup
|
||||
t.Run("Test database backup", func(t *testing.T) {
|
||||
reqBody := map[string]string{"database_name": dbName}
|
||||
bodyBytes, _ := json.Marshal(reqBody)
|
||||
|
||||
req, _ := http.NewRequest("POST", env.GatewayURL+"/v1/db/sqlite/backup", bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err, "Should execute backup request")
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
var result map[string]interface{}
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
require.NoError(t, json.Unmarshal(bodyBytes, &result), "Should decode backup response")
|
||||
|
||||
backupCID, ok := result["backup_cid"].(string)
|
||||
require.True(t, ok, "Should have backup CID")
|
||||
assert.NotEmpty(t, backupCID, "Backup CID should not be empty")
|
||||
|
||||
t.Logf("✓ Database backup created")
|
||||
t.Logf(" - CID: %s", backupCID)
|
||||
} else {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Logf("⚠ Backup returned status %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
})
|
||||
|
||||
// Step 6: Test concurrent database queries
|
||||
t.Run("Test concurrent database reads", func(t *testing.T) {
|
||||
// WAL mode should allow concurrent reads — run sequentially to avoid t.Fatal in goroutines
|
||||
for i := 0; i < 5; i++ {
|
||||
users := e2e.QuerySQLite(t, env, dbName, "SELECT * FROM users")
|
||||
assert.GreaterOrEqual(t, len(users), 0, "Should query successfully")
|
||||
}
|
||||
|
||||
t.Logf("✓ Sequential reads successful")
|
||||
})
|
||||
}
|
||||
|
||||
func TestFullStack_StaticSite_SQLite(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
appName := fmt.Sprintf("fullstack-static-%d", time.Now().Unix())
|
||||
frontendName := appName + "-frontend"
|
||||
dbName := appName + "-db"
|
||||
|
||||
var frontendID string
|
||||
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
if frontendID != "" {
|
||||
e2e.DeleteDeployment(t, env, frontendID)
|
||||
}
|
||||
e2e.DeleteSQLiteDB(t, env, dbName)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Deploy static site and create database", func(t *testing.T) {
|
||||
// Create database
|
||||
e2e.CreateSQLiteDB(t, env, dbName)
|
||||
e2e.ExecuteSQLQuery(t, env, dbName, "CREATE TABLE page_views (id INTEGER PRIMARY KEY, page TEXT, count INTEGER)")
|
||||
e2e.ExecuteSQLQuery(t, env, dbName, "INSERT INTO page_views (page, count) VALUES ('home', 0)")
|
||||
|
||||
// Deploy frontend
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
frontendID = e2e.CreateTestDeployment(t, env, frontendName, tarballPath)
|
||||
|
||||
assert.NotEmpty(t, frontendID, "Frontend deployment should succeed")
|
||||
t.Logf("✓ Static site deployed with SQLite backend")
|
||||
|
||||
// Wait for deployment
|
||||
time.Sleep(2 * time.Second)
|
||||
})
|
||||
|
||||
t.Run("Test frontend serving and database interaction", func(t *testing.T) {
|
||||
frontendDomain := env.BuildDeploymentDomain(frontendName)
|
||||
|
||||
// Test frontend
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, frontendDomain, "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "Frontend should serve")
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
assert.Contains(t, string(body), "<div id=\"root\">", "Should contain React app")
|
||||
|
||||
// Simulate page view tracking
|
||||
e2e.ExecuteSQLQuery(t, env, dbName, "UPDATE page_views SET count = count + 1 WHERE page = 'home'")
|
||||
|
||||
// Verify count
|
||||
views := e2e.QuerySQLite(t, env, dbName, "SELECT count FROM page_views WHERE page = 'home'")
|
||||
require.Len(t, views, 1, "Should have page view record")
|
||||
|
||||
count, ok := views[0]["count"].(float64)
|
||||
require.True(t, ok, "Count should be a number")
|
||||
assert.Equal(t, float64(1), count, "Page view count should be incremented")
|
||||
|
||||
t.Logf("✓ Full stack integration verified")
|
||||
t.Logf(" - Frontend: %s", frontendDomain)
|
||||
t.Logf(" - Database: %s", dbName)
|
||||
t.Logf(" - Page views tracked: %.0f", count)
|
||||
})
|
||||
}
|
||||
125
core/e2e/integration/ipfs_replica_test.go
Normal file
125
core/e2e/integration/ipfs_replica_test.go
Normal file
@ -0,0 +1,125 @@
|
||||
//go:build e2e
|
||||
|
||||
package integration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestIPFS_ContentPinnedOnMultipleNodes verifies that deploying a static app
|
||||
// makes the IPFS content available across multiple nodes.
|
||||
func TestIPFS_ContentPinnedOnMultipleNodes(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err)
|
||||
|
||||
if len(env.Config.Servers) < 2 {
|
||||
t.Skip("Requires at least 2 servers")
|
||||
}
|
||||
|
||||
deploymentName := fmt.Sprintf("ipfs-pin-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID)
|
||||
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(15 * time.Second) // Wait for IPFS content replication
|
||||
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
contentCID, _ := deployment["content_cid"].(string)
|
||||
require.NotEmpty(t, contentCID, "Deployment should have a content CID")
|
||||
|
||||
t.Run("Content served via gateway", func(t *testing.T) {
|
||||
// Extract domain from deployment URLs
|
||||
urls, _ := deployment["urls"].([]interface{})
|
||||
require.NotEmpty(t, urls, "Deployment should have URLs")
|
||||
urlStr, _ := urls[0].(string)
|
||||
domain := urlStr
|
||||
if len(urlStr) > 8 && urlStr[:8] == "https://" {
|
||||
domain = urlStr[8:]
|
||||
} else if len(urlStr) > 7 && urlStr[:7] == "http://" {
|
||||
domain = urlStr[7:]
|
||||
}
|
||||
if len(domain) > 0 && domain[len(domain)-1] == '/' {
|
||||
domain = domain[:len(domain)-1]
|
||||
}
|
||||
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
t.Logf("status=%d, body=%d bytes", resp.StatusCode, len(body))
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"IPFS content should be served via gateway (CID: %s)", contentCID)
|
||||
})
|
||||
}
|
||||
|
||||
// TestIPFS_LargeFileDeployment verifies that deploying an app with larger
|
||||
// static assets works correctly.
|
||||
func TestIPFS_LargeFileDeployment(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err)
|
||||
|
||||
deploymentName := fmt.Sprintf("ipfs-large-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
// The react-vite tarball is our largest test asset
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID)
|
||||
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
t.Run("Deployment has valid CID", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
contentCID, _ := deployment["content_cid"].(string)
|
||||
assert.NotEmpty(t, contentCID, "Should have a content CID")
|
||||
assert.True(t, len(contentCID) > 10, "CID should be a valid IPFS hash")
|
||||
t.Logf("Content CID: %s", contentCID)
|
||||
})
|
||||
|
||||
t.Run("Static content serves correctly", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
urls, ok := deployment["urls"].([]interface{})
|
||||
if !ok || len(urls) == 0 {
|
||||
t.Skip("No URLs in deployment")
|
||||
}
|
||||
|
||||
nodeURL, _ := urls[0].(string)
|
||||
domain := nodeURL
|
||||
if len(nodeURL) > 8 && nodeURL[:8] == "https://" {
|
||||
domain = nodeURL[8:]
|
||||
} else if len(nodeURL) > 7 && nodeURL[:7] == "http://" {
|
||||
domain = nodeURL[7:]
|
||||
}
|
||||
if len(domain) > 0 && domain[len(domain)-1] == '/' {
|
||||
domain = domain[:len(domain)-1]
|
||||
}
|
||||
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Greater(t, len(body), 100, "Response should have substantial content")
|
||||
})
|
||||
}
|
||||
136
core/e2e/production/cross_node_proxy_test.go
Normal file
136
core/e2e/production/cross_node_proxy_test.go
Normal file
@ -0,0 +1,136 @@
|
||||
//go:build e2e && production
|
||||
|
||||
package production
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestCrossNode_ProxyRouting tests that requests routed through the gateway
|
||||
// are served correctly for a deployment.
|
||||
func TestCrossNode_ProxyRouting(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
if len(env.Config.Servers) < 2 {
|
||||
t.Skip("Cross-node testing requires at least 2 servers in config")
|
||||
}
|
||||
|
||||
deploymentName := fmt.Sprintf("proxy-test-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for deployment to be active
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
domain := env.BuildDeploymentDomain(deploymentName)
|
||||
t.Logf("Testing routing for: %s", domain)
|
||||
|
||||
t.Run("Request via gateway succeeds", func(t *testing.T) {
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"Request should return 200 (got %d: %s)", resp.StatusCode, string(body))
|
||||
|
||||
assert.Contains(t, string(body), "<div id=\"root\">",
|
||||
"Should serve deployment content")
|
||||
})
|
||||
}
|
||||
|
||||
// TestCrossNode_APIConsistency tests that API responses are consistent
|
||||
func TestCrossNode_APIConsistency(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("consistency-test-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for replication
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
t.Run("Deployment list contains our deployment", func(t *testing.T) {
|
||||
req, err := http.NewRequest("GET", env.GatewayURL+"/v1/deployments/list", nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
var result map[string]interface{}
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&result))
|
||||
|
||||
deployments, ok := result["deployments"].([]interface{})
|
||||
require.True(t, ok, "Response should have deployments array")
|
||||
t.Logf("Gateway reports %d deployments", len(deployments))
|
||||
|
||||
found := false
|
||||
for _, d := range deployments {
|
||||
dep, _ := d.(map[string]interface{})
|
||||
if dep["name"] == deploymentName {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
assert.True(t, found, "Our deployment should be in the list")
|
||||
})
|
||||
}
|
||||
|
||||
// TestCrossNode_DeploymentGetConsistency tests that deployment details are correct
|
||||
func TestCrossNode_DeploymentGetConsistency(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("get-consistency-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for replication
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
t.Run("Deployment details are correct", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
|
||||
cid, _ := deployment["content_cid"].(string)
|
||||
assert.NotEmpty(t, cid, "Should have a content CID")
|
||||
|
||||
name, _ := deployment["name"].(string)
|
||||
assert.Equal(t, deploymentName, name, "Name should match")
|
||||
|
||||
t.Logf("Deployment: name=%s, cid=%s, status=%s", name, cid, deployment["status"])
|
||||
})
|
||||
}
|
||||
228
core/e2e/production/failover_test.go
Normal file
228
core/e2e/production/failover_test.go
Normal file
@ -0,0 +1,228 @@
|
||||
//go:build e2e && production
|
||||
|
||||
package production
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestFailover_HomeNodeDown verifies that when the home node's deployment process
|
||||
// is down, requests still succeed via the replica node.
|
||||
func TestFailover_HomeNodeDown(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err)
|
||||
|
||||
if len(env.Config.Servers) < 2 {
|
||||
t.Skip("Failover testing requires at least 2 servers")
|
||||
}
|
||||
|
||||
// Deploy a Node.js backend so we have a process to stop
|
||||
deploymentName := fmt.Sprintf("failover-test-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/node-api")
|
||||
|
||||
deploymentID := createNodeJSDeploymentProd(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID)
|
||||
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for deployment and replica
|
||||
healthy := e2e.WaitForHealthy(t, env, deploymentID, 90*time.Second)
|
||||
require.True(t, healthy, "Deployment should become healthy")
|
||||
time.Sleep(20 * time.Second) // Wait for async replica setup
|
||||
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURLProd(t, deployment)
|
||||
require.NotEmpty(t, nodeURL)
|
||||
domain := extractDomainProd(nodeURL)
|
||||
|
||||
t.Run("Deployment serves via gateway", func(t *testing.T) {
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/health")
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"Deployment should be served via gateway (got %d: %s)", resp.StatusCode, string(body))
|
||||
t.Logf("Gateway response: status=%d body=%s", resp.StatusCode, string(body))
|
||||
})
|
||||
}
|
||||
|
||||
// TestFailover_5xxRetry verifies that if one node returns a gateway error,
|
||||
// the middleware retries on the next replica.
|
||||
func TestFailover_5xxRetry(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err)
|
||||
|
||||
if len(env.Config.Servers) < 2 {
|
||||
t.Skip("Requires at least 2 servers")
|
||||
}
|
||||
|
||||
// Deploy a static app (always works via IPFS, no process to crash)
|
||||
deploymentName := fmt.Sprintf("retry-test-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID)
|
||||
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(10 * time.Second)
|
||||
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
nodeURL := extractNodeURLProd(t, deployment)
|
||||
if nodeURL == "" {
|
||||
t.Skip("No node URL")
|
||||
}
|
||||
domain := extractDomainProd(nodeURL)
|
||||
|
||||
t.Run("Deployment serves successfully", func(t *testing.T) {
|
||||
resp := e2e.TestDeploymentWithHostHeader(t, env, domain, "/")
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"Static content should be served (got %d: %s)", resp.StatusCode, string(body))
|
||||
})
|
||||
}
|
||||
|
||||
// TestFailover_CrossNodeProxyTimeout verifies that cross-node proxy fails fast
|
||||
// (within a reasonable timeout) rather than hanging.
|
||||
func TestFailover_CrossNodeProxyTimeout(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err)
|
||||
|
||||
if len(env.Config.Servers) < 2 {
|
||||
t.Skip("Requires at least 2 servers")
|
||||
}
|
||||
|
||||
// Make a request to a non-existent deployment — should fail fast
|
||||
domain := fmt.Sprintf("nonexistent-%d.%s", time.Now().Unix(), env.BaseDomain)
|
||||
|
||||
start := time.Now()
|
||||
|
||||
req, _ := http.NewRequest("GET", env.GatewayURL+"/", nil)
|
||||
req.Host = domain
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if err != nil {
|
||||
t.Logf("Request failed in %v: %v", elapsed, err)
|
||||
} else {
|
||||
resp.Body.Close()
|
||||
t.Logf("Got status %d in %v", resp.StatusCode, elapsed)
|
||||
}
|
||||
|
||||
// Should respond within 15 seconds (our proxy timeout is 5s)
|
||||
assert.Less(t, elapsed.Seconds(), 15.0,
|
||||
"Request to non-existent deployment should fail fast, took %v", elapsed)
|
||||
}
|
||||
|
||||
func createNodeJSDeploymentProd(t *testing.T, env *e2e.E2ETestEnv, name, tarballPath string) string {
|
||||
t.Helper()
|
||||
|
||||
var fileData []byte
|
||||
|
||||
info, err := os.Stat(tarballPath)
|
||||
require.NoError(t, err, "Failed to stat: %s", tarballPath)
|
||||
|
||||
if info.IsDir() {
|
||||
tarData, err := exec.Command("tar", "-czf", "-", "-C", tarballPath, ".").Output()
|
||||
require.NoError(t, err, "Failed to create tarball from %s", tarballPath)
|
||||
fileData = tarData
|
||||
} else {
|
||||
file, err := os.Open(tarballPath)
|
||||
require.NoError(t, err, "Failed to open tarball: %s", tarballPath)
|
||||
defer file.Close()
|
||||
fileData, _ = io.ReadAll(file)
|
||||
}
|
||||
|
||||
body := &bytes.Buffer{}
|
||||
boundary := "----WebKitFormBoundary7MA4YWxkTrZu0gW"
|
||||
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"name\"\r\n\r\n")
|
||||
body.WriteString(name + "\r\n")
|
||||
|
||||
body.WriteString("--" + boundary + "\r\n")
|
||||
body.WriteString("Content-Disposition: form-data; name=\"tarball\"; filename=\"app.tar.gz\"\r\n")
|
||||
body.WriteString("Content-Type: application/gzip\r\n\r\n")
|
||||
|
||||
body.Write(fileData)
|
||||
body.WriteString("\r\n--" + boundary + "--\r\n")
|
||||
|
||||
req, err := http.NewRequest("POST", env.GatewayURL+"/v1/deployments/nodejs/upload", body)
|
||||
require.NoError(t, err)
|
||||
|
||||
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
t.Fatalf("Deployment upload failed with status %d: %s", resp.StatusCode, string(bodyBytes))
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&result))
|
||||
|
||||
if id, ok := result["deployment_id"].(string); ok {
|
||||
return id
|
||||
}
|
||||
if id, ok := result["id"].(string); ok {
|
||||
return id
|
||||
}
|
||||
t.Fatalf("Deployment response missing id: %+v", result)
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractNodeURLProd(t *testing.T, deployment map[string]interface{}) string {
|
||||
t.Helper()
|
||||
if urls, ok := deployment["urls"].([]interface{}); ok && len(urls) > 0 {
|
||||
if url, ok := urls[0].(string); ok {
|
||||
return url
|
||||
}
|
||||
}
|
||||
if urls, ok := deployment["urls"].(map[string]interface{}); ok {
|
||||
if url, ok := urls["node"].(string); ok {
|
||||
return url
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractDomainProd(url string) string {
|
||||
domain := url
|
||||
if len(url) > 8 && url[:8] == "https://" {
|
||||
domain = url[8:]
|
||||
} else if len(url) > 7 && url[:7] == "http://" {
|
||||
domain = url[7:]
|
||||
}
|
||||
if len(domain) > 0 && domain[len(domain)-1] == '/' {
|
||||
domain = domain[:len(domain)-1]
|
||||
}
|
||||
return domain
|
||||
}
|
||||
185
core/e2e/production/https_certificate_test.go
Normal file
185
core/e2e/production/https_certificate_test.go
Normal file
@ -0,0 +1,185 @@
|
||||
//go:build e2e && production
|
||||
|
||||
package production
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestHTTPS_CertificateValid tests that HTTPS works with a valid certificate
|
||||
func TestHTTPS_CertificateValid(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("https-test-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
|
||||
deploymentID := e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
defer func() {
|
||||
if !env.SkipCleanup {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for deployment and certificate provisioning
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
domain := env.BuildDeploymentDomain(deploymentName)
|
||||
httpsURL := fmt.Sprintf("https://%s", domain)
|
||||
|
||||
t.Run("HTTPS connection with certificate verification", func(t *testing.T) {
|
||||
// Create client that DOES verify certificates
|
||||
client := &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
// Do NOT skip verification - we want to test real certs
|
||||
InsecureSkipVerify: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", httpsURL+"/", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
// Certificate might not be ready yet, or domain might not resolve
|
||||
t.Logf("⚠ HTTPS request failed (this may be expected if certs are still provisioning): %v", err)
|
||||
t.Skip("HTTPS not available or certificate not ready")
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Logf("HTTPS returned %d (deployment may not be routed yet): %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
// Check TLS connection state
|
||||
if resp.TLS != nil {
|
||||
t.Logf("✓ HTTPS works with valid certificate")
|
||||
t.Logf(" - Domain: %s", domain)
|
||||
t.Logf(" - TLS Version: %x", resp.TLS.Version)
|
||||
t.Logf(" - Cipher Suite: %x", resp.TLS.CipherSuite)
|
||||
if len(resp.TLS.PeerCertificates) > 0 {
|
||||
cert := resp.TLS.PeerCertificates[0]
|
||||
t.Logf(" - Certificate Subject: %s", cert.Subject)
|
||||
t.Logf(" - Certificate Issuer: %s", cert.Issuer)
|
||||
t.Logf(" - Valid Until: %s", cert.NotAfter)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestHTTPS_CertificateDetails tests certificate properties
|
||||
func TestHTTPS_CertificateDetails(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
t.Run("Base domain certificate", func(t *testing.T) {
|
||||
httpsURL := fmt.Sprintf("https://%s", env.BaseDomain)
|
||||
|
||||
// Connect and get certificate info
|
||||
conn, err := tls.Dial("tcp", env.BaseDomain+":443", &tls.Config{
|
||||
InsecureSkipVerify: true, // We just want to inspect the cert
|
||||
})
|
||||
if err != nil {
|
||||
t.Logf("⚠ Could not connect to %s:443: %v", env.BaseDomain, err)
|
||||
t.Skip("HTTPS not available on base domain")
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
certs := conn.ConnectionState().PeerCertificates
|
||||
require.NotEmpty(t, certs, "Should have certificates")
|
||||
|
||||
cert := certs[0]
|
||||
t.Logf("Certificate for %s:", env.BaseDomain)
|
||||
t.Logf(" - Subject: %s", cert.Subject)
|
||||
t.Logf(" - DNS Names: %v", cert.DNSNames)
|
||||
t.Logf(" - Valid From: %s", cert.NotBefore)
|
||||
t.Logf(" - Valid Until: %s", cert.NotAfter)
|
||||
t.Logf(" - Issuer: %s", cert.Issuer)
|
||||
|
||||
// Check that certificate covers our domain
|
||||
coversDomain := false
|
||||
for _, name := range cert.DNSNames {
|
||||
if name == env.BaseDomain || name == "*."+env.BaseDomain {
|
||||
coversDomain = true
|
||||
break
|
||||
}
|
||||
}
|
||||
assert.True(t, coversDomain, "Certificate should cover %s", env.BaseDomain)
|
||||
|
||||
// Check certificate is not expired
|
||||
assert.True(t, time.Now().Before(cert.NotAfter), "Certificate should not be expired")
|
||||
assert.True(t, time.Now().After(cert.NotBefore), "Certificate should be valid now")
|
||||
|
||||
// Make actual HTTPS request to verify it works
|
||||
client := &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
InsecureSkipVerify: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
resp, err := client.Get(httpsURL)
|
||||
if err != nil {
|
||||
t.Logf("⚠ HTTPS request failed: %v", err)
|
||||
} else {
|
||||
resp.Body.Close()
|
||||
t.Logf("✓ HTTPS request succeeded with status %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestHTTPS_HTTPRedirect tests that HTTP requests are redirected to HTTPS
|
||||
func TestHTTPS_HTTPRedirect(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
t.Run("HTTP redirects to HTTPS", func(t *testing.T) {
|
||||
// Create client that doesn't follow redirects
|
||||
client := &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
|
||||
httpURL := fmt.Sprintf("http://%s", env.BaseDomain)
|
||||
|
||||
resp, err := client.Get(httpURL)
|
||||
if err != nil {
|
||||
t.Logf("⚠ HTTP request failed: %v", err)
|
||||
t.Skip("HTTP not available or redirects not configured")
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Check for redirect
|
||||
if resp.StatusCode >= 300 && resp.StatusCode < 400 {
|
||||
location := resp.Header.Get("Location")
|
||||
t.Logf("✓ HTTP redirects to: %s (status %d)", location, resp.StatusCode)
|
||||
assert.Contains(t, location, "https://", "Should redirect to HTTPS")
|
||||
} else if resp.StatusCode == http.StatusOK {
|
||||
// HTTP might just serve content directly in some configurations
|
||||
t.Logf("⚠ HTTP returned 200 instead of redirect (HTTPS redirect may not be configured)")
|
||||
} else {
|
||||
t.Logf("HTTP returned status %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
204
core/e2e/production/https_external_test.go
Normal file
204
core/e2e/production/https_external_test.go
Normal file
@ -0,0 +1,204 @@
|
||||
//go:build e2e && production
|
||||
|
||||
package production
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestHTTPS_ExternalAccess tests that deployed apps are accessible via HTTPS
|
||||
// from the public internet with valid SSL certificates.
|
||||
//
|
||||
// This test requires:
|
||||
// - Orama deployed on a VPS with a real domain
|
||||
// - DNS properly configured
|
||||
// - Run with: go test -v -tags "e2e production" -run TestHTTPS ./e2e/production/...
|
||||
func TestHTTPS_ExternalAccess(t *testing.T) {
|
||||
// Skip if not configured for external testing
|
||||
externalURL := os.Getenv("ORAMA_EXTERNAL_URL")
|
||||
if externalURL == "" {
|
||||
t.Skip("ORAMA_EXTERNAL_URL not set - skipping external HTTPS test")
|
||||
}
|
||||
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("https-test-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
var deploymentID string
|
||||
|
||||
// Cleanup after test
|
||||
defer func() {
|
||||
if !env.SkipCleanup && deploymentID != "" {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Deploy static app", func(t *testing.T) {
|
||||
deploymentID = e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID)
|
||||
t.Logf("Created deployment: %s (ID: %s)", deploymentName, deploymentID)
|
||||
})
|
||||
|
||||
var deploymentDomain string
|
||||
|
||||
t.Run("Get deployment domain", func(t *testing.T) {
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
|
||||
nodeURL := extractNodeURL(t, deployment)
|
||||
require.NotEmpty(t, nodeURL, "Deployment should have node URL")
|
||||
|
||||
deploymentDomain = extractDomain(nodeURL)
|
||||
t.Logf("Deployment domain: %s", deploymentDomain)
|
||||
})
|
||||
|
||||
t.Run("Wait for DNS propagation", func(t *testing.T) {
|
||||
// Poll DNS until the domain resolves
|
||||
deadline := time.Now().Add(2 * time.Minute)
|
||||
|
||||
for time.Now().Before(deadline) {
|
||||
ips, err := net.LookupHost(deploymentDomain)
|
||||
if err == nil && len(ips) > 0 {
|
||||
t.Logf("DNS resolved: %s -> %v", deploymentDomain, ips)
|
||||
return
|
||||
}
|
||||
t.Logf("DNS not yet resolved, waiting...")
|
||||
time.Sleep(5 * time.Second)
|
||||
}
|
||||
|
||||
t.Fatalf("DNS did not resolve within timeout for %s", deploymentDomain)
|
||||
})
|
||||
|
||||
t.Run("Test HTTPS access with valid certificate", func(t *testing.T) {
|
||||
// Create HTTP client that DOES verify certificates
|
||||
// (no InsecureSkipVerify - we want to test real SSL)
|
||||
client := &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: &tls.Config{
|
||||
// Use default verification (validates certificate)
|
||||
InsecureSkipVerify: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("https://%s/", deploymentDomain)
|
||||
t.Logf("Testing HTTPS: %s", url)
|
||||
|
||||
resp, err := client.Get(url)
|
||||
require.NoError(t, err, "HTTPS request should succeed with valid certificate")
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode, "Should return 200 OK")
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify it's our React app
|
||||
assert.Contains(t, string(body), "<div id=\"root\">", "Should serve React app")
|
||||
|
||||
t.Logf("HTTPS test passed: %s returned %d", url, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("Verify SSL certificate details", func(t *testing.T) {
|
||||
conn, err := tls.Dial("tcp", deploymentDomain+":443", nil)
|
||||
require.NoError(t, err, "TLS dial should succeed")
|
||||
defer conn.Close()
|
||||
|
||||
state := conn.ConnectionState()
|
||||
require.NotEmpty(t, state.PeerCertificates, "Should have peer certificates")
|
||||
|
||||
cert := state.PeerCertificates[0]
|
||||
t.Logf("Certificate subject: %s", cert.Subject)
|
||||
t.Logf("Certificate issuer: %s", cert.Issuer)
|
||||
t.Logf("Certificate valid from: %s to %s", cert.NotBefore, cert.NotAfter)
|
||||
|
||||
// Verify certificate is not expired
|
||||
assert.True(t, time.Now().After(cert.NotBefore), "Certificate should be valid (not before)")
|
||||
assert.True(t, time.Now().Before(cert.NotAfter), "Certificate should be valid (not expired)")
|
||||
|
||||
// Verify domain matches
|
||||
err = cert.VerifyHostname(deploymentDomain)
|
||||
assert.NoError(t, err, "Certificate should be valid for domain %s", deploymentDomain)
|
||||
})
|
||||
}
|
||||
|
||||
// TestHTTPS_DomainFormat verifies deployment URL format
|
||||
func TestHTTPS_DomainFormat(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err, "Failed to load test environment")
|
||||
|
||||
deploymentName := fmt.Sprintf("domain-test-%d", time.Now().Unix())
|
||||
tarballPath := filepath.Join("../../testdata/apps/react-app")
|
||||
var deploymentID string
|
||||
|
||||
// Cleanup after test
|
||||
defer func() {
|
||||
if !env.SkipCleanup && deploymentID != "" {
|
||||
e2e.DeleteDeployment(t, env, deploymentID)
|
||||
}
|
||||
}()
|
||||
|
||||
t.Run("Deploy app and verify domain format", func(t *testing.T) {
|
||||
deploymentID = e2e.CreateTestDeployment(t, env, deploymentName, tarballPath)
|
||||
require.NotEmpty(t, deploymentID)
|
||||
|
||||
deployment := e2e.GetDeployment(t, env, deploymentID)
|
||||
|
||||
t.Logf("Deployment URLs: %+v", deployment["urls"])
|
||||
|
||||
// Get deployment URL (handles both array and map formats)
|
||||
deploymentURL := extractNodeURL(t, deployment)
|
||||
assert.NotEmpty(t, deploymentURL, "Should have deployment URL")
|
||||
|
||||
// URL should be simple format: {name}.{baseDomain} (NOT {name}.node-{shortID}.{baseDomain})
|
||||
if deploymentURL != "" {
|
||||
assert.NotContains(t, deploymentURL, ".node-", "URL should NOT contain node identifier (simplified format)")
|
||||
assert.Contains(t, deploymentURL, deploymentName, "URL should contain deployment name")
|
||||
t.Logf("Deployment URL: %s", deploymentURL)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func extractNodeURL(t *testing.T, deployment map[string]interface{}) string {
|
||||
t.Helper()
|
||||
|
||||
if urls, ok := deployment["urls"].([]interface{}); ok && len(urls) > 0 {
|
||||
if url, ok := urls[0].(string); ok {
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
if urls, ok := deployment["urls"].(map[string]interface{}); ok {
|
||||
if url, ok := urls["node"].(string); ok {
|
||||
return url
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractDomain(url string) string {
|
||||
domain := url
|
||||
if len(url) > 8 && url[:8] == "https://" {
|
||||
domain = url[8:]
|
||||
} else if len(url) > 7 && url[:7] == "http://" {
|
||||
domain = url[7:]
|
||||
}
|
||||
if len(domain) > 0 && domain[len(domain)-1] == '/' {
|
||||
domain = domain[:len(domain)-1]
|
||||
}
|
||||
return domain
|
||||
}
|
||||
95
core/e2e/production/middleware_test.go
Normal file
95
core/e2e/production/middleware_test.go
Normal file
@ -0,0 +1,95 @@
|
||||
//go:build e2e && production
|
||||
|
||||
package production
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestMiddleware_NonExistentDeployment verifies that requests to a non-existent
|
||||
// deployment return 404 (not 502 or hang).
|
||||
func TestMiddleware_NonExistentDeployment(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err)
|
||||
|
||||
domain := fmt.Sprintf("does-not-exist-%d.%s", time.Now().Unix(), env.BaseDomain)
|
||||
|
||||
req, _ := http.NewRequest("GET", env.GatewayURL+"/", nil)
|
||||
req.Host = domain
|
||||
|
||||
start := time.Now()
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if err != nil {
|
||||
t.Logf("Request failed in %v: %v", elapsed, err)
|
||||
// Connection refused or timeout is acceptable
|
||||
assert.Less(t, elapsed.Seconds(), 15.0, "Should fail fast")
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
t.Logf("Status: %d, elapsed: %v, body: %s", resp.StatusCode, elapsed, string(body))
|
||||
|
||||
// Should be 404 or 502, not 200
|
||||
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
|
||||
"Non-existent deployment should not return 200")
|
||||
assert.Less(t, elapsed.Seconds(), 15.0, "Should respond fast")
|
||||
}
|
||||
|
||||
// TestMiddleware_InternalAPIAuthRejection verifies that internal replica API
|
||||
// endpoints reject requests without the proper internal auth header.
|
||||
func TestMiddleware_InternalAPIAuthRejection(t *testing.T) {
|
||||
env, err := e2e.LoadTestEnv()
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("No auth header rejected", func(t *testing.T) {
|
||||
req, _ := http.NewRequest("POST",
|
||||
env.GatewayURL+"/v1/internal/deployments/replica/setup", nil)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Should be rejected (401 or 403)
|
||||
assert.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden,
|
||||
"Internal API without auth should be rejected (got %d)", resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("Wrong auth header rejected", func(t *testing.T) {
|
||||
req, _ := http.NewRequest("POST",
|
||||
env.GatewayURL+"/v1/internal/deployments/replica/setup", nil)
|
||||
req.Header.Set("X-Orama-Internal-Auth", "wrong-token")
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusBadRequest,
|
||||
"Internal API with wrong auth should be rejected (got %d)", resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("Regular API key does not grant internal access", func(t *testing.T) {
|
||||
req, _ := http.NewRequest("POST",
|
||||
env.GatewayURL+"/v1/internal/deployments/replica/setup", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+env.APIKey)
|
||||
|
||||
resp, err := env.HTTPClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
// The request may pass auth but fail on bad body — 400 is acceptable
|
||||
// But it should NOT succeed with 200
|
||||
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
|
||||
"Regular API key should not fully authenticate internal endpoints")
|
||||
})
|
||||
}
|
||||
148
core/e2e/shared/auth_extended_test.go
Normal file
148
core/e2e/shared/auth_extended_test.go
Normal file
@ -0,0 +1,148 @@
|
||||
//go:build e2e
|
||||
|
||||
package shared
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DeBrosOfficial/network/e2e"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestAuth_ExpiredOrInvalidJWT verifies that an expired/invalid JWT token is rejected.
|
||||
func TestAuth_ExpiredOrInvalidJWT(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
gatewayURL := e2e.GetGatewayURL()
|
||||
|
||||
// Craft an obviously invalid JWT
|
||||
invalidJWT := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiZXhwIjoxfQ.invalid"
|
||||
|
||||
req, err := http.NewRequest("GET", gatewayURL+"/v1/deployments/list", nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+invalidJWT)
|
||||
|
||||
client := e2e.NewHTTPClient(10 * time.Second)
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode,
|
||||
"Invalid JWT should return 401")
|
||||
}
|
||||
|
||||
// TestAuth_EmptyAPIKey verifies that an empty API key is rejected.
|
||||
func TestAuth_EmptyAPIKey(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
gatewayURL := e2e.GetGatewayURL()
|
||||
|
||||
req, err := http.NewRequest("GET", gatewayURL+"/v1/deployments/list", nil)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer ")
|
||||
|
||||
client := e2e.NewHTTPClient(10 * time.Second)
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode,
|
||||
"Empty API key should return 401")
|
||||
}
|
||||
|
||||
// TestAuth_SQLInjectionInAPIKey verifies that SQL injection in the API key
|
||||
// does not bypass authentication.
|
||||
func TestAuth_SQLInjectionInAPIKey(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
gatewayURL := e2e.GetGatewayURL()
|
||||
|
||||
injectionAttempts := []string{
|
||||
"' OR '1'='1",
|
||||
"'; DROP TABLE api_keys; --",
|
||||
"\" OR \"1\"=\"1",
|
||||
"admin'--",
|
||||
}
|
||||
|
||||
for _, attempt := range injectionAttempts {
|
||||
t.Run(attempt, func(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", gatewayURL+"/v1/deployments/list", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+attempt)
|
||||
|
||||
client := e2e.NewHTTPClient(10 * time.Second)
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode,
|
||||
"SQL injection attempt should be rejected")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuth_NamespaceScopedAccess verifies that an API key for one namespace
|
||||
// cannot access another namespace's deployments.
|
||||
func TestAuth_NamespaceScopedAccess(t *testing.T) {
|
||||
// Create two environments with different namespaces
|
||||
env1, err := e2e.LoadTestEnvWithNamespace("auth-test-ns1")
|
||||
if err != nil {
|
||||
t.Skip("Could not create namespace env1: " + err.Error())
|
||||
}
|
||||
|
||||
env2, err := e2e.LoadTestEnvWithNamespace("auth-test-ns2")
|
||||
if err != nil {
|
||||
t.Skip("Could not create namespace env2: " + err.Error())
|
||||
}
|
||||
|
||||
t.Run("Namespace 1 key cannot list namespace 2 deployments", func(t *testing.T) {
|
||||
// Use env1's API key to query env2's gateway
|
||||
// The namespace should be scoped to the API key
|
||||
req, _ := http.NewRequest("GET", env2.GatewayURL+"/v1/deployments/list", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+env1.APIKey)
|
||||
req.Header.Set("X-Namespace", "auth-test-ns2")
|
||||
|
||||
resp, err := env1.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
t.Skip("Gateway unreachable")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// The API should either reject (403) or return only ns1's deployments
|
||||
t.Logf("Cross-namespace access returned: %d", resp.StatusCode)
|
||||
|
||||
if resp.StatusCode == http.StatusOK {
|
||||
t.Log("API returned 200 — namespace isolation may be enforced at data level")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestAuth_PublicEndpointsNoAuth verifies that health/status endpoints
|
||||
// don't require authentication.
|
||||
func TestAuth_PublicEndpointsNoAuth(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
gatewayURL := e2e.GetGatewayURL()
|
||||
client := e2e.NewHTTPClient(10 * time.Second)
|
||||
|
||||
publicPaths := []string{
|
||||
"/v1/health",
|
||||
"/v1/status",
|
||||
}
|
||||
|
||||
for _, path := range publicPaths {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
req, _ := http.NewRequest("GET", gatewayURL+path, nil)
|
||||
// No auth header
|
||||
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"%s should be accessible without auth", path)
|
||||
})
|
||||
}
|
||||
}
|
||||
333
core/e2e/shared/auth_negative_test.go
Normal file
333
core/e2e/shared/auth_negative_test.go
Normal file
@ -0,0 +1,333 @@
|
||||
//go:build e2e
|
||||
|
||||
package shared_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
e2e "github.com/DeBrosOfficial/network/e2e"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// =============================================================================
|
||||
// STRICT AUTHENTICATION NEGATIVE TESTS
|
||||
// These tests verify that authentication is properly enforced.
|
||||
// Tests FAIL if unauthenticated/invalid requests are allowed through.
|
||||
// =============================================================================
|
||||
|
||||
func TestAuth_MissingAPIKey(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Request protected endpoint without auth headers
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, e2e.GetGatewayURL()+"/v1/cache/health", nil)
|
||||
require.NoError(t, err, "FAIL: Could not create request")
|
||||
|
||||
client := e2e.NewHTTPClient(30 * time.Second)
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// STRICT: Must reject requests without authentication
|
||||
require.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden,
|
||||
"FAIL: Protected endpoint allowed request without auth - expected 401/403, got %d", resp.StatusCode)
|
||||
t.Logf(" ✓ Missing API key correctly rejected with status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestAuth_InvalidAPIKey(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Request with invalid API key
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, e2e.GetGatewayURL()+"/v1/cache/health", nil)
|
||||
require.NoError(t, err, "FAIL: Could not create request")
|
||||
|
||||
req.Header.Set("Authorization", "Bearer invalid-key-xyz-123456789")
|
||||
|
||||
client := e2e.NewHTTPClient(30 * time.Second)
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// STRICT: Must reject invalid API keys
|
||||
require.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden,
|
||||
"FAIL: Invalid API key was accepted - expected 401/403, got %d", resp.StatusCode)
|
||||
t.Logf(" ✓ Invalid API key correctly rejected with status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestAuth_CacheWithoutAuth(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Request cache endpoint without auth
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/health",
|
||||
SkipAuth: true,
|
||||
}
|
||||
|
||||
_, status, err := req.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
|
||||
// STRICT: Cache endpoint must require authentication
|
||||
require.True(t, status == http.StatusUnauthorized || status == http.StatusForbidden,
|
||||
"FAIL: Cache endpoint accessible without auth - expected 401/403, got %d", status)
|
||||
t.Logf(" ✓ Cache endpoint correctly requires auth (status %d)", status)
|
||||
}
|
||||
|
||||
func TestAuth_StorageWithoutAuth(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Request storage endpoint without auth
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: e2e.GetGatewayURL() + "/v1/storage/status/QmTest",
|
||||
SkipAuth: true,
|
||||
}
|
||||
|
||||
_, status, err := req.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
|
||||
// STRICT: Storage endpoint must require authentication
|
||||
require.True(t, status == http.StatusUnauthorized || status == http.StatusForbidden,
|
||||
"FAIL: Storage endpoint accessible without auth - expected 401/403, got %d", status)
|
||||
t.Logf(" ✓ Storage endpoint correctly requires auth (status %d)", status)
|
||||
}
|
||||
|
||||
func TestAuth_RQLiteWithoutAuth(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Request rqlite endpoint without auth
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/schema",
|
||||
SkipAuth: true,
|
||||
}
|
||||
|
||||
_, status, err := req.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
|
||||
// STRICT: RQLite endpoint must require authentication
|
||||
require.True(t, status == http.StatusUnauthorized || status == http.StatusForbidden,
|
||||
"FAIL: RQLite endpoint accessible without auth - expected 401/403, got %d", status)
|
||||
t.Logf(" ✓ RQLite endpoint correctly requires auth (status %d)", status)
|
||||
}
|
||||
|
||||
func TestAuth_MalformedBearerToken(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Request with malformed bearer token (missing "Bearer " prefix)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, e2e.GetGatewayURL()+"/v1/cache/health", nil)
|
||||
require.NoError(t, err, "FAIL: Could not create request")
|
||||
|
||||
req.Header.Set("Authorization", "invalid-token-format-no-bearer")
|
||||
|
||||
client := e2e.NewHTTPClient(30 * time.Second)
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// STRICT: Must reject malformed authorization headers
|
||||
require.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden,
|
||||
"FAIL: Malformed auth header accepted - expected 401/403, got %d", resp.StatusCode)
|
||||
t.Logf(" ✓ Malformed bearer token correctly rejected (status %d)", resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestAuth_ExpiredJWT(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Test with a clearly invalid JWT structure
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, e2e.GetGatewayURL()+"/v1/cache/health", nil)
|
||||
require.NoError(t, err, "FAIL: Could not create request")
|
||||
|
||||
req.Header.Set("Authorization", "Bearer expired.jwt.token.invalid")
|
||||
|
||||
client := e2e.NewHTTPClient(30 * time.Second)
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// STRICT: Must reject invalid/expired JWT tokens
|
||||
require.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden,
|
||||
"FAIL: Invalid JWT accepted - expected 401/403, got %d", resp.StatusCode)
|
||||
t.Logf(" ✓ Invalid JWT correctly rejected (status %d)", resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestAuth_EmptyBearerToken(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Request with empty bearer token
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, e2e.GetGatewayURL()+"/v1/cache/health", nil)
|
||||
require.NoError(t, err, "FAIL: Could not create request")
|
||||
|
||||
req.Header.Set("Authorization", "Bearer ")
|
||||
|
||||
client := e2e.NewHTTPClient(30 * time.Second)
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// STRICT: Must reject empty bearer tokens
|
||||
require.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden,
|
||||
"FAIL: Empty bearer token accepted - expected 401/403, got %d", resp.StatusCode)
|
||||
t.Logf(" ✓ Empty bearer token correctly rejected (status %d)", resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestAuth_DuplicateAuthHeaders(t *testing.T) {
|
||||
if e2e.GetAPIKey() == "" {
|
||||
t.Skip("No API key configured")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Request with both valid API key in Authorization header
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/health",
|
||||
Headers: map[string]string{
|
||||
"Authorization": "Bearer " + e2e.GetAPIKey(),
|
||||
"X-API-Key": e2e.GetAPIKey(),
|
||||
},
|
||||
}
|
||||
|
||||
_, status, err := req.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
|
||||
// Should succeed since we have a valid API key
|
||||
require.Equal(t, http.StatusOK, status,
|
||||
"FAIL: Valid API key rejected when multiple auth headers present - got %d", status)
|
||||
t.Logf(" ✓ Duplicate auth headers with valid key succeeds (status %d)", status)
|
||||
}
|
||||
|
||||
func TestAuth_CaseSensitiveAPIKey(t *testing.T) {
|
||||
apiKey := e2e.GetAPIKey()
|
||||
if apiKey == "" {
|
||||
t.Skip("No API key configured")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Create incorrectly cased API key
|
||||
incorrectKey := ""
|
||||
for i, ch := range apiKey {
|
||||
if i%2 == 0 && unicode.IsLetter(ch) {
|
||||
if unicode.IsLower(ch) {
|
||||
incorrectKey += string(unicode.ToUpper(ch))
|
||||
} else {
|
||||
incorrectKey += string(unicode.ToLower(ch))
|
||||
}
|
||||
} else {
|
||||
incorrectKey += string(ch)
|
||||
}
|
||||
}
|
||||
|
||||
// Skip if the key didn't change (no letters)
|
||||
if incorrectKey == apiKey {
|
||||
t.Skip("API key has no letters to change case")
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, e2e.GetGatewayURL()+"/v1/cache/health", nil)
|
||||
require.NoError(t, err, "FAIL: Could not create request")
|
||||
|
||||
req.Header.Set("Authorization", "Bearer "+incorrectKey)
|
||||
|
||||
client := e2e.NewHTTPClient(30 * time.Second)
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// STRICT: API keys MUST be case-sensitive
|
||||
require.True(t, resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden,
|
||||
"FAIL: API key check is not case-sensitive - modified key accepted with status %d", resp.StatusCode)
|
||||
t.Logf(" ✓ Case-modified API key correctly rejected (status %d)", resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestAuth_HealthEndpointNoAuth(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Health endpoint at /v1/health should NOT require auth
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, e2e.GetGatewayURL()+"/v1/health", nil)
|
||||
require.NoError(t, err, "FAIL: Could not create request")
|
||||
|
||||
client := e2e.NewHTTPClient(30 * time.Second)
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Health endpoint should be publicly accessible
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"FAIL: Health endpoint should not require auth - expected 200, got %d", resp.StatusCode)
|
||||
t.Logf(" ✓ Health endpoint correctly accessible without auth")
|
||||
}
|
||||
|
||||
func TestAuth_StatusEndpointNoAuth(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Status endpoint at /v1/status should NOT require auth
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, e2e.GetGatewayURL()+"/v1/status", nil)
|
||||
require.NoError(t, err, "FAIL: Could not create request")
|
||||
|
||||
client := e2e.NewHTTPClient(30 * time.Second)
|
||||
resp, err := client.Do(req)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Status endpoint should be publicly accessible
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"FAIL: Status endpoint should not require auth - expected 200, got %d", resp.StatusCode)
|
||||
t.Logf(" ✓ Status endpoint correctly accessible without auth")
|
||||
}
|
||||
|
||||
func TestAuth_DeploymentsWithoutAuth(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Request deployments endpoint without auth
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: e2e.GetGatewayURL() + "/v1/deployments/list",
|
||||
SkipAuth: true,
|
||||
}
|
||||
|
||||
_, status, err := req.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
|
||||
// STRICT: Deployments endpoint must require authentication
|
||||
require.True(t, status == http.StatusUnauthorized || status == http.StatusForbidden,
|
||||
"FAIL: Deployments endpoint accessible without auth - expected 401/403, got %d", status)
|
||||
t.Logf(" ✓ Deployments endpoint correctly requires auth (status %d)", status)
|
||||
}
|
||||
|
||||
func TestAuth_SQLiteWithoutAuth(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Request SQLite endpoint without auth
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: e2e.GetGatewayURL() + "/v1/db/sqlite/list",
|
||||
SkipAuth: true,
|
||||
}
|
||||
|
||||
_, status, err := req.Do(ctx)
|
||||
require.NoError(t, err, "FAIL: Request failed")
|
||||
|
||||
// STRICT: SQLite endpoint must require authentication
|
||||
require.True(t, status == http.StatusUnauthorized || status == http.StatusForbidden,
|
||||
"FAIL: SQLite endpoint accessible without auth - expected 401/403, got %d", status)
|
||||
t.Logf(" ✓ SQLite endpoint correctly requires auth (status %d)", status)
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
//go:build e2e
|
||||
|
||||
package e2e
|
||||
package shared_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
@ -8,17 +8,19 @@ import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
e2e "github.com/DeBrosOfficial/network/e2e"
|
||||
)
|
||||
|
||||
func TestCache_Health(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := &HTTPRequest{
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: GetGatewayURL() + "/v1/cache/health",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/health",
|
||||
}
|
||||
|
||||
body, status, err := req.Do(ctx)
|
||||
@ -31,7 +33,7 @@ func TestCache_Health(t *testing.T) {
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := DecodeJSON(body, &resp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -45,19 +47,19 @@ func TestCache_Health(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCache_PutGet(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
key := "test-key"
|
||||
value := "test-value"
|
||||
|
||||
// Put value
|
||||
putReq := &HTTPRequest{
|
||||
putReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/put",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/put",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -75,9 +77,9 @@ func TestCache_PutGet(t *testing.T) {
|
||||
}
|
||||
|
||||
// Get value
|
||||
getReq := &HTTPRequest{
|
||||
getReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/get",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/get",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -94,7 +96,7 @@ func TestCache_PutGet(t *testing.T) {
|
||||
}
|
||||
|
||||
var getResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &getResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &getResp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -104,12 +106,12 @@ func TestCache_PutGet(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCache_PutGetJSON(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
key := "json-key"
|
||||
jsonValue := map[string]interface{}{
|
||||
"name": "John",
|
||||
@ -118,9 +120,9 @@ func TestCache_PutGetJSON(t *testing.T) {
|
||||
}
|
||||
|
||||
// Put JSON value
|
||||
putReq := &HTTPRequest{
|
||||
putReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/put",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/put",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -138,9 +140,9 @@ func TestCache_PutGetJSON(t *testing.T) {
|
||||
}
|
||||
|
||||
// Get JSON value
|
||||
getReq := &HTTPRequest{
|
||||
getReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/get",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/get",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -157,7 +159,7 @@ func TestCache_PutGetJSON(t *testing.T) {
|
||||
}
|
||||
|
||||
var getResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &getResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &getResp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -171,19 +173,19 @@ func TestCache_PutGetJSON(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCache_Delete(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
key := "delete-key"
|
||||
value := "delete-value"
|
||||
|
||||
// Put value
|
||||
putReq := &HTTPRequest{
|
||||
putReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/put",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/put",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -197,9 +199,9 @@ func TestCache_Delete(t *testing.T) {
|
||||
}
|
||||
|
||||
// Delete value
|
||||
deleteReq := &HTTPRequest{
|
||||
deleteReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/delete",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/delete",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -216,9 +218,9 @@ func TestCache_Delete(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify deletion
|
||||
getReq := &HTTPRequest{
|
||||
getReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/get",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/get",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -233,19 +235,19 @@ func TestCache_Delete(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCache_TTL(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
key := "ttl-key"
|
||||
value := "ttl-value"
|
||||
|
||||
// Put value with TTL
|
||||
putReq := &HTTPRequest{
|
||||
putReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/put",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/put",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -264,9 +266,9 @@ func TestCache_TTL(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify value exists
|
||||
getReq := &HTTPRequest{
|
||||
getReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/get",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/get",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -279,7 +281,7 @@ func TestCache_TTL(t *testing.T) {
|
||||
}
|
||||
|
||||
// Wait for TTL expiry (2 seconds + buffer)
|
||||
Delay(2500)
|
||||
e2e.Delay(2500)
|
||||
|
||||
// Verify value is expired
|
||||
_, status, err = getReq.Do(ctx)
|
||||
@ -289,19 +291,19 @@ func TestCache_TTL(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCache_Scan(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
|
||||
// Put multiple keys
|
||||
keys := []string{"user-1", "user-2", "session-1", "session-2"}
|
||||
for _, key := range keys {
|
||||
putReq := &HTTPRequest{
|
||||
putReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/put",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/put",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -316,9 +318,9 @@ func TestCache_Scan(t *testing.T) {
|
||||
}
|
||||
|
||||
// Scan all keys
|
||||
scanReq := &HTTPRequest{
|
||||
scanReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/scan",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/scan",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
},
|
||||
@ -334,7 +336,7 @@ func TestCache_Scan(t *testing.T) {
|
||||
}
|
||||
|
||||
var scanResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &scanResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &scanResp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -345,19 +347,19 @@ func TestCache_Scan(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCache_ScanWithRegex(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
|
||||
// Put keys with different patterns
|
||||
keys := []string{"user-1", "user-2", "session-1", "session-2"}
|
||||
for _, key := range keys {
|
||||
putReq := &HTTPRequest{
|
||||
putReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/put",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/put",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -372,9 +374,9 @@ func TestCache_ScanWithRegex(t *testing.T) {
|
||||
}
|
||||
|
||||
// Scan with regex pattern
|
||||
scanReq := &HTTPRequest{
|
||||
scanReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/scan",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/scan",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"pattern": "^user-",
|
||||
@ -391,7 +393,7 @@ func TestCache_ScanWithRegex(t *testing.T) {
|
||||
}
|
||||
|
||||
var scanResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &scanResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &scanResp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -402,19 +404,19 @@ func TestCache_ScanWithRegex(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCache_MultiGet(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
keys := []string{"key-1", "key-2", "key-3"}
|
||||
|
||||
// Put values
|
||||
for i, key := range keys {
|
||||
putReq := &HTTPRequest{
|
||||
putReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/put",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/put",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": key,
|
||||
@ -429,9 +431,9 @@ func TestCache_MultiGet(t *testing.T) {
|
||||
}
|
||||
|
||||
// Multi-get
|
||||
multiGetReq := &HTTPRequest{
|
||||
multiGetReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/mget",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/mget",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"keys": keys,
|
||||
@ -448,7 +450,7 @@ func TestCache_MultiGet(t *testing.T) {
|
||||
}
|
||||
|
||||
var mgetResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &mgetResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &mgetResp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -459,14 +461,14 @@ func TestCache_MultiGet(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCache_MissingDMap(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
getReq := &HTTPRequest{
|
||||
getReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/get",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/get",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": "",
|
||||
"key": "any-key",
|
||||
@ -484,16 +486,16 @@ func TestCache_MissingDMap(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCache_MissingKey(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dmap := GenerateDMapName()
|
||||
dmap := e2e.GenerateDMapName()
|
||||
|
||||
getReq := &HTTPRequest{
|
||||
getReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/cache/get",
|
||||
URL: e2e.GetGatewayURL() + "/v1/cache/get",
|
||||
Body: map[string]interface{}{
|
||||
"dmap": dmap,
|
||||
"key": "non-existent-key",
|
||||
@ -1,23 +1,25 @@
|
||||
//go:build e2e
|
||||
|
||||
package e2e
|
||||
package shared_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
e2e "github.com/DeBrosOfficial/network/e2e"
|
||||
)
|
||||
|
||||
func TestNetwork_Health(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := &HTTPRequest{
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: GetGatewayURL() + "/v1/health",
|
||||
URL: e2e.GetGatewayURL() + "/v1/health",
|
||||
SkipAuth: true,
|
||||
}
|
||||
|
||||
@ -31,7 +33,7 @@ func TestNetwork_Health(t *testing.T) {
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := DecodeJSON(body, &resp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -41,14 +43,14 @@ func TestNetwork_Health(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestNetwork_Status(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := &HTTPRequest{
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: GetGatewayURL() + "/v1/network/status",
|
||||
URL: e2e.GetGatewayURL() + "/v1/network/status",
|
||||
}
|
||||
|
||||
body, status, err := req.Do(ctx)
|
||||
@ -61,7 +63,7 @@ func TestNetwork_Status(t *testing.T) {
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := DecodeJSON(body, &resp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -75,14 +77,14 @@ func TestNetwork_Status(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestNetwork_Peers(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := &HTTPRequest{
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: GetGatewayURL() + "/v1/network/peers",
|
||||
URL: e2e.GetGatewayURL() + "/v1/network/peers",
|
||||
}
|
||||
|
||||
body, status, err := req.Do(ctx)
|
||||
@ -95,7 +97,7 @@ func TestNetwork_Peers(t *testing.T) {
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := DecodeJSON(body, &resp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -105,18 +107,18 @@ func TestNetwork_Peers(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestNetwork_ProxyAnonSuccess(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := &HTTPRequest{
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/proxy/anon",
|
||||
URL: e2e.GetGatewayURL() + "/v1/proxy/anon",
|
||||
Body: map[string]interface{}{
|
||||
"url": "https://httpbin.org/get",
|
||||
"method": "GET",
|
||||
"headers": map[string]string{"User-Agent": "DeBros-E2E-Test/1.0"},
|
||||
"headers": map[string]string{"User-Agent": "Orama-E2E-Test/1.0"},
|
||||
},
|
||||
}
|
||||
|
||||
@ -130,7 +132,7 @@ func TestNetwork_ProxyAnonSuccess(t *testing.T) {
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := DecodeJSON(body, &resp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -144,14 +146,14 @@ func TestNetwork_ProxyAnonSuccess(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestNetwork_ProxyAnonBadURL(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := &HTTPRequest{
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/proxy/anon",
|
||||
URL: e2e.GetGatewayURL() + "/v1/proxy/anon",
|
||||
Body: map[string]interface{}{
|
||||
"url": "http://localhost:1/nonexistent",
|
||||
"method": "GET",
|
||||
@ -165,18 +167,18 @@ func TestNetwork_ProxyAnonBadURL(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestNetwork_ProxyAnonPostRequest(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := &HTTPRequest{
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/proxy/anon",
|
||||
URL: e2e.GetGatewayURL() + "/v1/proxy/anon",
|
||||
Body: map[string]interface{}{
|
||||
"url": "https://httpbin.org/post",
|
||||
"method": "POST",
|
||||
"headers": map[string]string{"User-Agent": "DeBros-E2E-Test/1.0"},
|
||||
"headers": map[string]string{"User-Agent": "Orama-E2E-Test/1.0"},
|
||||
"body": "test_data",
|
||||
},
|
||||
}
|
||||
@ -191,7 +193,7 @@ func TestNetwork_ProxyAnonPostRequest(t *testing.T) {
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := DecodeJSON(body, &resp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -206,9 +208,9 @@ func TestNetwork_Unauthorized(t *testing.T) {
|
||||
defer cancel()
|
||||
|
||||
// Create request without auth
|
||||
req := &HTTPRequest{
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: GetGatewayURL() + "/v1/network/status",
|
||||
URL: e2e.GetGatewayURL() + "/v1/network/status",
|
||||
SkipAuth: true,
|
||||
}
|
||||
|
||||
@ -1,40 +1,42 @@
|
||||
//go:build e2e
|
||||
|
||||
package e2e
|
||||
package shared_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
e2e "github.com/DeBrosOfficial/network/e2e"
|
||||
)
|
||||
|
||||
// TestPubSub_SubscribePublish tests basic pub/sub functionality via WebSocket
|
||||
func TestPubSub_SubscribePublish(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
topic := GenerateTopic()
|
||||
topic := e2e.GenerateTopic()
|
||||
message := "test-message-from-publisher"
|
||||
|
||||
// Create subscriber first
|
||||
subscriber, err := NewWSPubSubClient(t, topic)
|
||||
subscriber, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create subscriber: %v", err)
|
||||
}
|
||||
defer subscriber.Close()
|
||||
|
||||
// Give subscriber time to register
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Create publisher
|
||||
publisher, err := NewWSPubSubClient(t, topic)
|
||||
publisher, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create publisher: %v", err)
|
||||
}
|
||||
defer publisher.Close()
|
||||
|
||||
// Give connections time to stabilize
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Publish message
|
||||
if err := publisher.Publish([]byte(message)); err != nil {
|
||||
@ -54,37 +56,37 @@ func TestPubSub_SubscribePublish(t *testing.T) {
|
||||
|
||||
// TestPubSub_MultipleSubscribers tests that multiple subscribers receive the same message
|
||||
func TestPubSub_MultipleSubscribers(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
topic := GenerateTopic()
|
||||
topic := e2e.GenerateTopic()
|
||||
message1 := "message-1"
|
||||
message2 := "message-2"
|
||||
|
||||
// Create two subscribers
|
||||
sub1, err := NewWSPubSubClient(t, topic)
|
||||
sub1, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create subscriber1: %v", err)
|
||||
}
|
||||
defer sub1.Close()
|
||||
|
||||
sub2, err := NewWSPubSubClient(t, topic)
|
||||
sub2, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create subscriber2: %v", err)
|
||||
}
|
||||
defer sub2.Close()
|
||||
|
||||
// Give subscribers time to register
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Create publisher
|
||||
publisher, err := NewWSPubSubClient(t, topic)
|
||||
publisher, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create publisher: %v", err)
|
||||
}
|
||||
defer publisher.Close()
|
||||
|
||||
// Give connections time to stabilize
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Publish first message
|
||||
if err := publisher.Publish([]byte(message1)); err != nil {
|
||||
@ -133,30 +135,30 @@ func TestPubSub_MultipleSubscribers(t *testing.T) {
|
||||
|
||||
// TestPubSub_Deduplication tests that multiple identical messages are all received
|
||||
func TestPubSub_Deduplication(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
topic := GenerateTopic()
|
||||
topic := e2e.GenerateTopic()
|
||||
message := "duplicate-test-message"
|
||||
|
||||
// Create subscriber
|
||||
subscriber, err := NewWSPubSubClient(t, topic)
|
||||
subscriber, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create subscriber: %v", err)
|
||||
}
|
||||
defer subscriber.Close()
|
||||
|
||||
// Give subscriber time to register
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Create publisher
|
||||
publisher, err := NewWSPubSubClient(t, topic)
|
||||
publisher, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create publisher: %v", err)
|
||||
}
|
||||
defer publisher.Close()
|
||||
|
||||
// Give connections time to stabilize
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Publish the same message multiple times
|
||||
for i := 0; i < 3; i++ {
|
||||
@ -164,7 +166,7 @@ func TestPubSub_Deduplication(t *testing.T) {
|
||||
t.Fatalf("publish %d failed: %v", i, err)
|
||||
}
|
||||
// Small delay between publishes
|
||||
Delay(50)
|
||||
e2e.Delay(50)
|
||||
}
|
||||
|
||||
// Receive messages - should get all (no dedup filter)
|
||||
@ -185,30 +187,30 @@ func TestPubSub_Deduplication(t *testing.T) {
|
||||
|
||||
// TestPubSub_ConcurrentPublish tests concurrent message publishing
|
||||
func TestPubSub_ConcurrentPublish(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
topic := GenerateTopic()
|
||||
topic := e2e.GenerateTopic()
|
||||
numMessages := 10
|
||||
|
||||
// Create subscriber
|
||||
subscriber, err := NewWSPubSubClient(t, topic)
|
||||
subscriber, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create subscriber: %v", err)
|
||||
}
|
||||
defer subscriber.Close()
|
||||
|
||||
// Give subscriber time to register
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Create publisher
|
||||
publisher, err := NewWSPubSubClient(t, topic)
|
||||
publisher, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create publisher: %v", err)
|
||||
}
|
||||
defer publisher.Close()
|
||||
|
||||
// Give connections time to stabilize
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Publish multiple messages concurrently
|
||||
var wg sync.WaitGroup
|
||||
@ -241,45 +243,45 @@ func TestPubSub_ConcurrentPublish(t *testing.T) {
|
||||
|
||||
// TestPubSub_TopicIsolation tests that messages are isolated to their topics
|
||||
func TestPubSub_TopicIsolation(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
topic1 := GenerateTopic()
|
||||
topic2 := GenerateTopic()
|
||||
topic1 := e2e.GenerateTopic()
|
||||
topic2 := e2e.GenerateTopic()
|
||||
msg1 := "message-on-topic1"
|
||||
msg2 := "message-on-topic2"
|
||||
|
||||
// Create subscriber for topic1
|
||||
sub1, err := NewWSPubSubClient(t, topic1)
|
||||
sub1, err := e2e.NewWSPubSubClient(t, topic1)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create subscriber1: %v", err)
|
||||
}
|
||||
defer sub1.Close()
|
||||
|
||||
// Create subscriber for topic2
|
||||
sub2, err := NewWSPubSubClient(t, topic2)
|
||||
sub2, err := e2e.NewWSPubSubClient(t, topic2)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create subscriber2: %v", err)
|
||||
}
|
||||
defer sub2.Close()
|
||||
|
||||
// Give subscribers time to register
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Create publishers
|
||||
pub1, err := NewWSPubSubClient(t, topic1)
|
||||
pub1, err := e2e.NewWSPubSubClient(t, topic1)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create publisher1: %v", err)
|
||||
}
|
||||
defer pub1.Close()
|
||||
|
||||
pub2, err := NewWSPubSubClient(t, topic2)
|
||||
pub2, err := e2e.NewWSPubSubClient(t, topic2)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create publisher2: %v", err)
|
||||
}
|
||||
defer pub2.Close()
|
||||
|
||||
// Give connections time to stabilize
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Publish to topic2 first
|
||||
if err := pub2.Publish([]byte(msg2)); err != nil {
|
||||
@ -312,29 +314,29 @@ func TestPubSub_TopicIsolation(t *testing.T) {
|
||||
|
||||
// TestPubSub_EmptyMessage tests sending and receiving empty messages
|
||||
func TestPubSub_EmptyMessage(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
topic := GenerateTopic()
|
||||
topic := e2e.GenerateTopic()
|
||||
|
||||
// Create subscriber
|
||||
subscriber, err := NewWSPubSubClient(t, topic)
|
||||
subscriber, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create subscriber: %v", err)
|
||||
}
|
||||
defer subscriber.Close()
|
||||
|
||||
// Give subscriber time to register
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Create publisher
|
||||
publisher, err := NewWSPubSubClient(t, topic)
|
||||
publisher, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create publisher: %v", err)
|
||||
}
|
||||
defer publisher.Close()
|
||||
|
||||
// Give connections time to stabilize
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Publish empty message
|
||||
if err := publisher.Publish([]byte("")); err != nil {
|
||||
@ -354,9 +356,9 @@ func TestPubSub_EmptyMessage(t *testing.T) {
|
||||
|
||||
// TestPubSub_LargeMessage tests sending and receiving large messages
|
||||
func TestPubSub_LargeMessage(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
topic := GenerateTopic()
|
||||
topic := e2e.GenerateTopic()
|
||||
|
||||
// Create a large message (100KB)
|
||||
largeMessage := make([]byte, 100*1024)
|
||||
@ -365,24 +367,24 @@ func TestPubSub_LargeMessage(t *testing.T) {
|
||||
}
|
||||
|
||||
// Create subscriber
|
||||
subscriber, err := NewWSPubSubClient(t, topic)
|
||||
subscriber, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create subscriber: %v", err)
|
||||
}
|
||||
defer subscriber.Close()
|
||||
|
||||
// Give subscriber time to register
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Create publisher
|
||||
publisher, err := NewWSPubSubClient(t, topic)
|
||||
publisher, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create publisher: %v", err)
|
||||
}
|
||||
defer publisher.Close()
|
||||
|
||||
// Give connections time to stabilize
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Publish large message
|
||||
if err := publisher.Publish(largeMessage); err != nil {
|
||||
@ -409,30 +411,30 @@ func TestPubSub_LargeMessage(t *testing.T) {
|
||||
|
||||
// TestPubSub_RapidPublish tests rapid message publishing
|
||||
func TestPubSub_RapidPublish(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
topic := GenerateTopic()
|
||||
topic := e2e.GenerateTopic()
|
||||
numMessages := 50
|
||||
|
||||
// Create subscriber
|
||||
subscriber, err := NewWSPubSubClient(t, topic)
|
||||
subscriber, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create subscriber: %v", err)
|
||||
}
|
||||
defer subscriber.Close()
|
||||
|
||||
// Give subscriber time to register
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Create publisher
|
||||
publisher, err := NewWSPubSubClient(t, topic)
|
||||
publisher, err := e2e.NewWSPubSubClient(t, topic)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create publisher: %v", err)
|
||||
}
|
||||
defer publisher.Close()
|
||||
|
||||
// Give connections time to stabilize
|
||||
Delay(200)
|
||||
e2e.Delay(200)
|
||||
|
||||
// Publish messages rapidly
|
||||
for i := 0; i < numMessages; i++ {
|
||||
@ -1,6 +1,6 @@
|
||||
//go:build e2e
|
||||
|
||||
package e2e
|
||||
package shared_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
@ -9,17 +9,19 @@ import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
e2e "github.com/DeBrosOfficial/network/e2e"
|
||||
)
|
||||
|
||||
func TestPubSub_Presence(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
topic := GenerateTopic()
|
||||
topic := e2e.GenerateTopic()
|
||||
memberID := "user123"
|
||||
memberMeta := map[string]interface{}{"name": "Alice"}
|
||||
|
||||
// 1. Subscribe with presence
|
||||
client1, err := NewWSPubSubPresenceClient(t, topic, memberID, memberMeta)
|
||||
client1, err := e2e.NewWSPubSubPresenceClient(t, topic, memberID, memberMeta)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create presence client: %v", err)
|
||||
}
|
||||
@ -48,9 +50,9 @@ func TestPubSub_Presence(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := &HTTPRequest{
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: fmt.Sprintf("%s/v1/pubsub/presence?topic=%s", GetGatewayURL(), topic),
|
||||
URL: fmt.Sprintf("%s/v1/pubsub/presence?topic=%s", e2e.GetGatewayURL(), topic),
|
||||
}
|
||||
|
||||
body, status, err := req.Do(ctx)
|
||||
@ -63,7 +65,7 @@ func TestPubSub_Presence(t *testing.T) {
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := DecodeJSON(body, &resp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -83,7 +85,7 @@ func TestPubSub_Presence(t *testing.T) {
|
||||
|
||||
// 3. Subscribe second member
|
||||
memberID2 := "user456"
|
||||
client2, err := NewWSPubSubPresenceClient(t, topic, memberID2, nil)
|
||||
client2, err := e2e.NewWSPubSubPresenceClient(t, topic, memberID2, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create second presence client: %v", err)
|
||||
}
|
||||
@ -119,4 +121,3 @@ func TestPubSub_Presence(t *testing.T) {
|
||||
t.Fatalf("expected presence.leave for %s, got %v for %v", memberID2, event["type"], event["member_id"])
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
//go:build e2e
|
||||
|
||||
package e2e
|
||||
package shared_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
@ -8,23 +8,36 @@ import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
e2e "github.com/DeBrosOfficial/network/e2e"
|
||||
)
|
||||
|
||||
func TestRQLite_CreateTable(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
table := GenerateTableName()
|
||||
table := e2e.GenerateTableName()
|
||||
|
||||
// Cleanup table after test
|
||||
defer func() {
|
||||
dropReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/drop-table",
|
||||
Body: map[string]interface{}{"table": table},
|
||||
}
|
||||
dropReq.Do(context.Background())
|
||||
}()
|
||||
|
||||
schema := fmt.Sprintf(
|
||||
"CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)",
|
||||
table,
|
||||
)
|
||||
|
||||
req := &HTTPRequest{
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
Body: map[string]interface{}{
|
||||
"schema": schema,
|
||||
},
|
||||
@ -41,21 +54,32 @@ func TestRQLite_CreateTable(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRQLite_InsertQuery(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
table := GenerateTableName()
|
||||
table := e2e.GenerateTableName()
|
||||
|
||||
// Cleanup table after test
|
||||
defer func() {
|
||||
dropReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/drop-table",
|
||||
Body: map[string]interface{}{"table": table},
|
||||
}
|
||||
dropReq.Do(context.Background())
|
||||
}()
|
||||
|
||||
schema := fmt.Sprintf(
|
||||
"CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)",
|
||||
table,
|
||||
)
|
||||
|
||||
// Create table
|
||||
createReq := &HTTPRequest{
|
||||
createReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
Body: map[string]interface{}{
|
||||
"schema": schema,
|
||||
},
|
||||
@ -67,9 +91,9 @@ func TestRQLite_InsertQuery(t *testing.T) {
|
||||
}
|
||||
|
||||
// Insert rows
|
||||
insertReq := &HTTPRequest{
|
||||
insertReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
Body: map[string]interface{}{
|
||||
"statements": []string{
|
||||
fmt.Sprintf("INSERT INTO %s(name) VALUES ('alice')", table),
|
||||
@ -84,9 +108,9 @@ func TestRQLite_InsertQuery(t *testing.T) {
|
||||
}
|
||||
|
||||
// Query rows
|
||||
queryReq := &HTTPRequest{
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/query",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/query",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT name FROM %s ORDER BY id", table),
|
||||
},
|
||||
@ -102,7 +126,7 @@ func TestRQLite_InsertQuery(t *testing.T) {
|
||||
}
|
||||
|
||||
var queryResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &queryResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &queryResp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -112,21 +136,21 @@ func TestRQLite_InsertQuery(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRQLite_DropTable(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
table := GenerateTableName()
|
||||
table := e2e.GenerateTableName()
|
||||
schema := fmt.Sprintf(
|
||||
"CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY, note TEXT)",
|
||||
table,
|
||||
)
|
||||
|
||||
// Create table
|
||||
createReq := &HTTPRequest{
|
||||
createReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
Body: map[string]interface{}{
|
||||
"schema": schema,
|
||||
},
|
||||
@ -138,9 +162,9 @@ func TestRQLite_DropTable(t *testing.T) {
|
||||
}
|
||||
|
||||
// Drop table
|
||||
dropReq := &HTTPRequest{
|
||||
dropReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/drop-table",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/drop-table",
|
||||
Body: map[string]interface{}{
|
||||
"table": table,
|
||||
},
|
||||
@ -156,9 +180,9 @@ func TestRQLite_DropTable(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify table doesn't exist via schema
|
||||
schemaReq := &HTTPRequest{
|
||||
schemaReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/schema",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/schema",
|
||||
}
|
||||
|
||||
body, status, err := schemaReq.Do(ctx)
|
||||
@ -168,7 +192,7 @@ func TestRQLite_DropTable(t *testing.T) {
|
||||
}
|
||||
|
||||
var schemaResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &schemaResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &schemaResp); err != nil {
|
||||
t.Logf("warning: failed to decode schema response: %v", err)
|
||||
return
|
||||
}
|
||||
@ -184,14 +208,14 @@ func TestRQLite_DropTable(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRQLite_Schema(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := &HTTPRequest{
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/schema",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/schema",
|
||||
}
|
||||
|
||||
body, status, err := req.Do(ctx)
|
||||
@ -204,7 +228,7 @@ func TestRQLite_Schema(t *testing.T) {
|
||||
}
|
||||
|
||||
var resp map[string]interface{}
|
||||
if err := DecodeJSON(body, &resp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &resp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -214,14 +238,14 @@ func TestRQLite_Schema(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRQLite_MalformedSQL(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req := &HTTPRequest{
|
||||
req := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/query",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/query",
|
||||
Body: map[string]interface{}{
|
||||
"sql": "SELECT * FROM nonexistent_table WHERE invalid syntax",
|
||||
},
|
||||
@ -239,21 +263,32 @@ func TestRQLite_MalformedSQL(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRQLite_LargeTransaction(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
table := GenerateTableName()
|
||||
table := e2e.GenerateTableName()
|
||||
|
||||
// Cleanup table after test
|
||||
defer func() {
|
||||
dropReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/drop-table",
|
||||
Body: map[string]interface{}{"table": table},
|
||||
}
|
||||
dropReq.Do(context.Background())
|
||||
}()
|
||||
|
||||
schema := fmt.Sprintf(
|
||||
"CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY AUTOINCREMENT, value INTEGER)",
|
||||
table,
|
||||
)
|
||||
|
||||
// Create table
|
||||
createReq := &HTTPRequest{
|
||||
createReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
Body: map[string]interface{}{
|
||||
"schema": schema,
|
||||
},
|
||||
@ -270,9 +305,9 @@ func TestRQLite_LargeTransaction(t *testing.T) {
|
||||
statements = append(statements, fmt.Sprintf("INSERT INTO %s(value) VALUES (%d)", table, i))
|
||||
}
|
||||
|
||||
txReq := &HTTPRequest{
|
||||
txReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
Body: map[string]interface{}{
|
||||
"statements": statements,
|
||||
},
|
||||
@ -284,9 +319,9 @@ func TestRQLite_LargeTransaction(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify all rows were inserted
|
||||
queryReq := &HTTPRequest{
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/query",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/query",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT COUNT(*) as count FROM %s", table),
|
||||
},
|
||||
@ -298,7 +333,7 @@ func TestRQLite_LargeTransaction(t *testing.T) {
|
||||
}
|
||||
|
||||
var countResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &countResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &countResp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -312,18 +347,35 @@ func TestRQLite_LargeTransaction(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRQLite_ForeignKeyMigration(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
orgsTable := GenerateTableName()
|
||||
usersTable := GenerateTableName()
|
||||
orgsTable := e2e.GenerateTableName()
|
||||
usersTable := e2e.GenerateTableName()
|
||||
|
||||
// Cleanup tables after test
|
||||
defer func() {
|
||||
dropUsersReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/drop-table",
|
||||
Body: map[string]interface{}{"table": usersTable},
|
||||
}
|
||||
dropUsersReq.Do(context.Background())
|
||||
|
||||
dropOrgsReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/drop-table",
|
||||
Body: map[string]interface{}{"table": orgsTable},
|
||||
}
|
||||
dropOrgsReq.Do(context.Background())
|
||||
}()
|
||||
|
||||
// Create base tables
|
||||
createOrgsReq := &HTTPRequest{
|
||||
createOrgsReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
Body: map[string]interface{}{
|
||||
"schema": fmt.Sprintf(
|
||||
"CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY, name TEXT)",
|
||||
@ -337,9 +389,9 @@ func TestRQLite_ForeignKeyMigration(t *testing.T) {
|
||||
t.Fatalf("create orgs table failed: status %d, err %v", status, err)
|
||||
}
|
||||
|
||||
createUsersReq := &HTTPRequest{
|
||||
createUsersReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/create-table",
|
||||
Body: map[string]interface{}{
|
||||
"schema": fmt.Sprintf(
|
||||
"CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY, name TEXT, org_id INTEGER, age TEXT)",
|
||||
@ -354,9 +406,9 @@ func TestRQLite_ForeignKeyMigration(t *testing.T) {
|
||||
}
|
||||
|
||||
// Seed data
|
||||
seedReq := &HTTPRequest{
|
||||
seedReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
Body: map[string]interface{}{
|
||||
"statements": []string{
|
||||
fmt.Sprintf("INSERT INTO %s(id,name) VALUES (1,'org')", orgsTable),
|
||||
@ -371,9 +423,9 @@ func TestRQLite_ForeignKeyMigration(t *testing.T) {
|
||||
}
|
||||
|
||||
// Migrate: change age type and add FK
|
||||
migrationReq := &HTTPRequest{
|
||||
migrationReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/transaction",
|
||||
Body: map[string]interface{}{
|
||||
"statements": []string{
|
||||
fmt.Sprintf(
|
||||
@ -396,9 +448,9 @@ func TestRQLite_ForeignKeyMigration(t *testing.T) {
|
||||
}
|
||||
|
||||
// Verify data is intact
|
||||
queryReq := &HTTPRequest{
|
||||
queryReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/query",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/query",
|
||||
Body: map[string]interface{}{
|
||||
"sql": fmt.Sprintf("SELECT name, org_id, age FROM %s", usersTable),
|
||||
},
|
||||
@ -410,7 +462,7 @@ func TestRQLite_ForeignKeyMigration(t *testing.T) {
|
||||
}
|
||||
|
||||
var queryResp map[string]interface{}
|
||||
if err := DecodeJSON(body, &queryResp); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &queryResp); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -420,14 +472,14 @@ func TestRQLite_ForeignKeyMigration(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRQLite_DropNonexistentTable(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dropReq := &HTTPRequest{
|
||||
dropReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/rqlite/drop-table",
|
||||
URL: e2e.GetGatewayURL() + "/v1/rqlite/drop-table",
|
||||
Body: map[string]interface{}{
|
||||
"table": "nonexistent_table_xyz_" + fmt.Sprintf("%d", time.Now().UnixNano()),
|
||||
},
|
||||
@ -1,6 +1,6 @@
|
||||
//go:build e2e
|
||||
|
||||
package e2e
|
||||
package shared_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@ -11,10 +11,12 @@ import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
e2e "github.com/DeBrosOfficial/network/e2e"
|
||||
)
|
||||
|
||||
func TestServerless_DeployAndInvoke(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
@ -30,7 +32,11 @@ func TestServerless_DeployAndInvoke(t *testing.T) {
|
||||
}
|
||||
|
||||
funcName := "e2e-hello"
|
||||
namespace := "default"
|
||||
// Use namespace from environment or default to test namespace
|
||||
namespace := os.Getenv("ORAMA_NAMESPACE")
|
||||
if namespace == "" {
|
||||
namespace = "default-test-ns" // Match the namespace from LoadTestEnv()
|
||||
}
|
||||
|
||||
// 1. Deploy function
|
||||
var buf bytes.Buffer
|
||||
@ -39,6 +45,7 @@ func TestServerless_DeployAndInvoke(t *testing.T) {
|
||||
// Add metadata
|
||||
_ = writer.WriteField("name", funcName)
|
||||
_ = writer.WriteField("namespace", namespace)
|
||||
_ = writer.WriteField("is_public", "true") // Make function public for E2E test
|
||||
|
||||
// Add WASM file
|
||||
part, err := writer.CreateFormFile("wasm", funcName+".wasm")
|
||||
@ -48,14 +55,14 @@ func TestServerless_DeployAndInvoke(t *testing.T) {
|
||||
part.Write(wasmBytes)
|
||||
writer.Close()
|
||||
|
||||
deployReq, _ := http.NewRequestWithContext(ctx, "POST", GetGatewayURL()+"/v1/functions", &buf)
|
||||
deployReq, _ := http.NewRequestWithContext(ctx, "POST", e2e.GetGatewayURL()+"/v1/functions", &buf)
|
||||
deployReq.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
if apiKey := GetAPIKey(); apiKey != "" {
|
||||
if apiKey := e2e.GetAPIKey(); apiKey != "" {
|
||||
deployReq.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
|
||||
client := NewHTTPClient(1 * time.Minute)
|
||||
client := e2e.NewHTTPClient(1 * time.Minute)
|
||||
resp, err := client.Do(deployReq)
|
||||
if err != nil {
|
||||
t.Fatalf("deploy request failed: %v", err)
|
||||
@ -69,10 +76,10 @@ func TestServerless_DeployAndInvoke(t *testing.T) {
|
||||
|
||||
// 2. Invoke function
|
||||
invokePayload := []byte(`{"name": "E2E Tester"}`)
|
||||
invokeReq, _ := http.NewRequestWithContext(ctx, "POST", GetGatewayURL()+"/v1/functions/"+funcName+"/invoke", bytes.NewReader(invokePayload))
|
||||
invokeReq, _ := http.NewRequestWithContext(ctx, "POST", e2e.GetGatewayURL()+"/v1/functions/"+funcName+"/invoke?namespace="+namespace, bytes.NewReader(invokePayload))
|
||||
invokeReq.Header.Set("Content-Type", "application/json")
|
||||
|
||||
if apiKey := GetAPIKey(); apiKey != "" {
|
||||
if apiKey := e2e.GetAPIKey(); apiKey != "" {
|
||||
invokeReq.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
|
||||
@ -94,8 +101,8 @@ func TestServerless_DeployAndInvoke(t *testing.T) {
|
||||
}
|
||||
|
||||
// 3. List functions
|
||||
listReq, _ := http.NewRequestWithContext(ctx, "GET", GetGatewayURL()+"/v1/functions?namespace="+namespace, nil)
|
||||
if apiKey := GetAPIKey(); apiKey != "" {
|
||||
listReq, _ := http.NewRequestWithContext(ctx, "GET", e2e.GetGatewayURL()+"/v1/functions?namespace="+namespace, nil)
|
||||
if apiKey := e2e.GetAPIKey(); apiKey != "" {
|
||||
listReq.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
resp, err = client.Do(listReq)
|
||||
@ -108,8 +115,8 @@ func TestServerless_DeployAndInvoke(t *testing.T) {
|
||||
}
|
||||
|
||||
// 4. Delete function
|
||||
deleteReq, _ := http.NewRequestWithContext(ctx, "DELETE", GetGatewayURL()+"/v1/functions/"+funcName+"?namespace="+namespace, nil)
|
||||
if apiKey := GetAPIKey(); apiKey != "" {
|
||||
deleteReq, _ := http.NewRequestWithContext(ctx, "DELETE", e2e.GetGatewayURL()+"/v1/functions/"+funcName+"?namespace="+namespace, nil)
|
||||
if apiKey := e2e.GetAPIKey(); apiKey != "" {
|
||||
deleteReq.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
resp, err = client.Do(deleteReq)
|
||||
@ -1,6 +1,6 @@
|
||||
//go:build e2e
|
||||
|
||||
package e2e
|
||||
package shared_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@ -10,6 +10,8 @@ import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
e2e "github.com/DeBrosOfficial/network/e2e"
|
||||
)
|
||||
|
||||
// uploadFile is a helper to upload a file to storage
|
||||
@ -34,7 +36,7 @@ func uploadFile(t *testing.T, ctx context.Context, content []byte, filename stri
|
||||
}
|
||||
|
||||
// Create request
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, e2e.GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
@ -42,13 +44,13 @@ func uploadFile(t *testing.T, ctx context.Context, content []byte, filename stri
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
// Add auth headers
|
||||
if jwt := GetJWT(); jwt != "" {
|
||||
if jwt := e2e.GetJWT(); jwt != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+jwt)
|
||||
} else if apiKey := GetAPIKey(); apiKey != "" {
|
||||
} else if apiKey := e2e.GetAPIKey(); apiKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
|
||||
client := NewHTTPClient(5 * time.Minute)
|
||||
client := e2e.NewHTTPClient(5 * time.Minute)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("upload request failed: %v", err)
|
||||
@ -60,28 +62,20 @@ func uploadFile(t *testing.T, ctx context.Context, content []byte, filename stri
|
||||
t.Fatalf("upload failed with status %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
result, err := DecodeJSONFromReader(resp.Body)
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to read upload response: %v", err)
|
||||
}
|
||||
var result map[string]interface{}
|
||||
if err := e2e.DecodeJSON(body, &result); err != nil {
|
||||
t.Fatalf("failed to decode upload response: %v", err)
|
||||
}
|
||||
|
||||
return result["cid"].(string)
|
||||
}
|
||||
|
||||
// DecodeJSON is a helper to decode JSON from io.ReadCloser
|
||||
func DecodeJSONFromReader(rc io.ReadCloser) (map[string]interface{}, error) {
|
||||
defer rc.Close()
|
||||
body, err := io.ReadAll(rc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var result map[string]interface{}
|
||||
err = DecodeJSON(body, &result)
|
||||
return result, err
|
||||
}
|
||||
|
||||
func TestStorage_UploadText(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
@ -107,18 +101,18 @@ func TestStorage_UploadText(t *testing.T) {
|
||||
}
|
||||
|
||||
// Create request
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, e2e.GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
if apiKey := GetAPIKey(); apiKey != "" {
|
||||
if apiKey := e2e.GetAPIKey(); apiKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
|
||||
client := NewHTTPClient(5 * time.Minute)
|
||||
client := e2e.NewHTTPClient(5 * time.Minute)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("upload request failed: %v", err)
|
||||
@ -132,7 +126,7 @@ func TestStorage_UploadText(t *testing.T) {
|
||||
|
||||
var result map[string]interface{}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if err := DecodeJSON(body, &result); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &result); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -150,7 +144,7 @@ func TestStorage_UploadText(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStorage_UploadBinary(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
@ -177,18 +171,18 @@ func TestStorage_UploadBinary(t *testing.T) {
|
||||
}
|
||||
|
||||
// Create request
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, e2e.GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
if apiKey := GetAPIKey(); apiKey != "" {
|
||||
if apiKey := e2e.GetAPIKey(); apiKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
|
||||
client := NewHTTPClient(5 * time.Minute)
|
||||
client := e2e.NewHTTPClient(5 * time.Minute)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("upload request failed: %v", err)
|
||||
@ -202,7 +196,7 @@ func TestStorage_UploadBinary(t *testing.T) {
|
||||
|
||||
var result map[string]interface{}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if err := DecodeJSON(body, &result); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &result); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -212,7 +206,7 @@ func TestStorage_UploadBinary(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStorage_UploadLarge(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
@ -239,18 +233,18 @@ func TestStorage_UploadLarge(t *testing.T) {
|
||||
}
|
||||
|
||||
// Create request
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, e2e.GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
if apiKey := GetAPIKey(); apiKey != "" {
|
||||
if apiKey := e2e.GetAPIKey(); apiKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
|
||||
client := NewHTTPClient(5 * time.Minute)
|
||||
client := e2e.NewHTTPClient(5 * time.Minute)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("upload request failed: %v", err)
|
||||
@ -264,7 +258,7 @@ func TestStorage_UploadLarge(t *testing.T) {
|
||||
|
||||
var result map[string]interface{}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if err := DecodeJSON(body, &result); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &result); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
@ -274,7 +268,7 @@ func TestStorage_UploadLarge(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStorage_PinUnpin(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
@ -299,18 +293,18 @@ func TestStorage_PinUnpin(t *testing.T) {
|
||||
}
|
||||
|
||||
// Create upload request
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, e2e.GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
if apiKey := GetAPIKey(); apiKey != "" {
|
||||
if apiKey := e2e.GetAPIKey(); apiKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
|
||||
client := NewHTTPClient(5 * time.Minute)
|
||||
client := e2e.NewHTTPClient(5 * time.Minute)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("upload failed: %v", err)
|
||||
@ -319,16 +313,23 @@ func TestStorage_PinUnpin(t *testing.T) {
|
||||
|
||||
var uploadResult map[string]interface{}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if err := DecodeJSON(body, &uploadResult); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &uploadResult); err != nil {
|
||||
t.Fatalf("failed to decode upload response: %v", err)
|
||||
}
|
||||
|
||||
cid := uploadResult["cid"].(string)
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("upload failed with status %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
cid, ok := uploadResult["cid"].(string)
|
||||
if !ok || cid == "" {
|
||||
t.Fatalf("no CID in upload response: %v", uploadResult)
|
||||
}
|
||||
|
||||
// Pin the file
|
||||
pinReq := &HTTPRequest{
|
||||
pinReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodPost,
|
||||
URL: GetGatewayURL() + "/v1/storage/pin",
|
||||
URL: e2e.GetGatewayURL() + "/v1/storage/pin",
|
||||
Body: map[string]interface{}{
|
||||
"cid": cid,
|
||||
"name": "pinned-file",
|
||||
@ -345,7 +346,7 @@ func TestStorage_PinUnpin(t *testing.T) {
|
||||
}
|
||||
|
||||
var pinResult map[string]interface{}
|
||||
if err := DecodeJSON(body2, &pinResult); err != nil {
|
||||
if err := e2e.DecodeJSON(body2, &pinResult); err != nil {
|
||||
t.Fatalf("failed to decode pin response: %v", err)
|
||||
}
|
||||
|
||||
@ -354,9 +355,9 @@ func TestStorage_PinUnpin(t *testing.T) {
|
||||
}
|
||||
|
||||
// Unpin the file
|
||||
unpinReq := &HTTPRequest{
|
||||
unpinReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodDelete,
|
||||
URL: GetGatewayURL() + "/v1/storage/unpin/" + cid,
|
||||
URL: e2e.GetGatewayURL() + "/v1/storage/unpin/" + cid,
|
||||
}
|
||||
|
||||
body3, status, err := unpinReq.Do(ctx)
|
||||
@ -370,7 +371,7 @@ func TestStorage_PinUnpin(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStorage_Status(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
@ -395,18 +396,18 @@ func TestStorage_Status(t *testing.T) {
|
||||
}
|
||||
|
||||
// Create upload request
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, e2e.GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
if apiKey := GetAPIKey(); apiKey != "" {
|
||||
if apiKey := e2e.GetAPIKey(); apiKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
|
||||
client := NewHTTPClient(5 * time.Minute)
|
||||
client := e2e.NewHTTPClient(5 * time.Minute)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("upload failed: %v", err)
|
||||
@ -415,16 +416,16 @@ func TestStorage_Status(t *testing.T) {
|
||||
|
||||
var uploadResult map[string]interface{}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if err := DecodeJSON(body, &uploadResult); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &uploadResult); err != nil {
|
||||
t.Fatalf("failed to decode upload response: %v", err)
|
||||
}
|
||||
|
||||
cid := uploadResult["cid"].(string)
|
||||
|
||||
// Get status
|
||||
statusReq := &HTTPRequest{
|
||||
statusReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: GetGatewayURL() + "/v1/storage/status/" + cid,
|
||||
URL: e2e.GetGatewayURL() + "/v1/storage/status/" + cid,
|
||||
}
|
||||
|
||||
statusBody, status, err := statusReq.Do(ctx)
|
||||
@ -437,7 +438,7 @@ func TestStorage_Status(t *testing.T) {
|
||||
}
|
||||
|
||||
var statusResult map[string]interface{}
|
||||
if err := DecodeJSON(statusBody, &statusResult); err != nil {
|
||||
if err := e2e.DecodeJSON(statusBody, &statusResult); err != nil {
|
||||
t.Fatalf("failed to decode status response: %v", err)
|
||||
}
|
||||
|
||||
@ -447,14 +448,14 @@ func TestStorage_Status(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStorage_InvalidCID(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
statusReq := &HTTPRequest{
|
||||
statusReq := &e2e.HTTPRequest{
|
||||
Method: http.MethodGet,
|
||||
URL: GetGatewayURL() + "/v1/storage/status/QmInvalidCID123456789",
|
||||
URL: e2e.GetGatewayURL() + "/v1/storage/status/QmInvalidCID123456789",
|
||||
}
|
||||
|
||||
_, status, err := statusReq.Do(ctx)
|
||||
@ -468,7 +469,7 @@ func TestStorage_InvalidCID(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStorage_GetByteRange(t *testing.T) {
|
||||
SkipIfMissingGateway(t)
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
@ -493,18 +494,18 @@ func TestStorage_GetByteRange(t *testing.T) {
|
||||
}
|
||||
|
||||
// Create upload request
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, e2e.GetGatewayURL()+"/v1/storage/upload", &buf)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
|
||||
if apiKey := GetAPIKey(); apiKey != "" {
|
||||
if apiKey := e2e.GetAPIKey(); apiKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
|
||||
client := NewHTTPClient(5 * time.Minute)
|
||||
client := e2e.NewHTTPClient(5 * time.Minute)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("upload failed: %v", err)
|
||||
@ -513,19 +514,19 @@ func TestStorage_GetByteRange(t *testing.T) {
|
||||
|
||||
var uploadResult map[string]interface{}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
if err := DecodeJSON(body, &uploadResult); err != nil {
|
||||
if err := e2e.DecodeJSON(body, &uploadResult); err != nil {
|
||||
t.Fatalf("failed to decode upload response: %v", err)
|
||||
}
|
||||
|
||||
cid := uploadResult["cid"].(string)
|
||||
|
||||
// Get full content
|
||||
getReq, err := http.NewRequestWithContext(ctx, http.MethodGet, GetGatewayURL()+"/v1/storage/get/"+cid, nil)
|
||||
getReq, err := http.NewRequestWithContext(ctx, http.MethodGet, e2e.GetGatewayURL()+"/v1/storage/get/"+cid, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create get request: %v", err)
|
||||
}
|
||||
|
||||
if apiKey := GetAPIKey(); apiKey != "" {
|
||||
if apiKey := e2e.GetAPIKey(); apiKey != "" {
|
||||
getReq.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
}
|
||||
|
||||
241
core/e2e/shared/webrtc_test.go
Normal file
241
core/e2e/shared/webrtc_test.go
Normal file
@ -0,0 +1,241 @@
|
||||
//go:build e2e
|
||||
|
||||
package shared_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
e2e "github.com/DeBrosOfficial/network/e2e"
|
||||
)
|
||||
|
||||
// turnCredentialsResponse is the expected response from the TURN credentials endpoint.
|
||||
type turnCredentialsResponse struct {
|
||||
URLs []string `json:"urls"`
|
||||
Username string `json:"username"`
|
||||
Credential string `json:"credential"`
|
||||
TTL int `json:"ttl"`
|
||||
}
|
||||
|
||||
// TestWebRTC_TURNCredentials_RequiresAuth verifies that the TURN credentials endpoint
|
||||
// rejects unauthenticated requests.
|
||||
func TestWebRTC_TURNCredentials_RequiresAuth(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
gatewayURL := e2e.GetGatewayURL()
|
||||
client := e2e.NewHTTPClient(10 * time.Second)
|
||||
|
||||
req, err := http.NewRequest("POST", gatewayURL+"/v1/webrtc/turn/credentials", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 Unauthorized, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWebRTC_TURNCredentials_ValidResponse verifies that authenticated requests to the
|
||||
// TURN credentials endpoint return a valid credential structure.
|
||||
func TestWebRTC_TURNCredentials_ValidResponse(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
gatewayURL := e2e.GetGatewayURL()
|
||||
apiKey := e2e.GetAPIKey()
|
||||
if apiKey == "" {
|
||||
t.Skip("no API key configured")
|
||||
}
|
||||
client := e2e.NewHTTPClient(10 * time.Second)
|
||||
|
||||
req, err := http.NewRequest("POST", gatewayURL+"/v1/webrtc/turn/credentials", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("expected 200 OK, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var creds turnCredentialsResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&creds); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
|
||||
if len(creds.URLs) == 0 {
|
||||
t.Fatal("expected at least one TURN URL")
|
||||
}
|
||||
if creds.Username == "" {
|
||||
t.Fatal("expected non-empty username")
|
||||
}
|
||||
if creds.Credential == "" {
|
||||
t.Fatal("expected non-empty credential")
|
||||
}
|
||||
if creds.TTL <= 0 {
|
||||
t.Fatalf("expected positive TTL, got %d", creds.TTL)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWebRTC_Rooms_RequiresAuth verifies that the rooms endpoint rejects unauthenticated requests.
|
||||
func TestWebRTC_Rooms_RequiresAuth(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
gatewayURL := e2e.GetGatewayURL()
|
||||
client := e2e.NewHTTPClient(10 * time.Second)
|
||||
|
||||
req, err := http.NewRequest("GET", gatewayURL+"/v1/webrtc/rooms", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 Unauthorized, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWebRTC_Signal_RequiresAuth verifies that the signaling WebSocket rejects
|
||||
// unauthenticated connections.
|
||||
func TestWebRTC_Signal_RequiresAuth(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
gatewayURL := e2e.GetGatewayURL()
|
||||
client := e2e.NewHTTPClient(10 * time.Second)
|
||||
|
||||
// Use regular HTTP GET to the signal endpoint — without auth it should return 401
|
||||
// before WebSocket upgrade
|
||||
req, err := http.NewRequest("GET", gatewayURL+"/v1/webrtc/signal?room=test-room", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWebRTC_Rooms_CreateAndList verifies room creation and listing with proper auth.
|
||||
func TestWebRTC_Rooms_CreateAndList(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
gatewayURL := e2e.GetGatewayURL()
|
||||
apiKey := e2e.GetAPIKey()
|
||||
if apiKey == "" {
|
||||
t.Skip("no API key configured")
|
||||
}
|
||||
client := e2e.NewHTTPClient(10 * time.Second)
|
||||
|
||||
roomID := e2e.GenerateUniqueID("e2e-webrtc-room")
|
||||
|
||||
// Create room
|
||||
createBody, _ := json.Marshal(map[string]string{"room_id": roomID})
|
||||
req, err := http.NewRequest("POST", gatewayURL+"/v1/webrtc/rooms", bytes.NewReader(createBody))
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("create room failed: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("expected 200/201, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// List rooms
|
||||
req, err = http.NewRequest("GET", gatewayURL+"/v1/webrtc/rooms", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
|
||||
resp, err = client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("list rooms failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Clean up: delete room
|
||||
req, err = http.NewRequest("DELETE", gatewayURL+"/v1/webrtc/rooms?room_id="+roomID, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
|
||||
resp2, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("delete room failed: %v", err)
|
||||
}
|
||||
resp2.Body.Close()
|
||||
}
|
||||
|
||||
// TestWebRTC_PermissionsPolicy verifies the Permissions-Policy header allows camera and microphone.
|
||||
func TestWebRTC_PermissionsPolicy(t *testing.T) {
|
||||
e2e.SkipIfMissingGateway(t)
|
||||
|
||||
gatewayURL := e2e.GetGatewayURL()
|
||||
apiKey := e2e.GetAPIKey()
|
||||
if apiKey == "" {
|
||||
t.Skip("no API key configured")
|
||||
}
|
||||
client := e2e.NewHTTPClient(10 * time.Second)
|
||||
|
||||
req, err := http.NewRequest("GET", gatewayURL+"/v1/webrtc/rooms", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("request failed: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
pp := resp.Header.Get("Permissions-Policy")
|
||||
if pp == "" {
|
||||
t.Skip("Permissions-Policy header not set")
|
||||
}
|
||||
|
||||
if !strings.Contains(pp, "camera=(self)") {
|
||||
t.Errorf("Permissions-Policy missing camera=(self), got: %s", pp)
|
||||
}
|
||||
if !strings.Contains(pp, "microphone=(self)") {
|
||||
t.Errorf("Permissions-Policy missing microphone=(self), got: %s", pp)
|
||||
}
|
||||
}
|
||||
@ -1,34 +1,43 @@
|
||||
module github.com/DeBrosOfficial/network
|
||||
|
||||
go 1.24.0
|
||||
|
||||
toolchain go1.24.1
|
||||
go 1.24.6
|
||||
|
||||
require (
|
||||
github.com/charmbracelet/bubbles v0.20.0
|
||||
github.com/charmbracelet/bubbletea v1.2.4
|
||||
github.com/charmbracelet/lipgloss v1.0.0
|
||||
github.com/coredns/caddy v1.1.4
|
||||
github.com/coredns/coredns v1.12.1
|
||||
github.com/ethereum/go-ethereum v1.13.14
|
||||
github.com/go-chi/chi/v5 v5.2.3
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674
|
||||
github.com/libp2p/go-libp2p v0.41.1
|
||||
github.com/libp2p/go-libp2p-pubsub v0.14.2
|
||||
github.com/mackerelio/go-osstat v0.2.6
|
||||
github.com/mattn/go-sqlite3 v1.14.32
|
||||
github.com/multiformats/go-multiaddr v0.15.0
|
||||
github.com/mdp/qrterminal/v3 v3.2.1
|
||||
github.com/miekg/dns v1.1.70
|
||||
github.com/multiformats/go-multiaddr v0.16.0
|
||||
github.com/olric-data/olric v0.7.0
|
||||
github.com/pion/interceptor v0.1.40
|
||||
github.com/pion/rtcp v1.2.15
|
||||
github.com/pion/turn/v4 v4.0.2
|
||||
github.com/pion/webrtc/v4 v4.1.2
|
||||
github.com/rqlite/gorqlite v0.0.0-20250609141355-ac86a4a1c9a8
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/tetratelabs/wazero v1.11.0
|
||||
go.uber.org/zap v1.27.0
|
||||
golang.org/x/crypto v0.40.0
|
||||
golang.org/x/net v0.42.0
|
||||
golang.org/x/crypto v0.47.0
|
||||
golang.org/x/net v0.49.0
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/RoaringBitmap/roaring v1.9.4 // indirect
|
||||
github.com/apparentlymart/go-cidr v1.1.0 // indirect
|
||||
github.com/armon/go-metrics v0.4.1 // indirect
|
||||
github.com/atotto/clipboard v0.1.4 // indirect
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||
@ -42,12 +51,14 @@ require (
|
||||
github.com/charmbracelet/x/term v0.2.1 // indirect
|
||||
github.com/containerd/cgroups v1.1.0 // indirect
|
||||
github.com/coreos/go-systemd/v22 v22.5.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/docker/go-units v0.5.0 // indirect
|
||||
github.com/elastic/gosigar v0.14.3 // indirect
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
|
||||
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 // indirect
|
||||
github.com/flynn/noise v1.1.0 // indirect
|
||||
github.com/francoispqt/gojay v1.2.13 // indirect
|
||||
github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
|
||||
@ -56,38 +67,40 @@ require (
|
||||
github.com/google/btree v1.1.3 // indirect
|
||||
github.com/google/gopacket v1.1.19 // indirect
|
||||
github.com/google/pprof v0.0.0-20250208200701-d0013a598941 // indirect
|
||||
github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
|
||||
github.com/hashicorp/go-metrics v0.5.4 // indirect
|
||||
github.com/hashicorp/go-msgpack/v2 v2.1.3 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/go-sockaddr v1.0.7 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||
github.com/hashicorp/golang-lru v1.0.2 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/hashicorp/logutils v1.0.0 // indirect
|
||||
github.com/hashicorp/memberlist v0.5.3 // indirect
|
||||
github.com/holiman/uint256 v1.2.4 // indirect
|
||||
github.com/huin/goupnp v1.3.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/ipfs/go-cid v0.5.0 // indirect
|
||||
github.com/ipfs/go-log/v2 v2.6.0 // indirect
|
||||
github.com/jackpal/go-nat-pmp v1.0.2 // indirect
|
||||
github.com/jbenet/go-temp-err-catcher v0.1.0 // indirect
|
||||
github.com/klauspost/compress v1.18.0 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
|
||||
github.com/koron/go-ssdp v0.0.5 // indirect
|
||||
github.com/koron/go-ssdp v0.0.6 // indirect
|
||||
github.com/libp2p/go-buffer-pool v0.1.0 // indirect
|
||||
github.com/libp2p/go-flow-metrics v0.2.0 // indirect
|
||||
github.com/libp2p/go-libp2p-asn-util v0.4.1 // indirect
|
||||
github.com/libp2p/go-msgio v0.3.0 // indirect
|
||||
github.com/libp2p/go-netroute v0.2.2 // indirect
|
||||
github.com/libp2p/go-netroute v0.3.0 // indirect
|
||||
github.com/libp2p/go-reuseport v0.4.0 // indirect
|
||||
github.com/libp2p/go-yamux/v5 v5.0.0 // indirect
|
||||
github.com/libp2p/go-yamux/v5 v5.0.1 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
|
||||
github.com/marten-seemann/tcp v0.0.0-20210406111302-dfbc87cc63fd // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-localereader v0.0.1 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/miekg/dns v1.1.66 // indirect
|
||||
github.com/mikioh/tcpinfo v0.0.0-20190314235526-30a79bb1804b // indirect
|
||||
github.com/mikioh/tcpopt v0.0.0-20190314235656-172688c1accc // indirect
|
||||
github.com/minio/sha256-simd v1.0.1 // indirect
|
||||
@ -101,37 +114,35 @@ require (
|
||||
github.com/multiformats/go-multiaddr-dns v0.4.1 // indirect
|
||||
github.com/multiformats/go-multiaddr-fmt v0.1.0 // indirect
|
||||
github.com/multiformats/go-multibase v0.2.0 // indirect
|
||||
github.com/multiformats/go-multicodec v0.9.0 // indirect
|
||||
github.com/multiformats/go-multicodec v0.9.1 // indirect
|
||||
github.com/multiformats/go-multihash v0.2.3 // indirect
|
||||
github.com/multiformats/go-multistream v0.6.0 // indirect
|
||||
github.com/multiformats/go-multistream v0.6.1 // indirect
|
||||
github.com/multiformats/go-varint v0.0.7 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/onsi/ginkgo/v2 v2.22.2 // indirect
|
||||
github.com/opencontainers/runtime-spec v1.2.0 // indirect
|
||||
github.com/opentracing/opentracing-go v1.2.0 // indirect
|
||||
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect
|
||||
github.com/pion/datachannel v1.5.10 // indirect
|
||||
github.com/pion/dtls/v2 v2.2.12 // indirect
|
||||
github.com/pion/dtls/v3 v3.0.4 // indirect
|
||||
github.com/pion/ice/v4 v4.0.8 // indirect
|
||||
github.com/pion/interceptor v0.1.37 // indirect
|
||||
github.com/pion/dtls/v3 v3.0.6 // indirect
|
||||
github.com/pion/ice/v4 v4.0.10 // indirect
|
||||
github.com/pion/logging v0.2.3 // indirect
|
||||
github.com/pion/mdns/v2 v2.0.7 // indirect
|
||||
github.com/pion/randutil v0.1.0 // indirect
|
||||
github.com/pion/rtcp v1.2.15 // indirect
|
||||
github.com/pion/rtp v1.8.11 // indirect
|
||||
github.com/pion/sctp v1.8.37 // indirect
|
||||
github.com/pion/sdp/v3 v3.0.10 // indirect
|
||||
github.com/pion/srtp/v3 v3.0.4 // indirect
|
||||
github.com/pion/rtp v1.8.19 // indirect
|
||||
github.com/pion/sctp v1.8.39 // indirect
|
||||
github.com/pion/sdp/v3 v3.0.13 // indirect
|
||||
github.com/pion/srtp/v3 v3.0.6 // indirect
|
||||
github.com/pion/stun v0.6.1 // indirect
|
||||
github.com/pion/stun/v3 v3.0.0 // indirect
|
||||
github.com/pion/transport/v2 v2.2.10 // indirect
|
||||
github.com/pion/transport/v3 v3.0.7 // indirect
|
||||
github.com/pion/turn/v4 v4.0.0 // indirect
|
||||
github.com/pion/webrtc/v4 v4.0.10 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/prometheus/client_golang v1.22.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/prometheus/client_golang v1.23.0 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.63.0 // indirect
|
||||
github.com/prometheus/common v0.67.5 // indirect
|
||||
github.com/prometheus/procfs v0.16.1 // indirect
|
||||
github.com/quic-go/qpack v0.5.1 // indirect
|
||||
github.com/quic-go/quic-go v0.50.1 // indirect
|
||||
@ -139,25 +150,33 @@ require (
|
||||
github.com/raulk/go-watchdog v1.3.0 // indirect
|
||||
github.com/redis/go-redis/v9 v9.8.0 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/rogpeppe/go-internal v1.13.1 // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 // indirect
|
||||
github.com/spaolacci/murmur3 v1.1.0 // indirect
|
||||
github.com/spf13/pflag v1.0.9 // indirect
|
||||
github.com/tidwall/btree v1.7.0 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/redcon v1.6.2 // indirect
|
||||
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
|
||||
github.com/wlynxg/anet v0.0.5 // indirect
|
||||
go.uber.org/dig v1.18.0 // indirect
|
||||
go.uber.org/fx v1.23.0 // indirect
|
||||
go.uber.org/mock v0.5.0 // indirect
|
||||
go.uber.org/dig v1.19.0 // indirect
|
||||
go.uber.org/fx v1.24.0 // indirect
|
||||
go.uber.org/mock v0.6.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
||||
golang.org/x/exp v0.0.0-20250718183923-645b1fa84792 // indirect
|
||||
golang.org/x/mod v0.26.0 // indirect
|
||||
golang.org/x/sync v0.16.0 // indirect
|
||||
golang.org/x/sys v0.38.0 // indirect
|
||||
golang.org/x/text v0.27.0 // indirect
|
||||
golang.org/x/tools v0.35.0 // indirect
|
||||
google.golang.org/protobuf v1.36.6 // indirect
|
||||
golang.org/x/mod v0.31.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.40.0 // indirect
|
||||
golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc // indirect
|
||||
golang.org/x/term v0.39.0 // indirect
|
||||
golang.org/x/text v0.33.0 // indirect
|
||||
golang.org/x/time v0.14.0 // indirect
|
||||
golang.org/x/tools v0.40.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect
|
||||
google.golang.org/grpc v1.78.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
lukechampine.com/blake3 v1.4.1 // indirect
|
||||
rsc.io/qr v0.2.0 // indirect
|
||||
)
|
||||
@ -17,6 +17,8 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF
|
||||
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
|
||||
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=
|
||||
github.com/apparentlymart/go-cidr v1.1.0 h1:2mAhrMoF+nhXqxTzSZMUzDHkLjmIHC+Zzn4tdgBZjnU=
|
||||
github.com/apparentlymart/go-cidr v1.1.0/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc=
|
||||
github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA=
|
||||
github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4=
|
||||
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
|
||||
@ -65,15 +67,21 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk
|
||||
github.com/containerd/cgroups v0.0.0-20201119153540-4cbc285b3327/go.mod h1:ZJeTFisyysqgcCdecO57Dj79RfL0LNeGiFUqLYQRYLE=
|
||||
github.com/containerd/cgroups v1.1.0 h1:v8rEWFl6EoqHB+swVNjVoCJE8o3jX7e8nqBGPLaDFBM=
|
||||
github.com/containerd/cgroups v1.1.0/go.mod h1:6ppBcbh/NOOUU+dMKrykgaBnK9lCIBxHqJDGwsa1mIw=
|
||||
github.com/coredns/caddy v1.1.4 h1:+Lls5xASB0QsA2jpCroCOwpPlb5GjIGlxdjXxdX0XVo=
|
||||
github.com/coredns/caddy v1.1.4/go.mod h1:A6ntJQlAWuQfFlsd9hvigKbo2WS0VUs2l1e2F+BawD4=
|
||||
github.com/coredns/coredns v1.12.1 h1:haptbGscSbdWU46xrjdPj1vp3wvH1Z2FgCSQKEdgN5s=
|
||||
github.com/coredns/coredns v1.12.1/go.mod h1:V26ngiKdNvAiEre5PTAvklrvTjnNjl6lakq1nbE/NbU=
|
||||
github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
|
||||
github.com/coreos/go-systemd/v22 v22.1.0/go.mod h1:xO0FLkIi5MaZafQlIrOotqXZ90ih+1atmu1JpKERPPk=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c h1:pFUpOrbxDR6AkioZ1ySsx5yxlDQZ8stG2b88gTPxgJU=
|
||||
github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c/go.mod h1:6UhI8N9EjYm1c2odKpFpAYeR8dsBeM7PtzQhRgxRr9U=
|
||||
github.com/decred/dcrd/crypto/blake256 v1.1.0 h1:zPMNGQCm0g4QTY27fOCorQW7EryeQ/U0x++OzVrdms8=
|
||||
@ -93,6 +101,7 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
|
||||
github.com/ethereum/go-ethereum v1.13.14 h1:EwiY3FZP94derMCIam1iW4HFVrSgIcpsu0HwTQtm6CQ=
|
||||
github.com/ethereum/go-ethereum v1.13.14/go.mod h1:TN8ZiHrdJwSe8Cb6x+p0hs5CxhJZPbqB7hHkaUXcmIU=
|
||||
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ=
|
||||
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
|
||||
github.com/flynn/noise v1.1.0 h1:KjPQoQCEFdZDiP03phOvGi11+SVVhBG2wOWAorLsstg=
|
||||
github.com/flynn/noise v1.1.0/go.mod h1:xbMo+0i6+IGbYdJhF31t2eR1BIU0CYc12+BNAKwUTag=
|
||||
@ -110,8 +119,10 @@ github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vb
|
||||
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
||||
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
|
||||
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
|
||||
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
|
||||
github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
|
||||
@ -137,6 +148,8 @@ github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:W
|
||||
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=
|
||||
github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
|
||||
@ -158,15 +171,18 @@ github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXi
|
||||
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
|
||||
github.com/google/pprof v0.0.0-20250208200701-d0013a598941 h1:43XjGa6toxLpeksjcxs1jIoIyr+vUfOqY2c6HB4bpoc=
|
||||
github.com/google/pprof v0.0.0-20250208200701-d0013a598941/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144=
|
||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY=
|
||||
github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE08qbEPm1M08qg=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo=
|
||||
github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA=
|
||||
github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
|
||||
github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw=
|
||||
github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645 h1:MJG/KsmcqMwFAkh8mTnAwhyKoB+sTAnY4CACC110tbU=
|
||||
github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645/go.mod h1:6iZfnjpejD4L/4DwD7NryNaJyCQdzwWwH2MWhCA90Kw=
|
||||
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
|
||||
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
@ -183,8 +199,9 @@ github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9
|
||||
github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs=
|
||||
github.com/hashicorp/go-sockaddr v1.0.7 h1:G+pTkSO01HpR5qCxg7lxfsFEZaG+C0VssTy/9dbT+Fw=
|
||||
github.com/hashicorp/go-sockaddr v1.0.7/go.mod h1:FZQbEYa1pxkQ7WLpyXJ6cbjpT8q0YgQaK/JakXqGyWw=
|
||||
github.com/hashicorp/go-uuid v1.0.0 h1:RS8zrF7PhGwyNPOtxSClXXj9HA8feRnJzgnI1RJCSnM=
|
||||
github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
|
||||
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||
github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c=
|
||||
github.com/hashicorp/golang-lru v1.0.2/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4=
|
||||
@ -198,6 +215,8 @@ github.com/holiman/uint256 v1.2.4 h1:jUc4Nk8fm9jZabQuqr2JzednajVmBpC+oiTiXZJEApU
|
||||
github.com/holiman/uint256 v1.2.4/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E=
|
||||
github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc=
|
||||
github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/ipfs/go-cid v0.5.0 h1:goEKKhaGm0ul11IHA7I6p1GmKz8kEYniqFopaB5Otwg=
|
||||
github.com/ipfs/go-cid v0.5.0/go.mod h1:0L7vmeNXpQpUS9vt+yEARkJ8rOg43DF3iPgn4GIN0mk=
|
||||
github.com/ipfs/go-log/v2 v2.6.0 h1:2Nu1KKQQ2ayonKp4MPo6pXCjqw1ULc9iohRqWV5EYqg=
|
||||
@ -224,8 +243,8 @@ github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2
|
||||
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/koron/go-ssdp v0.0.5 h1:E1iSMxIs4WqxTbIBLtmNBeOOC+1sCIXQeqTWVnpmwhk=
|
||||
github.com/koron/go-ssdp v0.0.5/go.mod h1:Qm59B7hpKpDqfyRNWRNr00jGwLdXjDyZh6y7rH6VS0w=
|
||||
github.com/koron/go-ssdp v0.0.6 h1:Jb0h04599eq/CY7rB5YEqPS83HmRfHP2azkxMN2rFtU=
|
||||
github.com/koron/go-ssdp v0.0.6/go.mod h1:0R9LfRJGek1zWTjN3JUNlm5INCDYGpRDfAptnct63fI=
|
||||
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
@ -250,12 +269,12 @@ github.com/libp2p/go-libp2p-testing v0.12.0 h1:EPvBb4kKMWO29qP4mZGyhVzUyR25dvfUI
|
||||
github.com/libp2p/go-libp2p-testing v0.12.0/go.mod h1:KcGDRXyN7sQCllucn1cOOS+Dmm7ujhfEyXQL5lvkcPg=
|
||||
github.com/libp2p/go-msgio v0.3.0 h1:mf3Z8B1xcFN314sWX+2vOTShIE0Mmn2TXn3YCUQGNj0=
|
||||
github.com/libp2p/go-msgio v0.3.0/go.mod h1:nyRM819GmVaF9LX3l03RMh10QdOroF++NBbxAb0mmDM=
|
||||
github.com/libp2p/go-netroute v0.2.2 h1:Dejd8cQ47Qx2kRABg6lPwknU7+nBnFRpko45/fFPuZ8=
|
||||
github.com/libp2p/go-netroute v0.2.2/go.mod h1:Rntq6jUAH0l9Gg17w5bFGhcC9a+vk4KNXs6s7IljKYE=
|
||||
github.com/libp2p/go-netroute v0.3.0 h1:nqPCXHmeNmgTJnktosJ/sIef9hvwYCrsLxXmfNks/oc=
|
||||
github.com/libp2p/go-netroute v0.3.0/go.mod h1:Nkd5ShYgSMS5MUKy/MU2T57xFoOKvvLR92Lic48LEyA=
|
||||
github.com/libp2p/go-reuseport v0.4.0 h1:nR5KU7hD0WxXCJbmw7r2rhRYruNRl2koHw8fQscQm2s=
|
||||
github.com/libp2p/go-reuseport v0.4.0/go.mod h1:ZtI03j/wO5hZVDFo2jKywN6bYKWLOy8Se6DrI2E1cLU=
|
||||
github.com/libp2p/go-yamux/v5 v5.0.0 h1:2djUh96d3Jiac/JpGkKs4TO49YhsfLopAoryfPmf+Po=
|
||||
github.com/libp2p/go-yamux/v5 v5.0.0/go.mod h1:en+3cdX51U0ZslwRdRLrvQsdayFt3TSUKvBGErzpWbU=
|
||||
github.com/libp2p/go-yamux/v5 v5.0.1 h1:f0WoX/bEF2E8SbE4c/k1Mo+/9z0O4oC/hWEA+nfYRSg=
|
||||
github.com/libp2p/go-yamux/v5 v5.0.1/go.mod h1:en+3cdX51U0ZslwRdRLrvQsdayFt3TSUKvBGErzpWbU=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=
|
||||
@ -273,9 +292,13 @@ github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh
|
||||
github.com/mattn/go-sqlite3 v1.14.32 h1:JD12Ag3oLy1zQA+BNn74xRgaBbdhbNIDYvQUEuuErjs=
|
||||
github.com/mattn/go-sqlite3 v1.14.32/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
|
||||
github.com/mdp/qrterminal/v3 v3.2.1 h1:6+yQjiiOsSuXT5n9/m60E54vdgFsw0zhADHhHLrFet4=
|
||||
github.com/mdp/qrterminal/v3 v3.2.1/go.mod h1:jOTmXvnBsMy5xqLniO0R++Jmjs2sTm9dFSuQ5kpz/SU=
|
||||
github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4=
|
||||
github.com/miekg/dns v1.1.66 h1:FeZXOS3VCVsKnEAd+wBkjMC3D2K+ww66Cq3VnCINuJE=
|
||||
github.com/miekg/dns v1.1.66/go.mod h1:jGFzBsSNbJw6z1HYut1RKBKHA9PBdxeHrZG8J+gC2WE=
|
||||
github.com/miekg/dns v1.1.70 h1:DZ4u2AV35VJxdD9Fo9fIWm119BsQL5cZU1cQ9s0LkqA=
|
||||
github.com/miekg/dns v1.1.70/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||
github.com/mikioh/tcp v0.0.0-20190314235350-803a9b46060c h1:bzE/A84HN25pxAuk9Eej1Kz9OUelF97nAc82bDquQI8=
|
||||
github.com/mikioh/tcp v0.0.0-20190314235350-803a9b46060c/go.mod h1:0SQS9kMwD2VsyFEB++InYyBJroV/FRmBgcydeSUcJms=
|
||||
github.com/mikioh/tcpinfo v0.0.0-20190314235526-30a79bb1804b h1:z78hV3sbSMAUoyUMM0I83AUIT6Hu17AWfgjzIbtrYFc=
|
||||
@ -306,21 +329,21 @@ github.com/multiformats/go-base32 v0.1.0/go.mod h1:Kj3tFY6zNr+ABYMqeUNeGvkIC/UYg
|
||||
github.com/multiformats/go-base36 v0.2.0 h1:lFsAbNOGeKtuKozrtBsAkSVhv1p9D0/qedU9rQyccr0=
|
||||
github.com/multiformats/go-base36 v0.2.0/go.mod h1:qvnKE++v+2MWCfePClUEjE78Z7P2a1UV0xHgWc0hkp4=
|
||||
github.com/multiformats/go-multiaddr v0.1.1/go.mod h1:aMKBKNEYmzmDmxfX88/vz+J5IU55txyt0p4aiWVohjo=
|
||||
github.com/multiformats/go-multiaddr v0.15.0 h1:zB/HeaI/apcZiTDwhY5YqMvNVl/oQYvs3XySU+qeAVo=
|
||||
github.com/multiformats/go-multiaddr v0.15.0/go.mod h1:JSVUmXDjsVFiW7RjIFMP7+Ev+h1DTbiJgVeTV/tcmP0=
|
||||
github.com/multiformats/go-multiaddr v0.16.0 h1:oGWEVKioVQcdIOBlYM8BH1rZDWOGJSqr9/BKl6zQ4qc=
|
||||
github.com/multiformats/go-multiaddr v0.16.0/go.mod h1:JSVUmXDjsVFiW7RjIFMP7+Ev+h1DTbiJgVeTV/tcmP0=
|
||||
github.com/multiformats/go-multiaddr-dns v0.4.1 h1:whi/uCLbDS3mSEUMb1MsoT4uzUeZB0N32yzufqS0i5M=
|
||||
github.com/multiformats/go-multiaddr-dns v0.4.1/go.mod h1:7hfthtB4E4pQwirrz+J0CcDUfbWzTqEzVyYKKIKpgkc=
|
||||
github.com/multiformats/go-multiaddr-fmt v0.1.0 h1:WLEFClPycPkp4fnIzoFoV9FVd49/eQsuaL3/CWe167E=
|
||||
github.com/multiformats/go-multiaddr-fmt v0.1.0/go.mod h1:hGtDIW4PU4BqJ50gW2quDuPVjyWNZxToGUh/HwTZYJo=
|
||||
github.com/multiformats/go-multibase v0.2.0 h1:isdYCVLvksgWlMW9OZRYJEa9pZETFivncJHmHnnd87g=
|
||||
github.com/multiformats/go-multibase v0.2.0/go.mod h1:bFBZX4lKCA/2lyOFSAoKH5SS6oPyjtnzK/XTFDPkNuk=
|
||||
github.com/multiformats/go-multicodec v0.9.0 h1:pb/dlPnzee/Sxv/j4PmkDRxCOi3hXTz3IbPKOXWJkmg=
|
||||
github.com/multiformats/go-multicodec v0.9.0/go.mod h1:L3QTQvMIaVBkXOXXtVmYE+LI16i14xuaojr/H7Ai54k=
|
||||
github.com/multiformats/go-multicodec v0.9.1 h1:x/Fuxr7ZuR4jJV4Os5g444F7xC4XmyUaT/FWtE+9Zjo=
|
||||
github.com/multiformats/go-multicodec v0.9.1/go.mod h1:LLWNMtyV5ithSBUo3vFIMaeDy+h3EbkMTek1m+Fybbo=
|
||||
github.com/multiformats/go-multihash v0.0.8/go.mod h1:YSLudS+Pi8NHE7o6tb3D8vrpKa63epEDmG8nTduyAew=
|
||||
github.com/multiformats/go-multihash v0.2.3 h1:7Lyc8XfX/IY2jWb/gI7JP+o7JEq9hOa7BFvVU9RSh+U=
|
||||
github.com/multiformats/go-multihash v0.2.3/go.mod h1:dXgKXCXjBzdscBLk9JkjINiEsCKRVch90MdaGiKsvSM=
|
||||
github.com/multiformats/go-multistream v0.6.0 h1:ZaHKbsL404720283o4c/IHQXiS6gb8qAN5EIJ4PN5EA=
|
||||
github.com/multiformats/go-multistream v0.6.0/go.mod h1:MOyoG5otO24cHIg8kf9QW2/NozURlkP/rvi2FQJyCPg=
|
||||
github.com/multiformats/go-multistream v0.6.1 h1:4aoX5v6T+yWmc2raBHsTvzmFhOI8WVOer28DeBBEYdQ=
|
||||
github.com/multiformats/go-multistream v0.6.1/go.mod h1:ksQf6kqHAb6zIsyw7Zm+gAuVo57Qbq84E27YlYqavqw=
|
||||
github.com/multiformats/go-varint v0.0.7 h1:sWSGR+f/eu5ABZA2ZpYKBILXTTs9JWpdEM/nEGOHFS8=
|
||||
github.com/multiformats/go-varint v0.0.7/go.mod h1:r8PUYw/fD/SjBCiKOoDlGF6QawOELpZAu9eioSos/OU=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
@ -338,6 +361,8 @@ github.com/onsi/gomega v1.36.2/go.mod h1:DdwyADRjrc825LhMEkD76cHR5+pUnjhUN8GlHlR
|
||||
github.com/opencontainers/runtime-spec v1.0.2/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0=
|
||||
github.com/opencontainers/runtime-spec v1.2.0 h1:z97+pHb3uELt/yiAWD691HNHQIF07bE7dzrbT927iTk=
|
||||
github.com/opencontainers/runtime-spec v1.2.0/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0=
|
||||
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
|
||||
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
|
||||
github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8=
|
||||
github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY=
|
||||
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
|
||||
@ -348,12 +373,12 @@ github.com/pion/datachannel v1.5.10/go.mod h1:p/jJfC9arb29W7WrxyKbepTU20CFgyx5oL
|
||||
github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s=
|
||||
github.com/pion/dtls/v2 v2.2.12 h1:KP7H5/c1EiVAAKUmXyCzPiQe5+bCJrpOeKg/L05dunk=
|
||||
github.com/pion/dtls/v2 v2.2.12/go.mod h1:d9SYc9fch0CqK90mRk1dC7AkzzpwJj6u2GU3u+9pqFE=
|
||||
github.com/pion/dtls/v3 v3.0.4 h1:44CZekewMzfrn9pmGrj5BNnTMDCFwr+6sLH+cCuLM7U=
|
||||
github.com/pion/dtls/v3 v3.0.4/go.mod h1:R373CsjxWqNPf6MEkfdy3aSe9niZvL/JaKlGeFphtMg=
|
||||
github.com/pion/ice/v4 v4.0.8 h1:ajNx0idNG+S+v9Phu4LSn2cs8JEfTsA1/tEjkkAVpFY=
|
||||
github.com/pion/ice/v4 v4.0.8/go.mod h1:y3M18aPhIxLlcO/4dn9X8LzLLSma84cx6emMSu14FGw=
|
||||
github.com/pion/interceptor v0.1.37 h1:aRA8Zpab/wE7/c0O3fh1PqY0AJI3fCSEM5lRWJVorwI=
|
||||
github.com/pion/interceptor v0.1.37/go.mod h1:JzxbJ4umVTlZAf+/utHzNesY8tmRkM2lVmkS82TTj8Y=
|
||||
github.com/pion/dtls/v3 v3.0.6 h1:7Hkd8WhAJNbRgq9RgdNh1aaWlZlGpYTzdqjy9x9sK2E=
|
||||
github.com/pion/dtls/v3 v3.0.6/go.mod h1:iJxNQ3Uhn1NZWOMWlLxEEHAN5yX7GyPvvKw04v9bzYU=
|
||||
github.com/pion/ice/v4 v4.0.10 h1:P59w1iauC/wPk9PdY8Vjl4fOFL5B+USq1+xbDcN6gT4=
|
||||
github.com/pion/ice/v4 v4.0.10/go.mod h1:y3M18aPhIxLlcO/4dn9X8LzLLSma84cx6emMSu14FGw=
|
||||
github.com/pion/interceptor v0.1.40 h1:e0BjnPcGpr2CFQgKhrQisBU7V3GXK6wrfYrGYaU6Jq4=
|
||||
github.com/pion/interceptor v0.1.40/go.mod h1:Z6kqH7M/FYirg3frjGJ21VLSRJGBXB/KqaTIrdqnOic=
|
||||
github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
|
||||
github.com/pion/logging v0.2.3 h1:gHuf0zpoh1GW67Nr6Gj4cv5Z9ZscU7g/EaoC/Ke/igI=
|
||||
github.com/pion/logging v0.2.3/go.mod h1:z8YfknkquMe1csOrxK5kc+5/ZPAzMxbKLX5aXpbpC90=
|
||||
@ -363,14 +388,14 @@ github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
|
||||
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
|
||||
github.com/pion/rtcp v1.2.15 h1:LZQi2JbdipLOj4eBjK4wlVoQWfrZbh3Q6eHtWtJBZBo=
|
||||
github.com/pion/rtcp v1.2.15/go.mod h1:jlGuAjHMEXwMUHK78RgX0UmEJFV4zUKOFHR7OP+D3D0=
|
||||
github.com/pion/rtp v1.8.11 h1:17xjnY5WO5hgO6SD3/NTIUPvSFw/PbLsIJyz1r1yNIk=
|
||||
github.com/pion/rtp v1.8.11/go.mod h1:8uMBJj32Pa1wwx8Fuv/AsFhn8jsgw+3rUC2PfoBZ8p4=
|
||||
github.com/pion/sctp v1.8.37 h1:ZDmGPtRPX9mKCiVXtMbTWybFw3z/hVKAZgU81wcOrqs=
|
||||
github.com/pion/sctp v1.8.37/go.mod h1:cNiLdchXra8fHQwmIoqw0MbLLMs+f7uQ+dGMG2gWebE=
|
||||
github.com/pion/sdp/v3 v3.0.10 h1:6MChLE/1xYB+CjumMw+gZ9ufp2DPApuVSnDT8t5MIgA=
|
||||
github.com/pion/sdp/v3 v3.0.10/go.mod h1:88GMahN5xnScv1hIMTqLdu/cOcUkj6a9ytbncwMCq2E=
|
||||
github.com/pion/srtp/v3 v3.0.4 h1:2Z6vDVxzrX3UHEgrUyIGM4rRouoC7v+NiF1IHtp9B5M=
|
||||
github.com/pion/srtp/v3 v3.0.4/go.mod h1:1Jx3FwDoxpRaTh1oRV8A/6G1BnFL+QI82eK4ms8EEJQ=
|
||||
github.com/pion/rtp v1.8.19 h1:jhdO/3XhL/aKm/wARFVmvTfq0lC/CvN1xwYKmduly3c=
|
||||
github.com/pion/rtp v1.8.19/go.mod h1:bAu2UFKScgzyFqvUKmbvzSdPr+NGbZtv6UB2hesqXBk=
|
||||
github.com/pion/sctp v1.8.39 h1:PJma40vRHa3UTO3C4MyeJDQ+KIobVYRZQZ0Nt7SjQnE=
|
||||
github.com/pion/sctp v1.8.39/go.mod h1:cNiLdchXra8fHQwmIoqw0MbLLMs+f7uQ+dGMG2gWebE=
|
||||
github.com/pion/sdp/v3 v3.0.13 h1:uN3SS2b+QDZnWXgdr69SM8KB4EbcnPnPf2Laxhty/l4=
|
||||
github.com/pion/sdp/v3 v3.0.13/go.mod h1:88GMahN5xnScv1hIMTqLdu/cOcUkj6a9ytbncwMCq2E=
|
||||
github.com/pion/srtp/v3 v3.0.6 h1:E2gyj1f5X10sB/qILUGIkL4C2CqK269Xq167PbGCc/4=
|
||||
github.com/pion/srtp/v3 v3.0.6/go.mod h1:BxvziG3v/armJHAaJ87euvkhHqWe9I7iiOy50K2QkhY=
|
||||
github.com/pion/stun v0.6.1 h1:8lp6YejULeHBF8NmV8e2787BogQhduZugh5PdhDyyN4=
|
||||
github.com/pion/stun v0.6.1/go.mod h1:/hO7APkX4hZKu/D0f2lHzNyvdkTGtIy3NDmLR7kSz/8=
|
||||
github.com/pion/stun/v3 v3.0.0 h1:4h1gwhWLWuZWOJIJR9s2ferRO+W3zA/b6ijOI6mKzUw=
|
||||
@ -381,24 +406,25 @@ github.com/pion/transport/v2 v2.2.10 h1:ucLBLE8nuxiHfvkFKnkDQRYWYfp8ejf4YBOPfaQp
|
||||
github.com/pion/transport/v2 v2.2.10/go.mod h1:sq1kSLWs+cHW9E+2fJP95QudkzbK7wscs8yYgQToO5E=
|
||||
github.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1o0=
|
||||
github.com/pion/transport/v3 v3.0.7/go.mod h1:YleKiTZ4vqNxVwh77Z0zytYi7rXHl7j6uPLGhhz9rwo=
|
||||
github.com/pion/turn/v4 v4.0.0 h1:qxplo3Rxa9Yg1xXDxxH8xaqcyGUtbHYw4QSCvmFWvhM=
|
||||
github.com/pion/turn/v4 v4.0.0/go.mod h1:MuPDkm15nYSklKpN8vWJ9W2M0PlyQZqYt1McGuxG7mA=
|
||||
github.com/pion/webrtc/v4 v4.0.10 h1:Hq/JLjhqLxi+NmCtE8lnRPDr8H4LcNvwg8OxVcdv56Q=
|
||||
github.com/pion/webrtc/v4 v4.0.10/go.mod h1:ViHLVaNpiuvaH8pdiuQxuA9awuE6KVzAXx3vVWilOck=
|
||||
github.com/pion/turn/v4 v4.0.2 h1:ZqgQ3+MjP32ug30xAbD6Mn+/K4Sxi3SdNOTFf+7mpps=
|
||||
github.com/pion/turn/v4 v4.0.2/go.mod h1:pMMKP/ieNAG/fN5cZiN4SDuyKsXtNTr0ccN7IToA1zs=
|
||||
github.com/pion/webrtc/v4 v4.1.2 h1:mpuUo/EJ1zMNKGE79fAdYNFZBX790KE7kQQpLMjjR54=
|
||||
github.com/pion/webrtc/v4 v4.1.2/go.mod h1:xsCXiNAmMEjIdFxAYU0MbB3RwRieJsegSB2JZsGN+8U=
|
||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v0.8.0/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
||||
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
||||
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
|
||||
github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU=
|
||||
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
|
||||
github.com/prometheus/client_golang v1.11.1/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0=
|
||||
github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q=
|
||||
github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0=
|
||||
github.com/prometheus/client_golang v1.23.0 h1:ust4zpdl9r4trLY/gSjlm07PuiBq2ynaXXlptpfy8Uc=
|
||||
github.com/prometheus/client_golang v1.23.0/go.mod h1:i/o0R9ByOnHX0McrTMTyhYvKE4haaf2mW08I+jGAjEE=
|
||||
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
@ -409,8 +435,8 @@ github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y8
|
||||
github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4=
|
||||
github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo=
|
||||
github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc=
|
||||
github.com/prometheus/common v0.63.0 h1:YR/EIY1o3mEFP/kZCD7iDMnLPlGyuU2Gb3HIcXnA98k=
|
||||
github.com/prometheus/common v0.63.0/go.mod h1:VVFF/fBIoToEnWRVkYoXEkq3R3paCoxG9PXP74SnV18=
|
||||
github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
|
||||
github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
|
||||
github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
||||
@ -432,12 +458,13 @@ github.com/redis/go-redis/v9 v9.8.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
|
||||
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rqlite/gorqlite v0.0.0-20250609141355-ac86a4a1c9a8 h1:BoxiqWvhprOB2isgM59s8wkgKwAoyQH66Twfmof41oE=
|
||||
github.com/rqlite/gorqlite v0.0.0-20250609141355-ac86a4a1c9a8/go.mod h1:xF/KoXmrRyahPfo5L7Szb5cAAUl53dMWBh9cMruGEZg=
|
||||
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I=
|
||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
|
||||
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
|
||||
@ -472,6 +499,10 @@ github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:Udh
|
||||
github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA=
|
||||
github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI=
|
||||
github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
|
||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
@ -484,8 +515,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=
|
||||
github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA=
|
||||
github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU=
|
||||
@ -511,18 +542,33 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA=
|
||||
go.uber.org/dig v1.18.0 h1:imUL1UiY0Mg4bqbFfsRQO5G4CGRBec/ZujWTvSVp3pw=
|
||||
go.uber.org/dig v1.18.0/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE=
|
||||
go.uber.org/fx v1.23.0 h1:lIr/gYWQGfTwGcSXWXu4vP5Ws6iqnNEIY+F/aFzCKTg=
|
||||
go.uber.org/fx v1.23.0/go.mod h1:o/D9n+2mLP6v1EG+qsdT1O8wKopYAsqZasju97SDFCU=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
|
||||
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
|
||||
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
|
||||
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
|
||||
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
|
||||
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
|
||||
go.uber.org/dig v1.19.0 h1:BACLhebsYdpQ7IROQ1AGPjrXcP5dF80U3gKoFzbaq/4=
|
||||
go.uber.org/dig v1.19.0/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE=
|
||||
go.uber.org/fx v1.24.0 h1:wE8mruvpg2kiiL1Vqd0CC+tr0/24XIB10Iwp2lLWzkg=
|
||||
go.uber.org/fx v1.24.0/go.mod h1:AmDeGyS+ZARGKM4tlH4FY2Jr63VjbEDJHtqXTGP5hbo=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
||||
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
|
||||
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
|
||||
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE=
|
||||
golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw=
|
||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
@ -538,8 +584,8 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y
|
||||
golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE=
|
||||
golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=
|
||||
golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
|
||||
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
|
||||
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
|
||||
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
|
||||
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20250718183923-645b1fa84792 h1:R9PFI6EUdfVKgwKjZef7QIwGcBKu86OEFpJ9nUEP2l4=
|
||||
golang.org/x/exp v0.0.0-20250718183923-645b1fa84792/go.mod h1:A+z0yzpGtvnG90cToK5n2tu8UJVP2XUATh+r+sfOOOc=
|
||||
@ -552,8 +598,8 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg=
|
||||
golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ=
|
||||
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
@ -577,8 +623,8 @@ golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI=
|
||||
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
|
||||
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
|
||||
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
|
||||
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
|
||||
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
@ -595,8 +641,8 @@ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20180810173357-98c5dad5d1a0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
@ -629,8 +675,10 @@ golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
|
||||
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc h1:bH6xUXay0AIFMElXG2rQ4uiE+7ncwtiOdPfYK1NK2XA=
|
||||
golang.org/x/telemetry v0.0.0-20251203150158-8fff8a5912fc/go.mod h1:hKdjCMrbv9skySur+Nek8Hd0uJ0GuxJIoIX2payrIdQ=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
@ -638,6 +686,8 @@ golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU=
|
||||
golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY=
|
||||
golang.org/x/term v0.39.0 h1:RclSuaJf32jOqZz74CkPA9qFuVTX7vhLlpfj/IGWlqY=
|
||||
golang.org/x/term v0.39.0/go.mod h1:yxzUCTP/U+FzoxfdKmLaA0RV1WgE0VY7hXBwKtY/4ww=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
@ -647,12 +697,12 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
|
||||
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
|
||||
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
|
||||
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
|
||||
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
|
||||
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20181030000716-a0a13e073c7b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
@ -665,12 +715,14 @@ golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roY
|
||||
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
|
||||
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
|
||||
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
|
||||
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/api v0.0.0-20180910000450-7ca32eb868bf/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0=
|
||||
google.golang.org/api v0.0.0-20181030000543-1d582fd0359e/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0=
|
||||
google.golang.org/api v0.1.0/go.mod h1:UGEZY7KEX120AnNLIHFMKIo4obdJhkp2tPbaPlQx13Y=
|
||||
@ -683,10 +735,14 @@ google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoA
|
||||
google.golang.org/genproto v0.0.0-20181029155118-b69ba1387ce2/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20181202183823-bd91e49a0898/go.mod h1:7Ep/1NZk928CDR8SjdVbjWNpdIf6nzjE3BTgJDr2Atg=
|
||||
google.golang.org/genproto v0.0.0-20190306203927-b5d61aea6440/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
|
||||
google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
|
||||
google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio=
|
||||
google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc=
|
||||
google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||
@ -694,8 +750,8 @@ google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miE
|
||||
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
|
||||
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
@ -719,5 +775,7 @@ honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWh
|
||||
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg=
|
||||
lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
|
||||
rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY=
|
||||
rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs=
|
||||
sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck=
|
||||
sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0=
|
||||
@ -1,4 +1,4 @@
|
||||
-- DeBros Gateway - Initial database schema (SQLite/RQLite dialect)
|
||||
-- Orama Gateway - Initial database schema (SQLite/RQLite dialect)
|
||||
-- This file scaffolds core tables used by the HTTP gateway for auth, observability, and namespacing.
|
||||
-- Apply via your migration tooling or manual execution in RQLite.
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
-- DeBros Gateway - Core schema (Phase 2)
|
||||
-- Orama Gateway - Core schema (Phase 2)
|
||||
-- Adds apps, nonces, subscriptions, refresh_tokens, audit_events, namespace_ownership
|
||||
-- SQLite/RQLite dialect
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
-- DeBros Gateway - Wallet to API Key linkage (Phase 3)
|
||||
-- Orama Gateway - Wallet to API Key linkage (Phase 3)
|
||||
-- Ensures one API key per (namespace, wallet) and enables lookup
|
||||
|
||||
BEGIN;
|
||||
77
core/migrations/005_dns_records.sql
Normal file
77
core/migrations/005_dns_records.sql
Normal file
@ -0,0 +1,77 @@
|
||||
-- Migration 005: DNS Records for CoreDNS Integration
|
||||
-- This migration creates tables for managing DNS records with RQLite backend for CoreDNS
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- DNS records table for dynamic DNS management
|
||||
CREATE TABLE IF NOT EXISTS dns_records (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
fqdn TEXT NOT NULL UNIQUE, -- Fully qualified domain name (e.g., myapp.node-7prvNa.orama.network)
|
||||
record_type TEXT NOT NULL DEFAULT 'A', -- DNS record type: A, AAAA, CNAME, TXT
|
||||
value TEXT NOT NULL, -- IP address or target value
|
||||
ttl INTEGER NOT NULL DEFAULT 300, -- Time to live in seconds
|
||||
namespace TEXT NOT NULL, -- Namespace that owns this record
|
||||
deployment_id TEXT, -- Optional: deployment that created this record
|
||||
node_id TEXT, -- Optional: specific node ID for node-specific routing
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,-- Enable/disable without deleting
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
created_by TEXT NOT NULL -- Wallet address or 'system' for auto-created records
|
||||
);
|
||||
|
||||
-- Indexes for fast DNS lookups
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_records_fqdn ON dns_records(fqdn);
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_records_namespace ON dns_records(namespace);
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_records_deployment ON dns_records(deployment_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_records_node_id ON dns_records(node_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_records_active ON dns_records(is_active);
|
||||
|
||||
-- DNS nodes registry for tracking active nodes
|
||||
CREATE TABLE IF NOT EXISTS dns_nodes (
|
||||
id TEXT PRIMARY KEY, -- Node ID (e.g., node-7prvNa)
|
||||
ip_address TEXT NOT NULL, -- Public IP address
|
||||
internal_ip TEXT, -- Private IP for cluster communication
|
||||
region TEXT, -- Geographic region
|
||||
status TEXT NOT NULL DEFAULT 'active', -- active, draining, offline
|
||||
last_seen TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
capabilities TEXT, -- JSON: ["wasm", "ipfs", "cache"]
|
||||
metadata TEXT, -- JSON: additional node info
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Indexes for node health monitoring
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_nodes_status ON dns_nodes(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_nodes_last_seen ON dns_nodes(last_seen);
|
||||
|
||||
-- Reserved domains table to prevent subdomain collisions
|
||||
CREATE TABLE IF NOT EXISTS reserved_domains (
|
||||
domain TEXT PRIMARY KEY,
|
||||
reason TEXT NOT NULL,
|
||||
reserved_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Seed reserved domains
|
||||
INSERT INTO reserved_domains (domain, reason) VALUES
|
||||
('api.orama.network', 'API gateway endpoint'),
|
||||
('www.orama.network', 'Marketing website'),
|
||||
('admin.orama.network', 'Admin panel'),
|
||||
('ns1.orama.network', 'Nameserver 1'),
|
||||
('ns2.orama.network', 'Nameserver 2'),
|
||||
('ns3.orama.network', 'Nameserver 3'),
|
||||
('ns4.orama.network', 'Nameserver 4'),
|
||||
('mail.orama.network', 'Email service'),
|
||||
('cdn.orama.network', 'Content delivery'),
|
||||
('docs.orama.network', 'Documentation'),
|
||||
('status.orama.network', 'Status page')
|
||||
ON CONFLICT(domain) DO NOTHING;
|
||||
|
||||
-- Mark migration as applied
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version INTEGER PRIMARY KEY,
|
||||
applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT OR IGNORE INTO schema_migrations(version) VALUES (5);
|
||||
|
||||
COMMIT;
|
||||
74
core/migrations/006_namespace_sqlite.sql
Normal file
74
core/migrations/006_namespace_sqlite.sql
Normal file
@ -0,0 +1,74 @@
|
||||
-- Migration 006: Per-Namespace SQLite Databases
|
||||
-- This migration creates infrastructure for isolated SQLite databases per namespace
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- Namespace SQLite databases registry
|
||||
CREATE TABLE IF NOT EXISTS namespace_sqlite_databases (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
namespace TEXT NOT NULL, -- Namespace that owns this database
|
||||
database_name TEXT NOT NULL, -- Database name (unique per namespace)
|
||||
home_node_id TEXT NOT NULL, -- Node ID where database file resides
|
||||
file_path TEXT NOT NULL, -- Absolute path on home node
|
||||
size_bytes BIGINT DEFAULT 0, -- Current database size
|
||||
backup_cid TEXT, -- Latest backup CID in IPFS
|
||||
last_backup_at TIMESTAMP, -- Last backup timestamp
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
created_by TEXT NOT NULL, -- Wallet address that created the database
|
||||
|
||||
UNIQUE(namespace, database_name)
|
||||
);
|
||||
|
||||
-- Indexes for database lookups
|
||||
CREATE INDEX IF NOT EXISTS idx_sqlite_databases_namespace ON namespace_sqlite_databases(namespace);
|
||||
CREATE INDEX IF NOT EXISTS idx_sqlite_databases_home_node ON namespace_sqlite_databases(home_node_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_sqlite_databases_name ON namespace_sqlite_databases(namespace, database_name);
|
||||
|
||||
-- SQLite database backups history
|
||||
CREATE TABLE IF NOT EXISTS namespace_sqlite_backups (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
database_id TEXT NOT NULL, -- References namespace_sqlite_databases.id
|
||||
backup_cid TEXT NOT NULL, -- IPFS CID of backup file
|
||||
size_bytes BIGINT NOT NULL, -- Backup file size
|
||||
backup_type TEXT NOT NULL, -- 'manual', 'scheduled', 'migration'
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
created_by TEXT NOT NULL,
|
||||
|
||||
FOREIGN KEY (database_id) REFERENCES namespace_sqlite_databases(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Index for backup history queries
|
||||
CREATE INDEX IF NOT EXISTS idx_sqlite_backups_database ON namespace_sqlite_backups(database_id, created_at DESC);
|
||||
|
||||
-- Namespace quotas for resource management (future use)
|
||||
CREATE TABLE IF NOT EXISTS namespace_quotas (
|
||||
namespace TEXT PRIMARY KEY,
|
||||
|
||||
-- Storage quotas
|
||||
max_sqlite_databases INTEGER DEFAULT 10, -- Max SQLite databases per namespace
|
||||
max_storage_bytes BIGINT DEFAULT 5368709120, -- 5GB default
|
||||
max_ipfs_pins INTEGER DEFAULT 1000, -- Max pinned IPFS objects
|
||||
|
||||
-- Compute quotas
|
||||
max_deployments INTEGER DEFAULT 20, -- Max concurrent deployments
|
||||
max_cpu_percent INTEGER DEFAULT 200, -- Total CPU quota (2 cores)
|
||||
max_memory_mb INTEGER DEFAULT 2048, -- Total memory quota
|
||||
|
||||
-- Rate limits
|
||||
max_rqlite_queries_per_minute INTEGER DEFAULT 1000,
|
||||
max_olric_ops_per_minute INTEGER DEFAULT 10000,
|
||||
|
||||
-- Current usage (updated periodically)
|
||||
current_storage_bytes BIGINT DEFAULT 0,
|
||||
current_deployments INTEGER DEFAULT 0,
|
||||
current_sqlite_databases INTEGER DEFAULT 0,
|
||||
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Mark migration as applied
|
||||
INSERT OR IGNORE INTO schema_migrations(version) VALUES (6);
|
||||
|
||||
COMMIT;
|
||||
178
core/migrations/007_deployments.sql
Normal file
178
core/migrations/007_deployments.sql
Normal file
@ -0,0 +1,178 @@
|
||||
-- Migration 007: Deployments System
|
||||
-- This migration creates the complete schema for managing custom deployments
|
||||
-- (Static sites, Next.js, Go backends, Node.js backends)
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- Main deployments table
|
||||
CREATE TABLE IF NOT EXISTS deployments (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
namespace TEXT NOT NULL, -- Owner namespace
|
||||
name TEXT NOT NULL, -- Deployment name (unique per namespace)
|
||||
type TEXT NOT NULL, -- 'static', 'nextjs', 'nextjs-static', 'go-backend', 'go-wasm', 'nodejs-backend'
|
||||
version INTEGER NOT NULL DEFAULT 1, -- Monotonic version counter
|
||||
status TEXT NOT NULL DEFAULT 'deploying', -- 'deploying', 'active', 'failed', 'stopped', 'updating'
|
||||
|
||||
-- Content storage
|
||||
content_cid TEXT, -- IPFS CID for static content or built assets
|
||||
build_cid TEXT, -- IPFS CID for build artifacts (Next.js SSR, binaries)
|
||||
|
||||
-- Runtime configuration
|
||||
home_node_id TEXT, -- Node ID hosting stateful data/processes
|
||||
port INTEGER, -- Allocated port (NULL for static/WASM)
|
||||
subdomain TEXT, -- Custom subdomain (e.g., myapp)
|
||||
environment TEXT, -- JSON: {"KEY": "value", ...}
|
||||
|
||||
-- Resource limits
|
||||
memory_limit_mb INTEGER DEFAULT 256,
|
||||
cpu_limit_percent INTEGER DEFAULT 50,
|
||||
disk_limit_mb INTEGER DEFAULT 1024,
|
||||
|
||||
-- Health & monitoring
|
||||
health_check_path TEXT DEFAULT '/health', -- HTTP path for health checks
|
||||
health_check_interval INTEGER DEFAULT 30, -- Seconds between health checks
|
||||
restart_policy TEXT DEFAULT 'always', -- 'always', 'on-failure', 'never'
|
||||
max_restart_count INTEGER DEFAULT 10, -- Max restarts before marking as failed
|
||||
|
||||
-- Metadata
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
deployed_by TEXT NOT NULL, -- Wallet address or API key
|
||||
|
||||
UNIQUE(namespace, name)
|
||||
);
|
||||
|
||||
-- Indexes for deployment lookups
|
||||
CREATE INDEX IF NOT EXISTS idx_deployments_namespace ON deployments(namespace);
|
||||
CREATE INDEX IF NOT EXISTS idx_deployments_status ON deployments(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_deployments_home_node ON deployments(home_node_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_deployments_type ON deployments(type);
|
||||
CREATE INDEX IF NOT EXISTS idx_deployments_subdomain ON deployments(subdomain);
|
||||
|
||||
-- Port allocations table (prevents port conflicts)
|
||||
CREATE TABLE IF NOT EXISTS port_allocations (
|
||||
node_id TEXT NOT NULL,
|
||||
port INTEGER NOT NULL,
|
||||
deployment_id TEXT NOT NULL,
|
||||
allocated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
PRIMARY KEY (node_id, port),
|
||||
FOREIGN KEY (deployment_id) REFERENCES deployments(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Index for finding allocated ports by node
|
||||
CREATE INDEX IF NOT EXISTS idx_port_allocations_node ON port_allocations(node_id, port);
|
||||
CREATE INDEX IF NOT EXISTS idx_port_allocations_deployment ON port_allocations(deployment_id);
|
||||
|
||||
-- Home node assignments (namespace → node mapping)
|
||||
CREATE TABLE IF NOT EXISTS home_node_assignments (
|
||||
namespace TEXT PRIMARY KEY,
|
||||
home_node_id TEXT NOT NULL,
|
||||
assigned_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
last_heartbeat TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
deployment_count INTEGER DEFAULT 0, -- Cached count for capacity planning
|
||||
total_memory_mb INTEGER DEFAULT 0, -- Cached total memory usage
|
||||
total_cpu_percent INTEGER DEFAULT 0 -- Cached total CPU usage
|
||||
);
|
||||
|
||||
-- Index for querying by node
|
||||
CREATE INDEX IF NOT EXISTS idx_home_node_by_node ON home_node_assignments(home_node_id);
|
||||
|
||||
-- Deployment domains (custom domain mapping)
|
||||
CREATE TABLE IF NOT EXISTS deployment_domains (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
deployment_id TEXT NOT NULL,
|
||||
namespace TEXT NOT NULL,
|
||||
domain TEXT NOT NULL UNIQUE, -- Full domain (e.g., myapp.orama.network or custom)
|
||||
routing_type TEXT NOT NULL DEFAULT 'balanced', -- 'balanced' or 'node_specific'
|
||||
node_id TEXT, -- For node_specific routing
|
||||
is_custom BOOLEAN DEFAULT FALSE, -- True for user's own domain
|
||||
tls_cert_cid TEXT, -- IPFS CID for custom TLS certificate
|
||||
verified_at TIMESTAMP, -- When custom domain was verified
|
||||
verification_token TEXT, -- TXT record token for domain verification
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
FOREIGN KEY (deployment_id) REFERENCES deployments(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Indexes for domain lookups
|
||||
CREATE INDEX IF NOT EXISTS idx_deployment_domains_deployment ON deployment_domains(deployment_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_deployment_domains_domain ON deployment_domains(domain);
|
||||
CREATE INDEX IF NOT EXISTS idx_deployment_domains_namespace ON deployment_domains(namespace);
|
||||
|
||||
-- Deployment history (version tracking and rollback)
|
||||
CREATE TABLE IF NOT EXISTS deployment_history (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
deployment_id TEXT NOT NULL,
|
||||
version INTEGER NOT NULL,
|
||||
content_cid TEXT,
|
||||
build_cid TEXT,
|
||||
deployed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
deployed_by TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'success', -- 'success', 'failed', 'rolled_back'
|
||||
error_message TEXT,
|
||||
rollback_from_version INTEGER, -- If this is a rollback, original version
|
||||
|
||||
FOREIGN KEY (deployment_id) REFERENCES deployments(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Indexes for history queries
|
||||
CREATE INDEX IF NOT EXISTS idx_deployment_history_deployment ON deployment_history(deployment_id, version DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_deployment_history_status ON deployment_history(status);
|
||||
|
||||
-- Deployment environment variables (separate for security)
|
||||
CREATE TABLE IF NOT EXISTS deployment_env_vars (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
deployment_id TEXT NOT NULL,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT NOT NULL, -- Encrypted in production
|
||||
is_secret BOOLEAN DEFAULT FALSE, -- True for sensitive values
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
UNIQUE(deployment_id, key),
|
||||
FOREIGN KEY (deployment_id) REFERENCES deployments(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Index for env var lookups
|
||||
CREATE INDEX IF NOT EXISTS idx_deployment_env_vars_deployment ON deployment_env_vars(deployment_id);
|
||||
|
||||
-- Deployment events log (audit trail)
|
||||
CREATE TABLE IF NOT EXISTS deployment_events (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
deployment_id TEXT NOT NULL,
|
||||
event_type TEXT NOT NULL, -- 'created', 'started', 'stopped', 'restarted', 'updated', 'deleted', 'health_check_failed'
|
||||
message TEXT,
|
||||
metadata TEXT, -- JSON: additional context
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
created_by TEXT, -- Wallet address or 'system'
|
||||
|
||||
FOREIGN KEY (deployment_id) REFERENCES deployments(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Index for event queries
|
||||
CREATE INDEX IF NOT EXISTS idx_deployment_events_deployment ON deployment_events(deployment_id, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_deployment_events_type ON deployment_events(event_type);
|
||||
|
||||
-- Process health checks (for dynamic deployments)
|
||||
CREATE TABLE IF NOT EXISTS deployment_health_checks (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
deployment_id TEXT NOT NULL,
|
||||
node_id TEXT NOT NULL,
|
||||
status TEXT NOT NULL, -- 'healthy', 'unhealthy', 'unknown'
|
||||
response_time_ms INTEGER,
|
||||
status_code INTEGER,
|
||||
error_message TEXT,
|
||||
checked_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
FOREIGN KEY (deployment_id) REFERENCES deployments(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Index for health check queries (keep only recent checks)
|
||||
CREATE INDEX IF NOT EXISTS idx_health_checks_deployment ON deployment_health_checks(deployment_id, checked_at DESC);
|
||||
|
||||
-- Mark migration as applied
|
||||
INSERT OR IGNORE INTO schema_migrations(version) VALUES (7);
|
||||
|
||||
COMMIT;
|
||||
31
core/migrations/008_ipfs_namespace_tracking.sql
Normal file
31
core/migrations/008_ipfs_namespace_tracking.sql
Normal file
@ -0,0 +1,31 @@
|
||||
-- Migration 008: IPFS Namespace Tracking
|
||||
-- This migration adds namespace isolation for IPFS content by tracking CID ownership.
|
||||
|
||||
-- Table: ipfs_content_ownership
|
||||
-- Tracks which namespace owns each CID uploaded to IPFS.
|
||||
-- This enables namespace isolation so that:
|
||||
-- - Namespace-A cannot GET/PIN/UNPIN Namespace-B's content
|
||||
-- - Same CID can be uploaded by different namespaces (shared content)
|
||||
CREATE TABLE IF NOT EXISTS ipfs_content_ownership (
|
||||
id TEXT PRIMARY KEY,
|
||||
cid TEXT NOT NULL,
|
||||
namespace TEXT NOT NULL,
|
||||
name TEXT,
|
||||
size_bytes BIGINT DEFAULT 0,
|
||||
is_pinned BOOLEAN DEFAULT FALSE,
|
||||
uploaded_at TIMESTAMP NOT NULL,
|
||||
uploaded_by TEXT NOT NULL,
|
||||
UNIQUE(cid, namespace)
|
||||
);
|
||||
|
||||
-- Index for fast namespace + CID lookup
|
||||
CREATE INDEX IF NOT EXISTS idx_ipfs_ownership_namespace_cid
|
||||
ON ipfs_content_ownership(namespace, cid);
|
||||
|
||||
-- Index for fast CID lookup across all namespaces
|
||||
CREATE INDEX IF NOT EXISTS idx_ipfs_ownership_cid
|
||||
ON ipfs_content_ownership(cid);
|
||||
|
||||
-- Index for namespace-only queries (list all content for a namespace)
|
||||
CREATE INDEX IF NOT EXISTS idx_ipfs_ownership_namespace
|
||||
ON ipfs_content_ownership(namespace);
|
||||
45
core/migrations/009_dns_records_multi.sql
Normal file
45
core/migrations/009_dns_records_multi.sql
Normal file
@ -0,0 +1,45 @@
|
||||
-- Migration 009: Update DNS Records to Support Multiple Records per FQDN
|
||||
-- This allows round-robin A records and multiple NS records for the same domain
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- SQLite doesn't support DROP CONSTRAINT, so we recreate the table
|
||||
-- First, create the new table structure
|
||||
CREATE TABLE IF NOT EXISTS dns_records_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
fqdn TEXT NOT NULL, -- Fully qualified domain name (e.g., myapp.node-7prvNa.orama.network)
|
||||
record_type TEXT NOT NULL DEFAULT 'A',-- DNS record type: A, AAAA, CNAME, TXT, NS, SOA
|
||||
value TEXT NOT NULL, -- IP address or target value
|
||||
ttl INTEGER NOT NULL DEFAULT 300, -- Time to live in seconds
|
||||
priority INTEGER DEFAULT 0, -- Priority for MX/SRV records, or weight for round-robin
|
||||
namespace TEXT NOT NULL DEFAULT 'system', -- Namespace that owns this record
|
||||
deployment_id TEXT, -- Optional: deployment that created this record
|
||||
node_id TEXT, -- Optional: specific node ID for node-specific routing
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,-- Enable/disable without deleting
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
created_by TEXT NOT NULL DEFAULT 'system', -- Wallet address or 'system' for auto-created records
|
||||
UNIQUE(fqdn, record_type, value) -- Allow multiple records of same type for same FQDN, but not duplicates
|
||||
);
|
||||
|
||||
-- Copy existing data if the old table exists
|
||||
INSERT OR IGNORE INTO dns_records_new (id, fqdn, record_type, value, ttl, namespace, deployment_id, node_id, is_active, created_at, updated_at, created_by)
|
||||
SELECT id, fqdn, record_type, value, ttl, namespace, deployment_id, node_id, is_active, created_at, updated_at, created_by
|
||||
FROM dns_records WHERE 1=1;
|
||||
|
||||
-- Drop old table and rename new one
|
||||
DROP TABLE IF EXISTS dns_records;
|
||||
ALTER TABLE dns_records_new RENAME TO dns_records;
|
||||
|
||||
-- Recreate indexes
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_records_fqdn ON dns_records(fqdn);
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_records_fqdn_type ON dns_records(fqdn, record_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_records_namespace ON dns_records(namespace);
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_records_deployment ON dns_records(deployment_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_records_node_id ON dns_records(node_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_dns_records_active ON dns_records(is_active);
|
||||
|
||||
-- Mark migration as applied
|
||||
INSERT OR IGNORE INTO schema_migrations(version) VALUES (9);
|
||||
|
||||
COMMIT;
|
||||
190
core/migrations/010_namespace_clusters.sql
Normal file
190
core/migrations/010_namespace_clusters.sql
Normal file
@ -0,0 +1,190 @@
|
||||
-- Migration 010: Namespace Clusters for Physical Isolation
|
||||
-- Creates tables to manage per-namespace RQLite and Olric clusters
|
||||
-- Each namespace gets its own 3-node cluster for complete isolation
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- Extend namespaces table with cluster status tracking
|
||||
-- Note: SQLite doesn't support ADD COLUMN IF NOT EXISTS, so we handle this carefully
|
||||
-- These columns track the provisioning state of the namespace's dedicated cluster
|
||||
|
||||
-- First check if columns exist, if not add them
|
||||
-- cluster_status: 'none', 'provisioning', 'ready', 'degraded', 'failed', 'deprovisioning'
|
||||
|
||||
-- Create a new namespaces table with additional columns if needed
|
||||
CREATE TABLE IF NOT EXISTS namespaces_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
cluster_status TEXT DEFAULT 'none',
|
||||
cluster_created_at TIMESTAMP,
|
||||
cluster_ready_at TIMESTAMP
|
||||
);
|
||||
|
||||
-- Copy data from old table if it exists and new columns don't
|
||||
INSERT OR IGNORE INTO namespaces_new (id, name, created_at, cluster_status)
|
||||
SELECT id, name, created_at, 'none' FROM namespaces WHERE NOT EXISTS (
|
||||
SELECT 1 FROM pragma_table_info('namespaces') WHERE name = 'cluster_status'
|
||||
);
|
||||
|
||||
-- If the column already exists, this migration was partially applied - skip the table swap
|
||||
-- We'll use a different approach: just ensure the new tables exist
|
||||
|
||||
-- Namespace clusters registry
|
||||
-- One record per namespace that has a dedicated cluster
|
||||
CREATE TABLE IF NOT EXISTS namespace_clusters (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
namespace_id INTEGER NOT NULL UNIQUE, -- FK to namespaces
|
||||
namespace_name TEXT NOT NULL, -- Cached for easier lookups
|
||||
status TEXT NOT NULL DEFAULT 'provisioning', -- provisioning, ready, degraded, failed, deprovisioning
|
||||
|
||||
-- Cluster configuration
|
||||
rqlite_node_count INTEGER NOT NULL DEFAULT 3,
|
||||
olric_node_count INTEGER NOT NULL DEFAULT 3,
|
||||
gateway_node_count INTEGER NOT NULL DEFAULT 3,
|
||||
|
||||
-- Provisioning metadata
|
||||
provisioned_by TEXT NOT NULL, -- Wallet address that triggered provisioning
|
||||
provisioned_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
ready_at TIMESTAMP,
|
||||
last_health_check TIMESTAMP,
|
||||
|
||||
-- Error tracking
|
||||
error_message TEXT,
|
||||
retry_count INTEGER DEFAULT 0,
|
||||
|
||||
FOREIGN KEY (namespace_id) REFERENCES namespaces(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_namespace_clusters_status ON namespace_clusters(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_namespace_clusters_namespace ON namespace_clusters(namespace_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_namespace_clusters_name ON namespace_clusters(namespace_name);
|
||||
|
||||
-- Namespace cluster nodes
|
||||
-- Tracks which physical nodes host services for each namespace cluster
|
||||
CREATE TABLE IF NOT EXISTS namespace_cluster_nodes (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
namespace_cluster_id TEXT NOT NULL, -- FK to namespace_clusters
|
||||
node_id TEXT NOT NULL, -- FK to dns_nodes (physical node)
|
||||
|
||||
-- Role in the cluster
|
||||
-- Each node can have multiple roles (rqlite + olric + gateway)
|
||||
role TEXT NOT NULL, -- 'rqlite_leader', 'rqlite_follower', 'olric', 'gateway'
|
||||
|
||||
-- Service ports (allocated from reserved range 10000-10099)
|
||||
rqlite_http_port INTEGER, -- Port for RQLite HTTP API
|
||||
rqlite_raft_port INTEGER, -- Port for RQLite Raft consensus
|
||||
olric_http_port INTEGER, -- Port for Olric HTTP API
|
||||
olric_memberlist_port INTEGER, -- Port for Olric memberlist gossip
|
||||
gateway_http_port INTEGER, -- Port for Gateway HTTP
|
||||
|
||||
-- Service status
|
||||
status TEXT NOT NULL DEFAULT 'pending', -- pending, starting, running, stopped, failed
|
||||
process_pid INTEGER, -- PID of running process (for local management)
|
||||
last_heartbeat TIMESTAMP,
|
||||
error_message TEXT,
|
||||
|
||||
-- Join addresses for cluster formation
|
||||
rqlite_join_address TEXT, -- Address to join RQLite cluster
|
||||
olric_peers TEXT, -- JSON array of Olric peer addresses
|
||||
|
||||
-- Metadata
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
UNIQUE(namespace_cluster_id, node_id, role),
|
||||
FOREIGN KEY (namespace_cluster_id) REFERENCES namespace_clusters(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_cluster_nodes_cluster ON namespace_cluster_nodes(namespace_cluster_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_cluster_nodes_node ON namespace_cluster_nodes(node_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_cluster_nodes_status ON namespace_cluster_nodes(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_cluster_nodes_role ON namespace_cluster_nodes(role);
|
||||
|
||||
-- Namespace port allocations
|
||||
-- Manages the reserved port range (10000-10099) for namespace services
|
||||
-- Each namespace instance on a node gets a block of 5 consecutive ports
|
||||
CREATE TABLE IF NOT EXISTS namespace_port_allocations (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
node_id TEXT NOT NULL, -- Physical node ID
|
||||
namespace_cluster_id TEXT NOT NULL, -- Namespace cluster this allocation belongs to
|
||||
|
||||
-- Port block (5 consecutive ports)
|
||||
port_start INTEGER NOT NULL, -- Start of port block (e.g., 10000)
|
||||
port_end INTEGER NOT NULL, -- End of port block (e.g., 10004)
|
||||
|
||||
-- Individual port assignments within the block
|
||||
rqlite_http_port INTEGER NOT NULL, -- port_start + 0
|
||||
rqlite_raft_port INTEGER NOT NULL, -- port_start + 1
|
||||
olric_http_port INTEGER NOT NULL, -- port_start + 2
|
||||
olric_memberlist_port INTEGER NOT NULL, -- port_start + 3
|
||||
gateway_http_port INTEGER NOT NULL, -- port_start + 4
|
||||
|
||||
allocated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
-- Prevent overlapping allocations on same node
|
||||
UNIQUE(node_id, port_start),
|
||||
-- One allocation per namespace per node
|
||||
UNIQUE(namespace_cluster_id, node_id),
|
||||
FOREIGN KEY (namespace_cluster_id) REFERENCES namespace_clusters(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_ns_port_alloc_node ON namespace_port_allocations(node_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_ns_port_alloc_cluster ON namespace_port_allocations(namespace_cluster_id);
|
||||
|
||||
-- Namespace cluster events
|
||||
-- Audit log for cluster provisioning and lifecycle events
|
||||
CREATE TABLE IF NOT EXISTS namespace_cluster_events (
|
||||
id TEXT PRIMARY KEY, -- UUID
|
||||
namespace_cluster_id TEXT NOT NULL,
|
||||
event_type TEXT NOT NULL, -- Event types listed below
|
||||
node_id TEXT, -- Optional: specific node this event relates to
|
||||
message TEXT,
|
||||
metadata TEXT, -- JSON for additional event data
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
FOREIGN KEY (namespace_cluster_id) REFERENCES namespace_clusters(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Event types:
|
||||
-- 'provisioning_started' - Cluster provisioning began
|
||||
-- 'nodes_selected' - 3 nodes were selected for the cluster
|
||||
-- 'ports_allocated' - Ports allocated on a node
|
||||
-- 'rqlite_started' - RQLite instance started on a node
|
||||
-- 'rqlite_joined' - RQLite instance joined the cluster
|
||||
-- 'rqlite_leader_elected' - RQLite leader election completed
|
||||
-- 'olric_started' - Olric instance started on a node
|
||||
-- 'olric_joined' - Olric instance joined memberlist
|
||||
-- 'gateway_started' - Gateway instance started on a node
|
||||
-- 'dns_created' - DNS records created for namespace
|
||||
-- 'cluster_ready' - All services ready, cluster is operational
|
||||
-- 'cluster_degraded' - One or more nodes are unhealthy
|
||||
-- 'cluster_failed' - Cluster failed to provision or operate
|
||||
-- 'node_failed' - Specific node became unhealthy
|
||||
-- 'node_recovered' - Node recovered from failure
|
||||
-- 'deprovisioning_started' - Cluster deprovisioning began
|
||||
-- 'deprovisioned' - Cluster fully deprovisioned
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_cluster_events_cluster ON namespace_cluster_events(namespace_cluster_id, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_cluster_events_type ON namespace_cluster_events(event_type);
|
||||
|
||||
-- Global deployment registry
|
||||
-- Prevents duplicate deployment subdomains across all namespaces
|
||||
-- Since deployments now use {name}-{random}.{domain}, we track used subdomains globally
|
||||
CREATE TABLE IF NOT EXISTS global_deployment_subdomains (
|
||||
subdomain TEXT PRIMARY KEY, -- Full subdomain (e.g., 'myapp-f3o4if')
|
||||
namespace TEXT NOT NULL, -- Owner namespace
|
||||
deployment_id TEXT NOT NULL, -- FK to deployments (in namespace cluster)
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
-- No FK to deployments since deployments are in namespace-specific clusters
|
||||
UNIQUE(subdomain)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_global_subdomains_namespace ON global_deployment_subdomains(namespace);
|
||||
CREATE INDEX IF NOT EXISTS idx_global_subdomains_deployment ON global_deployment_subdomains(deployment_id);
|
||||
|
||||
-- Mark migration as applied
|
||||
INSERT OR IGNORE INTO schema_migrations(version) VALUES (10);
|
||||
|
||||
COMMIT;
|
||||
19
core/migrations/011_dns_nameservers.sql
Normal file
19
core/migrations/011_dns_nameservers.sql
Normal file
@ -0,0 +1,19 @@
|
||||
-- Migration 011: DNS Nameservers Table
|
||||
-- Maps NS hostnames (ns1, ns2, ns3) to specific node IDs and IPs
|
||||
-- Provides stable NS assignment that survives restarts and re-seeding
|
||||
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS dns_nameservers (
|
||||
hostname TEXT PRIMARY KEY, -- e.g., "ns1", "ns2", "ns3"
|
||||
node_id TEXT NOT NULL, -- Peer ID of the assigned node
|
||||
ip_address TEXT NOT NULL, -- IP address of the assigned node
|
||||
domain TEXT NOT NULL, -- Base domain (e.g., "dbrs.space")
|
||||
assigned_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(node_id, domain) -- A node can only hold one NS slot per domain
|
||||
);
|
||||
|
||||
INSERT OR IGNORE INTO schema_migrations(version) VALUES (11);
|
||||
|
||||
COMMIT;
|
||||
15
core/migrations/012_deployment_replicas.sql
Normal file
15
core/migrations/012_deployment_replicas.sql
Normal file
@ -0,0 +1,15 @@
|
||||
-- Deployment replicas: tracks which nodes host replicas of each deployment
|
||||
CREATE TABLE IF NOT EXISTS deployment_replicas (
|
||||
deployment_id TEXT NOT NULL,
|
||||
node_id TEXT NOT NULL,
|
||||
port INTEGER DEFAULT 0,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
is_primary BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (deployment_id, node_id),
|
||||
FOREIGN KEY (deployment_id) REFERENCES deployments(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_deployment_replicas_node ON deployment_replicas(node_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_deployment_replicas_status ON deployment_replicas(deployment_id, status);
|
||||
9
core/migrations/013_wireguard_peers.sql
Normal file
9
core/migrations/013_wireguard_peers.sql
Normal file
@ -0,0 +1,9 @@
|
||||
-- WireGuard mesh peer tracking
|
||||
CREATE TABLE IF NOT EXISTS wireguard_peers (
|
||||
node_id TEXT PRIMARY KEY,
|
||||
wg_ip TEXT NOT NULL UNIQUE,
|
||||
public_key TEXT NOT NULL UNIQUE,
|
||||
public_ip TEXT NOT NULL,
|
||||
wg_port INTEGER DEFAULT 51820,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
8
core/migrations/014_invite_tokens.sql
Normal file
8
core/migrations/014_invite_tokens.sql
Normal file
@ -0,0 +1,8 @@
|
||||
CREATE TABLE IF NOT EXISTS invite_tokens (
|
||||
token TEXT PRIMARY KEY,
|
||||
created_by TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at DATETIME NOT NULL,
|
||||
used_at DATETIME,
|
||||
used_by_ip TEXT
|
||||
);
|
||||
3
core/migrations/015_ipfs_peer_ids.sql
Normal file
3
core/migrations/015_ipfs_peer_ids.sql
Normal file
@ -0,0 +1,3 @@
|
||||
-- Store IPFS peer IDs alongside WireGuard peers for automatic swarm discovery
|
||||
-- Each node registers its IPFS peer ID so other nodes can connect via ipfs swarm connect
|
||||
ALTER TABLE wireguard_peers ADD COLUMN ipfs_peer_id TEXT DEFAULT '';
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user