diff --git a/go.mod b/go.mod index 5afa294a0c76c9dab6579c09afaf956b66c4515e..9154d968d7faa71cb27757ff9ae4e90364354677 100644 --- a/go.mod +++ b/go.mod @@ -18,6 +18,7 @@ require ( github.com/chenzhuoyu/iasm v0.9.0 // indirect github.com/coreos/go-semver v0.3.1 // indirect github.com/coreos/go-systemd/v22 v22.5.0 // indirect + github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.4 // indirect @@ -35,7 +36,7 @@ require ( ) require ( - gitee.com/openeuler/PilotGo/sdk v0.0.0-20250806061906-ced6853de86f + gitee.com/openeuler/PilotGo/sdk v0.0.0-20250808080917-4f1087c03a0b github.com/bytedance/sonic v1.10.2 // indirect github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect github.com/gin-contrib/sse v0.1.0 // indirect diff --git a/go.sum b/go.sum index 561ec88f85bd8ab6bb613d644798d120123e1354..99ebf5efa0053749496b1caa5dabeccc3b74a0b1 100644 --- a/go.sum +++ b/go.sum @@ -4,6 +4,14 @@ gitee.com/openeuler/PilotGo/sdk v0.0.0-20250805090901-8510c2ef4ecb h1:QRRgVsmkbB gitee.com/openeuler/PilotGo/sdk v0.0.0-20250805090901-8510c2ef4ecb/go.mod h1:pIMXKeUO0pOimMAuuo7mtuNJ7/1IpZ8yI77cid+NlZ4= gitee.com/openeuler/PilotGo/sdk v0.0.0-20250806061906-ced6853de86f h1:nPPSPKI7049Zl28RFcWTxg2ksy/ga7xvzbEh0YrlJqc= gitee.com/openeuler/PilotGo/sdk v0.0.0-20250806061906-ced6853de86f/go.mod h1:pIMXKeUO0pOimMAuuo7mtuNJ7/1IpZ8yI77cid+NlZ4= +gitee.com/openeuler/PilotGo/sdk v0.0.0-20250807082311-4eaca627fa70 h1:IksWD8dgfDWyw1LNES4KWSEzfS/yKFe6tw8s9etaX88= +gitee.com/openeuler/PilotGo/sdk v0.0.0-20250807082311-4eaca627fa70/go.mod h1:MjGXxy1zfF0eQjT932SohfrkgnWGvozgB9sNQX/f/Gs= +gitee.com/openeuler/PilotGo/sdk v0.0.0-20250808015155-47ca0dc5a493 h1:x3ylIqMoZqACZrhMZE1rVyQ0wGAaNw4wPJBJ2b/TzQ4= +gitee.com/openeuler/PilotGo/sdk v0.0.0-20250808015155-47ca0dc5a493/go.mod h1:MjGXxy1zfF0eQjT932SohfrkgnWGvozgB9sNQX/f/Gs= +gitee.com/openeuler/PilotGo/sdk v0.0.0-20250808052926-b61a15f691b9 h1:wMNQK35CvoaIbU3TPaDORNFDJMBCGdk+y5APDGJ2nYk= +gitee.com/openeuler/PilotGo/sdk v0.0.0-20250808052926-b61a15f691b9/go.mod h1:MjGXxy1zfF0eQjT932SohfrkgnWGvozgB9sNQX/f/Gs= +gitee.com/openeuler/PilotGo/sdk v0.0.0-20250808080917-4f1087c03a0b h1:S6ErhW+DY2opiE3puFP+5FD7bmnthp1qZNXorG0+8Mg= +gitee.com/openeuler/PilotGo/sdk v0.0.0-20250808080917-4f1087c03a0b/go.mod h1:MjGXxy1zfF0eQjT932SohfrkgnWGvozgB9sNQX/f/Gs= github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= github.com/bytedance/sonic v1.10.2 h1:GQebETVBxYB7JGWJtLBi07OVzWwt+8dWA00gEVW2ZFE= @@ -23,6 +31,8 @@ github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSV github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= diff --git a/server/config.yml.templete b/server/config.yml.templete index 4bd10a529c4171d13088f35c2fdf91a86720473a..d196145b6497e1dca59de38cfa9c839b2901f9f0 100644 --- a/server/config.yml.templete +++ b/server/config.yml.templete @@ -1,5 +1,3 @@ -plugin_prometheus: - url: "http://localhost:8090" prometheus_server: addr: "localhost:9090" http_server: diff --git a/server/config/config.go b/server/config/config.go index 35144253df18ad82a1a9924e20ab9e2579a3c8b7..570a90ce14a94776c3f1044f3ae3cd86c6e32f03 100644 --- a/server/config/config.go +++ b/server/config/config.go @@ -16,18 +16,13 @@ import ( "gopkg.in/yaml.v2" ) -type PluginPrometheus struct { - URL string `yaml:"url"` -} type PrometheusServer struct { Addr string `yaml:"addr"` } + type HttpServer struct { Addr string `yaml:"addr"` } -type PilotGoServer struct { - Addr string `yaml:"addr"` -} type MysqlDBInfo struct { HostName string `yaml:"host"` @@ -47,7 +42,6 @@ type Etcd struct { } type ServerConfig struct { - PluginPrometheus *PluginPrometheus `yaml:"plugin_prometheus"` PrometheusServer *PrometheusServer `yaml:"prometheus_server"` HttpServer *HttpServer `yaml:"http_server"` Logopts *logger.LogOpts `yaml:"log"` diff --git a/server/main.go b/server/main.go index ee6a0d86ee9f7f4c3a5794f27e89416c6302b98e..4def06a245b3169ada02add3bd42a77954007eef 100644 --- a/server/main.go +++ b/server/main.go @@ -47,14 +47,7 @@ func main() { os.Exit(-1) } - server := router.InitRouter() - - plugin.Client = client.DefaultClient(plugin.Init(config.Config().PluginPrometheus, config.Config().PrometheusServer)) - router.RegisterAPIs(server) - router.StaticRouter(server) - service.GetTags() // pilotgo机器列表tag标签 - - _, err := registry.NewServiceRegistrar(®istry.Options{ + sr, err := registry.NewServiceRegistrar(®istry.Options{ Endpoints: config.Config().Etcd.Endpoints, ServiceAddr: config.Config().HttpServer.Addr, ServiceName: config.Config().Etcd.ServiveName, @@ -70,7 +63,12 @@ func main() { os.Exit(-1) } - if err := server.Run(config.Config().HttpServer.Addr); err != nil { - logger.Fatal("failed to run server: %v", err) + client, err := client.NewClient(config.Config().Etcd.ServiveName, sr.Registry) + if err != nil { + logger.Error("failed to create plugin client: %s", err) + os.Exit(-1) } + plugin.Client = client + + router.StartHttpServer() } diff --git a/server/plugin/plugin_manager.go b/server/plugin/client.go similarity index 41% rename from server/plugin/plugin_manager.go rename to server/plugin/client.go index ec15d82fd0a4c10ef162442a16ba94f26976ba07..a81ff6115861935012a850fc5d9fd62d791474ae 100644 --- a/server/plugin/plugin_manager.go +++ b/server/plugin/client.go @@ -8,25 +8,35 @@ package plugin import ( + "gitee.com/openeuler/PilotGo/sdk/common" "gitee.com/openeuler/PilotGo/sdk/plugin/client" - "openeuler.org/PilotGo/prometheus-plugin/server/config" + "openeuler.org/PilotGo/prometheus-plugin/server/dao" ) var Client *client.Client -func Init(plugin *config.PluginPrometheus, prometheus *config.PrometheusServer) *client.PluginInfo { - PluginInfo := client.PluginInfo{ - MenuName: "监控告警", - Name: "prometheus", - Version: "1.0.1", - Description: "Prometheus开源系统监视和警报工具包", - Author: "zhanghan", - Email: "zhanghan@kylinos.cn", - Url: plugin.URL, - Icon: "Odometer", - PluginType: "micro-app", - ReverseDest: "http://" + prometheus.Addr, +func GetTags() { + tag_cb := func(uuids []string) []common.Tag { + var tags []common.Tag + for _, uuid := range uuids { + ok, _ := dao.IsExistTargetUUID(uuid) + if ok { + tag := common.Tag{ + UUID: uuid, + Type: common.TypeOk, + Data: "监控", + } + tags = append(tags, tag) + } else { + tag := common.Tag{ + UUID: uuid, + Type: common.TypeError, + Data: "", + } + tags = append(tags, tag) + } + } + return tags } - - return &PluginInfo + Client.OnGetTags(tag_cb) } diff --git a/server/router/router.go b/server/router/router.go index bbdabbc2b4c741efedfc06f6ad8ad3034020369b..9346829a980d909e716d092e8822394a48b78681 100644 --- a/server/router/router.go +++ b/server/router/router.go @@ -8,17 +8,29 @@ package router import ( + "fmt" "net/http" "strings" - "gitee.com/openeuler/PilotGo-plugins/event/sdk" "gitee.com/openeuler/PilotGo/sdk/logger" "github.com/gin-gonic/gin" + "openeuler.org/PilotGo/prometheus-plugin/server/config" "openeuler.org/PilotGo/prometheus-plugin/server/httphandler" "openeuler.org/PilotGo/prometheus-plugin/server/plugin" ) -func InitRouter() *gin.Engine { +func StartHttpServer() { + server := initRouter() + + plugin.Client.RegisterHandlers(server) + + plugin.GetTags() // pilotgo机器列表tag标签 + + if err := server.Run(config.Config().HttpServer.Addr); err != nil { + logger.Fatal("failed to run server: %v", err) + } +} +func initRouter() *gin.Engine { gin.SetMode(gin.ReleaseMode) router := gin.New() router.Use(logger.RequestLogger([]string{ @@ -26,33 +38,31 @@ func InitRouter() *gin.Engine { })) router.Use(gin.Recovery()) + registerStaticRouter(router) + registerAPIs(router) return router } -func RegisterAPIs(router *gin.Engine) { - logger.Debug("router register") - plugin.Client.RegisterHandlers(router) - sdk.RegisterEventHandlers(router, plugin.Client) - sdk.UnPluginListenEventHandler() - +func registerAPIs(router *gin.Engine) { + logger.Info("router register") // prometheus api代理 - api := router.Group("/plugin/" + plugin.Client.PluginInfo.Name + "/api") + api := router.Group("/plugin/prometheus/api") prometheus := api.Group("") { prometheus.GET("/query", func(c *gin.Context) { - c.Set("query", plugin.Client.PluginInfo.ReverseDest) + c.Set("query", fmt.Sprintf("http://%s", config.Config().PrometheusServer.Addr)) httphandler.Query(c) }) prometheus.GET("/query_range", func(c *gin.Context) { - c.Set("query_range", plugin.Client.PluginInfo.ReverseDest) + c.Set("query_range", fmt.Sprintf("http://%s", config.Config().PrometheusServer.Addr)) httphandler.QueryRange(c) }) prometheus.GET("/targets", func(c *gin.Context) { - c.Set("targets", plugin.Client.PluginInfo.ReverseDest) + c.Set("targets", fmt.Sprintf("http://%s", config.Config().PrometheusServer.Addr)) httphandler.Targets(c) }) prometheus.GET("/alerts", func(c *gin.Context) { - c.Set("alerts", plugin.Client.PluginInfo.ReverseDest) + c.Set("alerts", fmt.Sprintf("http://%s", config.Config().PrometheusServer.Addr)) httphandler.Alerts(c) }) @@ -89,7 +99,7 @@ func RegisterAPIs(router *gin.Engine) { } } -func StaticRouter(router *gin.Engine) { +func registerStaticRouter(router *gin.Engine) { router.Static("/plugin/prometheus/assets", "../web/dist/assets") router.StaticFile("/plugin/prometheus", "../web/dist/index.html") diff --git a/vendor/gitee.com/openeuler/PilotGo-plugins/event/sdk/common.go b/vendor/gitee.com/openeuler/PilotGo-plugins/event/sdk/common.go deleted file mode 100644 index c02ce90503c5067ec14988c151713b90619bf964..0000000000000000000000000000000000000000 --- a/vendor/gitee.com/openeuler/PilotGo-plugins/event/sdk/common.go +++ /dev/null @@ -1,56 +0,0 @@ -package sdk - -import "encoding/json" - -// event消息类型定义 -const ( - // 主机安装软件包 - MsgPackageInstall = 0 - // 主机升级软件包 - MsgPackageUpdate = 1 - // 主机卸载软件包 - MsgPackageUninstall = 2 - // 主机ip变更 - MsgIPChange = 10 - - // 平台新增主机 - MsgHostAdd = 20 - // 平台移除主机 - MsgHostRemove = 21 - - // 插件添加 - MsgPluginAdd = 30 - // 插件卸载 - MsgPluginRemove = 31 -) - -// 将 MessageData json字符串转换成指定结构体的message消息数据 -func ToMessage(d string, s interface{}) error { - return json.Unmarshal([]byte(d), s) -} - -type MDPackageInstall struct { - HostUUID string - Name string - Version string - Time string -} - -type MDPackageUpdate struct { - HostUUID string - Name string - Version string - Time string -} - -type MDPackageUninstall struct { - HostUUID string - Name string - Version string - Time string -} - -type MDIPChange struct { - HostUUID string - NewIP string -} diff --git a/vendor/gitee.com/openeuler/PilotGo-plugins/event/sdk/event.go b/vendor/gitee.com/openeuler/PilotGo-plugins/event/sdk/event.go deleted file mode 100644 index e114a165a2cf1f99f899c78aab9e841cef4c9c32..0000000000000000000000000000000000000000 --- a/vendor/gitee.com/openeuler/PilotGo-plugins/event/sdk/event.go +++ /dev/null @@ -1,107 +0,0 @@ -package sdk - -import ( - "encoding/json" - "errors" - "io" - "os" - "os/signal" - "syscall" - - "gitee.com/openeuler/PilotGo/sdk/common" - "gitee.com/openeuler/PilotGo/sdk/logger" - "gitee.com/openeuler/PilotGo/sdk/plugin/client" - "github.com/gin-gonic/gin" -) - -func UnPluginListenEventHandler() { - sig := make(chan os.Signal, 1) - signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) - go func() { - logger.Info("插件监听注册goroutine已启动") - defer logger.Info("插件取消监听goroutine退出") - for { - s := <-sig - switch s { - case syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT: - logger.Info("接收到退出信号: %s", s.String()) - UnPluginListenEvent() - os.Exit(0) - default: - logger.Info("接收到未知信号: %s", s.String()) - } - } - }() -} -func RegisterEventHandlers(router *gin.Engine, c *client.Client) { - - api := router.Group("/plugin_manage/api/v1/") - { - api.POST("/event", eventHandler) - } - plugin_client = c - startEventProcessor(c) -} - -func eventHandler(c *gin.Context) { - j, err := io.ReadAll(c.Request.Body) // 接收数据 - if err != nil { - logger.Error("没获取到:%s", err.Error()) - return - } - var msg common.EventMessage - if err := json.Unmarshal(j, &msg); err != nil { - logger.Error("反序列化结果失败%s", err.Error()) - return - } - - ProcessEvent(&msg) -} - -func eventPluginServer() (string, error) { - plugins, err := plugin_client.GetPlugins() - if err != nil { - return "", err - } - - var eventServer string - for _, p := range plugins { - if p.Name == "event" { - eventServer = p.Url - break - } - } - - if eventServer == "" { - return "", errors.New("event plugin not found") - } - - return eventServer, nil -} - -func registerEventCallback(eventType int, callback common.EventCallback) { - plugin_client.EventCallbackMap[eventType] = callback -} - -func unregisterEventCallback(eventType int) { - delete(plugin_client.EventCallbackMap, eventType) -} - -func ProcessEvent(event *common.EventMessage) { - plugin_client.EventChan <- event -} - -func startEventProcessor(c *client.Client) { - go func(c *client.Client) { - for { - e := <-c.EventChan - - // TODO: process event message - cb, ok := c.EventCallbackMap[e.MessageType] - if ok { - cb(e) - } - } - }(c) - -} diff --git a/vendor/gitee.com/openeuler/PilotGo-plugins/event/sdk/listener.go b/vendor/gitee.com/openeuler/PilotGo-plugins/event/sdk/listener.go deleted file mode 100644 index f52dbbfb6353d94ee567285acd279687f26f5102..0000000000000000000000000000000000000000 --- a/vendor/gitee.com/openeuler/PilotGo-plugins/event/sdk/listener.go +++ /dev/null @@ -1,175 +0,0 @@ -package sdk - -import ( - "encoding/json" - "errors" - "net/http" - "strconv" - "strings" - - "gitee.com/openeuler/PilotGo/sdk/common" - "gitee.com/openeuler/PilotGo/sdk/plugin/client" - "gitee.com/openeuler/PilotGo/sdk/utils/httputils" -) - -var plugin_client *client.Client - -// 注册event事件监听 -func ListenEvent(eventTypes []int, callbacks common.EventCallback) error { - var eventtypes []string - for _, i := range eventTypes { - eventtypes = append(eventtypes, strconv.Itoa(i)) - } - - eventServer, err := eventPluginServer() - if err != nil { - return err - } - - url := eventServer + "/plugin/event/listener/register?eventTypes=" + strings.Join(eventtypes, ",") - r, err := httputils.Put(url, &httputils.Params{ - Body: plugin_client.PluginInfo, - }) - if err != nil { - return err - } - if r.StatusCode != http.StatusOK { - return errors.New("server process error:" + strconv.Itoa(r.StatusCode)) - } - - resp := &common.CommonResult{} - if err := json.Unmarshal(r.Body, resp); err != nil { - return err - } - if resp.Code != http.StatusOK { - return errors.New(resp.Message) - } - - data := &struct { - Status string `json:"status"` - Error string `json:"error"` - }{} - if err := resp.ParseData(data); err != nil { - return err - } - for _, eventType := range eventTypes { - registerEventCallback(eventType, callbacks) - } - return nil -} - -// 取消注册event事件监听 -func UnListenEvent(eventTypes []int) error { - var eventtypes []string - for _, i := range eventTypes { - eventtypes = append(eventtypes, strconv.Itoa(i)) - } - eventServer, err := eventPluginServer() - if err != nil { - return err - } - - url := eventServer + "/plugin/event/listener/unregister?eventTypes=" + strings.Join(eventtypes, ",") - r, err := httputils.Delete(url, &httputils.Params{ - Body: plugin_client.PluginInfo, - }) - if err != nil { - return err - } - if r.StatusCode != http.StatusOK { - return errors.New("server process error:" + strconv.Itoa(r.StatusCode)) - } - - resp := &common.CommonResult{} - if err := json.Unmarshal(r.Body, resp); err != nil { - return err - } - if resp.Code != http.StatusOK { - return errors.New(resp.Message) - } - - data := &struct { - Status string `json:"status"` - Error string `json:"error"` - }{} - if err := resp.ParseData(data); err != nil { - return err - } - - for _, eventType := range eventTypes { - unregisterEventCallback(eventType) - } - return nil -} - -// 插件服务退出,取消注册所有本插件的event事件监听 -func UnPluginListenEvent() error { - eventServer, err := eventPluginServer() - if err != nil { - return err - } - - url := eventServer + "/plugin/event/listener/unpluginRegister" - r, err := httputils.Delete(url, &httputils.Params{ - Body: plugin_client.PluginInfo, - }) - if err != nil { - return err - } - if r.StatusCode != http.StatusOK { - return errors.New("server process error:" + strconv.Itoa(r.StatusCode)) - } - - resp := &common.CommonResult{} - if err := json.Unmarshal(r.Body, resp); err != nil { - return err - } - if resp.Code != http.StatusOK { - return errors.New(resp.Message) - } - data := &struct { - EventType []int `json:"eventType"` - Status string `json:"status"` - }{} - if err := resp.ParseData(data); err != nil || data.Status != "ok" { - return err - } - for _, eventType := range data.EventType { - unregisterEventCallback(eventType) - } - return nil -} - -// 发布event事件 -func PublishEvent(msg common.EventMessage) error { - eventServer, err := eventPluginServer() - if err != nil { - return err - } - url := eventServer + "/plugin/event/publishEvent" - r, err := httputils.Put(url, &httputils.Params{ - Body: &msg, - }) - if err != nil { - return err - } - if r.StatusCode != http.StatusOK { - return errors.New("server process error:" + strconv.Itoa(r.StatusCode)) - } - - resp := &common.CommonResult{} - if err := json.Unmarshal(r.Body, resp); err != nil { - return err - } - if resp.Code != http.StatusOK { - return errors.New(resp.Message) - } - data := &struct { - Status string `json:"status"` - Error string `json:"error"` - }{} - if err := resp.ParseData(data); err != nil { - return err - } - return nil -} diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/go-micro/registry/etcd.go b/vendor/gitee.com/openeuler/PilotGo/sdk/go-micro/registry/etcd.go index 94e8041fde1f9377a7e5c1a826a49d618438d2ea..770dae9c202239c7140c1869a3cef95da89e795f 100644 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/go-micro/registry/etcd.go +++ b/vendor/gitee.com/openeuler/PilotGo/sdk/go-micro/registry/etcd.go @@ -99,12 +99,12 @@ func (e *etcdRegistry) Deregister() error { } func (e *etcdRegistry) Get(key string) (*ServiceInfo, error) { - resp, err := e.client.Get(e.ctx, key) + resp, err := e.client.Get(e.ctx, "/services/"+key) if err != nil { return &ServiceInfo{}, err } if len(resp.Kvs) == 0 { - return &ServiceInfo{}, nil + return &ServiceInfo{}, fmt.Errorf("未找到服务实例") } var service ServiceInfo if err := json.Unmarshal(resp.Kvs[0].Value, &service); err != nil { diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/go-micro/registry/service.go b/vendor/gitee.com/openeuler/PilotGo/sdk/go-micro/registry/service.go index 5c20a091a5f6cf348e1edb6f26dc29083f71fb27..7488f0d684a2bdb02a35fa85ed18d017590f5b9b 100644 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/go-micro/registry/service.go +++ b/vendor/gitee.com/openeuler/PilotGo/sdk/go-micro/registry/service.go @@ -20,12 +20,12 @@ import ( // ServiceRegistrar handles service registration and lifecycle management type ServiceRegistrar struct { - registry Registry - info *ServiceInfo + Registry Registry + ServiceInfo *ServiceInfo } // NewServiceRegistrar creates a new service registrar -func NewServiceRegistrar(opts *Options) (Registry, error) { +func NewServiceRegistrar(opts *Options) (*ServiceRegistrar, error) { // Create registry client reg, err := NewRegistry(RegistryTypeEtcd, opts) if err != nil { @@ -47,8 +47,8 @@ func NewServiceRegistrar(opts *Options) (Registry, error) { } sr := &ServiceRegistrar{ - registry: reg, - info: info, + Registry: reg, + ServiceInfo: info, } if err := sr.Start(); err != nil { @@ -70,12 +70,12 @@ func NewServiceRegistrar(opts *Options) (Registry, error) { }() logger.Info("service registered to etcd successfully") - return reg, nil + return sr, nil } // Start registers the service and starts keeping it alive func (s *ServiceRegistrar) Start() error { - if err := s.registry.Register(s.info); err != nil { + if err := s.Registry.Register(s.ServiceInfo); err != nil { return fmt.Errorf("failed to register service: %v", err) } return nil @@ -83,8 +83,8 @@ func (s *ServiceRegistrar) Start() error { // Stop deregisters the service and cleans up resources func (s *ServiceRegistrar) Stop() error { - if err := s.registry.Deregister(); err != nil { + if err := s.Registry.Deregister(); err != nil { return fmt.Errorf("failed to deregister service: %v", err) } - return s.registry.Close() + return s.Registry.Close() } diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/batch.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/batch.go index 70f1f99af2eb036a5ef9cc12b2f5afdf95fcc3dc..f592bf1e7be92380a3602f7564b0239ddc0a700a 100644 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/batch.go +++ b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/batch.go @@ -9,20 +9,23 @@ package client import ( "encoding/json" - "errors" + "fmt" "gitee.com/openeuler/PilotGo/sdk/common" + "gitee.com/openeuler/PilotGo/sdk/plugin/jwt" "gitee.com/openeuler/PilotGo/sdk/utils/httputils" ) func (c *Client) BatchList() ([]*common.BatchList, error) { - if !c.IsBind() { - return nil, errors.New("unbind PilotGo-server platform") + serverInfo, err := c.Registry.Get("pilotgo-server") + if err != nil { + return []*common.BatchList{}, err } - url := "http://" + c.Server() + "/api/v1/pluginapi/batch_list" + url := fmt.Sprintf("http://%s:%s/api/v1/pluginapi/batch_list", serverInfo.Address, serverInfo.Port) + r, err := httputils.Get(url, &httputils.Params{ Cookie: map[string]string{ - TokenCookie: c.token, + jwt.TokenCookie: c.token, }, }) if err != nil { @@ -40,13 +43,15 @@ func (c *Client) BatchList() ([]*common.BatchList, error) { } func (c *Client) BatchUUIDList(batchId string) ([]string, error) { - if !c.IsBind() { - return nil, errors.New("unbind PilotGo-server platform") + serverInfo, err := c.Registry.Get("pilotgo-server") + if err != nil { + return []string{}, err } - url := "http://" + c.Server() + "/api/v1/pluginapi/batch_uuid?batchId=" + batchId + url := fmt.Sprintf("http://%s:%s/api/v1/pluginapi/batch_uuid?batchId=%s", serverInfo.Address, serverInfo.Port, batchId) + r, err := httputils.Get(url, &httputils.Params{ Cookie: map[string]string{ - TokenCookie: c.token, + jwt.TokenCookie: c.token, }, }) if err != nil { diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/bindsync.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/bindsync.go deleted file mode 100644 index 83145caa4361716f06a51d5cd1894d9221fae895..0000000000000000000000000000000000000000 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/bindsync.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) KylinSoft Co., Ltd. 2024.All rights reserved. - * PilotGo licensed under the Mulan Permissive Software License, Version 2. - * See LICENSE file for more details. - * Author: wubijie - * Date: Wed Dec 27 19:38:17 2023 +0800 - */ -package client - -import ( - "gitee.com/openeuler/PilotGo/sdk/logger" -) - -func (c *Client) Wait4Bind() { - c.cond.L.Lock() - logger.Debug("等待bind中...") - for c.server == "" { - c.cond.Wait() // 等待条件变量被通知 - } - c.cond.L.Unlock() - logger.Debug("bind 成功!") -} diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/client.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/client.go index dcae6b878882762a634396cf9558ea866257821f..2de32e75168bd56450995c110c204b8969ee6b96 100644 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/client.go +++ b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/client.go @@ -2,32 +2,34 @@ * Copyright (c) KylinSoft Co., Ltd. 2024.All rights reserved. * PilotGo licensed under the Mulan Permissive Software License, Version 2. * See LICENSE file for more details. - * Author: zhanghan2021 - * Date: Wed Sep 27 17:35:12 2023 +0800 + * Author: zhanghan + * Date: Thu Aug 07 16:18:53 2025 +0800 */ package client import ( - "sync" + "fmt" "gitee.com/openeuler/PilotGo/sdk/common" + "gitee.com/openeuler/PilotGo/sdk/go-micro/registry" + "gitee.com/openeuler/PilotGo/sdk/plugin/jwt" "github.com/gin-gonic/gin" ) -const TokenCookie = "PluginToken" +type RunCommandCallback func([]*common.CmdResult) +type CallbackHandler struct { + RunCommandCallback RunCommandCallback + TaskLen int +} type GetTagsCallback func([]string) []common.Tag type Client struct { - PluginInfo *PluginInfo - // 并发锁 - l sync.Mutex - - // 远程PilotGo server地址 - server string + token string + Registry registry.Registry - // 鉴权token - token string + // 用于处理主机标签 + getTagsCallback GetTagsCallback // 用于event消息处理 EventChan chan *common.EventMessage @@ -36,93 +38,39 @@ type Client struct { // 用于异步command及script执行结果处理机 asyncCmdResultChan chan *common.AsyncCmdResult cmdProcessorCallbackMap map[string]CallbackHandler - - // 用于处理主机标签 - getTagsCallback GetTagsCallback - - // 用于平台扩展点功能 - extentions []common.Extention - - //用于权限校验 - permissions []common.Permission - - //bind阻塞功能支持 - mu sync.Mutex - cond *sync.Cond } -var global_client *Client - -func DefaultClient(desc *PluginInfo) *Client { - global_client = &Client{ - PluginInfo: desc, +func NewClient(serviceName string, reg registry.Registry) (*Client, error) { + token, err := jwt.GeneratePluginServiceToken(serviceName) + if err != nil { + return &Client{}, fmt.Errorf("failed to generate plugin service token: %s", err.Error()) + } + return &Client{ + token: token, + Registry: reg, EventChan: make(chan *common.EventMessage, 20), EventCallbackMap: make(map[int]common.EventCallback), asyncCmdResultChan: make(chan *common.AsyncCmdResult, 20), cmdProcessorCallbackMap: make(map[string]CallbackHandler), - extentions: []common.Extention{}, - permissions: []common.Permission{}, - } - global_client.cond = sync.NewCond(&global_client.mu) - - return global_client -} - -func GetClient() *Client { - return global_client -} - -func (client *Client) Server() string { - return client.server + }, nil } // RegisterHandlers 注册一些插件标准的API接口,清单如下: -// GET /plugin_manage/info -func (client *Client) RegisterHandlers(router *gin.Engine) { - // 提供插件基本信息 - mg := router.Group("/plugin_manage/", func(c *gin.Context) { - c.Set("__internal__client_instance", client) - }) - { - mg.GET("/info", infoHandler) - // 绑定PilotGo server - mg.PUT("/bind", bindHandler) - } - +func (cli *Client) RegisterHandlers(router *gin.Engine) { api := router.Group("/plugin_manage/api/v1/") { api.GET("/gettags", func(c *gin.Context) { - c.Set("__internal__client_instance", client) - }, tagsHandler) + c.Set("__internal__client_instance", cli) + }, TagsHandler) api.PUT("/command_result", func(c *gin.Context) { - c.Set("__internal__client_instance", client) - }, commandResultHandler) + c.Set("__internal__client_instance", cli) + }, RunCommandResultHandler) } - // pg := router.Group("/plugin/" + desc.Name) - // { - // pg.Any("/*any", func(c *gin.Context) { - // c.Set("__internal__reverse_dest", dest) - // ReverseProxyHandler(c) - // }) - // } - // TODO: start command result process service - // client.startEventProcessor() - client.startCommandResultProcessor() -} - -func (client *Client) OnGetTags(callback GetTagsCallback) { - client.getTagsCallback = callback -} - -// client是否bind PilotGo server -func (client *Client) IsBind() bool { - client.l.Lock() - defer client.l.Unlock() - - return !(client.server == "") + // c.startEventProcessor() + cli.startCommandResultProcessor() } diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/config.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/config.go index 41add3e37a4b5520f18a77919a44bfa4de4ab04f..dbe5c2e916e4e8e3131a1c40b728ed87a1183538 100644 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/config.go +++ b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/config.go @@ -10,19 +10,23 @@ package client import ( "encoding/json" "errors" + "fmt" "gitee.com/openeuler/PilotGo/sdk/common" + "gitee.com/openeuler/PilotGo/sdk/plugin/jwt" "gitee.com/openeuler/PilotGo/sdk/utils/httputils" ) func (c *Client) ApplyConfig(batch *common.Batch, path, content string) error { - if !c.IsBind() { - return errors.New("unbind PilotGo-server platform") + serverInfo, err := c.Registry.Get("pilotgo-server") + if err != nil { + return err } - url := c.Server() + "/api/v1/pluginapi/apply_config" + url := fmt.Sprintf("http://%s:%s/api/v1/pluginapi/apply_config", serverInfo.Address, serverInfo.Port) + r, err := httputils.Put(url, &httputils.Params{ Cookie: map[string]string{ - TokenCookie: c.token, + jwt.TokenCookie: c.token, }, }) if err != nil { diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/fileservice.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/fileservice.go index 3fe24a816e0537968ed1346189eb39e98544a0af..3dc8529974ca28d5a0184095e292feab6d792478 100644 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/fileservice.go +++ b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/fileservice.go @@ -20,6 +20,7 @@ import ( "strings" "gitee.com/openeuler/PilotGo/sdk/logger" + "gitee.com/openeuler/PilotGo/sdk/plugin/jwt" "gitee.com/openeuler/PilotGo/sdk/utils/httputils" ) @@ -31,7 +32,12 @@ func (client *Client) FileUpload(filePath string, filename string) error { return err } - upload_addr := "http://" + client.Server() + "/api/v1/pluginapi/upload?filename=" + filename + serverInfo, err := client.Registry.Get("pilotgo-server") + if err != nil { + return err + } + upload_addr := fmt.Sprintf("http://%s:%s/api/v1/pluginapi/upload?filename=%s", serverInfo.Address, serverInfo.Port, filename) + // 判断服务端是否是http协议 ishttp, err := httputils.ServerIsHttp(upload_addr) if err != nil { @@ -49,7 +55,7 @@ func (client *Client) FileUpload(filePath string, filename string) error { req.Header.Set("Content-Type", contentType) req.AddCookie(&http.Cookie{ - Name: TokenCookie, + Name: jwt.TokenCookie, Value: client.token, }) diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/handler.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/handler.go index d8e1389a1f5fc70c84e5eb149236ea9c39581f33..cfc0bb68231640f781c7313a9684e1f8eb7c01b6 100644 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/handler.go +++ b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/handler.go @@ -3,18 +3,13 @@ * PilotGo licensed under the Mulan Permissive Software License, Version 2. * See LICENSE file for more details. * Author: zhanghan2021 - * Date: Wed Sep 27 17:35:12 2023 +0800 + * Date: Thu Aug 07 17:35:12 2025 +0800 */ package client import ( "encoding/json" - "fmt" "io" - "net/http" - "net/http/httputil" - "net/url" - "strings" "gitee.com/openeuler/PilotGo/sdk/common" "gitee.com/openeuler/PilotGo/sdk/logger" @@ -22,77 +17,7 @@ import ( "github.com/gin-gonic/gin" ) -func ReverseProxyHandler(c *gin.Context) { - remote := c.GetString("__internal__reverse_dest") - if remote == "" { - fmt.Println("get reverse dest failed!") - return - } - - target, err := url.Parse(remote) - if err != nil { - return - } - - proxy := httputil.NewSingleHostReverseProxy(target) - c.Request.URL.Path = strings.Replace(c.Request.URL.Path, "/plugin/grafana", "", 1) //请求API - - proxy.ServeHTTP(c.Writer, c.Request) -} - -func infoHandler(c *gin.Context) { - v, ok := c.Get("__internal__client_instance") - if !ok { - response.Fail(c, gin.H{"status": false}, "未获取到client值信息") - return - } - client, ok := v.(*Client) - if !ok { - response.Fail(c, gin.H{"status": false}, "client信息错误") - return - } - - info := &PluginFullInfo{ - PluginInfo: *client.PluginInfo, - Extentions: client.extentions, - Permissions: client.permissions, - } - - c.JSON(http.StatusOK, info) -} - -func bindHandler(c *gin.Context) { - port := c.Query("port") - - v, ok := c.Get("__internal__client_instance") - if !ok { - response.Fail(c, gin.H{"status": false}, "未获取到client值信息") - return - } - client, ok := v.(*Client) - if !ok { - response.Fail(c, gin.H{"status": false}, "client信息错误") - return - } - server := strings.Split(c.Request.RemoteAddr, ":")[0] + ":" + port - if client.server == "" { - client.server = server - } else if client.server != "" && client.server != server { - logger.Error("已有PilotGo-server与此插件绑定") - } - client.cond.Broadcast() - - for _, c := range c.Request.Cookies() { - if c.Name == TokenCookie { - client.token = c.Value - } - } - - client.sendHeartBeat() - response.Success(c, nil, "bind server success") -} - -func commandResultHandler(c *gin.Context) { +func RunCommandResultHandler(c *gin.Context) { j, err := io.ReadAll(c.Request.Body) // 接收数据 if err != nil { logger.Error("没获取到:%s", err.Error()) @@ -119,7 +44,7 @@ func commandResultHandler(c *gin.Context) { } -func tagsHandler(c *gin.Context) { +func TagsHandler(c *gin.Context) { j, err := io.ReadAll(c.Request.Body) // 接收数据 if err != nil { logger.Error("没获取到:%s", err.Error()) diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/heartbeat.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/heartbeat.go deleted file mode 100644 index f4aedd3fb935c943b76e25c2c1ffa2041ec598af..0000000000000000000000000000000000000000 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/heartbeat.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) KylinSoft Co., Ltd. 2024.All rights reserved. - * PilotGo licensed under the Mulan Permissive Software License, Version 2. - * See LICENSE file for more details. - * Author: zhanghan2021 - * Date: Mon Dec 18 10:57:09 2023 +0800 - */ -package client - -import ( - "encoding/json" - "fmt" - "net/http" - "time" - - "gitee.com/openeuler/PilotGo/sdk/logger" - "gitee.com/openeuler/PilotGo/sdk/utils/httputils" -) - -const ( - HeartbeatInterval = 30 * time.Second - HeartbeatKey = "heartbeat:" -) - -// 插件连接状态 -type PluginStatus struct { - Connected bool - LastConnect time.Time -} - -func (client *Client) sendHeartBeat() { - clientID := client.PluginInfo.Url - go func() { - for { - err := client.sendHeartbeat(clientID) - if err != nil { - logger.Error("Heartbeat failed:%v", err) - } - time.Sleep(HeartbeatInterval) - } - }() -} - -func (client *Client) sendHeartbeat(clientID string) error { - p := &struct { - PluginUrl string `json:"clientID"` - }{ - PluginUrl: clientID, - } - - ServerUrl := "http://" + client.Server() + "/api/v1/pluginapi/heartbeat" - resp, err := httputils.Post(ServerUrl, &httputils.Params{ - Body: p, - Cookie: map[string]string{ - TokenCookie: client.token, - }, - }) - if err != nil { - return err - } - res := &struct { - Code int `json:"code"` - Message string `json:"msg"` - }{} - if err := json.Unmarshal(resp.Body, res); err != nil { - return err - } - if res.Code != http.StatusOK { - return fmt.Errorf("heartbeat failed with status: %v", res.Code) - } - return nil -} diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/machine.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/machine.go index 85bc2294a9d7c74967750ee19357de2d56dc65aa..10419ff1b9837bf863f979d8b351f66006e6b666 100644 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/machine.go +++ b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/machine.go @@ -9,20 +9,24 @@ package client import ( "encoding/json" - "errors" + "fmt" "gitee.com/openeuler/PilotGo/sdk/common" + "gitee.com/openeuler/PilotGo/sdk/plugin/jwt" "gitee.com/openeuler/PilotGo/sdk/utils/httputils" ) func (c *Client) MachineList() ([]*common.MachineNode, error) { - if !c.IsBind() { - return nil, errors.New("unbind PilotGo-server platform") + serverInfo, err := c.Registry.Get("pilotgo-server") + if err != nil { + return nil, err } - url := "http://" + c.Server() + "/api/v1/pluginapi/machine_list" + + url := fmt.Sprintf("http://%s:%s/api/v1/pluginapi/machine_list", serverInfo.Address, serverInfo.Port) + r, err := httputils.Get(url, &httputils.Params{ Cookie: map[string]string{ - TokenCookie: c.token, + jwt.TokenCookie: c.token, }, }) if err != nil { @@ -40,13 +44,15 @@ func (c *Client) MachineList() ([]*common.MachineNode, error) { } func (c *Client) MachineInfoByUUID(machine_uuid string) (*common.MachineNode, error) { - if !c.IsBind() { - return nil, errors.New("unbind PilotGo-server platform") + serverInfo, err := c.Registry.Get("pilotgo-server") + if err != nil { + return &common.MachineNode{}, err } - url := "http://" + c.Server() + "/api/v1/pluginapi/machine_info?machine_uuid=" + machine_uuid + url := fmt.Sprintf("http://%s:%s/api/v1/pluginapi/machine_info?machine_uuid=%s", serverInfo.Address, serverInfo.Port, machine_uuid) + r, err := httputils.Get(url, &httputils.Params{ Cookie: map[string]string{ - TokenCookie: c.token, + jwt.TokenCookie: c.token, }, }) if err != nil { diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/permission.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/permission.go deleted file mode 100644 index 10352de3b1ec4769d199042f46a6debe87b96ab8..0000000000000000000000000000000000000000 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/permission.go +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) KylinSoft Co., Ltd. 2024.All rights reserved. - * PilotGo licensed under the Mulan Permissive Software License, Version 2. - * See LICENSE file for more details. - * Author: wubijie - * Date: Thu Jan 11 20:24:26 2024 +0800 - */ -package client - -import ( - "encoding/json" - "errors" - "net/http" - "strings" - - "gitee.com/openeuler/PilotGo/sdk/common" - "gitee.com/openeuler/PilotGo/sdk/utils/httputils" -) - -func (c *Client) RegisterPermission(pers []common.Permission) error { - for _, v := range pers { - if strings.Contains(v.Resource, "/") { - return errors.New("permission-resource string contains /") - } else { - c.permissions = append(c.permissions, v) - } - } - return nil -} - -func (c *Client) HasPermission(resource, operate string) (bool, error) { - if !c.IsBind() { - return false, errors.New("unbind PilotGo-server platform") - } - - url := "http://" + c.Server() + "/api/v1/pluginapi/permission" - p := &common.Permission{ - Resource: resource, - Operate: operate, - } - - r, err := httputils.Post(url, &httputils.Params{ - Body: p, - Cookie: map[string]string{ - TokenCookie: c.token, - }, - }) - if err != nil { - return false, err - } - - res := &struct { - Code int `json:"code"` - Message string `json:"msg"` - Data bool `json:"data"` - }{} - if err := json.Unmarshal(r.Body, res); err != nil { - return false, err - } - if res.Code != http.StatusOK { - return false, errors.New(res.Message) - } - return res.Data, nil -} diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/plugin.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/plugin.go deleted file mode 100644 index 3fb88227a327003a9b9860144f6f227df52ddac4..0000000000000000000000000000000000000000 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/plugin.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) KylinSoft Co., Ltd. 2024.All rights reserved. - * PilotGo licensed under the Mulan Permissive Software License, Version 2. - * See LICENSE file for more details. - * Author: zhanghan2021 - * Date: Wed Sep 27 17:35:12 2023 +0800 - */ -package client - -import ( - "encoding/json" - "errors" - - "gitee.com/openeuler/PilotGo/sdk/common" - "gitee.com/openeuler/PilotGo/sdk/utils/httputils" -) - -// 用于初始化Client -type PluginInfo struct { - MenuName string `json:"menuName"` - Name string `json:"name"` - Version string `json:"version"` - Description string `json:"description"` - Author string `json:"author"` - Email string `json:"email"` - Url string `json:"url"` - Icon string `json:"icon"` - PluginType string `json:"plugin_type"` - ReverseDest string `json:"reverse_dest"` -} - -// 用于插件与PilotGo server通讯 -type PluginFullInfo struct { - PluginInfo - Extentions []common.Extention - Permissions []common.Permission -} - -func (c *Client) GetPlugins() ([]*PluginInfo, error) { - if !c.IsBind() { - return nil, errors.New("unbind PilotGo-server platform") - } - url := "http://" + c.Server() + "/api/v1/pluginapi/plugins" - r, err := httputils.Get(url, &httputils.Params{ - Cookie: map[string]string{ - TokenCookie: c.token, - }, - }) - if err != nil { - return nil, err - } - - resp := struct { - Code int `json:"code"` - Data []*PluginInfo `json:"data"` - }{} - if err := json.Unmarshal(r.Body, &resp); err != nil { - return nil, err - } - - return resp.Data, nil -} diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/script.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/script.go index ccf9776b230ada7f7ef7d0ee88c5f1cf0287378a..05a2a5b68492e954e2ca0053a6f388b7a1fa1b13 100644 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/script.go +++ b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/script.go @@ -3,32 +3,27 @@ * PilotGo licensed under the Mulan Permissive Software License, Version 2. * See LICENSE file for more details. * Author: zhanghan2021 - * Date: Wed Sep 27 17:35:12 2023 +0800 + * Date: Wed Aug 06 17:35:12 2025 +0800 */ package client import ( "encoding/base64" "encoding/json" - "errors" + "fmt" "gitee.com/openeuler/PilotGo/sdk/common" + "gitee.com/openeuler/PilotGo/sdk/plugin/jwt" "gitee.com/openeuler/PilotGo/sdk/utils/httputils" ) -type CallbackHandler struct { - RunCommandCallback RunCommandCallback - TaskLen int -} - -type RunCommandCallback func([]*common.CmdResult) - func (c *Client) RunCommand(batch *common.Batch, cmd string) ([]*common.CmdResult, error) { - if !c.IsBind() { - return nil, errors.New("unbind PilotGo-server platform") + serverInfo, err := c.Registry.Get("pilotgo-server") + if err != nil { + return nil, err } - url := "http://" + c.Server() + "/api/v1/pluginapi/run_command" + url := fmt.Sprintf("http://%s:%s/api/v1/pluginapi/run_command", serverInfo.Address, serverInfo.Port) p := &common.CmdStruct{ Batch: batch, @@ -38,7 +33,7 @@ func (c *Client) RunCommand(batch *common.Batch, cmd string) ([]*common.CmdResul r, err := httputils.Post(url, &httputils.Params{ Body: p, Cookie: map[string]string{ - TokenCookie: c.token, + jwt.TokenCookie: c.token, }, }) if err != nil { @@ -64,10 +59,11 @@ type ScriptStruct struct { } func (c *Client) RunScript(batch *common.Batch, script string, params []string) ([]*common.CmdResult, error) { - if !c.IsBind() { - return nil, errors.New("unbind PilotGo-server platform") + serverInfo, err := c.Registry.Get("pilotgo-server") + if err != nil { + return nil, err } - url := "http://" + c.Server() + "/api/v1/pluginapi/run_script" + url := fmt.Sprintf("http://%s:%s/api/v1/pluginapi/run_script", serverInfo.Address, serverInfo.Port) p := &ScriptStruct{ Batch: batch, @@ -78,7 +74,7 @@ func (c *Client) RunScript(batch *common.Batch, script string, params []string) r, err := httputils.Post(url, &httputils.Params{ Body: p, Cookie: map[string]string{ - TokenCookie: c.token, + jwt.TokenCookie: c.token, }, }) if err != nil { @@ -98,10 +94,11 @@ func (c *Client) RunScript(batch *common.Batch, script string, params []string) } func (c *Client) RunCommandAsync(batch *common.Batch, cmd string, callback RunCommandCallback) error { - if !c.IsBind() { - return errors.New("unbind PilotGo-server platform") + serverInfo, err := c.Registry.Get("pilotgo-server") + if err != nil { + return err } - url := "http://" + c.Server() + "/api/v1/pluginapi/run_command_async?plugin_name=" + c.PluginInfo.Name + url := fmt.Sprintf("http://%s:%s/api/v1/pluginapi/run_command_async?plugin_name=", serverInfo.Address, serverInfo.Port) p := &common.CmdStruct{ Batch: batch, @@ -111,7 +108,7 @@ func (c *Client) RunCommandAsync(batch *common.Batch, cmd string, callback RunCo r, err := httputils.Post(url, &httputils.Params{ Body: p, Cookie: map[string]string{ - TokenCookie: c.token, + jwt.TokenCookie: c.token, }, }) if err != nil { diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/service.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/service.go index a2fe2c661aaf8f757ee66a2ba96f1d79dce2e338..d156576c4d8b0078763c675163f7fa5644956a57 100644 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/service.go +++ b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/service.go @@ -9,17 +9,19 @@ package client import ( "encoding/json" - "errors" + "fmt" "gitee.com/openeuler/PilotGo/sdk/common" + "gitee.com/openeuler/PilotGo/sdk/plugin/jwt" "gitee.com/openeuler/PilotGo/sdk/utils/httputils" ) func (c *Client) ServiceStatus(batch *common.Batch, servicename string) ([]*common.ServiceResult, error) { - if !c.IsBind() { - return nil, errors.New("unbind PilotGo-server platform") + serverInfo, err := c.Registry.Get("pilotgo-server") + if err != nil { + return []*common.ServiceResult{}, err } - url := c.Server() + "/api/v1/pluginapi/service/:name" + url := fmt.Sprintf("http://%s:%s/api/v1/pluginapi/service/:name", serverInfo.Address, serverInfo.Port) p := &common.ServiceStruct{ Batch: batch, @@ -29,7 +31,7 @@ func (c *Client) ServiceStatus(batch *common.Batch, servicename string) ([]*comm r, err := httputils.Put(url, &httputils.Params{ Body: p, Cookie: map[string]string{ - TokenCookie: c.token, + jwt.TokenCookie: c.token, }, }) if err != nil { @@ -45,10 +47,11 @@ func (c *Client) ServiceStatus(batch *common.Batch, servicename string) ([]*comm } func (c *Client) StartService(batch *common.Batch, serviceName string) ([]*common.ServiceResult, error) { - if !c.IsBind() { - return nil, errors.New("unbind PilotGo-server platform") + serverInfo, err := c.Registry.Get("pilotgo-server") + if err != nil { + return []*common.ServiceResult{}, err } - url := c.Server() + "/api/v1/pluginapi/start_service" + url := fmt.Sprintf("http://%s:%s/api/v1/pluginapi/start_service", serverInfo.Address, serverInfo.Port) p := &common.ServiceStruct{ Batch: batch, @@ -58,7 +61,7 @@ func (c *Client) StartService(batch *common.Batch, serviceName string) ([]*commo r, err := httputils.Put(url, &httputils.Params{ Body: p, Cookie: map[string]string{ - TokenCookie: c.token, + jwt.TokenCookie: c.token, }, }) if err != nil { @@ -74,10 +77,11 @@ func (c *Client) StartService(batch *common.Batch, serviceName string) ([]*commo } func (c *Client) StopService(batch *common.Batch, serviceName string) ([]*common.ServiceResult, error) { - if !c.IsBind() { - return nil, errors.New("unbind PilotGo-server platform") + serverInfo, err := c.Registry.Get("pilotgo-server") + if err != nil { + return []*common.ServiceResult{}, err } - url := c.Server() + "/api/v1/pluginapi/stop_service" + url := fmt.Sprintf("http://%s:%s/api/v1/pluginapi/stop_service", serverInfo.Address, serverInfo.Port) p := &common.ServiceStruct{ Batch: batch, @@ -87,7 +91,7 @@ func (c *Client) StopService(batch *common.Batch, serviceName string) ([]*common r, err := httputils.Put(url, &httputils.Params{ Body: p, Cookie: map[string]string{ - TokenCookie: c.token, + jwt.TokenCookie: c.token, }, }) if err != nil { diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/extention.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/tags.go similarity index 45% rename from vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/extention.go rename to vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/tags.go index 1f7955035ebd2c3514e1fad54e01576fcac27a09..d0da97547752b176894f192f8fa76c5e4116c758 100644 --- a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/extention.go +++ b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/client/tags.go @@ -2,15 +2,11 @@ * Copyright (c) KylinSoft Co., Ltd. 2024.All rights reserved. * PilotGo licensed under the Mulan Permissive Software License, Version 2. * See LICENSE file for more details. - * Author: Gzx1999 - * Date: Tue Nov 7 15:01:17 2023 +0800 + * Author: zhanghan2021 + * Date: Wed Aug 06 17:35:12 2025 +0800 */ package client -import ( - "gitee.com/openeuler/PilotGo/sdk/common" -) - -func (c *Client) RegisterExtention(exts []common.Extention) { - c.extentions = append(c.extentions, exts...) +func (c *Client) OnGetTags(callback GetTagsCallback) { + c.getTagsCallback = callback } diff --git a/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/jwt/jwt.go b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/jwt/jwt.go new file mode 100644 index 0000000000000000000000000000000000000000..cf1fb02e53acb04967661d4f48203a5a6f8571d9 --- /dev/null +++ b/vendor/gitee.com/openeuler/PilotGo/sdk/plugin/jwt/jwt.go @@ -0,0 +1,97 @@ +/* + * Copyright (c) KylinSoft Co., Ltd. 2024.All rights reserved. + * PilotGo licensed under the Mulan Permissive Software License, Version 2. + * See LICENSE file for more details. + * Author: zhanghan + * Date: Thu Aug 07 16:18:53 2025 +0800 + */ +package jwt + +import ( + "errors" + "fmt" + "time" + + "github.com/dgrijalva/jwt-go" + "github.com/gin-gonic/gin" +) + +var Issue = "PilotGo" + +const ( + TokenCookie = "PluginToken" +) + +type PluginServiceClaims struct { + jwt.StandardClaims + + ServiceName string +} + +func GeneratePluginServiceToken(serviceName string) (string, error) { + claims := &PluginServiceClaims{ + ServiceName: serviceName, + + StandardClaims: jwt.StandardClaims{ + IssuedAt: time.Now().Unix(), + Issuer: Issue, + Subject: "plugin token", + }, + } + token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + tokenString, err := token.SignedString([]byte(serviceName)) + if err != nil { + return "", err + } + return tokenString, nil +} + +func ParsePluginServiceClaims(c *gin.Context) (*PluginServiceClaims, error) { + cookie, err := c.Request.Cookie(TokenCookie) + if err != nil { + return nil, err + } + + jwtSecretKey, err := getJWTSecretKeyForService(cookie.Value) + if err != nil { + return nil, err + } + + claims, err := parseClaims(cookie.Value, jwtSecretKey, &PluginServiceClaims{}) + if err != nil { + return nil, err + } + m, ok := claims.(*PluginServiceClaims) + if !ok { + return nil, errors.New("invalid plugin claims") + } + return m, nil +} + +func parseClaims(tokenString string, jwtSecretKey string, claims jwt.Claims) (jwt.Claims, error) { + if tokenString == "" { + return nil, fmt.Errorf("token is empty") + } + token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (i interface{}, err error) { + return []byte(jwtSecretKey), nil + }) + if err != nil { + return nil, fmt.Errorf("failed to parse token: %w", err) + } + + if token != nil && !token.Valid { + return nil, fmt.Errorf("token is invalid") + } + + return token.Claims, nil +} + +func getJWTSecretKeyForService(tokenString string) (string, error) { + parser := new(jwt.Parser) + tempClaims := &PluginServiceClaims{} + _, _, err := parser.ParseUnverified(tokenString, tempClaims) + if err != nil { + return "", fmt.Errorf("failed to parse token without verifying: %s", err.Error()) + } + return tempClaims.ServiceName, nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/.gitignore b/vendor/github.com/dgrijalva/jwt-go/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..80bed650ec039eb0d7bde5768e628c21c732c4a3 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/.gitignore @@ -0,0 +1,4 @@ +.DS_Store +bin + + diff --git a/vendor/github.com/dgrijalva/jwt-go/.travis.yml b/vendor/github.com/dgrijalva/jwt-go/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..1027f56cd94db30d0990d8a5ff935fa28d588827 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/.travis.yml @@ -0,0 +1,13 @@ +language: go + +script: + - go vet ./... + - go test -v ./... + +go: + - 1.3 + - 1.4 + - 1.5 + - 1.6 + - 1.7 + - tip diff --git a/vendor/github.com/dgrijalva/jwt-go/LICENSE b/vendor/github.com/dgrijalva/jwt-go/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..df83a9c2f0192f255c4130683558342ec4479f83 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/LICENSE @@ -0,0 +1,8 @@ +Copyright (c) 2012 Dave Grijalva + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md b/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md new file mode 100644 index 0000000000000000000000000000000000000000..7fc1f793cbc4e7fa3d2b88949f6769e948a5e7de --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/MIGRATION_GUIDE.md @@ -0,0 +1,97 @@ +## Migration Guide from v2 -> v3 + +Version 3 adds several new, frequently requested features. To do so, it introduces a few breaking changes. We've worked to keep these as minimal as possible. This guide explains the breaking changes and how you can quickly update your code. + +### `Token.Claims` is now an interface type + +The most requested feature from the 2.0 verison of this library was the ability to provide a custom type to the JSON parser for claims. This was implemented by introducing a new interface, `Claims`, to replace `map[string]interface{}`. We also included two concrete implementations of `Claims`: `MapClaims` and `StandardClaims`. + +`MapClaims` is an alias for `map[string]interface{}` with built in validation behavior. It is the default claims type when using `Parse`. The usage is unchanged except you must type cast the claims property. + +The old example for parsing a token looked like this.. + +```go + if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { + fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) + } +``` + +is now directly mapped to... + +```go + if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { + claims := token.Claims.(jwt.MapClaims) + fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) + } +``` + +`StandardClaims` is designed to be embedded in your custom type. You can supply a custom claims type with the new `ParseWithClaims` function. Here's an example of using a custom claims type. + +```go + type MyCustomClaims struct { + User string + *StandardClaims + } + + if token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, keyLookupFunc); err == nil { + claims := token.Claims.(*MyCustomClaims) + fmt.Printf("Token for user %v expires %v", claims.User, claims.StandardClaims.ExpiresAt) + } +``` + +### `ParseFromRequest` has been moved + +To keep this library focused on the tokens without becoming overburdened with complex request processing logic, `ParseFromRequest` and its new companion `ParseFromRequestWithClaims` have been moved to a subpackage, `request`. The method signatues have also been augmented to receive a new argument: `Extractor`. + +`Extractors` do the work of picking the token string out of a request. The interface is simple and composable. + +This simple parsing example: + +```go + if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil { + fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) + } +``` + +is directly mapped to: + +```go + if token, err := request.ParseFromRequest(req, request.OAuth2Extractor, keyLookupFunc); err == nil { + claims := token.Claims.(jwt.MapClaims) + fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) + } +``` + +There are several concrete `Extractor` types provided for your convenience: + +* `HeaderExtractor` will search a list of headers until one contains content. +* `ArgumentExtractor` will search a list of keys in request query and form arguments until one contains content. +* `MultiExtractor` will try a list of `Extractors` in order until one returns content. +* `AuthorizationHeaderExtractor` will look in the `Authorization` header for a `Bearer` token. +* `OAuth2Extractor` searches the places an OAuth2 token would be specified (per the spec): `Authorization` header and `access_token` argument +* `PostExtractionFilter` wraps an `Extractor`, allowing you to process the content before it's parsed. A simple example is stripping the `Bearer ` text from a header + + +### RSA signing methods no longer accept `[]byte` keys + +Due to a [critical vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/), we've decided the convenience of accepting `[]byte` instead of `rsa.PublicKey` or `rsa.PrivateKey` isn't worth the risk of misuse. + +To replace this behavior, we've added two helper methods: `ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)` and `ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)`. These are just simple helpers for unpacking PEM encoded PKCS1 and PKCS8 keys. If your keys are encoded any other way, all you need to do is convert them to the `crypto/rsa` package's types. + +```go + func keyLookupFunc(*Token) (interface{}, error) { + // Don't forget to validate the alg is what you expect: + if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { + return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) + } + + // Look up key + key, err := lookupPublicKey(token.Header["kid"]) + if err != nil { + return nil, err + } + + // Unpack key from PEM encoded PKCS8 + return jwt.ParseRSAPublicKeyFromPEM(key) + } +``` diff --git a/vendor/github.com/dgrijalva/jwt-go/README.md b/vendor/github.com/dgrijalva/jwt-go/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d358d881b8dde053f07b96db1257b71dce250d08 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/README.md @@ -0,0 +1,100 @@ +# jwt-go + +[![Build Status](https://travis-ci.org/dgrijalva/jwt-go.svg?branch=master)](https://travis-ci.org/dgrijalva/jwt-go) +[![GoDoc](https://godoc.org/github.com/dgrijalva/jwt-go?status.svg)](https://godoc.org/github.com/dgrijalva/jwt-go) + +A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) + +**NEW VERSION COMING:** There have been a lot of improvements suggested since the version 3.0.0 released in 2016. I'm working now on cutting two different releases: 3.2.0 will contain any non-breaking changes or enhancements. 4.0.0 will follow shortly which will include breaking changes. See the 4.0.0 milestone to get an idea of what's coming. If you have other ideas, or would like to participate in 4.0.0, now's the time. If you depend on this library and don't want to be interrupted, I recommend you use your dependency mangement tool to pin to version 3. + +**SECURITY NOTICE:** Some older versions of Go have a security issue in the cryotp/elliptic. Recommendation is to upgrade to at least 1.8.3. See issue #216 for more detail. + +**SECURITY NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided. + +## What the heck is a JWT? + +JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens. + +In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](http://tools.ietf.org/html/rfc4648) encoded. The last part is the signature, encoded the same way. + +The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used. + +The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [the RFC](http://self-issued.info/docs/draft-jones-json-web-token.html) for information about reserved keys and the proper way to add your own. + +## What's in the box? + +This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own. + +## Examples + +See [the project documentation](https://godoc.org/github.com/dgrijalva/jwt-go) for examples of usage: + +* [Simple example of parsing and validating a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac) +* [Simple example of building and signing a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac) +* [Directory of Examples](https://godoc.org/github.com/dgrijalva/jwt-go#pkg-examples) + +## Extensions + +This library publishes all the necessary components for adding your own signing methods. Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod`. + +Here's an example of an extension that integrates with the Google App Engine signing tools: https://github.com/someone1/gcp-jwt-go + +## Compliance + +This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences: + +* In order to protect against accidental use of [Unsecured JWTs](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#UnsecuredJWT), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key. + +## Project Status & Versioning + +This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason). + +This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases). + +While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v3`. It will do the right thing WRT semantic versioning. + +**BREAKING CHANGES:*** +* Version 3.0.0 includes _a lot_ of changes from the 2.x line, including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code. + +## Usage Tips + +### Signing vs Encryption + +A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data: + +* The author of the token was in the possession of the signing secret +* The data has not been modified since it was signed + +It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library. + +### Choosing a Signing Method + +There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric. + +Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation. + +Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification. + +### Signing Methods and Key Types + +Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones: + +* The [HMAC signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation +* The [RSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation +* The [ECDSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation + +### JWT and OAuth + +It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication. + +Without going too far down the rabbit hole, here's a description of the interaction of these technologies: + +* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth. +* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token. +* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL. + +## More + +Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go). + +The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation. diff --git a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..6370298313a63eae893676e9133b66f1b3fabcf6 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md @@ -0,0 +1,118 @@ +## `jwt-go` Version History + +#### 3.2.0 + +* Added method `ParseUnverified` to allow users to split up the tasks of parsing and validation +* HMAC signing method returns `ErrInvalidKeyType` instead of `ErrInvalidKey` where appropriate +* Added options to `request.ParseFromRequest`, which allows for an arbitrary list of modifiers to parsing behavior. Initial set include `WithClaims` and `WithParser`. Existing usage of this function will continue to work as before. +* Deprecated `ParseFromRequestWithClaims` to simplify API in the future. + +#### 3.1.0 + +* Improvements to `jwt` command line tool +* Added `SkipClaimsValidation` option to `Parser` +* Documentation updates + +#### 3.0.0 + +* **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code + * Dropped support for `[]byte` keys when using RSA signing methods. This convenience feature could contribute to security vulnerabilities involving mismatched key types with signing methods. + * `ParseFromRequest` has been moved to `request` subpackage and usage has changed + * The `Claims` property on `Token` is now type `Claims` instead of `map[string]interface{}`. The default value is type `MapClaims`, which is an alias to `map[string]interface{}`. This makes it possible to use a custom type when decoding claims. +* Other Additions and Changes + * Added `Claims` interface type to allow users to decode the claims into a custom type + * Added `ParseWithClaims`, which takes a third argument of type `Claims`. Use this function instead of `Parse` if you have a custom type you'd like to decode into. + * Dramatically improved the functionality and flexibility of `ParseFromRequest`, which is now in the `request` subpackage + * Added `ParseFromRequestWithClaims` which is the `FromRequest` equivalent of `ParseWithClaims` + * Added new interface type `Extractor`, which is used for extracting JWT strings from http requests. Used with `ParseFromRequest` and `ParseFromRequestWithClaims`. + * Added several new, more specific, validation errors to error type bitmask + * Moved examples from README to executable example files + * Signing method registry is now thread safe + * Added new property to `ValidationError`, which contains the raw error returned by calls made by parse/verify (such as those returned by keyfunc or json parser) + +#### 2.7.0 + +This will likely be the last backwards compatible release before 3.0.0, excluding essential bug fixes. + +* Added new option `-show` to the `jwt` command that will just output the decoded token without verifying +* Error text for expired tokens includes how long it's been expired +* Fixed incorrect error returned from `ParseRSAPublicKeyFromPEM` +* Documentation updates + +#### 2.6.0 + +* Exposed inner error within ValidationError +* Fixed validation errors when using UseJSONNumber flag +* Added several unit tests + +#### 2.5.0 + +* Added support for signing method none. You shouldn't use this. The API tries to make this clear. +* Updated/fixed some documentation +* Added more helpful error message when trying to parse tokens that begin with `BEARER ` + +#### 2.4.0 + +* Added new type, Parser, to allow for configuration of various parsing parameters + * You can now specify a list of valid signing methods. Anything outside this set will be rejected. + * You can now opt to use the `json.Number` type instead of `float64` when parsing token JSON +* Added support for [Travis CI](https://travis-ci.org/dgrijalva/jwt-go) +* Fixed some bugs with ECDSA parsing + +#### 2.3.0 + +* Added support for ECDSA signing methods +* Added support for RSA PSS signing methods (requires go v1.4) + +#### 2.2.0 + +* Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic. + +#### 2.1.0 + +Backwards compatible API change that was missed in 2.0.0. + +* The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte` + +#### 2.0.0 + +There were two major reasons for breaking backwards compatibility with this update. The first was a refactor required to expand the width of the RSA and HMAC-SHA signing implementations. There will likely be no required code changes to support this change. + +The second update, while unfortunately requiring a small change in integration, is required to open up this library to other signing methods. Not all keys used for all signing methods have a single standard on-disk representation. Requiring `[]byte` as the type for all keys proved too limiting. Additionally, this implementation allows for pre-parsed tokens to be reused, which might matter in an application that parses a high volume of tokens with a small set of keys. Backwards compatibilty has been maintained for passing `[]byte` to the RSA signing methods, but they will also accept `*rsa.PublicKey` and `*rsa.PrivateKey`. + +It is likely the only integration change required here will be to change `func(t *jwt.Token) ([]byte, error)` to `func(t *jwt.Token) (interface{}, error)` when calling `Parse`. + +* **Compatibility Breaking Changes** + * `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct` + * `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct` + * `KeyFunc` now returns `interface{}` instead of `[]byte` + * `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key + * `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key +* Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type. + * Added public package global `SigningMethodHS256` + * Added public package global `SigningMethodHS384` + * Added public package global `SigningMethodHS512` +* Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type. + * Added public package global `SigningMethodRS256` + * Added public package global `SigningMethodRS384` + * Added public package global `SigningMethodRS512` +* Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged. +* Refactored the RSA implementation to be easier to read +* Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` + +#### 1.0.2 + +* Fixed bug in parsing public keys from certificates +* Added more tests around the parsing of keys for RS256 +* Code refactoring in RS256 implementation. No functional changes + +#### 1.0.1 + +* Fixed panic if RS256 signing method was passed an invalid key + +#### 1.0.0 + +* First versioned release +* API stabilized +* Supports creating, signing, parsing, and validating JWT tokens +* Supports RS256 and HS256 signing methods \ No newline at end of file diff --git a/vendor/github.com/dgrijalva/jwt-go/claims.go b/vendor/github.com/dgrijalva/jwt-go/claims.go new file mode 100644 index 0000000000000000000000000000000000000000..f0228f02e033704327b9dc2b9e0ad01abac58d2e --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/claims.go @@ -0,0 +1,134 @@ +package jwt + +import ( + "crypto/subtle" + "fmt" + "time" +) + +// For a type to be a Claims object, it must just have a Valid method that determines +// if the token is invalid for any supported reason +type Claims interface { + Valid() error +} + +// Structured version of Claims Section, as referenced at +// https://tools.ietf.org/html/rfc7519#section-4.1 +// See examples for how to use this with your own claim types +type StandardClaims struct { + Audience string `json:"aud,omitempty"` + ExpiresAt int64 `json:"exp,omitempty"` + Id string `json:"jti,omitempty"` + IssuedAt int64 `json:"iat,omitempty"` + Issuer string `json:"iss,omitempty"` + NotBefore int64 `json:"nbf,omitempty"` + Subject string `json:"sub,omitempty"` +} + +// Validates time based claims "exp, iat, nbf". +// There is no accounting for clock skew. +// As well, if any of the above claims are not in the token, it will still +// be considered a valid claim. +func (c StandardClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() + + // The claims below are optional, by default, so if they are set to the + // default value in Go, let's not fail the verification for them. + if c.VerifyExpiresAt(now, false) == false { + delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) + vErr.Inner = fmt.Errorf("token is expired by %v", delta) + vErr.Errors |= ValidationErrorExpired + } + + if c.VerifyIssuedAt(now, false) == false { + vErr.Inner = fmt.Errorf("Token used before issued") + vErr.Errors |= ValidationErrorIssuedAt + } + + if c.VerifyNotBefore(now, false) == false { + vErr.Inner = fmt.Errorf("token is not valid yet") + vErr.Errors |= ValidationErrorNotValidYet + } + + if vErr.valid() { + return nil + } + + return vErr +} + +// Compares the aud claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { + return verifyAud(c.Audience, cmp, req) +} + +// Compares the exp claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { + return verifyExp(c.ExpiresAt, cmp, req) +} + +// Compares the iat claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { + return verifyIat(c.IssuedAt, cmp, req) +} + +// Compares the iss claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { + return verifyIss(c.Issuer, cmp, req) +} + +// Compares the nbf claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { + return verifyNbf(c.NotBefore, cmp, req) +} + +// ----- helpers + +func verifyAud(aud string, cmp string, required bool) bool { + if aud == "" { + return !required + } + if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 { + return true + } else { + return false + } +} + +func verifyExp(exp int64, now int64, required bool) bool { + if exp == 0 { + return !required + } + return now <= exp +} + +func verifyIat(iat int64, now int64, required bool) bool { + if iat == 0 { + return !required + } + return now >= iat +} + +func verifyIss(iss string, cmp string, required bool) bool { + if iss == "" { + return !required + } + if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { + return true + } else { + return false + } +} + +func verifyNbf(nbf int64, now int64, required bool) bool { + if nbf == 0 { + return !required + } + return now >= nbf +} diff --git a/vendor/github.com/dgrijalva/jwt-go/doc.go b/vendor/github.com/dgrijalva/jwt-go/doc.go new file mode 100644 index 0000000000000000000000000000000000000000..a86dc1a3b348cd1a3cf0730da9936f36098268a2 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/doc.go @@ -0,0 +1,4 @@ +// Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html +// +// See README.md for more info. +package jwt diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go new file mode 100644 index 0000000000000000000000000000000000000000..f977381240e394435fcc524f66a5f35cf5890582 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go @@ -0,0 +1,148 @@ +package jwt + +import ( + "crypto" + "crypto/ecdsa" + "crypto/rand" + "errors" + "math/big" +) + +var ( + // Sadly this is missing from crypto/ecdsa compared to crypto/rsa + ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") +) + +// Implements the ECDSA family of signing methods signing methods +// Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification +type SigningMethodECDSA struct { + Name string + Hash crypto.Hash + KeySize int + CurveBits int +} + +// Specific instances for EC256 and company +var ( + SigningMethodES256 *SigningMethodECDSA + SigningMethodES384 *SigningMethodECDSA + SigningMethodES512 *SigningMethodECDSA +) + +func init() { + // ES256 + SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} + RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { + return SigningMethodES256 + }) + + // ES384 + SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} + RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { + return SigningMethodES384 + }) + + // ES512 + SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} + RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { + return SigningMethodES512 + }) +} + +func (m *SigningMethodECDSA) Alg() string { + return m.Name +} + +// Implements the Verify method from SigningMethod +// For this verify method, key must be an ecdsa.PublicKey struct +func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { + var err error + + // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } + + // Get the key + var ecdsaKey *ecdsa.PublicKey + switch k := key.(type) { + case *ecdsa.PublicKey: + ecdsaKey = k + default: + return ErrInvalidKeyType + } + + if len(sig) != 2*m.KeySize { + return ErrECDSAVerification + } + + r := big.NewInt(0).SetBytes(sig[:m.KeySize]) + s := big.NewInt(0).SetBytes(sig[m.KeySize:]) + + // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Verify the signature + if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true { + return nil + } else { + return ErrECDSAVerification + } +} + +// Implements the Sign method from SigningMethod +// For this signing method, key must be an ecdsa.PrivateKey struct +func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { + // Get the key + var ecdsaKey *ecdsa.PrivateKey + switch k := key.(type) { + case *ecdsa.PrivateKey: + ecdsaKey = k + default: + return "", ErrInvalidKeyType + } + + // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Sign the string and return r, s + if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { + curveBits := ecdsaKey.Curve.Params().BitSize + + if m.CurveBits != curveBits { + return "", ErrInvalidKey + } + + keyBytes := curveBits / 8 + if curveBits%8 > 0 { + keyBytes += 1 + } + + // We serialize the outpus (r and s) into big-endian byte arrays and pad + // them with zeros on the left to make sure the sizes work out. Both arrays + // must be keyBytes long, and the output must be 2*keyBytes long. + rBytes := r.Bytes() + rBytesPadded := make([]byte, keyBytes) + copy(rBytesPadded[keyBytes-len(rBytes):], rBytes) + + sBytes := s.Bytes() + sBytesPadded := make([]byte, keyBytes) + copy(sBytesPadded[keyBytes-len(sBytes):], sBytes) + + out := append(rBytesPadded, sBytesPadded...) + + return EncodeSegment(out), nil + } else { + return "", err + } +} diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go new file mode 100644 index 0000000000000000000000000000000000000000..d19624b7264fb305cf7190c55a34b265a4f0e15f --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go @@ -0,0 +1,67 @@ +package jwt + +import ( + "crypto/ecdsa" + "crypto/x509" + "encoding/pem" + "errors" +) + +var ( + ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") + ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") +) + +// Parse PEM encoded Elliptic Curve Private Key Structure +func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { + return nil, err + } + + var pkey *ecdsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { + return nil, ErrNotECPrivateKey + } + + return pkey, nil +} + +// Parse PEM encoded PKCS1 or PKCS8 public key +func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + return nil, err + } + } + + var pkey *ecdsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { + return nil, ErrNotECPublicKey + } + + return pkey, nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/errors.go b/vendor/github.com/dgrijalva/jwt-go/errors.go new file mode 100644 index 0000000000000000000000000000000000000000..1c93024aad2ea97b1bd2b944066d20145a69f1ce --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/errors.go @@ -0,0 +1,59 @@ +package jwt + +import ( + "errors" +) + +// Error constants +var ( + ErrInvalidKey = errors.New("key is invalid") + ErrInvalidKeyType = errors.New("key is of invalid type") + ErrHashUnavailable = errors.New("the requested hash function is unavailable") +) + +// The errors that might occur when parsing and validating a token +const ( + ValidationErrorMalformed uint32 = 1 << iota // Token is malformed + ValidationErrorUnverifiable // Token could not be verified because of signing problems + ValidationErrorSignatureInvalid // Signature validation failed + + // Standard Claim validation errors + ValidationErrorAudience // AUD validation failed + ValidationErrorExpired // EXP validation failed + ValidationErrorIssuedAt // IAT validation failed + ValidationErrorIssuer // ISS validation failed + ValidationErrorNotValidYet // NBF validation failed + ValidationErrorId // JTI validation failed + ValidationErrorClaimsInvalid // Generic claims validation error +) + +// Helper for constructing a ValidationError with a string error message +func NewValidationError(errorText string, errorFlags uint32) *ValidationError { + return &ValidationError{ + text: errorText, + Errors: errorFlags, + } +} + +// The error from Parse if token is not valid +type ValidationError struct { + Inner error // stores the error returned by external dependencies, i.e.: KeyFunc + Errors uint32 // bitfield. see ValidationError... constants + text string // errors that do not have a valid error just have text +} + +// Validation error is an error type +func (e ValidationError) Error() string { + if e.Inner != nil { + return e.Inner.Error() + } else if e.text != "" { + return e.text + } else { + return "token is invalid" + } +} + +// No errors +func (e *ValidationError) valid() bool { + return e.Errors == 0 +} diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac.go b/vendor/github.com/dgrijalva/jwt-go/hmac.go new file mode 100644 index 0000000000000000000000000000000000000000..addbe5d401829cb555ebd16b7d6e5e7b6eacc3c9 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/hmac.go @@ -0,0 +1,95 @@ +package jwt + +import ( + "crypto" + "crypto/hmac" + "errors" +) + +// Implements the HMAC-SHA family of signing methods signing methods +// Expects key type of []byte for both signing and validation +type SigningMethodHMAC struct { + Name string + Hash crypto.Hash +} + +// Specific instances for HS256 and company +var ( + SigningMethodHS256 *SigningMethodHMAC + SigningMethodHS384 *SigningMethodHMAC + SigningMethodHS512 *SigningMethodHMAC + ErrSignatureInvalid = errors.New("signature is invalid") +) + +func init() { + // HS256 + SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { + return SigningMethodHS256 + }) + + // HS384 + SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { + return SigningMethodHS384 + }) + + // HS512 + SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { + return SigningMethodHS512 + }) +} + +func (m *SigningMethodHMAC) Alg() string { + return m.Name +} + +// Verify the signature of HSXXX tokens. Returns nil if the signature is valid. +func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { + // Verify the key is the right type + keyBytes, ok := key.([]byte) + if !ok { + return ErrInvalidKeyType + } + + // Decode signature, for comparison + sig, err := DecodeSegment(signature) + if err != nil { + return err + } + + // Can we use the specified hashing method? + if !m.Hash.Available() { + return ErrHashUnavailable + } + + // This signing method is symmetric, so we validate the signature + // by reproducing the signature from the signing string and key, then + // comparing that against the provided signature. + hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) + if !hmac.Equal(sig, hasher.Sum(nil)) { + return ErrSignatureInvalid + } + + // No validation errors. Signature is good. + return nil +} + +// Implements the Sign method from SigningMethod for this signing method. +// Key must be []byte +func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { + if keyBytes, ok := key.([]byte); ok { + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) + + return EncodeSegment(hasher.Sum(nil)), nil + } + + return "", ErrInvalidKeyType +} diff --git a/vendor/github.com/dgrijalva/jwt-go/map_claims.go b/vendor/github.com/dgrijalva/jwt-go/map_claims.go new file mode 100644 index 0000000000000000000000000000000000000000..291213c460d45e44a000d30d916162c0c499355a --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/map_claims.go @@ -0,0 +1,94 @@ +package jwt + +import ( + "encoding/json" + "errors" + // "fmt" +) + +// Claims type that uses the map[string]interface{} for JSON decoding +// This is the default claims type if you don't supply one +type MapClaims map[string]interface{} + +// Compares the aud claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyAudience(cmp string, req bool) bool { + aud, _ := m["aud"].(string) + return verifyAud(aud, cmp, req) +} + +// Compares the exp claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { + switch exp := m["exp"].(type) { + case float64: + return verifyExp(int64(exp), cmp, req) + case json.Number: + v, _ := exp.Int64() + return verifyExp(v, cmp, req) + } + return req == false +} + +// Compares the iat claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { + switch iat := m["iat"].(type) { + case float64: + return verifyIat(int64(iat), cmp, req) + case json.Number: + v, _ := iat.Int64() + return verifyIat(v, cmp, req) + } + return req == false +} + +// Compares the iss claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { + iss, _ := m["iss"].(string) + return verifyIss(iss, cmp, req) +} + +// Compares the nbf claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { + switch nbf := m["nbf"].(type) { + case float64: + return verifyNbf(int64(nbf), cmp, req) + case json.Number: + v, _ := nbf.Int64() + return verifyNbf(v, cmp, req) + } + return req == false +} + +// Validates time based claims "exp, iat, nbf". +// There is no accounting for clock skew. +// As well, if any of the above claims are not in the token, it will still +// be considered a valid claim. +func (m MapClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() + + if m.VerifyExpiresAt(now, false) == false { + vErr.Inner = errors.New("Token is expired") + vErr.Errors |= ValidationErrorExpired + } + + if m.VerifyIssuedAt(now, false) == false { + vErr.Inner = errors.New("Token used before issued") + vErr.Errors |= ValidationErrorIssuedAt + } + + if m.VerifyNotBefore(now, false) == false { + vErr.Inner = errors.New("Token is not valid yet") + vErr.Errors |= ValidationErrorNotValidYet + } + + if vErr.valid() { + return nil + } + + return vErr +} diff --git a/vendor/github.com/dgrijalva/jwt-go/none.go b/vendor/github.com/dgrijalva/jwt-go/none.go new file mode 100644 index 0000000000000000000000000000000000000000..f04d189d067bec2c78f6214e0038e470a0ffe3d0 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/none.go @@ -0,0 +1,52 @@ +package jwt + +// Implements the none signing method. This is required by the spec +// but you probably should never use it. +var SigningMethodNone *signingMethodNone + +const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" + +var NoneSignatureTypeDisallowedError error + +type signingMethodNone struct{} +type unsafeNoneMagicConstant string + +func init() { + SigningMethodNone = &signingMethodNone{} + NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) + + RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { + return SigningMethodNone + }) +} + +func (m *signingMethodNone) Alg() string { + return "none" +} + +// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key +func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { + // Key must be UnsafeAllowNoneSignatureType to prevent accidentally + // accepting 'none' signing method + if _, ok := key.(unsafeNoneMagicConstant); !ok { + return NoneSignatureTypeDisallowedError + } + // If signing method is none, signature must be an empty string + if signature != "" { + return NewValidationError( + "'none' signing method with non-empty signature", + ValidationErrorSignatureInvalid, + ) + } + + // Accept 'none' signing method. + return nil +} + +// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key +func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { + if _, ok := key.(unsafeNoneMagicConstant); ok { + return "", nil + } + return "", NoneSignatureTypeDisallowedError +} diff --git a/vendor/github.com/dgrijalva/jwt-go/parser.go b/vendor/github.com/dgrijalva/jwt-go/parser.go new file mode 100644 index 0000000000000000000000000000000000000000..d6901d9adb52bde1914ed614bc97f0a4a47057fb --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/parser.go @@ -0,0 +1,148 @@ +package jwt + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" +) + +type Parser struct { + ValidMethods []string // If populated, only these methods will be considered valid + UseJSONNumber bool // Use JSON Number format in JSON decoder + SkipClaimsValidation bool // Skip claims validation during token parsing +} + +// Parse, validate, and return a token. +// keyFunc will receive the parsed token and should return the key for validating. +// If everything is kosher, err will be nil +func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) +} + +func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + token, parts, err := p.ParseUnverified(tokenString, claims) + if err != nil { + return token, err + } + + // Verify signing method is in the required set + if p.ValidMethods != nil { + var signingMethodValid = false + var alg = token.Method.Alg() + for _, m := range p.ValidMethods { + if m == alg { + signingMethodValid = true + break + } + } + if !signingMethodValid { + // signing method is not in the listed set + return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) + } + } + + // Lookup key + var key interface{} + if keyFunc == nil { + // keyFunc was not provided. short circuiting validation + return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) + } + if key, err = keyFunc(token); err != nil { + // keyFunc returned an error + if ve, ok := err.(*ValidationError); ok { + return token, ve + } + return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} + } + + vErr := &ValidationError{} + + // Validate Claims + if !p.SkipClaimsValidation { + if err := token.Claims.Valid(); err != nil { + + // If the Claims Valid returned an error, check if it is a validation error, + // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set + if e, ok := err.(*ValidationError); !ok { + vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} + } else { + vErr = e + } + } + } + + // Perform validation + token.Signature = parts[2] + if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { + vErr.Inner = err + vErr.Errors |= ValidationErrorSignatureInvalid + } + + if vErr.valid() { + token.Valid = true + return token, nil + } + + return token, vErr +} + +// WARNING: Don't use this method unless you know what you're doing +// +// This method parses the token but doesn't validate the signature. It's only +// ever useful in cases where you know the signature is valid (because it has +// been checked previously in the stack) and you want to extract values from +// it. +func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { + parts = strings.Split(tokenString, ".") + if len(parts) != 3 { + return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) + } + + token = &Token{Raw: tokenString} + + // parse Header + var headerBytes []byte + if headerBytes, err = DecodeSegment(parts[0]); err != nil { + if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { + return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) + } + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + if err = json.Unmarshal(headerBytes, &token.Header); err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + + // parse Claims + var claimBytes []byte + token.Claims = claims + + if claimBytes, err = DecodeSegment(parts[1]); err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) + if p.UseJSONNumber { + dec.UseNumber() + } + // JSON Decode. Special case for map type to avoid weird pointer behavior + if c, ok := token.Claims.(MapClaims); ok { + err = dec.Decode(&c) + } else { + err = dec.Decode(&claims) + } + // Handle decode error + if err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + + // Lookup signature method + if method, ok := token.Header["alg"].(string); ok { + if token.Method = GetSigningMethod(method); token.Method == nil { + return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) + } + } else { + return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) + } + + return token, parts, nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa.go b/vendor/github.com/dgrijalva/jwt-go/rsa.go new file mode 100644 index 0000000000000000000000000000000000000000..e4caf1ca4a1160aeca417e8a0c9413c6c3097c14 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/rsa.go @@ -0,0 +1,101 @@ +package jwt + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" +) + +// Implements the RSA family of signing methods signing methods +// Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation +type SigningMethodRSA struct { + Name string + Hash crypto.Hash +} + +// Specific instances for RS256 and company +var ( + SigningMethodRS256 *SigningMethodRSA + SigningMethodRS384 *SigningMethodRSA + SigningMethodRS512 *SigningMethodRSA +) + +func init() { + // RS256 + SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { + return SigningMethodRS256 + }) + + // RS384 + SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { + return SigningMethodRS384 + }) + + // RS512 + SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { + return SigningMethodRS512 + }) +} + +func (m *SigningMethodRSA) Alg() string { + return m.Name +} + +// Implements the Verify method from SigningMethod +// For this signing method, must be an *rsa.PublicKey structure. +func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { + var err error + + // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } + + var rsaKey *rsa.PublicKey + var ok bool + + if rsaKey, ok = key.(*rsa.PublicKey); !ok { + return ErrInvalidKeyType + } + + // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Verify the signature + return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) +} + +// Implements the Sign method from SigningMethod +// For this signing method, must be an *rsa.PrivateKey structure. +func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { + var rsaKey *rsa.PrivateKey + var ok bool + + // Validate type of key + if rsaKey, ok = key.(*rsa.PrivateKey); !ok { + return "", ErrInvalidKey + } + + // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { + return EncodeSegment(sigBytes), nil + } else { + return "", err + } +} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go new file mode 100644 index 0000000000000000000000000000000000000000..10ee9db8a4ed65e118f8f6611b7f47c0b0e0512f --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go @@ -0,0 +1,126 @@ +// +build go1.4 + +package jwt + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" +) + +// Implements the RSAPSS family of signing methods signing methods +type SigningMethodRSAPSS struct { + *SigningMethodRSA + Options *rsa.PSSOptions +} + +// Specific instances for RS/PS and company +var ( + SigningMethodPS256 *SigningMethodRSAPSS + SigningMethodPS384 *SigningMethodRSAPSS + SigningMethodPS512 *SigningMethodRSAPSS +) + +func init() { + // PS256 + SigningMethodPS256 = &SigningMethodRSAPSS{ + &SigningMethodRSA{ + Name: "PS256", + Hash: crypto.SHA256, + }, + &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, + Hash: crypto.SHA256, + }, + } + RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { + return SigningMethodPS256 + }) + + // PS384 + SigningMethodPS384 = &SigningMethodRSAPSS{ + &SigningMethodRSA{ + Name: "PS384", + Hash: crypto.SHA384, + }, + &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, + Hash: crypto.SHA384, + }, + } + RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { + return SigningMethodPS384 + }) + + // PS512 + SigningMethodPS512 = &SigningMethodRSAPSS{ + &SigningMethodRSA{ + Name: "PS512", + Hash: crypto.SHA512, + }, + &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, + Hash: crypto.SHA512, + }, + } + RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { + return SigningMethodPS512 + }) +} + +// Implements the Verify method from SigningMethod +// For this verify method, key must be an rsa.PublicKey struct +func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { + var err error + + // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } + + var rsaKey *rsa.PublicKey + switch k := key.(type) { + case *rsa.PublicKey: + rsaKey = k + default: + return ErrInvalidKey + } + + // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options) +} + +// Implements the Sign method from SigningMethod +// For this signing method, key must be an rsa.PrivateKey struct +func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { + var rsaKey *rsa.PrivateKey + + switch k := key.(type) { + case *rsa.PrivateKey: + rsaKey = k + default: + return "", ErrInvalidKeyType + } + + // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { + return EncodeSegment(sigBytes), nil + } else { + return "", err + } +} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go new file mode 100644 index 0000000000000000000000000000000000000000..a5ababf956c4fc3ed74908c929b3e9e04d3fee7e --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go @@ -0,0 +1,101 @@ +package jwt + +import ( + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "errors" +) + +var ( + ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key") + ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") + ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") +) + +// Parse PEM encoded PKCS1 or PKCS8 private key +func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + var parsedKey interface{} + if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { + return nil, err + } + } + + var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } + + return pkey, nil +} + +// Parse PEM encoded PKCS1 or PKCS8 private key protected with password +func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + var parsedKey interface{} + + var blockDecrypted []byte + if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { + return nil, err + } + + if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { + return nil, err + } + } + + var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } + + return pkey, nil +} + +// Parse PEM encoded PKCS1 or PKCS8 public key +func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + return nil, err + } + } + + var pkey *rsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { + return nil, ErrNotRSAPublicKey + } + + return pkey, nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/signing_method.go b/vendor/github.com/dgrijalva/jwt-go/signing_method.go new file mode 100644 index 0000000000000000000000000000000000000000..ed1f212b21e1eaa5ca67d1e2b1969d984d92bfa7 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/signing_method.go @@ -0,0 +1,35 @@ +package jwt + +import ( + "sync" +) + +var signingMethods = map[string]func() SigningMethod{} +var signingMethodLock = new(sync.RWMutex) + +// Implement SigningMethod to add new methods for signing or verifying tokens. +type SigningMethod interface { + Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid + Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error + Alg() string // returns the alg identifier for this method (example: 'HS256') +} + +// Register the "alg" name and a factory function for signing method. +// This is typically done during init() in the method's implementation +func RegisterSigningMethod(alg string, f func() SigningMethod) { + signingMethodLock.Lock() + defer signingMethodLock.Unlock() + + signingMethods[alg] = f +} + +// Get a signing method from an "alg" string +func GetSigningMethod(alg string) (method SigningMethod) { + signingMethodLock.RLock() + defer signingMethodLock.RUnlock() + + if methodF, ok := signingMethods[alg]; ok { + method = methodF() + } + return +} diff --git a/vendor/github.com/dgrijalva/jwt-go/token.go b/vendor/github.com/dgrijalva/jwt-go/token.go new file mode 100644 index 0000000000000000000000000000000000000000..d637e0867c65bce725f9b08da469111ed7cf05e9 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/token.go @@ -0,0 +1,108 @@ +package jwt + +import ( + "encoding/base64" + "encoding/json" + "strings" + "time" +) + +// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). +// You can override it to use another time value. This is useful for testing or if your +// server uses a different time zone than your tokens. +var TimeFunc = time.Now + +// Parse methods use this callback function to supply +// the key for verification. The function receives the parsed, +// but unverified Token. This allows you to use properties in the +// Header of the token (such as `kid`) to identify which key to use. +type Keyfunc func(*Token) (interface{}, error) + +// A JWT Token. Different fields will be used depending on whether you're +// creating or parsing/verifying a token. +type Token struct { + Raw string // The raw token. Populated when you Parse a token + Method SigningMethod // The signing method used or to be used + Header map[string]interface{} // The first segment of the token + Claims Claims // The second segment of the token + Signature string // The third segment of the token. Populated when you Parse a token + Valid bool // Is the token valid? Populated when you Parse/Verify a token +} + +// Create a new Token. Takes a signing method +func New(method SigningMethod) *Token { + return NewWithClaims(method, MapClaims{}) +} + +func NewWithClaims(method SigningMethod, claims Claims) *Token { + return &Token{ + Header: map[string]interface{}{ + "typ": "JWT", + "alg": method.Alg(), + }, + Claims: claims, + Method: method, + } +} + +// Get the complete, signed token +func (t *Token) SignedString(key interface{}) (string, error) { + var sig, sstr string + var err error + if sstr, err = t.SigningString(); err != nil { + return "", err + } + if sig, err = t.Method.Sign(sstr, key); err != nil { + return "", err + } + return strings.Join([]string{sstr, sig}, "."), nil +} + +// Generate the signing string. This is the +// most expensive part of the whole deal. Unless you +// need this for something special, just go straight for +// the SignedString. +func (t *Token) SigningString() (string, error) { + var err error + parts := make([]string, 2) + for i, _ := range parts { + var jsonValue []byte + if i == 0 { + if jsonValue, err = json.Marshal(t.Header); err != nil { + return "", err + } + } else { + if jsonValue, err = json.Marshal(t.Claims); err != nil { + return "", err + } + } + + parts[i] = EncodeSegment(jsonValue) + } + return strings.Join(parts, "."), nil +} + +// Parse, validate, and return a token. +// keyFunc will receive the parsed token and should return the key for validating. +// If everything is kosher, err will be nil +func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return new(Parser).Parse(tokenString, keyFunc) +} + +func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) +} + +// Encode JWT specific base64url encoding with padding stripped +func EncodeSegment(seg []byte) string { + return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") +} + +// Decode JWT specific base64url encoding with padding stripped +func DecodeSegment(seg string) ([]byte, error) { + if l := len(seg) % 4; l > 0 { + seg += strings.Repeat("=", 4-l) + } + + return base64.URLEncoding.DecodeString(seg) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 7a55fd5e46c21f27c8406eb69b24e2cd8242c294..6b148130be59713f81a9ead13f3992726f379b19 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,12 +1,12 @@ # gitee.com/openeuler/PilotGo-plugins/event/sdk v0.0.0-20240730114546-6471a280e4d2 ## explicit; go 1.21.6 -gitee.com/openeuler/PilotGo-plugins/event/sdk -# gitee.com/openeuler/PilotGo/sdk v0.0.0-20250806061906-ced6853de86f +# gitee.com/openeuler/PilotGo/sdk v0.0.0-20250808080917-4f1087c03a0b ## explicit; go 1.23.0 gitee.com/openeuler/PilotGo/sdk/common gitee.com/openeuler/PilotGo/sdk/go-micro/registry gitee.com/openeuler/PilotGo/sdk/logger gitee.com/openeuler/PilotGo/sdk/plugin/client +gitee.com/openeuler/PilotGo/sdk/plugin/jwt gitee.com/openeuler/PilotGo/sdk/response gitee.com/openeuler/PilotGo/sdk/utils/httputils # github.com/bytedance/sonic v1.10.2 @@ -61,6 +61,9 @@ github.com/coreos/go-semver/semver # github.com/coreos/go-systemd/v22 v22.5.0 ## explicit; go 1.12 github.com/coreos/go-systemd/v22/journal +# github.com/dgrijalva/jwt-go v3.2.0+incompatible +## explicit +github.com/dgrijalva/jwt-go # github.com/gabriel-vasile/mimetype v1.4.3 ## explicit; go 1.20 github.com/gabriel-vasile/mimetype