plugin.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package authorization
  2. import (
  3. "sync"
  4. "github.com/docker/docker/pkg/plugins"
  5. )
  6. // Plugin allows third party plugins to authorize requests and responses
  7. // in the context of docker API
  8. type Plugin interface {
  9. // Name returns the registered plugin name
  10. Name() string
  11. // AuthZRequest authorizes the request from the client to the daemon
  12. AuthZRequest(*Request) (*Response, error)
  13. // AuthZResponse authorizes the response from the daemon to the client
  14. AuthZResponse(*Request) (*Response, error)
  15. }
  16. // NewPlugins constructs and initializes the authorization plugins based on plugin names
  17. func NewPlugins(names []string) []Plugin {
  18. plugins := []Plugin{}
  19. pluginsMap := make(map[string]struct{})
  20. for _, name := range names {
  21. if _, ok := pluginsMap[name]; ok {
  22. continue
  23. }
  24. pluginsMap[name] = struct{}{}
  25. plugins = append(plugins, newAuthorizationPlugin(name))
  26. }
  27. return plugins
  28. }
  29. // authorizationPlugin is an internal adapter to docker plugin system
  30. type authorizationPlugin struct {
  31. plugin *plugins.Plugin
  32. name string
  33. once sync.Once
  34. }
  35. func newAuthorizationPlugin(name string) Plugin {
  36. return &authorizationPlugin{name: name}
  37. }
  38. func (a *authorizationPlugin) Name() string {
  39. return a.name
  40. }
  41. func (a *authorizationPlugin) AuthZRequest(authReq *Request) (*Response, error) {
  42. if err := a.initPlugin(); err != nil {
  43. return nil, err
  44. }
  45. authRes := &Response{}
  46. if err := a.plugin.Client.Call(AuthZApiRequest, authReq, authRes); err != nil {
  47. return nil, err
  48. }
  49. return authRes, nil
  50. }
  51. func (a *authorizationPlugin) AuthZResponse(authReq *Request) (*Response, error) {
  52. if err := a.initPlugin(); err != nil {
  53. return nil, err
  54. }
  55. authRes := &Response{}
  56. if err := a.plugin.Client.Call(AuthZApiResponse, authReq, authRes); err != nil {
  57. return nil, err
  58. }
  59. return authRes, nil
  60. }
  61. // initPlugin initializes the authorization plugin if needed
  62. func (a *authorizationPlugin) initPlugin() error {
  63. // Lazy loading of plugins
  64. var err error
  65. a.once.Do(func() {
  66. if a.plugin == nil {
  67. a.plugin, err = plugins.Get(a.name, AuthZApiImplements)
  68. }
  69. })
  70. return err
  71. }