Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
34 changes: 34 additions & 0 deletions languages/golang/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit.
`[16]byte` (`github.com/google/uuid.UUID`, say), which is converted to
one. `stashgen` does not yet map a Go type to it.

- `encrypt.ReleaseEngine` frees the compiled engine at once. Without it,
the compiled engine is freed one minute after the last client closes.
`ReleaseEngine` is safe to call more than once. A client or checker that
is open when it is called keeps working. The compiled engine is then
freed when the last of them closes. In a test binary, `ReleaseEngine`
does not free the test builds that `encrypttest` clients and checkers
run: those are kept until the test binary exits.

### Changed

- **A record field converts a number of another width or kind, as a
Expand All @@ -40,6 +48,32 @@ and `languages/golang/encrypt/encrypttest/vX.Y.Z` on the same commit.

### Fixed

- A program that opens and closes clients one after another compiles the
engine once, not once per client. Before, the compiled engine was freed
when the last open client closed. So the next `NewClient` or
`NewChecker` compiled it again, for about 1 second each. Now the
compiled engine is kept for one minute after the last client or checker
closes. The first compile also uses every core. `encrypt.ReleaseEngine`
frees the compiled engine sooner.

- `encrypttest.AssertContexts` and `encrypttest.Contexts` compile the
engine once per test binary, not once per call. Before, each call
compiled it: about 1 second, or 10 to 50 seconds under the race
detector. They now ask the test build that `encrypttest.NewClient` runs,
so a test binary that uses both compiles one build. In this module's own
tests, the three `AssertContexts` tests took 138 seconds under `-race`,
and now take 5. A checkout of the repository now needs the test build
for them (`mise run wasm:guest:build:deterministic`), as `NewClient`
already does. A released module includes it.

- `encrypttest.NewClient` compiles the engine once per test binary, not
once per client. A suite that started a client in each test compiled the
engine again in every test. Under `go test -race` that took about 11
seconds a test. Now the first client compiles it, on every core. Every
later client starts in about 0.25 seconds under `-race`, and about 30
milliseconds without it. Parallel tests that start clients at once wait
for one compile, where before each compiled the engine itself.

