Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ephemeral: add ephemeral_google_service_account_jwt #20427

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/12142.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:none

```
1 change: 1 addition & 0 deletions google/fwprovider/framework_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1038,5 +1038,6 @@ func (p *FrameworkProvider) EphemeralResources(_ context.Context) []func() ephem
return []func() ephemeral.EphemeralResource{
resourcemanager.GoogleEphemeralServiceAccountAccessToken,
resourcemanager.GoogleEphemeralServiceAccountIdToken,
resourcemanager.GoogleEphemeralServiceAccountJwt,
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package resourcemanager

import (
"context"
"encoding/json"
"fmt"
"time"

"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
"github.com/hashicorp/terraform-plugin-framework-validators/setvalidator"
"github.com/hashicorp/terraform-plugin-framework/ephemeral"
"github.com/hashicorp/terraform-plugin-framework/ephemeral/schema"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-provider-google/google/fwtransport"
"github.com/hashicorp/terraform-provider-google/google/fwutils"
"github.com/hashicorp/terraform-provider-google/google/fwvalidators"
"google.golang.org/api/iamcredentials/v1"
)

var _ ephemeral.EphemeralResource = &googleEphemeralServiceAccountJwt{}

func GoogleEphemeralServiceAccountJwt() ephemeral.EphemeralResource {
return &googleEphemeralServiceAccountJwt{}
}

type googleEphemeralServiceAccountJwt struct {
providerConfig *fwtransport.FrameworkProviderConfig
}

func (p *googleEphemeralServiceAccountJwt) Metadata(ctx context.Context, req ephemeral.MetadataRequest, resp *ephemeral.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_service_account_jwt"
}

type ephemeralServiceAccountJwtModel struct {
Payload types.String `tfsdk:"payload"`
ExpiresIn types.Int64 `tfsdk:"expires_in"`
TargetServiceAccount types.String `tfsdk:"target_service_account"`
Delegates types.Set `tfsdk:"delegates"`
Jwt types.String `tfsdk:"jwt"`
}

func (p *googleEphemeralServiceAccountJwt) Schema(ctx context.Context, req ephemeral.SchemaRequest, resp *ephemeral.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Produces an arbitrary self-signed JWT for service accounts.",
Attributes: map[string]schema.Attribute{
"payload": schema.StringAttribute{
Required: true,
Description: `A JSON-encoded JWT claims set that will be included in the signed JWT.`,
},
"expires_in": schema.Int64Attribute{
Optional: true,
Description: "Number of seconds until the JWT expires. If set and non-zero an `exp` claim will be added to the payload derived from the current timestamp plus expires_in seconds.",
Validators: []validator.Int64{
int64validator.AtLeast(1), // Must be greater than 0
},
},
"target_service_account": schema.StringAttribute{
Description: "The email of the service account that will sign the JWT.",
Required: true,
Validators: []validator.String{
fwvalidators.ServiceAccountEmailValidator{},
},
},
"delegates": schema.SetAttribute{
Description: "Delegate chain of approvals needed to perform full impersonation. Specify the fully qualified service account name.",
Optional: true,
ElementType: types.StringType,
Validators: []validator.Set{
setvalidator.ValueStringsAre(fwvalidators.ServiceAccountEmailValidator{}),
},
},
"jwt": schema.StringAttribute{
Description: "The signed JWT containing the JWT Claims Set from the `payload`.",
Computed: true,
Sensitive: true,
},
},
}
}

func (p *googleEphemeralServiceAccountJwt) Configure(ctx context.Context, req ephemeral.ConfigureRequest, resp *ephemeral.ConfigureResponse) {
if req.ProviderData == nil {
return
}

pd, ok := req.ProviderData.(*fwtransport.FrameworkProviderConfig)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Data Source Configure Type",
fmt.Sprintf("Expected *fwtransport.FrameworkProviderConfig, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}

p.providerConfig = pd
}

func (p *googleEphemeralServiceAccountJwt) Open(ctx context.Context, req ephemeral.OpenRequest, resp *ephemeral.OpenResponse) {
var data ephemeralServiceAccountJwtModel

resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)

payload := data.Payload.ValueString()

if !data.ExpiresIn.IsNull() {
expiresIn := data.ExpiresIn.ValueInt64()
var decoded map[string]interface{}
if err := json.Unmarshal([]byte(payload), &decoded); err != nil {
resp.Diagnostics.AddError("Error decoding payload", err.Error())
return
}

decoded["exp"] = time.Now().Add(time.Duration(expiresIn) * time.Second).Unix()

payloadBytesWithExp, err := json.Marshal(decoded)
if err != nil {
resp.Diagnostics.AddError("Error re-encoding payload", err.Error())
return
}

payload = string(payloadBytesWithExp)

}

name := fmt.Sprintf("projects/-/serviceAccounts/%s", data.TargetServiceAccount.ValueString())

service := p.providerConfig.NewIamCredentialsClient(p.providerConfig.UserAgent)
jwtRequest := &iamcredentials.SignJwtRequest{
Payload: payload,
Delegates: fwutils.StringSet(data.Delegates),
}

jwtResponse, err := service.Projects.ServiceAccounts.SignJwt(name, jwtRequest).Do()
if err != nil {
resp.Diagnostics.AddError("Error calling iamcredentials.SignJwt", err.Error())
return
}

data.Jwt = types.StringValue(jwtResponse.SignedJwt)

resp.Diagnostics.Append(resp.Result.Set(ctx, data)...)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package resourcemanager_test

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-provider-google/google/acctest"
"github.com/hashicorp/terraform-provider-google/google/envvar"
)

func TestAccEphemeralServiceAccountJwt_basic(t *testing.T) {
t.Parallel()

serviceAccount := envvar.GetTestServiceAccountFromEnv(t)
targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "jwt-basic", serviceAccount)

resource.Test(t, resource.TestCase{
PreCheck: func() { acctest.AccTestPreCheck(t) },
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t),
Steps: []resource.TestStep{
{
Config: testAccEphemeralServiceAccountJwt_basic(targetServiceAccountEmail),
},
},
})
}

func TestAccEphemeralServiceAccountJwt_withDelegates(t *testing.T) {
t.Parallel()

initialServiceAccount := envvar.GetTestServiceAccountFromEnv(t)
delegateServiceAccountEmailOne := acctest.BootstrapServiceAccount(t, "jwt-delegate1", initialServiceAccount) // SA_2
delegateServiceAccountEmailTwo := acctest.BootstrapServiceAccount(t, "jwt-delegate2", delegateServiceAccountEmailOne) // SA_3
targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "jwt-target", delegateServiceAccountEmailTwo) // SA_4

resource.Test(t, resource.TestCase{
PreCheck: func() { acctest.AccTestPreCheck(t) },
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t),
Steps: []resource.TestStep{
{
Config: testAccEphemeralServiceAccountJwt_withDelegates(delegateServiceAccountEmailOne, delegateServiceAccountEmailTwo, targetServiceAccountEmail),
},
},
})
}

func TestAccEphemeralServiceAccountJwt_withExpiresIn(t *testing.T) {
t.Parallel()

serviceAccount := envvar.GetTestServiceAccountFromEnv(t)
targetServiceAccountEmail := acctest.BootstrapServiceAccount(t, "expiry", serviceAccount)

resource.Test(t, resource.TestCase{
PreCheck: func() { acctest.AccTestPreCheck(t) },
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t),
Steps: []resource.TestStep{
{
Config: testAccEphemeralServiceAccountJwt_withExpiresIn(targetServiceAccountEmail),
},
},
})
}

func testAccEphemeralServiceAccountJwt_basic(serviceAccountEmail string) string {
return fmt.Sprintf(`
ephemeral "google_service_account_jwt" "jwt" {
target_service_account = "%s"
payload = jsonencode({
"sub": "%[1]s",
"aud": "https://example.com"
})
}
`, serviceAccountEmail)
}

func testAccEphemeralServiceAccountJwt_withDelegates(delegateServiceAccountEmailOne, delegateServiceAccountEmailTwo, targetServiceAccountEmail string) string {
return fmt.Sprintf(`
ephemeral "google_service_account_jwt" "jwt" {
target_service_account = "%s"
delegates = [
"%s",
"%s",
]
payload = jsonencode({
"sub": "%[1]s",
"aud": "https://example.com"
})
}
# The delegation chain is:
# SA_1 (initialServiceAccountEmail) -> SA_2 (delegateServiceAccountEmailOne) -> SA_3 (delegateServiceAccountEmailTwo) -> SA_4 (targetServiceAccountEmail)
`, targetServiceAccountEmail, delegateServiceAccountEmailOne, delegateServiceAccountEmailTwo)
}

func testAccEphemeralServiceAccountJwt_withExpiresIn(serviceAccountEmail string) string {
return fmt.Sprintf(`
ephemeral "google_service_account_jwt" "jwt" {
target_service_account = "%s"
expires_in = 3600
payload = jsonencode({
"sub": "%[1]s",
"aud": "https://example.com"
})
}
`, serviceAccountEmail)
}
41 changes: 41 additions & 0 deletions website/docs/ephemeral-resources/service_account_jwt.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
subcategory: "Cloud Platform"
description: |-
Produces an arbitrary self-signed JWT for service accounts
---

# google_service_account_jwt

This ephemeral resource provides a [self-signed JWT](https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-jwt). Tokens issued from this ephemeral resource are typically used to call external services that accept JWTs for authentication.

## Example Usage

Note: in order to use the following, the caller must have _at least_ `roles/iam.serviceAccountTokenCreator` on the `target_service_account`.

```hcl
ephemeral "google_service_account_jwt" "foo" {
target_service_account = "[email protected]"

payload = jsonencode({
foo: "bar",
sub: "subject",
})

expires_in = 60
}
```

## Argument Reference

The following arguments are supported:

* `target_service_account` (Required) - The email of the service account that will sign the JWT.
* `payload` (Required) - The JSON-encoded JWT claims set to include in the self-signed JWT.
* `expires_in` (Optional) - Number of seconds until the JWT expires. If set and non-zero an `exp` claim will be added to the payload derived from the current timestamp plus expires_in seconds.
* `delegates` (Optional) - Delegate chain of approvals needed to perform full impersonation. Specify the fully qualified service account name.

## Attributes Reference

The following attribute is exported:

* `jwt` - The signed JWT containing the JWT Claims Set from the `payload`.