Skip to content

Cache secret lookups, fixes #2924 - #3628

Merged
vito merged 1 commit into
concourse:masterfrom
romankartgh:cache-cred-mgr-lookups
May 1, 2019
Merged

vito merged 1 commit into
concourse:masterfrom
romankartgh:cache-cred-mgr-lookups

Conversation

@romankartgh

@romankartgh romankartgh commented Mar 29, 2019 •

Copy link
Copy Markdown
Contributor

refactoring of secret managers + generic secret cache implementaiton

this will also serve as a good foundation for team-based credential managers RFC, as now you can introduce a composable secret manager (same way as caching and retrying is implemented), which can iterate over several underlying secret managers

* composable secret manager for team 1
           -> vault 1
           -> vault 2
           -> ssm

and you can add retries and caching at any layer. e.g. one global cache, or several caches per each credential manager, etc.

see commit description

@topherbullock

topherbullock commented Apr 22, 2019 •

Copy link
Copy Markdown
Contributor

Hey @ralekseenkov
Question about one of the commits in this PR: c0ceccc - was there a need to add the gobin ... directives vs installing counterfeiter to the GOPATH/$bin(https://github.com/maxbrunsfeld/counterfeiter#installing-counterfeiter-to-gopathbin), or is this change to ensure the version of the tool is tracked in go.mod?

@romankartgh

romankartgh commented Apr 23, 2019 •

Copy link
Copy Markdown
Contributor Author

@topherbullock my PR was created before Concourse team added instructions to install counterfeiter to $GOPATH/bin:
7be3c12#diff-6a3371457528722a734f3c51d9238c13

I just rebased my PR on top of master and removed these changes

Before, secret managers had logic inside to take a variables and look up secrets in different paths based on team name and pipeline name.
This made it really difficult to introduce proper _secret_ caching. It also presented problems for implementing “team credential managers” RFC.

This commit basically decouples secrets vs. variables, making sure that secret manager interface is clean (i.e. retrieve a secret based on its name).
It basically introduces a layered system, where:
* secret managers have an interface to retrieve a value of an individual secret
* secret managers can tell you how variable name should be transformed into secret names (this is currently specific to a secret manager)
* now you can construct vault, add retries, and caching, and then start retrieving variables with proper caching and retries:
    - result := NewVaultFactory(…)
    - result = creds.NewRetryableSecrets(result, retryConfig)
    - result = creds.NewCachedSecrets(result, cacheConfig)
    - variables = creds.NewVariables(result, teamName, pipelineName)

It also drops custom cache implementation for Vault and introduces a generic implmenetation based on patrickmn/go-cache

Please note that this is a breaking change due to renaming of parameters:
- vault-specific cache and max-lease parameters are not longer supported
- instead, global cache parameters are used (enabled, duration, purge-interval)

Signed-off-by: Roman Alekseenkov <[email protected]>
@vito

vito commented May 1, 2019

Copy link
Copy Markdown
Contributor

Taking a look at this now! There are merge conflicts but I've resolved them locally (it wasn't too bad). If all is good I'll just push the merge with the conflict resolutions. 👍

So far I've just kicked the tires at a surface level and confirmed that credentials are cached with a locally running Vault by inspecting the audit log to see when credentials are fetched.

The default cache duration is only one minute, which means credentials will still be re-fetched roughly every resource check (which also has a one minute interval). To me that makes sense, from the standpoint that it's a conservative default that will help when there are many builds running, while still preventing a credential rotated independent of its lease duration (i.e. manually) from impacting the system for too long, as the next resource check or two will pick it up. If users need to mitigate load they can always increase the --secret-cache-duration.

I haven't done any testing on lease durations yet, but its interaction with --secret-cache-duration makes sense to me (smaller duration wins).

Thanks for starting on all this, and thanks for your patience!

@romankartgh

Copy link
Copy Markdown
Contributor Author

Sounds good. I was trying to be careful, decoupling variable lookup logic (i.e. NewSecretLookupPaths) from secret retrieval. Hopefully nothing got broken as a result of this.

But there are cases like Kubernetes credential manager - it doesn't seem to have any tests and it's currently missing docs, see #2003. That makes it challenging to verify

@vito vito left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 went over the code and couldn't find anything wrong, though obviously there are lots of changes here affecting all credential managers, so I'm gonna keep an eye on TopGun for integration test coverage

i only had one tiny change requested (log line formatting), but I'll just make that fix locally and push since I've also got the merge conflict locally 👍

thanks a bunch!

