kms

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2026 License: MIT Imports: 43 Imported by: 0

README

KMS

Parity grade: A · SDK aws-sdk-go-v2/service/kms@v1.59.0 · last audited 2026-07-23 (13c27883a00454a6e63bc767d096528ecfd6c4b1)

Coverage

Metric Value
PARITY entries audited 54 (54 ok)
Feature families 4 (4 ok)
Known gaps 19
Deferred items 2
Resource leaks fixed
Known gaps
  • RESOLVED 2026-07-23: GrantConstraints had no SourceArn field (real SDK: GrantConstraints.SourceArn). Added; round-trips through CreateGrant -> ListGrants/ListRetirableGrants/Snapshot-Restore. NOT enforced -- no operation in this mock threads a caller/resource ARN through crypto calls to check against it, and no other service adapter currently supplies one either; enforcement remains cross-cutting request-context plumbing, not a KMS-local fix (bd: gopherstack-w3k, still open for the enforcement half only).
  • RESOLVED 2026-07-23: CreateGrantInput had no GrantTokens field (real SDK: authorizes the CreateGrant call itself via an existing not-yet-consistent grant). Added; accepted as a no-op (no IAM/authorization layer exists anywhere in this mock to authorize against), same precedent as CreateKeyInput/ReplicateKeyInput's BypassPolicyLockoutSafetyCheck.
  • RESOLVED 2026-07-23: GranteeServicePrincipal / RetiringServicePrincipal (AWS-service grantees) were not modeled on CreateGrantInput. Added, WITH real validation (exactly one of GranteePrincipal/GranteeServicePrincipal; RetiringPrincipal/RetiringServicePrincipal mutually exclusive; a service grantee requires a SourceArn constraint + a retiring principal), matching the real CreateGrantInput doc comments. No AWS-service-principal simulation exists (still no IAM layer), but the wire shape and its documented validation rules are both real and enforced now, unlike SourceArn's constraint-enforcement half above which has nothing local to check against.
  • RESOLVED 2026-07-12: DescribeKeyInput was missing the GrantTokens field -- added + wired validateGrantTokenPresence (see the DescribeKey op row and describe_key_grant_tokens_test.go). Unlike the CreateGrant/CreateGrantInput GrantTokens gap above (which authorizes the CreateGrant call itself and has nothing to validate without an IAM layer), DescribeKey's GrantTokens resolve to real existing grants, so validation is meaningful and AWS-accurate here (DescribeKey declares InvalidGrantTokenException).
  • RESOLVED 2026-07-12: the region-scoped KeyId resolution inconsistency (GetKeyPolicy/PutKeyPolicy/CreateGrant/ListGrants/RevokeGrant/RetireGrant indexed their policiesStore/grantsRegion using the request region instead of an ARN's embedded region). Root cause was two-fold and both fixed at source: (1) these ops discarded the region resolveKeyID returned and re-used getRegion(ctx) -- fixed by adding a shared resolveKeyAndRegion helper (lookupKey now delegates to it too) that returns the key's actual region, and routing all six ops through it; (2) resolveKeyID's resolution cache stored only the resolved UUID and returned the REQUEST region on every cache hit, so even the region resolveKeyID returned was wrong for any ARN resolved more than once -- fixed by caching a {keyID, region} pair (region="" sentinel for aliases means 'derive from request context', so alias behavior is unchanged; ARN caches its own embedded region, which is safe because the region is part of the ARN cache key). Verified by region_scoped_resolution_test.go (cross-region ReplicateKey -> replica-ARN Put/GetKeyPolicy round-trip + full grant lifecycle by ARN, all while ctx defaults to the primary's region).
  • RESOLVED 2026-09-07 (gopherstack-e76y): CreateKeyInput/KeyMetadata gained CustomKeyStoreID (real SDK: aws-sdk-go-v2/service/kms@v1.55.4 api_op_CreateKey.go:228, types/types.go:439). CreateKeyInput.CustomKeyStoreId's own doc comment (quoted in full): 'Creates the KMS key in the specified custom key store. The ConnectionState of the custom key store must be CONNECTED. To find the CustomKeyStoreID and ConnectionState use the DescribeCustomKeyStores operation. This parameter is valid only for symmetric encryption KMS keys in a single Region. You cannot create any other type of KMS key in a custom key store. When you create a KMS key in an CloudHSM key store, KMS generates a non-exportable 256-bit symmetric key in its associated CloudHSM cluster and associates it with the KMS key. When you create a KMS key in an external key store, you must use the XksKeyId parameter to specify an external key that serves as key material for the KMS key.' Implemented exactly what it states, no more: (1) the store must exist (CustomKeyStoreNotFoundException, extraction-confirmed in deserializeOpErrorCreateKey's error list); (2) its ConnectionState must be CONNECTED (CustomKeyStoreInvalidStateException, also extraction-confirmed, and its own doc comment names 'You requested the CreateKey operation in a custom key store that is not connected' as one of its own reasons for existing); (3) 'valid only for symmetric encryption KMS keys in a single Region' -- resolved KeySpec must be SYMMETRIC_DEFAULT, KeyUsage must be ENCRYPT_DECRYPT, and MultiRegion must be false, or the request is rejected with UnsupportedOperationException (ErrUnsupportedParameter, same sentinel already used elsewhere in this file for 'a specified parameter is not supported'). Declined only the external-key-store half: rather than accept a CustomKeyStoreId for an EXTERNAL_KEY_STORE-type store and silently ignore the doc's 'you must use the XksKeyId parameter' requirement, CreateKey rejects it outright (also UnsupportedOperationException) since XksKeyId itself is unmodeled -- see the new XksKeyId gap entry below (gopherstack-ufvn). The association persists on Key.CustomKeyStoreID and round-trips through DescribeKey.
  • OPEN 2026-09-08 (gopherstack-ufvn, follow-up to gopherstack-e76y; supersedes a same-day RESOLVED/OPEN split entry that was reverted): XksKeyId (external-key-store variant of the CustomKeyStoreId linkage, CreateKeyInput field, api_op_CreateKey.go:481-483) remains entirely unmodeled -- no field, no per-store external-key uniqueness tracking, none of XksKeyNotFoundException/XksKeyAlreadyInUseException/XksKeyInvalidConfigurationException (all three appear in CreateKey's own error list). A same-day pass added CreateKeyInput.XksKeyId plus validateXksKeyID (conditional-required-when-Origin=EXTERNAL_KEY_STORE, plus XksKeyIdType's length/pattern constraints from botocore's service-2.json), raising ErrValidation on failure -- then reverted it, because ErrValidation's wire code, ValidationException, is not in CreateKey's declared error set (CloudHsmClusterInvalidConfiguration, CustomKeyStoreInvalidState, CustomKeyStoreNotFound, DependencyTimeout, InvalidArn, KMSInternal, LimitExceeded, MalformedPolicyDocument, Tag, UnsupportedOperation, XksKeyAlreadyInUse, XksKeyInvalidConfiguration, XksKeyNotFound -- confirmed against kms@v1.59.0 deserializeOpErrorCreateKey), and this service models no ValidationException type at all (zero matches for 'type ValidationException struct' anywhere in the vendored kms module's types package). A caller using a typed client can never match an undeclared code; it degrades to a generic smithy error. Worse, validateXksKeyID ran before the existing CustomKeyStoreId linkage check, so for Origin=EXTERNAL_KEY_STORE with a missing or malformed XksKeyId, callers got this unmatchable code instead of the declared, matchable UnsupportedOperationException they got before the field existed -- a regression, not an improvement, since gopherstack declines the external-key-store linkage entirely regardless of XksKeyId's own shape. No declared code was found that fits a malformed/missing XksKeyId string: XksKeyInvalidConfigurationException's own doc is about the external key's own configuration ('The external key must be an AES-256 symmetric key that is enabled and performs encryption and decryption'), not about the identifier string being absent or badly formed, and XksKeyNotFoundException/XksKeyAlreadyInUseException require actually resolving against an external key manager, which doesn't exist here. CreateKey therefore still rejects any attempt to create a key in an EXTERNAL_KEY_STORE-type custom key store with UnsupportedOperationException, pinned by TestCreateKey_CustomKeyStore_Rejections's "external key store type" subtest (custom_key_store_link_test.go, sentinel-level) and TestCreateKey_ExternalKeyStore_UnsupportedOperationException_RealClient (wire_field_fixes_test.go, errors.As against the real *types.UnsupportedOperationException). Deliberate scope decision, not an oversight -- implementing the linkage is a real feature (see gopherstack-ufvn), not a bug fix, and no wire-shape-only validation of XksKeyId is worth adding without a declared error code to carry it.
  • RESOLVED 2026-09-07 (gopherstack-o3rp): confirmed and fixed. DisconnectCustomKeyStore's own doc comment (kms@v1.55.4 api_op_DisconnectCustomKeyStore.go, quoted in full): 'While a custom key store is disconnected, all attempts to create KMS keys in the custom key store or to use existing KMS keys in [cryptographic operations] will fail.' Error choice was NOT CustomKeyStoreInvalidStateException (that type's own doc enumerates only CreateKey/ConnectCustomKeyStore/DisconnectCustomKeyStore/UpdateCustomKeyStore/DeleteCustomKeyStore/GenerateRandom preconditions -- no crypto op) but KMSInvalidStateException, whose own doc says explicitly: 'For cryptographic operations on KMS keys in custom key stores, this exception represents a general failure with many possible causes.' Extraction of all twelve crypto ops' deserializeOpError functions (Encrypt, Decrypt, ReEncrypt, GenerateDataKey/WithoutPlaintext/Pair/PairWithoutPlaintext, Sign, Verify, GetPublicKey, GenerateMac, VerifyMac, DeriveSharedSecret -- kms@v1.55.4 deserializers.go) confirms every one declares KMSInvalidStateException and none declares CustomKeyStoreInvalidStateException, so the existing ErrKeyInvalidState sentinel (already mapped in kmsErrorTable, no new row needed) was reused rather than adding a new one. Confirmed DisconnectCustomKeyStore itself is unguarded against live keys (only DeleteCustomKeyStore refuses while keys reference the store), so the disconnected-with-live-keys case this issue depends on is reachable. Fix: all twelve crypto ops fetch key material through one shared helper, requireKeyMaterial(region, key) in store.go -- confirmed by grep before touching anything, not assumed -- so the guard was added there once (check Key.CustomKeyStoreID's backing store ConnectionState before returning material) rather than duplicated at each of the twelve call sites; those call sites only changed to pass the already-in-scope *Key instead of a bare keyID string. Regression test TestEncrypt_DisconnectedCustomKeyStore_WireErrorType drives the full HTTP handler (create+connect a store, create a key in it, disconnect, Encrypt) and asserts the JSON Type field is KMSInvalidStateException; confirmed pre-fix by neutering the new guard block in requireKeyMaterial, which makes the test fail with 200 OK instead of 400/KMSInvalidStateException.
  • RESOLVED 2026-09-07 (gopherstack-akm2): confirmed. ConnectCustomKeyStore/DisconnectCustomKeyStore/DeleteCustomKeyStore's own pre-existing state-transition guards (custom_key_stores.go) all returned ErrKeyInvalidState (KMSInvalidStateException), but raw error extraction of all four ops' deserializeOpError functions (kms@v1.55.4 deserializers.go) shows CustomKeyStoreInvalidStateException declared and KMSInvalidStateException declared by NONE of them -- confirmed by types/errors.go's CustomKeyStoreInvalidStateException doc comment, which lists exactly ConnectCustomKeyStore/DisconnectCustomKeyStore/UpdateCustomKeyStore/DeleteCustomKeyStore's non-connected/non-disconnected preconditions as its own reasons for existing. Fixed: all three call sites now use the existing ErrCustomKeyStoreInvalidState sentinel (added by gopherstack-e76y for CreateKey's check, previously unused by these three pre-existing guards). Also fixed a second, dependent gap this exposed: ErrCustomKeyStoreInvalidState was itself absent from handler.go's kmsErrorTable, so even CreateKey's existing use of it fell through to the generic 500 KMSInternalException default instead of the real 400 CustomKeyStoreInvalidStateException -- added the missing table entry (both CustomKeyStoreInvalidStateException and KMSInvalidStateException are ErrorFault: Client in the real SDK, so the HTTP status stays 400 either way; only the JSON error Type field was wrong). UpdateCustomKeyStore is NOT touched by this fix -- it has no ConnectionState guard at all in this backend (a separate, pre-existing feature gap, not a wrong-code bug; not added here to stay in scope). ErrCustomKeyStoreHasKeys (DeleteCustomKeyStore's separate 'store still has keys' check) is also absent from kmsErrorTable, same failure mode as the CreateKey gap above -- left unfixed, out of this issue's scope, noted for a future pass.
  • RESOLVED 2026-09-07 (gopherstack-ylkc): the ErrCustomKeyStoreHasKeys gap flagged (but left unfixed) by gopherstack-akm2 above. DeleteCustomKeyStore's still-has-keys guard (custom_key_stores.go) returns ErrCustomKeyStoreHasKeys (CustomKeyStoreHasCMKsException, added by gopherstack-e76y) but had no row in handler.go's kmsErrorTable, so it fell through the linear errors.Is scan to the generic 500 KMSInternalException default instead of the real 400 CustomKeyStoreHasCMKsException. Extraction of deserializeOpErrorDeleteCustomKeyStore (kms@v1.55.4 deserializers.go) confirms the op declares it: UnknownError, CustomKeyStoreHasCMKsException, CustomKeyStoreInvalidStateException, CustomKeyStoreNotFoundException, KMSInternalException. types/errors.go confirms CustomKeyStoreHasCMKsException.ErrorFault() is smithy.FaultClient, so the fix is a 400, not the pre-fix 500. Fixed: added the missing table row. A full sweep of every sentinel in errors.go against kmsErrorTable (comm -23 on both lists) found exactly this one omission and no others -- the akm2 CustomKeyStoreInvalidState gap it fixed earlier this session was the only sibling, and is already resolved above. Regression test TestDeleteCustomKeyStore_HasKeys_WireErrorType drives the full HTTP handler and asserts the JSON Type field (not just ErrorIs on the sentinel -- an ErrorIs-only assertion is exactly how both this gap and the akm2 one went undetected: TestDeleteCustomKeyStore_WithLinkedKey_Rejected in custom_key_store_link_test.go calls the backend directly and asserts only require.Error + assert.ErrorIs, which passes identically whether or not the table row exists). Confirmed pre-fix: reverting the table row makes the new test fail with 500/KMSInternalException instead of 400/CustomKeyStoreHasCMKsException.
  • RESOLVED 2026-09-07 (gopherstack-8u3f): cmd/errtargetaudit's data-table-aware pass (gopherstack-yn2o) resolved 41/54 kms ops and reported 15 class A findings -- a wire code emitted on an op whose deserializeOpError does not declare it. Every finding individually re-extracted against the pinned kms@v1.55.4 deserializers.go (not trusted from the tool summary). Verdicts: CONFIRMED and FIXED (4 root causes, 5 findings): (1) CancelKeyDeletion emitted DisabledException for a merely-Disabled key -- its own guard (KeyState != PendingDeletion && != PendingReplicaDeletion) is entirely about 'not pending deletion', unrelated to Disabled-vs-other, but it called the shared keyStateError(key) helper (Disabled->DisabledException, else->KMSInvalidStateException) instead of unconditionally raising KMSInvalidStateException as its own doc comment already said it should; keys.go:490-492 now raises ErrKeyInvalidState directly. (2) ImportKeyMaterial's wrong-state guard (KeyState != PendingImport) had the identical bug for the identical reason -- import.go:191-193 now also raises ErrKeyInvalidState directly instead of keyStateError(key). Neither CancelKeyDeletion nor ImportKeyMaterial declares DisabledException in kms@v1.55.4; both declare KMSInvalidStateException. keyStateError() itself is untouched -- callers that legitimately reach it with Disabled reachable (Decrypt/Encrypt/CreateGrant/DisableKeyRotation/EnableKeyRotation etc., all of which DO declare DisabledException) are unaffected, proven by TestDecrypt_DisabledKey_StillDisabledException. (3) VerifyMac's HMAC-mismatch branch (hmac.go) reused ErrInvalidSignature ('KMSInvalidSignatureException', the sentinel Verify's asymmetric-signature mismatch legitimately uses -- confirmed still correct via the pre-existing TestKMSHandlerInvalidSignatureError) instead of its own declared code. VerifyMac's deserializeOpError recognizes KMSInvalidMacException, a distinct type Verify does not declare. Added a new sentinel ErrInvalidMac ('KMSInvalidMacException', errors.go) + kmsErrorTable row (handler.go) and switched the hmac.go call site to it. (4) checkKeyMaterialExpiry (store.go), called only by Encrypt and Decrypt, raised ErrExpiredKeyMaterial ('ExpiredImportTokenException') when an EXTERNAL key's imported material had passed ValidTo -- neither Encrypt nor Decrypt declares ExpiredImportTokenException (only ImportKeyMaterial does, and nothing in this codebase currently reaches it that way); both declare KMSInvalidStateException, matching real AWS's behavior of transitioning an expired-material key back toward PendingImport. Switched to ErrKeyInvalidState. This exposed a genuinely hollow pre-existing test (TestKMS_ErrorClassification_MissingTableEntries/expired_import_material in handler_replication_maintenance_test.go) that drove the full HTTP handler but asserted the wrong wire Type; corrected to KMSInvalidStateException, plus two more backend-level errors.Is hollow tests found the same way while running the suite (TestKMSCancelKeyDeletion_RequiresPendingDeletion/disabled_key_fails in keys_test.go, TestVerifyMac_WrongMac in hmac_test.go) -- both asserted the pre-fix wrong sentinel and were corrected in place. CONFIRMED, LEFT FOR JUDGMENT CALL (2 findings): CreateKey's validateKeySpecUsage (keys.go) rejects an incompatible KeySpec/KeyUsage pair with ErrInvalidKeyUsage ('InvalidKeyUsageException'), which CreateKey's deserializeOpError does not declare (CreateKey declares no key-usage-shaped error at all). ValidationException is the closest real candidate, matching this file's established precedent for undeclared-per-op constraint checks (errors.go's ErrValidation comment, gopherstack-e3yu), but not re-verified against a live smithy trait for this specific field pair, so left for confirmation rather than assumed. DescribeKey's InvalidGrantTokenException (keys.go:277, validateGrantTokenPresence) is a harder case: extraction of deserializeOpErrorDescribeKey in the PINNED kms@v1.55.4 shows only DependencyTimeoutException/InvalidArnException/KMSInternalException/NotFoundException/UnknownError -- no InvalidGrantTokenException -- which directly contradicts this file's own prior 'RESOLVED 2026-07-12' gap entry above (citing kms@v1.54.0 and claiming DescribeKey does declare it). Re-extraction re-run twice against the exact function boundary to rule out a copy error; the pinned-version result stands. Left unfixed rather than unilaterally reverted because the existing validateGrantTokenPresence call, its dedicated describe_key_grant_tokens_test.go, and the above gap entry were a deliberate prior feature addition with its own reasoning, not an oversight -- reversing it removes real (if AWS-inaccurate per this SDK pin) grant-token validation and needs a human call on whether the 1.54.0->1.55.4 discrepancy is a real SDK model change or the earlier session verified against the wrong artifact. ImportKeyMaterial's InvalidKeyUsageException (import.go, 4 sentinel sites all reusing ErrInvalidKeyUsage: line ~156 RSA-OAEP unwrap failure, ~198 KeySpec!=symmetric, ~204 empty KeyMaterial, ~213 wrong-length material) is CONFIRMED not declared (ImportKeyMaterial's error list has no InvalidKeyUsageException) but needs a 4-way judgment call, not a single substitution: the unwrap-failure site plausibly maps to InvalidCiphertextException or IncorrectKeyMaterialException (both declared), the KeySpec-mismatch site to UnsupportedOperationException (declared, matches this mock's own doc comment about only supporting SYMMETRIC_DEFAULT), the empty-material site plausibly to ValidationException (smithy required-field precedent) or IncorrectKeyMaterialException, and the wrong-length site most plausibly to IncorrectKeyMaterialException. Left for a follow-up issue rather than guessed. FALSE POSITIVES (7 findings, all confirmed unreachable by direct code reading, not by trusting the tool): DisableKey and EnableKey's own keyStateError(key) calls (keys.go) are only reached when KeyState is PendingDeletion/PendingImport/PendingReplicaDeletion (the guard explicitly excludes Disabled before calling it), so keyStateError always returns ErrKeyInvalidState there -- DisabledException is statically unreachable through these two call sites, contra the tool's one-hop-callee approximation. ScheduleKeyDeletion's keyStateError(key) call (keys.go) is guarded identically (KeyState == PendingDeletion only), same conclusion. ListResourceTags/TagResource/UntagResource (handler_tags.go) all delegate key-existence checking to h.Backend.DescribeKey(ctx, &DescribeKeyInput{KeyID: input.KeyID}) with GrantTokens left at its zero value, so even though there IS a real call path from these ops down into validateGrantTokenPresence (which is where the tool's constructor-classifier evidence comes from), the argument reaching it is always an empty slice, which validateGrantTokenPresence special-cases to an immediate nil return -- InvalidGrantTokenException is unreachable via this path regardless of the DescribeKey finding above. ReplicateKey (replication.go) has no call path to validateGrantTokenPresence at all -- it does not call DescribeKey and does not accept/forward GrantTokens anywhere in its own body; this appears to be a spurious attribution with no supporting call-graph edge, not even the empty-argument case the tagging ops have. Gates: go test -race -count=1 ./services/kms/... and golangci-lint run services/kms/... both green. Every changed production line neutered individually (reverted -> confirmed compiles -> confirmed a specific test fails -> restored) before reporting; see the issue's chat transcript for the per-line table.
  • RESOLVED 2026-09-07 (gopherstack-h88p): the ImportKeyMaterial half of gopherstack-8u3f's 'LEFT FOR JUDGMENT CALL' finding above, decided per site (raw extraction re-run, both operations): ImportKeyMaterial declares DependencyTimeoutException/ExpiredImportTokenException/IncorrectKeyMaterialException/InvalidArnException/InvalidCiphertextException/InvalidImportTokenException/KMSInternalException/KMSInvalidStateException/NotFoundException/UnsupportedOperationException -- no InvalidKeyUsageException, no ValidationException. Four sites: (1) resolveKeyMaterial's RSA-OAEP unwrap failure (import.go) -> ErrInvalidCiphertext (InvalidCiphertextException); its own doc comment is explicit for exactly this op: 'From the ImportKeyMaterial operation, the request was rejected because KMS could not decrypt the encrypted (wrapped) key material.' (2) The KeySpec!=SYMMETRIC_DEFAULT guard -> ErrUnsupportedParameter (UnsupportedOperationException, already used elsewhere in this file for KeySpec-shaped mismatches); UnsupportedOperationException's own doc covers 'a specified parameter is not supported or a specified resource is not valid for this operation' -- the key's own KeySpec is the resource here, not a request parameter, but the doc's second clause fits. (3) Empty-KeyMaterial guard -> ErrIncorrectKeyMaterial (IncorrectKeyMaterialException), same sentinel as (4). First pass swapped this site to ErrValidation on the reasoning that EncryptedKeyMaterial is a required field a real SDK client rejects before the wire, 'same as GenerateMac's MacAlgorithm-empty check' -- caught in review as swapping one undeclared code (InvalidKeyUsageException) for another undeclared one (ValidationException, confirmed absent from every deserializer in the whole kms@v1.55.4 module, not just this op), with 'we already do this elsewhere' doing the load-bearing work instead of an actual declared-set fit. Corrected: IncorrectKeyMaterialException's own doc disjunction -- 'is, expired, invalid, or does not meet expectations' -- covers empty material under 'invalid', the same declared code the wrong-length site below uses under 'does not meet expectations'; AWS's own doc groups both failure modes under one exception, so one sentinel serving both sites matches the SDK's own granularity rather than losing a real distinction. (4) Wrong-length guard -> new sentinel ErrIncorrectKeyMaterial (IncorrectKeyMaterialException, errors.go + kmsErrorTable row added); its doc fits precisely: 'the key material in the request is, expired, invalid, or does not meet expectations.' CreateKey's half of the same 8u3f finding was NOT touched: re-extraction confirms CreateKey's declared set (CloudHsmClusterInvalidConfigurationException/CustomKeyStore{InvalidState,NotFound}Exception/DependencyTimeoutException/InvalidArnException/KMSInternalException/LimitExceededException/MalformedPolicyDocumentException/TagException/UnsupportedOperationException/XksKey{AlreadyInUse,InvalidConfiguration,NotFound}Exception) has no key-usage-shaped code and, unlike 8u3f's assumption, does NOT include ValidationException (confirmed absent from the whole kms@v1.55.4 SDK module, not just this op) -- so validateKeySpecUsage's ErrInvalidKeyUsage site and the HMAC+MultiRegion ErrInvalidKeyUsage site (both keys.go, both inside CreateKey) are a third bug shape (no declared code fits at all, unlike a two-candidate ambiguity) and are left as a documented landmine rather than swapped to a guess; filed as a fresh follow-up rather than left silently. Verified no pre-existing test asserted the wrong wire code for any of the four ImportKeyMaterial sites (searched all *_test.go for InvalidKeyUsageException; the only hits were Encrypt/VerifyMac/key_agreement, all legitimate), so 0 pre-existing tests needed correction. New regression tests in import_error_wiring_test.go drive the full HTTP handler and assert the JSON Type field for all four sites, plus two guard tests (Decrypt, VerifyMac) proving ops that legitimately declare InvalidKeyUsageException still emit it. Every changed production line neutered individually (reverted -> confirmed compiles -> confirmed the matching test fails with the specific pre-fix wire type -> restored), including the new kmsErrorTable row (reverting it alone drops the wrong-length case to 500/KMSInternalException). Gates: go test -race -count=1 ./services/kms/... and golangci-lint run services/kms/... both green. SIZING NOTE, not fixed here (out of scope for this issue): ErrValidation (ValidationException) itself remains a live sentinel with 36 raise sites across 16 non-test files (aliases.go, crypto.go x4, custom_key_stores.go x2, encryption.go, grants.go x7, handler_grants_policies.go, hmac.go x2 [including the GenerateMac MacAlgorithm-empty precedent this issue's first pass leaned on], import.go x3 [ExpirationModel validation + an internal type-assertion guard; the two former InvalidKeyUsageException sites this issue fixed no longer use it], keys.go x4, key_agreement.go x2, key_policies.go, random.go, replication.go x2, rotation.go, signing.go x2, store.go), every one of them emitting a code confirmed absent from every operation's deserializeOpError in the whole kms@v1.55.4 module (not just the op each site reaches). A future pass should re-run the per-site judgment call this issue applied to CreateKey and ImportKeyMaterial across all 36: for each, either find a real declared code (per-op, per-site, not by pattern-matching a sibling site) or leave a landmine -- 'the sentinel already exists elsewhere' is not itself a fit.
  • RESOLVED 2026-09-07 (gopherstack-i4q8): the h88p sizing note's full 36-site sweep. Re-derived the inventory from scratch rather than trusting h88p's per-file count (grep -n ErrValidation across the 16 non-test files, minus definition/comment hits in errors.go/handler.go/store.go/keys.go) -- got 36 total but grants.go is 8 sites, not 7 (h88p's list missed ListRetirableGrants' RetiringPrincipal/RetiringServicePrincipal exclusivity check, grants.go ~line 433; validateGrantPrincipals' 4 sites + CreateGrant's own 3 + that one = 8), so the file-count discrepancy cancels out to the same 36. For every site: traced its reaching operation(s) by grep on the enclosing function's callers (not assumed from the file it lives in), extracted that op's declared set with awk '/deserializeOpError<Op>\\(/,/^}/' deserializers.go | grep -oE '"[A-Za-z0-9]+"', and read the doc comment of any plausible candidate before accepting or rejecting it. FIXED (4 sites, all reused existing sentinels -- no new ones needed): CreateKey's Description-length check (keys.go, validateCreateKeyLimits) and CreateGrant's Name-length check (grants.go, inside CreateGrant) both -> ErrLimitExceeded (LimitExceededException); its own doc is explicit -- 'The request was rejected because a length constraint or quota was exceeded' -- and both ops declare it (CreateKey already reuses it for its Tags-count check one line below the Description one; CreateGrant declares it for grant-count-per-key, already used lower in the same function). PutKeyPolicy's PolicyName!='default' check, at BOTH of its two sites (handler_grants_policies.go's dispatch-level check, which is what a real client actually hits, and key_policies.go's own backend-level copy of the identical check) -> ErrUnsupportedParameter (UnsupportedOperationException); its doc -- 'a specified parameter is not supported' -- matches PolicyName's own field doc in api_op_PutKeyPolicy.go ('The only valid value is default'), the same enum-of-one pattern ErrUnsupportedParameter already covers for KeySpec/KeyPairSpec elsewhere, and PutKeyPolicy declares the code. The key_policies.go copy is provably dead code in production -- grep confirms Backend.PutKeyPolicy has exactly one caller (the handler dispatch), which already normalizes/rejects PolicyName before calling it -- fixed anyway as defense in depth and because it is reachable directly in tests (see key_policies_test.go). LEFT, 32 sites, each with an inline landmine comment naming the operation's declared set and why nothing in it fits (see aliases.go:203ish, crypto.go x4, custom_key_stores.go x2, encryption.go:43ish, grants.go x7 [4 in validateGrantPrincipals + the Operations-empty and invalid-grant-operation checks + ListRetirableGrants], hmac.go x2, import.go x3, keys.go x2 [UpdateKeyDescription's Description-length check does NOT get CreateKey's fix -- UpdateKeyDescription's declared set has no length/quota code at all -- and ListKeys' Limit check], key_agreement.go x2, random.go, replication.go x2, rotation.go, signing.go x2, store.go). Two are shared helpers reached by ops with DIFFERING declared sets, called out separately per this issue's instructions rather than folded into the per-site list: validateEncryptionContextSize (crypto.go) is reached by GenerateDataKey(WithoutPlaintext), GenerateDataKeyPair(WithoutPlaintext), Encrypt, Decrypt and ReEncrypt -- traced via grep on the helper's own name plus validateGenerateDataKeyInput/validateReEncryptInput's callers -- but the outcome is the same either way (none of the 7 declared sets has an EncryptionContext-size code, so the multi-op reachability doesn't change the verdict, just widens who it's wrong for); resolveKeyID (store.go) is reached by nearly every KeyId-resolving op (each with its own declared set per the pre-existing qxaj comment on the same function) but the specific branch is cache corruption, not a real client-triggerable condition, so there is no per-op fit question to answer at all. Two more are internal defensive checks unreachable by any request (import.go's wrapping-key type assertion, store.go's cache-entry type assertion) -- noted as a fourth, distinct sub-category (not a wrong-code bug at all; there is no real per-op question to resolve). Regression tests (handler_keys_test.go, handler_grants_policies_test.go) drive the full HTTP handler and assert the JSON Type field plus 'not ValidationException' plus a no-mutation check (rejected CreateKey creates no key, rejected CreateGrant creates no grant, rejected PutKeyPolicy leaves the stored policy unchanged) for all 4 fixed sites; the pre-existing TestKeyPolicy_InvalidPolicyName (key_policies_test.go), which called the backend directly and only asserted require.Error, was strengthened to assert.ErrorIs the correct sentinel and assert.NotErrorIs ErrValidation -- proven necessary by neutering key_policies.go's fix alone with the OLD assertion in place (full suite green, because require.Error is blind to which error), then again with the STRENGTHENED assertion (fails at key_policies_test.go:57-58 with the exact predicted 'expected UnsupportedOperationException, found ValidationException' diff). All 4 production lines individually neutered (reverted -> go build succeeded -> the matching test failed at the exact predicted line/diff -> restored): keys.go:145, grants.go:106, handler_grants_policies.go:67 (each caught by its new test), key_policies.go:28 (caught only by the strengthened pre-existing test, not by any handler test, since the line is unreachable via HTTP). Gates: go test -race -count=1 ./services/kms/... and golangci-lint run services/kms/... both green. Filed as follow-up, not fixed here: the third-bug-shape sites among the 32 left (CreateGrant's invalid-Operations-entry check, structurally identical to CreateKey's own undeclared KeyUsage-mismatch gap noted in h88p's entry above, both 5rjn-class) and the two conflicting-declared-set shared helpers, as candidates for either a future declared-code discovery or a permanent landmine, per this issue's own scope boundary of fixing only what clearly fits.
  • RESOLVED 2026-09-07 (gopherstack-yatn, orphan-code class): validateMacAlgorithm (crypto.go, reached by GenerateMac and VerifyMac) raised ErrInvalidAlgorithm ('InvalidAlgorithmException'), a code confirmed absent from the ENTIRE pinned kms@v1.55.4 module -- grep -rn InvalidAlgorithmException over the whole module returns nothing, not just 'wrong op'. Both GenerateMac's and VerifyMac's own deserializeOpError declare InvalidKeyUsageException, whose doc (types/errors.go:753-767) is explicit: 'the encryption algorithm or signing algorithm specified for the operation is incompatible with the type of key material in the KMS key (KeySpec)... For generating and verifying message authentication codes (MACs), the KeyUsage must be GENERATE_VERIFY_MAC.' Switched the call site to the pre-existing ErrInvalidKeyUsage sentinel (already in kmsErrorTable, no new row needed) and removed the now-dead ErrInvalidAlgorithm sentinel and its table row. Three pre-existing hmac_test.go assertions (TestGenerateMac_WrongAlgorithm_HMAC256KeyWithSHA512, TestGenerateMac_WrongAlgorithm_HMAC512KeyWithSHA256, TestVerifyMac_WrongAlgorithm) asserted the wrong wire string and were corrected in place. New regression tests (mac_algorithm_wiring_test.go) drive the full HTTP handler for both ops and assert the JSON Type field is InvalidKeyUsageException; confirmed failing pre-fix with the exact wrong value 'InvalidAlgorithmException'. Not authorization/enforcement-related -- pure algorithm-vs-keyspec validation, no grant/policy path touched. Gates: go test -race ./services/kms/... and golangci-lint run ./services/kms/... both green.
  • RESOLVED 2026-09-07 (gopherstack-5rjn): CreateKey's two h88p/i4q8-left landmines (validateKeySpecUsage's call, keys.go, and the HMAC+MultiRegion check next to it) turned out to need two different fixes, not one. (1) validateKeySpecUsage's ErrInvalidKeyUsage raise was swapped to ErrUnsupportedParameter (UnsupportedOperationException): CreateKey's declared set (re-derived, matches h88p's list exactly, confirmed word-for-word against the live AWS API_CreateKey.html Errors section) has no key-usage-shaped code, and InvalidKeyUsageException's own doc (docs-2.json) is about an existing key's KeyUsage being wrong for the operation invoked, not this creation-time KeySpec/KeyUsage pairing -- a different condition, not just an undeclared one. UnsupportedOperationException is both declared by CreateKey and evidenced live for a KeySpec-shaped CreateKey rejection (developerguide hmac-create-key.html: an HMAC KeySpec unsupported in a Region -> UnsupportedOperationException), and its doc's first clause ('a specified parameter is not supported') covers a KeyUsage value unsupported for the given KeySpec. Weighed gopherstack-q9bs's ValidationException finding and declined it here: q9bs's evidence (GetPublicKey's malformed-DER-blob case) is a pre-dispatch, structural fault; a KeySpec/KeyUsage pairing is cross-field operation logic, a materially different condition, so ValidationException does not fit better than the existing UnsupportedOperationException precedent already used for the same shape (import.go's KeySpec!=SYMMETRIC_DEFAULT guard, gopherstack-h88p). (2) The HMAC+MultiRegion check was not a wrong-error-code bug at all -- its premise was false. kms@v1.55.4's own api_op_CreateKey.go doc comment (the pinned SDK source this whole campaign treats as ground truth) is explicit: 'You can create multi-Region KMS keys for all supported KMS key types: symmetric encryption KMS keys, HMAC KMS keys, asymmetric encryption KMS keys, and asymmetric signing KMS keys.' Cross-confirmed against the live AWS API docs and the 2021-06 multi-Region-keys launch post. HMAC keys DO support MultiRegion; the check unconditionally rejected a valid request shape and was removed rather than re-coded. Two pre-existing tests encoded the false premise and were corrected, not weakened: TestKMSCreateKeyIncompatibleSpecUsage (signing_internal_test.go) asserted ErrInvalidKeyUsage for genuinely-incompatible KeySpec/KeyUsage pairs -- corrected to ErrUnsupportedParameter, matching (1) above; TestCreateKeyValidations's hmac_multiregion case (replication_test.go) asserted wantErr:true for HMAC+MultiRegion -- corrected to wantErr:false (renamed hmac_multiregion_allowed) per (2). TestHandlerCreateKeyHMACMultiRegionRejected (handler_replication_maintenance_test.go) was removed outright, superseded by TestHandler_CreateKey_HMACMultiRegion_ViaHTTP (handler_keys_test.go), which now asserts 200 with the requested KeySpec/KeyUsage/MultiRegion round-tripped. New regression test TestHandler_CreateKey_KeySpecKeyUsageMismatch_ViaHTTP (handler_keys_test.go) drives the full HTTP handler for RSA_2048+GENERATE_VERIFY_MAC and asserts JSON Type is UnsupportedOperationException, not InvalidKeyUsageException; confirmed failing pre-fix with the exact predicted values (400/InvalidKeyUsageException). errtargetaudit -dir kms shows 0 CreateKey findings after the fix (unrelated pre-existing DescribeKey/DisableKey/EnableKey/ScheduleKeyDeletion findings are untouched false positives per the 8u3f entry above). Not authorization/grant/policy-related -- pure KeySpec/KeyUsage/MultiRegion request validation. Gates: go test -race -count=1 ./services/kms/... and golangci-lint run ./services/kms/... both green.
  • RESOLVED 2026-09-07 (gopherstack-4ra7): the two shared-helper landmines i4q8 called out separately (differing caller declared sets defeat the per-call-site rule). Caller lists re-verified by grep, not trusted: validateEncryptionContextSize (crypto.go) is reached by GenerateDataKey and GenerateDataKeyWithoutPlaintext (both via the shared generateDataKey helper), GenerateDataKeyPair and GenerateDataKeyPairWithoutPlaintext (both via the shared generateDataKeyPair helper), Encrypt, Decrypt and ReEncrypt (via validateReEncryptInput) -- 7 ops, matching the issue exactly. Re-extracted all 7 declared sets from kms@v1.55.4 deserializers.go: none has a size/length/quota-shaped code (LimitExceededException is absent from every one of the 7; each set is dominated by key-state/grant-token/key-usage codes). No plumbing added: threading a per-caller sentinel through the helper, or returning a neutral sentinel for callers to translate, would add real cost (a new parameter or wrapper type threaded through 7 call sites) to select between codes that ALL fail to fit -- worse than the landmine it would replace. Kept ErrValidation (ValidationException) and documented why it is not a landmine here despite gopherstack-q9bs's structural/operation-logic distinction: an EncryptionContext byte-size cap is a single-field length constraint independent of any other field or resource state, the same shape as q9bs's own GetPublicKey malformed-DER-blob example, not a cross-field business rule like CreateKey's KeySpec/KeyUsage pairing (5rjn, above) -- so it is the pre-dispatch/structural class q9bs confirmed the allowlist entry covers, not the operation-logic class it doesn't. resolveKeyID's (store.go) cache-corruption branch (a failed type assertion on a sync.Map load) was independently verified unreachable, not assumed from the issue text: grep confirms the only two Store calls into keyIDResolutionCache (store.go:449, 460) always write cachedResolution, and Restore (persistence.go:322, 344) clears the cache via clearResolutionCache rather than repopulating it from snapshot data -- no code path, including snapshot/restore, can produce a non-cachedResolution entry. Same shape as gopherstack-t8iz's stepfunctions finding: an honest landmine, not a per-op design question, since there is no reachable per-op fit to resolve. Both sites already carried a one-line landmine comment; strengthened in place (crypto.go, store.go) to record the caller lists / unreachability proof and the q9bs cross-reference, rather than adding a second RESOLVED-but-changed-nothing note without pointing at the evidence. No production behavior changed for either site. Gates: go test -race -count=1 ./services/kms/... and golangci-lint run ./services/kms/... both green.
  • RESOLVED 2026-09-07 (gopherstack-jyi3): CreateGrant's invalid-Operations-entry check (grants.go) was left an open question by 3b06f1f3d (filed to decide alongside 5rjn) and then swept, with its landmine comment removed, by 905209940's blanket 32-site ValidationException ruling -- but never individually re-verified against CreateGrant's own declared set or GrantOperation's shape. Re-derived: CreateGrant's deserializeOpError (kms@v1.55.4) declares DependencyTimeoutException/DisabledException/DryRunOperationException/InvalidArnException/InvalidGrantTokenException/KMSInternalException/KMSInvalidStateException/LimitExceededException/NotFoundException -- no UnsupportedOperationException, so 5rjn's CreateKey KeySpec/KeyUsage remedy does not transfer (that op declares the code CreateGrant simply doesn't have). Checked GrantOperation directly in api-2.json: a plain enum-constrained string shape, no cross-field rule -- the same single-field structural class as q9bs's GetPublicKey malformed-blob precedent (and gopherstack-4ra7's EncryptionContext-size precedent), not the cross-field business-rule class 5rjn's KeySpec/KeyUsage pairing needed its own declared code for. So ErrValidation is correct here specifically, not merely by blanket inheritance. No code or test change (the site's behavior was already correct); grants.go's check now carries a short comment recording this, since 905209940 left it bare. gopherstack-i4q8's original 36-site inventory undercounted CreateGrant's other undeclared-code sites too (see gaps entries above, all still-correct ErrLimitExceeded/ErrValidation calls).
  • 2026-09-12 (reqfielddiff slice 6, gopherstack-xhu2t): ListKeyRotationsInput.IncludeKeyMaterial (ALL_KEY_MATERIAL) is entirely unmodeled -- honoring it means adding a synthetic 'first key material' RotationsListEntry plus tracking 'imported key material pending rotation' as a distinct generation, and this backend already has a documented precedent against exactly that: ImportKeyMaterialOutput's own doc comment (models.go) states 'this backend has no concept of multiple key-material generations per key.' Not implemented, consistent with that existing scope decision.
  • 2026-09-12 (reqfielddiff slice 6, gopherstack-xhu2t): CreateCustomKeyStore/UpdateCustomKeyStoreInput.XksProxyVpcEndpointServiceOwner is accepted-and-dropped -- the real CustomKeyStoresListEntry response type (kms@v1.59.0 types/types.go:35+) has no field to round-trip it onto, and this backend models no XKS-proxy/VPC-endpoint-service state at all (CustomKeyStore only tracks CustomKeyStoreType/ConnectionState, matching the pre-existing 'deferred' entry above: 'no CloudHSM cluster or XKS proxy is modeled'). Nothing observable to fix.
Deferred
  • Custom key store cryptographic connection/HSM simulation (ConnectCustomKeyStore is a pure state-machine transition; no CloudHSM cluster or XKS proxy is modeled, matching pre-existing scope). Re-audited 2026-07-23, still accurate -- no change.
  • REMOVED 2026-07-23: GetKeyLastUsage was listed here as 'not a real AWS KMS operation'. That was wrong on every prior pass -- see the GetKeyLastUsage ops row above. It is now field-diffed and current.

More

Documentation

Overview

Package kms provides a mock AWS Key Management Service (KMS) implementation.

Index

Constants

View Source
const (

	// MockAccountID is the mock AWS account ID.
	MockAccountID = config.DefaultAccountID
	// MockRegion is the mock AWS region.
	MockRegion = config.DefaultRegion
)
View Source
const ConnectionStateConnected = "CONNECTED"

ConnectionStateConnected indicates a custom key store is connected.

View Source
const ConnectionStateDisconnected = "DISCONNECTED"

ConnectionStateDisconnected indicates a custom key store is disconnected.

View Source
const KeyOriginAWSKMS = "AWS_KMS"

KeyOriginAWSKMS is the origin for keys whose material is generated by AWS KMS.

View Source
const KeyOriginExternal = "EXTERNAL"

KeyOriginExternal is the origin for keys whose material is imported by the customer.

View Source
const KeyStateDisabled = "Disabled"

KeyStateDisabled is the string constant for a disabled key.

View Source
const KeyStateEnabled = "Enabled"

KeyStateEnabled is the string constant for an enabled key.

View Source
const KeyStatePendingDeletion = "PendingDeletion"

KeyStatePendingDeletion is the string constant for a key pending deletion.

View Source
const KeyStatePendingImport = "PendingImport"

KeyStatePendingImport is the string constant for a key awaiting imported key material.

View Source
const KeyStatePendingReplicaDeletion = "PendingReplicaDeletion"

KeyStatePendingReplicaDeletion is the string constant for a multi-Region primary key whose deletion was scheduled while it still has replica keys. It stays in this non-final state indefinitely until the last replica is actually deleted, at which point it moves to KeyStatePendingDeletion and its waiting period begins.

View Source
const KeyUsageEncryptDecrypt = "ENCRYPT_DECRYPT"

KeyUsageEncryptDecrypt is the string constant for the default key usage.

View Source
const KeyUsageGenerateMac = "GENERATE_VERIFY_MAC"

KeyUsageGenerateMac is the key usage for HMAC keys.

View Source
const KeyUsageKeyAgreement = "KEY_AGREEMENT"

KeyUsageKeyAgreement is the key usage for ECDH key agreement keys.

View Source
const KeyUsageSignVerify = "SIGN_VERIFY"

KeyUsageSignVerify is the string constant for sign/verify-only keys.

Variables

View Source
var (
	// ErrKeyNotFound is returned when the specified key does not exist.
	ErrKeyNotFound = errors.New("NotFoundException")

	// ErrMalformedPolicyDocument is returned when the provided policy is invalid.
	ErrMalformedPolicyDocument = errors.New("MalformedPolicyDocumentException")
	// ErrAliasNotFound is returned when the specified alias does not exist.
	ErrAliasNotFound = errors.New("NotFoundException")
	// ErrAliasAlreadyExists is returned when an alias with the given name already exists.
	ErrAliasAlreadyExists = errors.New("AlreadyExistsException")
	// ErrInvalidAliasName is returned by CreateAlias when AliasName doesn't start with
	// "alias/", is reserved ("alias/aws/"), exceeds the length limit, or contains
	// disallowed characters. CreateAlias's own deserializeOpError (kms@v1.55.4
	// deserializers.go) recognizes InvalidAliasNameException for exactly this.
	ErrInvalidAliasName = errors.New("InvalidAliasNameException")
	// ErrCustomKeyStoreAlreadyExists is returned when a custom key store with the given name already exists.
	ErrCustomKeyStoreAlreadyExists = errors.New("CustomKeyStoreNameInUseException")
	// ErrCustomKeyStoreNotFound is returned when a custom key store ID does not exist.
	ErrCustomKeyStoreNotFound = errors.New("CustomKeyStoreNotFoundException")
	// ErrCustomKeyStoreInvalidState is returned by CreateKey when the target custom
	// key store's ConnectionState is not CONNECTED, and by Connect/Disconnect/
	// DeleteCustomKeyStore for their own state preconditions (UpdateCustomKeyStore
	// has no ConnectionState guard in this backend; see PARITY.md gopherstack-akm2).
	// CreateKey's own deserializeOpError (kms@v1.55.4 deserializers.go) recognizes
	// CustomKeyStoreInvalidStateException for exactly this.
	ErrCustomKeyStoreInvalidState = errors.New("CustomKeyStoreInvalidStateException")
	// ErrCustomKeyStoreHasKeys is returned by DeleteCustomKeyStore when the store
	// still contains KMS keys. DeleteCustomKeyStore's own deserializeOpError
	// recognizes CustomKeyStoreHasCMKsException for exactly this ("The custom key
	// store that you delete cannot contain any KMS keys").
	ErrCustomKeyStoreHasKeys = errors.New("CustomKeyStoreHasCMKsException")
	// ErrKeyDisabled is returned when an operation is attempted on a disabled key.
	ErrKeyDisabled = errors.New("DisabledException")
	// ErrKeyInvalidState is returned when a key is in a state that does not allow the requested
	// operation (e.g. PendingDeletion).
	ErrKeyInvalidState = errors.New("KMSInvalidStateException")
	// ErrInvalidKeyUsage is returned when the key is used for an operation incompatible with its
	// KeyUsage (e.g. encrypting with a SIGN_VERIFY key).
	ErrInvalidKeyUsage = errors.New("InvalidKeyUsageException")
	// ErrInvalidCiphertext is returned when the ciphertext cannot be decrypted.
	ErrInvalidCiphertext = errors.New("InvalidCiphertextException")
	// ErrIncorrectKey is returned when the KMS key identified by a caller-supplied KeyId
	// (Decrypt) or SourceKeyId (ReEncrypt) is not the key that encrypted the ciphertext.
	ErrIncorrectKey = errors.New("IncorrectKeyException")
	// ErrIncorrectKeyMaterial is returned by ImportKeyMaterial when the supplied key
	// material does not meet expectations (e.g. wrong length for the target key spec).
	// IncorrectKeyMaterialException's doc (kms@v1.55.4 types/errors.go): "the key
	// material in the request is, expired, invalid, or does not meet expectations".
	ErrIncorrectKeyMaterial = errors.New("IncorrectKeyMaterialException")
	// ErrGrantNotFound is returned when the specified grant does not exist.
	ErrGrantNotFound = errors.New("NotFoundException: grant not found")
	// ErrCiphertextTooShort is returned when the ciphertext is too short.
	ErrCiphertextTooShort = errors.New("ciphertext too short")
	// ErrInvalidDataKeySize is returned when a data key size is invalid or too large.
	ErrInvalidDataKeySize = errors.New("ValidationException: invalid data key size")
	// ErrInvalidSignature is returned when a signature verification fails.
	ErrInvalidSignature = errors.New("KMSInvalidSignatureException")
	// ErrInvalidMac is returned when a VerifyMac HMAC comparison fails. Distinct from
	// ErrInvalidSignature: VerifyMac's own deserializeOpError (kms@v1.55.4
	// deserializers.go) recognizes KMSInvalidMacException, not KMSInvalidSignatureException
	// (that code belongs to Verify only).
	ErrInvalidMac = errors.New("KMSInvalidMacException")
	// ErrKeyMaterialUnavailable is returned when key material is missing (e.g. restored from
	// an older snapshot that predates key material persistence).
	ErrKeyMaterialUnavailable = errors.New("key material unavailable for this key")
	// ErrUnsupportedOrigin is returned when an operation is incompatible with the key's origin.
	ErrUnsupportedOrigin = errors.New("UnsupportedOperationException")
	// ErrValidation is returned for invalid request parameters (maps to ValidationException).
	// "ValidationException" names no per-operation typed exception in kms@v1.55.4 (not in
	// types/errors.go, not in any op's deserializeOpError, and absent from the full
	// api-2.json model too) -- it is real for KMS at the pre-dispatch, protocol level
	// regardless: KMS's own GetPublicKey doc quotes a live wire ValidationException for a
	// malformed PublicKey that no op declares, and deserializeOpError's default case
	// preserves an unmodeled wire code rather than rejecting it. Settled by
	// gopherstack-q9bs; the sites below using it are correct, not landmines.
	ErrValidation = errors.New("ValidationException")
	// ErrDryRun is returned by the 15 KMS ops whose input carries a DryRun member
	// (CreateGrant, Decrypt, DeriveSharedSecret, Encrypt, GenerateDataKey,
	// GenerateDataKeyPair, GenerateDataKeyPairWithoutPlaintext,
	// GenerateDataKeyWithoutPlaintext, GenerateMac, ReEncrypt, RetireGrant,
	// RevokeGrant, Sign, Verify, VerifyMac -- grepped `DryRun \*bool` across
	// aws-sdk-go-v2/service/kms@v1.54.0's api_op_*.go) when DryRun=true and every
	// other check the op performs passes. DryRunOperationException's doc
	// (types/errors.go): "The request was rejected because the DryRun
	// parameter was specified".
	ErrDryRun = errors.New("DryRunOperationException")
	// ErrExpiredKeyMaterial is returned when a key's imported material has passed its ValidTo date.
	ErrExpiredKeyMaterial = errors.New("ExpiredImportTokenException")
	// ErrInvalidGrantToken is returned when a grant token is expired or malformed.
	ErrInvalidGrantToken = errors.New("InvalidGrantTokenException")
	// ErrLimitExceeded is returned when a service limit is exceeded (e.g. grants per key)
	// or, per LimitExceededException's own doc ("a length constraint or quota was
	// exceeded"), a length constraint -- CreateKey's Description and CreateGrant's
	// Name length checks reuse it for exactly that (gopherstack-i4q8).
	ErrLimitExceeded = errors.New("LimitExceededException")
	// ErrAccessDenied is returned when a grant token is valid but its Operations list
	// does not authorize the operation being performed.
	ErrAccessDenied = errors.New("AccessDeniedException")
	// ErrInvalidTag is returned when a tag key/value fails KMS's format constraints
	// (empty key, length limit, reserved "aws:" prefix). TagResource, CreateKey and
	// ReplicateKey's deserializeOpError all recognize TagException for this.
	ErrInvalidTag = errors.New("TagException")
	// ErrUnsupportedParameter is returned when a KeySpec/KeyPairSpec/WrappingAlgorithm/
	// WrappingKeySpec/PolicyName value is not one this operation supports. CreateKey,
	// GenerateDataKeyPair(WithoutPlaintext), GetParametersForImport, the rotation
	// ops and PutKeyPolicy all recognize UnsupportedOperationException for an
	// unsupported parameter value, per its doc ("a specified parameter is not
	// supported") -- gopherstack-i4q8 added the PutKeyPolicy reuse; gopherstack-5rjn
	// added validateKeySpecUsage's KeySpec/KeyUsage pairing check.
	ErrUnsupportedParameter = errors.New("UnsupportedOperationException")
	// ErrInvalidImportToken is returned when ImportKeyMaterial's wrapped key material
	// cannot be unwrapped because no GetParametersForImport wrapping key is on record
	// for the target KMS key (stale or skipped GetParametersForImport call).
	// ImportKeyMaterial's deserializeOpError recognizes InvalidImportTokenException.
	ErrInvalidImportToken = errors.New("InvalidImportTokenException")
	// ErrInvalidArn is returned by resolveKeyID/resolveARNKeyID for a malformed KeyId
	// ARN, for the KeyId-accepting operations whose own deserializeOpError recognizes
	// InvalidArnException (gopherstack-qxaj). Crypto ops (Encrypt, Decrypt, Sign,
	// GenerateDataKey, ...) do not model it -- those callers pass ErrKeyNotFound
	// instead, the only resource-shaped code they do recognize.
	ErrInvalidArn = errors.New("InvalidArnException")
)
View Source
var ErrNilAppContext = errors.New("nil AppContext passed to KMS Provider.Init")

ErrNilAppContext is returned by Init when a nil AppContext is passed.

View Source
var ErrUnknownOperation = errors.New("UnknownOperationException")

ErrUnknownOperation is returned when the requested KMS operation is not supported.

Functions

func UnixTimeFloat

func UnixTimeFloat(t time.Time) float64

UnixTimeFloat converts a time value to a Unix timestamp float.

Types

type Alias

type Alias struct {
	// AliasName is the alias name (e.g., alias/my-key).
	AliasName string `json:"AliasName"`
	// AliasArn is the full ARN of the alias.
	AliasArn string `json:"AliasArn"`
	// TargetKeyId is the key ID that this alias points to.
	TargetKeyID string `json:"TargetKeyId,omitempty"`
	// CreationDate is the Unix timestamp when the alias was created.
	CreationDate float64 `json:"CreationDate,omitempty"`
	// LastUpdatedDate is the Unix timestamp when the alias was last updated.
	LastUpdatedDate float64 `json:"LastUpdatedDate,omitempty"`
}

Alias represents a KMS alias pointing to a key.

type CancelKeyDeletionInput

type CancelKeyDeletionInput struct {
	KeyID string `json:"KeyId"`
}

CancelKeyDeletionInput is the request payload for CancelKeyDeletion.

type CancelKeyDeletionOutput

type CancelKeyDeletionOutput struct {
	KeyID    string `json:"KeyId"`
	KeyState string `json:"KeyState"`
}

CancelKeyDeletionOutput is the response payload for CancelKeyDeletion.

type ConfigProvider

type ConfigProvider interface {
	GetKMSSettings() Settings
}

ConfigProvider is a private interface to extract KMS configuration from the abstract AppContext Config.

type ConnectCustomKeyStoreInput

type ConnectCustomKeyStoreInput struct {
	// CustomKeyStoreId identifies the custom key store to connect.
	CustomKeyStoreID string `json:"CustomKeyStoreId"`
}

ConnectCustomKeyStoreInput is the request payload for ConnectCustomKeyStore.

type CreateAliasInput

type CreateAliasInput struct {
	// AliasName is the name of the alias (must begin with alias/).
	AliasName string `json:"AliasName"`
	// TargetKeyId is the key ID the alias should point to.
	TargetKeyID string `json:"TargetKeyId"`
}

CreateAliasInput is the request payload for CreateAlias.

type CreateCustomKeyStoreInput

type CreateCustomKeyStoreInput struct {
	// CustomKeyStoreName is the name of the custom key store to create.
	CustomKeyStoreName string `json:"CustomKeyStoreName"`
	// CustomKeyStoreType is the type of custom key store (default AWS_CLOUDHSM).
	CustomKeyStoreType string `json:"CustomKeyStoreType,omitempty"`
}

CreateCustomKeyStoreInput is the request payload for CreateCustomKeyStore.

type CreateCustomKeyStoreOutput

type CreateCustomKeyStoreOutput struct {
	// CustomKeyStoreId is the ID of the newly created custom key store.
	CustomKeyStoreID string `json:"CustomKeyStoreId"`
}

CreateCustomKeyStoreOutput is the response payload for CreateCustomKeyStore.

type CreateGrantInput

type CreateGrantInput struct {
	Constraints              *GrantConstraints `json:"Constraints,omitempty"`
	KeyID                    string            `json:"KeyId"`
	GranteePrincipal         string            `json:"GranteePrincipal,omitempty"`
	GranteeServicePrincipal  string            `json:"GranteeServicePrincipal,omitempty"`
	RetiringPrincipal        string            `json:"RetiringPrincipal,omitempty"`
	RetiringServicePrincipal string            `json:"RetiringServicePrincipal,omitempty"`
	Name                     string            `json:"Name,omitempty"`
	Operations               []string          `json:"Operations"`
	// GrantTokens authorizes the CreateGrant call itself via an existing,
	// not-yet-eventually-consistent grant. There is no IAM/authorization
	// layer anywhere in this mock, so this field is accepted for wire parity
	// and otherwise a no-op -- the same documented scope boundary as
	// CreateKeyInput/ReplicateKeyInput's BypassPolicyLockoutSafetyCheck.
	GrantTokens []string `json:"GrantTokens,omitempty"`
	DryRun      bool     `json:"DryRun,omitempty"`
}

CreateGrantInput is the request payload for CreateGrant.

type CreateGrantOutput

type CreateGrantOutput struct {
	GrantID    string `json:"GrantId"`
	GrantToken string `json:"GrantToken"`
}

CreateGrantOutput is the response payload for CreateGrant.

type CreateKeyInput

type CreateKeyInput struct {
	Description                    string `json:"Description,omitempty"`
	KeyUsage                       string `json:"KeyUsage,omitempty"`
	KeySpec                        string `json:"KeySpec,omitempty"`
	Origin                         string `json:"Origin,omitempty"`
	Policy                         string `json:"Policy,omitempty"`
	Region                         string `json:"-"`
	CustomKeyStoreID               string `json:"CustomKeyStoreId,omitempty"`
	Tags                           []Tag  `json:"Tags,omitempty"`
	MultiRegion                    bool   `json:"MultiRegion,omitempty"`
	BypassPolicyLockoutSafetyCheck bool   `json:"BypassPolicyLockoutSafetyCheck,omitempty"`
}

CreateKeyInput is the request payload for CreateKey.

type CreateKeyOutput

type CreateKeyOutput struct {
	// KeyMetadata contains the newly created key metadata.
	KeyMetadata KeyMetadata `json:"KeyMetadata"`
}

CreateKeyOutput is the response payload for CreateKey.

type CustomKeyStore

type CustomKeyStore struct {
	CustomKeyStoreID   string  `json:"CustomKeyStoreId"`
	CustomKeyStoreName string  `json:"CustomKeyStoreName"`
	ConnectionState    string  `json:"ConnectionState"`
	CustomKeyStoreType string  `json:"CustomKeyStoreType"`
	CreationDate       float64 `json:"CreationDate"`
}

CustomKeyStore represents an AWS KMS custom key store entry.

type DecryptInput

type DecryptInput struct {
	EncryptionContext map[string]string `json:"EncryptionContext,omitempty"`
	// GrantTokens is an optional list of grant tokens used to authorize the operation.
	GrantTokens         []string `json:"GrantTokens,omitempty"`
	KeyID               string   `json:"KeyId,omitempty"`
	CiphertextBlob      []byte   `json:"CiphertextBlob"`
	EncryptionAlgorithm string   `json:"EncryptionAlgorithm,omitempty"`
	DryRun              bool     `json:"DryRun,omitempty"`
}

DecryptInput is the request payload for Decrypt.

type DecryptOutput

type DecryptOutput struct {
	KeyID               string `json:"KeyId"`
	EncryptionAlgorithm string `json:"EncryptionAlgorithm,omitempty"`
	Plaintext           []byte `json:"Plaintext"`
}

DecryptOutput is the response payload for Decrypt.

type DeleteAliasInput

type DeleteAliasInput struct {
	// AliasName is the name of the alias to delete.
	AliasName string `json:"AliasName"`
}

DeleteAliasInput is the request payload for DeleteAlias.

type DeleteCustomKeyStoreInput

type DeleteCustomKeyStoreInput struct {
	// CustomKeyStoreId identifies the custom key store to delete.
	CustomKeyStoreID string `json:"CustomKeyStoreId"`
}

DeleteCustomKeyStoreInput is the request payload for DeleteCustomKeyStore.

type DeleteImportedKeyMaterialInput

type DeleteImportedKeyMaterialInput struct {
	// KeyId identifies the EXTERNAL-origin key whose material should be deleted.
	KeyID string `json:"KeyId"`
}

DeleteImportedKeyMaterialInput is the request payload for DeleteImportedKeyMaterial.

type DeleteImportedKeyMaterialOutput added in v1.3.1

type DeleteImportedKeyMaterialOutput struct {
	KeyID string `json:"KeyId"`
}

DeleteImportedKeyMaterialOutput is the response payload for DeleteImportedKeyMaterial. See ImportKeyMaterialOutput for why KeyMaterialId is not modeled.

type DeriveSharedSecretInput

type DeriveSharedSecretInput struct {
	// KeyId is the ECC key (KEY_AGREEMENT usage) used to derive the shared secret.
	KeyID string `json:"KeyId"`
	// KeyAgreementAlgorithm is the key agreement algorithm (always ECDH).
	KeyAgreementAlgorithm string `json:"KeyAgreementAlgorithm"`
	// PublicKey is the DER-encoded public key of the other party.
	PublicKey []byte `json:"PublicKey"`
	// GrantTokens is an optional list of grant tokens used to authorize the operation.
	GrantTokens []string `json:"GrantTokens,omitempty"`
	DryRun      bool     `json:"DryRun,omitempty"`
}

DeriveSharedSecretInput is the request payload for DeriveSharedSecret.

type DeriveSharedSecretOutput

type DeriveSharedSecretOutput struct {
	KeyID                 string `json:"KeyId"`
	KeyAgreementAlgorithm string `json:"KeyAgreementAlgorithm"`
	SharedSecret          []byte `json:"SharedSecret"`
}

DeriveSharedSecretOutput is the response payload for DeriveSharedSecret.

type DescribeCustomKeyStoresInput

type DescribeCustomKeyStoresInput struct {
	// CustomKeyStoreId filters results to a single custom key store by ID.
	CustomKeyStoreID string `json:"CustomKeyStoreId,omitempty"`
	// CustomKeyStoreName filters results to a single custom key store by name.
	CustomKeyStoreName string `json:"CustomKeyStoreName,omitempty"`
	// Limit caps the number of results returned.
	Limit *int32 `json:"Limit,omitempty"`
	// Marker is the pagination cursor from a previous call.
	Marker string `json:"Marker,omitempty"`
}

DescribeCustomKeyStoresInput is the request payload for DescribeCustomKeyStores.

type DescribeCustomKeyStoresOutput

type DescribeCustomKeyStoresOutput struct {
	NextMarker      string           `json:"NextMarker,omitempty"`
	CustomKeyStores []CustomKeyStore `json:"CustomKeyStores"`
	Truncated       bool             `json:"Truncated"`
}

DescribeCustomKeyStoresOutput is the response payload for DescribeCustomKeyStores.

type DescribeKeyInput

type DescribeKeyInput struct {
	// KeyId is the key ID or alias to describe.
	KeyID string `json:"KeyId"`
	// GrantTokens is an optional list of grant tokens used to make a just-created
	// grant that permits DescribeKey immediately effective. DescribeKey is a valid
	// grant operation (see isValidGrantOperation) and the real DescribeKey op
	// declares InvalidGrantTokenException in its error set, so a supplied token
	// must resolve to an existing, unexpired grant.
	GrantTokens []string `json:"GrantTokens,omitempty"`
}

DescribeKeyInput is the request payload for DescribeKey.

type DescribeKeyOutput

type DescribeKeyOutput struct {
	// KeyMetadata contains the key metadata.
	KeyMetadata KeyMetadata `json:"KeyMetadata"`
}

DescribeKeyOutput is the response payload for DescribeKey.

type DisableKeyInput

type DisableKeyInput struct {
	KeyID string `json:"KeyId"`
}

DisableKeyInput is the request payload for DisableKey.

type DisableKeyRotationInput

type DisableKeyRotationInput struct {
	// KeyId is the key to disable rotation for.
	KeyID string `json:"KeyId"`
}

DisableKeyRotationInput is the request payload for DisableKeyRotation.

type DisconnectCustomKeyStoreInput

type DisconnectCustomKeyStoreInput struct {
	// CustomKeyStoreId identifies the custom key store to disconnect.
	CustomKeyStoreID string `json:"CustomKeyStoreId"`
}

DisconnectCustomKeyStoreInput is the request payload for DisconnectCustomKeyStore.

type EnableKeyInput

type EnableKeyInput struct {
	KeyID string `json:"KeyId"`
}

EnableKeyInput is the request payload for EnableKey.

type EnableKeyRotationInput

type EnableKeyRotationInput struct {
	RotationPeriodInDays *int32 `json:"RotationPeriodInDays,omitempty"`
	KeyID                string `json:"KeyId"`
}

EnableKeyRotationInput is the request payload for EnableKeyRotation.

type EncryptInput

type EncryptInput struct {
	EncryptionContext map[string]string `json:"EncryptionContext,omitempty"`
	// GrantTokens is an optional list of grant tokens used to authorize the operation.
	GrantTokens []string `json:"GrantTokens,omitempty"`
	KeyID       string   `json:"KeyId"`
	Plaintext   []byte   `json:"Plaintext"`
	// EncryptionAlgorithm is required only for asymmetric keys; symmetric keys
	// default to SYMMETRIC_DEFAULT when omitted.
	EncryptionAlgorithm string `json:"EncryptionAlgorithm,omitempty"`
	DryRun              bool   `json:"DryRun,omitempty"`
}

EncryptInput is the request payload for Encrypt.

type EncryptOutput

type EncryptOutput struct {
	KeyID               string `json:"KeyId"`
	EncryptionAlgorithm string `json:"EncryptionAlgorithm,omitempty"`
	CiphertextBlob      []byte `json:"CiphertextBlob"`
}

EncryptOutput is the response payload for Encrypt.

type ErrorResponse

type ErrorResponse struct {
	// Type is the error type string.
	Type string `json:"__type"`
	// Message is the human-readable error message.
	Message string `json:"message"`
}

ErrorResponse is the KMS JSON error response format.

type GenerateDataKeyInput

type GenerateDataKeyInput struct {
	EncryptionContext map[string]string `json:"EncryptionContext,omitempty"`
	NumberOfBytes     *int32            `json:"NumberOfBytes,omitempty"`
	KeyID             string            `json:"KeyId"`
	KeySpec           string            `json:"KeySpec,omitempty"`
	GrantTokens       []string          `json:"GrantTokens,omitempty"`
	DryRun            bool              `json:"DryRun,omitempty"`
}

GenerateDataKeyInput is the request payload for GenerateDataKey.

type GenerateDataKeyOutput

type GenerateDataKeyOutput struct {
	KeyID          string `json:"KeyId"`
	CiphertextBlob []byte `json:"CiphertextBlob"`
	Plaintext      []byte `json:"Plaintext"`
}

GenerateDataKeyOutput is the response payload for GenerateDataKey.

type GenerateDataKeyPairInput

type GenerateDataKeyPairInput struct {
	// EncryptionContext is the optional encryption context for the wrapping key.
	EncryptionContext map[string]string `json:"EncryptionContext,omitempty"`
	// KeyId is the KMS symmetric key used to encrypt the private key.
	KeyID string `json:"KeyId"`
	// KeyPairSpec specifies the asymmetric key spec (e.g. RSA_2048, ECC_NIST_P256).
	KeyPairSpec string `json:"KeyPairSpec"`
	// GrantTokens is an optional list of grant tokens used to authorize the operation.
	GrantTokens []string `json:"GrantTokens,omitempty"`
	DryRun      bool     `json:"DryRun,omitempty"`
}

GenerateDataKeyPairInput is the request payload for GenerateDataKeyPair.

type GenerateDataKeyPairOutput

type GenerateDataKeyPairOutput struct {
	// KeyId is the ARN of the wrapping KMS key.
	KeyID string `json:"KeyId"`
	// KeyPairSpec is the key pair spec used.
	KeyPairSpec string `json:"KeyPairSpec"`
	// PrivateKeyCiphertextBlob is the DER-encoded private key encrypted under KeyId.
	PrivateKeyCiphertextBlob []byte `json:"PrivateKeyCiphertextBlob"`
	// PrivateKeyPlaintext is the DER-encoded PKCS#8 private key.
	PrivateKeyPlaintext []byte `json:"PrivateKeyPlaintext"`
	// PublicKey is the DER-encoded SubjectPublicKeyInfo public key.
	PublicKey []byte `json:"PublicKey"`
}

GenerateDataKeyPairOutput is the response payload for GenerateDataKeyPair.

type GenerateDataKeyPairWithoutPlaintextInput

type GenerateDataKeyPairWithoutPlaintextInput struct {
	// EncryptionContext is the optional encryption context for the wrapping key.
	EncryptionContext map[string]string `json:"EncryptionContext,omitempty"`
	// KeyId is the KMS symmetric key used to encrypt the private key.
	KeyID string `json:"KeyId"`
	// KeyPairSpec specifies the asymmetric key spec (e.g. RSA_2048, ECC_NIST_P256).
	KeyPairSpec string `json:"KeyPairSpec"`
	// GrantTokens is an optional list of grant tokens used to authorize the operation.
	GrantTokens []string `json:"GrantTokens,omitempty"`
	DryRun      bool     `json:"DryRun,omitempty"`
}

GenerateDataKeyPairWithoutPlaintextInput is the request payload for GenerateDataKeyPairWithoutPlaintext.

type GenerateDataKeyPairWithoutPlaintextOutput

type GenerateDataKeyPairWithoutPlaintextOutput struct {
	// KeyId is the ARN of the wrapping KMS key.
	KeyID string `json:"KeyId"`
	// KeyPairSpec is the key pair spec used.
	KeyPairSpec string `json:"KeyPairSpec"`
	// PrivateKeyCiphertextBlob is the DER-encoded private key encrypted under KeyId.
	PrivateKeyCiphertextBlob []byte `json:"PrivateKeyCiphertextBlob"`
	// PublicKey is the DER-encoded SubjectPublicKeyInfo public key.
	PublicKey []byte `json:"PublicKey"`
}

GenerateDataKeyPairWithoutPlaintextOutput is the response payload for GenerateDataKeyPairWithoutPlaintext.

type GenerateDataKeyWithoutPlaintextInput

type GenerateDataKeyWithoutPlaintextInput struct {
	EncryptionContext map[string]string `json:"EncryptionContext,omitempty"`
	NumberOfBytes     *int32            `json:"NumberOfBytes,omitempty"`
	KeyID             string            `json:"KeyId"`
	KeySpec           string            `json:"KeySpec,omitempty"`
	GrantTokens       []string          `json:"GrantTokens,omitempty"`
	DryRun            bool              `json:"DryRun,omitempty"`
}

GenerateDataKeyWithoutPlaintextInput is the request payload for GenerateDataKeyWithoutPlaintext.

type GenerateDataKeyWithoutPlaintextOutput

type GenerateDataKeyWithoutPlaintextOutput struct {
	KeyID          string `json:"KeyId"`
	CiphertextBlob []byte `json:"CiphertextBlob"`
}

GenerateDataKeyWithoutPlaintextOutput is the response payload for GenerateDataKeyWithoutPlaintext.

type GenerateMacInput

type GenerateMacInput struct {
	// KeyId is the HMAC KMS key used to generate the MAC.
	KeyID string `json:"KeyId"`
	// MacAlgorithm specifies the MAC algorithm (e.g. HMAC_SHA_256).
	MacAlgorithm string `json:"MacAlgorithm"`
	// Message is the data over which to compute the MAC.
	Message []byte `json:"Message"`
	// GrantTokens is an optional list of grant tokens used to authorize the operation.
	GrantTokens []string `json:"GrantTokens,omitempty"`
	DryRun      bool     `json:"DryRun,omitempty"`
}

GenerateMacInput is the request payload for GenerateMac.

type GenerateMacOutput

type GenerateMacOutput struct {
	KeyID        string `json:"KeyId"`
	MacAlgorithm string `json:"MacAlgorithm"`
	Mac          []byte `json:"Mac"`
}

GenerateMacOutput is the response payload for GenerateMac.

type GenerateRandomInput

type GenerateRandomInput struct {
	// NumberOfBytes specifies how many random bytes to generate (default 32, max 1024).
	NumberOfBytes *int32 `json:"NumberOfBytes,omitempty"`
}

GenerateRandomInput is the request payload for GenerateRandom.

type GenerateRandomOutput

type GenerateRandomOutput struct {
	// Plaintext contains the generated random bytes.
	Plaintext []byte `json:"Plaintext"`
}

GenerateRandomOutput is the response payload for GenerateRandom.

type GetKeyLastUsageInput

type GetKeyLastUsageInput struct {
	KeyID string `json:"KeyId"` //nolint:tagliatelle // AWS API uses KeyId
}

GetKeyLastUsageInput is the request payload for GetKeyLastUsage.

type GetKeyLastUsageOutput

type GetKeyLastUsageOutput struct {
	KeyLastUsage      *KeyLastUsageData `json:"KeyLastUsage,omitempty"`
	KeyID             string            `json:"KeyId,omitempty"`
	KeyCreationDate   float64           `json:"KeyCreationDate,omitempty"`
	TrackingStartDate float64           `json:"TrackingStartDate,omitempty"`
}

GetKeyLastUsageOutput is the response payload for GetKeyLastUsage.

type GetKeyPolicyInput

type GetKeyPolicyInput struct {
	KeyID      string `json:"KeyId"`
	PolicyName string `json:"PolicyName"`
}

GetKeyPolicyInput is the request payload for GetKeyPolicy.

type GetKeyPolicyOutput

type GetKeyPolicyOutput struct {
	Policy     string `json:"Policy"`
	PolicyName string `json:"PolicyName"`
}

GetKeyPolicyOutput is the response payload for GetKeyPolicy.

type GetKeyRotationStatusInput

type GetKeyRotationStatusInput struct {
	// KeyId is the key to query rotation status for.
	KeyID string `json:"KeyId"`
}

GetKeyRotationStatusInput is the request payload for GetKeyRotationStatus.

type GetKeyRotationStatusOutput

type GetKeyRotationStatusOutput struct {
	KeyID                     string  `json:"KeyId"`
	NextRotationDate          float64 `json:"NextRotationDate,omitempty"`
	OnDemandRotationStartDate float64 `json:"OnDemandRotationStartDate,omitempty"`
	RotationPeriodInDays      int32   `json:"RotationPeriodInDays,omitempty"`
	KeyRotationEnabled        bool    `json:"KeyRotationEnabled"`
}

GetKeyRotationStatusOutput is the response payload for GetKeyRotationStatus.

type GetParametersForImportInput

type GetParametersForImportInput struct {
	KeyID             string `json:"KeyId"`
	WrappingAlgorithm string `json:"WrappingAlgorithm,omitempty"`
	WrappingKeySpec   string `json:"WrappingKeySpec,omitempty"`
}

GetParametersForImportInput is the request payload for GetParametersForImport.

type GetParametersForImportOutput

type GetParametersForImportOutput struct {
	KeyID             string  `json:"KeyId"`
	ImportToken       []byte  `json:"ImportToken"`
	PublicKey         []byte  `json:"PublicKey"`
	ParametersValidTo float64 `json:"ParametersValidTo"`
}

GetParametersForImportOutput is the response payload for GetParametersForImport.

type GetPublicKeyInput

type GetPublicKeyInput struct {
	// KeyId identifies the asymmetric KMS key whose public key to retrieve.
	KeyID string `json:"KeyId"`
	// GrantTokens is an optional list of grant tokens used to authorize the operation.
	GrantTokens []string `json:"GrantTokens,omitempty"`
}

GetPublicKeyInput is the request payload for GetPublicKey.

type GetPublicKeyOutput

type GetPublicKeyOutput struct {
	// KeyId is the ID of the asymmetric KMS key.
	KeyID string `json:"KeyId"`
	// PublicKey is the DER-encoded public key.
	PublicKey []byte `json:"PublicKey"`
	// KeySpec is the key spec of the key.
	KeySpec string `json:"KeySpec"`
	// KeyUsage is the intended use of the key.
	KeyUsage string `json:"KeyUsage"`
	// SigningAlgorithms lists the signing algorithms supported by this key.
	SigningAlgorithms []string `json:"SigningAlgorithms,omitempty"`
	// EncryptionAlgorithms lists the encryption algorithms (empty for sign keys).
	EncryptionAlgorithms []string `json:"EncryptionAlgorithms,omitempty"`
	// KeyAgreementAlgorithms lists the key agreement algorithms (e.g. ECDH).
	KeyAgreementAlgorithms []string `json:"KeyAgreementAlgorithms,omitempty"`
}

GetPublicKeyOutput is the response payload for GetPublicKey.

type Grant

type Grant struct {
	// Constraints holds optional constraints for the grant.
	Constraints *GrantConstraints `json:"Constraints,omitempty"`
	// GrantID is the unique identifier for the grant.
	GrantID string `json:"GrantId"`
	// KeyID is the ID of the KMS key.
	KeyID string `json:"KeyId"`
	// GranteePrincipal is the principal that receives the grant. Mutually
	// exclusive with GranteeServicePrincipal; exactly one must be set.
	GranteePrincipal string `json:"GranteePrincipal,omitempty"`
	// GranteeServicePrincipal is the AWS service principal that receives the
	// grant. Mutually exclusive with GranteePrincipal; exactly one must be
	// set. No AWS-service-principal simulation exists in this mock (no
	// IAM/authorization layer at all -- see CreateGrantInput.GrantTokens), so
	// this is stored/round-tripped for wire parity, matching real AWS's
	// GrantListEntry shape, without any behavioral effect.
	GranteeServicePrincipal string `json:"GranteeServicePrincipal,omitempty"`
	// RetiringPrincipal is the principal that can retire the grant. Mutually
	// exclusive with RetiringServicePrincipal.
	RetiringPrincipal string `json:"RetiringPrincipal,omitempty"`
	// RetiringServicePrincipal is the AWS service principal that can retire
	// the grant. Mutually exclusive with RetiringPrincipal. Same no-IAM-layer
	// scope boundary as GranteeServicePrincipal.
	RetiringServicePrincipal string `json:"RetiringServicePrincipal,omitempty"`
	// GrantToken is a token that can be used to identify this grant.
	GrantToken string `json:"GrantToken"`
	// TokenIssuedAt records when the grant token was issued, enabling expiry checks.
	TokenIssuedAt time.Time `json:"TokenIssuedAt"`
	// Name is an optional name for the grant.
	Name string `json:"Name,omitempty"`
	// Operations is the list of cryptographic operations the grantee can perform.
	Operations []string `json:"Operations"`
	// CreationDate is the Unix timestamp when the grant was created.
	CreationDate float64 `json:"CreationDate"`
	// IssuingAccount is the AWS account ID under which the grant was issued.
	IssuingAccount string `json:"IssuingAccount,omitempty"`
}

Grant represents a KMS key grant.

type GrantConstraints

type GrantConstraints struct {
	// EncryptionContextEquals requires the caller's encryption context to be
	// an exact match of this map (same keys and values).
	EncryptionContextEquals map[string]string `json:"EncryptionContextEquals,omitempty"`
	// EncryptionContextSubset requires the caller's encryption context to
	// contain at least all key-value pairs present in this map.
	EncryptionContextSubset map[string]string `json:"EncryptionContextSubset,omitempty"`
	// SourceArn restricts grant use to requests made on behalf of the named
	// AWS resource (effectively the aws:SourceArn condition key). This mock
	// has no cross-service request-context plumbing to carry a "made on
	// behalf of" resource ARN through crypto calls, so the constraint is
	// stored and round-tripped (CreateGrant -> ListGrants/ListRetirableGrants)
	// for wire parity but is NOT enforced -- consistent with the scope
	// boundary already documented for grant-token authorization elsewhere in
	// this package (see isValidGrantOperation's doc and CreateGrantInput.
	// GrantTokens below).
	SourceArn string `json:"SourceArn,omitempty"`
}

GrantConstraints holds the constraints for a grant. When set, cryptographic operations using this grant's token must supply an encryption context that satisfies the constraint.

type GrantListEntry added in v1.3.1

type GrantListEntry struct {
	Constraints              *GrantConstraints `json:"Constraints,omitempty"`
	GrantID                  string            `json:"GrantId"`
	KeyID                    string            `json:"KeyId"`
	GranteePrincipal         string            `json:"GranteePrincipal,omitempty"`
	GranteeServicePrincipal  string            `json:"GranteeServicePrincipal,omitempty"`
	RetiringPrincipal        string            `json:"RetiringPrincipal,omitempty"`
	RetiringServicePrincipal string            `json:"RetiringServicePrincipal,omitempty"`
	Name                     string            `json:"Name,omitempty"`
	Operations               []string          `json:"Operations"`
	CreationDate             float64           `json:"CreationDate"`
	IssuingAccount           string            `json:"IssuingAccount,omitempty"`
}

GrantListEntry is the wire shape of a single ListGrants/ListRetirableGrants result entry, matching real AWS's types.GrantListEntry field-for-field. It deliberately excludes GrantToken and TokenIssuedAt: a grant token is returned exactly once, in the CreateGrant response, and is never retrievable from a List call -- see kms.Grant for the internal storage representation that does carry both.

type Handler

type Handler struct {
	Backend StorageBackend

	DefaultRegion string
	// contains filtered or unexported fields
}

Handler is the Echo HTTP handler for KMS operations.

func NewHandler

func NewHandler(backend StorageBackend) *Handler

NewHandler creates a new KMS handler with the given storage backend and logger.

func (*Handler) ChaosOperations

func (h *Handler) ChaosOperations() []string

ChaosOperations returns all operations that can be fault-injected.

func (*Handler) ChaosRegions

func (h *Handler) ChaosRegions() []string

ChaosRegions returns all regions this KMS instance handles.

func (*Handler) ChaosServiceName

func (h *Handler) ChaosServiceName() string

ChaosServiceName returns the lowercase AWS service name for fault rule matching.

func (*Handler) ExtractOperation

func (h *Handler) ExtractOperation(c *echo.Context) string

ExtractOperation extracts the KMS operation name from the X-Amz-Target header.

func (*Handler) ExtractResource

func (h *Handler) ExtractResource(c *echo.Context) string

ExtractResource returns the key ID from the request body when present.

func (*Handler) GetSupportedOperations

func (h *Handler) GetSupportedOperations() []string

GetSupportedOperations returns the list of supported KMS operations (sorted alphabetically).

func (*Handler) Handler

func (h *Handler) Handler() echo.HandlerFunc

Handler returns the Echo handler function for KMS operations.

func (*Handler) MatchPriority

func (h *Handler) MatchPriority() int

MatchPriority returns the routing priority for the KMS handler.

func (*Handler) Name

func (h *Handler) Name() string

Name returns the service name.

func (*Handler) Reset

func (h *Handler) Reset()

Reset clears all state in the backend and the handler's tag store. It is used by the POST /_gopherstack/reset endpoint for CI pipelines.

func (*Handler) Restore

func (h *Handler) Restore(ctx context.Context, data []byte) error

Restore implements persistence.Persistable. It accepts both the current wrapped format (handlerSnapshot) and a legacy snapshot (raw bytes produced by delegating straight to Backend.Snapshot, with no handler-level tags) so that pre-existing on-disk snapshots taken before tags were persisted still restore backend state cleanly instead of erroring out.

func (*Handler) RouteMatcher

func (h *Handler) RouteMatcher() service.Matcher

RouteMatcher returns a matcher that identifies KMS requests by the X-Amz-Target header.

func (*Handler) Snapshot

func (h *Handler) Snapshot(ctx context.Context) []byte

Snapshot implements persistence.Persistable. It wraps the backend's own snapshot together with handler-level resource tags (see handlerSnapshot) so a Restore round-trip preserves tags, not just key/alias/grant state.

func (*Handler) StartWorker

func (h *Handler) StartWorker(ctx context.Context) error

StartWorker starts the background janitor if one is configured.

func (*Handler) TagKeyByARN

func (h *Handler) TagKeyByARN(ctx context.Context, keyARN string, newTags map[string]string) error

TagKeyByARN applies tags to the KMS key identified by its ARN.

func (*Handler) TaggedKeys

func (h *Handler) TaggedKeys(ctx context.Context) []TaggedKeyInfo

TaggedKeys returns a snapshot of all KMS keys with their ARNs and tags. Intended for use by the Resource Groups Tagging API provider.

func (*Handler) UntagKeyByARN

func (h *Handler) UntagKeyByARN(ctx context.Context, keyARN string, tagKeys []string) error

UntagKeyByARN removes the specified tag keys from the KMS key identified by its ARN.

func (*Handler) WithJanitor

func (h *Handler) WithJanitor(interval time.Duration, taskTimeout ...time.Duration) *Handler

WithJanitor attaches a background key-deletion janitor to the handler. If the backend is not an *InMemoryBackend, this is a no-op.

type ImportKeyMaterialInput

type ImportKeyMaterialInput struct {
	KeyID           string  `json:"KeyId"`
	ExpirationModel string  `json:"ExpirationModel,omitempty"`
	KeyMaterial     []byte  `json:"EncryptedKeyMaterial"`
	ValidTo         float64 `json:"ValidTo,omitempty"`
}

ImportKeyMaterialInput is the request payload for ImportKeyMaterial.

type ImportKeyMaterialOutput added in v1.3.1

type ImportKeyMaterialOutput struct {
	KeyID string `json:"KeyId"`
}

ImportKeyMaterialOutput is the response payload for ImportKeyMaterial. The real output also declares KeyMaterialId, part of the multi-key-material rotation feature (aws-sdk-go-v2 kms@v1.55.4 api_op_ImportKeyMaterial.go); this backend has no concept of multiple key-material generations per key, so only KeyId — always present on the real wire response — is echoed back.

type InMemoryBackend

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

InMemoryBackend is a concurrency-safe in-memory KMS backend.

func NewInMemoryBackend

func NewInMemoryBackend() *InMemoryBackend

NewInMemoryBackend creates and returns a new empty KMS backend with default account/region.

func NewInMemoryBackendWithConfig

func NewInMemoryBackendWithConfig(accountID, region string) *InMemoryBackend

NewInMemoryBackendWithConfig creates a new KMS backend with the given account ID and region.

func (*InMemoryBackend) AddCustomKeyStoreInternal

func (b *InMemoryBackend) AddCustomKeyStoreInternal(ks *CustomKeyStore)

AddCustomKeyStoreInternal inserts a custom key store directly into the backend. This is intended for test seeding only.

func (*InMemoryBackend) AddKeyInternal

func (b *InMemoryBackend) AddKeyInternal(key *Key, km *keyMaterial)

AddKeyInternal inserts a key directly into the backend without going through CreateKey. It also inserts the provided key material if non-nil. This is intended for test seeding only. The region is derived from the key ARN, falling back to defaultRegion.

func (*InMemoryBackend) CancelKeyDeletion

func (b *InMemoryBackend) CancelKeyDeletion(
	ctx context.Context,
	input *CancelKeyDeletionInput,
) (*CancelKeyDeletionOutput, error)

CancelKeyDeletion cancels a pending key deletion and sets the key to Disabled. AWS raises KMSInvalidStateException if the key is not pending deletion (KeyStatePendingDeletion or KeyStatePendingReplicaDeletion).

func (*InMemoryBackend) ConnectCustomKeyStore

func (b *InMemoryBackend) ConnectCustomKeyStore(
	ctx context.Context,
	input *ConnectCustomKeyStoreInput,
) error

ConnectCustomKeyStore transitions a custom key store from DISCONNECTED to CONNECTED.

func (*InMemoryBackend) CreateAlias

func (b *InMemoryBackend) CreateAlias(ctx context.Context, input *CreateAliasInput) error

CreateAlias creates an alias pointing to a key.

func (*InMemoryBackend) CreateCustomKeyStore

func (b *InMemoryBackend) CreateCustomKeyStore(
	ctx context.Context, input *CreateCustomKeyStoreInput,
) (*CreateCustomKeyStoreOutput, error)

CreateCustomKeyStore creates a new in-memory custom key store entry in DISCONNECTED state.

func (*InMemoryBackend) CreateGrant

func (b *InMemoryBackend) CreateGrant(
	ctx context.Context,
	input *CreateGrantInput,
) (*CreateGrantOutput, error)

CreateGrant creates a new grant on the specified key.

func (*InMemoryBackend) CreateKey

func (b *InMemoryBackend) CreateKey(
	ctx context.Context,
	input *CreateKeyInput,
) (*CreateKeyOutput, error)

CreateKey creates a new KMS key and stores it in the backend.

func (*InMemoryBackend) Decrypt

func (b *InMemoryBackend) Decrypt(
	ctx context.Context,
	input *DecryptInput,
) (*DecryptOutput, error)

func (*InMemoryBackend) DeleteAlias

func (b *InMemoryBackend) DeleteAlias(ctx context.Context, input *DeleteAliasInput) error

DeleteAlias removes an alias. Per AWS KMS behaviour, an alias pointing to a key in PendingDeletion state cannot be deleted — the caller must cancel the deletion first.

func (*InMemoryBackend) DeleteCustomKeyStore

func (b *InMemoryBackend) DeleteCustomKeyStore(
	ctx context.Context,
	input *DeleteCustomKeyStoreInput,
) error

DeleteCustomKeyStore removes an existing custom key store. It must be in DISCONNECTED state.

func (*InMemoryBackend) DeleteImportedKeyMaterial

func (b *InMemoryBackend) DeleteImportedKeyMaterial(
	ctx context.Context,
	input *DeleteImportedKeyMaterialInput,
) error

DeleteImportedKeyMaterial removes the imported key material from an EXTERNAL-origin key. The key transitions to PendingImport; it can receive new material via ImportKeyMaterial.

func (*InMemoryBackend) DeriveSharedSecret

func (b *InMemoryBackend) DeriveSharedSecret(
	ctx context.Context, input *DeriveSharedSecretInput,
) (*DeriveSharedSecretOutput, error)

DeriveSharedSecret computes an ECDH shared secret using an ECC KEY_AGREEMENT KMS key and the provided DER-encoded peer public key.

func (*InMemoryBackend) DescribeCustomKeyStores

func (b *InMemoryBackend) DescribeCustomKeyStores(
	ctx context.Context, input *DescribeCustomKeyStoresInput,
) (*DescribeCustomKeyStoresOutput, error)

DescribeCustomKeyStores returns a list of custom key stores matching optional filters.

func (*InMemoryBackend) DescribeKey

func (b *InMemoryBackend) DescribeKey(
	ctx context.Context,
	input *DescribeKeyInput,
) (*DescribeKeyOutput, error)

DescribeKey returns metadata for the specified key.

func (*InMemoryBackend) DisableKey

func (b *InMemoryBackend) DisableKey(ctx context.Context, input *DisableKeyInput) error

DisableKey disables the specified key. AWS raises KMSInvalidStateException for keys pending deletion or import.

func (*InMemoryBackend) DisableKeyRotation

func (b *InMemoryBackend) DisableKeyRotation(
	ctx context.Context,
	input *DisableKeyRotationInput,
) error

DisableKeyRotation disables automatic key rotation for the specified key. Asymmetric keys and EXTERNAL-origin keys do not support rotation and return ErrUnsupportedOrigin.

func (*InMemoryBackend) DisconnectCustomKeyStore

func (b *InMemoryBackend) DisconnectCustomKeyStore(
	ctx context.Context,
	input *DisconnectCustomKeyStoreInput,
) error

DisconnectCustomKeyStore transitions a custom key store from CONNECTED to DISCONNECTED.

func (*InMemoryBackend) EnableKey

func (b *InMemoryBackend) EnableKey(ctx context.Context, input *EnableKeyInput) error

EnableKey enables the specified key. AWS raises KMSInvalidStateException for keys pending deletion or import.

func (*InMemoryBackend) EnableKeyRotation

func (b *InMemoryBackend) EnableKeyRotation(
	ctx context.Context,
	input *EnableKeyRotationInput,
) error

EnableKeyRotation enables automatic key rotation for the specified key. The rotation period defaults to 365 days. Rotation is NOT performed immediately; it is scheduled starting from the key's creation date or last rotation date. The key must be in the Enabled state.

func (*InMemoryBackend) Encrypt

func (b *InMemoryBackend) Encrypt(
	ctx context.Context,
	input *EncryptInput,
) (*EncryptOutput, error)

Encrypt encrypts the given plaintext using the specified key.

func (*InMemoryBackend) GenerateDataKey

func (b *InMemoryBackend) GenerateDataKey(
	ctx context.Context,
	input *GenerateDataKeyInput,
) (*GenerateDataKeyOutput, error)

GenerateDataKey generates a random data key, returning both plaintext and encrypted forms.

func (*InMemoryBackend) GenerateDataKeyPair

func (b *InMemoryBackend) GenerateDataKeyPair(
	ctx context.Context, input *GenerateDataKeyPairInput,
) (*GenerateDataKeyPairOutput, error)

GenerateDataKeyPair generates a new ephemeral asymmetric key pair, returning the public key, plaintext private key (DER-encoded PKCS#8), and the private key encrypted under the specified KMS wrapping key.

func (*InMemoryBackend) GenerateDataKeyPairWithoutPlaintext

GenerateDataKeyPairWithoutPlaintext generates an asymmetric key pair but omits the plaintext private key from the response.

func (*InMemoryBackend) GenerateDataKeyWithoutPlaintext

GenerateDataKeyWithoutPlaintext generates a data key but returns only the encrypted copy.

func (*InMemoryBackend) GenerateMac

func (b *InMemoryBackend) GenerateMac(
	ctx context.Context,
	input *GenerateMacInput,
) (*GenerateMacOutput, error)

GenerateMac computes an HMAC tag over the provided message using an HMAC KMS key.

func (*InMemoryBackend) GenerateRandom

func (b *InMemoryBackend) GenerateRandom(
	_ context.Context,
	input *GenerateRandomInput,
) (*GenerateRandomOutput, error)

GenerateRandom returns the requested number of cryptographically secure random bytes. NumberOfBytes defaults to 32 when not specified; maximum is 1024.

func (*InMemoryBackend) GetKeyLastUsage

func (b *InMemoryBackend) GetKeyLastUsage(
	ctx context.Context,
	input *GetKeyLastUsageInput,
) (*GetKeyLastUsageOutput, error)

GetKeyLastUsage returns the last successful cryptographic operation performed with the specified key.

Unlike almost every other KeyId-accepting KMS operation, the real aws-sdk-go-v2/service/kms@v1.55.4 GetKeyLastUsageInput doc comment is explicit that "Alias names are not supported" here -- a key ID or key ARN only. Rejected before taking any lock, matching validKeyPolicyDoc-style input validation elsewhere in this file.

func (*InMemoryBackend) GetKeyPolicy

func (b *InMemoryBackend) GetKeyPolicy(
	ctx context.Context,
	input *GetKeyPolicyInput,
) (*GetKeyPolicyOutput, error)

GetKeyPolicy retrieves the key policy for a KMS key.

func (*InMemoryBackend) GetKeyRotationStatus

func (b *InMemoryBackend) GetKeyRotationStatus(
	ctx context.Context,
	input *GetKeyRotationStatusInput,
) (*GetKeyRotationStatusOutput, error)

GetKeyRotationStatus returns rotation configuration and schedule for the specified key.

func (*InMemoryBackend) GetParametersForImport

func (b *InMemoryBackend) GetParametersForImport(
	ctx context.Context, input *GetParametersForImportInput,
) (*GetParametersForImportOutput, error)

GetParametersForImport returns wrapping parameters for EXTERNAL-origin key material import. Returns a real RSA public key (DER-encoded SubjectPublicKeyInfo) that callers can use to RSA-OAEP-wrap their key material before calling ImportKeyMaterial.

func (*InMemoryBackend) GetPublicKey

func (b *InMemoryBackend) GetPublicKey(
	ctx context.Context,
	input *GetPublicKeyInput,
) (*GetPublicKeyOutput, error)

GetPublicKey returns the public key for an asymmetric KMS key.

func (*InMemoryBackend) ImportKeyMaterial

func (b *InMemoryBackend) ImportKeyMaterial(
	ctx context.Context,
	input *ImportKeyMaterialInput,
) error

ImportKeyMaterial imports externally supplied key material into a key created with Origin=EXTERNAL. The key must be in PendingImport state. On success the key transitions to Enabled. Only SYMMETRIC_DEFAULT keys are supported; asymmetric EXTERNAL keys are not modeled by this mock.

func (*InMemoryBackend) ListAliases

func (b *InMemoryBackend) ListAliases(
	ctx context.Context,
	input *ListAliasesInput,
) (*ListAliasesOutput, error)

ListAliases returns a paginated list of aliases, optionally filtered by key.

func (*InMemoryBackend) ListGrants

func (b *InMemoryBackend) ListGrants(
	ctx context.Context,
	input *ListGrantsInput,
) (*ListGrantsOutput, error)

ListGrants returns the grants for a specified key with optional pagination and GrantId filter.

func (*InMemoryBackend) ListKeyPolicies

func (b *InMemoryBackend) ListKeyPolicies(
	ctx context.Context,
	input *ListKeyPoliciesInput,
) (*ListKeyPoliciesOutput, error)

ListKeyPolicies returns policy names available for a key.

func (*InMemoryBackend) ListKeyRotations

func (b *InMemoryBackend) ListKeyRotations(
	ctx context.Context,
	input *ListKeyRotationsInput,
) (*ListKeyRotationsOutput, error)

ListKeyRotations returns observed key material rotation timestamps for a key.

func (*InMemoryBackend) ListKeys

func (b *InMemoryBackend) ListKeys(
	ctx context.Context,
	input *ListKeysInput,
) (*ListKeysOutput, error)

ListKeys returns a paginated list of all keys.

func (*InMemoryBackend) ListRetirableGrants

func (b *InMemoryBackend) ListRetirableGrants(
	ctx context.Context,
	input *ListRetirableGrantsInput,
) (*ListGrantsOutput, error)

ListRetirableGrants returns all grants for which the given principal is the retiring principal. ListRetirableGrantsInput's doc requires exactly one of RetiringPrincipal/ RetiringServicePrincipal (kms@v1.55.4 api_op_ListRetirableGrants.go: "You must specify either RetiringPrincipal or RetiringServicePrincipal, but not both.").

func (*InMemoryBackend) PutKeyPolicy

func (b *InMemoryBackend) PutKeyPolicy(ctx context.Context, input *PutKeyPolicyInput) error

PutKeyPolicy stores a key policy for a KMS key. Only the "default" policy name is supported.

func (*InMemoryBackend) ReEncrypt

func (b *InMemoryBackend) ReEncrypt(
	ctx context.Context,
	input *ReEncryptInput,
) (*ReEncryptOutput, error)

ReEncrypt decrypts a ciphertext and re-encrypts it under a different key.

func (*InMemoryBackend) ReplicateKey

func (b *InMemoryBackend) ReplicateKey(
	ctx context.Context,
	input *ReplicateKeyInput,
) (*ReplicateKeyOutput, error)

ReplicateKey creates a multi-region replica for an existing key in the target region.

func (*InMemoryBackend) Reset

func (b *InMemoryBackend) Reset()

Reset clears all in-memory state from the backend. It is used by the POST /_gopherstack/reset endpoint for CI pipelines and rapid local development.

func (*InMemoryBackend) Restore

func (b *InMemoryBackend) Restore(ctx context.Context, data []byte) error

Restore loads backend state from a JSON snapshot. It implements persistence.Persistable. If a key in the snapshot does not have corresponding key material (e.g. from an older snapshot format), a warning is logged. Callers of Encrypt/Sign/etc. will receive ErrKeyMaterialUnavailable.

func (*InMemoryBackend) RetireGrant

func (b *InMemoryBackend) RetireGrant(ctx context.Context, input *RetireGrantInput) error

RetireGrant retires a grant by grant token or grant ID + key ID.

func (*InMemoryBackend) RevokeGrant

func (b *InMemoryBackend) RevokeGrant(ctx context.Context, input *RevokeGrantInput) error

RevokeGrant revokes a grant by ID.

func (*InMemoryBackend) RotateKeyOnDemand

func (b *InMemoryBackend) RotateKeyOnDemand(
	ctx context.Context,
	input *RotateKeyOnDemandInput,
) (*RotateKeyOnDemandOutput, error)

RotateKeyOnDemand rotates key material immediately without changing automatic rotation status.

func (*InMemoryBackend) ScheduleKeyDeletion

func (b *InMemoryBackend) ScheduleKeyDeletion(
	ctx context.Context,
	input *ScheduleKeyDeletionInput,
) (*ScheduleKeyDeletionOutput, error)

ScheduleKeyDeletion schedules a key for deletion. PendingWindowInDays must be in the range [7, 30]; values outside this range are rejected. AWS raises ValidationException for out-of-range values and KMSInvalidStateException for keys already in PendingDeletion.

func (*InMemoryBackend) Sign

func (b *InMemoryBackend) Sign(ctx context.Context, input *SignInput) (*SignOutput, error)

Sign creates a digital signature for the specified message using an asymmetric KMS key.

func (*InMemoryBackend) Snapshot

func (b *InMemoryBackend) Snapshot(ctx context.Context) []byte

Snapshot serialises the backend state to JSON. It implements persistence.Persistable. Key materials that cannot be serialized are omitted from the snapshot with a warning log.

func (*InMemoryBackend) UpdateAlias

func (b *InMemoryBackend) UpdateAlias(ctx context.Context, input *UpdateAliasInput) error

UpdateAlias redirects an existing alias to a different key. The alias must already exist; the target key must exist and not be in PendingDeletion state.

func (*InMemoryBackend) UpdateCustomKeyStore

func (b *InMemoryBackend) UpdateCustomKeyStore(
	ctx context.Context,
	input *UpdateCustomKeyStoreInput,
) error

UpdateCustomKeyStore updates mutable properties for a custom key store.

func (*InMemoryBackend) UpdateKeyDescription

func (b *InMemoryBackend) UpdateKeyDescription(
	ctx context.Context,
	input *UpdateKeyDescriptionInput,
) error

UpdateKeyDescription updates a key's description field.

func (*InMemoryBackend) UpdatePrimaryRegion

func (b *InMemoryBackend) UpdatePrimaryRegion(
	ctx context.Context,
	input *UpdatePrimaryRegionInput,
) error

UpdatePrimaryRegion promotes the replica in PrimaryRegion to be the new primary and demotes the current primary to a replica. Both keys must be Enabled multi-region keys.

func (*InMemoryBackend) Verify

func (b *InMemoryBackend) Verify(ctx context.Context, input *VerifyInput) (*VerifyOutput, error)

Verify verifies a digital signature using an asymmetric KMS key.

func (*InMemoryBackend) VerifyMac

func (b *InMemoryBackend) VerifyMac(
	ctx context.Context,
	input *VerifyMacInput,
) (*VerifyMacOutput, error)

VerifyMac verifies an HMAC tag over the provided message using an HMAC KMS key. Returns an error if the MAC does not match; on success returns the key ARN and algorithm.

type Janitor

type Janitor struct {
	Backend *InMemoryBackend
	// OnKeyPurged, if set, is invoked synchronously at the end of purgeKey after
	// the key's backend-owned state has been removed. It lets a caller (see
	// Handler.WithJanitor) cascade-clean side state that lives outside
	// InMemoryBackend entirely -- specifically Handler.tags, a side map keyed
	// by KeyID that the janitor has no access to itself. Without this hook, a
	// permanently-deleted key's tag collection (and the lockmetrics/Prometheus
	// registration it owns) would never be released, since KMS key IDs are
	// UUIDs that are never reused and Handler.tags has no other cleanup path.
	// Called with the backend write lock held: implementations must not call
	// back into any InMemoryBackend method.
	OnKeyPurged func(region, keyID string)

	// Interval is the time between janitor sweeps.
	Interval time.Duration
	// TaskTimeout bounds each individual janitor task. When non-zero, each task
	// runs with a child context that expires after this duration, preventing a
	// stalled operation from blocking the janitor loop indefinitely.
	TaskTimeout time.Duration
	// contains filtered or unexported fields
}

Janitor is the KMS background worker that permanently deletes keys past their scheduled deletion date and purges the associated key material.

func NewJanitor

func NewJanitor(backend *InMemoryBackend, interval time.Duration) *Janitor

NewJanitor creates a new KMS Janitor for the given backend. A zero interval falls back to defaultKMSJanitorInterval.

func (*Janitor) Run

func (j *Janitor) Run(ctx context.Context)

Run runs the janitor loop until ctx is cancelled.

func (*Janitor) SweepOnce

func (j *Janitor) SweepOnce(ctx context.Context)

SweepOnce executes a single deletion sweep. Exposed for testing.

type Key

type Key struct {
	Origin           string `json:"Origin,omitempty"`
	PrimaryRegion    string `json:"PrimaryRegion,omitempty"`
	Description      string `json:"Description,omitempty"`
	KeyState         string `json:"KeyState"`
	KeyUsage         string `json:"KeyUsage"`
	KeySpec          string `json:"KeySpec,omitempty"`
	KeyID            string `json:"KeyId"`
	Arn              string `json:"Arn"`
	ExpirationModel  string `json:"ExpirationModel,omitempty"`
	CustomKeyStoreID string `json:"CustomKeyStoreId,omitempty"`
	// Rotations stores all rotation events with their types. The separate
	// RotationDates and OnDemandRotationDates slices are kept for JSON
	// backwards-compatibility with existing snapshots.
	Rotations             []RotationRecord `json:"Rotations,omitempty"`
	RotationDates         []float64        `json:"RotationDates,omitempty"`
	OnDemandRotationDates []float64        `json:"OnDemandRotationDates,omitempty"`
	// ReplicaKeyIDs stores the key IDs of replica keys created from this primary.
	ReplicaKeyIDs        []string `json:"ReplicaKeyIds,omitempty"`
	CreationDate         float64  `json:"CreationDate"`
	DeletionDate         float64  `json:"DeletionDate,omitempty"`
	ValidTo              float64  `json:"ValidTo,omitempty"`
	PendingWindowInDays  int      `json:"PendingWindowInDays,omitempty"`
	RotationPeriodInDays int32    `json:"RotationPeriodInDays,omitempty"`
	Enabled              bool     `json:"Enabled"`
	MultiRegion          bool     `json:"MultiRegion,omitempty"`
	RotationEnabled      bool     `json:"RotationEnabled"`
}

Key represents a KMS customer-managed key.

type KeyLastUsageData

type KeyLastUsageData struct {
	CloudTrailEventID string  `json:"CloudTrailEventId,omitempty"`
	KmsRequestID      string  `json:"KmsRequestId,omitempty"`
	Operation         string  `json:"Operation,omitempty"`
	Timestamp         float64 `json:"Timestamp,omitempty"`
}

KeyLastUsageData contains information about the last successful cryptographic operation on a KMS key.

type KeyListEntry

type KeyListEntry struct {
	// KeyId is the UUID of the key.
	KeyID string `json:"KeyId"`
	// KeyArn is the full ARN of the key.
	KeyArn string `json:"KeyArn"`
	// Description is the optional human-readable description of the key.
	Description string `json:"Description,omitempty"`
}

KeyListEntry is a brief key reference used in ListKeys.

type KeyMetadata

type KeyMetadata struct {
	MultiRegionConfiguration    *MultiRegionConfiguration `json:"MultiRegionConfiguration,omitempty"`
	PrimaryRegion               string                    `json:"PrimaryRegion,omitempty"`
	Arn                         string                    `json:"Arn"`
	Description                 string                    `json:"Description,omitempty"`
	KeyState                    string                    `json:"KeyState"`
	KeyUsage                    string                    `json:"KeyUsage"`
	KeyManager                  string                    `json:"KeyManager,omitempty"`
	Origin                      string                    `json:"Origin,omitempty"`
	KeySpec                     string                    `json:"KeySpec,omitempty"`
	KeyID                       string                    `json:"KeyId"`
	AWSAccountID                string                    `json:"AWSAccountId,omitempty"`
	CustomKeyStoreID            string                    `json:"CustomKeyStoreId,omitempty"`
	CustomerMasterKeySpec       string                    `json:"CustomerMasterKeySpec,omitempty"`
	MultiRegionKeyType          string                    `json:"MultiRegionKeyType,omitempty"`
	ExpirationModel             string                    `json:"ExpirationModel,omitempty"`
	MacAlgorithms               []string                  `json:"MacAlgorithms,omitempty"`
	SigningAlgorithms           []string                  `json:"SigningAlgorithms,omitempty"`
	KeyAgreementAlgorithms      []string                  `json:"KeyAgreementAlgorithms,omitempty"`
	EncryptionAlgorithms        []string                  `json:"EncryptionAlgorithms,omitempty"`
	CreationDate                float64                   `json:"CreationDate"`
	DeletionDate                float64                   `json:"DeletionDate,omitempty"`
	ValidTo                     float64                   `json:"ValidTo,omitempty"`
	PendingDeletionWindowInDays int                       `json:"PendingDeletionWindowInDays,omitempty"`
	MultiRegion                 bool                      `json:"MultiRegion"`
	Enabled                     bool                      `json:"Enabled"`
}

KeyMetadata is the metadata for a KMS key returned in API responses.

type KeyRotationEntry

type KeyRotationEntry struct {
	KeyID        string  `json:"KeyId,omitempty"`
	RotationType string  `json:"RotationType,omitempty"`
	RotationDate float64 `json:"RotationDate"`
}

KeyRotationEntry describes one key rotation event.

type ListAliasesInput

type ListAliasesInput struct {
	// KeyId optionally filters aliases to those pointing to this key.
	KeyID string `json:"KeyId,omitempty"`
	// Limit caps the number of results returned.
	Limit *int32 `json:"Limit,omitempty"`
	// Marker is the pagination cursor from a previous call.
	Marker string `json:"Marker,omitempty"`
}

ListAliasesInput is the request payload for ListAliases.

type ListAliasesOutput

type ListAliasesOutput struct {
	NextMarker string  `json:"NextMarker,omitempty"`
	Aliases    []Alias `json:"Aliases"`
	Truncated  bool    `json:"Truncated"`
}

ListAliasesOutput is the response payload for ListAliases.

type ListGrantsInput

type ListGrantsInput struct {
	Limit   *int32 `json:"Limit,omitempty"`
	KeyID   string `json:"KeyId"`
	GrantID string `json:"GrantId,omitempty"`
	Marker  string `json:"Marker,omitempty"`
}

ListGrantsInput is the request payload for ListGrants.

type ListGrantsOutput

type ListGrantsOutput struct {
	NextMarker string           `json:"NextMarker,omitempty"`
	Grants     []GrantListEntry `json:"Grants"`
	Truncated  bool             `json:"Truncated"`
}

ListGrantsOutput is the response payload for ListGrants.

type ListKeyPoliciesInput

type ListKeyPoliciesInput struct {
	Limit  *int32 `json:"Limit,omitempty"`
	KeyID  string `json:"KeyId"`
	Marker string `json:"Marker,omitempty"`
}

ListKeyPoliciesInput is the request payload for ListKeyPolicies.

type ListKeyPoliciesOutput

type ListKeyPoliciesOutput struct {
	NextMarker  string   `json:"NextMarker,omitempty"`
	PolicyNames []string `json:"PolicyNames"`
	Truncated   bool     `json:"Truncated"`
}

ListKeyPoliciesOutput is the response payload for ListKeyPolicies.

type ListKeyRotationsInput

type ListKeyRotationsInput struct {
	Limit  *int32 `json:"Limit,omitempty"`
	KeyID  string `json:"KeyId"`
	Marker string `json:"Marker,omitempty"`
}

ListKeyRotationsInput is the request payload for ListKeyRotations.

type ListKeyRotationsOutput

type ListKeyRotationsOutput struct {
	NextMarker string             `json:"NextMarker,omitempty"`
	Rotations  []KeyRotationEntry `json:"Rotations"`
	Truncated  bool               `json:"Truncated"`
}

ListKeyRotationsOutput is the response payload for ListKeyRotations.

type ListKeysInput

type ListKeysInput struct {
	// Limit caps the number of results returned.
	Limit *int32 `json:"Limit,omitempty"`
	// Marker is the pagination cursor from a previous call.
	Marker string `json:"Marker,omitempty"`
}

ListKeysInput is the request payload for ListKeys.

type ListKeysOutput

type ListKeysOutput struct {
	NextMarker string         `json:"NextMarker,omitempty"`
	Keys       []KeyListEntry `json:"Keys"`
	Truncated  bool           `json:"Truncated"`
}

ListKeysOutput is the response payload for ListKeys.

type ListRetirableGrantsInput

type ListRetirableGrantsInput struct {
	Limit                    *int32 `json:"Limit,omitempty"`
	RetiringPrincipal        string `json:"RetiringPrincipal,omitempty"`
	RetiringServicePrincipal string `json:"RetiringServicePrincipal,omitempty"`
	Marker                   string `json:"Marker,omitempty"`
}

ListRetirableGrantsInput is the request payload for ListRetirableGrants. Real AWS requires exactly one of RetiringPrincipal/RetiringServicePrincipal (aws-sdk-go-v2/service/kms@v1.55.4 api_op_ListRetirableGrants.go).

type MultiRegionConfiguration

type MultiRegionConfiguration struct {
	// MultiRegionKeyType is either PRIMARY or REPLICA.
	MultiRegionKeyType string `json:"MultiRegionKeyType,omitempty"`
	// PrimaryKey references the primary key in the multi-region set.
	PrimaryKey *MultiRegionKeyRef `json:"PrimaryKey,omitempty"`
	// ReplicaKeys lists the replica keys associated with the primary.
	ReplicaKeys []MultiRegionKeyRef `json:"ReplicaKeys,omitempty"`
}

MultiRegionConfiguration describes the multi-region key topology.

type MultiRegionKeyRef

type MultiRegionKeyRef struct {
	// Arn is the ARN of the multi-region key.
	Arn string `json:"Arn"`
	// Region is the AWS region of the multi-region key.
	Region string `json:"Region"`
}

MultiRegionKeyRef is a reference to a primary or replica key in a multi-region set.

type Provider

type Provider struct{}

Provider implements service.Provider for the KMS service.

func (*Provider) Init

Init initializes the KMS service backend and handler.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the logical name of the provider.

type PutKeyPolicyInput

type PutKeyPolicyInput struct {
	KeyID      string `json:"KeyId"`
	PolicyName string `json:"PolicyName"`
	Policy     string `json:"Policy"`
	// BypassPolicyLockoutSafetyCheck is accepted as a no-op -- same precedent
	// as CreateKeyInput/ReplicateKeyInput's field of the same name (models.go),
	// no IAM layer exists in this mock to enforce the lockout check it waives.
	BypassPolicyLockoutSafetyCheck bool `json:"BypassPolicyLockoutSafetyCheck,omitempty"`
}

PutKeyPolicyInput is the request payload for PutKeyPolicy.

type ReEncryptInput

type ReEncryptInput struct {
	SourceEncryptionContext        map[string]string `json:"SourceEncryptionContext,omitempty"`
	DestinationEncryptionContext   map[string]string `json:"DestinationEncryptionContext,omitempty"`
	DestinationKeyID               string            `json:"DestinationKeyId"`
	SourceKeyID                    string            `json:"SourceKeyId,omitempty"`
	CiphertextBlob                 []byte            `json:"CiphertextBlob"`
	SourceEncryptionAlgorithm      string            `json:"SourceEncryptionAlgorithm,omitempty"`
	DestinationEncryptionAlgorithm string            `json:"DestinationEncryptionAlgorithm,omitempty"`
	DryRun                         bool              `json:"DryRun,omitempty"`
}

ReEncryptInput is the request payload for ReEncrypt.

type ReEncryptOutput

type ReEncryptOutput struct {
	KeyID                          string `json:"KeyId"`
	SourceKeyID                    string `json:"SourceKeyId"`
	SourceEncryptionAlgorithm      string `json:"SourceEncryptionAlgorithm,omitempty"`
	DestinationEncryptionAlgorithm string `json:"DestinationEncryptionAlgorithm,omitempty"`
	CiphertextBlob                 []byte `json:"CiphertextBlob"`
}

ReEncryptOutput is the response payload for ReEncrypt.

type ReplicateKeyInput

type ReplicateKeyInput struct {
	KeyID         string `json:"KeyId"`
	ReplicaRegion string `json:"ReplicaRegion"`
	Description   string `json:"Description,omitempty"`
	// Policy is the key policy to attach to the replica. If omitted, KMS
	// attaches the default key policy (matches CreateKey's Policy field).
	// The key policy is NOT a shared property of multi-region keys: the
	// replica gets its own independent policy rather than inheriting the
	// primary's.
	Policy string `json:"Policy,omitempty"`
	// Tags are optional tags to apply to the replica key.
	Tags                           []Tag `json:"Tags,omitempty"`
	BypassPolicyLockoutSafetyCheck bool  `json:"BypassPolicyLockoutSafetyCheck,omitempty"`
}

ReplicateKeyInput is the request payload for ReplicateKey.

type ReplicateKeyOutput

type ReplicateKeyOutput struct {
	ReplicaKeyMetadata KeyMetadata `json:"ReplicaKeyMetadata"`
	ReplicaPolicy      string      `json:"ReplicaPolicy,omitempty"`
	ReplicaTags        []Tag       `json:"ReplicaTags,omitempty"`
}

ReplicateKeyOutput is the response payload for ReplicateKey.

type RetireGrantInput

type RetireGrantInput struct {
	GrantToken string `json:"GrantToken,omitempty"`
	GrantID    string `json:"GrantId,omitempty"`
	KeyID      string `json:"KeyId,omitempty"`
	DryRun     bool   `json:"DryRun,omitempty"`
}

RetireGrantInput is the request payload for RetireGrant.

type RevokeGrantInput

type RevokeGrantInput struct {
	KeyID   string `json:"KeyId"`
	GrantID string `json:"GrantId"`
	DryRun  bool   `json:"DryRun,omitempty"`
}

RevokeGrantInput is the request payload for RevokeGrant.

type RotateKeyOnDemandInput

type RotateKeyOnDemandInput struct {
	KeyID string `json:"KeyId"`
}

RotateKeyOnDemandInput is the request payload for RotateKeyOnDemand.

type RotateKeyOnDemandOutput

type RotateKeyOnDemandOutput struct {
	KeyID string `json:"KeyId"`
}

RotateKeyOnDemandOutput is the response payload for RotateKeyOnDemand.

type RotationRecord

type RotationRecord struct {
	RotationType string  `json:"RotationType"`
	Date         float64 `json:"Date"`
}

RotationRecord records a single key material rotation with its type.

type ScheduleKeyDeletionInput

type ScheduleKeyDeletionInput struct {
	KeyID               string `json:"KeyId"`
	PendingWindowInDays int    `json:"PendingWindowInDays,omitempty"`
}

ScheduleKeyDeletionInput is the request payload for ScheduleKeyDeletion.

type ScheduleKeyDeletionOutput

type ScheduleKeyDeletionOutput struct {
	KeyID    string `json:"KeyId"`
	KeyState string `json:"KeyState"`
	// DeletionDate is absent for a multi-Region primary key with replicas:
	// real AWS doesn't know the deletion date until the last replica is
	// deleted, so the key is in KeyStatePendingReplicaDeletion instead.
	DeletionDate        float64 `json:"DeletionDate,omitempty"`
	PendingWindowInDays int     `json:"PendingWindowInDays,omitempty"`
}

ScheduleKeyDeletionOutput is the response payload for ScheduleKeyDeletion.

type Settings

type Settings struct {
	JanitorInterval time.Duration `json:"janitor_interval" env:"KMS_JANITOR_INTERVAL" default:"1m" help:"Janitor tick interval."` //nolint:lll // Kong struct tag makes this line long
}

Settings holds service-level configuration for the KMS backend. Fields are picked up by the Kong CLI parser when this struct is embedded in the root CLI command.

type SignInput

type SignInput struct {
	KeyID            string   `json:"KeyId"`
	MessageType      string   `json:"MessageType,omitempty"`
	SigningAlgorithm string   `json:"SigningAlgorithm"`
	Message          []byte   `json:"Message"`
	GrantTokens      []string `json:"GrantTokens,omitempty"`
	DryRun           bool     `json:"DryRun,omitempty"`
}

SignInput is the request payload for Sign.

type SignOutput

type SignOutput struct {
	KeyID            string `json:"KeyId"`
	SigningAlgorithm string `json:"SigningAlgorithm"`
	Signature        []byte `json:"Signature"`
}

SignOutput is the response payload for Sign.

type StorageBackend

type StorageBackend interface {
	CreateKey(ctx context.Context, input *CreateKeyInput) (*CreateKeyOutput, error)
	DescribeKey(ctx context.Context, input *DescribeKeyInput) (*DescribeKeyOutput, error)
	ListKeys(ctx context.Context, input *ListKeysInput) (*ListKeysOutput, error)
	Encrypt(ctx context.Context, input *EncryptInput) (*EncryptOutput, error)
	Decrypt(ctx context.Context, input *DecryptInput) (*DecryptOutput, error)
	GenerateDataKey(
		ctx context.Context,
		input *GenerateDataKeyInput,
	) (*GenerateDataKeyOutput, error)
	GenerateDataKeyWithoutPlaintext(
		ctx context.Context, input *GenerateDataKeyWithoutPlaintextInput,
	) (*GenerateDataKeyWithoutPlaintextOutput, error)
	ReEncrypt(ctx context.Context, input *ReEncryptInput) (*ReEncryptOutput, error)
	Sign(ctx context.Context, input *SignInput) (*SignOutput, error)
	Verify(ctx context.Context, input *VerifyInput) (*VerifyOutput, error)
	GetPublicKey(ctx context.Context, input *GetPublicKeyInput) (*GetPublicKeyOutput, error)
	CreateAlias(ctx context.Context, input *CreateAliasInput) error
	UpdateAlias(ctx context.Context, input *UpdateAliasInput) error
	DeleteAlias(ctx context.Context, input *DeleteAliasInput) error
	ListAliases(ctx context.Context, input *ListAliasesInput) (*ListAliasesOutput, error)
	EnableKeyRotation(ctx context.Context, input *EnableKeyRotationInput) error
	DisableKeyRotation(ctx context.Context, input *DisableKeyRotationInput) error
	GetKeyRotationStatus(
		ctx context.Context,
		input *GetKeyRotationStatusInput,
	) (*GetKeyRotationStatusOutput, error)
	DisableKey(ctx context.Context, input *DisableKeyInput) error
	EnableKey(ctx context.Context, input *EnableKeyInput) error
	ScheduleKeyDeletion(
		ctx context.Context,
		input *ScheduleKeyDeletionInput,
	) (*ScheduleKeyDeletionOutput, error)
	CancelKeyDeletion(
		ctx context.Context,
		input *CancelKeyDeletionInput,
	) (*CancelKeyDeletionOutput, error)
	CreateGrant(ctx context.Context, input *CreateGrantInput) (*CreateGrantOutput, error)
	ListGrants(ctx context.Context, input *ListGrantsInput) (*ListGrantsOutput, error)
	RevokeGrant(ctx context.Context, input *RevokeGrantInput) error
	RetireGrant(ctx context.Context, input *RetireGrantInput) error
	ListRetirableGrants(
		ctx context.Context,
		input *ListRetirableGrantsInput,
	) (*ListGrantsOutput, error)
	PutKeyPolicy(ctx context.Context, input *PutKeyPolicyInput) error
	GetKeyPolicy(ctx context.Context, input *GetKeyPolicyInput) (*GetKeyPolicyOutput, error)
	GetParametersForImport(
		ctx context.Context,
		input *GetParametersForImportInput,
	) (*GetParametersForImportOutput, error)
	ListKeyPolicies(
		ctx context.Context,
		input *ListKeyPoliciesInput,
	) (*ListKeyPoliciesOutput, error)
	ListKeyRotations(
		ctx context.Context,
		input *ListKeyRotationsInput,
	) (*ListKeyRotationsOutput, error)
	ImportKeyMaterial(ctx context.Context, input *ImportKeyMaterialInput) error
	DeleteImportedKeyMaterial(ctx context.Context, input *DeleteImportedKeyMaterialInput) error
	ReplicateKey(ctx context.Context, input *ReplicateKeyInput) (*ReplicateKeyOutput, error)
	RotateKeyOnDemand(
		ctx context.Context,
		input *RotateKeyOnDemandInput,
	) (*RotateKeyOnDemandOutput, error)
	ConnectCustomKeyStore(ctx context.Context, input *ConnectCustomKeyStoreInput) error
	CreateCustomKeyStore(
		ctx context.Context,
		input *CreateCustomKeyStoreInput,
	) (*CreateCustomKeyStoreOutput, error)
	DeleteCustomKeyStore(ctx context.Context, input *DeleteCustomKeyStoreInput) error
	DeriveSharedSecret(
		ctx context.Context,
		input *DeriveSharedSecretInput,
	) (*DeriveSharedSecretOutput, error)
	DescribeCustomKeyStores(
		ctx context.Context,
		input *DescribeCustomKeyStoresInput,
	) (*DescribeCustomKeyStoresOutput, error)
	DisconnectCustomKeyStore(ctx context.Context, input *DisconnectCustomKeyStoreInput) error
	UpdateCustomKeyStore(ctx context.Context, input *UpdateCustomKeyStoreInput) error
	UpdateKeyDescription(ctx context.Context, input *UpdateKeyDescriptionInput) error
	UpdatePrimaryRegion(ctx context.Context, input *UpdatePrimaryRegionInput) error
	GenerateDataKeyPair(
		ctx context.Context,
		input *GenerateDataKeyPairInput,
	) (*GenerateDataKeyPairOutput, error)
	GenerateDataKeyPairWithoutPlaintext(
		ctx context.Context, input *GenerateDataKeyPairWithoutPlaintextInput,
	) (*GenerateDataKeyPairWithoutPlaintextOutput, error)
	GenerateMac(ctx context.Context, input *GenerateMacInput) (*GenerateMacOutput, error)
	GenerateRandom(ctx context.Context, input *GenerateRandomInput) (*GenerateRandomOutput, error)
	VerifyMac(ctx context.Context, input *VerifyMacInput) (*VerifyMacOutput, error)
	GetKeyLastUsage(
		ctx context.Context,
		input *GetKeyLastUsageInput,
	) (*GetKeyLastUsageOutput, error)
}

StorageBackend defines the interface for the KMS in-memory backend.

type Tag

type Tag struct {
	// TagKey is the tag key.
	TagKey string `json:"TagKey"`
	// TagValue is the tag value.
	TagValue string `json:"TagValue"`
}

Tag is a key-value pair attached to a KMS resource.

type TaggedKeyInfo

type TaggedKeyInfo struct {
	Tags map[string]string
	ARN  string
}

TaggedKeyInfo contains a KMS key's ARN and tag snapshot. Used by the Resource Groups Tagging API cross-service listing.

type UpdateAliasInput

type UpdateAliasInput struct {
	// AliasName is the existing alias to redirect.
	AliasName string `json:"AliasName"`
	// TargetKeyId is the new key ID the alias should point to.
	TargetKeyID string `json:"TargetKeyId"`
}

UpdateAliasInput is the request payload for UpdateAlias.

type UpdateCustomKeyStoreInput

type UpdateCustomKeyStoreInput struct {
	CustomKeyStoreID      string `json:"CustomKeyStoreId"`
	NewCustomKeyStoreName string `json:"NewCustomKeyStoreName,omitempty"`
}

UpdateCustomKeyStoreInput is the request payload for UpdateCustomKeyStore.

type UpdateKeyDescriptionInput

type UpdateKeyDescriptionInput struct {
	KeyID       string `json:"KeyId"`
	Description string `json:"Description"`
}

UpdateKeyDescriptionInput is the request payload for UpdateKeyDescription.

type UpdatePrimaryRegionInput

type UpdatePrimaryRegionInput struct {
	KeyID         string `json:"KeyId"`
	PrimaryRegion string `json:"PrimaryRegion"`
}

UpdatePrimaryRegionInput is the request payload for UpdatePrimaryRegion.

type VerifyInput

type VerifyInput struct {
	KeyID            string   `json:"KeyId"`
	MessageType      string   `json:"MessageType,omitempty"`
	SigningAlgorithm string   `json:"SigningAlgorithm"`
	Message          []byte   `json:"Message"`
	Signature        []byte   `json:"Signature"`
	GrantTokens      []string `json:"GrantTokens,omitempty"`
	DryRun           bool     `json:"DryRun,omitempty"`
}

VerifyInput is the request payload for Verify.

type VerifyMacInput

type VerifyMacInput struct {
	// KeyId is the HMAC KMS key used to verify the MAC.
	KeyID string `json:"KeyId"`
	// MacAlgorithm specifies the MAC algorithm (e.g. HMAC_SHA_256).
	MacAlgorithm string `json:"MacAlgorithm"`
	// Message is the data over which to verify the MAC.
	Message []byte `json:"Message"`
	// Mac is the MAC tag to verify.
	Mac []byte `json:"Mac"`
	// GrantTokens is an optional list of grant tokens used to authorize the operation.
	GrantTokens []string `json:"GrantTokens,omitempty"`
	DryRun      bool     `json:"DryRun,omitempty"`
}

VerifyMacInput is the request payload for VerifyMac.

type VerifyMacOutput

type VerifyMacOutput struct {
	KeyID        string `json:"KeyId"`
	MacAlgorithm string `json:"MacAlgorithm"`
	MacValid     bool   `json:"MacValid"`
}

VerifyMacOutput is the response payload for VerifyMac.

type VerifyOutput

type VerifyOutput struct {
	KeyID            string `json:"KeyId"`
	SigningAlgorithm string `json:"SigningAlgorithm"`
	SignatureValid   bool   `json:"SignatureValid"`
}

VerifyOutput is the response payload for Verify.

Jump to

Keyboard shortcuts

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