|
| 1 | +package encrypt_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "database/sql" |
| 6 | + "os" |
| 7 | + "slices" |
| 8 | + "testing" |
| 9 | + |
| 10 | + _ "github.com/jackc/pgx/v5/stdlib" |
| 11 | + |
| 12 | + "github.com/cipherstash/stack/languages/golang/encrypt" |
| 13 | + "github.com/cipherstash/stack/languages/golang/encrypt/internal/testusers" |
| 14 | +) |
| 15 | + |
| 16 | +// The query methods against a real PostgreSQL, through database/sql and the |
| 17 | +// pgx driver: generated rows stored in separate columns, an eq query on the |
| 18 | +// equality term, and a matches query whose rows are decrypted and verified. |
| 19 | +// The keys are the deterministic test build's, so only the database is |
| 20 | +// outside the test. Skipped unless DATABASE_URL names a database the test |
| 21 | +// may create a temporary table in. |
| 22 | + |
| 23 | +// matchPositions reads a stored match filter, or a match query's term, as |
| 24 | +// the int[] of its little-endian uint16 positions, so PostgreSQL can test |
| 25 | +// that a row's filter holds every position of the query with @>. |
| 26 | +const matchPositions = ` |
| 27 | +CREATE FUNCTION pg_temp.match_positions(term bytea) RETURNS int[] |
| 28 | +LANGUAGE sql IMMUTABLE STRICT AS $$ |
| 29 | + SELECT coalesce(array_agg(get_byte(term, 2 * i) | (get_byte(term, 2 * i + 1) << 8)), '{}') |
| 30 | + FROM generate_series(0, length(term) / 2 - 1) AS i |
| 31 | +$$` |
| 32 | + |
| 33 | +func TestQueriesRunAgainstPostgres(t *testing.T) { |
| 34 | + url := os.Getenv("DATABASE_URL") |
| 35 | + if url == "" { |
| 36 | + t.Skip("DATABASE_URL is not set") |
| 37 | + } |
| 38 | + f := readQueryFixture(t) |
| 39 | + c := queryFixtureClient(t, f) |
| 40 | + ctx := context.Background() |
| 41 | + cipher := c.DefaultKeyset() |
| 42 | + |
| 43 | + db, err := sql.Open("pgx", url) |
| 44 | + if err != nil { |
| 45 | + t.Fatal(err) |
| 46 | + } |
| 47 | + t.Cleanup(func() { _ = db.Close() }) |
| 48 | + // One connection: the table and the function are temporary, so they |
| 49 | + // live in this session alone. |
| 50 | + conn, err := db.Conn(ctx) |
| 51 | + if err != nil { |
| 52 | + t.Fatal(err) |
| 53 | + } |
| 54 | + t.Cleanup(func() { _ = conn.Close() }) |
| 55 | + for _, stmt := range []string{ |
| 56 | + `CREATE TEMPORARY TABLE profiles ( |
| 57 | + id bigint PRIMARY KEY, |
| 58 | + email bytea NOT NULL, |
| 59 | + email_eq bytea NOT NULL, |
| 60 | + age bytea NOT NULL, |
| 61 | + age_eq bytea NOT NULL, |
| 62 | + age_ore bytea NOT NULL, |
| 63 | + name bytea NOT NULL, |
| 64 | + name_match bytea NOT NULL |
| 65 | + )`, |
| 66 | + matchPositions, |
| 67 | + } { |
| 68 | + if _, err := conn.ExecContext(ctx, stmt); err != nil { |
| 69 | + t.Fatal(err) |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + // The fixture's verify page, as names, and one email each. |
| 74 | + var people []testusers.QueryProfile |
| 75 | + for i, v := range f.Verify.Values { |
| 76 | + if v != nil { |
| 77 | + people = append(people, testusers.QueryProfile{Email: "p" + string(rune('a'+i)) + "@example.com", Age: uint32(20 + i), Name: *v}) |
| 78 | + } |
| 79 | + } |
| 80 | + encrypted, err := testusers.EncryptQueryProfile(ctx, cipher, people) |
| 81 | + if err != nil { |
| 82 | + t.Fatal(err) |
| 83 | + } |
| 84 | + for i, e := range encrypted { |
| 85 | + if _, err := conn.ExecContext(ctx, |
| 86 | + `INSERT INTO profiles VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, |
| 87 | + i, e.Email.Ciphertext, e.Email.Equality, e.Age.Ciphertext, e.Age.Equality, e.Age.Ore, e.Name.Ciphertext, e.Name.Match, |
| 88 | + ); err != nil { |
| 89 | + t.Fatal(err) |
| 90 | + } |
| 91 | + } |
| 92 | + if _, err := conn.ExecContext(ctx, `ANALYZE profiles`); err != nil { |
| 93 | + t.Fatal(err) |
| 94 | + } |
| 95 | + |
| 96 | + // eq: the equality term binds as a parameter and finds its one row. |
| 97 | + eq, err := testusers.QueryProfileFields.Email.Eq(ctx, cipher, people[2].Email) |
| 98 | + if err != nil { |
| 99 | + t.Fatal(err) |
| 100 | + } |
| 101 | + var id int64 |
| 102 | + if err := conn.QueryRowContext(ctx, `SELECT id FROM profiles WHERE email_eq = $1`, eq).Scan(&id); err != nil || id != 2 { |
| 103 | + t.Fatalf("eq found row %d, %v; want 2", id, err) |
| 104 | + } |
| 105 | + |
| 106 | + // matches: size the fetch, let the server answer, then decrypt the rows |
| 107 | + // it returned and keep those Verify reports true. |
| 108 | + q, err := testusers.QueryProfileFields.Name.Matches(ctx, cipher, f.Verify.Input) |
| 109 | + if err != nil { |
| 110 | + t.Fatal(err) |
| 111 | + } |
| 112 | + var rows uint64 |
| 113 | + if err := conn.QueryRowContext(ctx, `SELECT greatest(reltuples, 0)::bigint FROM pg_class WHERE oid = 'profiles'::regclass`).Scan(&rows); err != nil { |
| 114 | + t.Fatal(err) |
| 115 | + } |
| 116 | + limit, err := q.TargetLimit(ctx, 10, encrypt.Stats{Rows: rows}) |
| 117 | + if err != nil { |
| 118 | + t.Fatal(err) |
| 119 | + } |
| 120 | + if _, bounded := limit.Rows(); bounded { |
| 121 | + t.Fatal("a field declared with tags has no expected token count, so with no histogram the limit is unbounded") |
| 122 | + } |
| 123 | + result, err := conn.QueryContext(ctx, ` |
| 124 | + SELECT id, email, email_eq, age, age_eq, age_ore, name, name_match FROM profiles |
| 125 | + WHERE pg_temp.match_positions(name_match) @> pg_temp.match_positions($1) |
| 126 | + ORDER BY id LIMIT $2`, q, limit.FetchOr(50)) |
| 127 | + if err != nil { |
| 128 | + t.Fatal(err) |
| 129 | + } |
| 130 | + var ids []int64 |
| 131 | + var fetched []testusers.EncryptedQueryProfile |
| 132 | + for result.Next() { |
| 133 | + var e testusers.EncryptedQueryProfile |
| 134 | + if err := result.Scan(&id, &e.Email.Ciphertext, &e.Email.Equality, &e.Age.Ciphertext, &e.Age.Equality, &e.Age.Ore, &e.Name.Ciphertext, &e.Name.Match); err != nil { |
| 135 | + t.Fatal(err) |
| 136 | + } |
| 137 | + ids = append(ids, id) |
| 138 | + fetched = append(fetched, e) |
| 139 | + } |
| 140 | + if err := result.Err(); err != nil { |
| 141 | + t.Fatal(err) |
| 142 | + } |
| 143 | + decrypted, err := testusers.DecryptQueryProfile(ctx, cipher, fetched) |
| 144 | + if err != nil { |
| 145 | + t.Fatal(err) |
| 146 | + } |
| 147 | + names := make([]string, len(decrypted)) |
| 148 | + for i, p := range decrypted { |
| 149 | + names[i] = p.Name |
| 150 | + } |
| 151 | + verified, err := q.Verify(ctx, names) |
| 152 | + if err != nil { |
| 153 | + t.Fatal(err) |
| 154 | + } |
| 155 | + var hits []string |
| 156 | + for i, ok := range verified { |
| 157 | + if ok { |
| 158 | + hits = append(hits, names[i]) |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + var want []string |
| 163 | + for i, v := range f.Verify.Values { |
| 164 | + if v != nil && f.Verify.Verified[i] { |
| 165 | + want = append(want, *v) |
| 166 | + } |
| 167 | + } |
| 168 | + if !slices.Equal(hits, want) { |
| 169 | + t.Fatalf("matches %q verified %q from the server's %q (rows %v), want %q", f.Verify.Input, hits, names, ids, want) |
| 170 | + } |
| 171 | + // The server's answer has no false negative: every true match came back. |
| 172 | + for _, w := range want { |
| 173 | + if !slices.Contains(names, w) { |
| 174 | + t.Fatalf("the server did not return %q", w) |
| 175 | + } |
| 176 | + } |
| 177 | +} |
0 commit comments