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

Feat/api cors #523

Closed
wants to merge 5 commits into from
Closed
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
29 changes: 25 additions & 4 deletions cloud/aws/deploy/api/apigateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,17 @@ import (

"github.com/nitrictech/nitric/cloud/aws/deploy/config"
"github.com/nitrictech/nitric/cloud/aws/deploy/exec"
"github.com/nitrictech/nitric/cloud/common/cors"
common "github.com/nitrictech/nitric/cloud/common/deploy/tags"
v1 "github.com/nitrictech/nitric/core/pkg/api/nitric/v1"
)

type AwsApiGatewayArgs struct {
OpenAPISpec *openapi3.T
LambdaFunctions map[string]*exec.LambdaExecUnit
StackID string
Config *config.ApiConfig
Cors *v1.ApiCorsDefinition
}

type AwsApiGateway struct {
Expand Down Expand Up @@ -132,11 +135,29 @@ func NewAwsApiGateway(ctx *pulumi.Context, name string, args *AwsApiGatewayArgs,
return string(b), nil
}).(pulumi.StringOutput)

var awsCorsConfig *apigatewayv2.ApiCorsConfigurationArgs

if args.Cors != nil {
corsConfig, err := cors.GetCorsConfig(args.Cors)
if err != nil {
return nil, err
}

awsCorsConfig = &apigatewayv2.ApiCorsConfigurationArgs{}
awsCorsConfig.AllowCredentials = pulumi.Bool(corsConfig.GetAllowCredentials())
awsCorsConfig.AllowOrigins = pulumi.ToStringArray(corsConfig.GetAllowOrigins())
awsCorsConfig.AllowHeaders = pulumi.ToStringArray(corsConfig.GetAllowHeaders())
awsCorsConfig.AllowMethods = pulumi.ToStringArray(corsConfig.GetAllowMethods())
awsCorsConfig.ExposeHeaders = pulumi.ToStringArray(corsConfig.GetExposeHeaders())
awsCorsConfig.MaxAge = pulumi.Int(corsConfig.GetMaxAge())
}

