-
Notifications
You must be signed in to change notification settings - Fork 207
Add authentication logic for API key #1193
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") | ||
|
|
||
| go_library( | ||
| name = "go_default_library", | ||
| srcs = ["verifier.go"], | ||
| importpath = "github.com/pipe-cd/pipe/pkg/app/api/apikeyverifier", | ||
| visibility = ["//visibility:public"], | ||
| deps = [ | ||
| "//pkg/cache:go_default_library", | ||
| "//pkg/cache/memorycache:go_default_library", | ||
| "//pkg/model:go_default_library", | ||
| "@org_uber_go_zap//:go_default_library", | ||
| ], | ||
| ) | ||
|
|
||
| go_test( | ||
| name = "go_default_test", | ||
| size = "small", | ||
| srcs = ["verifier_test.go"], | ||
| embed = [":go_default_library"], | ||
| deps = [ | ||
| "//pkg/model:go_default_library", | ||
| "@com_github_stretchr_testify//assert:go_default_library", | ||
| "@com_github_stretchr_testify//require:go_default_library", | ||
| "@org_golang_google_protobuf//proto:go_default_library", | ||
| "@org_uber_go_zap//:go_default_library", | ||
| ], | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| // Copyright 2020 The PipeCD Authors. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package apikeyverifier | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "time" | ||
|
|
||
| "go.uber.org/zap" | ||
|
|
||
| "github.com/pipe-cd/pipe/pkg/cache" | ||
| "github.com/pipe-cd/pipe/pkg/cache/memorycache" | ||
| "github.com/pipe-cd/pipe/pkg/model" | ||
| ) | ||
|
|
||
| type apiKeyGetter interface { | ||
| GetAPIKey(ctx context.Context, id string) (*model.APIKey, error) | ||
| } | ||
|
|
||
| type Verifier struct { | ||
| apiKeyCache cache.Cache | ||
| apiKeyStore apiKeyGetter | ||
| logger *zap.Logger | ||
| } | ||
|
|
||
| func NewVerifier(ctx context.Context, getter apiKeyGetter, logger *zap.Logger) *Verifier { | ||
| return &Verifier{ | ||
| apiKeyCache: memorycache.NewTTLCache(ctx, 5*time.Minute, time.Minute), | ||
| apiKeyStore: getter, | ||
| logger: logger, | ||
| } | ||
| } | ||
|
|
||
| func (v *Verifier) Verify(ctx context.Context, key string) (*model.APIKey, error) { | ||
| keyID, err := model.ExtractAPIKeyID(key) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| var apiKey *model.APIKey | ||
| item, err := v.apiKeyCache.Get(keyID) | ||
| if err == nil { | ||
| apiKey = item.(*model.APIKey) | ||
| if err := checkAPIKey(apiKey, keyID, key); err != nil { | ||
| return nil, err | ||
| } | ||
| return apiKey, nil | ||
| } | ||
|
|
||
| // If the cache data was not found, | ||
| // we have to retrieve from datastore and save it to the cache. | ||
| apiKey, err = v.apiKeyStore.GetAPIKey(ctx, keyID) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("unable to find API key %s from datastore, %w", keyID, err) | ||
| } | ||
|
|
||
| if err := v.apiKeyCache.Put(keyID, apiKey); err != nil { | ||
| v.logger.Warn("unable to store API key in memory cache", zap.Error(err)) | ||
| } | ||
| if err := checkAPIKey(apiKey, keyID, key); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| return apiKey, nil | ||
| } | ||
|
|
||
| func checkAPIKey(apiKey *model.APIKey, id, key string) error { | ||
| if apiKey.Disabled { | ||
| return fmt.Errorf("the api key %s was already disabled", id) | ||
| } | ||
|
|
||
| if err := apiKey.CompareKey(key); err != nil { | ||
| return fmt.Errorf("invalid api key %s: %w", id, err) | ||
| } | ||
|
|
||
| return nil | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| // Copyright 2020 The PipeCD Authors. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package apikeyverifier | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| "go.uber.org/zap" | ||
| "google.golang.org/protobuf/proto" | ||
|
|
||
| "github.com/pipe-cd/pipe/pkg/model" | ||
| ) | ||
|
|
||
| type fakeAPIKeyGetter struct { | ||
| calls int | ||
| apiKeys map[string]*model.APIKey | ||
| } | ||
|
|
||
| func (g *fakeAPIKeyGetter) GetAPIKey(_ context.Context, id string) (*model.APIKey, error) { | ||
| g.calls++ | ||
| p, ok := g.apiKeys[id] | ||
| if ok { | ||
| msg := proto.Clone(p) | ||
| return msg.(*model.APIKey), nil | ||
| } | ||
| return nil, fmt.Errorf("not found") | ||
| } | ||
|
|
||
| func TestVerify(t *testing.T) { | ||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| defer cancel() | ||
|
|
||
| var id1 = "test-api-key" | ||
| key1, hash1, err := model.GenerateAPIKey(id1) | ||
| require.NoError(t, err) | ||
|
|
||
| var id2 = "disabled-api-key" | ||
| key2, hash2, err := model.GenerateAPIKey(id2) | ||
| require.NoError(t, err) | ||
|
|
||
| apiKeyGetter := &fakeAPIKeyGetter{ | ||
| apiKeys: map[string]*model.APIKey{ | ||
| id1: { | ||
| Id: id1, | ||
| Name: id1, | ||
| KeyHash: hash1, | ||
| ProjectId: "test-project", | ||
| }, | ||
| id2: { | ||
| Id: id2, | ||
| Name: id2, | ||
| KeyHash: hash2, | ||
| ProjectId: "test-project", | ||
| Disabled: true, | ||
| }, | ||
| }, | ||
| } | ||
| v := NewVerifier(ctx, apiKeyGetter, zap.NewNop()) | ||
|
|
||
| // Not found key. | ||
| notFoundKey, _, err := model.GenerateAPIKey("not-found-api-key") | ||
| require.NoError(t, err) | ||
|
|
||
| apiKey, err := v.Verify(ctx, notFoundKey) | ||
| require.Nil(t, apiKey) | ||
| require.NotNil(t, err) | ||
| assert.Equal(t, "unable to find API key not-found-api-key from datastore, not found", err.Error()) | ||
| require.Equal(t, 1, apiKeyGetter.calls) | ||
|
|
||
| // Found key but it was disabled. | ||
| apiKey, err = v.Verify(ctx, key2) | ||
| require.Nil(t, apiKey) | ||
| require.NotNil(t, err) | ||
| assert.Equal(t, "the api key disabled-api-key was already disabled", err.Error()) | ||
| require.Equal(t, 2, apiKeyGetter.calls) | ||
|
|
||
| // Found key but invalid secret. | ||
| apiKey, err = v.Verify(ctx, fmt.Sprintf("%s.invalidhash", id1)) | ||
| require.Nil(t, apiKey) | ||
| require.NotNil(t, err) | ||
| assert.Equal(t, "invalid api key test-api-key: wrong api key test-api-key.invalidhash: crypto/bcrypt: hashedPassword is not the hash of the given password", err.Error()) | ||
| require.Equal(t, 3, apiKeyGetter.calls) | ||
|
|
||
| // OK. | ||
| apiKey, err = v.Verify(ctx, key1) | ||
| assert.Equal(t, id1, apiKey.Name) | ||
| assert.Nil(t, err) | ||
| require.Equal(t, 3, apiKeyGetter.calls) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
does this change due to some change in requirement? 👀
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To be honest, I'm wondering about the APIKey's length.
Currently, the returned APIKey contains 2 parts like this "UUID-PART.RANDOM-PART".
If the random part is 50 characters then the whole APIKey looks pretty long.
So I reduced the length of that part to 32 and the entire length of the APIKey is 64 characters.
(Not sure, but maybe we also should encrypt the APIKey (e.g. base64) to get a better look 🤔 )
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it would be better if the key has a specific length in all cases, will reduce other issues around miss/conflict setting. What do you think? 🤔
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You are right. Nice catch!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
let's address it by another PR 😄