github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/apiserver/bakeryutil/service.go (about)

     1  // Copyright 2018 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package bakeryutil
     5  
     6  import (
     7  	"time"
     8  
     9  	"gopkg.in/macaroon-bakery.v2-unstable/bakery"
    10  
    11  	"github.com/juju/errors"
    12  	"github.com/juju/juju/apiserver/authentication"
    13  	"github.com/juju/juju/state"
    14  	"github.com/juju/juju/state/bakerystorage"
    15  )
    16  
    17  // BakeryServicePublicKeyLocator is an implementation of
    18  // bakery.PublicKeyLocator that simply returns the embedded
    19  // bakery service's public key.
    20  type BakeryServicePublicKeyLocator struct {
    21  	Service *bakery.Service
    22  }
    23  
    24  // PublicKeyForLocation implements bakery.PublicKeyLocator.
    25  func (b BakeryServicePublicKeyLocator) PublicKeyForLocation(string) (*bakery.PublicKey, error) {
    26  	return b.Service.PublicKey(), nil
    27  }
    28  
    29  // NewBakeryService returns a new bakery.Service and bakery.KeyPair.
    30  // The bakery service is identifeid by the model corresponding to the
    31  // State.
    32  func NewBakeryService(
    33  	st *state.State,
    34  	store bakerystorage.ExpirableStorage,
    35  	locator bakery.PublicKeyLocator,
    36  ) (*bakery.Service, *bakery.KeyPair, error) {
    37  	key, err := bakery.GenerateKey()
    38  	if err != nil {
    39  		return nil, nil, errors.Annotate(err, "generating key for bakery service")
    40  	}
    41  	service, err := bakery.NewService(bakery.NewServiceParams{
    42  		Location: "juju model " + st.ModelUUID(),
    43  		Store:    store,
    44  		Key:      key,
    45  		Locator:  locator,
    46  	})
    47  	if err != nil {
    48  		return nil, nil, errors.Trace(err)
    49  	}
    50  	return service, key, nil
    51  }
    52  
    53  // ExpirableStorageBakeryService wraps bakery.Service,
    54  // adding the ExpireStorageAfter method.
    55  type ExpirableStorageBakeryService struct {
    56  	*bakery.Service
    57  	Key     *bakery.KeyPair
    58  	Store   bakerystorage.ExpirableStorage
    59  	Locator bakery.PublicKeyLocator
    60  }
    61  
    62  // ExpireStorageAfter implements authentication.ExpirableStorageBakeryService.
    63  func (s *ExpirableStorageBakeryService) ExpireStorageAfter(t time.Duration) (authentication.ExpirableStorageBakeryService, error) {
    64  	store := s.Store.ExpireAfter(t)
    65  	service, err := bakery.NewService(bakery.NewServiceParams{
    66  		Location: s.Location(),
    67  		Store:    store,
    68  		Key:      s.Key,
    69  		Locator:  s.Locator,
    70  	})
    71  	if err != nil {
    72  		return nil, errors.Trace(err)
    73  	}
    74  	return &ExpirableStorageBakeryService{service, s.Key, store, s.Locator}, nil
    75  }