{"modulePath":"github.com/LeanerCloud/cloud-commitments-platform","version":"v0.0.0-20261203094540-401891603b4e","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package credentials\n\nPackage credentials provides AES-256-GCM encryption for cloud account credentials and helpers for resolving provider-specific credential structs.\n\n## Constants\n\n```go\nconst (\n\tEnvSecretARN  = \"CREDENTIAL_ENCRYPTION_KEY_SECRET_ARN\"  // #nosec G101 -- env var name for AWS Secrets Manager ARN; not a credential value\n\tEnvSecretName = \"CREDENTIAL_ENCRYPTION_KEY_SECRET_NAME\" // #nosec G101 -- env var name for Azure Key Vault secret; not a credential value\n\tEnvSecretID   = \"CREDENTIAL_ENCRYPTION_KEY_SECRET_ID\"   // #nosec G101 -- env var name for GCP Secret Manager secret; not a credential value\n\tEnvRawKey     = \"CREDENTIAL_ENCRYPTION_KEY\"             // Raw 64-char hex (ops/dev)\n\tEnvAllowDev   = \"CREDENTIAL_ENCRYPTION_ALLOW_DEV_KEY\"   // 1 = permit zero-key fallback\n)\n```\nEnv var names used by LoadKey, in priority order.\n\n```go\nconst (\n\tCredTypeAWSAccessKeys     = \"aws_access_keys\"\n\tCredTypeAzureClientSecret = \"azure_client_secret\"\n\tCredTypeGCPServiceAccount = \"gcp_service_account\"          // #nosec G101 -- credential type name constant; not a credential value\n\tCredTypeGCPWIFConfig      = \"gcp_workload_identity_config\" // #nosec G101 -- credential type name constant; not a credential value\n)\n```\nCredential type constants used as credType in CredentialStore.\n\n```go\nconst ProblemNotStored = \"not stored\"\n```\nProblemNotStored is the AWSConfigError.Problem for a credential that has not been saved for the account.\n\n## Variables\n\n```go\nvar ErrHostIdentityUnavailable error = hostIdentityUnavailableError{}\n```\nErrHostIdentityUnavailable means the host identity check could not run: no STS client, an STS error or timeout (a canceled caller included), or an empty STS answer. The cause is on the platform side, so unlike ErrNotHostAccount its tenant-visible text asks for no config change. errors.Is also matches it against ErrNotHostAccount, so every caller keeps failing closed exactly as before (issue #559).\n\n```go\nvar ErrMultipleKeys = errors.New(\"credentials: multiple encryption-key env vars set; configure exactly one\")\n```\nErrMultipleKeys is returned by LoadKey when more than one key-source env var is set simultaneously. Ambiguous key selection is treated as a hard startup error so misconfiguration is caught immediately rather than silently using the first-priority source.\n\n```go\nvar ErrNoKey = errors.New(\"credentials: no credential encryption key configured\")\n```\nErrNoKey is returned by LoadKey when no encryption key is configured and CREDENTIAL\\_ENCRYPTION\\_ALLOW\\_DEV\\_KEY is not set.\n\n```go\nvar ErrNotHostAccount = errors.New(\"credentials: aws_role_arn is empty but the account is not confirmed as the CUDly host account; set aws_role_arn\")\n```\nErrNotHostAccount means a role\\_arn account with no role ARN could not be confirmed as the AWS account CUDly's own credentials belong to. Its text is stored in tenant-visible rows, so it never carries the host account id or raw STS errors; those are logged. VerifyHostAccount returns it as such only when STS names a different account, the one case the tenant can fix by setting aws\\_role\\_arn; ErrHostIdentityUnavailable also matches it.\n\n## Functions\n\n```go\nfunc BuildAzureFederatedCredential(\n\tsigner oidc.Signer,\n\tissuerURL string,\n\ttenantID string,\n\tclientID string,\n) (azcore.TokenCredential, error)\n```\nBuildAzureFederatedCredential returns an azcore.TokenCredential that authenticates to Azure AD using a federated identity credential. On each call it mints a fresh JWT using the provided Signer, sets its issuer to the CUDly deployment URL, and hands it to azidentity.NewClientAssertionCredential which handles the actual exchange with the Azure token endpoint.\n\nThe target Azure AD app registration must have a federated identity credential configured with:\n\n\tissuer   = \u003cissuerURL\u003e\n\tsubject  = cudly-controller\n\taudience = api://AzureADTokenExchange\n\n— all three are checked by Azure AD when validating the assertion.\n\nNo private key, cert, or client secret is stored anywhere — the signing happens inside the cloud KMS the Signer wraps.\n\n```go\nfunc BuildGCPFederatedCredential(\n\tctx context.Context,\n\tsigner oidc.Signer,\n\tissuerURL string,\n\taudience string,\n\tserviceAccountEmail string,\n) (oauth2.TokenSource, error)\n```\nBuildGCPFederatedCredential returns an oauth2.TokenSource that authenticates to GCP using a federated Workload Identity Pool provider bound to CUDly's OIDC issuer. Each call to Token() mints a fresh KMS-signed JWT, exchanges it at sts.googleapis.com for a GCP federated token, then impersonates the target service account via iamcredentials.googleapis.com to get an access token scoped to cloud-platform.\n\nNo service-account key JSON or any other long-lived secret is stored or read by this path — the signing happens inside the cloud KMS the Signer wraps.\n\n```go\nfunc Decrypt(key []byte, blob string) ([]byte, error)\n```\nDecrypt reverses Encrypt. Returns the original plaintext.\n\n```go\nfunc DevKey() []byte\n```\nDevKey returns the all-zero 32-byte dev key. Exposed for the rekey migration command (cmd/rekey) which needs to detect rows encrypted under it without going through the LoadKey env-var path.\n\n```go\nfunc Encrypt(key, plaintext []byte) (string, error)\n```\nEncrypt encrypts plaintext using AES-256-GCM. Returns a string in the format \"\\\u003cbase64url(nonce)\u003e.\\\u003cbase64url(ciphertext)\u003e\".\n\n```go\nfunc LoadKey(ctx context.Context, resolver secrets.Resolver) (key []byte, source string, err error)\n```\nLoadKey loads the 32-byte AES-256 key for tenant credential encryption. First non-empty wins, in this order:\n\n 1. CREDENTIAL\\_ENCRYPTION\\_KEY\\_SECRET\\_ARN  → resolver.GetSecret(arn)   (AWS)\n 2. CREDENTIAL\\_ENCRYPTION\\_KEY\\_SECRET\\_NAME → resolver.GetSecret(name)  (Azure)\n 3. CREDENTIAL\\_ENCRYPTION\\_KEY\\_SECRET\\_ID   → resolver.GetSecret(id)    (GCP)\n 4. CREDENTIAL\\_ENCRYPTION\\_KEY              → raw 64-char hex\n\nIf none are set, returns ErrNoKey unless CREDENTIAL\\_ENCRYPTION\\_ALLOW\\_DEV\\_KEY=1 is set (in which case the all-zero dev key is returned with a loud warning).\n\nThe returned source string is the env var name that resolved (for logging). Callers MUST NOT log the key value.\n\nA successful load is memoized for the process lifetime. A failed load is not: one throttled secret fetch, or a first caller whose context was already canceled, would otherwise break credential decryption until the process restarts (issue #104), so the next call retries. Tests reset the cache via resetKeyCacheForTest() in this package's test files.\n\n```go\nfunc ResolveAWSCredentialProvider(\n\tctx context.Context,\n\taccount *config.CloudAccount,\n\tstore CredentialStore,\n\tstsClient STSClient,\n) (aws.CredentialsProvider, error)\n```\nResolveAWSCredentialProvider calls ResolveAWSCredentialProviderWithOpts with empty options. It cannot resolve bastion accounts (those need AccountLookup and STSClientFactory), so production callers use the WithOpts variant.\n\n```go\nfunc ResolveAWSCredentialProviderWithOpts(\n\tctx context.Context,\n\taccount *config.CloudAccount,\n\tstore CredentialStore,\n\tstsClient STSClient,\n\topts AWSResolveOptions,\n) (aws.CredentialsProvider, error)\n```\nResolveAWSCredentialProviderWithOpts returns an aws.CredentialsProvider for the account.\n\nLogic per auth mode:\n\n  - access\\_keys: load stored key pair → static credentials provider\n  - role\\_arn:    use ambient (instance role / env) → STS AssumeRole\n  - bastion:     load bastion account creds → STS AssumeRole into target (requires opts.AccountLookup + opts.STSClientFactory)\n  - workload\\_identity\\_federation: token file → STS AssumeRoleWithWebIdentity\n\n```go\nfunc ResolveAzureTokenCredential(\n\tctx context.Context,\n\taccount *config.CloudAccount,\n\tstore CredentialStore,\n) (azcore.TokenCredential, error)\n```\nResolveAzureTokenCredential is a convenience wrapper that passes zero-valued options to ResolveAzureTokenCredentialWithOpts. Since the legacy cert-based WIF path has been removed, this entry point can only resolve client\\_secret and managed\\_identity accounts — WIF accounts require opts.Signer + IssuerURL via the With-opts variant.\n\n```go\nfunc ResolveAzureTokenCredentialWithOpts(\n\tctx context.Context,\n\taccount *config.CloudAccount,\n\tstore CredentialStore,\n\topts AzureResolveOptions,\n) (azcore.TokenCredential, error)\n```\nResolveAzureTokenCredentialWithOpts is like ResolveAzureTokenCredential but accepts per-deployment options. For workload\\_identity\\_federation accounts, AzureResolveOptions.Signer and .IssuerURL must both be set so BuildAzureFederatedCredential can mint the KMS-signed client assertion Azure AD expects — there is no fallback path.\n\nRoutes by AzureAuthMode:\n\n  - managed\\_identity  → ManagedIdentityCredential (no stored cred needed)\n  - workload\\_identity\\_federation → federated credential via opts.Signer\n  - client\\_secret (default) → loads stored secret and returns ClientSecretCredential\n\n```go\nfunc ResolveGCPTokenSource(ctx context.Context, account *config.CloudAccount, store CredentialStore) (oauth2.TokenSource, error)\n```\nResolveGCPTokenSource is the legacy entry point — calls ResolveGCPTokenSourceWithOpts with zero-valued options so existing cert-based / stored-JSON accounts keep working.\n\n```go\nfunc ResolveGCPTokenSourceWithOpts(\n\tctx context.Context,\n\taccount *config.CloudAccount,\n\tstore CredentialStore,\n\topts GCPResolveOptions,\n) (oauth2.TokenSource, error)\n```\nResolveGCPTokenSourceWithOpts is like ResolveGCPTokenSource but accepts per-deployment options. When opts.Signer and opts.IssuerURL are both set, accounts in workload\\_identity\\_federation mode with a gcp\\_wif\\_audience field and no stored JSON config are routed through BuildGCPFederatedCredential (the secret-free path). Existing stored-JSON accounts keep working.\n\nRoutes by GCPAuthMode:\n\n  - application\\_default → returns (nil, nil); caller uses ADC.\n  - workload\\_identity\\_federation → federated (if no stored cred and signer+issuer+audience present) or legacy stored-JSON.\n  - service\\_account\\_key (or empty) → stored-JSON path.\n\n```go\nfunc ValidateGCPWIFEndpoints(tokenURL, impersonationURL string) error\n```\nValidateGCPWIFEndpoints checks the endpoint URLs of a GCP external\\_account credential config. token\\_url is required and must be an https URL whose host is exactly sts.googleapis.com. service\\_account\\_impersonation\\_url is optional; when set it must be an https URL whose host is exactly iamcredentials.googleapis.com. Neither URL may carry user info or an explicit port. The returned error names the field and the expected form only, never the submitted value.\n\n```go\nfunc VerifyHostAccount(ctx context.Context, account *config.CloudAccount, hostSTS CallerIdentityClient) error\n```\nVerifyHostAccount confirms account.ExternalID is the AWS account that hostSTS, an STS client signed with the host's ambient credentials, runs as. An account mismatch returns ErrNotHostAccount; a check that could not run returns ErrHostIdentityUnavailable. Both are returned unwrapped; the detail goes to the log only. The STS call inherits ctx, so a canceled caller stops it, and is bounded by hostIdentityTimeout.\n\n## Types\n\n```go\ntype AWSConfigError struct {\n\tField   string\n\tProblem string\n\t// contains filtered or unexported fields\n}\n```\nAWSConfigError reports an AWS account row whose configuration the resolver cannot use. Field and Problem are fixed, tenant-safe strings (a setting name and what is wrong with it) that callers may show to users; Error() keeps the detailed log-oriented text the resolver has always returned.\n\n```go\nfunc (e *AWSConfigError) Error() string\n```\n\n```go\ntype AWSCredentials struct {\n\tAccessKeyID     string\n\tSecretAccessKey string\n}\n```\nAWSCredentials holds resolved AWS access key credentials.\n\n```go\nfunc (c *AWSCredentials) String() string\n```\nString returns a redacted representation to prevent accidental logging.\n\n```go\ntype AWSResolveOptions struct {\n\tAccountLookup    AccountLookupFunc\n\tSTSClientFactory STSClientFactory\n\t// AmbientProvider is the host Lambda / EC2 instance credentials provider.\n\t// Required when resolving a Self account (role_arn with empty AWSRoleARN).\n\tAmbientProvider aws.CredentialsProvider\n\t// AmbientSTS is an STS client signed with AmbientProvider, used to check\n\t// a Self account's external_id against the host identity.\n\tAmbientSTS CallerIdentityClient\n}\n```\nAWSResolveOptions holds optional dependencies for the AWS credential resolver. The bastion path requires both AccountLookup and STSClientFactory and fails closed when either is nil: it never trusts the caller-supplied STS client to carry bastion credentials (issue #263).\n\nAmbientProvider, when set, is returned for role\\_arn accounts whose AWSRoleARN is empty (the \"Self\" account shape: auth\\_mode=role\\_arn with no role ARN), once AmbientSTS confirms the account is the host. This mirrors the scheduler's collectAWSForAccount logic.\n\n```go\ntype AccountLookupFunc func(ctx context.Context, id string) (*config.CloudAccount, error)\n```\nAccountLookupFunc resolves a CloudAccount by ID. Used by the bastion path so the resolver can self-load the bastion account's credentials rather than trust a caller-supplied STS client.\n\n```go\nfunc AccountLookupFromStore(store CloudAccountGetter) AccountLookupFunc\n```\nAccountLookupFromStore returns an AccountLookupFunc backed by store, or nil when store is nil (bastion resolution then fails closed instead of panicking on a nil store).\n\n```go\ntype AzureCredentials struct {\n\tClientSecret string //nolint:gosec // G117: intentional Azure client-secret field crossing the secure-store boundary; value is resolved from the credential store and used directly for API authentication\n}\n```\nAzureCredentials holds resolved Azure service principal credentials.\n\n```go\nfunc ResolveAzureCredentials(ctx context.Context, account *config.CloudAccount, store CredentialStore) (*AzureCredentials, error)\n```\nResolveAzureCredentials decrypts and returns the Azure client secret for the account.\n\n```go\nfunc (c *AzureCredentials) String() string\n```\nString returns a redacted representation.\n\n```go\ntype AzureResolveOptions struct {\n\t// Signer is the OIDC issuer signer for this CUDly deployment.\n\t// Non-nil signals that the deployment supports federated identity\n\t// credentials.\n\tSigner oidc.Signer\n\t// IssuerURL is the base URL at which this deployment publishes\n\t// /.well-known/openid-configuration. Must match what the Azure AD\n\t// federated credential is registered with.\n\tIssuerURL string\n}\n```\nAzureResolveOptions carries per-deployment wiring that ResolveAzureTokenCredential needs to pick the federated (secret-free) path. A zero value selects the legacy cert-based path for backward compatibility with existing accounts.\n\n```go\ntype CallerIdentityClient interface {\n\tGetCallerIdentity(ctx context.Context, params *sts.GetCallerIdentityInput, optFns ...func(*sts.Options)) (*sts.GetCallerIdentityOutput, error)\n}\n```\nCallerIdentityClient is satisfied by \\*sts.Client.\n\n```go\ntype CloudAccountGetter interface {\n\tGetCloudAccount(ctx context.Context, id string) (*config.CloudAccount, error)\n}\n```\nCloudAccountGetter is the config-store method the bastion path needs to load the bastion account. config.StoreInterface satisfies it.\n\n```go\ntype CredentialStore interface {\n\t// SaveCredential encrypts payload and persists it for accountID/credType.\n\t// If a record for the same (accountID, credType) already exists it is replaced.\n\tSaveCredential(ctx context.Context, accountID, credType string, payload []byte) error\n\n\t// LoadRaw decrypts and returns the raw credential bytes.\n\t// Returns nil, nil when no credential is stored for the given (accountID, credType).\n\tLoadRaw(ctx context.Context, accountID, credType string) ([]byte, error)\n\n\t// DeleteCredential removes the stored credential for accountID/credType.\n\tDeleteCredential(ctx context.Context, accountID, credType string) error\n\n\t// HasCredential reports whether any credential exists for accountID/credType.\n\tHasCredential(ctx context.Context, accountID, credType string) (bool, error)\n\n\t// EncryptPayload encrypts plaintext using the store's AES-256-GCM key.\n\t// Used to encrypt credential data in the account_registrations table.\n\tEncryptPayload(plaintext []byte) (string, error)\n\n\t// DecryptPayload decrypts a ciphertext blob encrypted by EncryptPayload.\n\tDecryptPayload(ciphertext string) ([]byte, error)\n}\n```\nCredentialStore handles encrypted credential blobs backed by the account\\_credentials table. The interface is defined here (not in config/) to avoid circular imports: credentials→config is fine; config→credentials would be circular.\n\n```go\nfunc NewCredentialStore(pool *pgxpool.Pool, encKey []byte) CredentialStore\n```\nNewCredentialStore creates a CredentialStore backed by PostgreSQL. encKey must be the 32-byte AES-256 key (obtain via LoadKey).\n\n```go\ntype GCPResolveOptions struct {\n\t// Signer is the OIDC issuer signer for this CUDly deployment.\n\tSigner oidc.Signer\n\t// IssuerURL is the base URL this deployment publishes OIDC at\n\t// (e.g. \"https://\u003ccudly\u003e/oidc\"). Must match what the target GCP\n\t// Workload Identity Pool provider's issuer-uri is registered as.\n\tIssuerURL string\n}\n```\nGCPResolveOptions carries per-deployment wiring that ResolveGCPTokenSource needs to pick the secret-free federated path. A zero value selects the legacy stored-JSON path for backward compatibility with accounts registered before the redesign.\n\n```go\ntype STSClient interface {\n\tAssumeRole(ctx context.Context, params *sts.AssumeRoleInput, optFns ...func(*sts.Options)) (*sts.AssumeRoleOutput, error)\n\tAssumeRoleWithWebIdentity(ctx context.Context, params *sts.AssumeRoleWithWebIdentityInput, optFns ...func(*sts.Options)) (*sts.AssumeRoleWithWebIdentityOutput, error)\n}\n```\nSTSClient is the STS interface required for role assumption and web identity federation. Satisfied by \\*sts.Client from github.com/aws/aws-sdk-go-v2/service/sts.\n\n```go\ntype STSClientFactory func(provider aws.CredentialsProvider) STSClient\n```\nSTSClientFactory builds an STSClient from a credentials provider. Used by the bastion path to construct an STS client backed by the bastion account's own credentials before assuming the target role.\n\n```go\nfunc NewSTSClientFactory(base aws.Config) STSClientFactory\n```\nNewSTSClientFactory returns an STSClientFactory that builds an STS client from base (region, endpoint, HTTP client, retryer) signed with the given provider instead of base's own credentials. The provider is cached so a role-based bastion is not re-assumed on every STS call.\n\n","path":"github.com/LeanerCloud/cloud-commitments-platform/internal/credentials","name":"credentials","synopsis":"Package credentials provides AES-256-GCM encryption for cloud account credentials and helpers for resolving provider-specific credential structs.","isRedistributable":true}
