Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,11 @@ generated files by hand. Changes to the agent protocol are additive: old agents

## Patched cores

Four protocol cores are built with a patch, each through a `replace` in `go.mod` whose comment says what and why:
Four protocol cores and the RPC library are built with a patch, each through a `replace` in `go.mod` whose comment says what and why:

- `third_party/connect` is Connect (`connectrpc.com/connect`) with `NewUnaryHandler` cut to what has to know the message types: upstream
compiled the whole handler again for every request and response struct, 15 KB of wasm for each of the panel's procedures (3.4 MB
in the admin Worker). The copy holds the root package only, and its `MISTGATE.md` says what is patched and how to check it.
- `third_party/reality` and `third_party/hysteria-core` are copies of the upstream module in the repository (small trees), each
with a `MISTGATE.md`: the version it copies, the changes, how to move it to a new upstream version. They are also published as
branches `mistgate` of `github.com/Mistgate/REALITY` and `github.com/Mistgate/hysteria`; Mistgate builds from the copy.
Expand Down
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -236,3 +236,8 @@ replace github.com/xtls/xray-core => github.com/Mistgate/Xray-core v0.0.0-202611
// a facade without sockets or files (mgdns), a zone responder, hooks for dialing and DNS, limits. From the public fork
// github.com/Mistgate/MasterDnsVPN (its MISTGATE.md says what and why). Pin a commit of the fork, not a branch.
replace masterdnsvpn-go => github.com/Mistgate/MasterDnsVPN v0.0.0-20261201015347-cb8d620bacc6

// Connect with NewUnaryHandler cut to what has to know the message types (third_party/connect/MISTGATE.md): upstream
// stencils the whole handler for every pair of request and response structs, 15 KB of wasm for each of the panel's 270
// procedures, 3.4 MB in the admin Worker.
replace connectrpc.com/connect => ./third_party/connect
40 changes: 40 additions & 0 deletions internal/vendorcheck/connect_behavior_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package vendorcheck

import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"

"connectrpc.com/connect"
"google.golang.org/protobuf/types/known/emptypb"
)

// Upstream's unary handler returns the context's error before it calls the procedure; the patch that moved the body of
// NewUnaryHandler into newUnaryHandler (third_party/connect/MISTGATE.md) must keep that, or a request whose client is gone
// would still run, a change of state included.
func TestPatchedConnectSkipsACanceledRequest(t *testing.T) {
called := false
h := connect.NewUnaryHandler("/test.v1.Test/Call", func(context.Context, *connect.Request[emptypb.Empty]) (*connect.Response[emptypb.Empty], error) {
called = true
return connect.NewResponse(&emptypb.Empty{}), nil
})
serve := func(ctx context.Context) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/test.v1.Test/Call", strings.NewReader("")).WithContext(ctx)
req.Header.Set("Content-Type", "application/proto")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}

if rec := serve(context.Background()); rec.Code != http.StatusOK || !called {
t.Fatalf("a live request: status %d, called %v; want 200 and the procedure run", rec.Code, called)
}
called = false
ctx, cancel := context.WithCancel(context.Background())
cancel()
if serve(ctx); called {
t.Fatal("the procedure ran for a canceled request")
}
}
141 changes: 141 additions & 0 deletions internal/vendorcheck/connect_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package vendorcheck

import (
"encoding/json"
"io/fs"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"

"golang.org/x/mod/modfile"
)

const (
connectPath = "connectrpc.com/connect"
connectDir = "../../third_party/connect"
)

func connectRequired(t *testing.T) string {
t.Helper()
data, err := os.ReadFile("../../go.mod")
if err != nil {
t.Fatal(err)
}
mod, err := modfile.Parse("go.mod", data, nil)
if err != nil {
t.Fatal(err)
}
for _, r := range mod.Require {
if r.Mod.Path == connectPath {
return r.Mod.Version
}
}
t.Fatal(connectPath + " is not required by go.mod")
return ""
}