- **Other calls no longer wait behind a token refresh** (#1958). An
`auth.Strategy` is shared by every encrypt and decrypt in a process, and
about once every 15 minutes its token is refreshed with the token
Expand Down
13 changes: 13 additions & 0 deletions languages/golang/encrypt/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,19 @@ if err != nil {
defer client.Close()
```

The first `NewClient` in a process compiles the engine to machine code.
That takes about a second. The engine is a WebAssembly module. Every later
client reuses the compiled engine and skips that second.

The compiled engine is kept while any client is open, and for one minute
after the last client closes. So a program that opens and closes clients
one after another compiles the engine once. After that minute, the
compiled engine is freed. The next client compiles it again.

To free the compiled engine at once, call `encrypt.ReleaseEngine()`. A
client that is still open keeps working. The compiled engine is then freed
when the last open client closes.

`ctx` is Go's `context.Context`: the deadline and cancellation for the one
ZeroKMS round trip `NewClient` makes. It has nothing to do with an
*encryption* context, which is what a field is sealed under; that is the
Expand Down
5 changes: 5 additions & 0 deletions languages/golang/encrypt/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ func NewChecker(ctx context.Context) (*Checker, error) {
if err != nil {
return nil, err
}
return newCheckerOver(ctx, wasm)
}

// newCheckerOver is a checker over wasm, a build of the guest.
func newCheckerOver(ctx context.Context, wasm []byte) (*Checker, error) {
t := &transport{rt: refusingTransport{}, token: noToken{}}
inst, err := newInstance(ctx, wasm, t, guest.BestEffort)
if err != nil {
Expand Down
5 changes: 5 additions & 0 deletions languages/golang/encrypt/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ import (
// a ZeroKMS request is performed between steps, with the client free for
// other callers (see step.go). Close it when done, as with any resource.
//
// Clients share the compiled engine. The first client in a process
// compiles it, in about a second, and it is kept for a minute after the
// last client closes, so the next client does not compile it again.
// [ReleaseEngine] frees it at once.
//
// A call whose context ends fails with the context's error, and only that
// call: one request's cancellation or deadline never closes the client for
// the others sharing it. A call waiting its turn leaves the queue when its
Expand Down
19 changes: 11 additions & 8 deletions languages/golang/encrypt/encrypttest/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,15 @@ func WithSeed(seed [32]byte) ClientOption {
// or [encrypt.ErrForbidden] for a keyset the client has no grant for. The
// client has no token, so it never returns [encrypt.ErrUnauthorized].
//
// # Start-up time
//
// The first client in a test binary compiles the engine, on every core.
// That takes under a second, or a few seconds under the race detector. The
// compiled engine is kept until the test binary exits, so every later
// client starts in tens of milliseconds, or a few hundred under the race
// detector. A client per test is fine. A client is also safe for
// concurrent use, so parallel tests may share one.
//
// # Seeds
//
// Every client with the default seed opens what any other client with it
Expand Down Expand Up @@ -148,17 +157,10 @@ func NewClient(tb testing.TB, opts ...ClientOption) *encrypt.Client {
for _, opt := range opts {
opt(&o)
}
built, err := testclient.New(context.Background(), plainTestBuild, eqlTestBuild, o.seed)
client, err := narrow[*encrypt.Client](testclient.New(context.Background(), testBuilds, o.seed))
if err != nil {
tb.Fatalf("encrypttest: %v", err)
}
client, ok := built.(*encrypt.Client)
if !ok {
if closer, ok := built.(interface{ Close() error }); ok {
_ = closer.Close()
}
tb.Fatalf("encrypttest: the constructor returned %T, not *encrypt.Client", built)
}
tb.Cleanup(func() {
if err := client.Close(); err != nil {
tb.Errorf("encrypttest: closing the client: %v", err)
Expand Down Expand Up @@ -225,6 +227,7 @@ var (
eqlTestBuild = sync.OnceValues(func() ([]byte, error) {
return readTestBuild(eqlGuestPath, "wasm:guest:build:eql:deterministic")
})
testBuilds = testclient.Builds{Plain: plainTestBuild, WithEQL: eqlTestBuild}
)

func readTestBuild(path, task string) ([]byte, error) {
Expand Down
36 changes: 36 additions & 0 deletions languages/golang/encrypt/encrypttest/client_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,46 @@ package encrypttest

import (
"encoding/hex"
"errors"
"strings"
"testing"
)

// closer counts its Close calls.
type closer struct{ closed int }

func (c *closer) Close() error {
c.closed++
return nil
}

// narrow gives back what a constructor built when it is the type asked
// for. A constructor's error comes back unchanged. A value of another type
// is an error, and is closed so that it does not leak.
func TestNarrow(t *testing.T) {
built := &closer{}
if got, err := narrow[*closer](built, nil); err != nil || got != built {
t.Fatalf("narrow = %v, %v; want the value built", got, err)
}
if built.closed != 0 {
t.Fatal("narrow closed the value it gave back")
}

failed := errors.New("constructor failed")
if _, err := narrow[*closer](nil, failed); !errors.Is(err, failed) {
t.Fatalf("%v, want the constructor's error", err)
}

wrong := &closer{}
_, err := narrow[*strings.Builder](wrong, nil)
if err == nil || !strings.Contains(err.Error(), "*encrypttest.closer, not *strings.Builder") {
t.Fatalf("%v, want an error naming both types", err)
}
if wrong.closed != 1 {
t.Fatalf("the value of the wrong type was closed %d times, want 1", wrong.closed)
}
}

// The default seed is a promise: values an application's fixtures sealed
// under it in one release open under the next. Comparing two clients cannot
// show it changed, because both read the changed value, so it is pinned here
Expand Down
34 changes: 30 additions & 4 deletions languages/golang/encrypt/encrypttest/encrypttest.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,26 +26,52 @@ import (

"github.com/cipherstash/stack/languages/golang/encrypt"
"github.com/cipherstash/stack/languages/golang/encrypt/gensupport"
"github.com/cipherstash/stack/languages/golang/encrypt/internal/testclient"
"github.com/cipherstash/stack/languages/golang/internal/record"
)

// Contexts asks the embedded engine for the contexts of the declaration's
// fields. The text has one line per field, then one indented line with its
// Contexts asks the engine for the contexts of the declaration's fields.
// The text has one line per field, then one indented line with its
// context: "email\n context: users / email\n". It needs no credentials
// and no network. [AssertContexts] reads this text; a test that wants the
// text itself, to print or to compare whole, calls this.
//
// It asks the test build of the engine, the one [NewClient] runs. The test
// build gives the same contexts as the production build: the two differ
// only in where their keys come from. The first call, or the first client,
// in a test binary compiles the test build, and every later call reuses
// it.
func Contexts(ctx context.Context, d gensupport.Declaration) (string, error) {
if err := versionSkew(); err != nil {
return "", err
}
checker, err := encrypt.NewChecker(ctx)
checker, err := narrow[*encrypt.Checker](testclient.NewChecker(ctx, testBuilds))
if err != nil {
return "", err
return "", fmt.Errorf("encrypttest: %w", err)
}
defer func() { _ = checker.Close() }()
return d.Contexts(ctx, checker)
}

// narrow is what a testclient constructor returned, as the type T it
// builds. The constructors return any, because package testclient cannot
// import package encrypt to name the type. A value of another type is
// closed, if it can be, and is an error.
func narrow[T any](built any, err error) (T, error) {
var zero T
if err != nil {
return zero, err
}
v, ok := built.(T)
if !ok {
if closer, ok := built.(interface{ Close() error }); ok {
_ = closer.Close()
}
return zero, fmt.Errorf("the constructor returned %T, not %T", built, zero)
}
return v, nil
}

// A FieldContext is the context of one field, as a test states it: the
// field's name and the parts of its context, in order. Build one with
// [Field].
Expand Down
11 changes: 0 additions & 11 deletions languages/golang/encrypt/encrypttest/encrypttest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package encrypttest_test

import (
"context"
"errors"
"fmt"
"strings"
"testing"
Expand Down Expand Up @@ -30,15 +29,7 @@ func users() gensupport.Declaration {
Encrypt("notes", gensupport.String)
}

func skipWithoutGuest(t *testing.T) {
t.Helper()
if _, err := encrypttest.Contexts(context.Background(), users()); errors.Is(err, encrypt.ErrGuestNotBuilt) {
t.Skip(err)
}
}

func TestAssertContextsPassesOnTheEnginesContexts(t *testing.T) {
skipWithoutGuest(t)
encrypttest.AssertContexts(t, users(),
encrypttest.Field("email", "users", "email"),
encrypttest.Field("notes", "users", "notes"),
Expand All @@ -54,7 +45,6 @@ func TestAssertContextsPassesOnTheEnginesContexts(t *testing.T) {
}

func TestAssertContextsNamesTheFirstFieldThatDiffers(t *testing.T) {
skipWithoutGuest(t)
r := &recorder{TB: t}
encrypttest.AssertContexts(r, users(),
encrypttest.Field("email", "users", "email"),
Expand Down Expand Up @@ -101,7 +91,6 @@ func TestAssertContextsNamesTheFirstFieldThatDiffers(t *testing.T) {
}

func TestAssertContextsReportsARefusedDeclaration(t *testing.T) {
skipWithoutGuest(t)
bad := gensupport.Declare("users").EncryptIndex("age", gensupport.Uint32, encrypt.Match())
r := &recorder{TB: t}
encrypttest.AssertContexts(r, bad)
Expand Down
Loading
Loading