Comment thread atc/atccmd/command.go
result := secretsFactory.NewSecrets()
result = creds.NewRetryableSecrets(result, cmd.CredentialManagement.RetryConfig)
if cmd.CredentialManagement.CacheConfig.Enabled {
result = creds.NewCachedSecrets(result, cmd.CredentialManagement.CacheConfig)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉 composition!

package creds

import (
"github.com/patrickmn/go-cache"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice that there was a package for this 👍

}

// here we want to cache secret value, expiration, and found flag too
// meaning that "secret not found" responses will be cached too!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

neat

Get(string) (interface{}, *time.Time, bool, error)

// NewSecretLookupPaths returns an instance of lookup policy, which can transform pipeline ((var)) into one or more secret paths, based on team name and pipeline name
NewSecretLookupPaths(string, string) []SecretLookupPath

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 nice idea - simplifies everyone's Get implementation

although, should this just be called SecretLookupPaths? it doesn't really feel like a constructor to me

return path.Join(append([]string{c.PathPrefix}, segments...)...)
}

func (c CredHubAtc) List() ([]template.VariableDefinition, error) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 I like that folks don't have to implement this stub anymore

func (s *SecretsManager) Get(secretPath string) (interface{}, *time.Time, bool, error) {
value, expiration, found, err := s.getSecretById(secretPath)
if err != nil {
s.log.Error("unable to retrieve aws secret", err, lager.Data{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be conventional formatting:

Suggested change
s.log.Error("unable to retrieve aws secret", err, lager.Data{
s.log.Error("failed-to-fetch-aws-secret", err, lager.Data{

@vito
vito merged commit 82facc4 into concourse:master May 1, 2019
@romankartgh

Copy link
Copy Markdown
Contributor Author

thanks :)

@samgurtman-zz

samgurtman-zz commented May 2, 2019 •

Copy link
Copy Markdown

I hate to do this, but would anyone have any guidance on back porting this to 5.1.0? I have a big of egg on my face after moving our credentials to SSM. I guess I can set the default resource check to much longer, but this seems like a way better solution.

I tried to cherry pick this and build the binaries but I have panics when I actually started the web binary up.

@romankartgh

Copy link
Copy Markdown
Contributor Author

@samgurtman it might be easier to wait for 5.2.0 because maintaining your own forks is never fun. if you really want to backport, ping me on Discord and I can try to help

@cirocosta

cirocosta commented May 6, 2019 •

Copy link
Copy Markdown
Contributor

Hey @ralekseenkov,

I noticed that the Kubernetes cred mgmt changed a bit, breaking the tests we have in place for such integration:

Context("Consuming per-team k8s secrets", func() {
JustBeforeEach(func() {
// ((foo)) --> bar
createCredentialSecret(releaseName, "foo", "main", map[string]string{"value": "bar"})
// ((caz.baz)) --> zaz
createCredentialSecret(releaseName, "caz", "main", map[string]string{"baz": "zaz"})
fly.Run("set-pipeline", "-n", "-c", "../pipelines/minimal-credential-management.yml", "-p", "pipeline")
session := fly.Start("get-pipeline", "-p", "pipeline")
Wait(session)
Expect(string(session.Out.Contents())).ToNot(ContainSubstring("bar"))
Expect(string(session.Out.Contents())).ToNot(ContainSubstring("zaz"))
fly.Run("unpause-pipeline", "-p", "pipeline")
})
Context("using the default namespace created by the chart", func() {
It("Gets credentials set by consuming k8s secrets", func() {
session := fly.Start("trigger-job", "-j", "pipeline/unit", "-w")
Wait(session)
Expect(string(session.Out.Contents())).To(ContainSubstring("bar"))
Expect(string(session.Out.Contents())).To(ContainSubstring("zaz"))
})
})
Context("using a user-provided namespace", func() {
BeforeEach(func() {
Run(nil, "kubectl", "create", "namespace", releaseName+"-main")
extraArgs = []string{
"--set=concourse.web.kubernetes.createTeamNamespaces=false",
}
})
It("Gets credentials set by consuming k8s secrets", func() {
session := fly.Start("trigger-job", "-j", "pipeline/unit", "-w")
Wait(session)
Expect(string(session.Out.Contents())).To(ContainSubstring("bar"))
Expect(string(session.Out.Contents())).To(ContainSubstring("zaz"))
})
AfterEach(func() {
Run(nil, "kubectl", "delete", "namespace", releaseName+"-main", "--wait=false")
})
})

Seems related to the fact that the Get expects the :-formatted entry:

// Get retrieves the value and expiration of an individual secret
func (k Kubernetes) Get(secretPath string) (interface{}, *time.Time, bool, error) {
parts := strings.Split(secretPath, ":")

If I understood the PR correctly, the changes should be backward-compatible - was the break unintentional? Sorry if I'm missing some understanding of the changes 😅

Regarding tests, yeah, we should do a better job regarding such integration - at the moment the only tests we have live under topgun/k8s, which are pretty much e2e testing against a real k8s cluster.

Thanks!

@cirocosta

cirocosta commented May 6, 2019 •

Copy link
Copy Markdown
Contributor

Oh, here's an example failure:

running: kubectl create secret generic foo --namespace=topgun-k8s-cm-664743-1-main --from-literal=value=bar
secret/foo created
running: kubectl create secret generic caz --namespace=topgun-k8s-cm-664743-1-main --from-literal=baz=zaz
secret/caz created

fly -t concourse-topgun-k8s-1 set-pipeline -n -c ../pipelines/minimal-credential-management.yml -p pipeline
jobs:
  job unit has been added:
+ name: unit
+ plan:
+ - task: run
+   config:
+     platform: linux
+     image_resource:
+       type: registry-image
+       source:
+         repository: busybox
+     run:
+       path: /bin/sh
+       args:
+       - -c
+       - |
+         echo plain-secret=((foo))
+         echo nested-secret=((caz.baz))

...

failed to interpolate task config: 
  Finding variable 'foo': unable to split kubernetes secret path 
  into [namespace]:[secret]: topgun-k8s-cm-664743-1-/main/pipeline/foo

@romankartgh

Copy link
Copy Markdown
Contributor Author

@cirocosta it should be backwards compatible. I'll look into this today

cirocosta pushed a commit that referenced this pull request May 7, 2019
With the introduction of cache secret lookups (see [1]), we updated the
helm chart to account for the fact that those can be configured (see
[2]).

This commit adds a test that validates that the caching occurs by
triggering the pipeline two times:

1. having the secret there in the namespace, and another
2. not having the secret in the namespace - just in-memory (cached).

[1]: #3628
[2]: helm/charts@d9eef44

Signed-off-by: Ciro S. Costa <[email protected]>
@YoussB YoussB added the release/documented Documentation and release notes have been updated. label May 8, 2019
eyenx pushed a commit to eyenx/charts that referenced this pull request May 28, 2019
* [stable/concourse] Update flags for next Concourse release

- Adds `CONCOURSE_CLUSTER_NAME` (concourse.web.clusterName)
  - https://github.com/concourse/concourse/pull/3736<Paste>

Signed-off-by: Ciro S. Costa <[email protected]>

* [stable/concourse] add generic secret configurations

With the introduction generic caching, we no longer need the
vault-specific cacheing flags, while at the same time, having the need
of providing new ones (generic).

concourse/concourse#3628

Signed-off-by: Ciro S. Costa <[email protected]>

* [stable/concourse] add auditing flags

With the introduction of auditing capabilities (see Auditor#3577 [1]),
it's now possible to configure in a per-subsystem basis which API
requests an installation should audit.

This commit adds the necessary support for such flags.

[1]: concourse/concourse#3577

Signed-off-by: Ciro S. Costa <[email protected]>

* [stable/concourse] update image version to 5.2.0

Signed-off-by: Ciro S. Costa <[email protected]>
Co-authored-by: Krishna Mannem <[email protected]>

* [stable/concourse] Add time based build log retention flags

concourse/concourse#3560

Signed-off-by: Ciro S. Costa <[email protected]>
Co-authored-by: Krishna Mannem <[email protected]>

* [stable/concourse] add support for externalGardenUrl

With the addition of `external-garden-url` to the `concourse worker`
command, one is now able to reference a non-embedded garden server to be
used as the target for container creation.

concourse/concourse#3806

Signed-off-by: Ciro S. Costa <[email protected]>
taylorsilva pushed a commit to taylorsilva/concourse-helm that referenced this pull request Oct 2, 2019
* [stable/concourse] Update flags for next Concourse release

- Adds `CONCOURSE_CLUSTER_NAME` (concourse.web.clusterName)
  - https://github.com/concourse/concourse/pull/3736<Paste>

Signed-off-by: Ciro S. Costa <[email protected]>

* [stable/concourse] add generic secret configurations

With the introduction generic caching, we no longer need the
vault-specific cacheing flags, while at the same time, having the need
of providing new ones (generic).

concourse/concourse#3628

Signed-off-by: Ciro S. Costa <[email protected]>

* [stable/concourse] add auditing flags

With the introduction of auditing capabilities (see Auditor#3577 [1]),
it's now possible to configure in a per-subsystem basis which API
requests an installation should audit.

This commit adds the necessary support for such flags.

[1]: concourse/concourse#3577

Signed-off-by: Ciro S. Costa <[email protected]>

* [stable/concourse] update image version to 5.2.0

Signed-off-by: Ciro S. Costa <[email protected]>
Co-authored-by: Krishna Mannem <[email protected]>

* [stable/concourse] Add time based build log retention flags

concourse/concourse#3560

Signed-off-by: Ciro S. Costa <[email protected]>
Co-authored-by: Krishna Mannem <[email protected]>

* [stable/concourse] add support for externalGardenUrl

With the addition of `external-garden-url` to the `concourse worker`
command, one is now able to reference a non-embedded garden server to be
used as the target for container creation.

concourse/concourse#3806

Signed-off-by: Ciro S. Costa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release/documented Documentation and release notes have been updated.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants