package graph import ( "bytes" "context" "encoding/json" "net/http" "net/http/httptest" "slices" "strings" "testing" "github.com/99designs/gqlgen/graphql" "github.com/99designs/gqlgen/graphql/handler" "github.com/99designs/gqlgen/graphql/handler/transport" "github.com/vektah/gqlparser/v2/ast" "adam-french.co.uk/job-tracker/internal/auth" "adam-french.co.uk/job-tracker/internal/handlers" ) // Authorisation is declared in the schema (@admin) and enforced by // directives.go. These tests cover both halves: that the function decides // correctly, and that the schema marks every field — the second being the // one that matters day to day, since the way this goes wrong is a new field // added without a directive. // // Nothing here needs a database: a refused field never reaches its resolver, // and the tests only ever drive fields that are refused or that return before // touching the Store. var ( anonymous = context.Background() admin = auth.WithAdmin(context.Background(), true) refused = auth.WithAdmin(context.Background(), false) ) func TestRequireAdmin(t *testing.T) { cases := []struct { name string ctx context.Context wantErr string // "" means the resolver must run }{ {"no verdict recorded", anonymous, "admin access required"}, {"site said no", refused, "admin access required"}, {"site said yes", admin, ""}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { called := false next := func(ctx context.Context) (any, error) { called = true return "resolved", nil } res, err := requireAdmin(c.ctx, nil, next) if c.wantErr == "" { if err != nil || !called || res != "resolved" { t.Fatalf("res = %v, err = %v, resolver called = %v; want the resolver's result", res, err, called) } return } // The exact string is what the front end looks for. if err == nil || err.Error() != c.wantErr { t.Fatalf("err = %v, want %q", err, c.wantErr) } if called || res != nil { t.Fatal("the resolver ran, or a result came back, for a refused request") } }) } } // Directives() must supply every directive the schema declares; a nil one // makes gqlgen fail each field that uses it. func TestDirectivesAreAllImplemented(t *testing.T) { if Directives().Admin == nil { t.Fatal("Directives() left @admin unimplemented") } } func schemaUnderTest() *ast.Schema { return NewExecutableSchema(Config{}).Schema() } // Everything the tracker holds is private, so unlike the main site there is // no public allow-list: every root field must carry @admin. func TestEveryRootFieldIsAdmin(t *testing.T) { schema := schemaUnderTest() for _, root := range []*ast.Definition{schema.Query, schema.Mutation} { for _, field := range root.Fields { if strings.HasPrefix(field.Name, "__") { continue } if field.Directives.ForName("admin") == nil { t.Errorf("%s.%s has no @admin, so anyone who can reach the tracker can call it", root.Name, field.Name) } } } } // @admin is meant for the two root types. One on an object's field would be // enforced, but nothing above would notice it being removed. func TestDirectivesOnlyOnRootFields(t *testing.T) { schema := schemaUnderTest() for name, def := range schema.Types { if def == schema.Query || def == schema.Mutation || strings.HasPrefix(name, "__") { continue } for _, field := range def.Fields { if field.Directives.ForName("admin") != nil { t.Errorf("%s.%s carries @admin outside Query/Mutation", name, field.Name) } } } } // execute runs one operation through the real executable schema, wired the // way main wires it, and returns the response's error messages. The Store is // empty: every operation below is refused, or returns, before its resolver // would touch the database. func execute(t *testing.T, ctx context.Context, query string, variables map[string]any) []string { t.Helper() srv := handler.New(NewExecutableSchema(Config{ Resolvers: &Resolver{Store: &handlers.Store{}}, Directives: Directives(), })) srv.AddTransport(transport.POST{}) body, err := json.Marshal(map[string]any{"query": query, "variables": variables}) if err != nil { t.Fatal(err) } req := httptest.NewRequest(http.MethodPost, "/graphql", bytes.NewReader(body)).WithContext(ctx) req.Header.Set("Content-Type", "application/json") rec := httptest.NewRecorder() srv.ServeHTTP(rec, req) var resp struct { Errors []struct { Message string `json:"message"` } `json:"errors"` } if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { t.Fatalf("decoding response %s: %v", rec.Body, err) } var messages []string for _, e := range resp.Errors { messages = append(messages, e.Message) } return messages } // End to end: the message a client receives for a refused field is the bare // string, with nothing wrapped around it. func TestGuardedFieldsRefuseOverTheWire(t *testing.T) { cases := []struct { name string ctx context.Context query string }{ {"anonymous query", anonymous, `{ jobApplications { id } }`}, {"refused query", refused, `{ jobLeads { id } }`}, {"anonymous mutation", anonymous, `mutation { deleteJobApplication(id: 1) }`}, {"refused mutation", refused, `mutation { runJobLeadSync }`}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { got := execute(t, c.ctx, c.query, nil) if !slices.Equal(got, []string{"admin access required"}) { t.Fatalf("errors = %q, want exactly \"admin access required\"", got) } }) } } // The JobStatus enum over the wire, from the side the tracker page uses it: // status sent as a JSON string variable. A value in the vocabulary reaches the // resolver (shown by the resolver's own validation error, which comes before // any database access); one outside it is refused before the resolver runs. func TestJobStatusInputOverTheWire(t *testing.T) { const mutation = `mutation ($input: CreateJobApplicationInput!) { createJobApplication(input: $input) { id status } }` input := func(status any) map[string]any { // A blank title makes the resolver return early, so no test here // needs a database. return map[string]any{"input": map[string]any{"jobTitle": " ", "company": "Acme", "status": status}} } for _, status := range []string{"saved", "applied", "screening", "assessment", "interviewing", "offer", "rejected", "withdrawn"} { got := execute(t, admin, mutation, input(status)) if !slices.Equal(got, []string{"jobTitle and company are required"}) { t.Errorf("status %q: errors = %q, want it accepted and the resolver reached", status, got) } } for _, status := range []any{"hired", "Applied", "", " applied", 3} { got := execute(t, admin, mutation, input(status)) if len(got) != 1 || got[0] == "jobTitle and company are required" { t.Errorf("status %#v: errors = %q, want it refused before the resolver", status, got) } } // The guard still comes first: an anonymous caller learns nothing about // the vocabulary from a valid input. if got := execute(t, context.Background(), mutation, input("applied")); !slices.Equal(got, []string{"admin access required"}) { t.Errorf("anonymous: errors = %q", got) } } // IDs: the wire form must be what it was when every type had a hand-written // resolver returning int. Both marshallers write a quoted decimal string and // both read a string or a number. func TestUintIDWireFormatMatchesIntID(t *testing.T) { for _, id := range []uint{0, 1, 12, 4294967295} { var asUint, asInt bytes.Buffer graphql.MarshalUintID(id).MarshalGQL(&asUint) graphql.MarshalIntID(int(id)).MarshalGQL(&asInt) if asUint.String() != asInt.String() { t.Errorf("id %d: UintID writes %s, IntID wrote %s", id, &asUint, &asInt) } } if got := func() string { var b bytes.Buffer graphql.MarshalUintID(12).MarshalGQL(&b) return b.String() }(); got != `"12"` { t.Errorf("MarshalUintID(12) = %s, want \"12\"", got) } }