gcp

package module
v0.0.0-...-f25926c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2022 License: Apache-2.0 Imports: 17 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// SecureTokenEndpoint is the Endpoint the STS client calls to.
	SecureTokenEndpoint = "https://sts.googleapis.com/v1/token"

	Scope = "https://www.googleapis.com/auth/cloud-platform"

	// Server side
	// TokenPath is url path for handling STS requests.
	TokenPath = "/token"
	// StsStatusPath is the path for dumping STS status.
	StsStatusPath = "/stsStatus"
	// URLEncodedForm is the encoding type specified in a STS request.
	URLEncodedForm = "application/x-www-form-urlencoded"
	// TokenExchangeGrantType is the required value for "grant_type" parameter in a STS request.
	TokenExchangeGrantType = "urn:ietf:params:oauth:grant-type:token-exchange"
	// SubjectTokenType is the required token type in a STS request.
	SubjectTokenType = "urn:ietf:params:oauth:token-type:jwt"

	Debug = false
)

From nodeagent/plugin/providers/google/stsclient In Istio, the code is used if "GoogleCA" is set as CA_PROVIDER or CA_ADDR has the right prefix

Functions

func GKE2RestCluster

func GKE2RestCluster(ctx context.Context, uk *hbone.HBone, token string, p string) ([]*hbone.Cluster, error)

GKE2RestCluster gets all the clusters for a project, and returns Cluster object.

func GcpSecret

func GcpSecret(ctx context.Context, uk *hbone.HBone, token, p, n, v string) ([]byte, error)

Get a GCP secrets - used for bootstraping the credentials and provisioning.

Example for creating a secret:

gcloud secrets create ca \
  --data-file <PATH-TO-SECRET-FILE> \
  --replication-policy automatic \
  --project dmeshgate \
  --format json \
  --quiet

func GetCluster

func GetCluster(ctx context.Context, uk *hbone.HBone, token, path string) (*hbone.Cluster, error)

GetCluster returns a cluster config using the GKE API. Path must follow GKE API spec: /projects/P/locations/L/l

func Hub2RestClusters

func Hub2RestClusters(ctx context.Context, uk *hbone.HBone, tok, p string) ([]*hbone.Cluster, error)

func InitDefaultTokenSource

func InitDefaultTokenSource(ctx context.Context, uk *hbone.HBone) error

Init GCP auth Will init AuthProviders["gcp"].

DefaultTokenSource will: - check GOOGLE_APPLICATION_CREDENTIALS - ~/.config/gcloud/application_default_credentials.json" - use metadata

This also works for K8S, using node MDS or GKE MDS - but only if the ServiceAccount is annotated with a GSA (with permissions to use). Also specific to GKE and GCP APIs.

func TokenPayload

func TokenPayload(jwt string) string

TokenPayload returns the decoded token. Used for logging/debugging token content, without printing the signature.

Types

type AuthConfig

type AuthConfig struct {
	// ProjectNumber is required - this code doesn't look it up.
	// Set as x-goog-user-project
	ProjectNumber string

	// TrustDomain to use - typically based on project name.
	TrustDomain string

	// GKE Cluster address.
	// https://container.googleapis.com/v1/projects/%s/locations/%s/clusters/%s
	// It is also the iss field in the token.
	ClusterAddress string

	// TokenSource returns K8S or federated tokens with a given audience.
	TokenSource TokenSource
}

AuthConfig contains the settings for getting tokens using K8S or federated tokens.

type Cluster

type Cluster struct {
	Name string

	// nodeConfig
	MasterAuth struct {
		ClusterCaCertificate []byte
	}
	Location string

	Endpoint string

	ResourceLabels map[string]string

	// loggingService, monitoringService
	//Network string "default"
	//Subnetwork string
	ClusterIpv4Cidr  string
	ServicesIpv4Cidr string

	// For regional clusters - each zone.
	// For zonal - one entry, equal with location
	Locations []string
	// ipAllocationPolicy - clusterIpv4Cider, serviceIpv4Cider...
	// masterAuthorizedNetworksConfig
	// maintenancePolicy
	// autoscaling
	NetworkConfig struct {
		// projects/NAME/global/networks/default
		Network    string
		Subnetwork string
	}
}

type Clusters

type Clusters struct {
	Clusters []*Cluster
}

Clusters return the list of GKE clusters.

type Duration

type Duration struct {
	// Signed seconds of the span of time. Must be from -315,576,000,000
	// to +315,576,000,000 inclusive. Note: these bounds are computed from:
	// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
	Seconds int64 `json:"seconds"`
}

From tokenexchangeplugin.go

type HubCluster

