-
Notifications
You must be signed in to change notification settings - Fork 108
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
viperx: Added viper BindEnvsToSchema helper #85
Merged
Merged
Changes from 1 commit
Commits
Show all changes
4 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 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 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 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,115 @@ | ||
package viperx | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"strings" | ||
|
||
"github.com/pkg/errors" | ||
|
||
"github.com/tidwall/gjson" | ||
|
||
"github.com/ory/viper" | ||
|
||
"github.com/ory/x/stringslice" | ||
) | ||
|
||
const ( | ||
none = iota - 1 | ||
properties | ||
ref | ||
allOf | ||
anyOf | ||
oneOf | ||
) | ||
|
||
var keys = []string{ | ||
"properties", | ||
"$ref", | ||
"allOf", | ||
"anyOf", | ||
"oneOf", | ||
} | ||
|
||
// BindEnvsToSchema uses all keys it can find from `` | ||
func BindEnvsToSchema(schema json.RawMessage) error { | ||
keys, err := getSchemaKeys(string(schema), string(schema), []string{}, []string{}) | ||
if err != nil { | ||
return err | ||
} | ||
return viper.BindEnv(keys...) | ||
} | ||
|
||
func getSchemaKeys(root, current string, parents []string, traversed []string) ([]string, error) { | ||
var foundKey = -1 | ||
var result gjson.Result | ||
for i, value := range gjson.GetMany( | ||
current, | ||
keys..., | ||
) { | ||
if value.Exists() { | ||
foundKey = i | ||
result = value | ||
break | ||
} | ||
} | ||
|
||
if foundKey == none { | ||
return nil, nil | ||
} | ||
|
||
var paths []string | ||
var err error | ||
|
||
traversed = append(traversed, keys[foundKey]) | ||
switch foundKey { | ||
case properties: | ||
result.ForEach(func(k, v gjson.Result) bool { | ||
this := append(parents, k.String()) | ||
paths = append(paths, strings.Join(this, ".")) | ||
if v.IsObject() { | ||
merge, innerErr := getSchemaKeys(root, v.Raw, this, traversed) | ||
if innerErr != nil { | ||
err = innerErr | ||
return false // break out | ||
} | ||
paths = append(paths, merge...) | ||
} | ||
return true // run through all keys | ||
}) | ||
case ref: | ||
defpath := result.String() | ||
if !strings.HasPrefix(defpath, "#/definitions/") { | ||
return nil, errors.New("only references to #/definitions/ are supported") | ||
} | ||
path := strings.ReplaceAll(strings.TrimPrefix(defpath, "#/"), "/", ".") | ||
if stringslice.HasI(traversed, path) { | ||
return nil, errors.Errorf("detected circular dependency in schema path: %v", traversed) | ||
} | ||
merge, err := getSchemaKeys(root, gjson.Get(root, path).Raw, parents, append(traversed, path)) | ||
if err != nil { | ||
return nil, err | ||
} | ||
paths = append(paths, merge...) | ||
case allOf: | ||
fallthrough | ||
case oneOf: | ||
fallthrough | ||
case anyOf: | ||
for _, item := range result.Array() { | ||
merge, err := getSchemaKeys(root, item.Raw, parents, traversed) | ||
if err != nil { | ||
return nil, err | ||
} | ||
paths = append(paths, merge...) | ||
} | ||
default: | ||
panic(fmt.Sprintf("found unexpected key: %d", foundKey)) | ||
} | ||
|
||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return stringslice.Unique(paths), err | ||
} |
This file contains 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,110 @@ | ||
package viperx | ||
|
||
import ( | ||
"fmt" | ||
"io/ioutil" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestBindEnv(t *testing.T) { | ||
readFile := func(path string) string { | ||
schema, err := ioutil.ReadFile(path) | ||
require.NoError(t, err) | ||
return string(schema) | ||
} | ||
|
||
for k, tc := range []struct { | ||
schema string | ||
expectErr bool | ||
expectedKeys []string | ||
}{ | ||
{ | ||
schema: readFile("./stub/.oathkeeper.schema.json"), | ||
expectedKeys: []string{ | ||
"serve", "serve.api", "serve.api.port", "serve.api.host", "serve.api.cors", | ||
"serve.api.cors.enabled", "serve.api.cors.allowed_origins", "serve.api.cors.allowed_methods", | ||
"serve.api.cors.allowed_headers", "serve.api.cors.exposed_headers", "serve.api.cors.allow_credentials", | ||
"serve.api.cors.max_age", "serve.api.cors.debug", "serve.api.tls", "serve.api.tls.key", "serve.api.tls.key.path", | ||
"serve.api.tls.key.base64", "serve.api.tls.cert", "serve.api.tls.cert.path", "serve.api.tls.cert.base64", "serve.proxy", | ||
"serve.proxy.port", "serve.proxy.host", "serve.proxy.timeout", "serve.proxy.timeout.read", "serve.proxy.timeout.write", | ||
"serve.proxy.timeout.idle", "serve.proxy.cors", "serve.proxy.cors.enabled", "serve.proxy.cors.allowed_origins", | ||
"serve.proxy.cors.allowed_methods", "serve.proxy.cors.allowed_headers", "serve.proxy.cors.exposed_headers", | ||
"serve.proxy.cors.allow_credentials", "serve.proxy.cors.max_age", "serve.proxy.cors.debug", "serve.proxy.tls", "serve.proxy.tls.key", | ||
"serve.proxy.tls.key.path", "serve.proxy.tls.key.base64", "serve.proxy.tls.cert", "serve.proxy.tls.cert.path", "serve.proxy.tls.cert.base64", | ||
"access_rules", "access_rules.repositories", "authenticators", "authenticators.anonymous", | ||
"authenticators.anonymous.enabled", "authenticators.anonymous.config", "authenticators.anonymous.config.subject", "authenticators.noop", | ||
"authenticators.noop.enabled", "authenticators.unauthorized", "authenticators.unauthorized.enabled", "authenticators.cookie_session", | ||
"authenticators.cookie_session.enabled", "authenticators.cookie_session.config", "authenticators.cookie_session.config.check_session_url", | ||
"authenticators.cookie_session.config.only", "authenticators.jwt", "authenticators.jwt.enabled", "authenticators.jwt.config", | ||
"authenticators.jwt.config.required_scope", "authenticators.jwt.config.target_audience", "authenticators.jwt.config.trusted_issuers", | ||
"authenticators.jwt.config.allowed_algorithms", "authenticators.jwt.config.jwks_urls", "authenticators.jwt.config.scope_strategy", | ||
"authenticators.jwt.config.token_from", "authenticators.jwt.config.token_from.header", "authenticators.jwt.config.token_from.query_parameter", | ||
"authenticators.oauth2_client_credentials", "authenticators.oauth2_client_credentials.enabled", "authenticators.oauth2_client_credentials.config", | ||
"authenticators.oauth2_client_credentials.config.token_url", "authenticators.oauth2_client_credentials.config.required_scope", | ||
"authenticators.oauth2_introspection", "authenticators.oauth2_introspection.enabled", "authenticators.oauth2_introspection.config", | ||
"authenticators.oauth2_introspection.config.introspection_url", "authenticators.oauth2_introspection.config.scope_strategy", | ||
"authenticators.oauth2_introspection.config.pre_authorization", "authenticators.oauth2_introspection.config.pre_authorization.enabled", | ||
"authenticators.oauth2_introspection.config.pre_authorization.client_id", "authenticators.oauth2_introspection.config.pre_authorization.client_secret", | ||
"authenticators.oauth2_introspection.config.pre_authorization.token_url", "authenticators.oauth2_introspection.config.pre_authorization.scope", | ||
"authenticators.oauth2_introspection.config.required_scope", "authenticators.oauth2_introspection.config.target_audience", | ||
"authenticators.oauth2_introspection.config.trusted_issuers", "authenticators.oauth2_introspection.config.token_from", | ||
"authenticators.oauth2_introspection.config.token_from.header", "authenticators.oauth2_introspection.config.token_from.query_parameter", | ||
"authorizers", "authorizers.allow", "authorizers.allow.enabled", "authorizers.deny", "authorizers.deny.enabled", "authorizers.keto_engine_acp_ory", | ||
"authorizers.keto_engine_acp_ory.enabled", "authorizers.keto_engine_acp_ory.config", "authorizers.keto_engine_acp_ory.config.base_url", | ||
"authorizers.keto_engine_acp_ory.config.required_action", "authorizers.keto_engine_acp_ory.config.required_resource", "authorizers.keto_engine_acp_ory.config.subject", | ||
"authorizers.keto_engine_acp_ory.config.flavor", "mutators", "mutators.noop", "mutators.noop.enabled", "mutators.cookie", | ||
"mutators.cookie.enabled", "mutators.cookie.config", "mutators.cookie.config.cookies", "mutators.header", | ||
"mutators.header.enabled", "mutators.header.config", "mutators.header.config.headers", "mutators.hydrator", | ||
"mutators.hydrator.enabled", "mutators.hydrator.config", "mutators.hydrator.config.api", "mutators.hydrator.config.api.url", | ||
"mutators.hydrator.config.api.auth", "mutators.hydrator.config.api.auth.basic", "mutators.hydrator.config.api.auth.basic.username", | ||
"mutators.hydrator.config.api.auth.basic.password", "mutators.hydrator.config.api.retry", "mutators.hydrator.config.api.retry.number_of_retries", | ||
"mutators.hydrator.config.api.retry.delay_in_milliseconds", "mutators.id_token", "mutators.id_token.enabled", | ||
"mutators.id_token.config", "mutators.id_token.config.claims", "mutators.id_token.config.issuer_url", | ||
"mutators.id_token.config.jwks_url", "mutators.id_token.config.ttl", "log", "log.level", "log.format", | ||
"profiling", | ||
}, | ||
}, | ||
{ | ||
schema: readFile("./stub/config.schema.json"), | ||
expectedKeys: []string{"dsn"}, | ||
}, | ||
{ | ||
schema: `{"$ref": "http://google/schema.json"}`, | ||
expectErr: true, | ||
}, | ||
{ | ||
// this should fail because of recursion | ||
schema: `{ | ||
"definitions": { | ||
"foo": { | ||
"$ref": "#/definitions/foo" | ||
} | ||
}, | ||
"type": "object", | ||
"properties": { | ||
"bar": { | ||
"$ref": "#/definitions/foo" | ||
} | ||
} | ||
}`, | ||
expectErr: true, | ||
}, | ||
{ | ||
schema: `{"oneOf": [{ "type": "object", "properties": { "foo": true, "bar": true } },{ "type": "object", "properties": { "foo": true } }]}`, | ||
expectedKeys: []string{"foo", "bar"}, | ||
}, | ||
} { | ||
t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) { | ||
actual, err := getSchemaKeys(tc.schema, tc.schema, []string{}, []string{}) | ||
if tc.expectErr { | ||
require.Error(t, err) | ||
return | ||
} | ||
require.NoError(t, err) | ||
assert.EqualValues(t, tc.expectedKeys, actual) | ||
}) | ||
} | ||
} |
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.
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.
As I noted previously this usage of BindEnv is incorrect: this function does not accept multiple keys https://github.com/spf13/viper/blob/master/viper.go#L960 It either accepts one parameter (the key) or two parameters (the key and the corresponding ENV_VAR_NAME)
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.
Also, how do we deal with the env names? I guess with the effect of
SetEnvKeyReplacer
it will work automatically, so afterviper.BindEnv("foo.bar.baz")
envFOO_BAR_BAZ
should work, right?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.
Ah, thanks, I overlooked that completely. Fixed and added a test to make sure this works properly.
Exactly!