feat(feeds): add opt-in Gecko relay and folder shortcuts
Document engine redistribution requirements; exclude upstream engine assets and keep the viewer disabled by default.
This commit is contained in:
1 parent
b23e63d4c6
commit
5321d613b4
37 files changed
+2051
-29
No files matched your search
@@ -0,0 +1,22 @@
|
||||
PagesWiki Gecko relay
|
||||
|
||||
This image contains the PagesWiki TCP relay, not Firefox/Gecko, gecko.js,
|
||||
gecko.wasm.zst, Mozilla runtime assets or browser fonts.
|
||||
|
||||
Third-party code linked into the relay binary:
|
||||
- Go standard library and runtime, Copyright The Go Authors.
|
||||
BSD-3-Clause; full license: /licenses/Go.txt
|
||||
Source and release archives: https://go.dev/dl/
|
||||
- golang.org/x/net v0.35.0 (WebSocket transport), Copyright The Go Authors.
|
||||
BSD-3-Clause; full license: /licenses/golang-x-net.txt
|
||||
Source: https://go.googlesource.com/net/+/refs/tags/v0.35.0/
|
||||
|
||||
The licenses are copied from the exact toolchain/module used at build time.
|
||||
The scratch runtime image does not contain Alpine, BusyBox or apk.
|
||||
The PagesWiki integration source and engine redistribution assessment are in:
|
||||
https://git.anya.jp/anya/pages
|
||||
docs/operations/gecko-redistribution.md
|
||||
|
||||
Mounting and serving an independently obtained browser engine requires a
|
||||
separate assessment and delivery of its applicable notices and source offer.
|
||||
This relay notice is not a license grant for that engine.
|
||||
@@ -0,0 +1,137 @@
|
||||
// Package geckorelay provides a bounded TCP-only Wisp transport for Gecko.
|
||||
// It is not a public general-purpose proxy: the PagesWiki frontend authenticates
|
||||
// the user and signs each backend request, and every destination is checked here.
|
||||
package geckorelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const GrantHeader = "X-PagesWiki-Gecko-Grant"
|
||||
|
||||
type Grant struct {
|
||||
Subject string `json:"subject"`
|
||||
Nonce string `json:"nonce"`
|
||||
Expires int64 `json:"expires"`
|
||||
}
|
||||
|
||||
func Sign(key string, grant Grant) string {
|
||||
data, _ := json.Marshal(grant)
|
||||
body := base64.RawURLEncoding.EncodeToString(data)
|
||||
h := hmac.New(sha256.New, []byte(key))
|
||||
h.Write([]byte(body))
|
||||
return body + "." + base64.RawURLEncoding.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
func Verify(key, token string, now time.Time) (Grant, error) {
|
||||
var grant Grant
|
||||
parts := strings.Split(token, ".")
|
||||
if len(key) < 32 || len(token) > 2048 || len(parts) != 2 {
|
||||
return grant, errors.New("invalid grant")
|
||||
}
|
||||
sig, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return grant, errors.New("invalid grant")
|
||||
}
|
||||
h := hmac.New(sha256.New, []byte(key))
|
||||
h.Write([]byte(parts[0]))
|
||||
if !hmac.Equal(sig, h.Sum(nil)) {
|
||||
return grant, errors.New("invalid grant")
|
||||
}
|
||||
data, err := base64.RawURLEncoding.DecodeString(parts[0])
|
||||
if err != nil {
|
||||
return grant, errors.New("invalid grant")
|
||||
}
|
||||
if json.Unmarshal(data, &grant) != nil || grant.Subject == "" || len(grant.Subject) > 160 || len(grant.Nonce) < 16 || len(grant.Nonce) > 80 || grant.Expires <= now.Unix() || grant.Expires > now.Add(time.Minute).Unix() {
|
||||
return Grant{}, errors.New("invalid grant")
|
||||
}
|
||||
return grant, nil
|
||||
}
|
||||
|
||||
var denied = func() []netip.Prefix {
|
||||
var result []netip.Prefix
|
||||
for _, p := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "192.88.99.0/24", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "2001::/23", "2001:db8::/32", "2002::/16", "3fff::/20"} {
|
||||
result = append(result, netip.MustParsePrefix(p))
|
||||
}
|
||||
return result
|
||||
}()
|
||||
|
||||
func PublicIP(ip netip.Addr) bool {
|
||||
ip = ip.Unmap()
|
||||
if !ip.IsValid() || ip.Zone() != "" || !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
|
||||
return false
|
||||
}
|
||||
// Only globally allocated IPv6 unicast; excludes NAT64, mapped/private and
|
||||
// future address classes rather than treating unknown ranges as public.
|
||||
if ip.Is6() && !netip.MustParsePrefix("2000::/3").Contains(ip) {
|
||||
return false
|
||||
}
|
||||
for _, p := range denied {
|
||||
if p.Contains(ip) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func ValidDestination(host string, port uint16) bool {
|
||||
if port != 80 && port != 443 {
|
||||
return false
|
||||
}
|
||||
if ip, err := netip.ParseAddr(host); err == nil {
|
||||
return PublicIP(ip)
|
||||
}
|
||||
host = strings.TrimSuffix(strings.ToLower(host), ".")
|
||||
if len(host) == 0 || len(host) > 253 || host == "localhost" || strings.HasSuffix(host, ".localhost") || !strings.Contains(host, ".") {
|
||||
return false
|
||||
}
|
||||
for _, label := range strings.Split(host, ".") {
|
||||
if len(label) == 0 || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
|
||||
return false
|
||||
}
|
||||
for _, c := range label {
|
||||
if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
type lookupFunc func(context.Context, string, string) ([]netip.Addr, error)
|
||||
type dialFunc func(context.Context, string, string) (net.Conn, error)
|
||||
|
||||
func dialPublic(ctx context.Context, host string, port uint16, lookup lookupFunc, dial dialFunc) (net.Conn, error) {
|
||||
if !ValidDestination(host, port) {
|
||||
return nil, errors.New("blocked destination")
|
||||
}
|
||||
ips, err := lookup(ctx, "ip", host)
|
||||
if err != nil || len(ips) == 0 || len(ips) > 16 {
|
||||
return nil, errors.New("destination lookup failed")
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if !PublicIP(ip) {
|
||||
return nil, errors.New("blocked destination")
|
||||
}
|
||||
}
|
||||
for _, ip := range ips {
|
||||
conn, e := dial(ctx, "tcp", net.JoinHostPort(ip.Unmap().String(), strconv.Itoa(int(port))))
|
||||
if e == nil {
|
||||
return conn, nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil, errors.New("destination unavailable")
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package geckorelay
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const AssetsPrefix = "/assets/v0.0.1/"
|
||||
|
||||
// Hashes of the two unmodified files in upstream v0.0.1. The release archive
|
||||
// itself is pinned in docs/operations/gecko-relay.md. Refuse mixed engine/glue.
|
||||
func VerifyAssets(dir string) error {
|
||||
for name, want := range map[string]string{
|
||||
"gecko.js": "e5aeebffd21106eccf23b1219316221add5e95085bc5a1bfb941117cfcd75ef7",
|
||||
"gecko.wasm.zst": "ebd6c75179152624d9644865e11792ed25cadc714d9e0985f412baf9c637a086",
|
||||
} {
|
||||
f, err := os.Open(filepath.Join(dir, name))
|
||||
if err != nil {
|
||||
return fmt.Errorf("required Gecko asset unavailable: %s", name)
|
||||
}
|
||||
h := sha256.New()
|
||||
_, err = io.Copy(h, io.LimitReader(f, 64<<20))
|
||||
f.Close()
|
||||
if err != nil || hex.EncodeToString(h.Sum(nil)) != want {
|
||||
return fmt.Errorf("Gecko asset checksum mismatch: %s", name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
package geckorelay
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/websocket"
|
||||
)
|
||||
|
||||
const (
|
||||
window = 8
|
||||
maxFrame = 256 << 10
|
||||
maxStreams = 16
|
||||
maxBytes = 256 << 20
|
||||
bytesPerSecond = 2 << 20
|
||||
)
|
||||
|
||||
type Relay struct {
|
||||
Key, Assets string
|
||||
mu sync.Mutex
|
||||
active map[string]bool
|
||||
used map[string]int64
|
||||
rx, tx, rejected atomic.Int64
|
||||
// Overridden only by package tests; deployment always resolves and pins public IPs.
|
||||
dial func(context.Context, string, uint16) (net.Conn, error)
|
||||
}
|
||||
|
||||
func New(key, assets string) (*Relay, error) {
|
||||
if len(key) < 32 {
|
||||
return nil, errors.New("relay key must contain at least 32 bytes")
|
||||
}
|
||||
r := &Relay{Key: key, Assets: assets, active: map[string]bool{}, used: map[string]int64{}}
|
||||
r.dial = func(ctx context.Context, host string, port uint16) (net.Conn, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||
defer cancel()
|
||||
return dialPublic(ctx, host, port, net.DefaultResolver.LookupNetIP, (&net.Dialer{Timeout: 2 * time.Second}).DialContext)
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (r *Relay) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if req.URL.Path == "/health" && req.Method == "GET" {
|
||||
io.WriteString(w, "ok")
|
||||
return
|
||||
}
|
||||
grant, err := Verify(r.Key, req.Header.Get(GrantHeader), time.Now())
|
||||
if err != nil {
|
||||
http.Error(w, "forbidden", 403)
|
||||
return
|
||||
}
|
||||
if req.Method != "GET" || req.URL.RawQuery != "" {
|
||||
http.Error(w, "invalid request", 400)
|
||||
return
|
||||
}
|
||||
if req.URL.Path == "/status" {
|
||||
r.mu.Lock()
|
||||
active := len(r.active)
|
||||
r.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]any{"active_sessions": active, "received_bytes": r.rx.Load(), "sent_bytes": r.tx.Load(), "rejected": r.rejected.Load(), "profile": "tcp-80-443", "max_sessions": 4, "max_streams": maxStreams, "bytes_per_second": bytesPerSecond, "max_session_bytes": maxBytes})
|
||||
return
|
||||
}
|
||||
if req.URL.Path == AssetsPrefix+"gecko.js" || req.URL.Path == AssetsPrefix+"gecko.wasm.zst" {
|
||||
w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400, immutable")
|
||||
if strings.HasSuffix(req.URL.Path, ".js") {
|
||||
w.Header().Set("Content-Type", "text/javascript")
|
||||
} else {
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
}
|
||||
http.ServeFile(w, req, filepath.Join(r.Assets, filepath.Base(req.URL.Path)))
|
||||
return
|
||||
}
|
||||
if req.URL.Path != "/wisp/" {
|
||||
http.NotFound(w, req)
|
||||
return
|
||||
}
|
||||
r.mu.Lock()
|
||||
now := time.Now().Unix()
|
||||
for nonce, expires := range r.used {
|
||||
if expires <= now {
|
||||
delete(r.used, nonce)
|
||||
}
|
||||
}
|
||||
if r.active[grant.Subject] || len(r.active) >= 4 || r.used[grant.Nonce] > now || len(r.used) >= 256 {
|
||||
r.mu.Unlock()
|
||||
r.rejected.Add(1)
|
||||
http.Error(w, "session limit", 429)
|
||||
return
|
||||
}
|
||||
r.active[grant.Subject] = true
|
||||
r.used[grant.Nonce] = grant.Expires
|
||||
r.mu.Unlock()
|
||||
defer func() { r.mu.Lock(); delete(r.active, grant.Subject); r.mu.Unlock() }()
|
||||
wsServer := websocket.Server{Handshake: func(c *websocket.Config, req *http.Request) error {
|
||||
// Only the authenticated PagesWiki proxy can sign a grant. It validates
|
||||
// the browser Origin before forwarding, not the untrusted client header.
|
||||
if req.Header.Get("Origin") == "" {
|
||||
return errors.New("origin required")
|
||||
}
|
||||
return nil
|
||||
}, Handler: func(ws *websocket.Conn) { r.serve(ws) }}
|
||||
wsServer.ServeHTTP(w, req)
|
||||
}
|
||||
|
||||
type stream struct {
|
||||
data chan []byte
|
||||
done chan struct{}
|
||||
once sync.Once
|
||||
mu sync.Mutex
|
||||
conn net.Conn
|
||||
}
|
||||
|
||||
func (s *stream) close() {
|
||||
s.once.Do(func() {
|
||||
close(s.done)
|
||||
s.mu.Lock()
|
||||
if s.conn != nil {
|
||||
s.conn.Close()
|
||||
}
|
||||
s.mu.Unlock()
|
||||
})
|
||||
}
|
||||
func packet(kind byte, id uint32, data []byte) []byte {
|
||||
b := make([]byte, 5+len(data))
|
||||
b[0] = kind
|
||||
binary.LittleEndian.PutUint32(b[1:], id)
|
||||
copy(b[5:], data)
|
||||
return b
|
||||
}
|
||||
func credit() []byte { b := make([]byte, 4); binary.LittleEndian.PutUint32(b, window); return b }
|
||||
|
||||
func (r *Relay) serve(ws *websocket.Conn) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
|
||||
defer cancel()
|
||||
defer ws.Close()
|
||||
ws.MaxPayloadBytes = maxFrame + 5
|
||||
var mu, sendMu, budgetMu sync.Mutex
|
||||
streams := map[uint32]*stream{}
|
||||
var workers sync.WaitGroup
|
||||
var spent int64
|
||||
tokens := float64(bytesPerSecond)
|
||||
last := time.Now()
|
||||
account := func(n int) bool {
|
||||
budgetMu.Lock()
|
||||
defer budgetMu.Unlock()
|
||||
spent += int64(n)
|
||||
if spent > maxBytes {
|
||||
return false
|
||||
}
|
||||
now := time.Now()
|
||||
tokens += now.Sub(last).Seconds() * bytesPerSecond
|
||||
if tokens > bytesPerSecond {
|
||||
tokens = bytesPerSecond
|
||||
}
|
||||
last = now
|
||||
tokens -= float64(n)
|
||||
if tokens < 0 {
|
||||
timer := time.NewTimer(time.Duration(-tokens / bytesPerSecond * float64(time.Second)))
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
tokens = 0
|
||||
last = time.Now()
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
send := func(kind byte, id uint32, data []byte) error {
|
||||
sendMu.Lock()
|
||||
defer sendMu.Unlock()
|
||||
ws.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
return websocket.Message.Send(ws, packet(kind, id, data))
|
||||
}
|
||||
defer func() {
|
||||
cancel()
|
||||
mu.Lock()
|
||||
for _, s := range streams {
|
||||
s.close()
|
||||
}
|
||||
mu.Unlock()
|
||||
workers.Wait()
|
||||
}()
|
||||
go func() { <-ctx.Done(); ws.Close() }()
|
||||
if send(3, 0, credit()) != nil {
|
||||
return
|
||||
}
|
||||
connections := 0
|
||||
for {
|
||||
ws.SetReadDeadline(time.Now().Add(90 * time.Second))
|
||||
var b []byte
|
||||
if websocket.Message.Receive(ws, &b) != nil {
|
||||
return
|
||||
}
|
||||
if len(b) < 5 || !account(len(b)) {
|
||||
return
|
||||
}
|
||||
r.rx.Add(int64(len(b)))
|
||||
kind, id := b[0], binary.LittleEndian.Uint32(b[1:])
|
||||
if id == 0 {
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
s := streams[id]
|
||||
mu.Unlock()
|
||||
switch kind {
|
||||
case 1:
|
||||
connections++
|
||||
if s != nil || len(b) < 9 || len(b) > 261 || connections > 256 {
|
||||
return
|
||||
}
|
||||
port := binary.LittleEndian.Uint16(b[6:8])
|
||||
host := string(b[8:])
|
||||
if b[5] != 1 || !ValidDestination(host, port) {
|
||||
r.rejected.Add(1)
|
||||
if send(4, id, []byte{0x48}) != nil {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
mu.Lock()
|
||||
full := len(streams) >= maxStreams
|
||||
mu.Unlock()
|
||||
if full {
|
||||
r.rejected.Add(1)
|
||||
if send(4, id, []byte{0x49}) != nil {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
s = &stream{data: make(chan []byte, window), done: make(chan struct{})}
|
||||
mu.Lock()
|
||||
streams[id] = s
|
||||
mu.Unlock()
|
||||
workers.Add(1)
|
||||
go func(id uint32, s *stream, host string, port uint16) {
|
||||
defer workers.Done()
|
||||
defer func() { s.close(); mu.Lock(); delete(streams, id); mu.Unlock() }()
|
||||
dialCtx, stop := context.WithCancel(ctx)
|
||||
defer stop()
|
||||
go func() {
|
||||
select {
|
||||
case <-s.done:
|
||||
stop()
|
||||
case <-dialCtx.Done():
|
||||
}
|
||||
}()
|
||||
conn, e := r.dial(dialCtx, host, port)
|
||||
if e != nil {
|
||||
r.rejected.Add(1)
|
||||
send(4, id, []byte{0x48})
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.conn = conn
|
||||
s.mu.Unlock()
|
||||
select {
|
||||
case <-s.done:
|
||||
conn.Close()
|
||||
return
|
||||
default:
|
||||
}
|
||||
readerDone := make(chan struct{})
|
||||
defer func() { conn.Close(); <-readerDone }()
|
||||
go func() {
|
||||
defer close(readerDone)
|
||||
defer s.close()
|
||||
buffer := make([]byte, 64<<10)
|
||||
for {
|
||||
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
|
||||
n, e := conn.Read(buffer)
|
||||
if n > 0 {
|
||||
if !account(n) {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
r.tx.Add(int64(n))
|
||||
if send(2, id, buffer[:n]) != nil {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
if e != nil {
|
||||
send(4, id, []byte{2})
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
count := 0
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-s.done:
|
||||
return
|
||||
case data := <-s.data:
|
||||
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
if _, e = io.Copy(conn, bytes.NewReader(data)); e != nil {
|
||||
send(4, id, []byte{3})
|
||||
return
|
||||
}
|
||||
count++
|
||||
if count == window {
|
||||
count = 0
|
||||
if send(3, id, credit()) != nil {
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}(id, s, host, port)
|
||||
case 2:
|
||||
if s == nil {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case <-s.done:
|
||||
case s.data <- b[5:]:
|
||||
default:
|
||||
r.rejected.Add(1)
|
||||
s.close()
|
||||
if send(4, id, []byte{0x49}) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
case 4:
|
||||
if len(b) != 6 {
|
||||
return
|
||||
}
|
||||
if s != nil {
|
||||
s.close()
|
||||
}
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package geckorelay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/websocket"
|
||||
)
|
||||
|
||||
const testKey = "synthetic-relay-key-at-least-32-bytes-long"
|
||||
|
||||
func TestAssetsPin(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if VerifyAssets(dir) == nil {
|
||||
t.Fatal("missing assets accepted")
|
||||
}
|
||||
for _, name := range []string{"gecko.js", "gecko.wasm.zst"} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte("untrusted"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if VerifyAssets(dir) == nil {
|
||||
t.Fatal("unverified assets accepted")
|
||||
}
|
||||
if assets := os.Getenv("PAGESWIKI_GECKO_TEST_ASSETS"); assets != "" {
|
||||
if err := VerifyAssets(assets); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrant(t *testing.T) {
|
||||
now := time.Now()
|
||||
g := Grant{"domain:actor", "0123456789abcdef", now.Add(30 * time.Second).Unix()}
|
||||
token := Sign(testKey, g)
|
||||
if got, e := Verify(testKey, token, now); e != nil || got != g {
|
||||
t.Fatal(got, e)
|
||||
}
|
||||
for _, bad := range []string{token + "x", "", strings.Repeat("x", 2049), Sign(testKey, Grant{g.Subject, g.Nonce, now.Add(2 * time.Minute).Unix()}), Sign(testKey, Grant{g.Subject, g.Nonce, now.Unix()})} {
|
||||
if _, e := Verify(testKey, bad, now); e == nil {
|
||||
t.Fatal("accepted invalid grant")
|
||||
}
|
||||
}
|
||||
if _, e := Verify("other-key-at-least-32-bytes-long!!", token, now); e == nil {
|
||||
t.Fatal("wrong key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDestinations(t *testing.T) {
|
||||
for _, host := range []string{"127.0.0.1", "localhost", "host.localhost", "10.0.0.1", "169.254.169.254", "100.64.0.1", "192.0.2.2", "198.19.0.1", "::1", "::ffff:127.0.0.1", "64:ff9b::808:808", "2002:808:808::1", "2001:db8::1", "3fff::1", "fd00::1", "fe80::1%eth0", "bad/host", "example.org\x00.evil", "singlelabel"} {
|
||||
if ValidDestination(host, 443) {
|
||||
t.Fatalf("allowed %q", host)
|
||||
}
|
||||
}
|
||||
for _, host := range []string{"example.org", "EXAMPLE.org.", "8.8.8.8", "2606:4700:4700::1111"} {
|
||||
if !ValidDestination(host, 443) {
|
||||
t.Fatal("blocked", host)
|
||||
}
|
||||
}
|
||||
if ValidDestination("example.org", 22) {
|
||||
t.Fatal("port allowed")
|
||||
}
|
||||
called := false
|
||||
dial := func(_ context.Context, _, addr string) (net.Conn, error) {
|
||||
called = true
|
||||
if addr != "8.8.8.8:443" {
|
||||
t.Fatal("unvalidated DNS re-resolution", addr)
|
||||
}
|
||||
a, b := net.Pipe()
|
||||
b.Close()
|
||||
return a, nil
|
||||
}
|
||||
lookup := func(_ context.Context, _, _ string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("127.0.0.1")}, nil
|
||||
}
|
||||
if _, err := dialPublic(context.Background(), "example.org", 443, lookup, dial); err == nil || called {
|
||||
t.Fatal("mixed DNS allowed")
|
||||
}
|
||||
lookup = func(_ context.Context, _, _ string) ([]netip.Addr, error) {
|
||||
return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
|
||||
}
|
||||
c, err := dialPublic(context.Background(), "example.org", 443, lookup, dial)
|
||||
if err != nil || !called {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
|
||||
func TestRelayFramesAndLimits(t *testing.T) {
|
||||
r, _ := New(testKey, t.TempDir())
|
||||
r.dial = func(ctx context.Context, host string, port uint16) (net.Conn, error) {
|
||||
a, b := net.Pipe()
|
||||
go func() { defer b.Close(); io.Copy(b, b) }()
|
||||
return a, nil
|
||||
}
|
||||
s := httptest.NewServer(r)
|
||||
defer s.Close()
|
||||
grant := Sign(testKey, Grant{"domain:actor", "nonce-first-connection", time.Now().Add(30 * time.Second).Unix()})
|
||||
dial := func(token string) (*websocket.Conn, error) {
|
||||
cfg, _ := websocket.NewConfig("ws"+strings.TrimPrefix(s.URL, "http")+"/wisp/", "https://pages.example")
|
||||
cfg.Header.Set(GrantHeader, token)
|
||||
return websocket.DialConfig(cfg)
|
||||
}
|
||||
if c, e := dial(""); e == nil {
|
||||
c.Close()
|
||||
t.Fatal("anonymous websocket")
|
||||
}
|
||||
c, err := dial(grant)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
receive := func() []byte {
|
||||
var p []byte
|
||||
if e := websocket.Message.Receive(c, &p); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return p
|
||||
}
|
||||
p := receive()
|
||||
if p[0] != 3 || binary.LittleEndian.Uint32(p[1:]) != 0 || binary.LittleEndian.Uint32(p[5:]) != window {
|
||||
t.Fatal(p)
|
||||
}
|
||||
if second, e := dial(grant); e == nil {
|
||||
second.Close()
|
||||
t.Fatal("duplicate actor/replayed grant")
|
||||
}
|
||||
connect := func(id uint32, host string, port uint16, kind byte) {
|
||||
body := []byte{kind, byte(port), byte(port >> 8)}
|
||||
body = append(body, host...)
|
||||
if e := websocket.Message.Send(c, packet(1, id, body)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
connect(1, "127.0.0.1", 80, 1)
|
||||
if p = receive(); p[0] != 4 || p[5] != 0x48 {
|
||||
t.Fatal(p)
|
||||
}
|
||||
connect(2, "example.org", 443, 2)
|
||||
if p = receive(); p[0] != 4 {
|
||||
t.Fatal("UDP accepted")
|
||||
}
|
||||
connect(3, "example.org", 443, 1)
|
||||
for n := 0; n < window; n++ {
|
||||
if e := websocket.Message.Send(c, packet(2, 3, []byte("hello"))); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
got := 0
|
||||
creditSeen := false
|
||||
for got < window*5 || !creditSeen {
|
||||
p = receive()
|
||||
switch p[0] {
|
||||
case 2:
|
||||
got += len(p) - 5
|
||||
case 3:
|
||||
creditSeen = true
|
||||
default:
|
||||
t.Fatal(p)
|
||||
}
|
||||
}
|
||||
// Wisp credits count DATA frames, including empty payloads.
|
||||
for n := 0; n < window; n++ {
|
||||
if e := websocket.Message.Send(c, packet(2, 3, nil)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if p = receive(); p[0] != 3 || binary.LittleEndian.Uint32(p[1:]) != 3 {
|
||||
t.Fatal("empty frame credit", p)
|
||||
}
|
||||
websocket.Message.Send(c, packet(4, 3, []byte{2}))
|
||||
websocket.Message.Send(c, packet(9, 4, nil))
|
||||
var b []byte
|
||||
if websocket.Message.Receive(c, &b) == nil && b[0] != 4 {
|
||||
t.Fatal("invalid packet accepted")
|
||||
}
|
||||
resp, e := http.Get(s.URL + "/status")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != 403 {
|
||||
t.Fatal("unprotected metrics")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayStreamBoundAndCancellation(t *testing.T) {
|
||||
r, _ := New(testKey, t.TempDir())
|
||||
var dialing atomic.Int64
|
||||
r.dial = func(ctx context.Context, host string, port uint16) (net.Conn, error) {
|
||||
dialing.Add(1)
|
||||
defer dialing.Add(-1)
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
server := httptest.NewServer(r)
|
||||
defer server.Close()
|
||||
cfg, _ := websocket.NewConfig("ws"+strings.TrimPrefix(server.URL, "http")+"/wisp/", "https://pages.example")
|
||||
cfg.Header.Set(GrantHeader, Sign(testKey, Grant{"domain:actor", "stream-bound-nonce", time.Now().Add(30 * time.Second).Unix()}))
|
||||
c, err := websocket.DialConfig(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
c.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
var frame []byte
|
||||
if err = websocket.Message.Receive(c, &frame); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for id := 1; id <= maxStreams+1; id++ {
|
||||
if err = websocket.Message.Send(c, packet(1, uint32(id), append([]byte{1, 80, 0}, []byte("example.org")...))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err = websocket.Message.Receive(c, &frame); err != nil || len(frame) != 6 || frame[0] != 4 || binary.LittleEndian.Uint32(frame[1:]) != maxStreams+1 || frame[5] != 0x49 {
|
||||
t.Fatal("stream cap", frame, err)
|
||||
}
|
||||
c.Close()
|
||||
for n := 0; n < 100; n++ {
|
||||
r.mu.Lock()
|
||||
active := len(r.active)
|
||||
r.mu.Unlock()
|
||||
if active == 0 && dialing.Load() == 0 {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("closing session did not cancel pending dials")
|
||||
}
|
||||
|
||||
func TestRelaySessionBoundAndReplay(t *testing.T) {
|
||||
r, _ := New(testKey, t.TempDir())
|
||||
server := httptest.NewServer(r)
|
||||
defer server.Close()
|
||||
dial := func(subject, nonce string) (*websocket.Conn, error) {
|
||||
cfg, _ := websocket.NewConfig("ws"+strings.TrimPrefix(server.URL, "http")+"/wisp/", "https://pages.example")
|
||||
cfg.Header.Set(GrantHeader, Sign(testKey, Grant{subject, nonce, time.Now().Add(30 * time.Second).Unix()}))
|
||||
return websocket.DialConfig(cfg)
|
||||
}
|
||||
var conns []*websocket.Conn
|
||||
for _, subject := range []string{"one", "two", "three", "four"} {
|
||||
c, e := dial(subject, "unique-session-nonce-"+subject)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
conns = append(conns, c)
|
||||
defer c.Close()
|
||||
}
|
||||
if c, e := dial("five", "unique-session-nonce-five"); e == nil {
|
||||
c.Close()
|
||||
t.Fatal("global cap exceeded")
|
||||
}
|
||||
conns[0].Close()
|
||||
for n := 0; n < 100; n++ {
|
||||
r.mu.Lock()
|
||||
active := len(r.active)
|
||||
r.mu.Unlock()
|
||||
if active == 3 {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if c, e := dial("one", "unique-session-nonce-one"); e == nil {
|
||||
c.Close()
|
||||
t.Fatal("replayed after close")
|
||||
}
|
||||
c, e := dial("five", "unique-session-nonce-retry")
|
||||
if e != nil {
|
||||
t.Fatal("slot not released", e)
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
Reference in new issue
Block a user