|
1
|
|
|
package preshared |
|
2
|
|
|
|
|
3
|
|
|
import ( |
|
4
|
|
|
"context" |
|
5
|
|
|
|
|
6
|
|
|
"google.golang.org/grpc/codes" |
|
7
|
|
|
"google.golang.org/grpc/status" |
|
8
|
|
|
|
|
9
|
|
|
grpcAuth "github.com/grpc-ecosystem/go-grpc-middleware/auth" |
|
10
|
|
|
"github.com/pkg/errors" |
|
11
|
|
|
|
|
12
|
|
|
"github.com/Permify/permify/internal/config" |
|
13
|
|
|
base "github.com/Permify/permify/pkg/pb/base/v1" |
|
14
|
|
|
) |
|
15
|
|
|
|
|
16
|
|
|
// KeyAuthenticator - Interface for key authenticator |
|
17
|
|
|
type KeyAuthenticator interface { |
|
18
|
|
|
Authenticate(ctx context.Context) error |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
// KeyAuthn - Authentication Keys Structure |
|
22
|
|
|
type KeyAuthn struct { |
|
23
|
|
|
keys map[string]struct{} |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
// NewKeyAuthn - Create New Authenticated Keys |
|
27
|
|
|
func NewKeyAuthn(_ context.Context, cfg config.Preshared) (*KeyAuthn, error) { |
|
28
|
|
|
if len(cfg.Keys) < 1 { |
|
29
|
|
|
return nil, errors.New("pre shared key authn must have at least one key") |
|
30
|
|
|
} |
|
31
|
|
|
mapKeys := make(map[string]struct{}) |
|
32
|
|
|
for _, k := range cfg.Keys { |
|
33
|
|
|
mapKeys[k] = struct{}{} |
|
34
|
|
|
} |
|
35
|
|
|
return &KeyAuthn{ |
|
36
|
|
|
keys: mapKeys, |
|
37
|
|
|
}, nil |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
// Authenticate - Checking whether any API request contain keys |
|
41
|
|
|
func (a *KeyAuthn) Authenticate(ctx context.Context) error { |
|
42
|
|
|
key, err := grpcAuth.AuthFromMD(ctx, "Bearer") |
|
43
|
|
|
if err != nil { |
|
44
|
|
|
return errors.New(base.ErrorCode_ERROR_CODE_MISSING_BEARER_TOKEN.String()) |
|
45
|
|
|
} |
|
46
|
|
|
if _, found := a.keys[key]; found { |
|
47
|
|
|
return nil |
|
48
|
|
|
} |
|
49
|
|
|
return status.Error(codes.Unauthenticated, base.ErrorCode_ERROR_CODE_INVALID_KEY.String()) |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
// Get Request Metadata - gets the current request metadata, refreshing tokens |
|
53
|
|
|
// if required |
|
54
|
|
|
func (a *KeyAuthn) GetRequestMetadata(_ context.Context, uri ...string) (map[string]string, error) { |
|
55
|
|
|
return map[string]string{ |
|
56
|
|
|
"Authorization": "Bearer " + "test", |
|
57
|
|
|
}, nil |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
// RequireTransportSecurity indicates whether the credentials requires |
|
61
|
|
|
// transport security. |
|
62
|
|
|
func (a *KeyAuthn) RequireTransportSecurity() bool { |
|
63
|
|
|
return true |
|
64
|
|
|
} |
|
65
|
|
|
|