// The go.mod `replace` sends connect to third_party/connect whatever version is required, so a bump would go on building the old copy.
func TestVendoredConnectVersionMatchesGoMod(t *testing.T) {
doc, err := os.ReadFile(filepath.Join(connectDir, "MISTGATE.md"))
if err != nil {
t.Fatal(err)
}
m := regexp.MustCompile(`\*\*(v[0-9][^*]*)\*\*`).FindSubmatch(doc)
if m == nil {
t.Fatal("third_party/connect/MISTGATE.md does not name the version it is a copy of (**vX.Y.Z**)")
}
if got, want := string(m[1]), connectRequired(t); got != want {
t.Fatalf("go.mod requires %s %s, but third_party/connect is a copy of %s: re-vendor it (third_party/connect/MISTGATE.md says how)", connectPath, want, got)
}
}

// The parts of a patched file that MISTGATE.md says are ours: from the first marker up to the second (or to the end of the file).
// Everything outside them, and the "Modified by" line under the licence header, must be upstream's.
var connectPatched = map[string]struct{ from, to string }{
"handler.go": {"func NewUnaryHandler[Req, Res any](", "// NewUnaryHandlerSimple constructs"},
"connect.go": {"func receiveUnaryResponse[T any](", ""},
}

const connectModifiedLine = "// Modified by Mistgate: see MISTGATE.md in this directory (the marked parts of this file).\n\n"

func cutConnect(t *testing.T, name, text string, ours bool) string {
t.Helper()
if ours {
if strings.Count(text, connectModifiedLine) != 1 {
t.Errorf("%s does not carry the \"Modified by Mistgate\" line exactly once", name)
}
text = strings.Replace(text, connectModifiedLine, "", 1)
}
r := connectPatched[name]
a := strings.Index(text, r.from)
if a < 0 {
t.Fatalf("%s: the start of the patched part (%q) is missing", name, r.from)
}
b := len(text)
if r.to != "" {
if b = strings.Index(text, r.to); b < a {
t.Fatalf("%s: the end of the patched part (%q) is missing", name, r.to)
}
}
return text[:a] + text[b:]
}

// The copy differs from upstream in the Go module cache by the two patched parts and its own MISTGATE.md, and holds every
// root file of upstream (a file added by a new version must not go missing).
func TestVendoredConnectIsUpstreamPlusThePatch(t *testing.T) {
version := connectRequired(t)
out, err := exec.Command("go", "mod", "download", "-json", connectPath+"@"+version).Output()
if err != nil {
t.Skipf("the upstream module %s@%s is not in the module cache and could not be downloaded: %v", connectPath, version, err)
}
var info struct{ Dir string }
if err := json.Unmarshal(out, &info); err != nil || info.Dir == "" {
t.Skipf("go mod download printed no directory for %s@%s", connectPath, version)
}
err = filepath.WalkDir(connectDir, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
rel, _ := filepath.Rel(connectDir, path)
rel = filepath.ToSlash(rel)
if rel == "MISTGATE.md" {
return nil
}
got, err := os.ReadFile(path)
if err != nil {
return err
}
want, err := os.ReadFile(filepath.Join(info.Dir, filepath.FromSlash(rel)))
if err != nil {
t.Errorf("%s is not in upstream %s: %v", rel, version, err)
return nil
}
g, w := string(got), string(want)
if _, patched := connectPatched[rel]; patched {
g, w = cutConnect(t, rel, g, true), cutConnect(t, rel, w, false)
}
if g != w {
t.Errorf("%s differs from upstream %s beyond the declared patch", rel, version)
}
return nil
})
if err != nil {
t.Fatal(err)
}
entries, err := os.ReadDir(info.Dir)
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
name := e.Name()
if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
continue
}
if _, err := os.Stat(filepath.Join(connectDir, name)); err != nil {
t.Errorf("upstream file %s is missing from third_party/connect", name)
}
}
}
Loading
Loading