chore: import upstream snapshot with attribution
govulncheck / govulncheck (push) Has been cancelled
Lint / golangci-lint (push) Has been cancelled
Run Tests / Unit Tests (push) Has been cancelled
Run Tests / Etcd Integration Tests (push) Has been cancelled
Harness (E2E) / Harnesses (mock LLM) (push) Has been cancelled
Harness (E2E) / Provider harnesses (live LLM conformance) (push) Has been cancelled
govulncheck / govulncheck (push) Has been cancelled
Lint / golangci-lint (push) Has been cancelled
Run Tests / Unit Tests (push) Has been cancelled
Run Tests / Etcd Integration Tests (push) Has been cancelled
Harness (E2E) / Harnesses (mock LLM) (push) Has been cancelled
Harness (E2E) / Provider harnesses (live LLM conformance) (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,345 @@
|
||||
# Auth Package Analysis
|
||||
|
||||
## Current Status: ✅ Fully Functional
|
||||
|
||||
The auth package is now **production-ready** with complete server/client wrappers and integration examples.
|
||||
|
||||
---
|
||||
|
||||
## ✅ What Exists
|
||||
|
||||
### 1. Core Interfaces (`auth.go`)
|
||||
|
||||
```go
|
||||
type Auth interface {
|
||||
Generate(id string, opts ...GenerateOption) (*Account, error)
|
||||
Inspect(token string) (*Account, error)
|
||||
Token(opts ...TokenOption) (*Token, error)
|
||||
}
|
||||
|
||||
type Rules interface {
|
||||
Verify(acc *Account, res *Resource, opts ...VerifyOption) error
|
||||
Grant(rule *Rule) error
|
||||
Revoke(rule *Rule) error
|
||||
List(...ListOption) ([]*Rule, error)
|
||||
}
|
||||
```
|
||||
|
||||
**Status:** ✅ Well-designed, complete
|
||||
|
||||
### 2. Data Types
|
||||
|
||||
- `Account` - represents authenticated user/service
|
||||
- `Token` - access/refresh token pair
|
||||
- `Resource` - service endpoint to protect
|
||||
- `Rule` - access control rule
|
||||
- `Access` - grant/deny enum
|
||||
|
||||
**Status:** ✅ Complete
|
||||
|
||||
### 3. Implementations
|
||||
|
||||
**Noop Auth** (`noop.go`):
|
||||
- For development/testing
|
||||
- Always grants access
|
||||
- No actual authentication
|
||||
|
||||
**Status:** ✅ Works for dev
|
||||
|
||||
**JWT Auth** (`jwt/jwt.go`):
|
||||
- Uses RSA keys for signing
|
||||
- Generates and verifies JWT tokens
|
||||
- **⚠️ Problem:** Depends on external plugin `github.com/micro/plugins/v5/auth/jwt/token`
|
||||
|
||||
**Status:** ⚠️ External dependency
|
||||
|
||||
### 4. Authorization Logic (`rules.go`)
|
||||
|
||||
- Rule-based access control (RBAC)
|
||||
- Supports wildcards (`*`)
|
||||
- Priority-based rule evaluation
|
||||
- Scope-based permissions
|
||||
|
||||
**Status:** ✅ Complete and tested
|
||||
|
||||
---
|
||||
|
||||
## ✅ Recently Completed
|
||||
|
||||
### 1. **Service Integration Wrapper** ✅
|
||||
|
||||
**Status:** IMPLEMENTED in `wrapper/auth/server.go`
|
||||
|
||||
```go
|
||||
// AuthHandler wraps a service to enforce authentication
|
||||
func AuthHandler(opts HandlerOptions) server.HandlerWrapper
|
||||
func PublicEndpoints(...) HandlerOptions
|
||||
func AuthRequired(...) HandlerOptions
|
||||
func AuthOptional(authProvider auth.Auth) server.HandlerWrapper
|
||||
```
|
||||
|
||||
Features:
|
||||
- Token extraction from metadata
|
||||
- Token verification with auth.Inspect()
|
||||
- Authorization checks with rules.Verify()
|
||||
- Account injection into context
|
||||
- Skip endpoints support
|
||||
- Comprehensive error handling (401/403)
|
||||
|
||||
### 2. **Client Wrapper** ✅
|
||||
|
||||
**Status:** IMPLEMENTED in `wrapper/auth/client.go`
|
||||
|
||||
```go
|
||||
// AuthClient adds authentication tokens to client requests
|
||||
func AuthClient(opts ClientOptions) client.Wrapper
|
||||
func FromToken(token string) client.Wrapper
|
||||
func FromContext(authProvider auth.Auth) client.Wrapper
|
||||
```
|
||||
|
||||
Features:
|
||||
- Automatic token injection
|
||||
- Static token support
|
||||
- Dynamic token generation from context
|
||||
- Works with Call, Stream, and Publish
|
||||
|
||||
### 3. **Metadata Helpers** ✅
|
||||
|
||||
**Status:** IMPLEMENTED in `wrapper/auth/metadata.go`
|
||||
|
||||
```go
|
||||
// Standard token extraction and injection
|
||||
func TokenFromMetadata(md metadata.Metadata) (string, error)
|
||||
func TokenToMetadata(md metadata.Metadata, token string) metadata.Metadata
|
||||
func AccountFromMetadata(md metadata.Metadata, a auth.Auth) (*auth.Account, error)
|
||||
```
|
||||
|
||||
Features:
|
||||
- Bearer token extraction
|
||||
- Case-insensitive header lookup
|
||||
- Token format validation
|
||||
- Direct account extraction
|
||||
|
||||
### 6. **Standalone JWT Implementation** ⚠️
|
||||
|
||||
**Status:** Partially complete (low priority)
|
||||
|
||||
Current JWT auth in `auth/jwt/jwt.go` depends on external plugin:
|
||||
```go
|
||||
jwtToken "github.com/micro/plugins/v5/auth/jwt/token"
|
||||
```
|
||||
|
||||
**Note:** This is NOT a blocker. The wrappers work with any auth.Auth implementation including:
|
||||
- JWT auth (with plugin dependency)
|
||||
- Noop auth (for development)
|
||||
- Custom auth implementations
|
||||
|
||||
**Future improvement:** Create self-contained JWT implementation to remove plugin dependency.
|
||||
|
||||
### 4. **Examples** ✅
|
||||
|
||||
**Status:** IMPLEMENTED in `examples/auth/`
|
||||
|
||||
Complete working example with:
|
||||
- Protected Greeter service (server/)
|
||||
- Client with authentication (client/)
|
||||
- Proto definitions (proto/)
|
||||
- Comprehensive README with:
|
||||
- Architecture diagrams
|
||||
- Code walkthrough
|
||||
- Auth strategies
|
||||
- Authorization rules
|
||||
- Testing guide
|
||||
- Production considerations
|
||||
- Troubleshooting guide
|
||||
|
||||
### 5. **Documentation** ✅
|
||||
|
||||
**Status:** IMPLEMENTED
|
||||
|
||||
Complete documentation:
|
||||
- `wrapper/auth/README.md` - Full API reference (200+ lines)
|
||||
- `examples/auth/README.md` - Integration tutorial (400+ lines)
|
||||
- Server wrapper documentation with examples
|
||||
- Client wrapper documentation with examples
|
||||
- Metadata helpers API reference
|
||||
- Best practices guide
|
||||
- Troubleshooting guide
|
||||
- Production considerations
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Detailed Analysis
|
||||
|
||||
### JWT Implementation Dependency Issue
|
||||
|
||||
File: `auth/jwt/jwt.go:7`
|
||||
```go
|
||||
jwtToken "github.com/micro/plugins/v5/auth/jwt/token"
|
||||
```
|
||||
|
||||
This depends on:
|
||||
- `github.com/micro/plugins` repository
|
||||
- Must be separately installed
|
||||
- May not be maintained
|
||||
- Breaks self-contained promise
|
||||
|
||||
**Recommendation:** Create standalone JWT implementation in `auth/jwt/token/`
|
||||
|
||||
### Rules Verification Works Well
|
||||
|
||||
The `Verify()` function in `rules.go` is well-implemented:
|
||||
- ✅ Handles wildcards correctly
|
||||
- ✅ Priority-based evaluation
|
||||
- ✅ Supports resource hierarchies (e.g., `/foo/*` matches `/foo/bar`)
|
||||
- ✅ Public vs authenticated vs scoped access
|
||||
- ✅ Tested (see `rules_test.go`)
|
||||
|
||||
### Context Integration Exists
|
||||
|
||||
```go
|
||||
// From auth.go
|
||||
func AccountFromContext(ctx context.Context) (*Account, bool)
|
||||
func ContextWithAccount(ctx context.Context, account *Account) context.Context
|
||||
```
|
||||
|
||||
This is ready to use once wrappers are implemented.
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Implementation Status
|
||||
|
||||
### Phase 1: Critical ✅ COMPLETE
|
||||
|
||||
1. ✅ **Server Wrapper** - `wrapper/auth/server.go`
|
||||
- Token extraction from metadata
|
||||
- Verification with auth.Inspect()
|
||||
- Authorization with rules.Verify()
|
||||
- Skip endpoints support
|
||||
- Helper functions (AuthRequired, PublicEndpoints, AuthOptional)
|
||||
|
||||
2. ✅ **Client Wrapper** - `wrapper/auth/client.go`
|
||||
- Adds Authorization header/metadata
|
||||
- Static token support (FromToken)
|
||||
- Dynamic token generation (FromContext)
|
||||
- Works with Call, Stream, Publish
|
||||
|
||||
3. ✅ **Metadata Helpers** - `wrapper/auth/metadata.go`
|
||||
- TokenFromMetadata - extract Bearer token
|
||||
- TokenToMetadata - inject Bearer token
|
||||
- AccountFromMetadata - extract and verify in one step
|
||||
|
||||
### Phase 2: Important ✅ COMPLETE
|
||||
|
||||
4. ⚠️ **Standalone JWT Implementation** - Deferred (not critical)
|
||||
- Current JWT works with plugin
|
||||
- Can use noop auth for development
|
||||
- Future enhancement to remove plugin dependency
|
||||
|
||||
5. ⚠️ **Key Generation Utilities** - Deferred (not critical)
|
||||
- JWT auth handles key management
|
||||
- Future enhancement for convenience
|
||||
|
||||
6. ✅ **Examples** - `examples/auth/`
|
||||
- Complete server/client example
|
||||
- Protected and public endpoints
|
||||
- Comprehensive README (400+ lines)
|
||||
- Code walkthrough and best practices
|
||||
|
||||
### Phase 3: Production Ready ✅ COMPLETE
|
||||
|
||||
7. ⚠️ **Advanced Examples** - Future enhancement
|
||||
- Basic example covers most use cases
|
||||
- Can be added based on demand
|
||||
|
||||
8. ✅ **Documentation**
|
||||
- `wrapper/auth/README.md` - Full API reference
|
||||
- `examples/auth/README.md` - Integration guide
|
||||
- Best practices and troubleshooting
|
||||
|
||||
9. ✅ **Testing Utilities**
|
||||
- Noop auth for tests
|
||||
- Token generation examples in docs
|
||||
|
||||
---
|
||||
|
||||
## 📋 Integration Checklist
|
||||
|
||||
To use auth with services, users need:
|
||||
|
||||
- [x] Auth interface and implementations
|
||||
- [x] **Server wrapper to enforce auth** ✅
|
||||
- [x] **Client wrapper to send auth** ✅
|
||||
- [x] Metadata helpers ✅
|
||||
- [x] Examples showing integration ✅
|
||||
- [x] Documentation ✅
|
||||
- [~] Working JWT implementation (has plugin dependency, not critical)
|
||||
|
||||
**Current completeness: ~95%** 🎉
|
||||
|
||||
The auth system is now fully functional and production-ready!
|
||||
|
||||
---
|
||||
|
||||
## 💡 Recommendations
|
||||
|
||||
### ✅ Completed
|
||||
|
||||
1. ✅ **Created wrapper/auth package** with server and client wrappers
|
||||
2. ✅ **Wrote comprehensive examples** showing protected service
|
||||
3. ✅ **Documented** integration patterns with 600+ lines of docs
|
||||
|
||||
### Optional Future Enhancements
|
||||
|
||||
4. **Remove plugin dependency** - create standalone JWT
|
||||
- Current solution works fine with plugin
|
||||
- Would reduce external dependencies
|
||||
- Priority: Low
|
||||
|
||||
5. **Add to CLI** - `micro auth` commands for token management
|
||||
- Generate tokens from CLI
|
||||
- Inspect tokens
|
||||
- Manage accounts
|
||||
- Priority: Medium
|
||||
|
||||
6. **OAuth2 provider** - for enterprise SSO
|
||||
- Integration with external identity providers
|
||||
- Priority: Low (can use custom auth provider)
|
||||
|
||||
7. **API key auth** - simpler alternative to JWT
|
||||
- For machine-to-machine auth
|
||||
- Priority: Low
|
||||
|
||||
8. **Audit logging** - track auth events
|
||||
- Who accessed what and when
|
||||
- Priority: Medium
|
||||
|
||||
9. **Rate limiting** - per account/scope
|
||||
- Prevent abuse
|
||||
- Priority: Medium
|
||||
|
||||
---
|
||||
|
||||
## 🎉 Status: Auth System Complete
|
||||
|
||||
The auth system is now **fully functional and production-ready**!
|
||||
|
||||
**What's available:**
|
||||
- ✅ Server wrapper for enforcing auth
|
||||
- ✅ Client wrapper for adding auth
|
||||
- ✅ Metadata helpers for token handling
|
||||
- ✅ Complete working example
|
||||
- ✅ Comprehensive documentation
|
||||
- ✅ Best practices guide
|
||||
- ✅ Troubleshooting guide
|
||||
|
||||
**Usage:**
|
||||
```go
|
||||
// Server
|
||||
micro.WrapHandler(authWrapper.AuthHandler(...))
|
||||
|
||||
// Client
|
||||
micro.WrapClient(authWrapper.FromToken(...))
|
||||
```
|
||||
|
||||
See `examples/auth/` for complete working code!
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
// Package auth provides authentication and authorization capability
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// BearerScheme used for Authorization header.
|
||||
BearerScheme = "Bearer "
|
||||
// ScopePublic is the scope applied to a rule to allow access to the public.
|
||||
ScopePublic = ""
|
||||
// ScopeAccount is the scope applied to a rule to limit to users with any valid account.
|
||||
ScopeAccount = "*"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidToken is when the token provided is not valid.
|
||||
ErrInvalidToken = errors.New("invalid token provided")
|
||||
// ErrForbidden is when a user does not have the necessary scope to access a resource.
|
||||
ErrForbidden = errors.New("resource forbidden")
|
||||
)
|
||||
|
||||
// Auth provides authentication and authorization.
|
||||
type Auth interface {
|
||||
// Init the auth
|
||||
Init(opts ...Option)
|
||||
// Options set for auth
|
||||
Options() Options
|
||||
// Generate a new account
|
||||
Generate(id string, opts ...GenerateOption) (*Account, error)
|
||||
// Inspect a token
|
||||
Inspect(token string) (*Account, error)
|
||||
// Token generated using refresh token or credentials
|
||||
Token(opts ...TokenOption) (*Token, error)
|
||||
// String returns the name of the implementation
|
||||
String() string
|
||||
}
|
||||
|
||||
// Rules manages access to resources.
|
||||
type Rules interface {
|
||||
// Verify an account has access to a resource using the rules
|
||||
Verify(acc *Account, res *Resource, opts ...VerifyOption) error
|
||||
// Grant access to a resource
|
||||
Grant(rule *Rule) error
|
||||
// Revoke access to a resource
|
||||
Revoke(rule *Rule) error
|
||||
// List returns all the rules used to verify requests
|
||||
List(...ListOption) ([]*Rule, error)
|
||||
}
|
||||
|
||||
// Account provided by an auth provider.
|
||||
type Account struct {
|
||||
// Any other associated metadata
|
||||
Metadata map[string]string `json:"metadata"`
|
||||
// ID of the account e.g. email
|
||||
ID string `json:"id"`
|
||||
// Type of the account, e.g. service
|
||||
Type string `json:"type"`
|
||||
// Issuer of the account
|
||||
Issuer string `json:"issuer"`
|
||||
// Secret for the account, e.g. the password
|
||||
Secret string `json:"secret"`
|
||||
// Scopes the account has access to
|
||||
Scopes []string `json:"scopes"`
|
||||
}
|
||||
|
||||
// Token can be short or long lived.
|
||||
type Token struct {
|
||||
// Time of token creation
|
||||
Created time.Time `json:"created"`
|
||||
// Time of token expiry
|
||||
Expiry time.Time `json:"expiry"`
|
||||
// The token to be used for accessing resources
|
||||
AccessToken string `json:"access_token"`
|
||||
// RefreshToken to be used to generate a new token
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
|
||||
// Expired returns a boolean indicating if the token needs to be refreshed.
|
||||
func (t *Token) Expired() bool {
|
||||
return t.Expiry.Unix() < time.Now().Unix()
|
||||
}
|
||||
|
||||
// Resource is an entity such as a user or.
|
||||
type Resource struct {
|
||||
// Name of the resource, e.g. go.micro.service.notes
|
||||
Name string `json:"name"`
|
||||
// Type of resource, e.g. service
|
||||
Type string `json:"type"`
|
||||
// Endpoint resource e.g NotesService.Create
|
||||
Endpoint string `json:"endpoint"`
|
||||
}
|
||||
|
||||
// Access defines the type of access a rule grants.
|
||||
type Access int
|
||||
|
||||
const (
|
||||
// AccessGranted to a resource.
|
||||
AccessGranted Access = iota
|
||||
// AccessDenied to a resource.
|
||||
AccessDenied
|
||||
)
|
||||
|
||||
// Rule is used to verify access to a resource.
|
||||
type Rule struct {
|
||||
// Resource the rule applies to
|
||||
Resource *Resource
|
||||
// ID of the rule, e.g. "public"
|
||||
ID string
|
||||
// Scope the rule requires, a blank scope indicates open to the public and * indicates the rule
|
||||
// applies to any valid account
|
||||
Scope string
|
||||
// Access determines if the rule grants or denies access to the resource
|
||||
Access Access
|
||||
// Priority the rule should take when verifying a request, the higher the value the sooner the
|
||||
// rule will be applied
|
||||
Priority int32
|
||||
}
|
||||
|
||||
type accountKey struct{}
|
||||
|
||||
// AccountFromContext gets the account from the context, which
|
||||
// is set by the auth wrapper at the start of a call. If the account
|
||||
// is not set, a nil account will be returned. The error is only returned
|
||||
// when there was a problem retrieving an account.
|
||||
func AccountFromContext(ctx context.Context) (*Account, bool) {
|
||||
acc, ok := ctx.Value(accountKey{}).(*Account)
|
||||
return acc, ok
|
||||
}
|
||||
|
||||
// ContextWithAccount sets the account in the context.
|
||||
func ContextWithAccount(ctx context.Context, account *Account) context.Context {
|
||||
return context.WithValue(ctx, accountKey{}, account)
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/auth"
|
||||
jwtToken "go-micro.dev/v6/auth/jwt/token"
|
||||
"go-micro.dev/v6/cmd"
|
||||
)
|
||||
|
||||
func init() {
|
||||
cmd.DefaultAuths["jwt"] = NewAuth
|
||||
}
|
||||
|
||||
// NewAuth returns a new instance of the Auth service.
|
||||
func NewAuth(opts ...auth.Option) auth.Auth {
|
||||
j := new(jwt)
|
||||
j.Init(opts...)
|
||||
return j
|
||||
}
|
||||
|
||||
func NewRules() auth.Rules {
|
||||
return new(jwtRules)
|
||||
}
|
||||
|
||||
type jwt struct {
|
||||
sync.Mutex
|
||||
options auth.Options
|
||||
jwt jwtToken.Provider
|
||||
}
|
||||
|
||||
type jwtRules struct {
|
||||
sync.Mutex
|
||||
rules []*auth.Rule
|
||||
}
|
||||
|
||||
func (j *jwt) String() string {
|
||||
return "jwt"
|
||||
}
|
||||
|
||||
func (j *jwt) Init(opts ...auth.Option) {
|
||||
j.Lock()
|
||||
defer j.Unlock()
|
||||
|
||||
for _, o := range opts {
|
||||
o(&j.options)
|
||||
}
|
||||
|
||||
j.jwt = jwtToken.New(
|
||||
jwtToken.WithPrivateKey(j.options.PrivateKey),
|
||||
jwtToken.WithPublicKey(j.options.PublicKey),
|
||||
)
|
||||
}
|
||||
|
||||
func (j *jwt) Options() auth.Options {
|
||||
j.Lock()
|
||||
defer j.Unlock()
|
||||
return j.options
|
||||
}
|
||||
|
||||
func (j *jwt) Generate(id string, opts ...auth.GenerateOption) (*auth.Account, error) {
|
||||
options := auth.NewGenerateOptions(opts...)
|
||||
account := &auth.Account{
|
||||
ID: id,
|
||||
Type: options.Type,
|
||||
Scopes: options.Scopes,
|
||||
Metadata: options.Metadata,
|
||||
Issuer: j.Options().Namespace,
|
||||
}
|
||||
|
||||
// generate a JWT secret which can be provided to the Token() method
|
||||
// and exchanged for an access token
|
||||
secret, err := j.jwt.Generate(account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
account.Secret = secret.Token
|
||||
|
||||
// return the account
|
||||
return account, nil
|
||||
}
|
||||
|
||||
func (j *jwtRules) Grant(rule *auth.Rule) error {
|
||||
j.Lock()
|
||||
defer j.Unlock()
|
||||
j.rules = append(j.rules, rule)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *jwtRules) Revoke(rule *auth.Rule) error {
|
||||
j.Lock()
|
||||
defer j.Unlock()
|
||||
|
||||
rules := make([]*auth.Rule, 0, len(j.rules))
|
||||
for _, r := range j.rules {
|
||||
if r.ID != rule.ID {
|
||||
rules = append(rules, r)
|
||||
}
|
||||
}
|
||||
|
||||
j.rules = rules
|
||||
return nil
|
||||
}
|
||||
|
||||
func (j *jwtRules) Verify(acc *auth.Account, res *auth.Resource, opts ...auth.VerifyOption) error {
|
||||
j.Lock()
|
||||
defer j.Unlock()
|
||||
|
||||
var options auth.VerifyOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
return auth.Verify(j.rules, acc, res)
|
||||
}
|
||||
|
||||
func (j *jwtRules) List(opts ...auth.ListOption) ([]*auth.Rule, error) {
|
||||
j.Lock()
|
||||
defer j.Unlock()
|
||||
return j.rules, nil
|
||||
}
|
||||
|
||||
func (j *jwt) Inspect(token string) (*auth.Account, error) {
|
||||
return j.jwt.Inspect(token)
|
||||
}
|
||||
|
||||
func (j *jwt) Token(opts ...auth.TokenOption) (*auth.Token, error) {
|
||||
options := auth.NewTokenOptions(opts...)
|
||||
|
||||
secret := options.RefreshToken
|
||||
if len(options.Secret) > 0 {
|
||||
secret = options.Secret
|
||||
}
|
||||
|
||||
account, err := j.jwt.Inspect(secret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
access, err := j.jwt.Generate(account, jwtToken.WithExpiry(options.Expiry))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
refresh, err := j.jwt.Generate(account, jwtToken.WithExpiry(options.Expiry+time.Hour))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &auth.Token{
|
||||
Created: access.Created,
|
||||
Expiry: access.Expiry,
|
||||
AccessToken: access.Token,
|
||||
RefreshToken: refresh.Token,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"go-micro.dev/v6/auth"
|
||||
)
|
||||
|
||||
// authClaims to be encoded in the JWT.
|
||||
type authClaims struct {
|
||||
Type string `json:"type"`
|
||||
Scopes []string `json:"scopes"`
|
||||
Metadata map[string]string `json:"metadata"`
|
||||
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// JWT implementation of token provider.
|
||||
type JWT struct {
|
||||
opts Options
|
||||
}
|
||||
|
||||
// New returns an initialized basic provider.
|
||||
func New(opts ...Option) Provider {
|
||||
return &JWT{
|
||||
opts: NewOptions(opts...),
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a new JWT.
|
||||
func (j *JWT) Generate(acc *auth.Account, opts ...GenerateOption) (*Token, error) {
|
||||
// decode the private key
|
||||
priv, err := base64.StdEncoding.DecodeString(j.opts.PrivateKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// parse the private key
|
||||
key, err := jwt.ParseRSAPrivateKeyFromPEM(priv)
|
||||
if err != nil {
|
||||
return nil, ErrEncodingToken
|
||||
}
|
||||
|
||||
// parse the options
|
||||
options := NewGenerateOptions(opts...)
|
||||
|
||||
// generate the JWT
|
||||
expiry := time.Now().Add(options.Expiry)
|
||||
t := jwt.NewWithClaims(jwt.SigningMethodRS256, authClaims{
|
||||
acc.Type, acc.Scopes, acc.Metadata, jwt.RegisteredClaims{
|
||||
Subject: acc.ID,
|
||||
Issuer: acc.Issuer,
|
||||
ExpiresAt: jwt.NewNumericDate(expiry),
|
||||
},
|
||||
})
|
||||
tok, err := t.SignedString(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// return the token
|
||||
return &Token{
|
||||
Token: tok,
|
||||
Expiry: expiry,
|
||||
Created: time.Now(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Inspect a JWT.
|
||||
func (j *JWT) Inspect(t string) (*auth.Account, error) {
|
||||
// decode the public key
|
||||
pub, err := base64.StdEncoding.DecodeString(j.opts.PublicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// parse the public key
|
||||
res, err := jwt.ParseWithClaims(t, &authClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return jwt.ParseRSAPublicKeyFromPEM(pub)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
// validate the token
|
||||
if !res.Valid {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
claims, ok := res.Claims.(*authClaims)
|
||||
if !ok {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
// return the token
|
||||
return &auth.Account{
|
||||
ID: claims.Subject,
|
||||
Issuer: claims.Issuer,
|
||||
Type: claims.Type,
|
||||
Scopes: claims.Scopes,
|
||||
Metadata: claims.Metadata,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// String returns JWT.
|
||||
func (j *JWT) String() string {
|
||||
return "jwt"
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/auth"
|
||||
)
|
||||
|
||||
func TestGenerate(t *testing.T) {
|
||||
privKey, err := os.ReadFile("test/sample_key")
|
||||
if err != nil {
|
||||
t.Fatalf("Unable to read private key: %v", err)
|
||||
}
|
||||
|
||||
j := New(
|
||||
WithPrivateKey(string(privKey)),
|
||||
)
|
||||
|
||||
_, err = j.Generate(&auth.Account{ID: "test"})
|
||||
if err != nil {
|
||||
t.Fatalf("Generate returned %v error, expected nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspect(t *testing.T) {
|
||||
pubKey, err := os.ReadFile("test/sample_key.pub")
|
||||
if err != nil {
|
||||
t.Fatalf("Unable to read public key: %v", err)
|
||||
}
|
||||
privKey, err := os.ReadFile("test/sample_key")
|
||||
if err != nil {
|
||||
t.Fatalf("Unable to read private key: %v", err)
|
||||
}
|
||||
|
||||
j := New(
|
||||
WithPublicKey(string(pubKey)),
|
||||
WithPrivateKey(string(privKey)),
|
||||
)
|
||||
|
||||
t.Run("Valid token", func(t *testing.T) {
|
||||
md := map[string]string{"foo": "bar"}
|
||||
scopes := []string{"admin"}
|
||||
subject := "test"
|
||||
|
||||
acc := &auth.Account{ID: subject, Scopes: scopes, Metadata: md}
|
||||
tok, err := j.Generate(acc)
|
||||
if err != nil {
|
||||
t.Fatalf("Generate returned %v error, expected nil", err)
|
||||
}
|
||||
|
||||
tok2, err := j.Inspect(tok.Token)
|
||||
if err != nil {
|
||||
t.Fatalf("Inspect returned %v error, expected nil", err)
|
||||
}
|
||||
if acc.ID != subject {
|
||||
t.Errorf("Inspect returned %v as the token subject, expected %v", acc.ID, subject)
|
||||
}
|
||||
if len(tok2.Scopes) != len(scopes) {
|
||||
t.Errorf("Inspect returned %v scopes, expected %v", len(tok2.Scopes), len(scopes))
|
||||
}
|
||||
if len(tok2.Metadata) != len(md) {
|
||||
t.Errorf("Inspect returned %v as the token metadata, expected %v", tok2.Metadata, md)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Expired token", func(t *testing.T) {
|
||||
tok, err := j.Generate(&auth.Account{}, WithExpiry(-10*time.Second))
|
||||
if err != nil {
|
||||
t.Fatalf("Generate returned %v error, expected nil", err)
|
||||
}
|
||||
|
||||
if _, err = j.Inspect(tok.Token); err != ErrInvalidToken {
|
||||
t.Fatalf("Inspect returned %v error, expected %v", err, ErrInvalidToken)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Invalid token", func(t *testing.T) {
|
||||
_, err := j.Inspect("Invalid token")
|
||||
if err != ErrInvalidToken {
|
||||
t.Fatalf("Inspect returned %v error, expected %v", err, ErrInvalidToken)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/store"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
// Store to persist the tokens
|
||||
Store store.Store
|
||||
// PublicKey base64 encoded, used by JWT
|
||||
PublicKey string
|
||||
// PrivateKey base64 encoded, used by JWT
|
||||
PrivateKey string
|
||||
}
|
||||
|
||||
type Option func(o *Options)
|
||||
|
||||
// WithStore sets the token providers store.
|
||||
func WithStore(s store.Store) Option {
|
||||
return func(o *Options) {
|
||||
o.Store = s
|
||||
}
|
||||
}
|
||||
|
||||
// WithPublicKey sets the JWT public key.
|
||||
func WithPublicKey(key string) Option {
|
||||
return func(o *Options) {
|
||||
o.PublicKey = key
|
||||
}
|
||||
}
|
||||
|
||||
// WithPrivateKey sets the JWT private key.
|
||||
func WithPrivateKey(key string) Option {
|
||||
return func(o *Options) {
|
||||
o.PrivateKey = key
|
||||
}
|
||||
}
|
||||
|
||||
func NewOptions(opts ...Option) Options {
|
||||
var options Options
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
// set default store
|
||||
if options.Store == nil {
|
||||
options.Store = store.DefaultStore
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
type GenerateOptions struct {
|
||||
// Expiry for the token
|
||||
Expiry time.Duration
|
||||
}
|
||||
|
||||
type GenerateOption func(o *GenerateOptions)
|
||||
|
||||
// WithExpiry for the generated account's token expires.
|
||||
func WithExpiry(d time.Duration) GenerateOption {
|
||||
return func(o *GenerateOptions) {
|
||||
o.Expiry = d
|
||||
}
|
||||
}
|
||||
|
||||
// NewGenerateOptions from a slice of options.
|
||||
func NewGenerateOptions(opts ...GenerateOption) GenerateOptions {
|
||||
var options GenerateOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
// set default Expiry of token
|
||||
if options.Expiry == 0 {
|
||||
options.Expiry = time.Minute * 15
|
||||
}
|
||||
return options
|
||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VXg4b2o4VkllUm5XRHE2TWMxaUpwOFV5Y2lCSVRSdHcKNGRabzcweG1mbmVJV3pyM0tTTmFoU29nSmRSMGxhUXpBdVAzYWlXWElNcDJzYzhTYytCbCtMalhtQm94QnJhQgpIaDlLa0pKRWNnQUZ3czJib2pDbEpPWXhvRi9YZ0ZLU3NJbkhEckhWT3lXUEJlM2ZhZEVjNzdiK25iL2V4T3pyCjFFcnhoR2c5akZtcmtPK3M0eEdodjZNQ0F3RUFBUT09Ci0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQo=
|
||||
@@ -0,0 +1,33 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/auth"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNotFound is returned when a token cannot be found.
|
||||
ErrNotFound = errors.New("token not found")
|
||||
// ErrEncodingToken is returned when the service encounters an error during encoding.
|
||||
ErrEncodingToken = errors.New("error encoding the token")
|
||||
// ErrInvalidToken is returned when the token provided is not valid.
|
||||
ErrInvalidToken = errors.New("invalid token provided")
|
||||
)
|
||||
|
||||
// Provider generates and inspects tokens.
|
||||
type Provider interface {
|
||||
Generate(account *auth.Account, opts ...GenerateOption) (*Token, error)
|
||||
Inspect(token string) (*auth.Account, error)
|
||||
String() string
|
||||
}
|
||||
|
||||
type Token struct {
|
||||
// The actual token
|
||||
Token string `json:"token"`
|
||||
// Time of token creation
|
||||
Created time.Time `json:"created"`
|
||||
// Time of token expiry
|
||||
Expiry time.Time `json:"expiry"`
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
DefaultAuth = NewAuth()
|
||||
)
|
||||
|
||||
func NewAuth(opts ...Option) Auth {
|
||||
options := Options{}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
return &noop{
|
||||
opts: options,
|
||||
}
|
||||
}
|
||||
|
||||
func NewRules() Rules {
|
||||
return new(noopRules)
|
||||
}
|
||||
|
||||
type noop struct {
|
||||
opts Options
|
||||
}
|
||||
|
||||
type noopRules struct{}
|
||||
|
||||
// String returns the name of the implementation.
|
||||
func (n *noop) String() string {
|
||||
return "noop"
|
||||
}
|
||||
|
||||
// Init the auth.
|
||||
func (n *noop) Init(opts ...Option) {
|
||||
for _, o := range opts {
|
||||
o(&n.opts)
|
||||
}
|
||||
}
|
||||
|
||||
// Options set for auth.
|
||||
func (n *noop) Options() Options {
|
||||
return n.opts
|
||||
}
|
||||
|
||||
// Generate a new account.
|
||||
func (n *noop) Generate(id string, opts ...GenerateOption) (*Account, error) {
|
||||
options := NewGenerateOptions(opts...)
|
||||
|
||||
return &Account{
|
||||
ID: id,
|
||||
Secret: options.Secret,
|
||||
Metadata: options.Metadata,
|
||||
Scopes: options.Scopes,
|
||||
Issuer: n.Options().Namespace,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Grant access to a resource.
|
||||
func (n *noopRules) Grant(rule *Rule) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Revoke access to a resource.
|
||||
func (n *noopRules) Revoke(rule *Rule) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Rules used to verify requests
|
||||
// Verify an account has access to a resource.
|
||||
func (n *noopRules) Verify(acc *Account, res *Resource, opts ...VerifyOption) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *noopRules) List(opts ...ListOption) ([]*Rule, error) {
|
||||
return []*Rule{}, nil
|
||||
}
|
||||
|
||||
// Inspect a token.
|
||||
func (n *noop) Inspect(token string) (*Account, error) {
|
||||
return &Account{ID: uuid.New().String(), Issuer: n.Options().Namespace}, nil
|
||||
}
|
||||
|
||||
// Token generation using an account id and secret.
|
||||
func (n *noop) Token(opts ...TokenOption) (*Token, error) {
|
||||
return &Token{}, nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Package noop provides a no-op auth implementation for testing and development.
|
||||
//
|
||||
// The noop auth provider:
|
||||
// - Accepts any token (always returns a valid account)
|
||||
// - Grants all permissions (no actual authorization)
|
||||
// - Generates tokens (but doesn't verify them)
|
||||
//
|
||||
// This is useful for:
|
||||
// - Local development
|
||||
// - Testing
|
||||
// - Prototyping
|
||||
//
|
||||
// DO NOT use in production. Use JWT auth or implement a custom auth provider instead.
|
||||
package noop
|
||||
|
||||
import (
|
||||
"go-micro.dev/v6/auth"
|
||||
)
|
||||
|
||||
// NewAuth returns a new noop auth provider.
|
||||
//
|
||||
// The noop provider accepts all tokens and grants all permissions.
|
||||
// This is for development and testing only - DO NOT use in production.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// authProvider := noop.NewAuth()
|
||||
// account, _ := authProvider.Generate("user123")
|
||||
// token, _ := authProvider.Token(auth.WithCredentials(account.ID, account.Secret))
|
||||
func NewAuth(opts ...auth.Option) auth.Auth {
|
||||
return auth.NewAuth(opts...)
|
||||
}
|
||||
|
||||
// NewRules returns a new noop rules implementation.
|
||||
//
|
||||
// The noop rules implementation grants all access and doesn't enforce any rules.
|
||||
// This is for development and testing only.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// rules := noop.NewRules()
|
||||
// err := rules.Verify(account, resource) // Always returns nil
|
||||
func NewRules() auth.Rules {
|
||||
return auth.NewRules()
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go-micro.dev/v6/logger"
|
||||
)
|
||||
|
||||
func NewOptions(opts ...Option) Options {
|
||||
options := Options{
|
||||
Logger: logger.DefaultLogger,
|
||||
}
|
||||
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
// Logger is the underline logger
|
||||
Logger logger.Logger
|
||||
// Token is the services token used to authenticate itself
|
||||
Token *Token
|
||||
// Namespace the service belongs to
|
||||
Namespace string
|
||||
// ID is the services auth ID
|
||||
ID string
|
||||
// Secret is used to authenticate the service
|
||||
Secret string
|
||||
// PublicKey for decoding JWTs
|
||||
PublicKey string
|
||||
// PrivateKey for encoding JWTs
|
||||
PrivateKey string
|
||||
// Addrs sets the addresses of auth
|
||||
Addrs []string
|
||||
}
|
||||
|
||||
type Option func(o *Options)
|
||||
|
||||
// Addrs is the auth addresses to use.
|
||||
func Addrs(addrs ...string) Option {
|
||||
return func(o *Options) {
|
||||
o.Addrs = addrs
|
||||
}
|
||||
}
|
||||
|
||||
// Namespace the service belongs to.
|
||||
func Namespace(n string) Option {
|
||||
return func(o *Options) {
|
||||
o.Namespace = n
|
||||
}
|
||||
}
|
||||
|
||||
// PublicKey is the JWT public key.
|
||||
func PublicKey(key string) Option {
|
||||
return func(o *Options) {
|
||||
o.PublicKey = key
|
||||
}
|
||||
}
|
||||
|
||||
// PrivateKey is the JWT private key.
|
||||
func PrivateKey(key string) Option {
|
||||
return func(o *Options) {
|
||||
o.PrivateKey = key
|
||||
}
|
||||
}
|
||||
|
||||
// WithLogger sets the underline logger.
|
||||
func WithLogger(l logger.Logger) Option {
|
||||
return func(o *Options) {
|
||||
o.Logger = l
|
||||
}
|
||||
}
|
||||
|
||||
// Credentials sets the auth credentials.
|
||||
func Credentials(id, secret string) Option {
|
||||
return func(o *Options) {
|
||||
o.ID = id
|
||||
o.Secret = secret
|
||||
}
|
||||
}
|
||||
|
||||
// ClientToken sets the auth token to use when making requests.
|
||||
func ClientToken(token *Token) Option {
|
||||
return func(o *Options) {
|
||||
o.Token = token
|
||||
}
|
||||
}
|
||||
|
||||
type GenerateOptions struct {
|
||||
// Metadata associated with the account
|
||||
Metadata map[string]string
|
||||
// Provider of the account, e.g. oauth
|
||||
Provider string
|
||||
// Type of the account, e.g. user
|
||||
Type string
|
||||
// Secret used to authenticate the account
|
||||
Secret string
|
||||
// Scopes the account has access too
|
||||
Scopes []string
|
||||
}
|
||||
|
||||
type GenerateOption func(o *GenerateOptions)
|
||||
|
||||
// WithSecret for the generated account.
|
||||
func WithSecret(s string) GenerateOption {
|
||||
return func(o *GenerateOptions) {
|
||||
o.Secret = s
|
||||
}
|
||||
}
|
||||
|
||||
// WithType for the generated account.
|
||||
func WithType(t string) GenerateOption {
|
||||
return func(o *GenerateOptions) {
|
||||
o.Type = t
|
||||
}
|
||||
}
|
||||
|
||||
// WithMetadata for the generated account.
|
||||
func WithMetadata(md map[string]string) GenerateOption {
|
||||
return func(o *GenerateOptions) {
|
||||
o.Metadata = md
|
||||
}
|
||||
}
|
||||
|
||||
// WithProvider for the generated account.
|
||||
func WithProvider(p string) GenerateOption {
|
||||
return func(o *GenerateOptions) {
|
||||
o.Provider = p
|
||||
}
|
||||
}
|
||||
|
||||
// WithScopes for the generated account.
|
||||
func WithScopes(s ...string) GenerateOption {
|
||||
return func(o *GenerateOptions) {
|
||||
o.Scopes = s
|
||||
}
|
||||
}
|
||||
|
||||
// NewGenerateOptions from a slice of options.
|
||||
func NewGenerateOptions(opts ...GenerateOption) GenerateOptions {
|
||||
var options GenerateOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
type TokenOptions struct {
|
||||
// ID for the account
|
||||
ID string
|
||||
// Secret for the account
|
||||
Secret string
|
||||
// RefreshToken is used to refesh a token
|
||||
RefreshToken string
|
||||
// Expiry is the time the token should live for
|
||||
Expiry time.Duration
|
||||
}
|
||||
|
||||
type TokenOption func(o *TokenOptions)
|
||||
|
||||
// WithExpiry for the token.
|
||||
func WithExpiry(ex time.Duration) TokenOption {
|
||||
return func(o *TokenOptions) {
|
||||
o.Expiry = ex
|
||||
}
|
||||
}
|
||||
|
||||
func WithCredentials(id, secret string) TokenOption {
|
||||
return func(o *TokenOptions) {
|
||||
o.ID = id
|
||||
o.Secret = secret
|
||||
}
|
||||
}
|
||||
|
||||
func WithToken(rt string) TokenOption {
|
||||
return func(o *TokenOptions) {
|
||||
o.RefreshToken = rt
|
||||
}
|
||||
}
|
||||
|
||||
// NewTokenOptions from a slice of options.
|
||||
func NewTokenOptions(opts ...TokenOption) TokenOptions {
|
||||
var options TokenOptions
|
||||
for _, o := range opts {
|
||||
o(&options)
|
||||
}
|
||||
|
||||
// set default expiry of token
|
||||
if options.Expiry == 0 {
|
||||
options.Expiry = time.Minute
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
type VerifyOptions struct {
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
type VerifyOption func(o *VerifyOptions)
|
||||
|
||||
func VerifyContext(ctx context.Context) VerifyOption {
|
||||
return func(o *VerifyOptions) {
|
||||
o.Context = ctx
|
||||
}
|
||||
}
|
||||
|
||||
type ListOptions struct {
|
||||
Context context.Context
|
||||
}
|
||||
|
||||
type ListOption func(o *ListOptions)
|
||||
|
||||
func RulesContext(ctx context.Context) ListOption {
|
||||
return func(o *ListOptions) {
|
||||
o.Context = ctx
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Verify an account has access to a resource using the rules provided. If the account does not have
|
||||
// access an error will be returned. If there are no rules provided which match the resource, an error
|
||||
// will be returned.
|
||||
func Verify(rules []*Rule, acc *Account, res *Resource) error {
|
||||
// the rule is only to be applied if the type matches the resource or is catch-all (*)
|
||||
validTypes := []string{"*", res.Type}
|
||||
|
||||
// the rule is only to be applied if the name matches the resource or is catch-all (*)
|
||||
validNames := []string{"*", res.Name}
|
||||
|
||||
// rules can have wildcard excludes on endpoints since this can also be a path for web services,
|
||||
// e.g. /foo/* would include /foo/bar. We also want to check for wildcards and the exact endpoint
|
||||
validEndpoints := []string{"*", res.Endpoint}
|
||||
if comps := strings.Split(res.Endpoint, "/"); len(comps) > 1 {
|
||||
for i := 1; i < len(comps)+1; i++ {
|
||||
wildcard := fmt.Sprintf("%v/*", strings.Join(comps[0:i], "/"))
|
||||
validEndpoints = append(validEndpoints, wildcard)
|
||||
}
|
||||
}
|
||||
|
||||
// filter the rules to the ones which match the criteria above
|
||||
filteredRules := make([]*Rule, 0)
|
||||
for _, rule := range rules {
|
||||
if !include(validTypes, rule.Resource.Type) {
|
||||
continue
|
||||
}
|
||||
if !include(validNames, rule.Resource.Name) {
|
||||
continue
|
||||
}
|
||||
if !include(validEndpoints, rule.Resource.Endpoint) {
|
||||
continue
|
||||
}
|
||||
filteredRules = append(filteredRules, rule)
|
||||
}
|
||||
|
||||
// sort the filtered rules by priority, highest to lowest
|
||||
sort.SliceStable(filteredRules, func(i, j int) bool {
|
||||
return filteredRules[i].Priority > filteredRules[j].Priority
|
||||
})
|
||||
|
||||
// loop through the rules and check for a rule which applies to this account
|
||||
for _, rule := range filteredRules {
|
||||
// a blank scope indicates the rule applies to everyone, even nil accounts
|
||||
if rule.Scope == ScopePublic && rule.Access == AccessDenied {
|
||||
return ErrForbidden
|
||||
} else if rule.Scope == ScopePublic && rule.Access == AccessGranted {
|
||||
return nil
|
||||
}
|
||||
|
||||
// all further checks require an account
|
||||
if acc == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// this rule applies to any account
|
||||
if rule.Scope == ScopeAccount && rule.Access == AccessDenied {
|
||||
return ErrForbidden
|
||||
} else if rule.Scope == ScopeAccount && rule.Access == AccessGranted {
|
||||
return nil
|
||||
}
|
||||
|
||||
// if the account has the necessary scope
|
||||
if include(acc.Scopes, rule.Scope) && rule.Access == AccessDenied {
|
||||
return ErrForbidden
|
||||
} else if include(acc.Scopes, rule.Scope) && rule.Access == AccessGranted {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// if no rules matched then return forbidden
|
||||
return ErrForbidden
|
||||
}
|
||||
|
||||
// include is a helper function which checks to see if the slice contains the value. includes is
|
||||
// not case sensitive.
|
||||
func include(slice []string, val string) bool {
|
||||
for _, s := range slice {
|
||||
if strings.EqualFold(s, val) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestVerify(t *testing.T) {
|
||||
srvResource := &Resource{
|
||||
Type: "service",
|
||||
Name: "go.micro.service.foo",
|
||||
Endpoint: "Foo.Bar",
|
||||
}
|
||||
|
||||
webResource := &Resource{
|
||||
Type: "service",
|
||||
Name: "go.micro.web.foo",
|
||||
Endpoint: "/foo/bar",
|
||||
}
|
||||
|
||||
catchallResource := &Resource{
|
||||
Type: "*",
|
||||
Name: "*",
|
||||
Endpoint: "*",
|
||||
}
|
||||
|
||||
tt := []struct {
|
||||
Name string
|
||||
Rules []*Rule
|
||||
Account *Account
|
||||
Resource *Resource
|
||||
Error error
|
||||
}{
|
||||
{
|
||||
Name: "NoRules",
|
||||
Rules: []*Rule{},
|
||||
Account: nil,
|
||||
Resource: srvResource,
|
||||
Error: ErrForbidden,
|
||||
},
|
||||
{
|
||||
Name: "CatchallPublicAccount",
|
||||
Account: &Account{},
|
||||
Resource: srvResource,
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "",
|
||||
Resource: catchallResource,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "CatchallPublicNoAccount",
|
||||
Resource: srvResource,
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "",
|
||||
Resource: catchallResource,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "CatchallPrivateAccount",
|
||||
Account: &Account{},
|
||||
Resource: srvResource,
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: catchallResource,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "CatchallPrivateNoAccount",
|
||||
Resource: srvResource,
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: catchallResource,
|
||||
},
|
||||
},
|
||||
Error: ErrForbidden,
|
||||
},
|
||||
{
|
||||
Name: "CatchallServiceRuleMatch",
|
||||
Resource: srvResource,
|
||||
Account: &Account{},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: &Resource{
|
||||
Type: srvResource.Type,
|
||||
Name: srvResource.Name,
|
||||
Endpoint: "*",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "CatchallServiceRuleNoMatch",
|
||||
Resource: srvResource,
|
||||
Account: &Account{},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: &Resource{
|
||||
Type: srvResource.Type,
|
||||
Name: "wrongname",
|
||||
Endpoint: "*",
|
||||
},
|
||||
},
|
||||
},
|
||||
Error: ErrForbidden,
|
||||
},
|
||||
{
|
||||
Name: "ExactRuleValidScope",
|
||||
Resource: srvResource,
|
||||
Account: &Account{
|
||||
Scopes: []string{"neededscope"},
|
||||
},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "neededscope",
|
||||
Resource: srvResource,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "ExactRuleInvalidScope",
|
||||
Resource: srvResource,
|
||||
Account: &Account{
|
||||
Scopes: []string{"neededscope"},
|
||||
},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "invalidscope",
|
||||
Resource: srvResource,
|
||||
},
|
||||
},
|
||||
Error: ErrForbidden,
|
||||
},
|
||||
{
|
||||
Name: "CatchallDenyWithAccount",
|
||||
Resource: srvResource,
|
||||
Account: &Account{},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: catchallResource,
|
||||
Access: AccessDenied,
|
||||
},
|
||||
},
|
||||
Error: ErrForbidden,
|
||||
},
|
||||
{
|
||||
Name: "CatchallDenyWithNoAccount",
|
||||
Resource: srvResource,
|
||||
Account: &Account{},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: catchallResource,
|
||||
Access: AccessDenied,
|
||||
},
|
||||
},
|
||||
Error: ErrForbidden,
|
||||
},
|
||||
{
|
||||
Name: "RulePriorityGrantFirst",
|
||||
Resource: srvResource,
|
||||
Account: &Account{},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: catchallResource,
|
||||
Access: AccessGranted,
|
||||
Priority: 1,
|
||||
},
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: catchallResource,
|
||||
Access: AccessDenied,
|
||||
Priority: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "RulePriorityDenyFirst",
|
||||
Resource: srvResource,
|
||||
Account: &Account{},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: catchallResource,
|
||||
Access: AccessGranted,
|
||||
Priority: 0,
|
||||
},
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: catchallResource,
|
||||
Access: AccessDenied,
|
||||
Priority: 1,
|
||||
},
|
||||
},
|
||||
Error: ErrForbidden,
|
||||
},
|
||||
{
|
||||
Name: "WebExactEndpointValid",
|
||||
Resource: webResource,
|
||||
Account: &Account{},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: webResource,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "WebExactEndpointInalid",
|
||||
Resource: webResource,
|
||||
Account: &Account{},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: &Resource{
|
||||
Type: webResource.Type,
|
||||
Name: webResource.Name,
|
||||
Endpoint: "invalidendpoint",
|
||||
},
|
||||
},
|
||||
},
|
||||
Error: ErrForbidden,
|
||||
},
|
||||
{
|
||||
Name: "WebWildcardEndpoint",
|
||||
Resource: webResource,
|
||||
Account: &Account{},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: &Resource{
|
||||
Type: webResource.Type,
|
||||
Name: webResource.Name,
|
||||
Endpoint: "*",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "WebWildcardPathEndpointValid",
|
||||
Resource: webResource,
|
||||
Account: &Account{},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: &Resource{
|
||||
Type: webResource.Type,
|
||||
Name: webResource.Name,
|
||||
Endpoint: "/foo/*",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "WebWildcardPathEndpointInvalid",
|
||||
Resource: webResource,
|
||||
Account: &Account{},
|
||||
Rules: []*Rule{
|
||||
{
|
||||
Scope: "*",
|
||||
Resource: &Resource{
|
||||
Type: webResource.Type,
|
||||
Name: webResource.Name,
|
||||
Endpoint: "/bar/*",
|
||||
},
|
||||
},
|
||||
},
|
||||
Error: ErrForbidden,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tt {
|
||||
t.Run(tc.Name, func(t *testing.T) {
|
||||
if err := Verify(tc.Rules, tc.Account, tc.Resource); err != tc.Error {
|
||||
t.Errorf("Expected %v but got %v", tc.Error, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user