Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: completed external kms and improved the testcase for kms

=ad67e8ade89b
diff --git a/backend-go/go.mod b/backend-go/go.mod
index 6a65ed84cb..560cb75168 100644
--- a/backend-go/go.mod
+++ b/backend-go/go.mod
@@ -3,7 +3,13 @@ module github.com/infisical/api
go 1.26.1
require (
+ cloud.google.com/go/kms v1.31.0
github.com/ThalesGroup/crypto11 v1.6.0
+ github.com/aws/aws-sdk-go-v2 v1.41.7
+ github.com/aws/aws-sdk-go-v2/config v1.32.18
+ github.com/aws/aws-sdk-go-v2/credentials v1.19.17
+ github.com/aws/aws-sdk-go-v2/service/kms v1.52.0
+ github.com/aws/aws-sdk-go-v2/service/sts v1.42.1
github.com/bmatcuk/doublestar/v4 v4.10.0
github.com/doordash-oss/oapi-codegen-dd/v3 v3.75.5
github.com/go-chi/chi/v5 v5.2.4
@@ -18,13 +24,30 @@ require (
github.com/redis/go-redis/v9 v9.18.0
github.com/stretchr/testify v1.11.1
github.com/testcontainers/testcontainers-go v0.41.0
- golang.org/x/crypto v0.49.0
+ golang.org/x/crypto v0.51.0
+ google.golang.org/api v0.281.0
)
require (
+ cloud.google.com/go v0.123.0 // indirect
+ cloud.google.com/go/auth v0.20.0 // indirect
+ cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect
+ cloud.google.com/go/compute/metadata v0.9.0 // indirect
+ cloud.google.com/go/iam v1.7.0 // indirect
+ cloud.google.com/go/longrunning v0.9.0 // indirect
dario.cat/mergo v1.0.2 // indirect
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
+ github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 // indirect
+ github.com/aws/aws-sdk-go-v2/service/signin v1.0.11 // indirect
+ github.com/aws/aws-sdk-go-v2/service/sso v1.30.17 // indirect
+ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.0 // indirect
+ github.com/aws/smithy-go v1.25.1 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
@@ -50,6 +73,9 @@ require (
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
+ github.com/google/s2a-go v0.1.9 // indirect
+ github.com/googleapis/enterprise-certificate-proxy v0.3.16 // indirect
+ github.com/googleapis/gax-go/v2 v2.22.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
github.com/iancoleman/strcase v0.3.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
@@ -85,23 +111,27 @@ require (
github.com/tklauser/numcpus v0.11.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
- go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 // indirect
- go.opentelemetry.io/otel v1.41.0 // indirect
+ go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 // indirect
+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect
+ go.opentelemetry.io/otel v1.43.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 // indirect
- go.opentelemetry.io/otel/metric v1.41.0 // indirect
- go.opentelemetry.io/otel/sdk/metric v1.41.0 // indirect
- go.opentelemetry.io/otel/trace v1.41.0 // indirect
+ go.opentelemetry.io/otel/metric v1.43.0 // indirect
+ go.opentelemetry.io/otel/trace v1.43.0 // indirect
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.yaml.in/yaml/v4 v4.0.0-rc.4 // indirect
- golang.org/x/mod v0.33.0 // indirect
- golang.org/x/net v0.52.0 // indirect
+ golang.org/x/mod v0.35.0 // indirect
+ golang.org/x/net v0.55.0 // indirect
+ golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sync v0.20.0 // indirect
- golang.org/x/sys v0.42.0 // indirect
- golang.org/x/text v0.35.0 // indirect
- golang.org/x/time v0.14.0 // indirect
- golang.org/x/tools v0.42.0 // indirect
- google.golang.org/grpc v1.79.1 // indirect
+ golang.org/x/sys v0.45.0 // indirect
+ golang.org/x/text v0.37.0 // indirect
+ golang.org/x/time v0.15.0 // indirect
+ golang.org/x/tools v0.44.0 // indirect
+ google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect
+ google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260523011958-0a33c5d7ca68 // indirect
+ google.golang.org/grpc v1.81.1 // indirect
google.golang.org/protobuf v1.36.11 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
diff --git a/backend-go/go.sum b/backend-go/go.sum
index e2cb3743a7..b521d51713 100644
--- a/backend-go/go.sum
+++ b/backend-go/go.sum
@@ -1,3 +1,17 @@
+cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE=
+cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU=
+cloud.google.com/go/auth v0.20.0 h1:kXTssoVb4azsVDoUiF8KvxAqrsQcQtB53DcSgta74CA=
+cloud.google.com/go/auth v0.20.0/go.mod h1:942/yi/itH1SsmpyrbnTMDgGfdy2BUqIKyd0cyYLc5Q=
+cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
+cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
+cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
+cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
+cloud.google.com/go/iam v1.7.0 h1:JD3zh0C6LHl16aCn5Akff0+GELdp1+4hmh6ndoFLl8U=
+cloud.google.com/go/iam v1.7.0/go.mod h1:tetWZW1PD/m6vcuY2Zj/aU0eCHNPuxedbnbRTyKXvdY=
+cloud.google.com/go/kms v1.31.0 h1:LS8N92OxFDgOLg5NCo3OmbvjtQAIVT5gUHVLKIDHaFE=
+cloud.google.com/go/kms v1.31.0/go.mod h1:YIyXZym11R5uovJJt4oN5eUL3oPmirF3yKeIh6QAf4U=
+cloud.google.com/go/longrunning v0.9.0 h1:0EzbDEGsAvOZNbqXopgniY0w0a1phvu5IdUFq8grmqY=
+cloud.google.com/go/longrunning v0.9.0/go.mod h1:pkTz846W7bF4o2SzdWJ40Hu0Re+UoNT6Q5t+igIcb8E=
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
@@ -8,6 +22,36 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/ThalesGroup/crypto11 v1.6.0 h1:Og9EMn44fBS4GNnGnH1aqHnF2wL6F7IU/RhpJajWX/4=
github.com/ThalesGroup/crypto11 v1.6.0/go.mod h1:H6LRjN5R5SHxTrLqGNteisLDI0/IC6+SGx1pHtbwizE=
+github.com/aws/aws-sdk-go-v2 v1.41.7 h1:DWpAJt66FmnnaRIOT/8ASTucrvuDPZASqhhLey6tLY8=
+github.com/aws/aws-sdk-go-v2 v1.41.7/go.mod h1:4LAfZOPHNVNQEckOACQx60Y8pSRjIkNZQz1w92xpMJc=
+github.com/aws/aws-sdk-go-v2/config v1.32.18 h1:Hcia46bxhGgF3BaSnG8nSNCWmqTK6bj9xN9/FJ3WK6Q=
+github.com/aws/aws-sdk-go-v2/config v1.32.18/go.mod h1:zEjCAYmxqDadH1WX8CdBvmLKhUEUVFgKRQG38zjDmrY=
+github.com/aws/aws-sdk-go-v2/credentials v1.19.17 h1:gP2nkGsS+KMvF/jfFz2Vv2qiiOqWKyPACSzPsqHgoW8=
+github.com/aws/aws-sdk-go-v2/credentials v1.19.17/go.mod h1:Bsew3S/moG5iT77giPj1q8wb/s0RE5/QfH+ASjYtuQc=
+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23 h1:UuSfcORqNSz/ey3VPRS8TcVH2Ikf0/sC+Hdj400QI6U=
+github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23/go.mod h1:+G/OSGiOFnSOkYloKj/9M35s74LgVAdJBSD5lsFfqKg=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 h1:GpT/TrnBYuE5gan2cZbTtvP+JlHsutdmlV2YfEyNde0=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23/go.mod h1:xYWD6BS9ywC5bS3sz9Xh04whO/hzK2plt2Zkyrp4JuA=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 h1:bpd8vxhlQi2r1hiueOw02f/duEPTMK59Q4QMAoTTtTo=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23/go.mod h1:15DfR2nw+CRHIk0tqNyifu3G1YdAOy68RftkhMDDwYk=
+github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 h1:OQqn11BtaYv1WLUowvcA30MpzIu8Ti4pcLPIIyoKZrA=
+github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24/go.mod h1:X5ZJyfwVrWA96GzPmUCWFQaEARPR7gCrpq2E92PJwAE=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 h1:FLudkZLt5ci0ozzgkVo8BJGwvqNaZbTWb3UcucAateA=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9/go.mod h1:w7wZ/s9qK7c8g4al+UyoF1Sp/Z45UwMGcqIzLWVQHWk=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 h1:pbrxO/kuIwgEsOPLkaHu0O+m4fNgLU8B3vxQ+72jTPw=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23/go.mod h1:/CMNUqoj46HpS3MNRDEDIwcgEnrtZlKRaHNaHxIFpNA=
+github.com/aws/aws-sdk-go-v2/service/kms v1.52.0 h1:QNtg+Mtj1zmepk568+UKBD5DFfqh+ESTUUqQT27JkQc=
+github.com/aws/aws-sdk-go-v2/service/kms v1.52.0/go.mod h1:Y0+uxvxz6ib4KktRdK0V4X45Vcs/JyYoz8H71pO8xeI=
+github.com/aws/aws-sdk-go-v2/service/signin v1.0.11 h1:TdJ+HdzOBhU8+iVAOGUTU63VXopcumCOF1paFulHWZc=
+github.com/aws/aws-sdk-go-v2/service/signin v1.0.11/go.mod h1:R82ZRExE/nheo0N+T8zHPcLRTcH8MGsnR3BiVGX0TwI=
+github.com/aws/aws-sdk-go-v2/service/sso v1.30.17 h1:7byT8HUWrgoRp6sXjxtZwgOKfhss5fW6SkLBtqzgRoE=
+github.com/aws/aws-sdk-go-v2/service/sso v1.30.17/go.mod h1:xNWknVi4Ezm1vg1QsB/5EWpAJURq22uqd38U8qKvOJc=
+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.0 h1:nDARhv/oF55bcxF7rCI/4PDxOKnVXVWwDuDwCs2I2SQ=
+github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.0/go.mod h1:4vIRDq+CJB2xFAXZ+YgGUTiEft7oAQlhIs71xcSeuVg=
+github.com/aws/aws-sdk-go-v2/service/sts v1.42.1 h1:F/M5Y9I3nwr2IEpshZgh1GeHpOItExNM9L1euNuh/fk=
+github.com/aws/aws-sdk-go-v2/service/sts v1.42.1/go.mod h1:mTNxImtovCOEEuD65mKW7DCsL+2gjEH+RPEAexAzAio=
+github.com/aws/smithy-go v1.25.1 h1:J8ERsGSU7d+aCmdQur5Txg6bVoYelvQJgtZehD12GkI=
+github.com/aws/smithy-go v1.25.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/bmatcuk/doublestar/v4 v4.10.0 h1:zU9WiOla1YA122oLM6i4EXvGW62DvKZVxIe6TYWexEs=
@@ -24,6 +68,8 @@ github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1x
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik=
+github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
@@ -53,6 +99,11 @@ github.com/doordash-oss/oapi-codegen-dd/v3 v3.75.5 h1:0aocYIVXTZltwnXgTAc0EiYpoa
github.com/doordash-oss/oapi-codegen-dd/v3 v3.75.5/go.mod h1:B/2dCvBVmDo+pdBf+wfc583utG8j07DvR+5IxnKMJuw=
github.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=
github.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
+github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA=
+github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ=
+github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A=
+github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds=
+github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
@@ -80,11 +131,19 @@ github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAy
github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
+github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/googleapis/enterprise-certificate-proxy v0.3.16 h1:F/VPrx0YPBdksZJQdCAp0WUsqnNmZpUZszzfYt0M5Dw=
+github.com/googleapis/enterprise-certificate-proxy v0.3.16/go.mod h1:9Yb0eAkH/Xqhvv3zbeKf/+wMJqCeocWc6KIhDvEAuYE=
+github.com/googleapis/gax-go/v2 v2.22.0 h1:PjIWBpgGIVKGoCXuiCoP64altEJCj3/Ei+kSU5vlZD4=
+github.com/googleapis/gax-go/v2 v2.22.0/go.mod h1:irWBbALSr0Sk3qlqb9SyJ1h68WjgeFuiOzI4Rqw5+aY=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
github.com/hibiken/asynq v0.26.0 h1:1Zxr92MlDnb1Zt/QR5g2vSCqUS03i95lUfqx5X7/wrw=
@@ -147,6 +206,8 @@ github.com/pb33f/ordered-map/v2 v2.3.0 h1:k2OhVEQkhTCQMhAicQ3Z6iInzoZNQ7L9MVomwK
github.com/pb33f/ordered-map/v2 v2.3.0/go.mod h1:oe5ue+6ZNhy7QN9cPZvPA23Hx0vMHnNVeMg4fGdCANw=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
+github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=
+github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
@@ -185,22 +246,24 @@ github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
-go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18=
-go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg=
-go.opentelemetry.io/otel v1.41.0 h1:YlEwVsGAlCvczDILpUXpIpPSL/VPugt7zHThEMLce1c=
-go.opentelemetry.io/otel v1.41.0/go.mod h1:Yt4UwgEKeT05QbLwbyHXEwhnjxNO6D8L5PQP51/46dE=
+go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=
+go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=
+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=
+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=
+go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
+go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 h1:ao6Oe+wSebTlQ1OEht7jlYTzQKE+pnx/iNywFvTbuuI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0/go.mod h1:u3T6vz0gh/NVzgDgiwkgLxpsSF6PaPmo2il0apGJbls=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 h1:inYW9ZhgqiDqh6BioM7DVHHzEGVq76Db5897WLGZ5Go=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0/go.mod h1:Izur+Wt8gClgMJqO/cZ8wdeeMryJ/xxiOVgFSSfpDTY=
-go.opentelemetry.io/otel/metric v1.41.0 h1:rFnDcs4gRzBcsO9tS8LCpgR0dxg4aaxWlJxCno7JlTQ=
-go.opentelemetry.io/otel/metric v1.41.0/go.mod h1:xPvCwd9pU0VN8tPZYzDZV/BMj9CM9vs00GuBjeKhJps=
-go.opentelemetry.io/otel/sdk v1.41.0 h1:YPIEXKmiAwkGl3Gu1huk1aYWwtpRLeskpV+wPisxBp8=
-go.opentelemetry.io/otel/sdk v1.41.0/go.mod h1:ahFdU0G5y8IxglBf0QBJXgSe7agzjE4GiTJ6HT9ud90=
-go.opentelemetry.io/otel/sdk/metric v1.41.0 h1:siZQIYBAUd1rlIWQT2uCxWJxcCO7q3TriaMlf08rXw8=
-go.opentelemetry.io/otel/sdk/metric v1.41.0/go.mod h1:HNBuSvT7ROaGtGI50ArdRLUnvRTRGniSUZbxiWxSO8Y=
-go.opentelemetry.io/otel/trace v1.41.0 h1:Vbk2co6bhj8L59ZJ6/xFTskY+tGAbOnCtQGVVa9TIN0=
-go.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis=
+go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
+go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
+go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
+go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
+go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
+go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
+go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
+go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
@@ -209,35 +272,43 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v4 v4.0.0-rc.4 h1:UP4+v6fFrBIb1l934bDl//mmnoIZEDK0idg1+AIvX5U=
go.yaml.in/yaml/v4 v4.0.0-rc.4/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
-golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
-golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
-golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
-golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
-golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
-golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
+golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
+golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
+golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
+golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
+golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
+golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
+golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
+golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
-golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
-golang.org/x/term v0.41.0 h1:QCgPso/Q3RTJx2Th4bDLqML4W6iJiaXFq2/ftQF13YU=
-golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
-golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
-golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
-golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
-golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
-golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
-golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
+golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
+golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
+golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
+golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
+golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
+golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
+golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
-google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 h1:JLQynH/LBHfCTSbDWl+py8C+Rg/k1OVH3xfcaiANuF0=
-google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:kSJwQxqmFXeo79zOmbrALdflXQeAYcUbgS7PbpMknCY=
-google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 h1:mWPCjDEyshlQYzBpMNHaEof6UX1PmHcaUODUywQ0uac=
-google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
-google.golang.org/grpc v1.79.1 h1:zGhSi45ODB9/p3VAawt9a+O/MULLl9dpizzNNpq7flY=
-google.golang.org/grpc v1.79.1/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
+google.golang.org/api v0.281.0 h1:sohYgszGGg3zC0P6ncdV6J9IOBtN9LVfFKz8C9tTtJU=
+google.golang.org/api v0.281.0/go.mod h1:6Wssta4c5n9qHq5CBhmlai5h/PUa1djdDAIhYEHyvcM=
+google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0=
+google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I=
+google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 h1:VPWxll4HlMw1Vs/qXtN7BvhZqsS9cdAittCNvVENElA=
+google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:7QBABkRtR8z+TEnmXTqIqwJLlzrZKVfAUm7tY3yGv0M=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260523011958-0a33c5d7ca68 h1:PvEgGJf9C/1u5CHkInMg7UFYYUoiaQmW2LbtH0pjB78=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260523011958-0a33c5d7ca68/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
+google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ=
+google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
diff --git a/backend-go/internal/ee/services/externalkms/externalkms.go b/backend-go/internal/ee/services/externalkms/externalkms.go
new file mode 100644
index 0000000000..4788866bf7
--- /dev/null
+++ b/backend-go/internal/ee/services/externalkms/externalkms.go
@@ -0,0 +1,82 @@
+package externalkms
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+)
+
+// Provider identifies the external KMS provider type.
+const (
+ ProviderAWS = "aws"
+ ProviderGCP = "gcp"
+)
+
+// Service provides encryption/decryption via external KMS providers (AWS, GCP).
+// It implements the ExternalKmsProvider interface expected by the core KMS service.
+type Service struct {
+ logger *slog.Logger
+}
+
+// Deps holds dependencies for the external KMS service.
+type Deps struct{}
+
+// NewService creates a new external KMS service.
+func NewService(_ context.Context, logger *slog.Logger, _ *Deps) (*Service, error) {
+ return &Service{
+ logger: logger.With(slog.String("service", "externalkms")),
+ }, nil
+}
+
+// Encrypt encrypts plaintext using the specified external KMS provider.
+// The config parameter contains the decrypted provider configuration JSON.
+func (s *Service) Encrypt(ctx context.Context, provider string, config, plaintext []byte) ([]byte, error) {
+ p, err := s.createProvider(ctx, provider, config)
+ if err != nil {
+ return nil, err
+ }
+ defer p.Close() //nolint:errcheck // best-effort cleanup
+
+ return p.Encrypt(ctx, plaintext)
+}
+
+// Decrypt decrypts ciphertext using the specified external KMS provider.
+// The config parameter contains the decrypted provider configuration JSON.
+func (s *Service) Decrypt(ctx context.Context, provider string, config, ciphertext []byte) ([]byte, error) {
+ p, err := s.createProvider(ctx, provider, config)
+ if err != nil {
+ return nil, err
+ }
+ defer p.Close() //nolint:errcheck // best-effort cleanup
+
+ return p.Decrypt(ctx, ciphertext)
+}
+
+// provider is the internal interface for KMS provider implementations.
+type provider interface {
+ Encrypt(ctx context.Context, plaintext []byte) ([]byte, error)
+ Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error)
+ Close() error
+}
+
+func (s *Service) createProvider(ctx context.Context, providerType string, config []byte) (provider, error) {
+ switch providerType {
+ case ProviderAWS:
+ var cfg AwsConfig
+ if err := json.Unmarshal(config, &cfg); err != nil {
+ return nil, fmt.Errorf("parsing AWS KMS config: %w", err)
+ }
+ return newAwsProvider(ctx, &cfg)
+
+ case ProviderGCP:
+ var cfg GcpConfig
+ if err := json.Unmarshal(config, &cfg); err != nil {
+ return nil, fmt.Errorf("parsing GCP KMS config: %w", err)
+ }
+ return newGcpProvider(ctx, &cfg)
+
+ default:
+ return nil, fmt.Errorf("unsupported external KMS provider: %s", providerType)
+ }
+}
diff --git a/backend-go/internal/ee/services/externalkms/externalkms_integration_test.go b/backend-go/internal/ee/services/externalkms/externalkms_integration_test.go
new file mode 100644
index 0000000000..52e9e594a7
--- /dev/null
+++ b/backend-go/internal/ee/services/externalkms/externalkms_integration_test.go
@@ -0,0 +1,323 @@
+//go:build integration
+
+package externalkms_test
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/infisical/api/internal/ee/services/externalkms"
+ "github.com/infisical/api/internal/testutil"
+ "github.com/infisical/api/internal/testutil/infra"
+)
+
+// Secret keys in Infisical /platform folder.
+const (
+ // GCP
+ SecretGCPCredentialJSON = "EXTERNAL_KMS_GCP_CREDENTIAL_JSON"
+ SecretGCPKeyName = "EXTERNAL_KMS_GCP_KEY_NAME"
+
+ // AWS Access Key auth
+ SecretAWSAccessKey = "EXTERNAL_KMS_AWS_ACCESS_KEY"
+ SecretAWSSecretKey = "EXTERNAL_KMS_AWS_SECRET_KEY"
+ SecretAWSRegion = "EXTERNAL_KMS_AWS_REGION"
+ SecretAWSKeyID = "EXTERNAL_KMS_AWS_KEY_ID"
+
+ // AWS Assume Role auth
+ SecretAWSAssumeRoleARN = "EXTERNAL_KMS_AWS_ASSUME_ROLE_ARN"
+ SecretAWSAssumeRoleExternalID = "EXTERNAL_KMS_AWS_ASSUME_ROLE_EXTERNAL_ID"
+)
+
+func newService(t *testing.T) *externalkms.Service {
+ t.Helper()
+ svc, err := externalkms.NewService(context.Background(), testutil.NopLogger(), &externalkms.Deps{})
+ require.NoError(t, err)
+ return svc
+}
+
+// ==========================================================================
+// GCP KMS
+// ==========================================================================
+
+func TestGCPProvider_EncryptDecrypt_RoundTrip(t *testing.T) {
+ secrets := infra.GetPlatformSecrets(t)
+ credJSON := secrets.Require(t, SecretGCPCredentialJSON)
+ keyName := secrets.Require(t, SecretGCPKeyName)
+
+ svc := newService(t)
+ ctx := context.Background()
+
+ config := mustMarshalGCPConfig(t, credJSON, keyName)
+ plaintext := []byte("gcp-kms-test-payload")
+
+ ciphertext, err := svc.Encrypt(ctx, externalkms.ProviderGCP, config, plaintext)
+ require.NoError(t, err)
+ require.NotEmpty(t, ciphertext)
+ require.NotEqual(t, plaintext, ciphertext, "ciphertext must differ from plaintext")
+
+ decrypted, err := svc.Decrypt(ctx, externalkms.ProviderGCP, config, ciphertext)
+ require.NoError(t, err)
+ require.Equal(t, plaintext, decrypted)
+}
+
+func TestGCPProvider_EncryptIsNonDeterministic(t *testing.T) {
+ secrets := infra.GetPlatformSecrets(t)
+ credJSON := secrets.Require(t, SecretGCPCredentialJSON)
+ keyName := secrets.Require(t, SecretGCPKeyName)
+
+ svc := newService(t)
+ ctx := context.Background()
+
+ config := mustMarshalGCPConfig(t, credJSON, keyName)
+ plaintext := []byte("same-input-different-output")
+
+ ct1, err := svc.Encrypt(ctx, externalkms.ProviderGCP, config, plaintext)
+ require.NoError(t, err)
+
+ ct2, err := svc.Encrypt(ctx, externalkms.ProviderGCP, config, plaintext)
+ require.NoError(t, err)
+
+ require.NotEqual(t, ct1, ct2, "KMS encryption must use random IV, producing different ciphertext each time")
+}
+
+func TestGCPProvider_DecryptInvalidCiphertext(t *testing.T) {
+ secrets := infra.GetPlatformSecrets(t)
+ credJSON := secrets.Require(t, SecretGCPCredentialJSON)
+ keyName := secrets.Require(t, SecretGCPKeyName)
+
+ svc := newService(t)
+ ctx := context.Background()
+
+ config := mustMarshalGCPConfig(t, credJSON, keyName)
+ garbage := []byte("this-is-not-valid-ciphertext")
+
+ _, err := svc.Decrypt(ctx, externalkms.ProviderGCP, config, garbage)
+ require.Error(t, err, "decrypt must fail on invalid ciphertext")
+}
+
+func mustMarshalGCPConfig(t *testing.T, credJSON, keyName string) []byte {
+ t.Helper()
+
+ var cred externalkms.GcpCredential
+ err := json.Unmarshal([]byte(credJSON), &cred)
+ require.NoError(t, err, "GCP credential JSON must be valid")
+
+ config := externalkms.GcpConfig{
+ Credential: cred,
+ KeyName: keyName,
+ }
+
+ data, err := json.Marshal(config)
+ require.NoError(t, err)
+ return data
+}
+
+// ==========================================================================
+// AWS KMS - Access Key Auth
+// ==========================================================================
+
+func TestAWSProvider_AccessKey_EncryptDecrypt_RoundTrip(t *testing.T) {
+ secrets := infra.GetPlatformSecrets(t)
+ accessKey := secrets.Require(t, SecretAWSAccessKey)
+ secretKey := secrets.Require(t, SecretAWSSecretKey)
+ region := secrets.Require(t, SecretAWSRegion)
+ keyID := secrets.Require(t, SecretAWSKeyID)
+
+ svc := newService(t)
+ ctx := context.Background()
+
+ config := mustMarshalAWSAccessKeyConfig(t, accessKey, secretKey, region, keyID)
+ plaintext := []byte("aws-kms-accesskey-test-payload")
+
+ ciphertext, err := svc.Encrypt(ctx, externalkms.ProviderAWS, config, plaintext)
+ require.NoError(t, err)
+ require.NotEmpty(t, ciphertext)
+ require.NotEqual(t, plaintext, ciphertext, "ciphertext must differ from plaintext")
+
+ decrypted, err := svc.Decrypt(ctx, externalkms.ProviderAWS, config, ciphertext)
+ require.NoError(t, err)
+ require.Equal(t, plaintext, decrypted)
+}
+
+func TestAWSProvider_AccessKey_EncryptIsNonDeterministic(t *testing.T) {
+ secrets := infra.GetPlatformSecrets(t)
+ accessKey := secrets.Require(t, SecretAWSAccessKey)
+ secretKey := secrets.Require(t, SecretAWSSecretKey)
+ region := secrets.Require(t, SecretAWSRegion)
+ keyID := secrets.Require(t, SecretAWSKeyID)
+
+ svc := newService(t)
+ ctx := context.Background()
+
+ config := mustMarshalAWSAccessKeyConfig(t, accessKey, secretKey, region, keyID)
+ plaintext := []byte("same-input-different-output")
+
+ ct1, err := svc.Encrypt(ctx, externalkms.ProviderAWS, config, plaintext)
+ require.NoError(t, err)
+
+ ct2, err := svc.Encrypt(ctx, externalkms.ProviderAWS, config, plaintext)
+ require.NoError(t, err)
+
+ require.NotEqual(t, ct1, ct2, "KMS encryption must use random IV, producing different ciphertext each time")
+}
+
+func TestAWSProvider_AccessKey_DecryptInvalidCiphertext(t *testing.T) {
+ secrets := infra.GetPlatformSecrets(t)
+ accessKey := secrets.Require(t, SecretAWSAccessKey)
+ secretKey := secrets.Require(t, SecretAWSSecretKey)
+ region := secrets.Require(t, SecretAWSRegion)
+ keyID := secrets.Require(t, SecretAWSKeyID)
+
+ svc := newService(t)
+ ctx := context.Background()
+
+ config := mustMarshalAWSAccessKeyConfig(t, accessKey, secretKey, region, keyID)
+ garbage := []byte("this-is-not-valid-ciphertext")
+
+ _, err := svc.Decrypt(ctx, externalkms.ProviderAWS, config, garbage)
+ require.Error(t, err, "decrypt must fail on invalid ciphertext")
+}
+
+func mustMarshalAWSAccessKeyConfig(t *testing.T, accessKey, secretKey, region, keyID string) []byte {
+ t.Helper()
+
+ config := externalkms.AwsConfig{
+ Credential: externalkms.AwsCredential{
+ Type: externalkms.AwsCredentialTypeAccessKey,
+ Data: externalkms.AwsCredentialData{
+ AccessKey: accessKey,
+ SecretKey: secretKey,
+ },
+ },
+ AwsRegion: region,
+ KmsKeyID: keyID,
+ }
+
+ data, err := json.Marshal(config)
+ require.NoError(t, err)
+ return data
+}
+
+// ==========================================================================
+// AWS KMS - Assume Role Auth
+// ==========================================================================
+
+func TestAWSProvider_AssumeRole_EncryptDecrypt_RoundTrip(t *testing.T) {
+ secrets := infra.GetPlatformSecrets(t)
+ accessKey := secrets.Require(t, SecretAWSAccessKey)
+ secretKey := secrets.Require(t, SecretAWSSecretKey)
+ roleARN := secrets.Require(t, SecretAWSAssumeRoleARN)
+ region := secrets.Require(t, SecretAWSRegion)
+ keyID := secrets.Require(t, SecretAWSKeyID)
+ externalID := secrets.Get(SecretAWSAssumeRoleExternalID) // optional
+
+ // Set base credentials for STS AssumeRole
+ t.Setenv("AWS_ACCESS_KEY_ID", accessKey)
+ t.Setenv("AWS_SECRET_ACCESS_KEY", secretKey)
+
+ svc := newService(t)
+ ctx := context.Background()
+
+ config := mustMarshalAWSAssumeRoleConfig(t, roleARN, externalID, region, keyID)
+ plaintext := []byte("aws-kms-assumerole-test-payload")
+
+ ciphertext, err := svc.Encrypt(ctx, externalkms.ProviderAWS, config, plaintext)
+ require.NoError(t, err)
+ require.NotEmpty(t, ciphertext)
+ require.NotEqual(t, plaintext, ciphertext, "ciphertext must differ from plaintext")
+
+ decrypted, err := svc.Decrypt(ctx, externalkms.ProviderAWS, config, ciphertext)
+ require.NoError(t, err)
+ require.Equal(t, plaintext, decrypted)
+}
+
+func mustMarshalAWSAssumeRoleConfig(t *testing.T, roleARN, externalID, region, keyID string) []byte {
+ t.Helper()
+
+ config := externalkms.AwsConfig{
+ Credential: externalkms.AwsCredential{
+ Type: externalkms.AwsCredentialTypeAssumeRole,
+ Data: externalkms.AwsCredentialData{
+ AssumeRoleArn: roleARN,
+ ExternalID: externalID,
+ },
+ },
+ AwsRegion: region,
+ KmsKeyID: keyID,
+ }
+
+ data, err := json.Marshal(config)
+ require.NoError(t, err)
+ return data
+}
+
+// ==========================================================================
+// Cross-provider isolation
+// ==========================================================================
+
+func TestCrossProvider_CiphertextNotInterchangeable(t *testing.T) {
+ secrets := infra.GetPlatformSecrets(t)
+
+ // Skip if either provider's secrets are missing
+ gcpCredJSON := secrets.Require(t, SecretGCPCredentialJSON)
+ gcpKeyName := secrets.Require(t, SecretGCPKeyName)
+ awsAccessKey := secrets.Require(t, SecretAWSAccessKey)
+ awsSecretKey := secrets.Require(t, SecretAWSSecretKey)
+ awsRegion := secrets.Require(t, SecretAWSRegion)
+ awsKeyID := secrets.Require(t, SecretAWSKeyID)
+
+ svc := newService(t)
+ ctx := context.Background()
+
+ gcpConfig := mustMarshalGCPConfig(t, gcpCredJSON, gcpKeyName)
+ awsConfig := mustMarshalAWSAccessKeyConfig(t, awsAccessKey, awsSecretKey, awsRegion, awsKeyID)
+
+ plaintext := []byte("cross-provider-test")
+
+ // Encrypt with GCP
+ gcpCiphertext, err := svc.Encrypt(ctx, externalkms.ProviderGCP, gcpConfig, plaintext)
+ require.NoError(t, err)
+
+ // Attempt to decrypt GCP ciphertext with AWS — must fail
+ _, err = svc.Decrypt(ctx, externalkms.ProviderAWS, awsConfig, gcpCiphertext)
+ require.Error(t, err, "GCP ciphertext must not be decryptable by AWS KMS")
+
+ // Encrypt with AWS
+ awsCiphertext, err := svc.Encrypt(ctx, externalkms.ProviderAWS, awsConfig, plaintext)
+ require.NoError(t, err)
+
+ // Attempt to decrypt AWS ciphertext with GCP — must fail
+ _, err = svc.Decrypt(ctx, externalkms.ProviderGCP, gcpConfig, awsCiphertext)
+ require.Error(t, err, "AWS ciphertext must not be decryptable by GCP KMS")
+}
+
+// ==========================================================================
+// Error cases
+// ==========================================================================
+
+func TestService_UnsupportedProvider(t *testing.T) {
+ svc := newService(t)
+ ctx := context.Background()
+
+ _, err := svc.Encrypt(ctx, "unsupported-provider", []byte("{}"), []byte("test"))
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "unsupported")
+}
+
+func TestService_InvalidConfigJSON(t *testing.T) {
+ svc := newService(t)
+ ctx := context.Background()
+
+ invalidJSON := []byte("not-valid-json")
+
+ _, err := svc.Encrypt(ctx, externalkms.ProviderAWS, invalidJSON, []byte("test"))
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "parsing")
+
+ _, err = svc.Encrypt(ctx, externalkms.ProviderGCP, invalidJSON, []byte("test"))
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "parsing")
+}
diff --git a/backend-go/internal/ee/services/externalkms/externalkms_mock.go b/backend-go/internal/ee/services/externalkms/externalkms_mock.go
new file mode 100644
index 0000000000..c83018d77f
--- /dev/null
+++ b/backend-go/internal/ee/services/externalkms/externalkms_mock.go
@@ -0,0 +1,78 @@
+//go:build integration
+
+package externalkms
+
+import (
+ "context"
+ "fmt"
+)
+
+// MockProvider implements a simple mock external KMS for testing.
+// Uses XOR cipher so encrypt/decrypt are reversible and verifiable.
+type MockProvider struct {
+ EncryptCalls int
+ DecryptCalls int
+ LastProvider string
+ LastConfig []byte
+ ShouldFail bool
+ FailMessage string
+}
+
+// NewMockProvider creates a new mock external KMS provider.
+func NewMockProvider() *MockProvider {
+ return &MockProvider{}
+}
+
+// Encrypt implements the service interface using XOR "encryption".
+func (m *MockProvider) Encrypt(_ context.Context, provider string, config, plaintext []byte) ([]byte, error) {
+ m.EncryptCalls++
+ m.LastProvider = provider
+ m.LastConfig = config
+
+ if m.ShouldFail {
+ msg := m.FailMessage
+ if msg == "" {
+ msg = "mock external KMS encrypt failed"
+ }
+ return nil, fmt.Errorf("%s", msg)
+ }
+
+ // XOR with 0x42 - simple reversible transformation for testing
+ result := make([]byte, len(plaintext))
+ for i, b := range plaintext {
+ result[i] = b ^ 0x42
+ }
+ return result, nil
+}
+
+// Decrypt implements the service interface using XOR "decryption".
+func (m *MockProvider) Decrypt(_ context.Context, provider string, config, ciphertext []byte) ([]byte, error) {
+ m.DecryptCalls++
+ m.LastProvider = provider
+ m.LastConfig = config
+
+ if m.ShouldFail {
+ msg := m.FailMessage
+ if msg == "" {
+ msg = "mock external KMS decrypt failed"
+ }
+ return nil, fmt.Errorf("%s", msg)
+ }
+
+ // XOR with 0x42 - reverses the "encryption"
+ result := make([]byte, len(ciphertext))
+ for i, b := range ciphertext {
+ result[i] = b ^ 0x42
+ }
+ return result, nil
+}
+
+// Reset clears call counts and captured data.
+func (m *MockProvider) Reset() {
+ m.EncryptCalls = 0
+ m.DecryptCalls = 0
+ m.LastProvider = ""
+ m.LastConfig = nil
+ m.ShouldFail = false
+ m.FailMessage = ""
+}
diff --git a/backend-go/internal/ee/services/externalkms/provider_aws.go b/backend-go/internal/ee/services/externalkms/provider_aws.go
new file mode 100644
index 0000000000..e6d8345d4f
--- /dev/null
+++ b/backend-go/internal/ee/services/externalkms/provider_aws.go
@@ -0,0 +1,131 @@
+package externalkms
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/credentials/stscreds"
+ "github.com/aws/aws-sdk-go-v2/service/kms"
+ "github.com/aws/aws-sdk-go-v2/service/sts"
+)
+
+// AWS credential types matching Node.js constants.
+const (
+ AwsCredentialTypeAccessKey = "access-key"
+ AwsCredentialTypeAssumeRole = "assume-role"
+)
+
+// AwsConfig holds the configuration for AWS KMS provider.
+// Matches the Node.js ExternalKmsAwsSchema structure.
+type AwsConfig struct {
+ Credential AwsCredential
+ AwsRegion string
+ KmsKeyID string
+}
+
+// AwsCredential represents AWS authentication credentials.
+type AwsCredential struct {
+ Type string
+ Data AwsCredentialData
+}
+
+// AwsCredentialData holds the actual credential values.
+type AwsCredentialData struct {
+ // For access-key type
+ AccessKey string
+ SecretKey string
+
+ // For assume-role type
+ AssumeRoleArn string
+ ExternalID string
+}
+
+// awsProvider implements the provider interface for AWS KMS.
+type awsProvider struct {
+ client *kms.Client
+ kmsKeyID string
+}
+
+func newAwsProvider(ctx context.Context, cfg *AwsConfig) (*awsProvider, error) {
+ awsCfg, err := buildAwsConfig(ctx, cfg)
+ if err != nil {
+ return nil, fmt.Errorf("building AWS config: %w", err)
+ }
+
+ client := kms.NewFromConfig(awsCfg)
+
+ return &awsProvider{
+ client: client,
+ kmsKeyID: cfg.KmsKeyID,
+ }, nil
+}
+
+// TODO(go): Add FIPS endpoint support via config.WithUseFIPSEndpoint when FIPS mode is enabled.
+func buildAwsConfig(ctx context.Context, cfg *AwsConfig) (aws.Config, error) {
+ switch cfg.Credential.Type {
+ case AwsCredentialTypeAccessKey:
+ return config.LoadDefaultConfig(ctx,
+ config.WithRegion(cfg.AwsRegion),
+ config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
+ cfg.Credential.Data.AccessKey,
+ cfg.Credential.Data.SecretKey,
+ "",
+ )),
+ )
+
+ case AwsCredentialTypeAssumeRole:
+ baseCfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(cfg.AwsRegion))
+ if err != nil {
+ return aws.Config{}, fmt.Errorf("loading base AWS config: %w", err)
+ }
+
+ stsClient := sts.NewFromConfig(baseCfg)
+ assumeRoleProvider := stscreds.NewAssumeRoleProvider(stsClient, cfg.Credential.Data.AssumeRoleArn,
+ func(o *stscreds.AssumeRoleOptions) {
+ if cfg.Credential.Data.ExternalID != "" {
+ o.ExternalID = aws.String(cfg.Credential.Data.ExternalID)
+ }
+ },
+ )
+
+ return config.LoadDefaultConfig(ctx,
+ config.WithRegion(cfg.AwsRegion),
+ config.WithCredentialsProvider(aws.NewCredentialsCache(assumeRoleProvider)),
+ )
+
+ default:
+ return aws.Config{}, fmt.Errorf("unsupported AWS credential type: %s", cfg.Credential.Type)
+ }
+}
+
+func (p *awsProvider) Encrypt(ctx context.Context, plaintext []byte) ([]byte, error) {
+ output, err := p.client.Encrypt(ctx, &kms.EncryptInput{
+ KeyId: aws.String(p.kmsKeyID),
+ Plaintext: plaintext,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("AWS KMS encrypt: %w", err)
+ }
+
+ return output.CiphertextBlob, nil
+}
+
+func (p *awsProvider) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) {
+ output, err := p.client.Decrypt(ctx, &kms.DecryptInput{
+ KeyId: aws.String(p.kmsKeyID),
+ CiphertextBlob: ciphertext,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("AWS KMS decrypt: %w", err)
+ }
+
+ return output.Plaintext, nil
+}
+
+func (p *awsProvider) Close() error {
+ // AWS SDK v2 clients don't require explicit cleanup
+ return nil
+}
diff --git a/backend-go/internal/ee/services/externalkms/provider_gcp.go b/backend-go/internal/ee/services/externalkms/provider_gcp.go
new file mode 100644
index 0000000000..f836a42f34
--- /dev/null
+++ b/backend-go/internal/ee/services/externalkms/provider_gcp.go
@@ -0,0 +1,86 @@
+package externalkms
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ kms "cloud.google.com/go/kms/apiv1"
+ "cloud.google.com/go/kms/apiv1/kmspb"
+ "google.golang.org/api/option"
+)
+
+// GcpConfig holds the configuration for GCP KMS provider.
+// Matches the Node.js ExternalKmsGcpSchema structure.
+type GcpConfig struct {
+ Credential GcpCredential
+ GcpRegion string
+ KeyName string
+}
+
+// GcpCredential represents a GCP service account credential.
+// This is the standard service account JSON structure.
+type GcpCredential struct {
+ Type string `json:"type"`
+ ProjectID string `json:"project_id"`
+ PrivateKeyID string `json:"private_key_id"`
+ PrivateKey string `json:"private_key"`
+ ClientEmail string `json:"client_email"`
+ ClientID string `json:"client_id"`
+ AuthURI string `json:"auth_uri"`
+ TokenURI string `json:"token_uri"`
+ AuthProviderX509CertURL string `json:"auth_provider_x509_cert_url"`
+ ClientX509CertURL string `json:"client_x509_cert_url"`
+ UniverseDomain string `json:"universe_domain"`
+}
+
+// gcpProvider implements the provider interface for GCP KMS.
+type gcpProvider struct {
+ client *kms.KeyManagementClient
+ keyName string
+}
+
+func newGcpProvider(ctx context.Context, cfg *GcpConfig) (*gcpProvider, error) {
+ credentialJSON, err := json.Marshal(cfg.Credential)
+ if err != nil {
+ return nil, fmt.Errorf("marshaling GCP credential: %w", err)
+ }
+
+ client, err := kms.NewKeyManagementClient(ctx, option.WithAuthCredentialsJSON(option.ServiceAccount, credentialJSON))
+ if err != nil {
+ return nil, fmt.Errorf("creating GCP KMS client: %w", err)
+ }
+
+ return &gcpProvider{
+ client: client,
+ keyName: cfg.KeyName,
+ }, nil
+}
+
+func (p *gcpProvider) Encrypt(ctx context.Context, plaintext []byte) ([]byte, error) {
+ resp, err := p.client.Encrypt(ctx, &kmspb.EncryptRequest{
+ Name: p.keyName,
+ Plaintext: plaintext,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("GCP KMS encrypt: %w", err)
+ }
+
+ return resp.Ciphertext, nil
+}
+
+func (p *gcpProvider) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) {
+ resp, err := p.client.Decrypt(ctx, &kmspb.DecryptRequest{
+ Name: p.keyName,
+ Ciphertext: ciphertext,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("GCP KMS decrypt: %w", err)
+ }
+
+ return resp.Plaintext, nil
+}
+
+func (p *gcpProvider) Close() error {
+ return p.client.Close()
+}
diff --git a/backend-go/internal/server/api/platform_services.go b/backend-go/internal/server/api/platform_services.go
index e2a60247a9..b59f9df475 100644
--- a/backend-go/internal/server/api/platform_services.go
+++ b/backend-go/internal/server/api/platform_services.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
+ "github.com/infisical/api/internal/ee/services/externalkms"
"github.com/infisical/api/internal/services/assumeprivilege"
"github.com/infisical/api/internal/services/auditlog"
"github.com/infisical/api/internal/services/auth/apiauth"
@@ -25,10 +26,16 @@ type PlatformServices struct {
}
func newPlatformServices(ctx context.Context, infra *Infra) (*PlatformServices, error) {
+ externalKmsSvc, err := externalkms.NewService(ctx, infra.Logger, &externalkms.Deps{})
+ if err != nil {
+ return nil, fmt.Errorf("external kms: %w", err)
+ }
+
kmsSvc, err := kms.NewService(ctx, infra.Logger, &kms.Deps{
- DB: infra.DB,
- HSM: infra.HSM,
- Config: infra.Config,
+ DB: infra.DB,
+ HSM: infra.HSM,
+ ExternalKms: externalKmsSvc,
+ Config: infra.Config,
})
if err != nil {
return nil, fmt.Errorf("kms: %w", err)
diff --git a/backend-go/internal/server/api/secretmanager/secret/main_test.go b/backend-go/internal/server/api/secretmanager/secret/main_test.go
index 2ecd6994f2..67bd27be65 100644
--- a/backend-go/internal/server/api/secretmanager/secret/main_test.go
+++ b/backend-go/internal/server/api/secretmanager/secret/main_test.go
@@ -64,9 +64,10 @@ func newSecretsHandler(t *testing.T) *secret.Handler {
t.Cleanup(func() { redisClient.Close() })
kmsSvc, err := kms.NewService(ctx, testutil.NopLogger(), &kms.Deps{
- DB: stack.DB(),
- HSM: nil,
- Config: stack.Config(),
+ DB: stack.DB(),
+ HSM: nil,
+ ExternalKms: nil,
+ Config: stack.Config(),
})
require.NoError(t, err)
diff --git a/backend-go/internal/services/kms/kms.go b/backend-go/internal/services/kms/kms.go
index 45dcb3408c..79149852ae 100644
--- a/backend-go/internal/services/kms/kms.go
+++ b/backend-go/internal/services/kms/kms.go
@@ -15,7 +15,6 @@ import (
"github.com/infisical/api/internal/config"
"github.com/infisical/api/internal/database/pg"
- "github.com/infisical/api/internal/database/pg/pglock"
"github.com/infisical/api/internal/libs/crypto/cipher"
"github.com/infisical/api/internal/libs/errutil"
)
@@ -45,14 +44,6 @@ const (
StrategySoftware RootKeyEncryptionStrategy = "SOFTWARE"
)
-// DataKeyType selects between org-level and project-level data keys.
-type DataKeyType int
-
-const (
- DataKeyOrganization DataKeyType = iota
- DataKeyProject
-)
-
// Encryptor encrypts plaintext and returns the ciphertext blob (with version suffix).
type Encryptor func(plainText []byte) ([]byte, error)
@@ -75,13 +66,6 @@ func (c *CipherPair) Decrypt(ciphertext []byte) ([]byte, error) {
return c.decrypt(ciphertext)
}
-// CreateCipherPairDTO selects which data key to use.
-type CreateCipherPairDTO struct {
- Type DataKeyType
- ProjectID string // required when Type == DataKeyProject
- OrgID uuid.UUID // required when Type == DataKeyOrganization
-}
-
// HsmService defines the HSM operations needed by the KMS service.
// Pass nil when HSM is not configured.
type HsmService interface {
@@ -91,6 +75,13 @@ type HsmService interface {
RandomBytes(n int) ([]byte, error)
}
+// ExternalKmsService defines external KMS operations (AWS, GCP).
+// Pass nil when external KMS is not configured.
+type ExternalKmsService interface {
+ Encrypt(ctx context.Context, provider string, config, plaintext []byte) ([]byte, error)
+ Decrypt(ctx context.Context, provider string, config, ciphertext []byte) ([]byte, error)
+}
+
// Service manages the KMS key hierarchy:
//
// ROOT_ENCRYPTION_KEY (in memory)
@@ -102,9 +93,10 @@ type Service struct {
rootEncryptionKey []byte // loaded during Start(), protected by mu
logger *slog.Logger
- encryptionKey []byte // decoded during Start(), used to decrypt root key
- db pg.DB // database operations
- hsm HsmService // nil when HSM is not configured
+ encryptionKey []byte // decoded during Start(), used to decrypt root key
+ db pg.DB // database operations
+ hsm HsmService // nil when HSM is not configured
+ externalKms ExternalKmsService // nil when external KMS is not configured
// Raw config values - decoded during Start() based on FIPS mode
rawEncryptionKey string
@@ -114,9 +106,10 @@ type Service struct {
// Deps holds the dependencies for the KMS shared service.
type Deps struct {
- DB pg.DB
- HSM HsmService // nil when HSM is not configured
- Config *config.Config
+ DB pg.DB
+ HSM HsmService // nil when HSM is not configured
+ ExternalKms ExternalKmsService // nil when external KMS is not configured
+ Config *config.Config
}
// NewService creates a new KMS service.
@@ -126,6 +119,7 @@ func NewService(_ context.Context, logger *slog.Logger, deps *Deps) (*Service, e
logger: logger.With(slog.String("service", "kms")),
db: deps.DB,
hsm: deps.HSM,
+ externalKms: deps.ExternalKms,
rawEncryptionKey: deps.Config.EncryptionKey,
rawRootEncryptionKey: deps.Config.RootEncryptionKey,
fipsEnabledEnv: deps.Config.FipsEnabled,
@@ -133,7 +127,7 @@ func NewService(_ context.Context, logger *slog.Logger, deps *Deps) (*Service, e
}
// Start bootstraps the KMS root key. It must be called once during server startup
-// before any calls to CreateCipherPairWithDataKey.
+// before any calls to CreateCipherPairWithOrgDataKey or CreateCipherPairWithProjectDataKey.
//
// It atomically finds or creates the root config in the database (using a PG advisory lock),
// then decrypts the root key into memory.
@@ -149,30 +143,7 @@ func (s *Service) Start(ctx context.Context, hsmConfigured bool) error {
return fmt.Errorf("KMS: resolving encryption key: %w", err)
}
- rootConfig, err := s.findOrCreateRootConfig(ctx, func() (encryptedRootKey []byte, encryptionStrategy string, err error) {
- var newRootKey []byte
- if hsmConfigured && s.hsm != nil {
- var genErr error
- newRootKey, genErr = s.hsm.RandomBytes(32)
- if genErr != nil {
- return nil, "", fmt.Errorf("generating root key with HSM: %w", genErr)
- }
- } else {
- newRootKey = make([]byte, 32)
- if _, genErr := rand.Read(newRootKey); genErr != nil {
- return nil, "", fmt.Errorf("generating root key: %w", genErr)
- }
- }
-
- encryptedNewKey, encErr := s.encryptRootKey(newRootKey, strategy)
- if encErr != nil {
- return nil, "", fmt.Errorf("encrypting new root key: %w", encErr)
- }
-
- strategyStr := string(strategy)
- return encryptedNewKey, strategyStr, nil
- })
-
+ rootConfig, err := s.findOrCreateRootConfig(ctx, hsmConfigured, strategy)
if err != nil {
return errutil.DatabaseErr("Failed to find or create KMS root config").WithErrf("Start: %w", err)
}
@@ -238,24 +209,6 @@ func (s *Service) resolveEncryptionKey(ctx context.Context) error {
return nil
}
-// CreateCipherPairWithDataKey returns an Encryptor/Decryptor pair bound to the
-// data key for the given org or project. All blobs include a "v01" version suffix.
-func (s *Service) CreateCipherPairWithDataKey(ctx context.Context, dto CreateCipherPairDTO) (*CipherPair, error) {
- dataKey, err := s.getDataKey(ctx, dto)
- if err != nil {
- return nil, err
- }
-
- return &CipherPair{
- encrypt: func(plainText []byte) ([]byte, error) {
- return encryptWithVersion(plainText, dataKey)
- },
- decrypt: func(cipherTextBlob []byte) ([]byte, error) {
- return decryptWithVersion(cipherTextBlob, dataKey)
- },
- }, nil
-}
-
// --- internal helpers ---
func (s *Service) getRootKey() []byte {
@@ -269,25 +222,6 @@ func (s *Service) getRootKey() []byte {
return keyCopy
}
-func (s *Service) getDataKey(ctx context.Context, dto CreateCipherPairDTO) ([]byte, error) {
- if dto.Type == DataKeyProject && dto.ProjectID == "" {
- return nil, fmt.Errorf("project ID is required for project data key")
- }
-
- if dto.Type == DataKeyOrganization && dto.OrgID == uuid.Nil {
- return nil, fmt.Errorf("org ID is required for organization data key")
- }
-
- switch dto.Type {
- case DataKeyProject:
- return s.getProjectDataKey(ctx, dto.ProjectID)
- case DataKeyOrganization:
- return s.getOrgDataKey(ctx, dto.OrgID)
- default:
- return nil, fmt.Errorf("KMS: unknown data key type: %d", dto.Type)
- }
-}
-
// --- KMS key material ---
// generateEncryptedKeyMaterial generates a random 32-byte key and encrypts it
@@ -311,26 +245,40 @@ func (s *Service) generateEncryptedKeyMaterial() ([]byte, error) {
return encryptedKey, nil
}
-// decryptKmsKey loads a KMS key record and decrypts its key material using the root key.
-// For internal KMS keys, decrypts locally. External KMS keys are not yet supported.
-func (s *Service) decryptKmsKey(ctx context.Context, kmsKeyID uuid.UUID) ([]byte, error) {
- kmsKeyDoc, err := s.findKmsKeyByID(ctx, kmsKeyID)
- if err != nil {
- return nil, errutil.DatabaseErr("Failed to find KMS key").WithErrf("decryptKmsKey(kmsKeyId=%s): %w", kmsKeyID, err)
+// decryptInternalKmsKey loads a KMS key record and decrypts its key material using the root key.
+// For internal KMS keys only. Returns error for external KMS keys.
+func (s *Service) decryptInternalKmsKey(ctx context.Context, kmsKeyID uuid.UUID) ([]byte, error) {
+ query := `
+ SELECT
+ kmsKey.id,
+ internalKms.id AS internal_kms_id,
+ internalKms."encryptedKey" AS internal_encrypted_key,
+ internalKms."encryptionAlgorithm" AS internal_encryption_algorithm,
+ externalKms.id AS external_kms_id
+ FROM kms_keys kmsKey
+ LEFT JOIN internal_kms internalKms ON internalKms."kmsKeyId" = kmsKey.id
+ LEFT JOIN external_kms externalKms ON externalKms."kmsKeyId" = kmsKey.id
+ WHERE kmsKey.id = @kmsKeyID
+ `
+ row := s.db.Replica().QueryRow(ctx, query, pgx.NamedArgs{"kmsKeyID": kmsKeyID})
+
+ var (
+ id uuid.UUID
+ internalKmsID sql.Null[uuid.UUID]
+ internalEncryptedKey sql.Null[[]byte]
+ internalEncryptionAlgorithm sql.Null[string]
+ externalKmsID sql.Null[uuid.UUID]
+ )
+ if err := row.Scan(&id, &internalKmsID, &internalEncryptedKey, &internalEncryptionAlgorithm, &externalKmsID); err != nil {
+ return nil, errutil.DatabaseErr("Failed to find KMS key").WithErrf("decryptInternalKmsKey(kmsKeyId=%s): %w", kmsKeyID, err)
}
- return s.decryptKmsKeyMaterial(kmsKeyDoc)
-}
-// decryptKmsKeyMaterial decrypts the key material from a kmsKeyWithAssociatedKms record.
-// Branches on internal (local AES-GCM) vs external (cloud provider — not yet implemented).
-func (s *Service) decryptKmsKeyMaterial(kmsKeyDoc *kmsKeyWithAssociatedKms) ([]byte, error) {
- // TODO(go): fix this before mileston
- if kmsKeyDoc.ExternalKmsID.Valid {
- panic("external KMS not implemented")
+ if externalKmsID.Valid {
+ return nil, fmt.Errorf("KMS: cannot get key material for external KMS")
}
- if !kmsKeyDoc.InternalKmsID.Valid {
- return nil, fmt.Errorf("KMS: key %s has no internal or external KMS association", kmsKeyDoc.ID.String())
+ if !internalKmsID.Valid {
+ return nil, fmt.Errorf("KMS: key %s has no internal or external KMS association", id.String())
}
rootKey := s.getRootKey()
@@ -338,12 +286,96 @@ func (s *Service) decryptKmsKeyMaterial(kmsKeyDoc *kmsKeyWithAssociatedKms) ([]b
return nil, fmt.Errorf("KMS: root encryption key not loaded, call Start first")
}
- if kmsKeyDoc.InternalEncryptionAlgorithm.V != "aes-256-gcm" {
- return nil, fmt.Errorf("KMS: unsupported encryption algorithm: %s", kmsKeyDoc.InternalEncryptionAlgorithm.V)
+ if internalEncryptionAlgorithm.V != "aes-256-gcm" {
+ return nil, fmt.Errorf("KMS: unsupported encryption algorithm: %s", internalEncryptionAlgorithm.V)
+ }
+
+ return cipher.SymmetricDecrypt(internalEncryptedKey.V, rootKey)
+}
+
+// decryptWithKmsKey decrypts ciphertext using the specified KMS key.
+// Handles both internal KMS (local decryption) and external KMS (AWS/GCP).
+func (s *Service) decryptWithKmsKey(ctx context.Context, kmsKeyID uuid.UUID, ciphertext []byte, depth int) ([]byte, error) {
+ if depth > 2 {
+ return nil, fmt.Errorf("KMS: max recursion depth exceeded")
+ }
+
+ query := `
+ SELECT
+ kmsKey.id,
+ kmsKey."orgId",
+ internalKms."encryptedKey",
+ internalKms."encryptionAlgorithm",
+ externalKms.id AS external_kms_id,
+ externalKms.provider,
+ externalKms."encryptedProviderInputs"
+ FROM kms_keys kmsKey
+ LEFT JOIN internal_kms internalKms ON internalKms."kmsKeyId" = kmsKey.id
+ LEFT JOIN external_kms externalKms ON externalKms."kmsKeyId" = kmsKey.id
+ WHERE kmsKey.id = @kmsKeyID
+ `
+ row := s.db.Replica().QueryRow(ctx, query, pgx.NamedArgs{"kmsKeyID": kmsKeyID})
+
+ var (
+ id uuid.UUID
+ orgID uuid.UUID
+ internalEncryptedKey sql.Null[[]byte]
+ internalEncAlgorithm sql.Null[string]
+ externalKmsID sql.Null[uuid.UUID]
+ externalProvider sql.Null[string]
+ externalEncryptedInput sql.Null[[]byte]
+ )
+ if err := row.Scan(&id, &orgID, &internalEncryptedKey, &internalEncAlgorithm, &externalKmsID, &externalProvider, &externalEncryptedInput); err != nil {
+ return nil, errutil.DatabaseErr("Failed to find KMS key").WithErrf("decryptWithKmsKey(kmsKeyId=%s): %w", kmsKeyID, err)
+ }
+
+ // External KMS: decrypt config with org's data key, then call external provider
+ if externalKmsID.Valid {
+ if s.externalKms == nil {
+ return nil, fmt.Errorf("KMS: external KMS service not configured")
+ }
+
+ org, err := s.findOrgKmsInfo(ctx, s.db.Replica(), orgID)
+ if err != nil {
+ return nil, fmt.Errorf("KMS: finding org for external KMS: %w", err)
+ }
+ if !org.KmsDefaultKeyID.Valid || len(org.KmsEncryptedDataKey) == 0 {
+ return nil, fmt.Errorf("KMS: org has no default KMS key")
+ }
+
+ orgDataKey, err := s.decryptWithKmsKey(ctx, org.KmsDefaultKeyID.V, org.KmsEncryptedDataKey, depth+1)
+ if err != nil {
+ return nil, fmt.Errorf("KMS: decrypting org data key: %w", err)
+ }
+
+ decryptedConfig, err := decryptWithVersion(externalEncryptedInput.V, orgDataKey)
+ if err != nil {
+ return nil, fmt.Errorf("KMS: decrypting external KMS config: %w", err)
+ }
+
+ return s.externalKms.Decrypt(ctx, externalProvider.V, decryptedConfig, ciphertext)
}
- // internal_kms.encrypted_key is AES-GCM encrypted with ROOT_KEY (no version suffix).
- return cipher.SymmetricDecrypt(kmsKeyDoc.InternalEncryptedKey.V, rootKey)
+ // Internal KMS: decrypt key material, then decrypt ciphertext locally
+ if !internalEncryptedKey.Valid {
+ return nil, fmt.Errorf("KMS: key %s has no internal or external KMS association", id.String())
+ }
+
+ rootKey := s.getRootKey()
+ if len(rootKey) == 0 {
+ return nil, fmt.Errorf("KMS: root encryption key not loaded")
+ }
+
+ if internalEncAlgorithm.V != "aes-256-gcm" {
+ return nil, fmt.Errorf("KMS: unsupported encryption algorithm: %s", internalEncAlgorithm.V)
+ }
+
+ kmsKey, err := cipher.SymmetricDecrypt(internalEncryptedKey.V, rootKey)
+ if err != nil {
+ return nil, fmt.Errorf("KMS: decrypting internal key: %w", err)
+ }
+
+ return decryptWithVersion(ciphertext, kmsKey)
}
// --- Root key encrypt/decrypt ---
@@ -435,35 +467,6 @@ type kmsRootConfigRow struct {
EncryptionStrategy sql.Null[string] `db:"encryption_strategy"`
}
-// kmsKeyWithAssociatedKms is the join result of kms_keys LEFT JOIN internal_kms LEFT JOIN external_kms.
-type kmsKeyWithAssociatedKms struct {
- ID uuid.UUID `db:"id"`
- Name string `db:"name"`
-
- // Internal KMS fields (nullable from LEFT JOIN)
- InternalKmsID sql.Null[uuid.UUID] `db:"internal_kms_id"`
- InternalEncryptedKey sql.Null[[]byte] `db:"internal_encrypted_key"`
- InternalEncryptionAlgorithm sql.Null[string] `db:"internal_encryption_algorithm"`
-
- // External KMS fields (nullable from LEFT JOIN)
- ExternalKmsID sql.Null[uuid.UUID] `db:"external_kms_id"`
-}
-
-// orgKmsInfo holds the narrow org fields needed by the KMS service.
-type orgKmsInfo struct {
- ID uuid.UUID `db:"id"`
- KmsDefaultKeyID sql.Null[uuid.UUID] `db:"kms_default_key_id"`
- KmsEncryptedDataKey []byte `db:"kms_encrypted_data_key"`
-}
-
-// projectKmsInfo holds the narrow project fields needed by the KMS service.
-type projectKmsInfo struct {
- ID string `db:"id"`
- OrgID uuid.UUID `db:"org_id"`
- KmsSecretManagerKeyID sql.Null[uuid.UUID] `db:"kms_secret_manager_key_id"`
- KmsSecretManagerEncryptedDataKey []byte `db:"kms_secret_manager_encrypted_data_key"`
-}
-
// --- Query methods ---
// findSuperAdminConfig returns the super_admin config row if it exists.
@@ -483,24 +486,20 @@ func (s *Service) findSuperAdminConfig(ctx context.Context) (*superAdminConfigRo
return &cfg, nil
}
-// findOrCreateRootConfig atomically ensures the KMS root config row exists.
-func (s *Service) findOrCreateRootConfig(ctx context.Context, createFn func() (encryptedRootKey []byte, encryptionStrategy string, err error)) (*kmsRootConfigRow, error) {
+func (s *Service) findOrCreateRootConfig(ctx context.Context, hsmConfigured bool, strategy RootKeyEncryptionStrategy) (*kmsRootConfigRow, error) {
tx, err := s.db.Primary().Begin(ctx)
if err != nil {
return nil, fmt.Errorf("beginning transaction: %w", err)
}
- defer tx.Rollback(ctx) //nolint:errcheck // rollback on defer is best-effort cleanup
+ defer tx.Rollback(ctx) //nolint:errcheck // rollback is no-op after commit
- // Acquire advisory lock
if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock($1)", PgLockKmsRootKeyInit); err != nil {
return nil, fmt.Errorf("acquiring advisory lock: %w", err)
}
- // Check if root config already exists.
- checkQuery := `SELECT id, "encryptedRootKey", "encryptionStrategy" FROM kms_root_config WHERE id = @id`
- checkArgs := pgx.NamedArgs{"id": KmsRootConfigUUID}
+ query := `SELECT id, "encryptedRootKey", "encryptionStrategy" FROM kms_root_config WHERE id = @id`
+ row := tx.QueryRow(ctx, query, pgx.NamedArgs{"id": KmsRootConfigUUID})
- row := tx.QueryRow(ctx, checkQuery, checkArgs)
var existing kmsRootConfigRow
err = row.Scan(&existing.ID, &existing.EncryptedRootKey, &existing.EncryptionStrategy)
if err == nil {
@@ -513,13 +512,25 @@ func (s *Service) findOrCreateRootConfig(ctx context.Context, createFn func() (e
return nil, fmt.Errorf("checking existing root config: %w", err)
}
- // Config doesn't exist — invoke callback to generate the new root key.
- encryptionRootKey, encryptionStrategy, err := createFn()
+ // Generate new root key
+ var newRootKey []byte
+ if hsmConfigured && s.hsm != nil {
+ newRootKey, err = s.hsm.RandomBytes(32)
+ if err != nil {
+ return nil, fmt.Errorf("generating root key with HSM: %w", err)
+ }
+ } else {
+ newRootKey = make([]byte, 32)
+ if _, err := rand.Read(newRootKey); err != nil {
+ return nil, fmt.Errorf("generating root key: %w", err)
+ }
+ }
+
+ encryptedRootKey, err := s.encryptRootKey(newRootKey, strategy)
if err != nil {
- return nil, fmt.Errorf("generating root config: %w", err)
+ return nil, fmt.Errorf("encrypting new root key: %w", err)
}
- // Create the initial root config row.
insertQuery := `
INSERT INTO kms_root_config (id, "encryptedRootKey", "encryptionStrategy")
VALUES (@id, @encryptedRootKey, @encryptionStrategy)
@@ -527,13 +538,12 @@ func (s *Service) findOrCreateRootConfig(ctx context.Context, createFn func() (e
`
insertArgs := pgx.NamedArgs{
"id": KmsRootConfigUUID,
- "encryptedRootKey": encryptionRootKey,
- "encryptionStrategy": encryptionStrategy,
+ "encryptedRootKey": encryptedRootKey,
+ "encryptionStrategy": string(strategy),
}
var result kmsRootConfigRow
- err = tx.QueryRow(ctx, insertQuery, insertArgs).Scan(&result.ID, &result.EncryptedRootKey, &result.EncryptionStrategy)
- if err != nil {
+ if err := tx.QueryRow(ctx, insertQuery, insertArgs).Scan(&result.ID, &result.EncryptedRootKey, &result.EncryptionStrategy); err != nil {
return nil, fmt.Errorf("creating root config: %w", err)
}
@@ -544,77 +554,6 @@ func (s *Service) findOrCreateRootConfig(ctx context.Context, createFn func() (e
return &result, nil
}
-// findKmsKeyByID loads a kms_keys row with its associated internal or external KMS material.
-func (s *Service) findKmsKeyByID(ctx context.Context, kmsKeyID uuid.UUID) (*kmsKeyWithAssociatedKms, error) {
- query := `
- SELECT
- kmsKey.id,
- kmsKey.name,
- internalKms.id AS internal_kms_id,
- internalKms."encryptedKey" AS internal_encrypted_key,
- internalKms."encryptionAlgorithm" AS internal_encryption_algorithm,
- externalKms.id AS external_kms_id
- FROM kms_keys kmsKey
- LEFT JOIN internal_kms internalKms ON internalKms."kmsKeyId" = kmsKey.id
- LEFT JOIN external_kms externalKms ON externalKms."kmsKeyId" = kmsKey.id
- WHERE kmsKey.id = @kmsKeyID
- `
- args := pgx.NamedArgs{"kmsKeyID": kmsKeyID}
-
- row := s.db.Replica().QueryRow(ctx, query, args)
- var result kmsKeyWithAssociatedKms
- err := row.Scan(
- &result.ID,
- &result.Name,
- &result.InternalKmsID,
- &result.InternalEncryptedKey,
- &result.InternalEncryptionAlgorithm,
- &result.ExternalKmsID,
- )
- if err != nil {
- return nil, fmt.Errorf("finding KMS key: %w", err)
- }
- return &result, nil
-}
-
-// findOrgKmsInfo returns the narrow org fields needed for KMS data key operations.
-// Pass a pg.Querier (either *pgxpool.Pool or pgx.Tx).
-func (s *Service) findOrgKmsInfo(ctx context.Context, q pg.Querier, orgID uuid.UUID) (*orgKmsInfo, error) {
- query := `
- SELECT id, "kmsDefaultKeyId", "kmsEncryptedDataKey"
- FROM organizations
- WHERE id = @orgID
- `
- args := pgx.NamedArgs{"orgID": orgID}
-
- row := q.QueryRow(ctx, query, args)
- var result orgKmsInfo
- err := row.Scan(&result.ID, &result.KmsDefaultKeyID, &result.KmsEncryptedDataKey)
- if err != nil {
- return nil, fmt.Errorf("finding org KMS info: %w", err)
- }
- return &result, nil
-}
-
-// findProjectKmsInfo returns the narrow project fields needed for KMS data key operations.
-// Pass a pg.Querier (either *pgxpool.Pool or pgx.Tx).
-func (s *Service) findProjectKmsInfo(ctx context.Context, q pg.Querier, projectID string) (*projectKmsInfo, error) {
- query := `
- SELECT id, "orgId", "kmsSecretManagerKeyId", "kmsSecretManagerEncryptedDataKey"
- FROM projects
- WHERE id = @projectID
- `
- args := pgx.NamedArgs{"projectID": projectID}
-
- row := q.QueryRow(ctx, query, args)
- var result projectKmsInfo
- err := row.Scan(&result.ID, &result.OrgID, &result.KmsSecretManagerKeyID, &result.KmsSecretManagerEncryptedDataKey)
- if err != nil {
- return nil, fmt.Errorf("finding project KMS info: %w", err)
- }
- return &result, nil
-}
-
// createKmsKeyWithInternal inserts a kms_keys row and its internal_kms material within a transaction.
func (s *Service) createKmsKeyWithInternal(ctx context.Context, tx pgx.Tx, orgID uuid.UUID, encryptedKey []byte) (uuid.UUID, error) {
keyName := generateRandomKeyName()
@@ -652,204 +591,3 @@ func (s *Service) createKmsKeyWithInternal(ctx context.Context, tx pgx.Tx, orgID
return kmsKeyID, nil
}
-
-// findOrCreateOrgKmsKey atomically ensures the org has a default KMS key.
-func (s *Service) findOrCreateOrgKmsKey(ctx context.Context, orgID uuid.UUID, createFn func() (encryptedKey []byte, err error)) (uuid.UUID, error) {
- lockID := fmt.Sprintf("kms-org-key:%s", orgID)
-
- tx, err := s.db.Primary().Begin(ctx)
- if err != nil {
- return uuid.Nil, fmt.Errorf("beginning transaction: %w", err)
- }
-
- lock, err := pglock.AcquireBlockingLock(ctx, tx, lockID)
- if err != nil {
- tx.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return uuid.Nil, fmt.Errorf("acquiring org key lock: %w", err)
- }
-
- // Re-check after lock — another request may have created it.
- org, err := s.findOrgKmsInfo(ctx, tx, orgID)
- if err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return uuid.Nil, fmt.Errorf("finding org: %w", err)
- }
- if org.KmsDefaultKeyID.Valid {
- if err := lock.Release(ctx); err != nil {
- return uuid.Nil, err
- }
- return org.KmsDefaultKeyID.V, nil
- }
-
- encryptedKey, err := createFn()
- if err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return uuid.Nil, fmt.Errorf("generating KMS key: %w", err)
- }
-
- createdID, err := s.createKmsKeyWithInternal(ctx, tx, org.ID, encryptedKey)
- if err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return uuid.Nil, err
- }
-
- // Update org with new key ID
- updateQuery := `UPDATE organizations SET "kmsDefaultKeyId" = @keyID WHERE id = @orgID`
- updateArgs := pgx.NamedArgs{"keyID": createdID, "orgID": orgID}
- if _, err := tx.Exec(ctx, updateQuery, updateArgs); err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return uuid.Nil, fmt.Errorf("updating org default key: %w", err)
- }
-
- if err := lock.Release(ctx); err != nil {
- return uuid.Nil, err
- }
- return createdID, nil
-}
-
-// findOrCreateOrgDataKey atomically ensures the org has an encrypted data key.
-func (s *Service) findOrCreateOrgDataKey(ctx context.Context, orgID uuid.UUID, createFn func() (encryptedDataKey []byte, err error)) ([]byte, error) {
- lockID := fmt.Sprintf("kms-org-data-key:%s", orgID)
-
- tx, err := s.db.Primary().Begin(ctx)
- if err != nil {
- return nil, fmt.Errorf("beginning transaction: %w", err)
- }
-
- lock, err := pglock.AcquireBlockingLock(ctx, tx, lockID)
- if err != nil {
- tx.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return nil, fmt.Errorf("acquiring org data key lock: %w", err)
- }
-
- // Re-check after lock — another request may have created it.
- org, err := s.findOrgKmsInfo(ctx, tx, orgID)
- if err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return nil, fmt.Errorf("finding org: %w", err)
- }
- if len(org.KmsEncryptedDataKey) > 0 {
- if err := lock.Release(ctx); err != nil {
- return nil, err
- }
- return org.KmsEncryptedDataKey, nil
- }
-
- encryptedDataKey, err := createFn()
- if err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return nil, fmt.Errorf("generating data key: %w", err)
- }
-
- updateQuery := `UPDATE organizations SET "kmsEncryptedDataKey" = @dataKey WHERE id = @orgID`
- updateArgs := pgx.NamedArgs{"dataKey": encryptedDataKey, "orgID": orgID}
- if _, err := tx.Exec(ctx, updateQuery, updateArgs); err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return nil, fmt.Errorf("setting org encrypted data key: %w", err)
- }
-
- if err := lock.Release(ctx); err != nil {
- return nil, err
- }
- return encryptedDataKey, nil
-}
-
-// findOrCreateProjectKmsKey atomically ensures the project has a secret manager KMS key.
-func (s *Service) findOrCreateProjectKmsKey(ctx context.Context, projectID string, createFn func() (encryptedKey []byte, err error)) (uuid.UUID, error) {
- lockID := fmt.Sprintf("kms-project-key:%s", projectID)
-
- tx, err := s.db.Primary().Begin(ctx)
- if err != nil {
- return uuid.Nil, fmt.Errorf("beginning transaction: %w", err)
- }
-
- lock, err := pglock.AcquireBlockingLock(ctx, tx, lockID)
- if err != nil {
- tx.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return uuid.Nil, fmt.Errorf("acquiring project key lock: %w", err)
- }
-
- // Re-check after lock — another request may have created it.
- project, err := s.findProjectKmsInfo(ctx, tx, projectID)
- if err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return uuid.Nil, fmt.Errorf("finding project: %w", err)
- }
- if project.KmsSecretManagerKeyID.Valid {
- if err := lock.Release(ctx); err != nil {
- return uuid.Nil, err
- }
- return project.KmsSecretManagerKeyID.V, nil
- }
-
- encryptedKey, err := createFn()
- if err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return uuid.Nil, fmt.Errorf("generating KMS key: %w", err)
- }
-
- createdID, err := s.createKmsKeyWithInternal(ctx, tx, project.OrgID, encryptedKey)
- if err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return uuid.Nil, err
- }
-
- updateQuery := `UPDATE projects SET "kmsSecretManagerKeyId" = @keyID WHERE id = @projectID`
- updateArgs := pgx.NamedArgs{"keyID": createdID, "projectID": projectID}
- if _, err := tx.Exec(ctx, updateQuery, updateArgs); err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return uuid.Nil, fmt.Errorf("updating project KMS key: %w", err)
- }
-
- if err := lock.Release(ctx); err != nil {
- return uuid.Nil, err
- }
- return createdID, nil
-}
-
-// findOrCreateProjectDataKey atomically ensures the project has an encrypted data key.
-func (s *Service) findOrCreateProjectDataKey(ctx context.Context, projectID string, createFn func() (encryptedDataKey []byte, err error)) ([]byte, error) {
- lockID := fmt.Sprintf("kms-project-data-key:%s", projectID)
-
- tx, err := s.db.Primary().Begin(ctx)
- if err != nil {
- return nil, fmt.Errorf("beginning transaction: %w", err)
- }
-
- lock, err := pglock.AcquireBlockingLock(ctx, tx, lockID)
- if err != nil {
- tx.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return nil, fmt.Errorf("acquiring project data key lock: %w", err)
- }
-
- // Re-check after lock — another request may have created it.
- project, err := s.findProjectKmsInfo(ctx, tx, projectID)
- if err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return nil, fmt.Errorf("finding project: %w", err)
- }
- if len(project.KmsSecretManagerEncryptedDataKey) > 0 {
- if err := lock.Release(ctx); err != nil {
- return nil, err
- }
- return project.KmsSecretManagerEncryptedDataKey, nil
- }
-
- encryptedDataKey, err := createFn()
- if err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return nil, fmt.Errorf("generating data key: %w", err)
- }
-
- updateQuery := `UPDATE projects SET "kmsSecretManagerEncryptedDataKey" = @dataKey WHERE id = @projectID`
- updateArgs := pgx.NamedArgs{"dataKey": encryptedDataKey, "projectID": projectID}
- if _, err := tx.Exec(ctx, updateQuery, updateArgs); err != nil {
- lock.Rollback(ctx) //nolint:errcheck // rollback on error is best-effort cleanup
- return nil, fmt.Errorf("setting project encrypted data key: %w", err)
- }
-
- if err := lock.Release(ctx); err != nil {
- return nil, err
- }
- return encryptedDataKey, nil
-}
diff --git a/backend-go/internal/services/kms/kms_integration_test.go b/backend-go/internal/services/kms/kms_integration_test.go
index a37f7fdc18..e86ae22816 100644
--- a/backend-go/internal/services/kms/kms_integration_test.go
+++ b/backend-go/internal/services/kms/kms_integration_test.go
@@ -4,23 +4,22 @@ package kms_test
import (
"context"
- "log"
+ "encoding/json"
"os"
"sync"
"testing"
"github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
"github.com/stretchr/testify/require"
+ "github.com/infisical/api/internal/ee/services/externalkms"
"github.com/infisical/api/internal/services/kms"
"github.com/infisical/api/internal/testutil"
"github.com/infisical/api/internal/testutil/infra"
)
-var (
- stack *infra.Stack
- orgID uuid.UUID
-)
+var stack *infra.Stack
func TestMain(m *testing.M) {
stack = infra.New().
@@ -29,332 +28,396 @@ func TestMain(m *testing.M) {
WithNodeJSApi().
MustStart()
- var err error
- orgID, err = uuid.Parse(stack.NodeJS().OrgID())
- if err != nil {
- log.Fatalf("kms_test: parsing org ID: %v", err)
- }
-
code := m.Run()
stack.Stop()
os.Exit(code)
}
-// setupService creates a KMS service wired to real PostgreSQL + Redis.
-func setupService(t *testing.T) *kms.Service {
+func startedService(t *testing.T) *kms.Service {
t.Helper()
-
svc, err := kms.NewService(context.Background(), testutil.NopLogger(), &kms.Deps{
- DB: stack.DB(),
- HSM: nil,
- Config: stack.Config(),
+ DB: stack.DB(),
+ HSM: nil,
+ ExternalKms: nil,
+ Config: stack.Config(),
})
require.NoError(t, err)
- return svc
-}
-
-// startedService returns a service with Start() already called.
-func startedService(t *testing.T) *kms.Service {
- t.Helper()
- svc := setupService(t)
require.NoError(t, svc.Start(context.Background(), false))
return svc
}
// ==========================================================================
-// Start
+// Key Isolation: Project A cannot decrypt Project B's data
// ==========================================================================
-func TestStart_Success(t *testing.T) {
- svc := setupService(t)
- err := svc.Start(context.Background(), false)
+func TestProjectIsolation_CrossProjectDecryptFails(t *testing.T) {
+ svc := startedService(t)
+ ctx := context.Background()
+
+ proj1 := stack.NodeJS().MustCreateProject("kms-iso-proj1")
+ proj2 := stack.NodeJS().MustCreateProject("kms-iso-proj2")
+
+ pair1, err := svc.CreateCipherPairWithProjectDataKey(ctx, proj1.ID)
require.NoError(t, err)
-}
-func TestStart_Idempotent(t *testing.T) {
- svc := setupService(t)
- ctx := context.Background()
+ pair2, err := svc.CreateCipherPairWithProjectDataKey(ctx, proj2.ID)
+ require.NoError(t, err)
+
+ secret := []byte("project1 secret")
+ ciphertext, err := pair1.Encrypt(secret)
+ require.NoError(t, err)
- require.NoError(t, svc.Start(ctx, false))
- require.NoError(t, svc.Start(ctx, false))
+ // Project2 must NOT decrypt project1's data
+ _, err = pair2.Decrypt(ciphertext)
+ require.Error(t, err, "project2 should not decrypt project1's ciphertext")
}
-func TestStart_Concurrent(t *testing.T) {
+// ==========================================================================
+// Concurrency: Racing first-access creates exactly ONE KMS key
+// ==========================================================================
+
+func TestConcurrentFirstAccess_CreatesExactlyOneProjectKey(t *testing.T) {
+ svc := startedService(t)
ctx := context.Background()
- const n = 10
- // Set up services before spawning goroutines (require.NoError isn't goroutine-safe).
- services := make([]*kms.Service, n)
- for i := 0; i < n; i++ {
- services[i] = setupService(t)
- }
+ // Fresh project with no KMS key yet
+ proj := stack.NodeJS().MustCreateProject("kms-race-proj")
- errs := make([]error, n)
+ const n = 10
var wg sync.WaitGroup
wg.Add(n)
+ errs := make([]error, n)
for i := 0; i < n; i++ {
go func(idx int) {
defer wg.Done()
- errs[idx] = services[idx].Start(ctx, false)
+ _, errs[idx] = svc.CreateCipherPairWithProjectDataKey(ctx, proj.ID)
}(i)
}
-
wg.Wait()
+
for i, err := range errs {
- require.NoError(t, err, "goroutine %d", i)
+ require.NoError(t, err, "goroutine %d failed", i)
}
+
+ // Verify: exactly ONE kms_keys row for this project
+ var kmsKeyCount int
+ err := stack.DB().Replica().QueryRow(ctx, `
+ SELECT COUNT(*) FROM kms_keys k
+ JOIN projects p ON p."kmsSecretManagerKeyId" = k.id
+ WHERE p.id = @projectID
+ `, pgx.NamedArgs{"projectID": proj.ID}).Scan(&kmsKeyCount)
+ require.NoError(t, err)
+ require.Equal(t, 1, kmsKeyCount, "expected exactly 1 KMS key, got %d", kmsKeyCount)
}
// ==========================================================================
-// Organization cipher pair
+// Node.js ↔ Go Compatibility (using secrets as proxy)
// ==========================================================================
-func TestOrgCipherPair_EncryptDecryptRoundTrip(t *testing.T) {
- svc := startedService(t)
+func TestCompatibility_GoDecryptsNodeEncryptedSecret(t *testing.T) {
ctx := context.Background()
- pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
- Type: kms.DataKeyOrganization,
- OrgID: orgID,
- })
+ // Create project and secret via Node.js
+ proj := stack.NodeJS().MustCreateProject("compat-node-to-go")
+ plaintext := "node-encrypted-secret-value"
+ secret := stack.NodeJS().CreateSecret(t, proj.ID, "dev", "/", "NODE_SECRET", plaintext, nil)
+
+ // Read encrypted value directly from secrets_v2
+ var encryptedValue []byte
+ err := stack.DB().Replica().QueryRow(ctx, `
+ SELECT "encryptedValue"
+ FROM secrets_v2
+ WHERE id = @secretID
+ `, pgx.NamedArgs{"secretID": secret.ID}).Scan(&encryptedValue)
require.NoError(t, err)
- require.NotNil(t, pair)
+ require.NotEmpty(t, encryptedValue)
- plaintext := []byte("hello secret world")
- ciphertext, err := pair.Encrypt(plaintext)
+ // Go decrypts using project's cipher pair
+ svc := startedService(t)
+ pair, err := svc.CreateCipherPairWithProjectDataKey(ctx, proj.ID)
require.NoError(t, err)
- require.NotEqual(t, plaintext, ciphertext)
- decrypted, err := pair.Decrypt(ciphertext)
+ decrypted, err := pair.Decrypt(encryptedValue)
require.NoError(t, err)
- require.Equal(t, plaintext, decrypted)
+ require.Equal(t, plaintext, string(decrypted))
}
-func TestOrgCipherPair_Idempotent(t *testing.T) {
- svc := startedService(t)
+func TestCompatibility_NodeDecryptsGoEncryptedSecret(t *testing.T) {
ctx := context.Background()
- dto := kms.CreateCipherPairDTO{
- Type: kms.DataKeyOrganization,
- OrgID: orgID,
- }
+ // Create project and initial secret via Node.js
+ proj := stack.NodeJS().MustCreateProject("compat-go-to-node")
+ originalValue := "original-value"
+ stack.NodeJS().CreateSecret(t, proj.ID, "dev", "/", "GO_SECRET", originalValue, nil)
- pair1, err := svc.CreateCipherPairWithDataKey(ctx, dto)
+ // Go encrypts a new value
+ svc := startedService(t)
+ pair, err := svc.CreateCipherPairWithProjectDataKey(ctx, proj.ID)
require.NoError(t, err)
- pair2, err := svc.CreateCipherPairWithDataKey(ctx, dto)
+ newPlaintext := "go-encrypted-secret-value"
+ newEncrypted, err := pair.Encrypt([]byte(newPlaintext))
require.NoError(t, err)
- // Encrypt with pair1, decrypt with pair2 — both bound to the same data key.
- plaintext := []byte("cross-pair test")
- ciphertext, err := pair1.Encrypt(plaintext)
+ // Update the secret's encrypted value directly in secrets_v2
+ result, err := stack.DB().Primary().Exec(ctx, `
+ UPDATE secrets_v2
+ SET "encryptedValue" = @encryptedValue
+ WHERE key = 'GO_SECRET' AND "folderId" IN (
+ SELECT id FROM secret_folders WHERE "envId" IN (
+ SELECT id FROM project_environments WHERE "projectId" = @projectID AND slug = 'dev'
+ ) AND name = 'root'
+ )
+ `, pgx.NamedArgs{
+ "encryptedValue": newEncrypted,
+ "projectID": proj.ID,
+ })
require.NoError(t, err)
+ require.Equal(t, int64(1), result.RowsAffected(), "should update exactly 1 row")
- decrypted, err := pair2.Decrypt(ciphertext)
- require.NoError(t, err)
- require.Equal(t, plaintext, decrypted)
+ // Node.js reads the secret via API - should decrypt successfully
+ readSecret := stack.NodeJS().GetSecretByKey(t, proj.ID, "dev", "/", "GO_SECRET")
+ require.Equal(t, newPlaintext, readSecret.Value)
}
-func TestOrgCipherPair_Concurrent(t *testing.T) {
+// ==========================================================================
+// Corrupted Input Handling
+// ==========================================================================
+
+func TestCorruptedCiphertext_TruncatedFails(t *testing.T) {
svc := startedService(t)
ctx := context.Background()
- const n = 10
- plaintext := []byte("concurrent org test")
- ciphertexts := make([][]byte, n)
- errs := make([]error, n)
+ proj := stack.NodeJS().MustCreateProject("kms-corrupt-trunc")
- var wg sync.WaitGroup
- wg.Add(n)
+ pair, err := svc.CreateCipherPairWithProjectDataKey(ctx, proj.ID)
+ require.NoError(t, err)
- for i := 0; i < n; i++ {
- go func(idx int) {
- defer wg.Done()
- pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
- Type: kms.DataKeyOrganization,
- OrgID: orgID,
- })
- if err != nil {
- errs[idx] = err
- return
- }
- ciphertexts[idx], errs[idx] = pair.Encrypt(plaintext)
- }(i)
- }
+ ciphertext, err := pair.Encrypt([]byte("some data"))
+ require.NoError(t, err)
- wg.Wait()
- for i, err := range errs {
- require.NoError(t, err, "goroutine %d", i)
- }
+ // Truncate ciphertext
+ truncated := ciphertext[:len(ciphertext)/2]
+ _, err = pair.Decrypt(truncated)
+ require.Error(t, err, "truncated ciphertext should fail")
+}
- // All ciphertexts should decrypt to the same plaintext.
- pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
- Type: kms.DataKeyOrganization,
- OrgID: orgID,
- })
+func TestCorruptedCiphertext_BitFlipFails(t *testing.T) {
+ svc := startedService(t)
+ ctx := context.Background()
+
+ proj := stack.NodeJS().MustCreateProject("kms-corrupt-flip")
+
+ pair, err := svc.CreateCipherPairWithProjectDataKey(ctx, proj.ID)
require.NoError(t, err)
- for i, ct := range ciphertexts {
- decrypted, err := pair.Decrypt(ct)
- require.NoError(t, err, "decrypting goroutine %d ciphertext", i)
- require.Equal(t, plaintext, decrypted, "goroutine %d", i)
- }
-}
+ ciphertext, err := pair.Encrypt([]byte("authentic data"))
+ require.NoError(t, err)
-// ==========================================================================
-// Project cipher pair
-// ==========================================================================
+ // Flip a bit in the middle of ciphertext
+ corrupted := make([]byte, len(ciphertext))
+ copy(corrupted, ciphertext)
+ corrupted[len(corrupted)/2] ^= 0xFF
+
+ _, err = pair.Decrypt(corrupted)
+ require.Error(t, err, "corrupted ciphertext should fail authentication")
+}
-func TestProjectCipherPair_CreatesFromScratch(t *testing.T) {
+func TestCorruptedCiphertext_WrongVersionSuffixStillDecrypts(t *testing.T) {
+ // Version suffix is informational metadata, not part of authentication.
+ // Modifying it does not break decryption - the ciphertext body is still valid.
svc := startedService(t)
ctx := context.Background()
- proj := stack.NodeJS().CreateProject(t, "kms-scratch")
+ proj := stack.NodeJS().MustCreateProject("kms-corrupt-ver")
- pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
- Type: kms.DataKeyProject,
- ProjectID: proj.ID,
- })
+ pair, err := svc.CreateCipherPairWithProjectDataKey(ctx, proj.ID)
require.NoError(t, err)
- require.NotNil(t, pair)
- plaintext := []byte("project secret data")
+ plaintext := []byte("versioned data")
ciphertext, err := pair.Encrypt(plaintext)
require.NoError(t, err)
- decrypted, err := pair.Decrypt(ciphertext)
- require.NoError(t, err)
+ // Replace version suffix (last 3 bytes) - decryption still works
+ tampered := make([]byte, len(ciphertext))
+ copy(tampered, ciphertext)
+ copy(tampered[len(tampered)-3:], "v99")
+
+ decrypted, err := pair.Decrypt(tampered)
+ require.NoError(t, err, "version suffix is not validated")
require.Equal(t, plaintext, decrypted)
}
-// TODO(go): fix the naming convention. Think about go way of this
-func TestProjectCipherPair_Idempotent(t *testing.T) {
+// ==========================================================================
+// Error Cases
+// ==========================================================================
+
+func TestCreateCipherPair_NonexistentProjectFails(t *testing.T) {
svc := startedService(t)
ctx := context.Background()
- proj := stack.NodeJS().CreateProject(t, "kms-idempotent")
-
- dto := kms.CreateCipherPairDTO{
- Type: kms.DataKeyProject,
- ProjectID: proj.ID,
- }
+ _, err := svc.CreateCipherPairWithProjectDataKey(ctx, "nonexistent-project-id")
+ require.Error(t, err)
+}
- pair1, err := svc.CreateCipherPairWithDataKey(ctx, dto)
- require.NoError(t, err)
+func TestCreateCipherPair_EmptyProjectIDFails(t *testing.T) {
+ svc := startedService(t)
+ ctx := context.Background()
- pair2, err := svc.CreateCipherPairWithDataKey(ctx, dto)
- require.NoError(t, err)
+ _, err := svc.CreateCipherPairWithProjectDataKey(ctx, "")
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "project ID is required")
+}
- // Cross-decrypt: encrypt with first, decrypt with second.
- plaintext := []byte("idempotent project test")
- ciphertext, err := pair1.Encrypt(plaintext)
- require.NoError(t, err)
+// ==========================================================================
+// External KMS Tests (using mock provider)
+// ==========================================================================
- decrypted, err := pair2.Decrypt(ciphertext)
+func startedServiceWithExternalKms(t *testing.T, extKms kms.ExternalKmsService) *kms.Service {
+ t.Helper()
+ svc, err := kms.NewService(context.Background(), testutil.NopLogger(), &kms.Deps{
+ DB: stack.DB(),
+ HSM: nil,
+ ExternalKms: extKms,
+ Config: stack.Config(),
+ })
require.NoError(t, err)
- require.Equal(t, plaintext, decrypted)
+ require.NoError(t, svc.Start(context.Background(), false))
+ return svc
}
-func TestProjectCipherPair_Concurrent(t *testing.T) {
- svc := startedService(t)
+// setupExternalKmsForProject creates an external KMS key for a project.
+// Returns the project and the original (unencrypted) provider config.
+func setupExternalKmsForProject(t *testing.T, svc *kms.Service, mock *externalkms.MockProvider, projectName string) (proj *infra.ProjectSeed, configJSON []byte) {
+ t.Helper()
ctx := context.Background()
- // All goroutines race on the same fresh project.
- proj := stack.NodeJS().CreateProject(t, "kms-concurrent")
+ // Create project via Node.js (this sets up org with internal KMS)
+ proj = stack.NodeJS().MustCreateProject(projectName)
- const n = 10
- plaintext := []byte("concurrent project test")
- ciphertexts := make([][]byte, n)
- errs := make([]error, n)
+ // Get org ID from project
+ var orgID uuid.UUID
+ err := stack.DB().Replica().QueryRow(ctx, `SELECT "orgId" FROM projects WHERE id = @id`,
+ pgx.NamedArgs{"id": proj.ID}).Scan(&orgID)
+ require.NoError(t, err)
- var wg sync.WaitGroup
- wg.Add(n)
+ // First, ensure org has a data key by creating a cipher pair
+ orgPair, err := svc.CreateCipherPairWithOrgDataKey(ctx, orgID)
+ require.NoError(t, err)
- for i := 0; i < n; i++ {
- go func(idx int) {
- defer wg.Done()
- pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
- Type: kms.DataKeyProject,
- ProjectID: proj.ID,
- })
- if err != nil {
- errs[idx] = err
- return
- }
- ciphertexts[idx], errs[idx] = pair.Encrypt(plaintext)
- }(i)
- }
+ // Create fake external KMS config
+ providerConfig := map[string]string{"key": "test-key-id", "region": "us-east-1"}
+ configJSON, err = json.Marshal(providerConfig)
+ require.NoError(t, err)
- wg.Wait()
- for i, err := range errs {
- require.NoError(t, err, "goroutine %d", i)
- }
+ // Encrypt config with org's data key
+ encryptedConfig, err := orgPair.Encrypt(configJSON)
+ require.NoError(t, err)
- // All should decrypt to same plaintext.
- pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
- Type: kms.DataKeyProject,
- ProjectID: proj.ID,
- })
+ // Create external KMS key in database
+ var kmsKeyID uuid.UUID
+ err = stack.DB().Primary().QueryRow(ctx, `
+ INSERT INTO kms_keys (name, "orgId", "isReserved", "keyUsage")
+ VALUES (@name, @orgID, false, 'encrypt-decrypt')
+ RETURNING id
+ `, pgx.NamedArgs{"name": "test-external-kms", "orgID": orgID}).Scan(&kmsKeyID)
require.NoError(t, err)
- for i, ct := range ciphertexts {
- decrypted, err := pair.Decrypt(ct)
- require.NoError(t, err, "decrypting goroutine %d ciphertext", i)
- require.Equal(t, plaintext, decrypted, "goroutine %d", i)
+ // Create external_kms record
+ _, err = stack.DB().Primary().Exec(ctx, `
+ INSERT INTO external_kms (id, provider, "encryptedProviderInputs", "kmsKeyId")
+ VALUES (gen_random_uuid(), 'aws', @encryptedConfig, @kmsKeyID)
+ `, pgx.NamedArgs{"encryptedConfig": encryptedConfig, "kmsKeyID": kmsKeyID})
+ require.NoError(t, err)
+
+ // Generate project data key and "encrypt" it with mock external KMS
+ // Mock uses XOR with 0x42, so we simulate what the external KMS would return
+ plainDataKey := make([]byte, 32)
+ for i := range plainDataKey {
+ plainDataKey[i] = byte(i + 1) // deterministic for testing
}
+ encryptedDataKey, err := mock.Encrypt(ctx, "aws", configJSON, plainDataKey)
+ require.NoError(t, err)
+
+ // Update project to use external KMS and set the encrypted data key
+ _, err = stack.DB().Primary().Exec(ctx, `
+ UPDATE projects
+ SET "kmsSecretManagerKeyId" = @kmsKeyID,
+ "kmsSecretManagerEncryptedDataKey" = @encryptedDataKey
+ WHERE id = @projectID
+ `, pgx.NamedArgs{"kmsKeyID": kmsKeyID, "encryptedDataKey": encryptedDataKey, "projectID": proj.ID})
+ require.NoError(t, err)
+
+ // Reset mock counters after setup
+ mock.Reset()
+
+ return proj, configJSON
}
-// TestProjectCipherPair_IsolatedPerProject verifies that different projects
-// get different data keys — ciphertexts are not cross-decryptable.
-func TestProjectCipherPair_IsolatedPerProject(t *testing.T) {
- svc := startedService(t)
+func TestExternalKms_DecryptFlowCallsProvider(t *testing.T) {
ctx := context.Background()
+ mock := externalkms.NewMockProvider()
+ svc := startedServiceWithExternalKms(t, mock)
- proj1 := stack.NodeJS().CreateProject(t, "kms-iso-1")
- proj2 := stack.NodeJS().CreateProject(t, "kms-iso-2")
+ proj, expectedConfig := setupExternalKmsForProject(t, svc, mock, "ext-kms-decrypt")
- pair1, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
- Type: kms.DataKeyProject,
- ProjectID: proj1.ID,
- })
+ // Create cipher pair - this calls external KMS to decrypt the project data key
+ pair, err := svc.CreateCipherPairWithProjectDataKey(ctx, proj.ID)
require.NoError(t, err)
- pair2, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
- Type: kms.DataKeyProject,
- ProjectID: proj2.ID,
- })
+ // External KMS Decrypt was called once to get the project data key
+ require.Equal(t, 1, mock.DecryptCalls, "external KMS decrypt should be called to get data key")
+ require.Equal(t, 0, mock.EncryptCalls, "external KMS encrypt is not used in this flow")
+
+ // Verify the config was decrypted and passed to provider
+ require.JSONEq(t, string(expectedConfig), string(mock.LastConfig))
+ require.Equal(t, "aws", mock.LastProvider)
+
+ // Local encrypt/decrypt uses the decrypted data key (no more external KMS calls)
+ plaintext := []byte("external kms test data")
+ ciphertext, err := pair.Encrypt(plaintext)
require.NoError(t, err)
- plaintext := []byte("isolation test")
- ciphertext, err := pair1.Encrypt(plaintext)
+ decrypted, err := pair.Decrypt(ciphertext)
require.NoError(t, err)
+ require.Equal(t, plaintext, decrypted)
- // Decrypting project1's ciphertext with project2's key should fail.
- _, err = pair2.Decrypt(ciphertext)
- require.Error(t, err)
+ // No additional external KMS calls - local crypto uses the data key
+ require.Equal(t, 1, mock.DecryptCalls, "no additional decrypt calls")
+ require.Equal(t, 0, mock.EncryptCalls, "no encrypt calls")
}
-// ==========================================================================
-// Error paths
-// ==========================================================================
+func TestExternalKms_ProviderFailurePropagates(t *testing.T) {
+ ctx := context.Background()
+ mock := externalkms.NewMockProvider()
+ svc := startedServiceWithExternalKms(t, mock)
-func TestCipherPair_MissingProjectID(t *testing.T) {
- svc := startedService(t)
+ proj, _ := setupExternalKmsForProject(t, svc, mock, "ext-kms-fail")
- _, err := svc.CreateCipherPairWithDataKey(context.Background(), kms.CreateCipherPairDTO{
- Type: kms.DataKeyProject,
- })
+ // Now configure mock to fail
+ mock.ShouldFail = true
+
+ // CreateCipherPairWithProjectDataKey should fail because it tries to decrypt
+ // the data key using the external KMS, which is configured to fail
+ _, err := svc.CreateCipherPairWithProjectDataKey(ctx, proj.ID)
require.Error(t, err)
- require.Contains(t, err.Error(), "project ID is required")
+ require.Contains(t, err.Error(), "mock external KMS decrypt failed")
}
-func TestCipherPair_MissingOrgID(t *testing.T) {
+func TestExternalKms_NilServiceReturnsError(t *testing.T) {
+ ctx := context.Background()
+ mock := externalkms.NewMockProvider()
+
+ // First create with mock to set up the external KMS in DB
+ svcWithMock := startedServiceWithExternalKms(t, mock)
+ proj, _ := setupExternalKmsForProject(t, svcWithMock, mock, "ext-kms-nil")
+
+ // Now create service WITHOUT external KMS
svc := startedService(t)
- _, err := svc.CreateCipherPairWithDataKey(context.Background(), kms.CreateCipherPairDTO{
- Type: kms.DataKeyOrganization,
- })
+ // This should fail because external KMS service is nil
+ _, err := svc.CreateCipherPairWithProjectDataKey(ctx, proj.ID)
require.Error(t, err)
- require.Contains(t, err.Error(), "org ID is required")
+ require.Contains(t, err.Error(), "external KMS service not configured")
}
diff --git a/backend-go/internal/services/kms/kms_org.go b/backend-go/internal/services/kms/kms_org.go
index 467657f9bb..1b392d88ec 100644
--- a/backend-go/internal/services/kms/kms_org.go
+++ b/backend-go/internal/services/kms/kms_org.go
@@ -3,71 +3,161 @@ package kms
import (
"context"
"crypto/rand"
+ "database/sql"
"fmt"
"github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/infisical/api/internal/database/pg"
+ "github.com/infisical/api/internal/database/pg/pglock"
+ "github.com/infisical/api/internal/libs/crypto/cipher"
"github.com/infisical/api/internal/libs/errutil"
)
+type orgKmsInfo struct {
+ ID uuid.UUID `db:"id"`
+ KmsDefaultKeyID sql.Null[uuid.UUID] `db:"kms_default_key_id"`
+ KmsEncryptedDataKey []byte `db:"kms_encrypted_data_key"`
+}
+
+func (s *Service) findOrgKmsInfo(ctx context.Context, q pg.Querier, orgID uuid.UUID) (*orgKmsInfo, error) {
+ query := `
+ SELECT id, "kmsDefaultKeyId", "kmsEncryptedDataKey"
+ FROM organizations
+ WHERE id = @orgID
+ `
+ row := q.QueryRow(ctx, query, pgx.NamedArgs{"orgID": orgID})
+
+ var result orgKmsInfo
+ if err := row.Scan(&result.ID, &result.KmsDefaultKeyID, &result.KmsEncryptedDataKey); err != nil {
+ return nil, fmt.Errorf("finding org KMS info: %w", err)
+ }
+ return &result, nil
+}
+
+func (s *Service) CreateCipherPairWithOrgDataKey(ctx context.Context, orgID uuid.UUID) (*CipherPair, error) {
+ if orgID == uuid.Nil {
+ return nil, fmt.Errorf("org ID is required")
+ }
+
+ dataKey, err := s.getOrgDataKey(ctx, orgID)
+ if err != nil {
+ return nil, err
+ }
+
+ return &CipherPair{
+ encrypt: func(plainText []byte) ([]byte, error) {
+ return encryptWithVersion(plainText, dataKey)
+ },
+ decrypt: func(cipherTextBlob []byte) ([]byte, error) {
+ return decryptWithVersion(cipherTextBlob, dataKey)
+ },
+ }, nil
+}
+
func (s *Service) getOrgDataKey(ctx context.Context, orgID uuid.UUID) ([]byte, error) {
org, err := s.findOrgKmsInfo(ctx, s.db.Replica(), orgID)
if err != nil {
return nil, errutil.DatabaseErr("Failed to find organization KMS info").WithErrf("getOrgDataKey(orgId=%s): %w", orgID, err)
}
- // Ensure org has a KMS key (lazy create if missing).
- kmsKeyID := org.KmsDefaultKeyID
- if !kmsKeyID.Valid {
- createdKmsKeyID, kmsErr := s.findOrCreateOrgKmsKey(ctx, orgID, func() ([]byte, error) {
- return s.generateEncryptedKeyMaterial()
- })
- if kmsErr != nil {
- return nil, errutil.DatabaseErr("Failed to ensure organization KMS key").WithErrf("getOrgDataKey(orgId=%s): %w", orgID, kmsErr)
- }
- kmsKeyID.V = createdKmsKeyID
- kmsKeyID.Valid = true
+ // Fast path: both KMS key and data key exist
+ if org.KmsDefaultKeyID.Valid && len(org.KmsEncryptedDataKey) > 0 {
+ // Use decryptWithKmsKey which handles both internal and external KMS
+ return s.decryptWithKmsKey(ctx, org.KmsDefaultKeyID.V, org.KmsEncryptedDataKey, 0)
}
- // Ensure org has a data key (lazy create if missing).
- if len(org.KmsEncryptedDataKey) == 0 {
- dataKey, dataErr := s.generateOrgDataKey(ctx, orgID, kmsKeyID.V)
- if dataErr != nil {
- return nil, errutil.DatabaseErr("Failed to ensure organization data key").WithErrf("getOrgDataKey(orgId=%s): %w", orgID, dataErr)
- }
- return dataKey, nil
+ // Slow path: need to create KMS key and/or data key under lock
+ return s.ensureOrgDataKey(ctx, orgID)
+}
+
+func (s *Service) ensureOrgDataKey(ctx context.Context, orgID uuid.UUID) (dataKey []byte, err error) {
+ // TODO(go): Once Node.js is retired, consolidate to single lock "kms-org:{orgID}".
+ // Currently using both locks to maintain compatibility with Node.js which uses separate locks.
+ keyLockID := fmt.Sprintf("kms-org-key:%s", orgID)
+ dataKeyLockID := fmt.Sprintf("kms-org-data-key:%s", orgID)
+
+ tx, err := s.db.Primary().Begin(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("beginning transaction: %w", err)
}
+ defer errutil.DeferErr(ctx, func() error { return tx.Rollback(ctx) }, "rolling back org data key tx")
- // Decrypt existing data key.
- kmsKey, err := s.decryptKmsKey(ctx, kmsKeyID.V)
+ lock, err := pglock.AcquireBlockingLock(ctx, tx, keyLockID)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("acquiring org key lock: %w", err)
}
- return decryptWithVersion(org.KmsEncryptedDataKey, kmsKey)
-}
-// generateOrgDataKey creates the org's encrypted data key if it doesn't exist.
-// Returns the plaintext data key.
-// The caller must ensure the org's KMS key exists before calling this
-// to avoid deadlocks with concurrent KMS key + data key creation.
-func (s *Service) generateOrgDataKey(ctx context.Context, orgID, kmsKeyID uuid.UUID) ([]byte, error) {
- // Decrypt KMS key once — used both for encrypting (create) and decrypting (existing).
- kmsKey, err := s.decryptKmsKey(ctx, kmsKeyID)
+ if _, err := pglock.AcquireBlockingLock(ctx, lock.Tx(), dataKeyLockID); err != nil {
+ return nil, fmt.Errorf("acquiring org data key lock: %w", err)
+ }
+
+ // Re-check after acquiring lock
+ org, err := s.findOrgKmsInfo(ctx, tx, orgID)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("finding org: %w", err)
+ }
+
+ var kmsKeyMaterial []byte
+
+ // Ensure KMS key exists
+ if !org.KmsDefaultKeyID.Valid {
+ encryptedKeyMaterial, err := s.generateEncryptedKeyMaterial()
+ if err != nil {
+ return nil, fmt.Errorf("generating KMS key: %w", err)
+ }
+
+ createdID, err := s.createKmsKeyWithInternal(ctx, tx, org.ID, encryptedKeyMaterial)
+ if err != nil {
+ return nil, err
+ }
+
+ updateQuery := `UPDATE organizations SET "kmsDefaultKeyId" = @keyID WHERE id = @orgID`
+ if _, err := tx.Exec(ctx, updateQuery, pgx.NamedArgs{"keyID": createdID, "orgID": orgID}); err != nil {
+ return nil, fmt.Errorf("updating org default key: %w", err)
+ }
+
+ // Decrypt the key material we just created
+ rootKey := s.getRootKey()
+ if len(rootKey) == 0 {
+ return nil, fmt.Errorf("KMS: root key not loaded")
+ }
+ kmsKeyMaterial, err = cipher.SymmetricDecrypt(encryptedKeyMaterial, rootKey)
+ if err != nil {
+ return nil, fmt.Errorf("decrypting KMS key: %w", err)
+ }
+ } else {
+ kmsKeyMaterial, err = s.decryptInternalKmsKey(ctx, org.KmsDefaultKeyID.V)
+ if err != nil {
+ return nil, err
+ }
}
- encryptedDataKey, err := s.findOrCreateOrgDataKey(ctx, orgID, func() ([]byte, error) {
+ // Ensure data key exists
+ var encryptedDataKey []byte
+ if len(org.KmsEncryptedDataKey) > 0 {
+ encryptedDataKey = org.KmsEncryptedDataKey
+ } else {
plainDataKey := make([]byte, 32)
if _, err := rand.Read(plainDataKey); err != nil {
return nil, fmt.Errorf("generating data key: %w", err)
}
- return encryptWithVersion(plainDataKey, kmsKey)
- })
- if err != nil {
- return nil, errutil.DatabaseErr("Failed to find or create organization data key").WithErrf("generateOrgDataKey(orgId=%s): %w", orgID, err)
+ encryptedDataKey, err = encryptWithVersion(plainDataKey, kmsKeyMaterial)
+ if err != nil {
+ return nil, fmt.Errorf("encrypting data key: %w", err)
+ }
+
+ updateQuery := `UPDATE organizations SET "kmsEncryptedDataKey" = @dataKey WHERE id = @orgID`
+ if _, err := tx.Exec(ctx, updateQuery, pgx.NamedArgs{"dataKey": encryptedDataKey, "orgID": orgID}); err != nil {
+ return nil, fmt.Errorf("setting org encrypted data key: %w", err)
+ }
+ }
+
+ if err := lock.Release(ctx); err != nil {
+ return nil, err
}
- return decryptWithVersion(encryptedDataKey, kmsKey)
+ return decryptWithVersion(encryptedDataKey, kmsKeyMaterial)
}
diff --git a/backend-go/internal/services/kms/kms_project.go b/backend-go/internal/services/kms/kms_project.go
index 9013e252ad..156abff290 100644
--- a/backend-go/internal/services/kms/kms_project.go
+++ b/backend-go/internal/services/kms/kms_project.go
@@ -3,70 +3,162 @@ package kms
import (
"context"
"crypto/rand"
+ "database/sql"
"fmt"
"github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/infisical/api/internal/database/pg"
+ "github.com/infisical/api/internal/database/pg/pglock"
+ "github.com/infisical/api/internal/libs/crypto/cipher"
"github.com/infisical/api/internal/libs/errutil"
)
+type projectKmsInfo struct {
+ ID string `db:"id"`
+ OrgID uuid.UUID `db:"org_id"`
+ KmsSecretManagerKeyID sql.Null[uuid.UUID] `db:"kms_secret_manager_key_id"`
+ KmsSecretManagerEncryptedDataKey []byte `db:"kms_secret_manager_encrypted_data_key"`
+}
+
+func (s *Service) findProjectKmsInfo(ctx context.Context, q pg.Querier, projectID string) (*projectKmsInfo, error) {
+ query := `
+ SELECT id, "orgId", "kmsSecretManagerKeyId", "kmsSecretManagerEncryptedDataKey"
+ FROM projects
+ WHERE id = @projectID
+ `
+ row := q.QueryRow(ctx, query, pgx.NamedArgs{"projectID": projectID})
+
+ var result projectKmsInfo
+ if err := row.Scan(&result.ID, &result.OrgID, &result.KmsSecretManagerKeyID, &result.KmsSecretManagerEncryptedDataKey); err != nil {
+ return nil, fmt.Errorf("finding project KMS info: %w", err)
+ }
+ return &result, nil
+}
+
+func (s *Service) CreateCipherPairWithProjectDataKey(ctx context.Context, projectID string) (*CipherPair, error) {
+ if projectID == "" {
+ return nil, fmt.Errorf("project ID is required")
+ }
+
+ dataKey, err := s.getProjectDataKey(ctx, projectID)
+ if err != nil {
+ return nil, err
+ }
+
+ return &CipherPair{
+ encrypt: func(plainText []byte) ([]byte, error) {
+ return encryptWithVersion(plainText, dataKey)
+ },
+ decrypt: func(cipherTextBlob []byte) ([]byte, error) {
+ return decryptWithVersion(cipherTextBlob, dataKey)
+ },
+ }, nil
+}
+
func (s *Service) getProjectDataKey(ctx context.Context, projectID string) ([]byte, error) {
project, err := s.findProjectKmsInfo(ctx, s.db.Replica(), projectID)
if err != nil {
return nil, errutil.DatabaseErr("Failed to find project KMS info").WithErrf("getProjectDataKey(projectId=%s): %w", projectID, err)
}
- // Ensure project has a KMS key (lazy create if missing).
- kmsKeyID := project.KmsSecretManagerKeyID
- if !kmsKeyID.Valid {
- createdKmsKeyID, kmsErr := s.findOrCreateProjectKmsKey(ctx, projectID, func() ([]byte, error) {
- return s.generateEncryptedKeyMaterial()
- })
- if kmsErr != nil {
- return nil, errutil.DatabaseErr("Failed to ensure project KMS key").WithErrf("getProjectDataKey(projectId=%s): %w", projectID, kmsErr)
- }
- kmsKeyID.V = createdKmsKeyID
- kmsKeyID.Valid = true
+ // Fast path: both KMS key and data key exist
+ if project.KmsSecretManagerKeyID.Valid && len(project.KmsSecretManagerEncryptedDataKey) > 0 {
+ // Use decryptWithKmsKey which handles both internal and external KMS
+ return s.decryptWithKmsKey(ctx, project.KmsSecretManagerKeyID.V, project.KmsSecretManagerEncryptedDataKey, 0)
}
- // Ensure project has a data key (lazy create if missing).
- if len(project.KmsSecretManagerEncryptedDataKey) == 0 {
- dataKey, dataErr := s.generateProjectDataKey(ctx, projectID, kmsKeyID.V)
- if dataErr != nil {
- return nil, errutil.DatabaseErr("Failed to ensure project data key").WithErrf("getProjectDataKey(projectId=%s): %w", projectID, dataErr)
- }
- return dataKey, nil
+ // Slow path: need to create KMS key and/or data key under lock
+ return s.ensureProjectDataKey(ctx, projectID)
+}
+
+func (s *Service) ensureProjectDataKey(ctx context.Context, projectID string) (dataKey []byte, err error) {
+ // TODO(go): Once Node.js is retired, consolidate to single lock "kms-project:{projectID}".
+ // Currently using both locks to maintain compatibility with Node.js which uses separate locks.
+ keyLockID := fmt.Sprintf("kms-project-key:%s", projectID)
+ dataKeyLockID := fmt.Sprintf("kms-project-data-key:%s", projectID)
+
+ tx, err := s.db.Primary().Begin(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("beginning transaction: %w", err)
}
+ defer errutil.DeferErr(ctx, func() error { return tx.Rollback(ctx) }, "rolling back project data key tx")
- // Decrypt existing data key.
- kmsKey, err := s.decryptKmsKey(ctx, kmsKeyID.V)
+ lock, err := pglock.AcquireBlockingLock(ctx, tx, keyLockID)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("acquiring project key lock: %w", err)
}
- return decryptWithVersion(project.KmsSecretManagerEncryptedDataKey, kmsKey)
-}
-// generateProjectDataKey creates the project's encrypted data key if it doesn't exist.
-// Returns the plaintext data key.
-// The caller must ensure the project's KMS key exists before calling this
-// to avoid deadlocks with concurrent KMS key + data key creation.
-func (s *Service) generateProjectDataKey(ctx context.Context, projectID string, kmsKeyID uuid.UUID) ([]byte, error) {
- // Decrypt KMS key once — used both for encrypting (create) and decrypting (existing).
- kmsKey, err := s.decryptKmsKey(ctx, kmsKeyID)
+ if _, err := pglock.AcquireBlockingLock(ctx, lock.Tx(), dataKeyLockID); err != nil {
+ return nil, fmt.Errorf("acquiring project data key lock: %w", err)
+ }
+
+ // Re-check after acquiring lock
+ project, err := s.findProjectKmsInfo(ctx, tx, projectID)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("finding project: %w", err)
+ }
+
+ var kmsKeyMaterial []byte
+
+ // Ensure KMS key exists
+ if !project.KmsSecretManagerKeyID.Valid {
+ encryptedKeyMaterial, err := s.generateEncryptedKeyMaterial()
+ if err != nil {
+ return nil, fmt.Errorf("generating KMS key: %w", err)
+ }
+
+ createdID, err := s.createKmsKeyWithInternal(ctx, tx, project.OrgID, encryptedKeyMaterial)
+ if err != nil {
+ return nil, err
+ }
+
+ updateQuery := `UPDATE projects SET "kmsSecretManagerKeyId" = @keyID WHERE id = @projectID`
+ if _, err := tx.Exec(ctx, updateQuery, pgx.NamedArgs{"keyID": createdID, "projectID": projectID}); err != nil {
+ return nil, fmt.Errorf("updating project KMS key: %w", err)
+ }
+
+ // Decrypt the key material we just created
+ rootKey := s.getRootKey()
+ if len(rootKey) == 0 {
+ return nil, fmt.Errorf("KMS: root key not loaded")
+ }
+ kmsKeyMaterial, err = cipher.SymmetricDecrypt(encryptedKeyMaterial, rootKey)
+ if err != nil {
+ return nil, fmt.Errorf("decrypting KMS key: %w", err)
+ }
+ } else {
+ kmsKeyMaterial, err = s.decryptInternalKmsKey(ctx, project.KmsSecretManagerKeyID.V)
+ if err != nil {
+ return nil, err
+ }
}
- encryptedDataKey, err := s.findOrCreateProjectDataKey(ctx, projectID, func() ([]byte, error) {
+ // Ensure data key exists
+ var encryptedDataKey []byte
+ if len(project.KmsSecretManagerEncryptedDataKey) > 0 {
+ encryptedDataKey = project.KmsSecretManagerEncryptedDataKey
+ } else {
plainDataKey := make([]byte, 32)
if _, err := rand.Read(plainDataKey); err != nil {
return nil, fmt.Errorf("generating data key: %w", err)
}
- return encryptWithVersion(plainDataKey, kmsKey)
- })
- if err != nil {
- return nil, errutil.DatabaseErr("Failed to find or create project data key").WithErrf("generateProjectDataKey(projectId=%s): %w", projectID, err)
+
+ encryptedDataKey, err = encryptWithVersion(plainDataKey, kmsKeyMaterial)
+ if err != nil {
+ return nil, fmt.Errorf("encrypting data key: %w", err)
+ }
+
+ updateQuery := `UPDATE projects SET "kmsSecretManagerEncryptedDataKey" = @dataKey WHERE id = @projectID`
+ if _, err := tx.Exec(ctx, updateQuery, pgx.NamedArgs{"dataKey": encryptedDataKey, "projectID": projectID}); err != nil {
+ return nil, fmt.Errorf("setting project encrypted data key: %w", err)
+ }
+ }
+
+ if err := lock.Release(ctx); err != nil {
+ return nil, err
}
- return decryptWithVersion(encryptedDataKey, kmsKey)
+ return decryptWithVersion(encryptedDataKey, kmsKeyMaterial)
}
diff --git a/backend-go/internal/services/secretmanager/secret/get_secret_by_name.go b/backend-go/internal/services/secretmanager/secret/get_secret_by_name.go
index 3ec96c0954..b58b7de7bf 100644
--- a/backend-go/internal/services/secretmanager/secret/get_secret_by_name.go
+++ b/backend-go/internal/services/secretmanager/secret/get_secret_by_name.go
@@ -51,10 +51,7 @@ func (s *Service) GetSecretByName(ctx context.Context, opts *GetSecretByNameOpts
return nil, errutil.NotFound("Folder not found")
}
- cipherPair, err := s.kmsService.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
- Type: kms.DataKeyProject,
- ProjectID: opts.ProjectID,
- })
+ cipherPair, err := s.kmsService.CreateCipherPairWithProjectDataKey(ctx, opts.ProjectID)
if err != nil {
return nil, errutil.InternalServer("Failed to get decryption key").WithErrf("GetSecretByName: %w", err)
}
diff --git a/backend-go/internal/services/secretmanager/secret/list_secrets.go b/backend-go/internal/services/secretmanager/secret/list_secrets.go
index 57f4d655c5..7b4b2ee5ad 100644
--- a/backend-go/internal/services/secretmanager/secret/list_secrets.go
+++ b/backend-go/internal/services/secretmanager/secret/list_secrets.go
@@ -133,10 +133,7 @@ func (s *Service) ListSecrets(ctx context.Context, opts *ListSecretsOpts) (*List
return nil, errutil.DatabaseErr("Failed to load secrets").WithErrf("ListSecrets: %w", err)
}
- cipherPair, err := s.kmsService.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
- Type: kms.DataKeyProject,
- ProjectID: opts.ProjectID,
- })
+ cipherPair, err := s.kmsService.CreateCipherPairWithProjectDataKey(ctx, opts.ProjectID)
if err != nil {
return nil, errutil.InternalServer("Failed to get decryption key").WithErrf("ListSecrets: %w", err)
}
diff --git a/backend-go/internal/services/secretmanager/secret/secret.go b/backend-go/internal/services/secretmanager/secret/secret.go
index 7ae32d2234..a88270247f 100644
--- a/backend-go/internal/services/secretmanager/secret/secret.go
+++ b/backend-go/internal/services/secretmanager/secret/secret.go
@@ -152,7 +152,7 @@ type SecretImportService interface {
// KMSService creates cipher pairs for encryption/decryption.
type KMSService interface {
- CreateCipherPairWithDataKey(ctx context.Context, dto kms.CreateCipherPairDTO) (*kms.CipherPair, error)
+ CreateCipherPairWithProjectDataKey(ctx context.Context, projectID string) (*kms.CipherPair, error)
}
// --- Service ---
diff --git a/backend-go/internal/testutil/infra/builder.go b/backend-go/internal/testutil/infra/builder.go
index 1a4da33ab4..6bdab1cc98 100644
--- a/backend-go/internal/testutil/infra/builder.go
+++ b/backend-go/internal/testutil/infra/builder.go
@@ -1,3 +1,5 @@
+//go:build integration
+
package infra
import (
diff --git a/backend-go/internal/testutil/infra/constants.go b/backend-go/internal/testutil/infra/constants.go
index 66fb3bce91..716183676b 100644
--- a/backend-go/internal/testutil/infra/constants.go
+++ b/backend-go/internal/testutil/infra/constants.go
@@ -1,3 +1,5 @@
+//go:build integration
+
package infra
// Test constants for infrastructure setup.
diff --git a/backend-go/internal/testutil/infra/infisical_secrets.go b/backend-go/internal/testutil/infra/infisical_secrets.go
new file mode 100644
index 0000000000..72b3666ab1
--- /dev/null
+++ b/backend-go/internal/testutil/infra/infisical_secrets.go
@@ -0,0 +1,255 @@
+//go:build integration
+
+package infra
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// Environment variables for Infisical test credentials.
+const (
+ EnvInfisicalTestAPIURL = "INFISICAL_TEST_API_URL"
+ EnvInfisicalTestClientID = "INFISICAL_TEST_IDENTITY_CLIENT_ID"
+ EnvInfisicalTestClientSecret = "INFISICAL_TEST_IDENTITY_CLIENT_SECRET"
+ EnvInfisicalTestProjectID = "INFISICAL_TEST_PROJECT_ID"
+
+ DefaultInfisicalAPIURL = "https://app.infisical.com"
+ TestEnvironment = "default"
+)
+
+// Secret folder paths for different teams/domains.
+const (
+ SecretPathPlatform = "/platform"
+ SecretPathSecretManager = "/secretmanager"
+)
+
+// infisicalClient handles authentication and fetching secrets from Infisical.
+type infisicalClient struct {
+ httpClient *http.Client
+ apiURL string
+ accessToken string
+ projectID string
+}
+
+var (
+ infisicalClientOnce sync.Once
+ infisicalClientInstance *infisicalClient
+ errInfisicalClient error
+)
+
+// getInfisicalClient returns a singleton authenticated Infisical client.
+func getInfisicalClient() (*infisicalClient, error) {
+ infisicalClientOnce.Do(func() {
+ infisicalClientInstance, errInfisicalClient = initInfisicalClient()
+ })
+ return infisicalClientInstance, errInfisicalClient
+}
+
+func initInfisicalClient() (*infisicalClient, error) {
+ clientID := os.Getenv(EnvInfisicalTestClientID)
+ clientSecret := os.Getenv(EnvInfisicalTestClientSecret)
+ projectID := os.Getenv(EnvInfisicalTestProjectID)
+
+ if clientID == "" || clientSecret == "" {
+ return nil, fmt.Errorf(
+ "skipping: Infisical test credentials not configured. "+
+ "Set %s and %s environment variables to enable cloud provider tests",
+ EnvInfisicalTestClientID, EnvInfisicalTestClientSecret,
+ )
+ }
+
+ if projectID == "" {
+ return nil, fmt.Errorf(
+ "skipping: Infisical test project not configured. "+
+ "Set %s environment variable to enable cloud provider tests",
+ EnvInfisicalTestProjectID,
+ )
+ }
+
+ apiURL := os.Getenv(EnvInfisicalTestAPIURL)
+ if apiURL == "" {
+ apiURL = DefaultInfisicalAPIURL
+ }
+
+ httpClient := &http.Client{Timeout: 30 * time.Second}
+
+ accessToken, err := authenticate(context.Background(), httpClient, apiURL, clientID, clientSecret)
+ if err != nil {
+ return nil, fmt.Errorf("skipping: failed to authenticate with Infisical: %w", err)
+ }
+
+ return &infisicalClient{
+ httpClient: httpClient,
+ apiURL: apiURL,
+ accessToken: accessToken,
+ projectID: projectID,
+ }, nil
+}
+
+// authenticate performs universal auth login and returns an access token.
+func authenticate(ctx context.Context, client *http.Client, apiURL, clientID, clientSecret string) (string, error) {
+ loginURL := apiURL + "/api/v1/auth/universal-auth/login"
+
+ form := url.Values{}
+ form.Set("clientId", clientID)
+ form.Set("clientSecret", clientSecret)
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, loginURL, strings.NewReader(form.Encode()))
+ if err != nil {
+ return "", fmt.Errorf("creating login request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+ resp, err := client.Do(req)
+ if err != nil {
+ return "", fmt.Errorf("login request failed: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != http.StatusOK {
+ return "", fmt.Errorf("login returned status %d", resp.StatusCode)
+ }
+
+ var loginResp struct {
+ AccessToken string `json:"accessToken"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&loginResp); err != nil {
+ return "", fmt.Errorf("decoding login response: %w", err)
+ }
+
+ return loginResp.AccessToken, nil
+}
+
+// listSecrets fetches secrets from the specified path.
+func (c *infisicalClient) listSecrets(ctx context.Context, secretPath string) (map[string]string, error) {
+ secretsURL := fmt.Sprintf("%s/api/v3/secrets/raw?workspaceId=%s&environment=%s&secretPath=%s",
+ c.apiURL,
+ url.QueryEscape(c.projectID),
+ url.QueryEscape(TestEnvironment),
+ url.QueryEscape(secretPath),
+ )
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, secretsURL, http.NoBody)
+ if err != nil {
+ return nil, fmt.Errorf("creating request: %w", err)
+ }
+ req.Header.Set("Authorization", "Bearer "+c.accessToken)
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return nil, fmt.Errorf("secrets request failed: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("secrets request returned status %d", resp.StatusCode)
+ }
+
+ var secretsResp struct {
+ Secrets []struct {
+ SecretKey string `json:"secretKey"`
+ SecretValue string `json:"secretValue"`
+ } `json:"secrets"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&secretsResp); err != nil {
+ return nil, fmt.Errorf("decoding secrets response: %w", err)
+ }
+
+ secretMap := make(map[string]string, len(secretsResp.Secrets))
+ for _, s := range secretsResp.Secrets {
+ secretMap[s.SecretKey] = s.SecretValue
+ }
+
+ return secretMap, nil
+}
+
+// InfisicalSecrets provides access to test secrets from a specific folder path.
+type InfisicalSecrets struct {
+ secrets map[string]string
+}
+
+var (
+ platformSecretsOnce sync.Once
+ platformSecretsInstance *InfisicalSecrets
+ errPlatformSecrets error
+
+ secretManagerSecretsOnce sync.Once
+ secretManagerSecretsInstance *InfisicalSecrets
+ errSecretManagerSecrets error
+)
+
+// GetPlatformSecrets returns secrets from the /platform folder.
+// Skips the test if credentials are not configured.
+func GetPlatformSecrets(t *testing.T) *InfisicalSecrets {
+ t.Helper()
+
+ platformSecretsOnce.Do(func() {
+ platformSecretsInstance, errPlatformSecrets = loadSecrets(SecretPathPlatform)
+ })
+
+ if errPlatformSecrets != nil {
+ t.Skip(errPlatformSecrets.Error())
+ }
+
+ return platformSecretsInstance
+}
+
+// GetSecretManagerSecrets returns secrets from the /secretmanager folder.
+// Skips the test if credentials are not configured.
+func GetSecretManagerSecrets(t *testing.T) *InfisicalSecrets {
+ t.Helper()
+
+ secretManagerSecretsOnce.Do(func() {
+ secretManagerSecretsInstance, errSecretManagerSecrets = loadSecrets(SecretPathSecretManager)
+ })
+
+ if errSecretManagerSecrets != nil {
+ t.Skip(errSecretManagerSecrets.Error())
+ }
+
+ return secretManagerSecretsInstance
+}
+
+func loadSecrets(path string) (*InfisicalSecrets, error) {
+ client, err := getInfisicalClient()
+ if err != nil {
+ return nil, err
+ }
+
+ secrets, err := client.listSecrets(context.Background(), path)
+ if err != nil {
+ return nil, fmt.Errorf("skipping: failed to list secrets from %s: %w", path, err)
+ }
+
+ return &InfisicalSecrets{secrets: secrets}, nil
+}
+
+// Get returns a secret value by key. Returns empty string if not found.
+func (s *InfisicalSecrets) Get(key string) string {
+ return s.secrets[key]
+}
+
+// Require returns a secret value by key, or skips the test if not found.
+func (s *InfisicalSecrets) Require(t *testing.T, key string) string {
+ t.Helper()
+ value, ok := s.secrets[key]
+ if !ok || value == "" {
+ t.Skipf("skipping: required secret %q not found in Infisical test project", key)
+ }
+ return value
+}
+
+// Has returns true if the secret exists and is non-empty.
+func (s *InfisicalSecrets) Has(key string) bool {
+ value, ok := s.secrets[key]
+ return ok && value != ""
+}
diff --git a/backend-go/internal/testutil/infra/nodejs.go b/backend-go/internal/testutil/infra/nodejs.go
index 937708458a..0a5041557d 100644
--- a/backend-go/internal/testutil/infra/nodejs.go
+++ b/backend-go/internal/testutil/infra/nodejs.go
@@ -1,3 +1,5 @@
+//go:build integration
+
package infra
import (
@@ -953,3 +955,32 @@ func (n *NodeJSService) DeleteServiceToken(t *testing.T, serviceTokenID string)
t.Fatalf("infra.DeleteServiceToken: returned %d: %s", r.StatusCode(), r.String())
}
}
+
+// GetSecretByKey reads a secret by key via the Node.js API.
+func (n *NodeJSService) GetSecretByKey(t *testing.T, projectID, environment, secretPath, key string) *SecretSeed {
+ t.Helper()
+
+ var resp GetSecretResponse
+ r, err := n.client.R().
+ SetAuthToken(n.identityToken).
+ SetQueryParams(map[string]string{
+ "projectId": projectID,
+ "environment": environment,
+ "secretPath": secretPath,
+ }).
+ SetResult(&resp).
+ Get(fmt.Sprintf("/api/v4/secrets/%s", key))
+ if err != nil {
+ t.Fatalf("infra.GetSecretByKey: request failed: %v", err)
+ }
+ if r.IsError() {
+ t.Fatalf("infra.GetSecretByKey: returned %d: %s", r.StatusCode(), r.String())
+ }
+
+ return &SecretSeed{
+ ID: resp.Secret.ID,
+ Key: resp.Secret.Key,
+ Value: resp.Secret.Value,
+ Version: resp.Secret.Version,
+ }
+}
diff --git a/backend-go/internal/testutil/infra/nodejs_types.go b/backend-go/internal/testutil/infra/nodejs_types.go
index 4e4f361883..796cb263ea 100644
--- a/backend-go/internal/testutil/infra/nodejs_types.go
+++ b/backend-go/internal/testutil/infra/nodejs_types.go
@@ -1,3 +1,5 @@
+//go:build integration
+
package infra
// Request and response types for Node.js API calls.
@@ -193,6 +195,18 @@ type CreateSecretResponse struct {
} `json:"secret"`
}
+// GetSecretResponse is the response from GET /api/v4/secrets/{key}.
+type GetSecretResponse struct {
+ Secret struct {
+ ID string `json:"id"`
+ Key string `json:"secretKey"`
+ Value string `json:"secretValue"`
+ Version int `json:"version"`
+ SecretPath string `json:"secretPath"`
+ Environment string `json:"environment"`
+ } `json:"secret"`
+}
+
// CreateFolderRequest is the request body for POST /api/v2/folders.
type CreateFolderRequest struct {
ProjectID string `json:"projectId"`
@@ -308,3 +322,22 @@ type UniversalAuthLoginRequest struct {
type UniversalAuthLoginResponse struct {
AccessToken string `json:"accessToken"`
}
+
+// CreateOrgRequest is the request body for POST /api/v1/organizations.
+type CreateOrgRequest struct {
+ Name string `json:"name"`
+}
+
+// CreateOrgResponse is the response from POST /api/v1/organizations.
+type CreateOrgResponse struct {
+ Organization struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ } `json:"organization"`
+}
+
+// OrgSeed contains metadata for an org created via the Node.js API.
+type OrgSeed struct {
+ ID string
+ Name string
+}
diff --git a/backend-go/internal/testutil/infra/postgres.go b/backend-go/internal/testutil/infra/postgres.go
index cad3748517..9f55f73d28 100644
--- a/backend-go/internal/testutil/infra/postgres.go
+++ b/backend-go/internal/testutil/infra/postgres.go
@@ -1,3 +1,5 @@
+//go:build integration
+
package infra
import (
diff --git a/backend-go/internal/testutil/infra/redis.go b/backend-go/internal/testutil/infra/redis.go
index c0f31c800c..f12b277542 100644
--- a/backend-go/internal/testutil/infra/redis.go
+++ b/backend-go/internal/testutil/infra/redis.go
@@ -1,3 +1,5 @@
+//go:build integration
+
package infra
import (
diff --git a/backend-go/internal/testutil/infra/stack.go b/backend-go/internal/testutil/infra/stack.go
index ab08781262..ad2c1bd50e 100644
--- a/backend-go/internal/testutil/infra/stack.go
+++ b/backend-go/internal/testutil/infra/stack.go
@@ -1,3 +1,5 @@
+//go:build integration
+
package infra
import (