Skip to content

Commit

Permalink
service: remove leaking go-micro references (#1347)
Browse files Browse the repository at this point in the history
* service/auth: add type aliases

* service/broker: add type aliases

* service/client: add type aliases

* service/config: add type aliases

* service/registry: add type aliases

* service/runtime: add type aliases

* service/store: add type aliases

* service: fix naming conflicts

* service/store: update interface to use micro options

* update micro to use new syntax

* Fix merge conflict

* service/broker: remove options from public funcs

* service/client: remove options from public funcs

* service/registry: remove options from public funcs

* service/server: remove options from public funcs

* service/registry: add alias for node

* wip: refactor auth package

* internal/auth: fix circular dep

* Update CI tests

* Tidy go.mod

* service/runtime: implement options

* Fix tests

* tidy go.mod

* service/auth: rename AccessToken to AccountToken
  • Loading branch information
ben-toogood committed Sep 11, 2020
1 parent 353bf80 commit 2fc8455
Show file tree
Hide file tree
Showing 57 changed files with 1,171 additions and 418 deletions.
4 changes: 2 additions & 2 deletions client/cli/commands.go
Expand Up @@ -56,7 +56,7 @@ func QueryStats(c *cli.Context, args []string) ([]byte, error) {
return nil, err
}

service, err := registry.GetService(args[0], goregistry.GetDomain(ns))
service, err := registry.DefaultRegistry.GetService(args[0], goregistry.GetDomain(ns))
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -85,7 +85,7 @@ func QueryStats(c *cli.Context, args []string) ([]byte, error) {
var err error

// call using client
err = client.Call(context.Background(), req, rsp, goclient.WithAddress(address))
err = client.DefaultClient.Call(context.Background(), req, rsp, goclient.WithAddress(address))

var started, uptime, memory, gc string
if err == nil {
Expand Down
2 changes: 1 addition & 1 deletion client/cli/helpers.go
Expand Up @@ -97,7 +97,7 @@ func streamService(c *cli.Context, args []string) ([]byte, error) {
// ignore error
json.Unmarshal([]byte(strings.Join(args[2:], " ")), &request)

req := client.NewRequest(service, endpoint, request, goclient.WithContentType("application/json"))
req := client.DefaultClient.NewRequest(service, endpoint, request, goclient.WithContentType("application/json"))
stream, err := client.Stream(context.Background(), req)
if err != nil {
return nil, fmt.Errorf("error calling %s.%s: %v", service, endpoint, err)
Expand Down
4 changes: 2 additions & 2 deletions client/cli/signup/cli.go
Expand Up @@ -10,14 +10,14 @@ import (
"time"

"github.com/micro/cli/v2"
"github.com/micro/go-micro/v3/auth"
cl "github.com/micro/go-micro/v3/client"
clinamespace "github.com/micro/micro/v3/client/cli/namespace"
clitoken "github.com/micro/micro/v3/client/cli/token"
cliutil "github.com/micro/micro/v3/client/cli/util"
"github.com/micro/micro/v3/cmd"
"github.com/micro/micro/v3/internal/report"
pb "github.com/micro/micro/v3/proto/signup"
"github.com/micro/micro/v3/service/auth"
"github.com/micro/micro/v3/service/client"
"github.com/micro/micro/v3/service/context"
"golang.org/x/crypto/ssh/terminal"
Expand Down Expand Up @@ -171,7 +171,7 @@ func Run(ctx *cli.Context) error {
os.Exit(1)
}

if err := clitoken.Save(env.Name, &auth.Token{
if err := clitoken.Save(env.Name, &auth.AccountToken{
AccessToken: tok.AccessToken,
RefreshToken: tok.RefreshToken,
Expiry: time.Unix(tok.Expiry, 0),
Expand Down
12 changes: 6 additions & 6 deletions client/cli/token/token.go
Expand Up @@ -6,30 +6,30 @@ import (
"strconv"
"time"

"github.com/micro/go-micro/v3/auth"
"github.com/micro/micro/v3/internal/config"
"github.com/micro/micro/v3/service/auth"
)

// Get tries a best effort read of auth token from user config.
// Might have missing `RefreshToken` or `Expiry` fields in case of
// incomplete or corrupted user config.
func Get(envName string) (*auth.Token, error) {
func Get(envName string) (*auth.AccountToken, error) {
path := []string{"micro", "auth", envName}
accessToken, _ := config.Get(append(path, "token")...)

refreshToken, err := config.Get(append(path, "refresh-token")...)
if err != nil {
// Gracefully degrading here in case the user only has a temporary access token at hand.
// The call will fail on the receiving end.
return &auth.Token{
return &auth.AccountToken{
AccessToken: accessToken,
}, nil
}

// See if the access token has expired
expiry, _ := config.Get(append(path, "expiry")...)
if len(expiry) == 0 {
return &auth.Token{
return &auth.AccountToken{
AccessToken: accessToken,
RefreshToken: refreshToken,
}, nil
Expand All @@ -38,15 +38,15 @@ func Get(envName string) (*auth.Token, error) {
if err != nil {
return nil, err
}
return &auth.Token{
return &auth.AccountToken{
AccessToken: accessToken,
RefreshToken: refreshToken,
Expiry: time.Unix(expiryInt, 0),
}, nil
}

// Save saves the auth token to the user's local config file
func Save(envName string, token *auth.Token) error {
func Save(envName string, token *auth.AccountToken) error {
if err := config.Set(token.AccessToken, "micro", "auth", envName, "token"); err != nil {
return err
}
Expand Down
6 changes: 3 additions & 3 deletions cmd/dynamic.go
Expand Up @@ -134,9 +134,9 @@ func callService(srv *goregistry.Service, namespace string, ctx *cli.Context) er
// TODO: parse out --header or --metadata

// construct and execute the request using the json content type
req := client.NewRequest(srv.Name, endpoint, body, goclient.WithContentType("application/json"))
req := client.DefaultClient.NewRequest(srv.Name, endpoint, body, goclient.WithContentType("application/json"))
var rsp json.RawMessage
if err := client.Call(callCtx, req, &rsp, goclient.WithAuthToken()); err != nil {
if err := client.DefaultClient.Call(callCtx, req, &rsp, goclient.WithAuthToken()); err != nil {
return err
}

Expand Down Expand Up @@ -273,7 +273,7 @@ loop:

// find a service in a domain matching the name
func serviceWithName(name, domain string) (*goregistry.Service, error) {
srvs, err := registry.GetService(name, goregistry.GetDomain(domain))
srvs, err := registry.DefaultRegistry.GetService(name, goregistry.GetDomain(domain))
if err == goregistry.ErrNotFound {
return nil, nil
} else if err != nil {
Expand Down
18 changes: 9 additions & 9 deletions cmd/util.go
Expand Up @@ -46,8 +46,8 @@ func setupAuthForCLI(ctx *cli.Context) error {

// Get new access token from refresh token if it's close to expiry
tok, err = auth.Token(
goauth.WithToken(tok.RefreshToken),
goauth.WithTokenIssuer(ns),
auth.WithToken(tok.RefreshToken),
auth.WithTokenIssuer(ns),
)
if err != nil {
return nil
Expand All @@ -71,9 +71,9 @@ func setupAuthForService() error {

// if no credentials were provided, self generate an account
if len(accID) == 0 || len(accSecret) == 0 {
opts := []goauth.GenerateOption{
goauth.WithType("service"),
goauth.WithScopes("service"),
opts := []auth.GenerateOption{
auth.WithType("service"),
auth.WithScopes("service"),
}

acc, err := auth.Generate(uuid.New().String(), opts...)
Expand All @@ -90,8 +90,8 @@ func setupAuthForService() error {

// generate the first token
token, err := auth.Token(
goauth.WithCredentials(accID, accSecret),
goauth.WithExpiry(time.Minute*10),
auth.WithCredentials(accID, accSecret),
auth.WithExpiry(time.Minute*10),
)
if err != nil {
return err
Expand Down Expand Up @@ -126,8 +126,8 @@ func refreshAuthToken() {

// generate the first token
tok, err := auth.Token(
goauth.WithToken(tok.RefreshToken),
goauth.WithExpiry(time.Minute*10),
auth.WithToken(tok.RefreshToken),
auth.WithExpiry(time.Minute*10),
)
if err != nil {
logger.Warnf("[Auth] Error refreshing token: %v", err)
Expand Down
71 changes: 71 additions & 0 deletions internal/auth/namespace/namespace.go
@@ -0,0 +1,71 @@
package namespace

import (
"context"
"errors"

"github.com/micro/micro/v3/service/auth"
)

var (
// ErrUnauthorized is returned by Authorize when a context without a blank account tries to access
// a restricted namespace
ErrUnauthorized = errors.New("An account is required")
// ErrForbidden is returned by Authorize when a context is trying to access a namespace it doesn't
// have access to
ErrForbidden = errors.New("Access denied to namespace")
)

const (
// DefaultNamespace used by the server
DefaultNamespace = "micro"
)

// Authorize will return an error if the context cannot access the given namespace
func Authorize(ctx context.Context, namespace string, opts ...AuthorizeOption) error {
// parse the options
var options AuthorizeOptions
for _, o := range opts {
o(&options)
}

// check to see if the namespace was made public
if namespace == options.PublicNamespace {
return nil
}

// accounts are always required so we can identify the caller. If auth is not configured, the noop
// auth implementation will return a blank account with the default namespace set, allowing the caller
// access to all resources
acc, ok := auth.AccountFromContext(ctx)
if !ok {
return ErrUnauthorized
}

// the server can access all namespaces
if acc.Issuer == DefaultNamespace {
return nil
}

// ensure the account is requesing access to it's own namespace
if acc.Issuer != namespace {
return ErrForbidden
}

return nil
}

// AuthorizeOptions are used to configure the Authorize method
type AuthorizeOptions struct {
PublicNamespace string
}

// AuthorizeOption sets an attribute on AuthorizeOptions
type AuthorizeOption func(o *AuthorizeOptions)

// Public indicates a namespace is public and can be accessed by anyone
func Public(ns string) AuthorizeOption {
return func(o *AuthorizeOptions) {
o.PublicNamespace = ns
}
}
18 changes: 9 additions & 9 deletions internal/command/command.go
Expand Up @@ -87,7 +87,7 @@ func GetService(c *cli.Context, args []string) ([]byte, error) {
var output []string
var srv []*goregistry.Service

srv, err = registry.GetService(args[0], goregistry.GetDomain(ns))
srv, err = registry.DefaultRegistry.GetService(args[0], goregistry.GetDomain(ns))
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -159,7 +159,7 @@ func ListServices(c *cli.Context) ([]byte, error) {
return nil, err
}

rsp, err = registry.ListServices(goregistry.ListDomain(ns))
rsp, err = registry.DefaultRegistry.ListServices(goregistry.ListDomain(ns))
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -197,7 +197,7 @@ func Publish(c *cli.Context, args []string) error {
}

ctx := callContext(c)
m := client.NewMessage(topic, msg, ct)
m := client.DefaultClient.NewMessage(topic, msg, ct)
return client.Publish(ctx, m)
}

Expand Down Expand Up @@ -231,7 +231,7 @@ func CallService(c *cli.Context, args []string) ([]byte, error) {

ctx := callContext(c)

creq := client.NewRequest(service, endpoint, request, goclient.WithContentType("application/json"))
creq := client.DefaultClient.NewRequest(service, endpoint, request, goclient.WithContentType("application/json"))

opts := []goclient.CallOption{goclient.WithAuthToken()}
if timeout := c.String("request_timeout"); timeout != "" {
Expand All @@ -249,12 +249,12 @@ func CallService(c *cli.Context, args []string) ([]byte, error) {
var err error
if output := c.String("output"); output == "raw" {
rsp := cbytes.Frame{}
err = client.Call(ctx, creq, &rsp, opts...)
err = client.DefaultClient.Call(ctx, creq, &rsp, opts...)
// set the raw output
response = rsp.Data
} else {
var rsp json.RawMessage
err = client.Call(ctx, creq, &rsp, opts...)
err = client.DefaultClient.Call(ctx, creq, &rsp, opts...)
// set the response
if err == nil {
var out bytes.Buffer
Expand Down Expand Up @@ -288,7 +288,7 @@ func QueryHealth(c *cli.Context, args []string) ([]byte, error) {
// if the address is specified then we just call it
if addr := c.String("address"); len(addr) > 0 {
rsp := &proto.HealthResponse{}
err := client.Call(
err := client.DefaultClient.Call(
context.Background(),
req,
rsp,
Expand All @@ -301,7 +301,7 @@ func QueryHealth(c *cli.Context, args []string) ([]byte, error) {
}

// otherwise get the service and call each instance individually
service, err := registry.GetService(args[0], goregistry.GetDomain(ns))
service, err := registry.DefaultRegistry.GetService(args[0], goregistry.GetDomain(ns))
if err != nil {
return nil, err
}
Expand All @@ -327,7 +327,7 @@ func QueryHealth(c *cli.Context, args []string) ([]byte, error) {
var err error

// call using client
err = client.Call(
err = client.DefaultClient.Call(
context.Background(),
req,
rsp,
Expand Down
4 changes: 2 additions & 2 deletions internal/handler/rpc.go
Expand Up @@ -127,7 +127,7 @@ func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// create request/response
var response json.RawMessage
var err error
req := client.NewRequest(service, endpoint, request, goclient.WithContentType("application/json"))
req := client.DefaultClient.NewRequest(service, endpoint, request, goclient.WithContentType("application/json"))

// create context
ctx := helper.RequestToContext(r)
Expand All @@ -154,7 +154,7 @@ func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}

// remote call
err = client.Call(ctx, req, &response, opts...)
err = client.DefaultClient.Call(ctx, req, &response, opts...)
if err != nil {
ce := goerrors.Parse(err.Error())
switch ce.Code {
Expand Down

0 comments on commit 2fc8455

Please sign in to comment.