File size: 5,840 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 |
package harness
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"testing"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
"github.com/target/goalert/auth"
"github.com/target/goalert/limit"
"github.com/target/goalert/permission"
"github.com/target/goalert/user"
)
// DefaultGraphQLAdminUserID is the UserID created & used for GraphQL calls by default.
const DefaultGraphQLAdminUserID = "00000000-0000-0000-0000-000000000002"
func (h *Harness) createGraphQLUser(userID string) {
h.t.Helper()
permission.SudoContext(context.Background(), func(ctx context.Context) {
h.t.Helper()
_, err := h.backend.UserStore.Insert(ctx, &user.User{
Name: "GraphQL User",
ID: userID,
Role: permission.RoleAdmin,
})
if err != nil {
h.t.Fatal(errors.Wrap(err, "create GraphQL user"))
}
})
}
func (h *Harness) createGraphQLSession(userID string) string {
h.t.Helper()
tok, err := h.backend.AuthHandler.CreateSession(context.Background(), "goalert-smoketest", userID)
if err != nil {
h.t.Fatal(errors.Wrap(err, "create auth session"))
}
h.gqlSessions[userID], err = tok.Encode(h.backend.SessionKeyring.Sign)
if err != nil {
h.t.Fatal(errors.Wrap(err, "sign auth session"))
}
return h.gqlSessions[userID]
}
// GraphQLQuery2 will perform a GraphQL2 query against the backend, internally
// handling authentication. Queries are performed with Admin role.
func (h *Harness) GraphQLQuery2(query string) *QLResponse {
h.t.Helper()
return h.GraphQLQueryT(h.t, query)
}
// SetConfigValue will update the config value id (e.g. `General.PublicURL`) to the provided value.
func (h *Harness) SetConfigValue(id, value string) {
h.t.Helper()
res := h.GraphQLQuery2(fmt.Sprintf(`mutation{setConfig(input:[{id: %s, value: %s}])}`, strconv.Quote(id), strconv.Quote(value)))
require.Empty(h.t, res.Errors)
// wait for engine cycle to complete to ensure next action
// uses new config only
h.Trigger()
}
// SetSystemLimit will update the value of a system limit given an id (e.g. `RulesPerSchedule`).
// TODO repalce SetSystemLimit with new mutation (work anticipated to be done with Admin Config view)
func (h *Harness) SetSystemLimit(id limit.ID, value int) {
h.t.Helper()
h.execQuery(fmt.Sprintf(`
UPDATE config_limits
SET max = %d
WHERE id='%s';
`, value, id), nil)
}
// GraphQLQueryT will perform a GraphQL query against the backend, internally
// handling authentication. Queries are performed with Admin role.
func (h *Harness) GraphQLQueryT(t *testing.T, query string) *QLResponse {
t.Helper()
return h.GraphQLQueryUserT(t, DefaultGraphQLAdminUserID, query)
}
func (h *Harness) GraphQLToken(userID string) string {
h.mx.Lock()
tok := h.gqlSessions[userID]
if tok == "" {
if userID == DefaultGraphQLAdminUserID {
h.createGraphQLUser(userID)
}
tok = h.createGraphQLSession(userID)
}
h.mx.Unlock()
return tok
}
// GraphQLQueryUserT will perform a GraphQL query against the backend, internally
// handling authentication. Queries are performed with the provided UserID.
func (h *Harness) GraphQLQueryUserT(t *testing.T, userID, query string) *QLResponse {
t.Helper()
return h.GraphQLQueryUserVarsT(t, userID, query, "", nil)
}
// GraphQLQueryUserT will perform a GraphQL query against the backend, internally
// handling authentication. Queries are performed with the provided UserID.
func (h *Harness) GraphQLQueryUserVarsT(t *testing.T, userID, query, opName string, vars any) *QLResponse {
t.Helper()
retry := 1
var err error
var resp *http.Response
tok := h.GraphQLToken(userID)
for {
query = strings.ReplaceAll(query, "\t", "")
q := struct {
Query string
Variables any `json:"variables,omitempty"`
OperationName string `json:"operationName,omitempty"`
}{Query: query, Variables: vars, OperationName: opName}
data, err := json.Marshal(q)
if err != nil {
h.t.Fatal("failed to marshal graphql query")
}
t.Log("Query:", query)
url := h.URL() + "/api/graphql"
req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
if err != nil {
t.Fatal("failed to make request:", err)
}
req.Header.Set("Content-Type", "application/json")
req.AddCookie(&http.Cookie{
Name: auth.CookieName,
Value: tok,
})
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal("failed to make http request:", err)
}
if resp.StatusCode == 401 && retry > 0 {
h.t.Logf("GraphQL request failed with 401, retrying with new session (%d left)", retry)
h.mx.Lock()
tok = h.createGraphQLSession(userID)
h.mx.Unlock()
resp.Body.Close()
retry--
continue
}
if resp.StatusCode != 200 {
data, _ := io.ReadAll(resp.Body)
t.Fatal("failed to make graphql request:", resp.Status, string(data))
}
break
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal("failed to read response body:", err)
}
var r QLResponse
err = json.Unmarshal(data, &r)
if err != nil {
t.Log("Response:", string(data))
t.Fatal("failed to parse GraphQL response:", err)
}
return &r
}
// QLResponse is a generic GraphQL response.
type QLResponse struct {
Data json.RawMessage
Errors []struct {
Message string
Path QLPath
Extensions struct {
Code string
Key string
FieldID string
}
}
}
type QLPath string
func (p *QLPath) UnmarshalJSON(data []byte) error {
var parts []any
err := json.Unmarshal(data, &parts)
if err != nil {
return err
}
var strParts []string
for _, p := range parts {
switch v := p.(type) {
case string:
strParts = append(strParts, v)
case float64:
strParts = append(strParts, strconv.Itoa(int(v)))
default:
return errors.Errorf("unexpected path part type: %T", p)
}
}
*p = QLPath(strings.Join(strParts, "."))
return nil
}
|