package auth import ( "context" "net/http" "os" "testing" "time" "cdr.dev/slog" "forge.cadoles.com/arcad/edge/pkg/app" edgehttp "forge.cadoles.com/arcad/edge/pkg/http" "forge.cadoles.com/arcad/edge/pkg/jwtutil" "forge.cadoles.com/arcad/edge/pkg/module" "github.com/lestrrat-go/jwx/v2/jwa" "github.com/lestrrat-go/jwx/v2/jwk" "github.com/lestrrat-go/jwx/v2/jwt" "github.com/pkg/errors" "gitlab.com/wpetit/goweb/logger" ) func TestAuthModule(t *testing.T) { t.Parallel() if testing.Verbose() { logger.SetLevel(slog.LevelDebug) } key := getDummyKey() server := app.NewServer( module.ConsoleModuleFactory(), ModuleFactory( WithJWT(getDummyKeySet(key)), ), ) script := "testdata/auth.js" data, err := os.ReadFile(script) if err != nil { t.Fatal(err) } ctx := context.Background() if err := server.Start(ctx, script, string(data)); err != nil { t.Fatalf("%+v", errors.WithStack(err)) } defer server.Stop() req, err := http.NewRequest("GET", "/foo", nil) if err != nil { t.Fatalf("%+v", errors.WithStack(err)) } token := jwt.New() if err := token.Set(jwt.SubjectKey, "jdoe"); err != nil { t.Fatalf("%+v", errors.WithStack(err)) } if err := token.Set(jwt.NotBeforeKey, time.Now()); err != nil { t.Fatalf("%+v", errors.WithStack(err)) } rawToken, err := jwt.Sign(token, jwt.WithKey(jwa.HS256, key)) if err != nil { t.Fatalf("%+v", errors.WithStack(err)) } req.Header.Add("Authorization", "Bearer "+string(rawToken)) ctx = edgehttp.WithContextHTTPRequest(context.Background(), req) if _, err := server.ExecFuncByName(ctx, "testAuth", ctx); err != nil { t.Fatalf("%+v", errors.WithStack(err)) } } func TestAuthAnonymousModule(t *testing.T) { t.Parallel() if testing.Verbose() { logger.SetLevel(slog.LevelDebug) } key := getDummyKey() server := app.NewServer( module.ConsoleModuleFactory(), ModuleFactory(WithJWT(getDummyKeySet(key))), ) script := "testdata/auth_anonymous.js" data, err := os.ReadFile("testdata/auth_anonymous.js") if err != nil { t.Fatal(err) } ctx := context.Background() if err := server.Start(ctx, script, string(data)); err != nil { t.Fatalf("%+v", errors.WithStack(err)) } defer server.Stop() req, err := http.NewRequest("GET", "/foo", nil) if err != nil { t.Fatalf("%+v", errors.WithStack(err)) } ctx = edgehttp.WithContextHTTPRequest(context.Background(), req) if _, err := server.ExecFuncByName(ctx, "testAuth", ctx); err != nil { t.Fatalf("%+v", errors.WithStack(err)) } } func getDummyKey() jwk.Key { secret := []byte("not_so_secret") key, err := jwk.FromRaw(secret) if err != nil { panic(errors.WithStack(err)) } if err := key.Set(jwk.AlgorithmKey, jwa.HS256); err != nil { panic(errors.WithStack(err)) } return key } func getDummyKeySet(key jwk.Key) jwtutil.GetKeySetFunc { return func() (jwk.Set, error) { set := jwk.NewSet() if err := set.AddKey(key); err != nil { return nil, errors.WithStack(err) } return set, nil } }