type HubCluster struct {
	// Full name - projects/wlhe-cr/locations/global/memberships/asm-cr
	//Name     string
	Endpoint *struct {
		GkeCluster *struct {
			// //container.googleapis.com/projects/wlhe-cr/locations/us-central1-c/clusters/asm-cr
			ResourceLink string
		}
	}
	State *struct {
		// READY
		Code string
	}

	Authority struct {
		Issuer               string `json:"issuer"`
		WorkloadIdentityPool string `json:"workloadIdentityPool"`
		IdentityProvider     string `json:"identityProvider"`
	} `json:"authority"`

	// Membership labels - different from GKE labels
	Labels map[string]string
}

type HubClusters

type HubClusters struct {
	Resources []HubCluster
}

HubClusters return the list of clusters registered in GKE Hub.

type JWT

type JWT struct {
	//An "aud" (Audience) claim in the token MUST include the Unicode
	//serialization of the origin (Section 6.1 of [RFC6454]) of the push
	//resource URL.  This binds the token to a specific push service and
	//ensures that the token is reusable for all push resource URLs that
	//share the same origin.
	// In K8S it is an array !
	Aud MultiString `json:"aud,omitempty"`

	//If the application server wishes to provide contact details, it MAY
	//include a "sub" (Subject) claim in the JWT.  The "sub" claim SHOULD
	//include a contact URI for the application server as either a
	//"mailto:" (email) [RFC6068] or an "https:" [RFC2818] URI.
	Sub string `json:"sub,omitempty"`

	// Max 24h
	Exp int64 `json:"exp,omitempty"`
	IAT int64 `json:"iat,omitempty"`

	// Issuer - for example kubernetes/serviceaccount.
	Iss string `json:"iss,omitempty"`

	Email string `json:"email,omitempty"`

	EmailVerified bool `json:"email_verified,omitempty"`

	K8S K8SAccountInfo `json:"kubernetes.io"`

	Name string `json:"kubernetes.io/serviceaccount/service-account.name"`

	Raw string `json:-`
}

JWT includes minimal field for a JWT, primarily for extracting iss for the exchange. This is used with K8S JWTs, which use multi-string.

type K8SAccountInfo

type K8SAccountInfo struct {
	Namespace string `json:"namespace"`
}

type MultiString

type MultiString []string

func (*MultiString) MarshalJSON

func (ms *MultiString) MarshalJSON() ([]byte, error)

func (*MultiString) UnmarshalJSON

func (ms *MultiString) UnmarshalJSON(data []byte) error

type STS

type STS struct {

	// Google service account to impersonate and return tokens for.
	// The KSA returned from K8S must have the IAM permissions
	GSA string

	// UseAccessToken will force returning a GSA access token, regardless of audience.
	UseAccessToken bool
	// contains filtered or unexported fields
}

STS provides token exchanges. Implements grpc and golang.org/x/oauth2.TokenSource The source of trust is the K8S token with TrustDomain audience, it is exchanged with access or ID tokens.

func NewFederatedTokenSource

func NewFederatedTokenSource(kr *AuthConfig) *STS

NewFederatedTokenSource returns federated tokens - google access tokens associated with the federated (k8s) identity. Can be used in some but not all APIs - in particular MeshCA requires this token.

https://cloud.google.com/iam/docs/reference/sts/rest/v1/TopLevel/token

func NewGSATokenSource

func NewGSATokenSource(kr *AuthConfig, gsa string) *STS

NewGSATokenSource returns a oauth2.TokenSource and grpc credentials.PerRPCCredentials implmentation, returning access tokens for a Google Service Account.

If the gsa is empty, the ASM mesh P4SA will be used instead. This is suitable for connecting to stackdriver and out-of-cluster managed Istiod. Otherwise, the gsa must grant the KSA (kubernetes service account) permission to act as the GSA.

func (*STS) GetRequestMetadata

func (s *STS) GetRequestMetadata(ctx context.Context, aud ...string) (map[string]string, error)

GetRequestMetadata implements credentials.PerRPCCredentials This can be used for both ID tokens or access tokens - if the 'aud' containts googleapis.com, access tokens are returned.

func (*STS) GetToken

func (s *STS) GetToken(ctx context.Context, aud string) (string, error)

func (*STS) RequireTransportSecurity

func (s *STS) RequireTransportSecurity() bool

func (*STS) ServeStsRequests

func (s *STS) ServeStsRequests(w http.ResponseWriter, req *http.Request)

ServeStsRequests handles STS requests and sends exchanged token in responses.

func (*STS) TokenFederated

func (s *STS) TokenFederated(ctx context.Context, k8sSAjwt string) (string, error)

TokenFederated exchanges the K8S JWT with a federated token - an google access token representing the K8S identity (and not a regular GSA!).