res.Api, err = apigatewayv2.NewApi(ctx, name, &apigatewayv2.ApiArgs{
Body: doc,
ProtocolType: pulumi.String("HTTP"),
Tags: pulumi.ToStringMap(common.Tags(args.StackID, name, resources.API)),
FailOnWarnings: pulumi.Bool(true),
Body: doc,
ProtocolType: pulumi.String("HTTP"),
Tags: pulumi.ToStringMap(common.Tags(args.StackID, name, resources.API)),
FailOnWarnings: pulumi.Bool(true),
CorsConfiguration: awsCorsConfig,
}, opts...)
if err != nil {
return nil, err
Expand Down
3 changes: 3 additions & 0 deletions cloud/aws/deploy/up.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,13 +288,16 @@ func (d *DeployServer) Up(request *deploy.DeployUpRequest, stream deploy.DeployS
return fmt.Errorf("invalid document suppled for api: %s", res.Name)
}

cors := t.Api.GetCors()

config, _ := config.Apis[res.Name]

_, err = api.NewAwsApiGateway(ctx, res.Name, &api.AwsApiGatewayArgs{
LambdaFunctions: execs,
StackID: stackID,
OpenAPISpec: doc,
Config: config,
Cors: cors,
})
if err != nil {
return err
Expand Down
8 changes: 4 additions & 4 deletions cloud/aws/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,15 @@ require (
github.com/aws/aws-sdk-go-v2/service/sfn v1.14.3
github.com/aws/aws-sdk-go-v2/service/sns v1.18.3
github.com/aws/aws-sdk-go-v2/service/sqs v1.19.12
github.com/aws/smithy-go v1.13.5
github.com/getkin/kin-openapi v0.113.0
github.com/golang/mock v1.6.0
github.com/golangci/golangci-lint v1.52.2
github.com/google/addlicense v1.1.1
github.com/imdario/mergo v0.3.15
github.com/mitchellh/mapstructure v1.5.0
github.com/nitrictech/nitric/cloud/common v0.0.0-20230616021604-4036d005db63
github.com/nitrictech/nitric/core v0.0.0-20230616021604-4036d005db63
github.com/nitrictech/nitric/cloud/common v0.0.0-20231105231620-0968ce7a6ee6
github.com/nitrictech/nitric/core v0.0.0-20231105231620-0968ce7a6ee6
github.com/onsi/ginkgo v1.16.5
github.com/onsi/gomega v1.26.0
github.com/pkg/errors v0.9.1
Expand Down Expand Up @@ -83,7 +84,6 @@ require (
github.com/aws/aws-sdk-go-v2/service/sso v1.11.26 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.13.9 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.17.6 // indirect
github.com/aws/smithy-go v1.13.5 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bkielbasa/cyclop v1.2.0 // indirect
github.com/blang/semver v3.5.1+incompatible // indirect
Expand Down Expand Up @@ -286,7 +286,7 @@ require (
github.com/urfave/cli/v2 v2.4.0 // indirect
github.com/uudashr/gocognit v1.0.6 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.45.0 // indirect
github.com/valyala/fasthttp v1.50.0 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
github.com/yagipy/maintidx v1.0.0 // indirect
Expand Down
12 changes: 6 additions & 6 deletions cloud/aws/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -645,10 +645,10 @@ github.com/nishanths/exhaustive v0.9.5 h1:TzssWan6orBiLYVqewCG8faud9qlFntJE30ACp
github.com/nishanths/exhaustive v0.9.5/go.mod h1:IbwrGdVMizvDcIxPYGVdQn5BqWJaOwpCvg4RGb8r/TA=
github.com/nishanths/predeclared v0.2.2 h1:V2EPdZPliZymNAn79T8RkNApBjMmVKh5XRpLm/w98Vk=
github.com/nishanths/predeclared v0.2.2/go.mod h1:RROzoN6TnGQupbC+lqggsOlcgysk3LMK/HI84Mp280c=
github.com/nitrictech/nitric/cloud/common v0.0.0-20230616021604-4036d005db63 h1:IFsLa+GXv2Z7eQrbZp+PaUmgGHGasFHtiBou9F+Y42g=
github.com/nitrictech/nitric/cloud/common v0.0.0-20230616021604-4036d005db63/go.mod h1:nz8/tXPMb5o2yv8g4+NsvDu0dPyrY6iZyXZ1EprenlM=
github.com/nitrictech/nitric/core v0.0.0-20230616021604-4036d005db63 h1:W8dtDQVg57v9FFeW+NuojL7OfOc8JF05upe9ZkGffNw=
github.com/nitrictech/nitric/core v0.0.0-20230616021604-4036d005db63/go.mod h1:ToPwEfaTjD8uz1tj1GxIRxLTEagC4Q1muzTzJdEYxhQ=
github.com/nitrictech/nitric/cloud/common v0.0.0-20231105231620-0968ce7a6ee6 h1:ABk9LbXWdN7A6GRU55d1Mh8u4QxUpuIGPlogenydtks=
github.com/nitrictech/nitric/cloud/common v0.0.0-20231105231620-0968ce7a6ee6/go.mod h1:nz8/tXPMb5o2yv8g4+NsvDu0dPyrY6iZyXZ1EprenlM=
github.com/nitrictech/nitric/core v0.0.0-20231105231620-0968ce7a6ee6 h1:NErEJJkXR6ESod/TDrlN+xalZz2Sv8CUkSVQe8Qs+Ms=
github.com/nitrictech/nitric/core v0.0.0-20231105231620-0968ce7a6ee6/go.mod h1:s1jivAiMfES33W80gdV/YiVPpUpDQrpnNpu9gdYyMKM=
github.com/nitrictech/protoutils v0.0.0-20220321044654-02667a814cdf h1:8MB8W8ylM8sCM2COGfiO39/tB6BTdiawLszaUGCNL5w=
github.com/nitrictech/protoutils v0.0.0-20220321044654-02667a814cdf/go.mod h1:b2lzk2a4o1bvSrSCE6yvTldHuXCJymuDVhdMJGOSslw=
github.com/nunnatsa/ginkgolinter v0.9.0 h1:Sm0zX5QfjJzkeCjEp+t6d3Ha0jwvoDjleP9XCsrEzOA=
Expand Down Expand Up @@ -893,8 +893,8 @@ github.com/uw-labs/lichen v0.1.7 h1:SDNE3kThhhtP70XfLN/C2bqaT9Epefg1i10lhWYIG4g=
github.com/uw-labs/lichen v0.1.7/go.mod h1:bvEgoBeVZGhzstRxPEpEwM4TGT6AJZ6GA29a4FuLxYw=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.45.0 h1:zPkkzpIn8tdHZUrVa6PzYd0i5verqiPSkgTd3bSUcpA=
github.com/valyala/fasthttp v1.45.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA=
github.com/valyala/fasthttp v1.50.0 h1:H7fweIlBm0rXLs2q0XbalvJ6r0CUPFWK3/bB4N13e9M=
github.com/valyala/fasthttp v1.50.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA=
github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=
github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw=
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 h1:QldyIu/L63oPpyvQmHgvgickp1Yw510KJOqX7H24mg8=
Expand Down
75 changes: 68 additions & 7 deletions cloud/azure/deploy/api/apimanagement.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@
package api

import (
"bytes"
"fmt"
"html/template"
"strings"

"github.com/nitrictech/nitric/cloud/common/cors"
"github.com/nitrictech/nitric/cloud/common/deploy/resources"

"github.com/getkin/kin-openapi/openapi3"
Expand All @@ -32,6 +35,7 @@ import (
"github.com/nitrictech/nitric/cloud/azure/deploy/utils"
common "github.com/nitrictech/nitric/cloud/common/deploy/tags"
commonutils "github.com/nitrictech/nitric/cloud/common/deploy/utils"
v1 "github.com/nitrictech/nitric/core/pkg/api/nitric/v1"
)

type AzureApiManagementArgs struct {
Expand All @@ -42,6 +46,7 @@ type AzureApiManagementArgs struct {
OpenAPISpec *openapi3.T
Apps map[string]*exec.ContainerApp
ManagedIdentity *managedidentity.UserAssignedIdentity
Cors *v1.ApiCorsDefinition
}

type AzureApiManagement struct {
Expand All @@ -54,6 +59,33 @@ type AzureApiManagement struct {

const policyTemplate = `<policies><inbound><base /><set-backend-service base-url="https://%s" />%s<authentication-managed-identity resource="%s" client-id="%s" /><set-header name="X-Forwarded-Authorization" exists-action="override"><value>@(context.Request.Headers.GetValueOrDefault("Authorization",""))</value></set-header></inbound><backend><base /></backend><outbound><base /></outbound><on-error><base /></on-error></policies>`

const corsTemplate = `
<policies><inbound><base />
<cors allow-credentials="{{.AllowCredentials}}">
{{if .AllowOrigins}}
<allowed-origins>
{{range .AllowOrigins}}<origin>{{.}}</origin>{{end}}
</allowed-origins>
{{end}}
{{if .AllowMethods}}
<allowed-methods preflight-result-max-age="{{.MaxAge}}">
{{range .AllowMethods}}<method>{{.}}</method>{{end}}
</allowed-methods>
{{end}}
{{if .AllowHeaders}}
<allowed-headers>
{{range .AllowHeaders}}<header>{{.}}</header>{{end}}
</allowed-headers>
{{end}}
{{if .ExposeHeaders}}
<expose-headers>
{{range .ExposeHeaders}}<header>{{.}}</header>{{end}}
</expose-headers>
{{end}}
</cors>
</inbound><backend><base /></backend><outbound><base /></outbound><on-error><base /></on-error></policies>
`

const jwtTemplate = `<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid." require-expiration-time="false">
<openid-config url="%s.well-known/openid-configuration" />
<required-claims>
Expand Down Expand Up @@ -181,6 +213,13 @@ func NewAzureApiManagement(ctx *pulumi.Context, name string, args *AzureApiManag
}
}

// this.api.id returns a URL path, which is the incorrect value here.
// We instead need the value passed to apiId in the api creation above.
// However, we want to maintain the pulumi dependency, so we need to keep the 'apply' call.
apiId := res.Api.ID().ToStringOutput().ApplyT(func(id string) string {
return name
}).(pulumi.StringOutput)

for _, pathItem := range args.OpenAPISpec.Paths {
for _, op := range pathItem.Operations() {
if v, ok := op.Extensions["x-nitric-target"]; ok {
Expand Down Expand Up @@ -214,13 +253,6 @@ func NewAzureApiManagement(ctx *pulumi.Context, name string, args *AzureApiManag
continue
}

// this.api.id returns a URL path, which is the incorrect value here.
// We instead need the value passed to apiId in the api creation above.
// However, we want to maintain the pulumi dependency, so we need to keep the 'apply' call.
apiId := res.Api.ID().ToStringOutput().ApplyT(func(id string) string {
return name
}).(pulumi.StringOutput)

_ = ctx.Log.Info("op policy "+op.OperationID+" , name "+name, &pulumi.LogArgs{Ephemeral: true})

_, err = apimanagement.NewApiOperationPolicy(ctx, utils.ResourceName(ctx, name+"-"+op.OperationID, utils.ApiOperationPolicyRT), &apimanagement.ApiOperationPolicyArgs{
Expand All @@ -239,6 +271,35 @@ func NewAzureApiManagement(ctx *pulumi.Context, name string, args *AzureApiManag
}
}

if args.Cors != nil {
corsConfig, err := cors.GetCorsConfig(args.Cors)
if err != nil {
return nil, err
}

var resultBuffer bytes.Buffer
t := template.Must(template.New("corsTemplate").Parse(corsTemplate))

err = t.Execute(&resultBuffer, corsConfig)
if err != nil {
return nil, err
}

corsTemplateResult := resultBuffer.String()

_, err = apimanagement.NewApiPolicy(ctx, utils.ResourceName(ctx, name+"-cors", utils.ApiOperationPolicyRT), &apimanagement.ApiPolicyArgs{
ResourceGroupName: args.ResourceGroupName,
ApiId: apiId,
ServiceName: res.Service.Name,
PolicyId: pulumi.String("policy"),
Format: pulumi.String("xml"),
Value: pulumi.String(corsTemplateResult),
})
if err != nil {
return nil, errors.WithMessage(err, "NewApiPolicy "+name+"-cors")
}
}

ctx.Export("api:"+name, res.Service.GatewayUrl)

return res, ctx.RegisterResourceOutputs(res, pulumi.Map{
Expand Down
1 change: 1 addition & 0 deletions cloud/azure/deploy/up.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,7 @@ func (d *DeployServer) Up(request *deploy.DeployUpRequest, stream deploy.DeployS
Apps: apps,
ManagedIdentity: contEnv.ManagedUser,
StackID: stackID,
Cors: a.GetApi().GetCors(),
})
if err != nil {
return err
Expand Down
9 changes: 4 additions & 5 deletions cloud/azure/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,10 @@ require (
github.com/golang/mock v1.6.0
github.com/golangci/golangci-lint v1.52.2
github.com/google/addlicense v1.1.1
github.com/google/uuid v1.3.0
github.com/imdario/mergo v0.3.15
github.com/mitchellh/mapstructure v1.5.0
github.com/nitrictech/nitric/cloud/common v0.0.0-00010101000000-000000000000
github.com/nitrictech/nitric/core v0.0.0-20230323041755-3456c50c02fe
github.com/nitrictech/nitric/cloud/common v0.0.0-20231105231620-0968ce7a6ee6
github.com/nitrictech/nitric/core v0.0.0-20231105231620-0968ce7a6ee6
github.com/onsi/ginkgo v1.16.5
github.com/onsi/gomega v1.26.0
github.com/pkg/errors v0.9.1
Expand All @@ -34,14 +33,13 @@ require (
github.com/pulumi/pulumi-azure-native-sdk/operationalinsights v1.92.0
github.com/pulumi/pulumi-azure-native-sdk/resources v1.92.0
github.com/pulumi/pulumi-azure-native-sdk/storage v1.92.0
github.com/pulumi/pulumi-azure-native/sdk v1.93.0
github.com/pulumi/pulumi-azure/sdk/v4 v4.42.0
github.com/pulumi/pulumi-azuread/sdk/v5 v5.33.0
github.com/pulumi/pulumi-random/sdk/v4 v4.8.2
github.com/pulumi/pulumi/sdk/v3 v3.65.1
github.com/samber/lo v1.38.1
github.com/uw-labs/lichen v0.1.7
github.com/valyala/fasthttp v1.45.0
github.com/valyala/fasthttp v1.50.0
go.mongodb.org/mongo-driver v1.11.1
google.golang.org/grpc v1.54.0
)
Expand Down Expand Up @@ -151,6 +149,7 @@ require (
github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/google/licenseclassifier v0.0.0-20201113175434-78a70215ca36 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/gookit/color v1.5.2 // indirect
github.com/gordonklaus/ineffassign v0.0.0-20230107090616-13ace0543b28 // indirect
github.com/gostaticanalysis/analysisutil v0.7.1 // indirect
Expand Down
6 changes: 2 additions & 4 deletions cloud/azure/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -772,8 +772,6 @@ github.com/pulumi/pulumi-azure-native-sdk/resources v1.92.0 h1:JU4X8/lVgtt/019Tu
github.com/pulumi/pulumi-azure-native-sdk/resources v1.92.0/go.mod h1:hcrDiuRrruKdGbfA9KSSDsu/ywC29FKk02bsvIVxlQE=
github.com/pulumi/pulumi-azure-native-sdk/storage v1.92.0 h1:pKOZCj84srz9uVEQJuzL6NAUBMwU/wZe3hFW6IJw9vQ=
github.com/pulumi/pulumi-azure-native-sdk/storage v1.92.0/go.mod h1:d2qFMWBm21L9R3aHqx+mJ4Xvcs77WFFfG1Dn72twwvo=
github.com/pulumi/pulumi-azure-native/sdk v1.93.0 h1:8vj8O3ZQ24SF9QT5wV76KWh3DOM5jTwKYoEy4TYX5FE=
github.com/pulumi/pulumi-azure-native/sdk v1.93.0/go.mod h1:lCTXVgZKSgw5n+CMW9iBmiTcwVgQJ8nwGLmPZedj578=
github.com/pulumi/pulumi-azure/sdk/v4 v4.42.0 h1:DOeBB0fJ/2IcEu1rT0IL8S2KNNf3bMXtTeLuPj13cPU=
github.com/pulumi/pulumi-azure/sdk/v4 v4.42.0/go.mod h1:7zcnKiAlh4fut19e5HcWO1F3cwi03a5pM121/lZ8TyE=
github.com/pulumi/pulumi-azuread/sdk/v5 v5.33.0 h1:/KXC518s5uvNrtk12HQCKgtzHm69v+IYMTmMInB5rCY=
Expand Down Expand Up @@ -950,8 +948,8 @@ github.com/uw-labs/lichen v0.1.7 h1:SDNE3kThhhtP70XfLN/C2bqaT9Epefg1i10lhWYIG4g=
github.com/uw-labs/lichen v0.1.7/go.mod h1:bvEgoBeVZGhzstRxPEpEwM4TGT6AJZ6GA29a4FuLxYw=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.45.0 h1:zPkkzpIn8tdHZUrVa6PzYd0i5verqiPSkgTd3bSUcpA=
github.com/valyala/fasthttp v1.45.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA=
github.com/valyala/fasthttp v1.50.0 h1:H7fweIlBm0rXLs2q0XbalvJ6r0CUPFWK3/bB4N13e9M=
github.com/valyala/fasthttp v1.50.0/go.mod h1:k2zXd82h/7UZc3VOdJ2WaUqt1uZ/XpXAfE9i+HBC3lA=
github.com/xanzy/ssh-agent v0.2.1/go.mod h1:mLlQY/MoOhWBj+gOGMQkOeiEvkx+8pJSI+0Bx9h2kr4=
github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=
github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw=
Expand Down
Loading