2023-04-10 15:36:59 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2019-12-06 20:46:46 +00:00
|
|
|
package nomad
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-04-02 00:24:02 +00:00
|
|
|
"errors"
|
2019-12-06 20:46:46 +00:00
|
|
|
"fmt"
|
|
|
|
"strings"
|
2020-01-02 15:03:05 +00:00
|
|
|
"sync"
|
2019-12-06 20:46:46 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/armon/go-metrics"
|
|
|
|
"github.com/hashicorp/consul/api"
|
|
|
|
"github.com/hashicorp/go-hclog"
|
|
|
|
"github.com/hashicorp/nomad/command/agent/consul"
|
2020-07-28 20:12:08 +00:00
|
|
|
"github.com/hashicorp/nomad/helper"
|
2019-12-06 20:46:46 +00:00
|
|
|
"github.com/hashicorp/nomad/nomad/structs"
|
2022-09-21 19:53:25 +00:00
|
|
|
"golang.org/x/exp/slices"
|
2020-01-02 15:03:05 +00:00
|
|
|
"golang.org/x/sync/errgroup"
|
2019-12-06 20:46:46 +00:00
|
|
|
"golang.org/x/time/rate"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// siTokenDescriptionFmt is the format for the .Description field of
|
|
|
|
// service identity tokens generated on behalf of Nomad.
|
|
|
|
siTokenDescriptionFmt = "_nomad_si [%s] [%s] [%s]"
|
|
|
|
|
|
|
|
// siTokenRequestRateLimit is the maximum number of requests per second Nomad
|
|
|
|
// will make against Consul for requesting SI tokens.
|
|
|
|
siTokenRequestRateLimit rate.Limit = 500
|
|
|
|
|
|
|
|
// siTokenMaxParallelRevokes is the maximum number of parallel SI token
|
|
|
|
// revocation requests Nomad will make against Consul.
|
|
|
|
siTokenMaxParallelRevokes = 64
|
|
|
|
|
2020-03-27 20:07:55 +00:00
|
|
|
// siTokenRevocationInterval is the interval at which SI tokens that failed
|
2020-01-02 15:03:05 +00:00
|
|
|
// initial revocation are retried.
|
2020-03-27 20:07:55 +00:00
|
|
|
siTokenRevocationInterval = 5 * time.Minute
|
2019-12-06 20:46:46 +00:00
|
|
|
)
|
|
|
|
|
2020-07-28 20:12:08 +00:00
|
|
|
const (
|
|
|
|
// configEntriesRequestRateLimit is the maximum number of requests per second
|
|
|
|
// Nomad will make against Consul for operations on global Configuration Entry
|
|
|
|
// objects.
|
|
|
|
configEntriesRequestRateLimit rate.Limit = 10
|
|
|
|
)
|
|
|
|
|
2019-12-06 20:46:46 +00:00
|
|
|
const (
|
|
|
|
// ConsulPolicyWrite is the literal text of the policy field of a Consul Policy
|
|
|
|
// Rule that we check when validating an Operator Consul token against the
|
|
|
|
// necessary permissions for creating a Service Identity token for a given
|
|
|
|
// service.
|
|
|
|
//
|
|
|
|
// The rule may be:
|
|
|
|
// - service.<exact>
|
|
|
|
// - service."*" (wildcard)
|
|
|
|
// - service_prefix.<matching> (including empty string)
|
|
|
|
//
|
|
|
|
// e.g.
|
|
|
|
// service "web" { policy = "write" }
|
|
|
|
// service_prefix "" { policy = "write" }
|
|
|
|
ConsulPolicyWrite = "write"
|
2021-03-16 18:22:21 +00:00
|
|
|
|
|
|
|
// ConsulPolicyRead is the literal text of the policy field of a Consul Policy
|
|
|
|
// Rule that we check when validating a job-submitter Consul token against the
|
|
|
|
// necessary permissions for reading the key-value store.
|
|
|
|
//
|
|
|
|
// The only acceptable rule is
|
|
|
|
// - service_prefix "" { policy = "read|write" }
|
|
|
|
ConsulPolicyRead = "read"
|
2019-12-06 20:46:46 +00:00
|
|
|
)
|
|
|
|
|
2020-05-18 19:21:12 +00:00
|
|
|
type ServiceIdentityRequest struct {
|
2021-03-16 18:22:21 +00:00
|
|
|
ConsulNamespace string
|
|
|
|
TaskKind structs.TaskKind
|
|
|
|
TaskName string
|
|
|
|
ClusterID string
|
|
|
|
AllocID string
|
2019-12-06 20:46:46 +00:00
|
|
|
}
|
|
|
|
|
2020-05-18 19:21:12 +00:00
|
|
|
func (sir ServiceIdentityRequest) Validate() error {
|
2019-12-06 20:46:46 +00:00
|
|
|
switch {
|
2020-05-18 19:21:12 +00:00
|
|
|
case sir.ClusterID == "":
|
2019-12-06 20:46:46 +00:00
|
|
|
return errors.New("cluster id not set")
|
2020-05-18 19:21:12 +00:00
|
|
|
case sir.AllocID == "":
|
2019-12-06 20:46:46 +00:00
|
|
|
return errors.New("alloc id not set")
|
2020-05-18 19:21:12 +00:00
|
|
|
case sir.TaskName == "":
|
2019-12-06 20:46:46 +00:00
|
|
|
return errors.New("task name not set")
|
2020-05-18 19:21:12 +00:00
|
|
|
case sir.TaskKind == "":
|
|
|
|
return errors.New("task kind not set")
|
2019-12-06 20:46:46 +00:00
|
|
|
default:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-18 19:21:12 +00:00
|
|
|
func (sir ServiceIdentityRequest) Description() string {
|
|
|
|
return fmt.Sprintf(siTokenDescriptionFmt, sir.ClusterID, sir.AllocID, sir.TaskName)
|
2019-12-06 20:46:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ConsulACLsAPI is an abstraction over the consul/api.ACL API used by Nomad
|
|
|
|
// Server.
|
2020-03-27 20:07:55 +00:00
|
|
|
//
|
|
|
|
// ACL requirements
|
|
|
|
// - acl:write (transitive through ACLsAPI)
|
2019-12-06 20:46:46 +00:00
|
|
|
type ConsulACLsAPI interface {
|
2021-03-16 18:22:21 +00:00
|
|
|
// CheckPermissions checks that the given Consul token has the necessary ACL
|
|
|
|
// permissions for each way that Consul is used as indicated by usage,
|
|
|
|
// returning an error if not.
|
|
|
|
CheckPermissions(ctx context.Context, namespace string, usage *structs.ConsulUsage, secretID string) error
|
2019-12-06 20:46:46 +00:00
|
|
|
|
|
|
|
// Create instructs Consul to create a Service Identity token.
|
2020-05-18 19:21:12 +00:00
|
|
|
CreateToken(context.Context, ServiceIdentityRequest) (*structs.SIToken, error)
|
2019-12-06 20:46:46 +00:00
|
|
|
|
|
|
|
// RevokeTokens instructs Consul to revoke the given token accessors.
|
2020-01-02 15:03:05 +00:00
|
|
|
RevokeTokens(context.Context, []*structs.SITokenAccessor, bool) bool
|
2019-12-06 20:46:46 +00:00
|
|
|
|
2020-05-21 12:18:12 +00:00
|
|
|
// MarkForRevocation marks the tokens for background revocation
|
|
|
|
MarkForRevocation([]*structs.SITokenAccessor)
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
// Stop is used to stop background token revocations. Intended to be used
|
|
|
|
// on Nomad Server shutdown.
|
|
|
|
Stop()
|
|
|
|
}
|
|
|
|
|
|
|
|
// PurgeSITokenAccessorFunc is called to remove SI Token accessors from the
|
|
|
|
// system (i.e. raft). If the function returns an error, the token will still
|
|
|
|
// be tracked and revocation attempts will retry in the background until there
|
|
|
|
// is a success.
|
|
|
|
type PurgeSITokenAccessorFunc func([]*structs.SITokenAccessor) error
|
|
|
|
|
|
|
|
type SITokenStats struct {
|
|
|
|
TrackedForRevoke int
|
2019-12-06 20:46:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type consulACLsAPI struct {
|
|
|
|
// aclClient is the API subset of the real consul client we need for
|
2020-01-02 15:03:05 +00:00
|
|
|
// managing Service Identity tokens
|
2019-12-06 20:46:46 +00:00
|
|
|
aclClient consul.ACLsAPI
|
|
|
|
|
|
|
|
// limiter is used to rate limit requests to consul
|
|
|
|
limiter *rate.Limiter
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
bgRevokeLock sync.Mutex
|
|
|
|
// Track accessors that must have their revocation retried in the background.
|
|
|
|
bgRetryRevocation []*structs.SITokenAccessor
|
|
|
|
// Track whether the background revocations have been stopped, to avoid
|
|
|
|
// creating tokens we would no longer be able to revoke. Expected to be used
|
|
|
|
// on a Server shutdown.
|
|
|
|
bgRevokeStopped bool
|
|
|
|
|
|
|
|
// purgeFunc is the Nomad Server function that removes the reference to the
|
|
|
|
// SI token accessor from the persistent raft store
|
|
|
|
purgeFunc PurgeSITokenAccessorFunc
|
|
|
|
|
|
|
|
// stopC is used to signal the client is shutting down and token revocation
|
|
|
|
// background goroutine should stop
|
|
|
|
stopC chan struct{}
|
|
|
|
|
2019-12-06 20:46:46 +00:00
|
|
|
// logger is used to log messages
|
|
|
|
logger hclog.Logger
|
|
|
|
}
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
func NewConsulACLsAPI(aclClient consul.ACLsAPI, logger hclog.Logger, purgeFunc PurgeSITokenAccessorFunc) *consulACLsAPI {
|
2020-05-22 01:05:53 +00:00
|
|
|
if purgeFunc == nil {
|
|
|
|
purgeFunc = func([]*structs.SITokenAccessor) error { return nil }
|
|
|
|
}
|
|
|
|
|
2019-12-06 20:46:46 +00:00
|
|
|
c := &consulACLsAPI{
|
|
|
|
aclClient: aclClient,
|
2020-01-02 15:03:05 +00:00
|
|
|
limiter: rate.NewLimiter(siTokenRequestRateLimit, int(siTokenRequestRateLimit)),
|
|
|
|
stopC: make(chan struct{}),
|
|
|
|
purgeFunc: purgeFunc,
|
2019-12-06 20:46:46 +00:00
|
|
|
logger: logger.Named("consul_acl"),
|
|
|
|
}
|
2020-01-02 15:03:05 +00:00
|
|
|
|
|
|
|
go c.bgRetryRevokeDaemon()
|
|
|
|
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop stops background token revocations from happening. Once stopped, tokens
|
|
|
|
// may no longer be created.
|
|
|
|
func (c *consulACLsAPI) Stop() {
|
|
|
|
c.bgRevokeLock.Lock()
|
|
|
|
defer c.bgRevokeLock.Unlock()
|
|
|
|
|
|
|
|
c.stopC <- struct{}{}
|
|
|
|
c.bgRevokeStopped = true
|
2019-12-06 20:46:46 +00:00
|
|
|
}
|
|
|
|
|
2021-03-16 18:22:21 +00:00
|
|
|
func (c *consulACLsAPI) readToken(ctx context.Context, secretID string) (*api.ACLToken, error) {
|
|
|
|
defer metrics.MeasureSince([]string{"nomad", "consul", "read_token"}, time.Now())
|
2020-01-02 15:03:05 +00:00
|
|
|
|
2021-03-16 18:22:21 +00:00
|
|
|
if id := strings.TrimSpace(secretID); !helper.IsUUID(id) {
|
|
|
|
return nil, errors.New("missing consul token")
|
2019-12-06 20:46:46 +00:00
|
|
|
}
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
// Ensure we are under our rate limit.
|
|
|
|
if err := c.limiter.Wait(ctx); err != nil {
|
2022-04-02 00:24:02 +00:00
|
|
|
return nil, fmt.Errorf("unable to read consul token: %w", err)
|
2020-01-02 15:03:05 +00:00
|
|
|
}
|
2019-12-06 20:46:46 +00:00
|
|
|
|
2021-03-16 18:22:21 +00:00
|
|
|
consulToken, _, err := c.aclClient.TokenReadSelf(&api.QueryOptions{
|
2019-12-06 20:46:46 +00:00
|
|
|
AllowStale: false,
|
|
|
|
Token: secretID,
|
|
|
|
})
|
|
|
|
if err != nil {
|
2022-04-02 00:24:02 +00:00
|
|
|
return nil, fmt.Errorf("unable to read consul token: %w", err)
|
2021-03-16 18:22:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return consulToken, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *consulACLsAPI) CheckPermissions(ctx context.Context, namespace string, usage *structs.ConsulUsage, secretID string) error {
|
|
|
|
// consul not used, nothing to check
|
|
|
|
if !usage.Used() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// lookup the token from consul
|
2021-04-20 20:23:30 +00:00
|
|
|
token, readErr := c.readToken(ctx, secretID)
|
|
|
|
if readErr != nil {
|
|
|
|
return readErr
|
|
|
|
}
|
|
|
|
|
|
|
|
// if the token is a global-management token, it has unrestricted privileges
|
|
|
|
if c.isManagementToken(token) {
|
|
|
|
return nil
|
2021-03-16 18:22:21 +00:00
|
|
|
}
|
|
|
|
|
2021-04-20 20:23:30 +00:00
|
|
|
// if the token cannot possibly be used to act on objects in the desired
|
|
|
|
// namespace, reject it immediately
|
|
|
|
if err := namespaceCheck(namespace, token); err != nil {
|
|
|
|
return err
|
2021-03-16 18:22:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// verify token has keystore read permission, if using template
|
|
|
|
if usage.KV {
|
2021-04-20 20:23:30 +00:00
|
|
|
allowable, err := c.canReadKeystore(namespace, token)
|
2021-03-16 18:22:21 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
} else if !allowable {
|
|
|
|
return errors.New("insufficient Consul ACL permissions to use template")
|
|
|
|
}
|
2019-12-06 20:46:46 +00:00
|
|
|
}
|
2021-03-16 18:22:21 +00:00
|
|
|
|
|
|
|
// verify token has service write permission for group+task services
|
|
|
|
for _, service := range usage.Services {
|
2021-04-20 20:23:30 +00:00
|
|
|
allowable, err := c.canWriteService(namespace, service, token)
|
2021-03-16 18:22:21 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
} else if !allowable {
|
2022-04-02 00:24:02 +00:00
|
|
|
return fmt.Errorf("insufficient Consul ACL permissions to write service %q", service)
|
2021-03-16 18:22:21 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-06 20:46:46 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-05-18 19:21:12 +00:00
|
|
|
func (c *consulACLsAPI) CreateToken(ctx context.Context, sir ServiceIdentityRequest) (*structs.SIToken, error) {
|
2019-12-06 20:46:46 +00:00
|
|
|
defer metrics.MeasureSince([]string{"nomad", "consul", "create_token"}, time.Now())
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
// make sure the background token revocations have not been stopped
|
|
|
|
c.bgRevokeLock.Lock()
|
|
|
|
stopped := c.bgRevokeStopped
|
|
|
|
c.bgRevokeLock.Unlock()
|
|
|
|
|
|
|
|
if stopped {
|
|
|
|
return nil, errors.New("client stopped and may no longer create tokens")
|
|
|
|
}
|
|
|
|
|
2021-03-16 22:05:08 +00:00
|
|
|
// Check the metadata for the token we want
|
2020-05-18 19:21:12 +00:00
|
|
|
if err := sir.Validate(); err != nil {
|
2019-12-06 20:46:46 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
// the SI token created must be for the service, not the sidecar of the service
|
2019-12-19 23:40:30 +00:00
|
|
|
// https://www.consul.io/docs/acl/acl-system.html#acl-service-identities
|
2020-05-18 19:21:12 +00:00
|
|
|
service := sir.TaskKind.Value()
|
2019-12-06 20:46:46 +00:00
|
|
|
partial := &api.ACLToken{
|
2020-05-18 19:21:12 +00:00
|
|
|
Description: sir.Description(),
|
|
|
|
ServiceIdentities: []*api.ACLServiceIdentity{{ServiceName: service}},
|
2021-03-16 18:22:21 +00:00
|
|
|
Namespace: sir.ConsulNamespace,
|
2020-05-28 13:20:15 +00:00
|
|
|
Local: true,
|
2019-12-06 20:46:46 +00:00
|
|
|
}
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
// Ensure we are under our rate limit.
|
|
|
|
if err := c.limiter.Wait(ctx); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-12-06 20:46:46 +00:00
|
|
|
token, _, err := c.aclClient.TokenCreate(partial, nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &structs.SIToken{
|
2021-03-16 18:22:21 +00:00
|
|
|
ConsulNamespace: token.Namespace,
|
|
|
|
AccessorID: token.AccessorID,
|
|
|
|
SecretID: token.SecretID,
|
|
|
|
TaskName: sir.TaskName,
|
2019-12-06 20:46:46 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
// RevokeTokens revokes the passed set of SI token accessors. If committed is set,
|
|
|
|
// the client's purge function is called (which purges the tokens from the Server's
|
|
|
|
// persistent store). If there is an error purging either because of Consul failures
|
|
|
|
// or because of the purge function, the revocation is retried in the background.
|
|
|
|
//
|
|
|
|
// The revocation of an SI token accessor is idempotent.
|
|
|
|
//
|
|
|
|
// A return value of true indicates one or more accessors were stored for
|
|
|
|
// a revocation retry attempt in the background (intended for tests).
|
|
|
|
func (c *consulACLsAPI) RevokeTokens(ctx context.Context, accessors []*structs.SITokenAccessor, committed bool) bool {
|
2019-12-06 20:46:46 +00:00
|
|
|
defer metrics.MeasureSince([]string{"nomad", "consul", "revoke_tokens"}, time.Now())
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
nTokens := float32(len(accessors))
|
2019-12-06 20:46:46 +00:00
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
if err := c.parallelRevoke(ctx, accessors); err != nil {
|
|
|
|
// If these tokens were uncommitted into raft, it is a best effort to
|
|
|
|
// revoke them now. If this immediate revocation does not work, Nomad loses
|
|
|
|
// track of them and will need to do a brute reconciliation later. This
|
|
|
|
// should happen rarely, and will be implemented soon.
|
|
|
|
if !committed {
|
|
|
|
metrics.IncrCounter([]string{"nomad", "consul", "undistributed_si_tokens_abandoned"}, nTokens)
|
2019-12-06 20:46:46 +00:00
|
|
|
}
|
2020-01-02 15:03:05 +00:00
|
|
|
|
|
|
|
c.logger.Warn("failed to revoke tokens, will reattempt later", "error", err)
|
|
|
|
c.storeForRevocation(accessors)
|
|
|
|
return true
|
2019-12-06 20:46:46 +00:00
|
|
|
}
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
if !committed {
|
|
|
|
// Un-committed tokens were revoked without incident (nothing to purge)
|
|
|
|
metrics.IncrCounter([]string{"nomad", "consul", "undistributed_si_tokens_revoked"}, nTokens)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Committed tokens were revoked without incident, now purge them
|
|
|
|
if err := c.purgeFunc(accessors); err != nil {
|
|
|
|
c.logger.Error("failed to purge SI token accessors", "error", err)
|
|
|
|
c.storeForRevocation(accessors)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Track that the SI tokens were revoked and purged successfully
|
|
|
|
metrics.IncrCounter([]string{"nomad", "consul", "distributed_si_tokens_revoked"}, nTokens)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-05-21 12:18:12 +00:00
|
|
|
func (c *consulACLsAPI) MarkForRevocation(accessors []*structs.SITokenAccessor) {
|
|
|
|
c.storeForRevocation(accessors)
|
|
|
|
}
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
func (c *consulACLsAPI) storeForRevocation(accessors []*structs.SITokenAccessor) {
|
|
|
|
c.bgRevokeLock.Lock()
|
|
|
|
defer c.bgRevokeLock.Unlock()
|
|
|
|
|
|
|
|
// copy / append the set of accessors we must track for revocation in the
|
|
|
|
// background
|
|
|
|
c.bgRetryRevocation = append(c.bgRetryRevocation, accessors...)
|
2019-12-06 20:46:46 +00:00
|
|
|
}
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
func (c *consulACLsAPI) parallelRevoke(ctx context.Context, accessors []*structs.SITokenAccessor) error {
|
|
|
|
g, pCtx := errgroup.WithContext(ctx)
|
|
|
|
|
|
|
|
// Cap the handlers
|
|
|
|
handlers := len(accessors)
|
|
|
|
if handlers > siTokenMaxParallelRevokes {
|
|
|
|
handlers = siTokenMaxParallelRevokes
|
|
|
|
}
|
|
|
|
|
|
|
|
// Revoke the SI Token Accessors
|
|
|
|
input := make(chan *structs.SITokenAccessor, handlers)
|
|
|
|
for i := 0; i < handlers; i++ {
|
|
|
|
g.Go(func() error {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case accessor, ok := <-input:
|
|
|
|
if !ok {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if err := c.singleRevoke(ctx, accessor); err != nil {
|
2022-04-02 00:24:02 +00:00
|
|
|
return fmt.Errorf(
|
|
|
|
"failed to revoke SI token accessor (alloc %q, node %q, task %q): %w",
|
|
|
|
accessor.AllocID, accessor.NodeID, accessor.TaskName, err,
|
2020-01-02 15:03:05 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
case <-pCtx.Done():
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Send the input
|
|
|
|
go func() {
|
|
|
|
defer close(input)
|
|
|
|
for _, accessor := range accessors {
|
|
|
|
select {
|
|
|
|
case <-pCtx.Done():
|
|
|
|
return
|
|
|
|
case input <- accessor:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Wait for everything to complete
|
|
|
|
return g.Wait()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *consulACLsAPI) singleRevoke(ctx context.Context, accessor *structs.SITokenAccessor) error {
|
2019-12-06 20:46:46 +00:00
|
|
|
c.logger.Trace("revoke SI token", "task", accessor.TaskName, "alloc_id", accessor.AllocID, "node_id", accessor.NodeID)
|
2020-01-02 15:03:05 +00:00
|
|
|
|
|
|
|
// Ensure we are under our rate limit.
|
|
|
|
if err := c.limiter.Wait(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Consul will no-op the deletion of a non-existent token (no error)
|
2021-03-16 18:22:21 +00:00
|
|
|
_, err := c.aclClient.TokenDelete(accessor.AccessorID, &api.WriteOptions{Namespace: accessor.ConsulNamespace})
|
2019-12-06 20:46:46 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
func (c *consulACLsAPI) bgRetryRevokeDaemon() {
|
2020-03-27 20:07:55 +00:00
|
|
|
ticker := time.NewTicker(siTokenRevocationInterval)
|
2020-01-02 15:03:05 +00:00
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-c.stopC:
|
|
|
|
return
|
|
|
|
case <-ticker.C:
|
|
|
|
c.bgRetryRevoke()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-21 12:18:12 +00:00
|
|
|
// maxConsulRevocationBatchSize is the maximum tokens a bgRetryRevoke should revoke
|
|
|
|
// at any given time.
|
|
|
|
const maxConsulRevocationBatchSize = 1000
|
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
func (c *consulACLsAPI) bgRetryRevoke() {
|
|
|
|
c.bgRevokeLock.Lock()
|
|
|
|
defer c.bgRevokeLock.Unlock()
|
|
|
|
|
|
|
|
// fast path, nothing to do
|
|
|
|
if len(c.bgRetryRevocation) == 0 {
|
|
|
|
return
|
|
|
|
}
|
2019-12-06 20:46:46 +00:00
|
|
|
|
2020-01-02 15:03:05 +00:00
|
|
|
// unlike vault tokens, SI tokens do not have a TTL, and so we must try to
|
|
|
|
// remove all SI token accessors, every time, until they're gone
|
2020-05-21 12:18:12 +00:00
|
|
|
toRevoke := len(c.bgRetryRevocation)
|
|
|
|
if toRevoke > maxConsulRevocationBatchSize {
|
|
|
|
toRevoke = maxConsulRevocationBatchSize
|
|
|
|
}
|
|
|
|
toPurge := make([]*structs.SITokenAccessor, toRevoke)
|
2020-01-02 15:03:05 +00:00
|
|
|
copy(toPurge, c.bgRetryRevocation)
|
|
|
|
|
|
|
|
if err := c.parallelRevoke(context.Background(), toPurge); err != nil {
|
2020-01-07 17:58:29 +00:00
|
|
|
c.logger.Warn("background SI token revocation failed", "error", err)
|
2020-01-02 15:03:05 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Call the revocation function
|
|
|
|
if err := c.purgeFunc(toPurge); err != nil {
|
|
|
|
// Just try again later (revocation is idempotent)
|
2020-01-07 17:58:29 +00:00
|
|
|
c.logger.Error("background SI token purge failed", "error", err)
|
2020-01-02 15:03:05 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Track that the SI tokens were revoked successfully
|
|
|
|
nTokens := float32(len(toPurge))
|
|
|
|
metrics.IncrCounter([]string{"nomad", "consul", "distributed_tokens_revoked"}, nTokens)
|
|
|
|
|
|
|
|
// Reset the list of accessors to retry, since we just removed them all.
|
|
|
|
c.bgRetryRevocation = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *consulACLsAPI) ListTokens() ([]string, error) {
|
|
|
|
// defer metrics.MeasureSince([]string{"nomad", "consul", "list_tokens"}, time.Now())
|
2019-12-06 20:46:46 +00:00
|
|
|
return nil, errors.New("not yet implemented")
|
|
|
|
}
|
2020-01-02 15:03:05 +00:00
|
|
|
|
|
|
|
// purgeSITokenAccessors is the Nomad Server method which will remove the set
|
|
|
|
// of SI token accessors from the persistent raft store.
|
|
|
|
func (s *Server) purgeSITokenAccessors(accessors []*structs.SITokenAccessor) error {
|
|
|
|
// Commit this update via Raft
|
|
|
|
request := structs.SITokenAccessorsRequest{Accessors: accessors}
|
|
|
|
_, _, err := s.raftApply(structs.ServiceIdentityAccessorDeregisterRequestType, request)
|
|
|
|
return err
|
|
|
|
}
|
2020-07-28 20:12:08 +00:00
|
|
|
|
|
|
|
// ConsulConfigsAPI is an abstraction over the consul/api.ConfigEntries API used by
|
|
|
|
// Nomad Server.
|
|
|
|
//
|
2021-04-19 17:29:36 +00:00
|
|
|
// Nomad will only perform write operations on Consul Ingress/Terminating Gateway
|
|
|
|
// Configuration Entries. Removing the entries is not yet safe, given that multiple
|
|
|
|
// Nomad clusters may be writing to the same config entries, which are global in
|
|
|
|
// the Consul scope. There was a Meta field introduced which Nomad can leverage
|
|
|
|
// in the future, when Consul no longer supports versions that do not contain the
|
|
|
|
// field. The Meta field would be used to track which Nomad "owns" the CE.
|
|
|
|
// https://github.com/hashicorp/nomad/issues/8971
|
2020-07-28 20:12:08 +00:00
|
|
|
type ConsulConfigsAPI interface {
|
2020-12-15 20:38:33 +00:00
|
|
|
// SetIngressCE adds the given ConfigEntry to Consul, overwriting
|
2020-07-28 20:12:08 +00:00
|
|
|
// the previous entry if set.
|
2021-04-19 17:29:36 +00:00
|
|
|
SetIngressCE(ctx context.Context, namespace, service string, entry *structs.ConsulIngressConfigEntry) error
|
2020-12-15 20:38:33 +00:00
|
|
|
|
|
|
|
// SetTerminatingCE adds the given ConfigEntry to Consul, overwriting
|
|
|
|
// the previous entry if set.
|
2021-04-19 17:29:36 +00:00
|
|
|
SetTerminatingCE(ctx context.Context, namespace, service string, entry *structs.ConsulTerminatingConfigEntry) error
|
2020-07-28 20:12:08 +00:00
|
|
|
|
|
|
|
// Stop is used to stop additional creations of Configuration Entries. Intended to
|
|
|
|
// be used on Nomad Server shutdown.
|
|
|
|
Stop()
|
|
|
|
}
|
|
|
|
|
|
|
|
type consulConfigsAPI struct {
|
|
|
|
// configsClient is the API subset of the real Consul client we need for
|
|
|
|
// managing Configuration Entries.
|
|
|
|
configsClient consul.ConfigAPI
|
|
|
|
|
|
|
|
// limiter is used to rate limit requests to Consul
|
|
|
|
limiter *rate.Limiter
|
|
|
|
|
|
|
|
// logger is used to log messages
|
|
|
|
logger hclog.Logger
|
|
|
|
|
|
|
|
// lock protects the stopped flag, which prevents use of the consul configs API
|
|
|
|
// client after shutdown.
|
|
|
|
lock sync.Mutex
|
|
|
|
stopped bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewConsulConfigsAPI(configsClient consul.ConfigAPI, logger hclog.Logger) *consulConfigsAPI {
|
|
|
|
return &consulConfigsAPI{
|
|
|
|
configsClient: configsClient,
|
|
|
|
limiter: rate.NewLimiter(configEntriesRequestRateLimit, int(configEntriesRequestRateLimit)),
|
|
|
|
logger: logger,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *consulConfigsAPI) Stop() {
|
|
|
|
c.lock.Lock()
|
|
|
|
defer c.lock.Unlock()
|
|
|
|
c.stopped = true
|
|
|
|
}
|
|
|
|
|
2021-04-19 17:29:36 +00:00
|
|
|
func (c *consulConfigsAPI) SetIngressCE(ctx context.Context, namespace, service string, entry *structs.ConsulIngressConfigEntry) error {
|
|
|
|
return c.setCE(ctx, convertIngressCE(namespace, service, entry))
|
2020-07-28 20:12:08 +00:00
|
|
|
}
|
|
|
|
|
2021-04-19 17:29:36 +00:00
|
|
|
func (c *consulConfigsAPI) SetTerminatingCE(ctx context.Context, namespace, service string, entry *structs.ConsulTerminatingConfigEntry) error {
|
|
|
|
return c.setCE(ctx, convertTerminatingCE(namespace, service, entry))
|
2020-12-15 20:38:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// setCE will set the Configuration Entry of any type Consul supports.
|
|
|
|
func (c *consulConfigsAPI) setCE(ctx context.Context, entry api.ConfigEntry) error {
|
2020-07-28 20:12:08 +00:00
|
|
|
defer metrics.MeasureSince([]string{"nomad", "consul", "create_config_entry"}, time.Now())
|
|
|
|
|
|
|
|
// make sure the background deletion goroutine has not been stopped
|
|
|
|
c.lock.Lock()
|
|
|
|
stopped := c.stopped
|
|
|
|
c.lock.Unlock()
|
|
|
|
|
|
|
|
if stopped {
|
|
|
|
return errors.New("client stopped and may not longer create config entries")
|
|
|
|
}
|
|
|
|
|
|
|
|
// ensure we are under our wait limit
|
|
|
|
if err := c.limiter.Wait(ctx); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-04-19 17:29:36 +00:00
|
|
|
_, _, err := c.configsClient.Set(entry, &api.WriteOptions{Namespace: entry.GetNamespace()})
|
2020-07-28 20:12:08 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-04-19 17:29:36 +00:00
|
|
|
func convertIngressCE(namespace, service string, entry *structs.ConsulIngressConfigEntry) api.ConfigEntry {
|
2020-07-28 20:12:08 +00:00
|
|
|
var listeners []api.IngressListener = nil
|
|
|
|
for _, listener := range entry.Listeners {
|
|
|
|
var services []api.IngressService = nil
|
2020-12-15 20:38:33 +00:00
|
|
|
for _, s := range listener.Services {
|
2020-07-28 20:12:08 +00:00
|
|
|
services = append(services, api.IngressService{
|
2020-12-15 20:38:33 +00:00
|
|
|
Name: s.Name,
|
2022-09-21 19:53:25 +00:00
|
|
|
Hosts: slices.Clone(s.Hosts),
|
2020-07-28 20:12:08 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
listeners = append(listeners, api.IngressListener{
|
|
|
|
Port: listener.Port,
|
|
|
|
Protocol: listener.Protocol,
|
|
|
|
Services: services,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-06-02 22:43:58 +00:00
|
|
|
tls := api.GatewayTLSConfig{}
|
|
|
|
if entry.TLS != nil {
|
|
|
|
tls.Enabled = entry.TLS.Enabled
|
|
|
|
tls.TLSMinVersion = entry.TLS.TLSMinVersion
|
|
|
|
tls.TLSMaxVersion = entry.TLS.TLSMaxVersion
|
2022-09-21 19:53:25 +00:00
|
|
|
tls.CipherSuites = slices.Clone(entry.TLS.CipherSuites)
|
2020-07-28 20:12:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return &api.IngressGatewayConfigEntry{
|
2021-04-19 17:29:36 +00:00
|
|
|
Namespace: namespace,
|
2020-07-28 20:12:08 +00:00
|
|
|
Kind: api.IngressGateway,
|
|
|
|
Name: service,
|
2022-06-02 22:43:58 +00:00
|
|
|
TLS: tls,
|
2020-07-28 20:12:08 +00:00
|
|
|
Listeners: listeners,
|
|
|
|
}
|
|
|
|
}
|
2020-12-15 20:38:33 +00:00
|
|
|
|
2021-04-19 17:29:36 +00:00
|
|
|
func convertTerminatingCE(namespace, service string, entry *structs.ConsulTerminatingConfigEntry) api.ConfigEntry {
|
2020-12-15 20:38:33 +00:00
|
|
|
var linked []api.LinkedService = nil
|
|
|
|
for _, s := range entry.Services {
|
|
|
|
linked = append(linked, api.LinkedService{
|
|
|
|
Name: s.Name,
|
|
|
|
CAFile: s.CAFile,
|
|
|
|
CertFile: s.CertFile,
|
|
|
|
KeyFile: s.KeyFile,
|
|
|
|
SNI: s.SNI,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return &api.TerminatingGatewayConfigEntry{
|
2021-04-19 17:29:36 +00:00
|
|
|
Namespace: namespace,
|
|
|
|
Kind: api.TerminatingGateway,
|
|
|
|
Name: service,
|
|
|
|
Services: linked,
|
2020-12-15 20:38:33 +00:00
|
|
|
}
|
|
|
|
}
|