(formerly called ExchangeToken)

func (*STS) TokenGSA

func (s *STS) TokenGSA(ctx context.Context, federatedToken string, audience string) (string, error)

Exchange a federated token equivalent with the k8s JWT with the ASM p4SA. TODO: can be used with any GSA, if the permission to call generateAccessToken is granted. This is a good way to get access tokens for a GSA using the KSA, similar with TokenRequest in the other direction.

May return an ID token with aud or access token.

https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken

constructFederatedTokenRequest returns an HTTP request for access token. Example of an access token request: POST https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/ service-<GCP project number>@gcp-sa-meshdataplane.iam.gserviceaccount.com:generateAccessToken Content-Type: application/json Authorization: Bearer <federated token>

{
 "Delegates": [],
 "Scope": [
     https://www.googleapis.com/auth/cloud-platform
 ],
}

This requires permission to impersonate:

gcloud iam service-accounts add-iam-policy-binding \
 GSA_NAME@GSA_PROJECT_ID.iam.gserviceaccount.com \
 --role=roles/iam.workloadIdentityUser \
 --member="serviceAccount:WORKLOAD_IDENTITY_POOL[K8S_NAMESPACE/KSA_NAME]"

The p4sa is auto-setup for all authenticated users.

type StsErrorResponse

type StsErrorResponse struct {
	// REQUIRED. A single ASCII Error code.
	Error string `json:"error"`
	// OPTIONAL. Human-readable ASCII [USASCII] text providing additional information.
	ErrorDescription string `json:"error_description"`
	// OPTIONAL. A URI identifying a human-readable web page with information
	// about the Error.
	ErrorURI string `json:"error_uri"`
}

StsErrorResponse stores all Error parameters sent as JSON in a STS Error response. The Error parameters are defined in https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16#section-2.2.2.

type StsRequestParameters

type StsRequestParameters struct {
	// REQUIRED. The value "urn:ietf:params:oauth:grant-type:token- exchange"
	// indicates that a token exchange is being performed.
	GrantType string
	// OPTIONAL. Indicates the location of the target service or resource where
	// the client intends to use the requested security token.
	Resource string
	// OPTIONAL. The logical name of the target service where the client intends
	// to use the requested security token.
	Audience string
	// OPTIONAL. A list of space-delimited, case-sensitive strings, that allow
	// the client to specify the desired Scope of the requested security token in the
	// context of the service or Resource where the token will be used.
	Scope string
	// OPTIONAL. An identifier, for the type of the requested security token.
	RequestedTokenType string
	// REQUIRED. A security token that represents the identity of the party on
	// behalf of whom the request is being made.
	SubjectToken string
	// REQUIRED. An identifier, that indicates the type of the security token in
	// the "subject_token" parameter.
	SubjectTokenType string
	// OPTIONAL. A security token that represents the identity of the acting party.
	ActorToken string
	// An identifier, that indicates the type of the security token in the
	// "actor_token" parameter.
	ActorTokenType string
}

StsRequestParameters stores all STS request attributes defined in https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16#section-2.1

type StsResponseParameters

type StsResponseParameters struct {
	// REQUIRED. The security token issued by the authorization server
	// in response to the token exchange request.
	AccessToken string `json:"access_token"`
	// REQUIRED. An identifier, representation of the issued security token.
	IssuedTokenType string `json:"issued_token_type"`
	// REQUIRED. A case-insensitive value specifying the method of using the access
	// token issued. It provides the client with information about how to utilize the
	// access token to access protected resources.
	TokenType string `json:"token_type"`
	// RECOMMENDED. The validity lifetime, in seconds, of the token issued by the
	// authorization server.
	ExpiresIn int64 `json:"expires_in"`
	// OPTIONAL, if the Scope of the issued security token is identical to the
	// Scope requested by the client; otherwise, REQUIRED.
	Scope string `json:"scope"`
	// OPTIONAL. A refresh token will typically not be issued when the exchange is
	// of one temporary credential (the subject_token) for a different temporary
	// credential (the issued token) for use in some other context.
	RefreshToken string `json:"refresh_token"`
}

StsResponseParameters stores all attributes sent as JSON in a successful STS response. These attributes are defined in https://tools.ietf.org/html/draft-ietf-oauth-token-exchange-16#section-2.2.1

type TokenCache

type TokenCache struct {
	// contains filtered or unexported fields
}

func NewTokenCache

func NewTokenCache(sts *STS) *TokenCache

func (*TokenCache) Token

func (c *TokenCache) Token(ctx context.Context, host string) (string, error)

type TokenSource

type TokenSource interface {
	// GetToken for a given audience.
	GetToken(context.Context, string) (string, error)
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL